twilio-video 2.24.2 → 2.24.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.
@@ -1,4 +1,4 @@
1
- /*! twilio-video.js 2.24.2
1
+ /*! twilio-video.js 2.24.3
2
2
 
3
3
  The following license applies to all parts of this software except as
4
4
  documented below.
@@ -36,11 +36,11 @@ documented below.
36
36
 
37
37
  */
38
38
  (function(root){var bundle=function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r}()({1:[function(require,module,exports){"use strict";var CancelablePromise=require("./util/cancelablepromise");function createCancelableRoomPromise(getLocalTracks,createLocalParticipant,createRoomSignaling,createRoom){var cancelableRoomSignalingPromise;var cancellationError=new Error("Canceled");return new CancelablePromise(function onCreate(resolve,reject,isCanceled){var localParticipant;getLocalTracks(function getLocalTracksSucceeded(localTracks){if(isCanceled()){return CancelablePromise.reject(cancellationError)}localParticipant=createLocalParticipant(localTracks);return createRoomSignaling(localParticipant).then(function createRoomSignalingSucceeded(getCancelableRoomSignalingPromise){if(isCanceled()){throw cancellationError}cancelableRoomSignalingPromise=getCancelableRoomSignalingPromise();return cancelableRoomSignalingPromise})}).then(function roomSignalingConnected(roomSignaling){if(isCanceled()){roomSignaling.disconnect();throw cancellationError}resolve(createRoom(localParticipant,roomSignaling))}).catch(function onError(error){reject(error)})},function onCancel(){if(cancelableRoomSignalingPromise){cancelableRoomSignalingPromise.cancel()}})}module.exports=createCancelableRoomPromise},{"./util/cancelablepromise":123}],2:[function(require,module,exports){"use strict";var MediaStreamTrack=require("./webrtc").MediaStreamTrack;var _a=require("./webrtc/util"),guessBrowser=_a.guessBrowser,guessBrowserVersion=_a.guessBrowserVersion;var createCancelableRoomPromise=require("./cancelableroompromise");var EncodingParametersImpl=require("./encodingparameters");var LocalParticipant=require("./localparticipant");var InsightsPublisher=require("./util/insightspublisher");var NullInsightsPublisher=require("./util/insightspublisher/null");var _b=require("./media/track/es5"),LocalAudioTrack=_b.LocalAudioTrack,LocalDataTrack=_b.LocalDataTrack,LocalVideoTrack=_b.LocalVideoTrack;var NetworkQualityConfigurationImpl=require("./networkqualityconfiguration");var Room=require("./room");var SignalingV2=require("./signaling/v2");var _c=require("./util"),asLocalTrack=_c.asLocalTrack,buildLogLevels=_c.buildLogLevels,filterObject=_c.filterObject,isNonArrayObject=_c.isNonArrayObject;var _d=require("./util/constants"),DEFAULT_ENVIRONMENT=_d.DEFAULT_ENVIRONMENT,DEFAULT_LOG_LEVEL=_d.DEFAULT_LOG_LEVEL,DEFAULT_LOGGER_NAME=_d.DEFAULT_LOGGER_NAME,DEFAULT_REALM=_d.DEFAULT_REALM,DEFAULT_REGION=_d.DEFAULT_REGION,WS_SERVER=_d.WS_SERVER,SDK_NAME=_d.SDK_NAME,SDK_VERSION=_d.SDK_VERSION,E=_d.typeErrors;var CancelablePromise=require("./util/cancelablepromise");var EventObserver=require("./util/eventobserver");var DefaultLog=require("./util/log");var validateBandwidthProfile=require("./util/validate").validateBandwidthProfile;var safariVersion=guessBrowser()==="safari"&&guessBrowserVersion();var connectCalls=0;var didPrintSafariWarning=false;var isSafariWithoutVP8Support=false;if(safariVersion){var safariMajorVersion=safariVersion.major,safariMinorVersion=safariVersion.minor;isSafariWithoutVP8Support=safariMajorVersion<12||safariMajorVersion===12&&safariMinorVersion<1}var deprecatedConnectOptionsProps=new Set([{didWarn:false,shouldDelete:true,name:"abortOnIceServersTimeout"},{didWarn:false,shouldDelete:true,name:"dscpTagging",newName:"enableDscp"},{didWarn:false,shouldDelete:true,name:"iceServersTimeout"},{didWarn:false,shouldDelete:false,name:"eventListener",newName:"Video.Logger"},{didWarn:false,shouldDelete:false,name:"logLevel",newName:"Video.Logger"}]);var deprecatedBandwidthProfileOptions=new Set([{didWarn:false,shouldDelete:false,name:"maxTracks",newName:"bandwidthProfile.video.clientTrackSwitchOffControl"},{didWarn:false,shouldDelete:false,name:"renderDimensions",newName:"bandwidthProfile.video.contentPreferencesMode"}]);function connect(token,options){if(typeof options==="undefined"){options={}}if(!isNonArrayObject(options)){return CancelablePromise.reject(E.INVALID_TYPE("options","object"))}var Log=options.Log||DefaultLog;var loggerName=options.loggerName||DEFAULT_LOGGER_NAME;var logLevel=options.logLevel||DEFAULT_LOG_LEVEL;var logLevels=buildLogLevels(logLevel);var logComponentName="[connect #"+ ++connectCalls+"]";var log;try{log=new Log("default",logComponentName,logLevels,loggerName)}catch(error){return CancelablePromise.reject(error)}deprecateOptions(options,log,deprecatedConnectOptionsProps);var adaptiveSimulcast=options.preferredVideoCodecs==="auto";if(adaptiveSimulcast){options.preferredVideoCodecs=[{codec:"VP8",simulcast:true,adaptiveSimulcast:true}]}if(options.maxVideoBitrate&&adaptiveSimulcast){log.error('ConnectOptions "maxVideoBitrate" is not compatible with "preferredVideoCodecs=auto"');return CancelablePromise.reject(E.ILLEGAL_INVOKE("connect",'ConnectOptions "maxVideoBitrate" is not compatible with "preferredVideoCodecs=auto"'))}options=Object.assign({automaticSubscription:true,dominantSpeaker:false,enableDscp:false,environment:DEFAULT_ENVIRONMENT,eventListener:null,insights:true,LocalAudioTrack:LocalAudioTrack,LocalDataTrack:LocalDataTrack,LocalParticipant:LocalParticipant,LocalVideoTrack:LocalVideoTrack,Log:Log,MediaStreamTrack:MediaStreamTrack,loggerName:loggerName,logLevel:logLevel,maxAudioBitrate:null,maxVideoBitrate:null,name:null,networkMonitor:true,networkQuality:false,preferredAudioCodecs:[],preferredVideoCodecs:[],realm:DEFAULT_REALM,region:DEFAULT_REGION,signaling:SignalingV2},filterObject(options));var eventPublisherOptions={};if(typeof options.wsServerInsights==="string"){eventPublisherOptions.gateway=options.wsServerInsights}var EventPublisher=options.insights?InsightsPublisher:NullInsightsPublisher;var eventPublisher=new EventPublisher(token,SDK_NAME,SDK_VERSION,options.environment,options.realm,eventPublisherOptions);var wsServer=WS_SERVER(options.environment,options.region);var eventObserver=new EventObserver(eventPublisher,Date.now(),log,options.eventListener);options=Object.assign({eventObserver:eventObserver,wsServer:wsServer},options);options.log=log;if(isSafariWithoutVP8Support&&!didPrintSafariWarning&&(log.logLevel!=="error"&&log.logLevel!=="off")){didPrintSafariWarning=true;log.warn(["Support for Safari 12.0 and below is limited because it does not support VP8.","This means you may experience codec issues in Group Rooms. You may also","experience codec issues in Peer-to-Peer (P2P) Rooms containing Android- or","iOS-based Participants who do not support H.264. However, P2P Rooms","with browser-based Participants should work. For more information, please","refer to this guide: https://www.twilio.com/docs/video/javascript-v2-developing-safari-11"].join(" "))}if(typeof token!=="string"){return CancelablePromise.reject(E.INVALID_TYPE("token","string"))}var localTrackOptions=Object.assign({},options);delete localTrackOptions.name;if("tracks"in options){if(!Array.isArray(options.tracks)){return CancelablePromise.reject(E.INVALID_TYPE("options.tracks","Array of LocalAudioTrack, LocalVideoTrack or MediaStreamTrack"))}try{options.tracks=options.tracks.map(function(track){return asLocalTrack(track,localTrackOptions)})}catch(error){return CancelablePromise.reject(error)}}var error=validateBandwidthProfile(options.bandwidthProfile);if(error){return CancelablePromise.reject(error)}options.clientTrackSwitchOffControl="disabled";options.contentPreferencesMode="disabled";if(options.bandwidthProfile){options.clientTrackSwitchOffControl="auto";options.contentPreferencesMode="auto";if(options.bandwidthProfile.video){deprecateOptions(options.bandwidthProfile.video,log,deprecatedBandwidthProfileOptions);if("maxTracks"in options.bandwidthProfile.video){options.clientTrackSwitchOffControl="disabled"}else if(options.bandwidthProfile.video.clientTrackSwitchOffControl==="manual"){options.clientTrackSwitchOffControl="manual"}else{options.clientTrackSwitchOffControl="auto"}if("renderDimensions"in options.bandwidthProfile.video){options.contentPreferencesMode="disabled"}else if(options.bandwidthProfile.video.contentPreferencesMode==="manual"){options.contentPreferencesMode="manual"}else{options.contentPreferencesMode="auto"}}}var Signaling=options.signaling;var signaling=new Signaling(options.wsServer,options);log.info("Connecting to a Room");log.debug("Options:",options);var encodingParameters=new EncodingParametersImpl({maxAudioBitrate:options.maxAudioBitrate,maxVideoBitrate:options.maxVideoBitrate},adaptiveSimulcast);var preferredCodecs={audio:options.preferredAudioCodecs.map(normalizeCodecSettings),video:options.preferredVideoCodecs.map(normalizeCodecSettings)};var networkQualityConfiguration=new NetworkQualityConfigurationImpl(isNonArrayObject(options.networkQuality)?options.networkQuality:{});var cancelableRoomPromise=createCancelableRoomPromise(getLocalTracks.bind(null,options),createLocalParticipant.bind(null,signaling,log,encodingParameters,networkQualityConfiguration,options),createRoomSignaling.bind(null,token,options,signaling,encodingParameters,preferredCodecs),createRoom.bind(null,options));cancelableRoomPromise.then(function(room){eventPublisher.connect(room.sid,room.localParticipant.sid);log.info("Connected to Room:",room.toString());log.info("Room name:",room.name);log.debug("Room:",room);room.once("disconnected",function(){return eventPublisher.disconnect()});return room},function(error){eventPublisher.disconnect();if(cancelableRoomPromise._isCanceled){log.info("Attempt to connect to a Room was canceled")}else{log.info("Error while connecting to a Room:",error)}});return cancelableRoomPromise}var AudioCodec={isac:"isac",opus:"opus",PCMA:"PCMA",PCMU:"PCMU"};var VideoEncodingMode={Auto:"auto"};var VideoCodec={H264:"H264",VP8:"VP8"};VideoCodec.VP9="VP9";var LogLevel={debug:"debug",info:"info",warn:"warn",error:"error",off:"off"};var NetworkQualityVerbosity={none:0,minimal:1,moderate:2,detailed:3};var TrackSwitchOffMode={detected:"detected",predicted:"predicted",disabled:"disabled"};var BandwidthProfileMode={grid:"grid",collaboration:"collaboration",presentation:"presentation"};var VideoContentPreferencesMode={auto:"auto",manual:"manual"};var ClientTrackSwitchOffControl={auto:"auto",manual:"manual"};var EventListenerLevel={debug:"debug",error:"error",info:"info",warning:"warning"};var EventListenerGroup={signaling:"signaling"};function deprecateOptions(options,log,deprecationTable){deprecationTable.forEach(function(prop){var didWarn=prop.didWarn,name=prop.name,newName=prop.newName,shouldDelete=prop.shouldDelete;if(name in options&&typeof options[name]!=="undefined"){if(newName&&shouldDelete){options[newName]=options[name]}if(shouldDelete){delete options[name]}if(!didWarn&&!["error","off"].includes(log.level)){log.warn('The ConnectOptions "'+name+'" is '+(newName?'deprecated and scheduled for removal. Please use "'+newName+'" instead.':"no longer applicable and will be ignored."));prop.didWarn=true}}})}function createLocalParticipant(signaling,log,encodingParameters,networkQualityConfiguration,options,localTracks){var localParticipantSignaling=signaling.createLocalParticipantSignaling(encodingParameters,networkQualityConfiguration);log.debug("Creating a new LocalParticipant:",localParticipantSignaling);return new options.LocalParticipant(localParticipantSignaling,localTracks,options)}function createRoom(options,localParticipant,roomSignaling){var room=new Room(localParticipant,roomSignaling,options);var log=options.log;log.debug("Creating a new Room:",room);roomSignaling.on("stateChanged",function stateChanged(state){if(state==="disconnected"){log.info("Disconnected from Room:",room.toString());roomSignaling.removeListener("stateChanged",stateChanged)}});return room}function createRoomSignaling(token,options,signaling,encodingParameters,preferredCodecs,localParticipant){options.log.debug("Creating a new RoomSignaling");return signaling.connect(localParticipant._signaling,token,encodingParameters,preferredCodecs,options)}function getLocalTracks(options,handleLocalTracks){var log=options.log;options.shouldStopLocalTracks=!options.tracks;if(options.shouldStopLocalTracks){log.info("LocalTracks were not provided, so they will be acquired "+"automatically before connecting to the Room. LocalTracks will "+"be released if connecting to the Room fails or if the Room "+"is disconnected")}else{log.info("Getting LocalTracks");log.debug("Options:",options)}return options.createLocalTracks(options).then(function getLocalTracksSucceeded(localTracks){var promise=handleLocalTracks(localTracks);promise.catch(function handleLocalTracksFailed(){if(options.shouldStopLocalTracks){log.info("The automatically acquired LocalTracks will now be stopped");localTracks.forEach(function(track){track.stop()})}});return promise})}function normalizeCodecSettings(nameOrSettings){var settings=typeof nameOrSettings==="string"?{codec:nameOrSettings}:nameOrSettings;switch(settings.codec.toLowerCase()){case"opus":{return Object.assign({dtx:true},settings)}case"vp8":{return Object.assign({simulcast:false},settings)}default:{return settings}}}module.exports=connect},{"./cancelableroompromise":1,"./encodingparameters":9,"./localparticipant":12,"./media/track/es5":14,"./networkqualityconfiguration":43,"./room":56,"./signaling/v2":70,"./util":131,"./util/cancelablepromise":123,"./util/constants":124,"./util/eventobserver":129,"./util/insightspublisher":132,"./util/insightspublisher/null":133,"./util/log":135,"./util/validate":149,"./webrtc":157,"./webrtc/util":170}],3:[function(require,module,exports){"use strict";var _a=require("./util/constants"),DEFAULT_LOG_LEVEL=_a.DEFAULT_LOG_LEVEL,DEFAULT_LOGGER_NAME=_a.DEFAULT_LOGGER_NAME;function createLocalTrack(kind,options){options=Object.assign({loggerName:DEFAULT_LOGGER_NAME,logLevel:DEFAULT_LOG_LEVEL},options);var createOptions={};createOptions.loggerName=options.loggerName;createOptions.logLevel=options.logLevel;delete options.loggerName;delete options.logLevel;var createLocalTracks=options.createLocalTracks;delete options.createLocalTracks;createOptions[kind]=Object.keys(options).length>0?options:true;return createLocalTracks(createOptions).then(function(localTracks){return localTracks[0]})}function createLocalAudioTrack(options){return createLocalTrack("audio",options)}function createLocalVideoTrack(options){return createLocalTrack("video",options)}var NoiseCancellationVendor={krisp:"krisp"};module.exports={audio:createLocalAudioTrack,video:createLocalVideoTrack}},{"./util/constants":124}],4:[function(require,module,exports){"use strict";var __assign=this&&this.__assign||function(){__assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++){s=arguments[i];for(var p in s)if(Object.prototype.hasOwnProperty.call(s,p))t[p]=s[p]}return t};return __assign.apply(this,arguments)};var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var __spreadArray=this&&this.__spreadArray||function(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to};Object.defineProperty(exports,"__esModule",{value:true});exports.createLocalTracks=void 0;var noisecancellationimpl_1=require("./media/track/noisecancellationimpl");var buildLogLevels=require("./util").buildLogLevels;var _a=require("./webrtc"),getUserMedia=_a.getUserMedia,MediaStreamTrack=_a.MediaStreamTrack;var _b=require("./media/track/es5"),LocalAudioTrack=_b.LocalAudioTrack,LocalDataTrack=_b.LocalDataTrack,LocalVideoTrack=_b.LocalVideoTrack;var Log=require("./util/log");var _c=require("./util/constants"),DEFAULT_LOG_LEVEL=_c.DEFAULT_LOG_LEVEL,DEFAULT_LOGGER_NAME=_c.DEFAULT_LOGGER_NAME;var workaround180748=require("./webaudio/workaround180748");var createLocalTrackCalls=0;function createLocalTracks(options){return __awaiter(this,void 0,void 0,function(){var isAudioVideoAbsent,fullOptions,logComponentName,logLevels,log,localTrackOptions,extraLocalTrackOptions,noiseCancellationOptions,mediaStreamConstraints,workaroundWebKitBug180748,mediaStream,mediaStreamTracks,error_1;var _this=this;return __generator(this,function(_a){switch(_a.label){case 0:isAudioVideoAbsent=!(options&&("audio"in options||"video"in options));fullOptions=__assign({audio:isAudioVideoAbsent,getUserMedia:getUserMedia,loggerName:DEFAULT_LOGGER_NAME,logLevel:DEFAULT_LOG_LEVEL,LocalAudioTrack:LocalAudioTrack,LocalDataTrack:LocalDataTrack,LocalVideoTrack:LocalVideoTrack,MediaStreamTrack:MediaStreamTrack,Log:Log,video:isAudioVideoAbsent},options);logComponentName="[createLocalTracks #"+ ++createLocalTrackCalls+"]";logLevels=buildLogLevels(fullOptions.logLevel);log=new fullOptions.Log("default",logComponentName,logLevels,fullOptions.loggerName);localTrackOptions=Object.assign({log:log},fullOptions);delete localTrackOptions.name;if(fullOptions.audio===false&&fullOptions.video===false){log.info("Neither audio nor video requested, so returning empty LocalTracks");return[2,[]]}if(fullOptions.tracks){log.info("Adding user-provided LocalTracks");log.debug("LocalTracks:",fullOptions.tracks);return[2,fullOptions.tracks]}extraLocalTrackOptions={audio:typeof fullOptions.audio==="object"&&fullOptions.audio.name?{name:fullOptions.audio.name}:{},video:typeof fullOptions.video==="object"&&fullOptions.video.name?{name:fullOptions.video.name}:{}};extraLocalTrackOptions.audio.isCreatedByCreateLocalTracks=true;extraLocalTrackOptions.video.isCreatedByCreateLocalTracks=true;if(typeof fullOptions.audio==="object"&&typeof fullOptions.audio.workaroundWebKitBug1208516==="boolean"){extraLocalTrackOptions.audio.workaroundWebKitBug1208516=fullOptions.audio.workaroundWebKitBug1208516}if(typeof fullOptions.audio==="object"&&"noiseCancellationOptions"in fullOptions.audio){noiseCancellationOptions=fullOptions.audio.noiseCancellationOptions;delete fullOptions.audio.noiseCancellationOptions}if(typeof fullOptions.video==="object"&&typeof fullOptions.video.workaroundWebKitBug1208516==="boolean"){extraLocalTrackOptions.video.workaroundWebKitBug1208516=fullOptions.video.workaroundWebKitBug1208516}if(typeof fullOptions.audio==="object"){delete fullOptions.audio.name}if(typeof fullOptions.video==="object"){delete fullOptions.video.name}mediaStreamConstraints={audio:fullOptions.audio,video:fullOptions.video};workaroundWebKitBug180748=typeof fullOptions.audio==="object"&&fullOptions.audio.workaroundWebKitBug180748;_a.label=1;case 1:_a.trys.push([1,4,,5]);return[4,workaroundWebKitBug180748?workaround180748(log,fullOptions.getUserMedia,mediaStreamConstraints):fullOptions.getUserMedia(mediaStreamConstraints)];case 2:mediaStream=_a.sent();mediaStreamTracks=__spreadArray(__spreadArray([],__read(mediaStream.getAudioTracks())),__read(mediaStream.getVideoTracks()));log.info("Call to getUserMedia successful; got tracks:",mediaStreamTracks);return[4,Promise.all(mediaStreamTracks.map(function(mediaStreamTrack){return __awaiter(_this,void 0,void 0,function(){var _a,cleanTrack,noiseCancellation;return __generator(this,function(_b){switch(_b.label){case 0:if(!(mediaStreamTrack.kind==="audio"&&noiseCancellationOptions))return[3,2];return[4,noisecancellationimpl_1.applyNoiseCancellation(mediaStreamTrack,noiseCancellationOptions,log)];case 1:_a=_b.sent(),cleanTrack=_a.cleanTrack,noiseCancellation=_a.noiseCancellation;return[2,new localTrackOptions.LocalAudioTrack(cleanTrack,__assign(__assign(__assign({},extraLocalTrackOptions.audio),localTrackOptions),{noiseCancellation:noiseCancellation}))];case 2:if(mediaStreamTrack.kind==="audio"){return[2,new localTrackOptions.LocalAudioTrack(mediaStreamTrack,__assign(__assign({},extraLocalTrackOptions.audio),localTrackOptions))]}_b.label=3;case 3:return[2,new localTrackOptions.LocalVideoTrack(mediaStreamTrack,__assign(__assign({},extraLocalTrackOptions.video),localTrackOptions))]}})})}))];case 3:return[2,_a.sent()];case 4:error_1=_a.sent();log.warn("Call to getUserMedia failed:",error_1);throw error_1;case 5:return[2]}})})}exports.createLocalTracks=createLocalTracks},{"./media/track/es5":14,"./media/track/noisecancellationimpl":28,"./util":131,"./util/constants":124,"./util/log":135,"./webaudio/workaround180748":154,"./webrtc":157}],5:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var DataTrackTransceiver=require("./transceiver");var DataTransport=require("./transport");var DataTrackReceiver=function(_super){__extends(DataTrackReceiver,_super);function DataTrackReceiver(dataChannel){var _this=_super.call(this,dataChannel.label,dataChannel.maxPacketLifeTime,dataChannel.maxRetransmits,dataChannel.ordered)||this;Object.defineProperties(_this,{_dataChannel:{value:dataChannel}});dataChannel.binaryType="arraybuffer";dataChannel.addEventListener("message",function(event){_this.emit("message",event.data)});dataChannel.addEventListener("close",function(){_this.emit("close")});return _this}DataTrackReceiver.prototype.stop=function(){this._dataChannel.close();_super.prototype.stop.call(this)};DataTrackReceiver.prototype.toDataTransport=function(){return new DataTransport(this._dataChannel)};return DataTrackReceiver}(DataTrackTransceiver);module.exports=DataTrackReceiver},{"./transceiver":7,"./transport":8}],6:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var DataTrackTransceiver=require("./transceiver");var makeUUID=require("../util").makeUUID;var DataTrackSender=function(_super){__extends(DataTrackSender,_super);function DataTrackSender(maxPacketLifeTime,maxRetransmtis,ordered){var _this=_super.call(this,makeUUID(),maxPacketLifeTime,maxRetransmtis,ordered)||this;Object.defineProperties(_this,{_clones:{value:new Set},_dataChannels:{value:new Set}});return _this}DataTrackSender.prototype._addClone=function(clone){this._clones.add(clone)};DataTrackSender.prototype.removeClone=function(clone){this._clones.delete(clone)};DataTrackSender.prototype.addDataChannel=function(dataChannel){this._dataChannels.add(dataChannel);return this};DataTrackSender.prototype.clone=function(){var _this=this;var clone=new DataTrackSender(this.maxPacketLifeTime,this.maxRetransmits,this.ordered);this._addClone(clone);clone.once("stopped",function(){return _this.removeClone(clone)});return clone};DataTrackSender.prototype.removeDataChannel=function(dataChannel){this._dataChannels.delete(dataChannel);return this};DataTrackSender.prototype.send=function(data){this._dataChannels.forEach(function(dataChannel){try{dataChannel.send(data)}catch(error){}});this._clones.forEach(function(clone){try{clone.send(data)}catch(error){}});return this};DataTrackSender.prototype.stop=function(){this._dataChannels.forEach(function(dataChannel){return dataChannel.close()});this._clones.forEach(function(clone){return clone.stop()});_super.prototype.stop.call(this)};return DataTrackSender}(DataTrackTransceiver);module.exports=DataTrackSender},{"../util":131,"./transceiver":7}],7:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var TrackTransceiver=require("../transceiver");var DataTrackTransceiver=function(_super){__extends(DataTrackTransceiver,_super);function DataTrackTransceiver(id,maxPacketLifeTime,maxRetransmits,ordered){var _this=_super.call(this,id,"data")||this;Object.defineProperties(_this,{maxPacketLifeTime:{enumerable:true,value:maxPacketLifeTime},maxRetransmits:{enumerable:true,value:maxRetransmits},ordered:{enumerable:true,value:ordered}});return _this}return DataTrackTransceiver}(TrackTransceiver);module.exports=DataTrackTransceiver},{"../transceiver":118}],8:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var EventEmitter=require("events").EventEmitter;var DataTransport=function(_super){__extends(DataTransport,_super);function DataTransport(dataChannel){var _this=_super.call(this)||this;Object.defineProperties(_this,{_dataChannel:{value:dataChannel},_messageQueue:{value:[]}});dataChannel.addEventListener("open",function(){_this._messageQueue.splice(0).forEach(function(message){return _this._publish(message)})});dataChannel.addEventListener("message",function(_a){var data=_a.data;try{var message=JSON.parse(data);_this.emit("message",message)}catch(error){}});_this.publish({type:"ready"});return _this}DataTransport.prototype._publish=function(message){var data=JSON.stringify(message);try{this._dataChannel.send(data)}catch(error){}};DataTransport.prototype.publish=function(message){var dataChannel=this._dataChannel;if(dataChannel.readyState==="closing"||dataChannel.readyState==="closed"){return false}if(dataChannel.readyState==="connecting"){this._messageQueue.push(message);return true}this._publish(message);return true};return DataTransport}(EventEmitter);module.exports=DataTransport},{events:173}],9:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var EventEmitter=require("events").EventEmitter;var EncodingParametersImpl=function(_super){__extends(EncodingParametersImpl,_super);function EncodingParametersImpl(encodingParameters,adaptiveSimulcast){var _this=_super.call(this)||this;encodingParameters=Object.assign({maxAudioBitrate:null,maxVideoBitrate:null},encodingParameters);Object.defineProperties(_this,{maxAudioBitrate:{value:encodingParameters.maxAudioBitrate,writable:true},maxVideoBitrate:{value:encodingParameters.maxVideoBitrate,writable:true},adaptiveSimulcast:{value:adaptiveSimulcast}});return _this}EncodingParametersImpl.prototype.toJSON=function(){return{maxAudioBitrate:this.maxAudioBitrate,maxVideoBitrate:this.maxVideoBitrate}};EncodingParametersImpl.prototype.update=function(encodingParameters){var _this=this;encodingParameters=Object.assign({maxAudioBitrate:this.maxAudioBitrate,maxVideoBitrate:this.maxVideoBitrate},encodingParameters);var shouldEmitChanged=["maxAudioBitrate","maxVideoBitrate"].reduce(function(shouldEmitChanged,maxKindBitrate){if(_this[maxKindBitrate]!==encodingParameters[maxKindBitrate]){_this[maxKindBitrate]=encodingParameters[maxKindBitrate];shouldEmitChanged=true}return shouldEmitChanged},false);if(shouldEmitChanged){this.emit("changed")}};return EncodingParametersImpl}(EventEmitter);module.exports=EncodingParametersImpl},{events:173}],10:[function(require,module,exports){"use strict";var EventEmitter=require("events").EventEmitter;var hidePrivateAndCertainPublicPropertiesInClass=require("./util").hidePrivateAndCertainPublicPropertiesInClass;module.exports=hidePrivateAndCertainPublicPropertiesInClass(EventEmitter,["domain"])},{"./util":131,events:173}],11:[function(require,module,exports){"use strict";var __assign=this&&this.__assign||function(){__assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++){s=arguments[i];for(var p in s)if(Object.prototype.hasOwnProperty.call(s,p))t[p]=s[p]}return t};return __assign.apply(this,arguments)};Object.defineProperty(exports,"__esModule",{value:true});var createlocaltracks_1=require("./createlocaltracks");var preflighttest_1=require("./preflight/preflighttest");var internals={connect:require("./connect"),createLocalAudioTrack:require("./createlocaltrack").audio,createLocalVideoTrack:require("./createlocaltrack").video,
39
- isSupported:require("./util/support")(),version:require("../package.json").version,Logger:require("./vendor/loglevel"),LocalAudioTrack:require("./media/track/es5").LocalAudioTrack,LocalDataTrack:require("./media/track/es5").LocalDataTrack,LocalVideoTrack:require("./media/track/es5").LocalVideoTrack};function connect(token,options){var internalOptions=__assign({createLocalTracks:createlocaltracks_1.createLocalTracks},options);return internals.connect(token,internalOptions)}function createLocalAudioTrack(options){var internalOptions=__assign({createLocalTracks:createlocaltracks_1.createLocalTracks},options);return internals.createLocalAudioTrack(internalOptions)}function createLocalVideoTrack(options){var internalOptions=__assign({createLocalTracks:createlocaltracks_1.createLocalTracks},options);return internals.createLocalVideoTrack(internalOptions)}var isSupported=internals.isSupported;var version=internals.version;var Logger=internals.Logger;var LocalAudioTrack=internals.LocalAudioTrack;var LocalVideoTrack=internals.LocalVideoTrack;var LocalDataTrack=internals.LocalDataTrack;module.exports={connect:connect,createLocalAudioTrack:createLocalAudioTrack,createLocalVideoTrack:createLocalVideoTrack,createLocalTracks:createlocaltracks_1.createLocalTracks,runPreflight:preflighttest_1.runPreflight,isSupported:isSupported,version:version,Logger:Logger,LocalAudioTrack:LocalAudioTrack,LocalVideoTrack:LocalVideoTrack,LocalDataTrack:LocalDataTrack}},{"../package.json":174,"./connect":2,"./createlocaltrack":3,"./createlocaltracks":4,"./media/track/es5":14,"./preflight/preflighttest":50,"./util/support":144,"./vendor/loglevel":151}],12:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var MediaStreamTrack=require("./webrtc").MediaStreamTrack;var _a=require("./util"),asLocalTrack=_a.asLocalTrack,asLocalTrackPublication=_a.asLocalTrackPublication,trackClass=_a.trackClass;var _b=require("./util/constants"),E=_b.typeErrors,trackPriority=_b.trackPriority;var validateLocalTrack=require("./util/validate").validateLocalTrack;var _c=require("./media/track/es5"),LocalAudioTrack=_c.LocalAudioTrack,LocalDataTrack=_c.LocalDataTrack,LocalVideoTrack=_c.LocalVideoTrack;var LocalAudioTrackPublication=require("./media/track/localaudiotrackpublication");var LocalDataTrackPublication=require("./media/track/localdatatrackpublication");var LocalVideoTrackPublication=require("./media/track/localvideotrackpublication");var Participant=require("./participant");var LocalParticipant=function(_super){__extends(LocalParticipant,_super);function LocalParticipant(signaling,localTracks,options){var _this=this;options=Object.assign({LocalAudioTrack:LocalAudioTrack,LocalVideoTrack:LocalVideoTrack,LocalDataTrack:LocalDataTrack,MediaStreamTrack:MediaStreamTrack,LocalAudioTrackPublication:LocalAudioTrackPublication,LocalVideoTrackPublication:LocalVideoTrackPublication,LocalDataTrackPublication:LocalDataTrackPublication,shouldStopLocalTracks:false,tracks:localTracks},options);var tracksToStop=options.shouldStopLocalTracks?new Set(localTracks.filter(function(localTrack){return localTrack.kind!=="data"})):new Set;_this=_super.call(this,signaling,options)||this;Object.defineProperties(_this,{_eventObserver:{value:options.eventObserver},_LocalAudioTrack:{value:options.LocalAudioTrack},_LocalDataTrack:{value:options.LocalDataTrack},_LocalVideoTrack:{value:options.LocalVideoTrack},_MediaStreamTrack:{value:options.MediaStreamTrack},_LocalAudioTrackPublication:{value:options.LocalAudioTrackPublication},_LocalDataTrackPublication:{value:options.LocalDataTrackPublication},_LocalVideoTrackPublication:{value:options.LocalVideoTrackPublication},_tracksToStop:{value:tracksToStop},signalingRegion:{enumerable:true,get:function(){return signaling.signalingRegion}}});_this._handleTrackSignalingEvents();return _this}LocalParticipant.prototype._addTrack=function(track,id,priority){var addedTrack=_super.prototype._addTrack.call(this,track,id);if(addedTrack&&this.state!=="disconnected"){this._addLocalTrack(track,priority)}return addedTrack};LocalParticipant.prototype._addLocalTrack=function(track,priority){var _a;var vendor=(_a=track.noiseCancellation)===null||_a===void 0?void 0:_a.vendor;this._signaling.addTrack(track._trackSender,track.name,priority,vendor);this._log.info("Added a new "+trackClass(track,true)+":",track.id);this._log.debug(trackClass(track,true)+":",track)};LocalParticipant.prototype._removeTrack=function(track,id){var removedTrack=_super.prototype._removeTrack.call(this,track,id);if(removedTrack&&this.state!=="disconnected"){this._signaling.removeTrack(track._trackSender);this._log.info("Removed a "+trackClass(track,true)+":",track.id);this._log.debug(trackClass(track,true)+":",track)}return removedTrack};LocalParticipant.prototype._getTrackEvents=function(){return _super.prototype._getTrackEvents.call(this).concat([["disabled","trackDisabled"],["enabled","trackEnabled"],["stopped","trackStopped"]])};LocalParticipant.prototype.toString=function(){return"[LocalParticipant #"+this._instanceId+(this.sid?": "+this.sid:"")+"]"};LocalParticipant.prototype._handleTrackSignalingEvents=function(){var _this=this;var log=this._log;if(this.state==="disconnected"){return}var localTrackDisabled=function(localTrack){var trackSignaling=_this._signaling.getPublication(localTrack._trackSender);if(trackSignaling){trackSignaling.disable();log.debug("Disabled the "+trackClass(localTrack,true)+":",localTrack.id)}};var localTrackEnabled=function(localTrack){var trackSignaling=_this._signaling.getPublication(localTrack._trackSender);if(trackSignaling){trackSignaling.enable();log.debug("Enabled the "+trackClass(localTrack,true)+":",localTrack.id)}};var localTrackStopped=function(localTrack){var trackSignaling=_this._signaling.getPublication(localTrack._trackSender);if(trackSignaling){trackSignaling.stop()}return trackSignaling};var stateChanged=function(state){log.debug("Transitioned to state:",state);if(state==="disconnected"){log.debug("Removing LocalTrack event listeners");_this._signaling.removeListener("stateChanged",stateChanged);_this.removeListener("trackDisabled",localTrackDisabled);_this.removeListener("trackEnabled",localTrackEnabled);_this.removeListener("trackStopped",localTrackStopped);_this._tracks.forEach(function(track){var trackSignaling=localTrackStopped(track);if(trackSignaling){track._trackSender.removeClone(trackSignaling._trackTransceiver)}});log.info("LocalParticipant disconnected. Stopping "+_this._tracksToStop.size+" automatically-acquired LocalTracks");_this._tracksToStop.forEach(function(track){track.stop()})}else if(state==="connected"){log.info("reconnected");setTimeout(function(){return _this.emit("reconnected")},0)}};this.on("trackDisabled",localTrackDisabled);this.on("trackEnabled",localTrackEnabled);this.on("trackStopped",localTrackStopped);this._signaling.on("stateChanged",stateChanged);this._tracks.forEach(function(track){_this._addLocalTrack(track,trackPriority.PRIORITY_STANDARD);_this._getOrCreateLocalTrackPublication(track).catch(function(error){log.warn("Failed to get or create LocalTrackPublication for "+track+":",error)})})};LocalParticipant.prototype._getOrCreateLocalTrackPublication=function(localTrack){var localTrackPublication=getTrackPublication(this.tracks,localTrack);if(localTrackPublication){return Promise.resolve(localTrackPublication)}var log=this._log;var self=this;var trackSignaling=this._signaling.getPublication(localTrack._trackSender);if(!trackSignaling){return Promise.reject(new Error("Unexpected error: The "+localTrack+" cannot be published"))}return new Promise(function(resolve,reject){function updated(){var error=trackSignaling.error;if(error){trackSignaling.removeListener("updated",updated);log.warn("Failed to publish the "+trackClass(localTrack,true)+": "+error.message);self._removeTrack(localTrack,localTrack.id);setTimeout(function(){self.emit("trackPublicationFailed",error,localTrack)});reject(error);return}if(!self._tracks.has(localTrack.id)){trackSignaling.removeListener("updated",updated);reject(new Error("The "+localTrack+" was unpublished"));return}var sid=trackSignaling.sid;if(!sid){return}trackSignaling.removeListener("updated",updated);var options={log:log,LocalAudioTrackPublication:self._LocalAudioTrackPublication,LocalDataTrackPublication:self._LocalDataTrackPublication,LocalVideoTrackPublication:self._LocalVideoTrackPublication};localTrackPublication=getTrackPublication(self.tracks,localTrack);var warningHandler=function(twilioWarningName){return self.emit("trackWarning",twilioWarningName,localTrackPublication)};var warningsClearedHandler=function(){return self.emit("trackWarningsCleared",localTrackPublication)};var unpublish=function(publication){localTrackPublication.removeListener("trackWarning",warningHandler);localTrackPublication.removeListener("trackWarningsCleared",warningsClearedHandler);self.unpublishTrack(publication.track)};if(!localTrackPublication){localTrackPublication=asLocalTrackPublication(localTrack,trackSignaling,unpublish,options);self._addTrackPublication(localTrackPublication)}localTrackPublication.on("warning",warningHandler);localTrackPublication.on("warningsCleared",warningsClearedHandler);var state=self._signaling.state;if(state==="connected"||state==="connecting"){if(localTrack._processorEventObserver){localTrack._processorEventObserver.on("event",function(event){self._eventObserver.emit("event",{name:event.name,payload:event.data,group:"video-processor",level:"info"})})}if(localTrack.processedTrack){localTrack._captureFrames();localTrack._setSenderMediaStreamTrack(true)}}if(state==="connected"){setTimeout(function(){self.emit("trackPublished",localTrackPublication)})}resolve(localTrackPublication)}trackSignaling.on("updated",updated)})};LocalParticipant.prototype.publishTrack=function(localTrackOrMediaStreamTrack,options){var trackPublication=getTrackPublication(this.tracks,localTrackOrMediaStreamTrack);if(trackPublication){return Promise.resolve(trackPublication)}options=Object.assign({log:this._log,priority:trackPriority.PRIORITY_STANDARD,LocalAudioTrack:this._LocalAudioTrack,LocalDataTrack:this._LocalDataTrack,LocalVideoTrack:this._LocalVideoTrack,MediaStreamTrack:this._MediaStreamTrack},options);var localTrack;try{localTrack=asLocalTrack(localTrackOrMediaStreamTrack,options)}catch(error){return Promise.reject(error)}var noiseCancellation=localTrack.noiseCancellation;var allowedAudioProcessors=this._signaling.audioProcessors;if(noiseCancellation&&!allowedAudioProcessors.includes(noiseCancellation.vendor)){this._log.warn(noiseCancellation.vendor+" is not supported in this room. disabling it permanently");noiseCancellation.disablePermanently()}var priorityValues=Object.values(trackPriority);if(!priorityValues.includes(options.priority)){return Promise.reject(E.INVALID_VALUE("LocalTrackPublishOptions.priority",priorityValues))}var addedLocalTrack=this._addTrack(localTrack,localTrack.id,options.priority)||this._tracks.get(localTrack.id);return this._getOrCreateLocalTrackPublication(addedLocalTrack)};LocalParticipant.prototype.publishTracks=function(tracks){if(!Array.isArray(tracks)){throw E.INVALID_TYPE("tracks","Array of LocalAudioTrack, LocalVideoTrack, LocalDataTrack, or MediaStreamTrack")}return Promise.all(tracks.map(this.publishTrack,this))};LocalParticipant.prototype.setBandwidthProfile=function(){this._log.warn("setBandwidthProfile is not implemented yet and may be available in future versions of twilio-video.js")};LocalParticipant.prototype.setNetworkQualityConfiguration=function(networkQualityConfiguration){if(typeof networkQualityConfiguration!=="object"||networkQualityConfiguration===null){throw E.INVALID_TYPE("networkQualityConfiguration","NetworkQualityConfiguration")}["local","remote"].forEach(function(prop){if(prop in networkQualityConfiguration&&(typeof networkQualityConfiguration[prop]!=="number"||isNaN(networkQualityConfiguration[prop]))){throw E.INVALID_TYPE("networkQualityConfiguration."+prop,"number")}});this._signaling.setNetworkQualityConfiguration(networkQualityConfiguration);return this};LocalParticipant.prototype.setParameters=function(encodingParameters){if(typeof encodingParameters!=="undefined"&&typeof encodingParameters!=="object"){throw E.INVALID_TYPE("encodingParameters","EncodingParameters, null or undefined")}if(encodingParameters){if(this._signaling.getParameters().adaptiveSimulcast&&encodingParameters.maxVideoBitrate){throw E.INVALID_TYPE("encodingParameters",'encodingParameters.maxVideoBitrate is not compatible with "preferredVideoCodecs=auto"')}["maxAudioBitrate","maxVideoBitrate"].forEach(function(prop){if(typeof encodingParameters[prop]!=="undefined"&&typeof encodingParameters[prop]!=="number"&&encodingParameters[prop]!==null){throw E.INVALID_TYPE("encodingParameters."+prop,"number, null or undefined")}})}else if(encodingParameters===null){encodingParameters={maxAudioBitrate:null,maxVideoBitrate:null}}this._signaling.setParameters(encodingParameters);return this};LocalParticipant.prototype.unpublishTrack=function(track){validateLocalTrack(track,{LocalAudioTrack:this._LocalAudioTrack,LocalDataTrack:this._LocalDataTrack,LocalVideoTrack:this._LocalVideoTrack,MediaStreamTrack:this._MediaStreamTrack});var localTrack=this._tracks.get(track.id);if(!localTrack){return null}var trackSignaling=this._signaling.getPublication(localTrack._trackSender);trackSignaling.publishFailed(new Error("The "+localTrack+" was unpublished"));localTrack=this._removeTrack(localTrack,localTrack.id);if(!localTrack){return null}var localTrackPublication=getTrackPublication(this.tracks,localTrack);if(localTrackPublication){this._removeTrackPublication(localTrackPublication)}return localTrackPublication};LocalParticipant.prototype.unpublishTracks=function(tracks){var _this=this;if(!Array.isArray(tracks)){throw E.INVALID_TYPE("tracks","Array of LocalAudioTrack, LocalVideoTrack, LocalDataTrack, or MediaStreamTrack")}return tracks.reduce(function(unpublishedTracks,track){var unpublishedTrack=_this.unpublishTrack(track);return unpublishedTrack?unpublishedTracks.concat(unpublishedTrack):unpublishedTracks},[])};return LocalParticipant}(Participant);function getTrackPublication(trackPublications,track){return Array.from(trackPublications.values()).find(function(trackPublication){return trackPublication.track===track||trackPublication.track.mediaStreamTrack===track})||null}module.exports=LocalParticipant},{"./media/track/es5":14,"./media/track/localaudiotrackpublication":20,"./media/track/localdatatrackpublication":22,"./media/track/localvideotrackpublication":26,"./participant":45,"./util":131,"./util/constants":124,"./util/validate":149,"./webrtc":157}],13:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var MediaTrack=require("./mediatrack");var AudioTrack=function(_super){__extends(AudioTrack,_super);function AudioTrack(mediaTrackTransceiver,options){return _super.call(this,mediaTrackTransceiver,options)||this}AudioTrack.prototype._start=function(){_super.prototype._start.call(this);if(this._dummyEl){this._dummyEl.srcObject=null;this._dummyEl=null}};AudioTrack.prototype.attach=function(){return _super.prototype.attach.apply(this,arguments)};AudioTrack.prototype.detach=function(){return _super.prototype.detach.apply(this,arguments)};return AudioTrack}(MediaTrack);module.exports=AudioTrack},{"./mediatrack":27}],14:[function(require,module,exports){"use strict";module.exports={LocalAudioTrack:require("./localaudiotrack"),LocalVideoTrack:require("./localvideotrack"),LocalDataTrack:require("./localdatatrack")}},{"./localaudiotrack":15,"./localdatatrack":16,"./localvideotrack":17}],15:[function(require,module,exports){"use strict";var inherits=require("../../../vendor/inherits");var LocalAudioTrackClass=require("../localaudiotrack");function LocalAudioTrack(mediaStreamTrack,options){var track=new LocalAudioTrackClass(mediaStreamTrack,options);Object.setPrototypeOf(track,LocalAudioTrack.prototype);return track}inherits(LocalAudioTrack,LocalAudioTrackClass);module.exports=LocalAudioTrack},{"../../../vendor/inherits":150,"../localaudiotrack":19}],16:[function(require,module,exports){"use strict";var inherits=require("../../../vendor/inherits");var LocalDataTrackClass=require("../localdatatrack");function LocalDataTrack(options){var track=new LocalDataTrackClass(options);Object.setPrototypeOf(track,LocalDataTrack.prototype);return track}inherits(LocalDataTrack,LocalDataTrackClass);module.exports=LocalDataTrack},{"../../../vendor/inherits":150,"../localdatatrack":21}],17:[function(require,module,exports){"use strict";var inherits=require("../../../vendor/inherits");var LocalVideoTrackClass=require("../localvideotrack");function LocalVideoTrack(mediaStreamTrack,options){var track=new LocalVideoTrackClass(mediaStreamTrack,options);Object.setPrototypeOf(track,LocalVideoTrack.prototype);return track}inherits(LocalVideoTrack,LocalVideoTrackClass);module.exports=LocalVideoTrack},{"../../../vendor/inherits":150,"../localvideotrack":25}],18:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var EventEmitter=require("../../eventemitter");var _a=require("../../util"),buildLogLevels=_a.buildLogLevels,valueToJSON=_a.valueToJSON;var DEFAULT_LOG_LEVEL=require("../../util/constants").DEFAULT_LOG_LEVEL;var Log=require("../../util/log");var nInstances=0;var Track=function(_super){__extends(Track,_super);function Track(id,kind,options){var _this=this;options=Object.assign({name:id,log:null,logLevel:DEFAULT_LOG_LEVEL},options);_this=_super.call(this)||this;var name=String(options.name);var logLevels=buildLogLevels(options.logLevel);var log=options.log?options.log.createLog("media",_this):new Log("media",_this,logLevels,options.loggerName);Object.defineProperties(_this,{_instanceId:{value:++nInstances},_log:{value:log},kind:{enumerable:true,value:kind},name:{enumerable:true,value:name}});return _this}Track.prototype.toJSON=function(){return valueToJSON(this)};return Track}(EventEmitter);module.exports=Track},{"../../eventemitter":10,"../../util":131,"../../util/constants":124,"../../util/log":135}],19:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var AudioTrack=require("./audiotrack");var mixinLocalMediaTrack=require("./localmediatrack");var LocalMediaAudioTrack=mixinLocalMediaTrack(AudioTrack);var LocalAudioTrack=function(_super){__extends(LocalAudioTrack,_super);function LocalAudioTrack(mediaStreamTrack,options){var _this=this;var noiseCancellation=(options===null||options===void 0?void 0:options.noiseCancellation)||null;_this=_super.call(this,mediaStreamTrack,options)||this;Object.defineProperties(_this,{noiseCancellation:{enumerable:true,value:noiseCancellation,writable:false}});return _this}LocalAudioTrack.prototype.toString=function(){return"[LocalAudioTrack #"+this._instanceId+": "+this.id+"]"};LocalAudioTrack.prototype.attach=function(el){el=_super.prototype.attach.call(this,el);el.muted=true;return el};LocalAudioTrack.prototype._end=function(){return _super.prototype._end.apply(this,arguments)};LocalAudioTrack.prototype._reacquireTrack=function(constraints){var _this=this;this._log.debug("_reacquireTrack: ",constraints);if(this.noiseCancellation){return this.noiseCancellation.reacquireTrack(function(){return _super.prototype._reacquireTrack.call(_this,constraints)})}return _super.prototype._reacquireTrack.call(this,constraints)};LocalAudioTrack.prototype.disable=function(){return _super.prototype.disable.apply(this,arguments)};LocalAudioTrack.prototype.enable=function(){return _super.prototype.enable.apply(this,arguments)};LocalAudioTrack.prototype.restart=function(){return _super.prototype.restart.apply(this,arguments)};LocalAudioTrack.prototype.stop=function(){if(this.noiseCancellation){this.noiseCancellation.stop()}return _super.prototype.stop.apply(this,arguments)};return LocalAudioTrack}(LocalMediaAudioTrack);module.exports=LocalAudioTrack},{"./audiotrack":13,"./localmediatrack":23}],20:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var LocalTrackPublication=require("./localtrackpublication");var LocalAudioTrackPublication=function(_super){__extends(LocalAudioTrackPublication,_super);function LocalAudioTrackPublication(signaling,track,unpublish,options){return _super.call(this,signaling,track,unpublish,options)||this}LocalAudioTrackPublication.prototype.toString=function(){return"[LocalAudioTrackPublication #"+this._instanceId+": "+this.trackSid+"]"};return LocalAudioTrackPublication}(LocalTrackPublication);module.exports=LocalAudioTrackPublication},{"./localtrackpublication":24}],21:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var Track=require("./");var DefaultDataTrackSender=require("../../data/sender");var LocalDataTrack=function(_super){__extends(LocalDataTrack,_super);function LocalDataTrack(options){var _this=this;options=Object.assign({DataTrackSender:DefaultDataTrackSender,maxPacketLifeTime:null,maxRetransmits:null,ordered:true},options);var DataTrackSender=options.DataTrackSender;var dataTrackSender=new DataTrackSender(options.maxPacketLifeTime,options.maxRetransmits,options.ordered);_this=_super.call(this,dataTrackSender.id,"data",options)||this;Object.defineProperties(_this,{_trackSender:{value:dataTrackSender},id:{enumerable:true,value:dataTrackSender.id},maxPacketLifeTime:{enumerable:true,value:options.maxPacketLifeTime},maxRetransmits:{enumerable:true,value:options.maxRetransmits},ordered:{enumerable:true,value:options.ordered},reliable:{enumerable:true,value:options.maxPacketLifeTime===null&&options.maxRetransmits===null}});return _this}LocalDataTrack.prototype.send=function(data){this._trackSender.send(data)};return LocalDataTrack}(Track);module.exports=LocalDataTrack},{"../../data/sender":6,"./":18}],22:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var LocalTrackPublication=require("./localtrackpublication");var LocalDataTrackPublication=function(_super){__extends(LocalDataTrackPublication,_super);function LocalDataTrackPublication(signaling,track,unpublish,options){return _super.call(this,signaling,track,unpublish,options)||this}LocalDataTrackPublication.prototype.toString=function(){return"[LocalDataTrackPublication #"+this._instanceId+": "+this.trackSid+"]"};return LocalDataTrackPublication}(LocalTrackPublication);module.exports=LocalDataTrackPublication},{"./localtrackpublication":24}],23:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var getUserMedia=require("../../webrtc").getUserMedia;var _a=require("../../webrtc/util"),guessBrowser=_a.guessBrowser,isIOSChrome=_a.isIOSChrome;var _b=require("../../util"),capitalize=_b.capitalize,defer=_b.defer,isUserMediaTrack=_b.isUserMediaTrack,waitForSometime=_b.waitForSometime,waitForEvent=_b.waitForEvent;var ILLEGAL_INVOKE=require("../../util/constants").typeErrors.ILLEGAL_INVOKE;var detectSilentAudio=require("../../util/detectsilentaudio");var detectSilentVideo=require("../../util/detectsilentvideo");var documentVisibilityMonitor=require("../../util/documentvisibilitymonitor.js");var localMediaRestartDeferreds=require("../../util/localmediarestartdeferreds");var gUMSilentTrackWorkaround=require("../../webaudio/workaround180748");var MediaTrackSender=require("./sender");function mixinLocalMediaTrack(AudioOrVideoTrack){return function(_super){__extends(LocalMediaTrack,_super);function LocalMediaTrack(mediaStreamTrack,options){var _this=this;var workaroundWebKitBug1208516=(guessBrowser()==="safari"||isIOSChrome())&&isUserMediaTrack(mediaStreamTrack)&&typeof document==="object"&&typeof document.addEventListener==="function"&&typeof document.visibilityState==="string";options=Object.assign({getUserMedia:getUserMedia,isCreatedByCreateLocalTracks:false,workaroundWebKitBug1208516:workaroundWebKitBug1208516,gUMSilentTrackWorkaround:gUMSilentTrackWorkaround},options);var mediaTrackSender=new MediaTrackSender(mediaStreamTrack);var kind=mediaTrackSender.kind;_this=_super.call(this,mediaTrackSender,options)||this;Object.defineProperties(_this,{_constraints:{value:typeof options[kind]==="object"?options[kind]:{},writable:true},_getUserMedia:{value:options.getUserMedia},_gUMSilentTrackWorkaround:{value:options.gUMSilentTrackWorkaround},_workaroundWebKitBug1208516:{value:options.workaroundWebKitBug1208516},_workaroundWebKitBug1208516Cleanup:{value:null,writable:true},_didCallEnd:{value:false,writable:true},_isCreatedByCreateLocalTracks:{value:options.isCreatedByCreateLocalTracks},_trackSender:{value:mediaTrackSender},id:{enumerable:true,value:mediaTrackSender.id},isEnabled:{enumerable:true,get:function(){return mediaTrackSender.enabled}},isStopped:{enumerable:true,get:function(){return mediaTrackSender.readyState==="ended"}}});if(_this._workaroundWebKitBug1208516){_this._workaroundWebKitBug1208516Cleanup=restartWhenInadvertentlyStopped(_this)}return _this}LocalMediaTrack.prototype._end=function(){if(this._didCallEnd){return}_super.prototype._end.call(this);this._didCallEnd=true;this.emit("stopped",this)};LocalMediaTrack.prototype._initialize=function(){if(this._didCallEnd){this._didCallEnd=false}_super.prototype._initialize.call(this)};LocalMediaTrack.prototype._reacquireTrack=function(constraints){var _a;var _b=this,getUserMedia=_b._getUserMedia,gUMSilentTrackWorkaround=_b._gUMSilentTrackWorkaround,log=_b._log,kind=_b.mediaStreamTrack.kind;log.info("Re-acquiring the MediaStreamTrack");log.debug("Constraints:",constraints);var gUMConstraints=Object.assign({audio:false,video:false},(_a={},_a[kind]=constraints,_a));var gUMPromise=this._workaroundWebKitBug1208516Cleanup?gUMSilentTrackWorkaround(log,getUserMedia,gUMConstraints):getUserMedia(gUMConstraints);return gUMPromise.then(function(mediaStream){return mediaStream.getTracks()[0]})};LocalMediaTrack.prototype._restart=function(constraints){var _this=this;var log=this._log;constraints=constraints||this._constraints;this._stop();return this._reacquireTrack(constraints).catch(function(error){log.error("Failed to re-acquire the MediaStreamTrack:",{error:error,constraints:constraints});throw error}).then(function(newMediaStreamTrack){log.info("Re-acquired the MediaStreamTrack");log.debug("MediaStreamTrack:",newMediaStreamTrack);_this._constraints=Object.assign({},constraints);return _this._setMediaStreamTrack(newMediaStreamTrack)})};LocalMediaTrack.prototype._setMediaStreamTrack=function(mediaStreamTrack){var _this=this;mediaStreamTrack.enabled=this.mediaStreamTrack.enabled;this._stop();return(this._unprocessedTrack?Promise.resolve().then(function(){_this._unprocessedTrack=mediaStreamTrack}):this._trackSender.setMediaStreamTrack(mediaStreamTrack).catch(function(error){_this._log.warn("setMediaStreamTrack failed:",{error:error,mediaStreamTrack:mediaStreamTrack})})).then(function(){_this._initialize();_this._getAllAttachedElements().forEach(function(el){return _this._attach(el)})})};LocalMediaTrack.prototype._stop=function(){this.mediaStreamTrack.stop();this._end();return this};LocalMediaTrack.prototype.enable=function(enabled){enabled=typeof enabled==="boolean"?enabled:true;if(enabled!==this.mediaStreamTrack.enabled){this._log.info((enabled?"En":"Dis")+"abling");this.mediaStreamTrack.enabled=enabled;this.emit(enabled?"enabled":"disabled",this)}return this};LocalMediaTrack.prototype.disable=function(){return this.enable(false)};LocalMediaTrack.prototype.restart=function(constraints){var _this=this;var kind=this.kind;if(!this._isCreatedByCreateLocalTracks){return Promise.reject(ILLEGAL_INVOKE("restart","can only be called on a"+(" Local"+capitalize(kind)+"Track that is created using createLocalTracks")+(" or createLocal"+capitalize(kind)+"Track.")))}if(this._workaroundWebKitBug1208516Cleanup){
40
- this._workaroundWebKitBug1208516Cleanup();this._workaroundWebKitBug1208516Cleanup=null}var promise=this._restart(constraints);if(this._workaroundWebKitBug1208516){promise=promise.finally(function(){_this._workaroundWebKitBug1208516Cleanup=restartWhenInadvertentlyStopped(_this)})}return promise};LocalMediaTrack.prototype.stop=function(){this._log.info("Stopping");if(this._workaroundWebKitBug1208516Cleanup){this._workaroundWebKitBug1208516Cleanup();this._workaroundWebKitBug1208516Cleanup=null}return this._stop()};return LocalMediaTrack}(AudioOrVideoTrack)}function restartWhenInadvertentlyStopped(localMediaTrack){var log=localMediaTrack._log,kind=localMediaTrack.kind;var detectSilence={audio:detectSilentAudio,video:detectSilentVideo}[kind];var el=localMediaTrack._dummyEl,mediaStreamTrack=localMediaTrack.mediaStreamTrack;var trackChangeInProgress=null;function checkSilence(){return el.play().then(function(){return detectSilence(el)}).then(function(isSilent){if(isSilent){log.warn("Silence detected")}else{log.info("Non-silence detected")}return isSilent}).catch(function(error){log.warn("Failed to detect silence:",error)}).finally(function(){el.pause()})}function shouldReacquireTrack(){var _workaroundWebKitBug1208516Cleanup=localMediaTrack._workaroundWebKitBug1208516Cleanup,isStopped=localMediaTrack.isStopped,muted=localMediaTrack.mediaStreamTrack.muted;var isInadvertentlyStopped=isStopped&&!!_workaroundWebKitBug1208516Cleanup;return Promise.resolve().then(function(){return document.visibilityState==="visible"&&!trackChangeInProgress&&(muted||isInadvertentlyStopped||checkSilence())})}function maybeRestart(){return Promise.race([waitForEvent(mediaStreamTrack,"unmute"),waitForSometime(50)]).then(function(){return shouldReacquireTrack()}).then(function(shouldReacquire){if(shouldReacquire&&!trackChangeInProgress){trackChangeInProgress=defer();localMediaTrack._restart().finally(function(){el=localMediaTrack._dummyEl;removeMediaStreamTrackListeners();mediaStreamTrack=localMediaTrack.mediaStreamTrack;addMediaStreamTrackListeners();trackChangeInProgress.resolve();trackChangeInProgress=null}).catch(function(error){log.error("failed to restart track: ",error)})}var promise=trackChangeInProgress&&trackChangeInProgress.promise||Promise.resolve();return promise.finally(function(){return localMediaRestartDeferreds.resolveDeferred(kind)})}).catch(function(ex){log.error("error in maybeRestart: "+ex.message)})}function onMute(){var log=localMediaTrack._log,kind=localMediaTrack.kind;log.info("Muted");log.debug("LocalMediaTrack:",localMediaTrack);localMediaRestartDeferreds.startDeferred(kind)}function addMediaStreamTrackListeners(){mediaStreamTrack.addEventListener("ended",maybeRestart);mediaStreamTrack.addEventListener("mute",onMute);mediaStreamTrack.addEventListener("unmute",maybeRestart)}function removeMediaStreamTrackListeners(){mediaStreamTrack.removeEventListener("ended",maybeRestart);mediaStreamTrack.removeEventListener("mute",onMute);mediaStreamTrack.removeEventListener("unmute",maybeRestart)}var onVisibilityChange=function(isVisible){return isVisible?maybeRestart():false};documentVisibilityMonitor.onVisibilityChange(1,onVisibilityChange);addMediaStreamTrackListeners();return function(){documentVisibilityMonitor.offVisibilityChange(1,onVisibilityChange);removeMediaStreamTrackListeners()}}module.exports=mixinLocalMediaTrack},{"../../util":131,"../../util/constants":124,"../../util/detectsilentaudio":125,"../../util/detectsilentvideo":126,"../../util/documentvisibilitymonitor.js":127,"../../util/localmediarestartdeferreds":134,"../../webaudio/workaround180748":154,"../../webrtc":157,"../../webrtc/util":170,"./sender":38}],24:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var __spreadArray=this&&this.__spreadArray||function(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to};var TrackPublication=require("./trackpublication");var _a=require("../../util/constants"),E=_a.typeErrors,trackPriority=_a.trackPriority;var LocalTrackPublication=function(_super){__extends(LocalTrackPublication,_super);function LocalTrackPublication(signaling,track,unpublish,options){var _this=_super.call(this,track.name,signaling.sid,options)||this;Object.defineProperties(_this,{_reemitSignalingEvent:{value:function(){var args=[];for(var _i=0;_i<arguments.length;_i++){args[_i]=arguments[_i]}return _this.emit.apply(_this,__spreadArray([args&&args.length?"warning":"warningsCleared"],__read(args)))}},_reemitTrackEvent:{value:function(){return _this.emit(_this.isTrackEnabled?"trackEnabled":"trackDisabled")}},_signaling:{value:signaling},_unpublish:{value:unpublish},isTrackEnabled:{enumerable:true,get:function(){return this.track.kind==="data"?true:this.track.isEnabled}},kind:{enumerable:true,value:track.kind},priority:{enumerable:true,get:function(){return signaling.updatedPriority}},track:{enumerable:true,value:track}});["disabled","enabled"].forEach(function(name){return track.on(name,_this._reemitTrackEvent)});["warning","warningsCleared"].forEach(function(name){return signaling.on(name,_this._reemitSignalingEvent)});return _this}LocalTrackPublication.prototype.toString=function(){return"[LocalTrackPublication #"+this._instanceId+": "+this.trackSid+"]"};LocalTrackPublication.prototype.setPriority=function(priority){var priorityValues=Object.values(trackPriority);if(!priorityValues.includes(priority)){throw E.INVALID_VALUE("priority",priorityValues)}this._signaling.setPriority(priority);return this};LocalTrackPublication.prototype.unpublish=function(){var _this=this;["disabled","enabled"].forEach(function(name){return _this.track.removeListener(name,_this._reemitTrackEvent)});["warning","warningsCleared"].forEach(function(name){return _this._signaling.removeListener(name,_this._reemitSignalingEvent)});this._unpublish(this);return this};return LocalTrackPublication}(TrackPublication);module.exports=LocalTrackPublication},{"../../util/constants":124,"./trackpublication":39}],25:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var _a=require("../../webrtc/util"),guessBrowser=_a.guessBrowser,isIOSChrome=_a.isIOSChrome;var detectSilentVideo=require("../../util/detectsilentvideo");var mixinLocalMediaTrack=require("./localmediatrack");var VideoTrack=require("./videotrack");var isUserMediaTrack=require("../../util").isUserMediaTrack;var LocalMediaVideoTrack=mixinLocalMediaTrack(VideoTrack);var LocalVideoTrack=function(_super){__extends(LocalVideoTrack,_super);function LocalVideoTrack(mediaStreamTrack,options){var _this=this;options=Object.assign({workaroundSilentLocalVideo:(guessBrowser()==="safari"||isIOSChrome())&&isUserMediaTrack(mediaStreamTrack)&&typeof document!=="undefined"&&typeof document.createElement==="function"},options);_this=_super.call(this,mediaStreamTrack,options)||this;Object.defineProperties(_this,{_workaroundSilentLocalVideo:{value:options.workaroundSilentLocalVideo?workaroundSilentLocalVideo:null},_workaroundSilentLocalVideoCleanup:{value:null,writable:true}});if(_this._workaroundSilentLocalVideo){_this._workaroundSilentLocalVideoCleanup=_this._workaroundSilentLocalVideo(_this,document)}return _this}LocalVideoTrack.prototype.toString=function(){return"[LocalVideoTrack #"+this._instanceId+": "+this.id+"]"};LocalVideoTrack.prototype._checkIfCanCaptureFrames=function(){return _super.prototype._checkIfCanCaptureFrames.call(this,this._trackSender.isPublishing)};LocalVideoTrack.prototype._end=function(){return _super.prototype._end.apply(this,arguments)};LocalVideoTrack.prototype._setSenderMediaStreamTrack=function(useProcessed){var _this=this;var unprocessedTrack=this.mediaStreamTrack;var mediaStreamTrack=useProcessed?this.processedTrack:unprocessedTrack;return this._trackSender.setMediaStreamTrack(mediaStreamTrack).catch(function(error){return _this._log.warn("setMediaStreamTrack failed on LocalVideoTrack RTCRtpSender",{error:error,mediaStreamTrack:mediaStreamTrack})}).then(function(){_this._unprocessedTrack=useProcessed?unprocessedTrack:null})};LocalVideoTrack.prototype.addProcessor=function(){this._log.debug("Adding VideoProcessor to the LocalVideoTrack");var result=_super.prototype.addProcessor.apply(this,arguments);if(!this.processedTrack){return this._log.warn("Unable to add a VideoProcessor to the LocalVideoTrack")}this._log.debug("Updating LocalVideoTrack's MediaStreamTrack with the processed MediaStreamTrack",this.processedTrack);this._setSenderMediaStreamTrack(true);return result};LocalVideoTrack.prototype.removeProcessor=function(){var _this=this;this._log.debug("Removing VideoProcessor from the LocalVideoTrack");var result=_super.prototype.removeProcessor.apply(this,arguments);this._log.debug("Updating LocalVideoTrack's MediaStreamTrack with the original MediaStreamTrack");this._setSenderMediaStreamTrack().then(function(){return _this._updateElementsMediaStreamTrack()});return result};LocalVideoTrack.prototype.disable=function(){var result=_super.prototype.disable.apply(this,arguments);if(this.processedTrack){this.processedTrack.enabled=false}return result};LocalVideoTrack.prototype.enable=function(enabled){if(enabled===void 0){enabled=true}var result=_super.prototype.enable.apply(this,arguments);if(this.processedTrack){this.processedTrack.enabled=enabled;if(enabled){this._captureFrames();this._log.debug("Updating LocalVideoTrack's MediaStreamTrack with the processed MediaStreamTrack",this.processedTrack);this._setSenderMediaStreamTrack(true)}}return result};LocalVideoTrack.prototype.restart=function(){var _this=this;if(this._workaroundSilentLocalVideoCleanup){this._workaroundSilentLocalVideoCleanup();this._workaroundSilentLocalVideoCleanup=null}var promise=_super.prototype.restart.apply(this,arguments);if(this.processor){promise.then(function(){_this._restartProcessor()})}if(this._workaroundSilentLocalVideo){promise.finally(function(){_this._workaroundSilentLocalVideoCleanup=_this._workaroundSilentLocalVideo(_this,document)})}return promise};LocalVideoTrack.prototype.stop=function(){if(this._workaroundSilentLocalVideoCleanup){this._workaroundSilentLocalVideoCleanup();this._workaroundSilentLocalVideoCleanup=null}return _super.prototype.stop.apply(this,arguments)};return LocalVideoTrack}(LocalMediaVideoTrack);function workaroundSilentLocalVideo(localVideoTrack,doc){var log=localVideoTrack._log;var el=localVideoTrack._dummyEl,mediaStreamTrack=localVideoTrack.mediaStreamTrack;function onUnmute(){if(!localVideoTrack.isEnabled){return}log.info("Unmuted, checking silence");el.play().then(function(){return detectSilentVideo(el,doc)}).then(function(isSilent){if(!isSilent){log.info("Non-silent frames detected, so no need to restart");return}log.warn("Silence detected, restarting");localVideoTrack._stop();return localVideoTrack._restart()}).catch(function(error){log.warn("Failed to detect silence and restart:",error)}).finally(function(){el=localVideoTrack._dummyEl;if(el&&!el.paused){el.pause()}mediaStreamTrack.removeEventListener("unmute",onUnmute);mediaStreamTrack=localVideoTrack.mediaStreamTrack;mediaStreamTrack.addEventListener("unmute",onUnmute)})}mediaStreamTrack.addEventListener("unmute",onUnmute);return function(){mediaStreamTrack.removeEventListener("unmute",onUnmute)}}module.exports=LocalVideoTrack},{"../../util":131,"../../util/detectsilentvideo":126,"../../webrtc/util":170,"./localmediatrack":23,"./videotrack":42}],26:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var LocalTrackPublication=require("./localtrackpublication");var LocalVideoTrackPublication=function(_super){__extends(LocalVideoTrackPublication,_super);function LocalVideoTrackPublication(signaling,track,unpublish,options){return _super.call(this,signaling,track,unpublish,options)||this}LocalVideoTrackPublication.prototype.toString=function(){return"[LocalVideoTrackPublication #"+this._instanceId+": "+this.trackSid+"]"};return LocalVideoTrackPublication}(LocalTrackPublication);module.exports=LocalVideoTrackPublication},{"./localtrackpublication":24}],27:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var _a=require("../../webrtc/util"),guessBrowser=_a.guessBrowser,isIOSChrome=_a.isIOSChrome;var MediaStream=require("../../webrtc").MediaStream;var _b=require("../../util"),waitForEvent=_b.waitForEvent,waitForSometime=_b.waitForSometime;var localMediaRestartDeferreds=require("../../util/localmediarestartdeferreds");var Track=require("./");var MediaTrack=function(_super){__extends(MediaTrack,_super);function MediaTrack(mediaTrackTransceiver,options){var _this=this;options=Object.assign({playPausedElementsIfNotBackgrounded:(guessBrowser()==="safari"||isIOSChrome())&&typeof document==="object"&&typeof document.addEventListener==="function"&&typeof document.visibilityState==="string"},options);_this=_super.call(this,mediaTrackTransceiver.id,mediaTrackTransceiver.kind,options)||this;var isStarted=false;options=Object.assign({MediaStream:MediaStream},options);Object.defineProperties(_this,{_attachments:{value:new Set},_dummyEl:{value:null,writable:true},_elShims:{value:new WeakMap},_isStarted:{get:function(){return isStarted},set:function(_isStarted){isStarted=_isStarted}},_playPausedElementsIfNotBackgrounded:{value:options.playPausedElementsIfNotBackgrounded},_shouldShimAttachedElements:{value:options.workaroundWebKitBug212780||options.playPausedElementsIfNotBackgrounded},_unprocessedTrack:{value:null,writable:true},_MediaStream:{value:options.MediaStream},isStarted:{enumerable:true,get:function(){return isStarted}},mediaStreamTrack:{enumerable:true,get:function(){return this._unprocessedTrack||mediaTrackTransceiver.track}},processedTrack:{enumerable:true,value:null,writable:true}});_this._initialize();return _this}MediaTrack.prototype._start=function(){this._log.debug("Started");this._isStarted=true;if(this._dummyEl){this._dummyEl.oncanplay=null}this.emit("started",this)};MediaTrack.prototype._initialize=function(){var self=this;this._log.debug("Initializing");this._dummyEl=this._createElement();this.mediaStreamTrack.addEventListener("ended",function onended(){self._end();self.mediaStreamTrack.removeEventListener("ended",onended)});if(this._dummyEl){this._dummyEl.muted=true;this._dummyEl.oncanplay=this._start.bind(this,this._dummyEl);this._attach(this._dummyEl,this.mediaStreamTrack);this._attachments.delete(this._dummyEl)}};MediaTrack.prototype._end=function(){this._log.debug("Ended");if(this._dummyEl){this._dummyEl.remove();this._dummyEl.srcObject=null;this._dummyEl.oncanplay=null;this._dummyEl=null}};MediaTrack.prototype.attach=function(el){var _this=this;if(typeof el==="string"){el=this._selectElement(el)}else if(!el){el=this._createElement()}this._log.debug("Attempting to attach to element:",el);el=this._attach(el);if(this._shouldShimAttachedElements&&!this._elShims.has(el)){var onUnintentionallyPaused=this._playPausedElementsIfNotBackgrounded?function(){return playIfPausedAndNotBackgrounded(el,_this._log)}:null;this._elShims.set(el,shimMediaElement(el,onUnintentionallyPaused))}return el};MediaTrack.prototype._attach=function(el,mediaStreamTrack){if(mediaStreamTrack===void 0){mediaStreamTrack=this.processedTrack||this.mediaStreamTrack}var mediaStream=el.srcObject;if(!(mediaStream instanceof this._MediaStream)){mediaStream=new this._MediaStream}var getTracks=mediaStreamTrack.kind==="audio"?"getAudioTracks":"getVideoTracks";mediaStream[getTracks]().forEach(function(track){mediaStream.removeTrack(track)});mediaStream.addTrack(mediaStreamTrack);el.srcObject=mediaStream;el.autoplay=true;el.playsInline=true;if(!this._attachments.has(el)){this._attachments.add(el)}return el};MediaTrack.prototype._selectElement=function(selector){var el=document.querySelector(selector);if(!el){throw new Error("Selector matched no element: "+selector)}return el};MediaTrack.prototype._updateElementsMediaStreamTrack=function(){var _this=this;this._log.debug("Reattaching all elements to update mediaStreamTrack");this._getAllAttachedElements().forEach(function(el){return _this._attach(el)})};MediaTrack.prototype._createElement=function(){return typeof document!=="undefined"?document.createElement(this.kind):null};MediaTrack.prototype.detach=function(el){var els;if(typeof el==="string"){els=[this._selectElement(el)]}else if(!el){els=this._getAllAttachedElements()}else{els=[el]}this._log.debug("Attempting to detach from elements:",els);this._detachElements(els);return el?els[0]:els};MediaTrack.prototype._detachElements=function(elements){return elements.map(this._detachElement.bind(this))};MediaTrack.prototype._detachElement=function(el){if(!this._attachments.has(el)){return el}var mediaStream=el.srcObject;if(mediaStream instanceof this._MediaStream){mediaStream.removeTrack(this.processedTrack||this.mediaStreamTrack)}this._attachments.delete(el);if(this._shouldShimAttachedElements&&this._elShims.has(el)){var shim=this._elShims.get(el);shim.unShim();this._elShims.delete(el)}return el};MediaTrack.prototype._getAllAttachedElements=function(){var els=[];this._attachments.forEach(function(el){els.push(el)});return els};return MediaTrack}(Track);function playIfPausedAndNotBackgrounded(el,log){var tag=el.tagName.toLowerCase();log.warn("Unintentionally paused:",el);Promise.race([waitForEvent(document,"visibilitychange"),waitForSometime(1e3)]).then(function(){if(document.visibilityState==="visible"){localMediaRestartDeferreds.whenResolved("audio").then(function(){log.info("Playing unintentionally paused <"+tag+"> element");log.debug("Element:",el);return el.play()}).then(function(){log.info("Successfully played unintentionally paused <"+tag+"> element");log.debug("Element:",el)}).catch(function(error){log.warn("Error while playing unintentionally paused <"+tag+"> element:",{error:error,el:el})})}})}function shimMediaElement(el,onUnintentionallyPaused){if(onUnintentionallyPaused===void 0){onUnintentionallyPaused=null}var origPause=el.pause;var origPlay=el.play;var pausedIntentionally=false;el.pause=function(){pausedIntentionally=true;return origPause.call(el)};el.play=function(){pausedIntentionally=false;return origPlay.call(el)};var onPause=onUnintentionallyPaused?function(){if(!pausedIntentionally){onUnintentionallyPaused()}}:null;if(onPause){el.addEventListener("pause",onPause)}return{pausedIntentionally:function(){return pausedIntentionally},unShim:function(){el.pause=origPause;el.play=origPlay;if(onPause){el.removeEventListener("pause",onPause)}}}}module.exports=MediaTrack},{"../../util":131,"../../util/localmediarestartdeferreds":134,"../../webrtc":157,"../../webrtc/util":170,"./":18}],28:[function(require,module,exports){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};Object.defineProperty(exports,"__esModule",{value:true});exports.applyNoiseCancellation=exports.NoiseCancellationImpl=void 0;var noisecancellationadapter_1=require("../../noisecancellationadapter");var Log=require("../../util/log");var NoiseCancellationImpl=function(){function NoiseCancellationImpl(processor,originalTrack){this._processor=processor;this._sourceTrack=originalTrack;this._disabledPermanent=false}Object.defineProperty(NoiseCancellationImpl.prototype,"vendor",{get:function(){return this._processor.vendor},enumerable:false,configurable:true});Object.defineProperty(NoiseCancellationImpl.prototype,"sourceTrack",{get:function(){return this._sourceTrack},enumerable:false,configurable:true});Object.defineProperty(NoiseCancellationImpl.prototype,"isEnabled",{get:function(){return this._processor.isEnabled()},enumerable:false,configurable:true});NoiseCancellationImpl.prototype.enable=function(){if(this._disabledPermanent){throw new Error(this.vendor+" noise cancellation is disabled permanently for this track")}this._processor.enable();return Promise.resolve()};NoiseCancellationImpl.prototype.disable=function(){this._processor.disable();return Promise.resolve()};NoiseCancellationImpl.prototype.reacquireTrack=function(reacquire){return __awaiter(this,void 0,void 0,function(){var processorWasEnabled,track,processedTrack;return __generator(this,function(_a){switch(_a.label){case 0:processorWasEnabled=this._processor.isEnabled();this._processor.disconnect();return[4,reacquire()];case 1:track=_a.sent();this._sourceTrack=track;return[4,this._processor.connect(track)];case 2:processedTrack=_a.sent();if(processorWasEnabled){this._processor.enable()}else{this._processor.disable()}return[2,processedTrack]}})})};NoiseCancellationImpl.prototype.disablePermanently=function(){this._disabledPermanent=true;return this.disable()};NoiseCancellationImpl.prototype.stop=function(){this._processor.disconnect();this._sourceTrack.stop()};return NoiseCancellationImpl}();exports.NoiseCancellationImpl=NoiseCancellationImpl;function applyNoiseCancellation(mediaStreamTrack,noiseCancellationOptions,log){return __awaiter(this,void 0,void 0,function(){var processor,cleanTrack,noiseCancellation,ex_1;return __generator(this,function(_a){switch(_a.label){case 0:_a.trys.push([0,2,,3]);return[4,noisecancellationadapter_1.createNoiseCancellationAudioProcessor(noiseCancellationOptions,log)];case 1:processor=_a.sent();cleanTrack=processor.connect(mediaStreamTrack);noiseCancellation=new NoiseCancellationImpl(processor,mediaStreamTrack);return[2,{cleanTrack:cleanTrack,noiseCancellation:noiseCancellation}];case 2:ex_1=_a.sent();log.warn("Failed to create noise cancellation. Returning normal audio track: "+ex_1);return[2,{cleanTrack:mediaStreamTrack}];case 3:return[2]}})})}exports.applyNoiseCancellation=applyNoiseCancellation},{"../../noisecancellationadapter":44,"../../util/log":135}],29:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var MediaTrackTransceiver=require("./transceiver");var MediaTrackReceiver=function(_super){__extends(MediaTrackReceiver,_super);function MediaTrackReceiver(id,mediaStreamTrack){return _super.call(this,id,mediaStreamTrack)||this}return MediaTrackReceiver}(MediaTrackTransceiver);module.exports=MediaTrackReceiver},{"./transceiver":40}],30:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var AudioTrack=require("./audiotrack");var mixinRemoteMediaTrack=require("./remotemediatrack");var RemoteMediaAudioTrack=mixinRemoteMediaTrack(AudioTrack);var RemoteAudioTrack=function(_super){__extends(RemoteAudioTrack,_super);function RemoteAudioTrack(sid,mediaTrackReceiver,isEnabled,isSwitchedOff,setPriority,setRenderHint,options){return _super.call(this,sid,mediaTrackReceiver,isEnabled,isSwitchedOff,setPriority,setRenderHint,options)||this}RemoteAudioTrack.prototype.toString=function(){return"[RemoteAudioTrack #"+this._instanceId+": "+this.sid+"]"};RemoteAudioTrack.prototype.setPriority=function(priority){return _super.prototype.setPriority.call(this,priority)};return RemoteAudioTrack}(RemoteMediaAudioTrack);module.exports=RemoteAudioTrack},{"./audiotrack":13,"./remotemediatrack":34}],31:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var RemoteTrackPublication=require("./remotetrackpublication");var RemoteAudioTrackPublication=function(_super){__extends(RemoteAudioTrackPublication,_super);function RemoteAudioTrackPublication(signaling,options){return _super.call(this,signaling,options)||this}RemoteAudioTrackPublication.prototype.toString=function(){return"[RemoteAudioTrackPublication #"+this._instanceId+": "+this.trackSid+"]"};return RemoteAudioTrackPublication}(RemoteTrackPublication);module.exports=RemoteAudioTrackPublication},{"./remotetrackpublication":35}],32:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var __spreadArray=this&&this.__spreadArray||function(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to};var Track=require("./");var _a=require("../../util/constants"),E=_a.typeErrors,trackPriority=_a.trackPriority;var RemoteDataTrack=function(_super){__extends(RemoteDataTrack,_super);function RemoteDataTrack(sid,dataTrackReceiver,options){var _this=_super.call(this,dataTrackReceiver.id,"data",options)||this;Object.defineProperties(_this,{_isSwitchedOff:{value:false,writable:true},_priority:{value:null,writable:true},isEnabled:{enumerable:true,value:true},isSwitchedOff:{enumerable:true,get:function(){return this._isSwitchedOff}},maxPacketLifeTime:{enumerable:true,value:dataTrackReceiver.maxPacketLifeTime},maxRetransmits:{enumerable:true,value:dataTrackReceiver.maxRetransmits},ordered:{enumerable:true,value:dataTrackReceiver.ordered},priority:{enumerable:true,get:function(){return this._priority}},reliable:{enumerable:true,value:dataTrackReceiver.maxPacketLifeTime===null&&dataTrackReceiver.maxRetransmits===null},sid:{enumerable:true,value:sid}});dataTrackReceiver.on("message",function(data){_this.emit("message",data,_this)});return _this}RemoteDataTrack.prototype.setPriority=function(priority){var priorityValues=__spreadArray([null],__read(Object.values(trackPriority)));if(!priorityValues.includes(priority)){throw E.INVALID_VALUE("priority",priorityValues)}this._priority=priority;return this};RemoteDataTrack.prototype._setEnabled=function(){};RemoteDataTrack.prototype._setSwitchedOff=function(isSwitchedOff){if(this._isSwitchedOff!==isSwitchedOff){this._isSwitchedOff=isSwitchedOff;this.emit(isSwitchedOff?"switchedOff":"switchedOn",this)}};return RemoteDataTrack}(Track);module.exports=RemoteDataTrack},{"../../util/constants":124,"./":18}],33:[function(require,module,exports){
41
- "use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var RemoteTrackPublication=require("./remotetrackpublication");var RemoteDataTrackPublication=function(_super){__extends(RemoteDataTrackPublication,_super);function RemoteDataTrackPublication(signaling,options){return _super.call(this,signaling,options)||this}RemoteDataTrackPublication.prototype.toString=function(){return"[RemoteDataTrackPublication #"+this._instanceId+": "+this.trackSid+"]"};return RemoteDataTrackPublication}(RemoteTrackPublication);module.exports=RemoteDataTrackPublication},{"./remotetrackpublication":35}],34:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var __spreadArray=this&&this.__spreadArray||function(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to};var _a=require("../../util/constants"),E=_a.typeErrors,trackPriority=_a.trackPriority;var _b=require("../../webrtc/util"),guessBrowser=_b.guessBrowser,isIOSChrome=_b.isIOSChrome;var documentVisibilityMonitor=require("../../util/documentvisibilitymonitor.js");function mixinRemoteMediaTrack(AudioOrVideoTrack){return function(_super){__extends(RemoteMediaTrack,_super);function RemoteMediaTrack(sid,mediaTrackReceiver,isEnabled,isSwitchedOff,setPriority,setRenderHint,options){var _this=this;options=Object.assign({workaroundWebKitBug212780:(guessBrowser()==="safari"||isIOSChrome())&&typeof document==="object"&&typeof document.addEventListener==="function"&&typeof document.visibilityState==="string"},options);_this=_super.call(this,mediaTrackReceiver,options)||this;Object.defineProperties(_this,{_isEnabled:{value:isEnabled,writable:true},_isSwitchedOff:{value:isSwitchedOff,writable:true},_priority:{value:null,writable:true},_setPriority:{value:setPriority},_setRenderHint:{value:function(renderHint){_this._log.debug("updating render hint:",renderHint);setRenderHint(renderHint)}},isEnabled:{enumerable:true,get:function(){return this._isEnabled}},isSwitchedOff:{enumerable:true,get:function(){return this._isSwitchedOff}},priority:{enumerable:true,get:function(){return this._priority}},sid:{enumerable:true,value:sid},_workaroundWebKitBug212780:{value:options.workaroundWebKitBug212780},_workaroundWebKitBug212780Cleanup:{value:null,writable:true}});return _this}RemoteMediaTrack.prototype.setPriority=function(priority){var priorityValues=__spreadArray([null],__read(Object.values(trackPriority)));if(!priorityValues.includes(priority)){throw E.INVALID_VALUE("priority",priorityValues)}if(this._priority!==priority){this._priority=priority;this._setPriority(priority)}return this};RemoteMediaTrack.prototype._setEnabled=function(isEnabled){if(this._isEnabled!==isEnabled){this._isEnabled=isEnabled;this.emit(this._isEnabled?"enabled":"disabled",this)}};RemoteMediaTrack.prototype._setSwitchedOff=function(isSwitchedOff){if(this._isSwitchedOff!==isSwitchedOff){this._isSwitchedOff=isSwitchedOff;this.emit(isSwitchedOff?"switchedOff":"switchedOn",this)}};RemoteMediaTrack.prototype.attach=function(el){var result=_super.prototype.attach.call(this,el);if(this.mediaStreamTrack.enabled!==true){this.mediaStreamTrack.enabled=true;if(this.processedTrack){this.processedTrack.enabled=true}if(this.processor){this._captureFrames()}}if(this._workaroundWebKitBug212780){this._workaroundWebKitBug212780Cleanup=this._workaroundWebKitBug212780Cleanup||playIfPausedWhileInBackground(this)}return result};RemoteMediaTrack.prototype.detach=function(el){var result=_super.prototype.detach.call(this,el);if(this._attachments.size===0){this.mediaStreamTrack.enabled=false;if(this.processedTrack){this.processedTrack.enabled=false}if(this._workaroundWebKitBug212780Cleanup){this._workaroundWebKitBug212780Cleanup();this._workaroundWebKitBug212780Cleanup=null}}return result};return RemoteMediaTrack}(AudioOrVideoTrack)}function playIfPausedWhileInBackground(remoteMediaTrack){var log=remoteMediaTrack._log,kind=remoteMediaTrack.kind;function onVisibilityChanged(isVisible){if(!isVisible){return}remoteMediaTrack._attachments.forEach(function(el){var shim=remoteMediaTrack._elShims.get(el);var isInadvertentlyPaused=el.paused&&shim&&!shim.pausedIntentionally();if(isInadvertentlyPaused){log.info("Playing inadvertently paused <"+kind+"> element");log.debug("Element:",el);log.debug("RemoteMediaTrack:",remoteMediaTrack);el.play().then(function(){log.info("Successfully played inadvertently paused <"+kind+"> element");log.debug("Element:",el);log.debug("RemoteMediaTrack:",remoteMediaTrack)}).catch(function(err){log.warn("Error while playing inadvertently paused <"+kind+"> element:",{err:err,el:el,remoteMediaTrack:remoteMediaTrack})})}})}documentVisibilityMonitor.onVisibilityChange(2,onVisibilityChanged);return function(){documentVisibilityMonitor.offVisibilityChange(2,onVisibilityChanged)}}module.exports=mixinRemoteMediaTrack},{"../../util/constants":124,"../../util/documentvisibilitymonitor.js":127,"../../webrtc/util":170}],35:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var TrackPublication=require("./trackpublication");var RemoteTrackPublication=function(_super){__extends(RemoteTrackPublication,_super);function RemoteTrackPublication(signaling,options){var _this=_super.call(this,signaling.name,signaling.sid,options)||this;Object.defineProperties(_this,{_signaling:{value:signaling},_track:{value:null,writable:true},isSubscribed:{enumerable:true,get:function(){return!!this._track}},isTrackEnabled:{enumerable:true,get:function(){return signaling.isEnabled}},kind:{enumerable:true,value:signaling.kind},publishPriority:{enumerable:true,get:function(){return signaling.priority}},track:{enumerable:true,get:function(){return this._track}}});var error=signaling.error,isEnabled=signaling.isEnabled,isSwitchedOff=signaling.isSwitchedOff,priority=signaling.priority;signaling.on("updated",function(){if(error!==signaling.error){error=signaling.error;_this.emit("subscriptionFailed",signaling.error);return}if(isEnabled!==signaling.isEnabled){isEnabled=signaling.isEnabled;if(_this.track){_this.track._setEnabled(signaling.isEnabled)}_this.emit(signaling.isEnabled?"trackEnabled":"trackDisabled")}if(isSwitchedOff!==signaling.isSwitchedOff){_this._log.debug(_this.trackSid+": "+(isSwitchedOff?"OFF":"ON")+" => "+(signaling.isSwitchedOff?"OFF":"ON"));isSwitchedOff=signaling.isSwitchedOff;if(_this.track){_this.track._setSwitchedOff(signaling.isSwitchedOff);_this.emit(isSwitchedOff?"trackSwitchedOff":"trackSwitchedOn",_this.track)}else if(isSwitchedOff){_this._log.warn("Track was not subscribed when switched Off.")}}if(priority!==signaling.priority){priority=signaling.priority;_this.emit("publishPriorityChanged",priority)}});return _this}RemoteTrackPublication.prototype.toString=function(){return"[RemoteTrackPublication #"+this._instanceId+": "+this.trackSid+"]"};RemoteTrackPublication.prototype._subscribed=function(track){if(!this._track&&track){this._track=track;this.emit("subscribed",track)}};RemoteTrackPublication.prototype._unsubscribe=function(){if(this._track){var track=this._track;this._track=null;this.emit("unsubscribed",track)}};return RemoteTrackPublication}(TrackPublication);module.exports=RemoteTrackPublication},{"./trackpublication":39}],36:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var mixinRemoteMediaTrack=require("./remotemediatrack");var VideoTrack=require("./videotrack");var documentVisibilityMonitor=require("../../util/documentvisibilitymonitor.js");var NullObserver=require("../../util/nullobserver.js").NullObserver;var Timeout=require("../../util/timeout");var RemoteMediaVideoTrack=mixinRemoteMediaTrack(VideoTrack);var TRACK_TURN_OF_DELAY_MS=50;var RemoteVideoTrack=function(_super){__extends(RemoteVideoTrack,_super);function RemoteVideoTrack(sid,mediaTrackReceiver,isEnabled,isSwitchedOff,setPriority,setRenderHint,options){var _this=this;options=Object.assign({clientTrackSwitchOffControl:"auto",contentPreferencesMode:"auto",enableDocumentVisibilityTurnOff:true},options);options=Object.assign({IntersectionObserver:typeof IntersectionObserver==="undefined"||options.clientTrackSwitchOffControl!=="auto"?NullObserver:IntersectionObserver,ResizeObserver:typeof ResizeObserver==="undefined"||options.contentPreferencesMode!=="auto"?NullObserver:ResizeObserver},options);_this=_super.call(this,sid,mediaTrackReceiver,isEnabled,isSwitchedOff,setPriority,setRenderHint,options)||this;Object.defineProperties(_this,{_enableDocumentVisibilityTurnOff:{value:options.enableDocumentVisibilityTurnOff===true&&options.clientTrackSwitchOffControl==="auto"},_documentVisibilityTurnOffCleanup:{value:null,writable:true},_clientTrackSwitchOffControl:{value:options.clientTrackSwitchOffControl},_contentPreferencesMode:{value:options.contentPreferencesMode},_invisibleElements:{value:new WeakSet},_elToPipCallbacks:{value:new WeakMap},_elToPipWindows:{value:new WeakMap},_turnOffTimer:{value:new Timeout(function(){_this._setRenderHint({enabled:false})},TRACK_TURN_OF_DELAY_MS,false)},_resizeObserver:{value:new options.ResizeObserver(function(entries){var visibleElementResized=entries.find(function(entry){return!_this._invisibleElements.has(entry.target)});if(visibleElementResized){maybeUpdateDimensionHint(_this)}})},_intersectionObserver:{value:new options.IntersectionObserver(function(entries){var shouldSetRenderHint=false;entries.forEach(function(entry){var wasVisible=!_this._invisibleElements.has(entry.target);if(wasVisible!==entry.isIntersecting){if(entry.isIntersecting){_this._log.debug("intersectionObserver detected: Off => On");_this._invisibleElements.delete(entry.target)}else{_this._log.debug("intersectionObserver detected: On => Off");_this._invisibleElements.add(entry.target)}shouldSetRenderHint=true}});if(shouldSetRenderHint){maybeUpdateEnabledHint(_this);maybeUpdateDimensionHint(_this)}},{threshold:.25})}});return _this}RemoteVideoTrack.prototype._start=function(dummyEl){var result=_super.prototype._start.call(this,dummyEl);maybeUpdateEnabledHint(this);return result};RemoteVideoTrack.prototype.switchOn=function(){if(this._clientTrackSwitchOffControl!=="manual"){throw new Error('Invalid state. You can call switchOn only when bandwidthProfile.video.clientTrackSwitchOffControl is set to "manual"')}this._setRenderHint({enabled:true});return this};RemoteVideoTrack.prototype.switchOff=function(){if(this._clientTrackSwitchOffControl!=="manual"){throw new Error('Invalid state. You can call switchOff only when bandwidthProfile.video.clientTrackSwitchOffControl is set to "manual"')}this._setRenderHint({enabled:false});return this};RemoteVideoTrack.prototype.setContentPreferences=function(contentPreferences){if(this._contentPreferencesMode!=="manual"){throw new Error('Invalid state. You can call switchOn only when bandwidthProfile.video.contentPreferencesMode is set to "manual"')}if(contentPreferences.renderDimensions){this._setRenderHint({renderDimensions:contentPreferences.renderDimensions})}return this};RemoteVideoTrack.prototype._unObservePip=function(el){var pipCallbacks=this._elToPipCallbacks.get(el);if(pipCallbacks){el.removeEventListener("enterpictureinpicture",pipCallbacks.onEnterPip);el.removeEventListener("leavepictureinpicture",pipCallbacks.onLeavePip);this._elToPipCallbacks.delete(el)}};RemoteVideoTrack.prototype._observePip=function(el){var _this=this;var pipCallbacks=this._elToPipCallbacks.get(el);if(!pipCallbacks){var onEnterPip=function(event){return _this._onEnterPip(event,el)};var onLeavePip=function(event){return _this._onLeavePip(event,el)};var onResizePip=function(event){return _this._onResizePip(event,el)};el.addEventListener("enterpictureinpicture",onEnterPip);el.addEventListener("leavepictureinpicture",onLeavePip);this._elToPipCallbacks.set(el,{onEnterPip:onEnterPip,onLeavePip:onLeavePip,onResizePip:onResizePip})}};RemoteVideoTrack.prototype._onEnterPip=function(event,videoEl){this._log.debug("onEnterPip");var pipWindow=event.pictureInPictureWindow;this._elToPipWindows.set(videoEl,pipWindow);var onResizePip=this._elToPipCallbacks.get(videoEl).onResizePip;pipWindow.addEventListener("resize",onResizePip);maybeUpdateEnabledHint(this)};RemoteVideoTrack.prototype._onLeavePip=function(event,videoEl){this._log.debug("onLeavePip");this._elToPipWindows.delete(videoEl);var onResizePip=this._elToPipCallbacks.get(videoEl).onResizePip;var pipWindow=event.pictureInPictureWindow;pipWindow.removeEventListener("resize",onResizePip);maybeUpdateEnabledHint(this)};RemoteVideoTrack.prototype._onResizePip=function(){maybeUpdateDimensionHint(this)};RemoteVideoTrack.prototype.attach=function(el){var result=_super.prototype.attach.call(this,el);if(this._clientTrackSwitchOffControl==="auto"){this._invisibleElements.add(result)}this._intersectionObserver.observe(result);this._resizeObserver.observe(result);if(this._enableDocumentVisibilityTurnOff){this._documentVisibilityTurnOffCleanup=this._documentVisibilityTurnOffCleanup||setupDocumentVisibilityTurnOff(this)}this._observePip(result);return result};RemoteVideoTrack.prototype.detach=function(el){var _this=this;var result=_super.prototype.detach.call(this,el);var elements=Array.isArray(result)?result:[result];elements.forEach(function(element){_this._intersectionObserver.unobserve(element);_this._resizeObserver.unobserve(element);_this._invisibleElements.delete(element);_this._unObservePip(element)});if(this._attachments.size===0){if(this._documentVisibilityTurnOffCleanup){this._documentVisibilityTurnOffCleanup();this._documentVisibilityTurnOffCleanup=null}}maybeUpdateEnabledHint(this);maybeUpdateDimensionHint(this);return result};RemoteVideoTrack.prototype.addProcessor=function(){return _super.prototype.addProcessor.apply(this,arguments)};RemoteVideoTrack.prototype.removeProcessor=function(){return _super.prototype.removeProcessor.apply(this,arguments)};RemoteVideoTrack.prototype.toString=function(){return"[RemoteVideoTrack #"+this._instanceId+": "+this.sid+"]"};RemoteVideoTrack.prototype.setPriority=function(priority){return _super.prototype.setPriority.call(this,priority)};return RemoteVideoTrack}(RemoteMediaVideoTrack);function setupDocumentVisibilityTurnOff(removeVideoTrack){function onVisibilityChanged(){maybeUpdateEnabledHint(removeVideoTrack)}documentVisibilityMonitor.onVisibilityChange(1,onVisibilityChanged);return function(){documentVisibilityMonitor.offVisibilityChange(1,onVisibilityChanged)}}function maybeUpdateEnabledHint(remoteVideoTrack){if(remoteVideoTrack._clientTrackSwitchOffControl!=="auto"){return}var visibleElements=remoteVideoTrack._getAllAttachedElements().filter(function(el){return!remoteVideoTrack._invisibleElements.has(el)});var pipWindows=remoteVideoTrack._getAllAttachedElements().filter(function(el){return remoteVideoTrack._elToPipWindows.has(el)});var enabled=pipWindows.length>0||document.visibilityState==="visible"&&visibleElements.length>0;if(enabled===true){remoteVideoTrack._turnOffTimer.clear();remoteVideoTrack._setRenderHint({enabled:true})}else if(!remoteVideoTrack._turnOffTimer.isSet){remoteVideoTrack._turnOffTimer.start()}}function maybeUpdateDimensionHint(remoteVideoTrack){if(remoteVideoTrack._contentPreferencesMode!=="auto"){return}var visibleElements=remoteVideoTrack._getAllAttachedElements().filter(function(el){return!remoteVideoTrack._invisibleElements.has(el)});var pipElements=remoteVideoTrack._getAllAttachedElements().map(function(el){var pipWindow=remoteVideoTrack._elToPipWindows.get(el);return pipWindow?{clientHeight:pipWindow.height,clientWidth:pipWindow.width}:{clientHeight:0,clientWidth:0}});var totalElements=visibleElements.concat(pipElements);if(totalElements.length>0){var _a=__read(totalElements.sort(function(el1,el2){return el2.clientHeight+el2.clientWidth-el1.clientHeight-el1.clientWidth-1}),1),_b=_a[0],clientHeight=_b.clientHeight,clientWidth=_b.clientWidth;var renderDimensions={height:clientHeight,width:clientWidth};remoteVideoTrack._setRenderHint({renderDimensions:renderDimensions})}}module.exports=RemoteVideoTrack},{"../../util/documentvisibilitymonitor.js":127,"../../util/nullobserver.js":138,"../../util/timeout":145,"./remotemediatrack":34,"./videotrack":42}],37:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var RemoteTrackPublication=require("./remotetrackpublication");var RemoteVideoTrackPublication=function(_super){__extends(RemoteVideoTrackPublication,_super);function RemoteVideoTrackPublication(signaling,options){return _super.call(this,signaling,options)||this}RemoteVideoTrackPublication.prototype.toString=function(){return"[RemoteVideoTrackPublication #"+this._instanceId+": "+this.trackSid+"]"};return RemoteVideoTrackPublication}(RemoteTrackPublication);module.exports=RemoteVideoTrackPublication},{"./remotetrackpublication":35}],38:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var MediaTrackTransceiver=require("./transceiver");var MediaTrackSender=function(_super){__extends(MediaTrackSender,_super);function MediaTrackSender(mediaStreamTrack){var _this=_super.call(this,mediaStreamTrack.id,mediaStreamTrack)||this;Object.defineProperties(_this,{_clones:{value:new Set},_senders:{value:new Set},_senderToPublisherHintCallbacks:{value:new Map},isPublishing:{get:function(){return!!this._clones.size}}});return _this}MediaTrackSender.prototype.clone=function(){var clone=new MediaTrackSender(this.track.clone());this._clones.add(clone);return clone};MediaTrackSender.prototype.removeClone=function(clone){this._clones.delete(clone)};MediaTrackSender.prototype.setMediaStreamTrack=function(mediaStreamTrack){var _this=this;var clones=Array.from(this._clones);var senders=Array.from(this._senders);return Promise.all(clones.map(function(clone){return clone.setMediaStreamTrack(mediaStreamTrack.clone())}).concat(senders.map(function(sender){return _this._replaceTrack(sender,mediaStreamTrack)}))).finally(function(){_this._track=mediaStreamTrack})};MediaTrackSender.prototype.addSender=function(sender,publisherHintCallback){this._senders.add(sender);if(publisherHintCallback){this._senderToPublisherHintCallbacks.set(sender,publisherHintCallback)}return this};MediaTrackSender.prototype.removeSender=function(sender){this._senders.delete(sender);this._senderToPublisherHintCallbacks.delete(sender);return this};MediaTrackSender.prototype.setPublisherHint=function(encodings){var _a=__read(Array.from(this._senderToPublisherHintCallbacks.values()),1),publisherHintCallback=_a[0];return publisherHintCallback?publisherHintCallback(encodings):Promise.resolve("COULD_NOT_APPLY_HINT")};MediaTrackSender.prototype._replaceTrack=function(sender,mediaStreamTrack){var _this=this;return sender.replaceTrack(mediaStreamTrack).then(function(replaceTrackResult){_this.setPublisherHint(null).catch(function(){});_this.emit("replaced");return replaceTrackResult})};return MediaTrackSender}(MediaTrackTransceiver);module.exports=MediaTrackSender},{"./transceiver":40}],39:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var EventEmitter=require("../../eventemitter");var _a=require("../../util"),buildLogLevels=_a.buildLogLevels,valueToJSON=_a.valueToJSON;var DEFAULT_LOG_LEVEL=require("../../util/constants").DEFAULT_LOG_LEVEL;var Log=require("../../util/log");var nInstances=0;var TrackPublication=function(_super){__extends(TrackPublication,_super);function TrackPublication(trackName,trackSid,options){var _this=_super.call(this)||this;options=Object.assign({logLevel:DEFAULT_LOG_LEVEL},options);var logLevels=buildLogLevels(options.logLevel);Object.defineProperties(_this,{_instanceId:{value:nInstances++},_log:{value:options.log?options.log.createLog("default",_this):new Log("default",_this,logLevels,options.loggerName)},trackName:{enumerable:true,value:trackName},trackSid:{enumerable:true,value:trackSid}});return _this}TrackPublication.prototype.toJSON=function(){return valueToJSON(this)};TrackPublication.prototype.toString=function(){return"[TrackPublication #"+this._instanceId+": "+this.trackSid+"]"};return TrackPublication}(EventEmitter);module.exports=TrackPublication},{"../../eventemitter":10,"../../util":131,"../../util/constants":124,"../../util/log":135}],40:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var TrackTransceiver=require("../../transceiver");var MediaTrackTransceiver=function(_super){__extends(MediaTrackTransceiver,_super);function MediaTrackTransceiver(id,mediaStreamTrack){var _this=_super.call(this,id,mediaStreamTrack.kind)||this;Object.defineProperties(_this,{_track:{value:mediaStreamTrack,writable:true},enabled:{enumerable:true,get:function(){return this._track.enabled}},readyState:{enumerable:true,get:function(){return this._track.readyState}},track:{enumerable:true,get:function(){return this._track}}});return _this}MediaTrackTransceiver.prototype.stop=function(){this.track.stop();_super.prototype.stop.call(this)};return MediaTrackTransceiver}(TrackTransceiver);module.exports=MediaTrackTransceiver},{"../../transceiver":118}],41:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var EventEmitter=require("events").EventEmitter;var DEFAULT_VIDEO_PROCESSOR_STATS_INTERVAL_MS=require("../../util/constants").DEFAULT_VIDEO_PROCESSOR_STATS_INTERVAL_MS;var VideoProcessorEventObserver=function(_super){__extends(VideoProcessorEventObserver,_super);function VideoProcessorEventObserver(log){var _this=_super.call(this)||this;Object.defineProperties(_this,{_lastStatsSaveTime:{value:null,writable:true},_lastStatsPublishTime:{value:null,writable:true},_log:{value:log},_processorInfo:{value:null,writable:true},_stats:{value:null,writable:true}});_this.on("add",function(info){_this._lastStatsSaveTime=Date.now();_this._lastStatsPublishTime=Date.now();_this._processorInfo=info;_this._stats=[];_this._reemitEvent("add",_this._getEventData())});_this.on("remove",function(){var data=_this._getEventData();_this._lastStatsSaveTime=null;_this._lastStatsPublishTime=null;_this._processorInfo=null;_this._stats=null;_this._reemitEvent("remove",data)});_this.on("start",function(){_this._reemitEvent("start",_this._getEventData())});_this.on("stop",function(message){_this._reemitEvent("stop",Object.assign({message:message},_this._getEventData()))});_this.on("stats",function(){return _this._maybeEmitStats()});return _this}VideoProcessorEventObserver.prototype._getEventData=function(){if(!this._processorInfo){return{}}var _a=this._processorInfo,processor=_a.processor,captureHeight=_a.captureHeight,captureWidth=_a.captureWidth,inputFrameRate=_a.inputFrameRate,isRemoteVideoTrack=_a.isRemoteVideoTrack;var data={captureHeight:captureHeight,captureWidth:captureWidth,inputFrameRate:inputFrameRate,isRemoteVideoTrack:isRemoteVideoTrack};data.name=processor._name||"VideoProcessor";["assetsPath","blurFilterRadius","fitType","isSimdEnabled","maskBlurRadius","version"].forEach(function(prop){var val=processor["_"+prop];if(typeof val!=="undefined"){data[prop]=val}});Object.keys(data).forEach(function(prop){var val=data[prop];if(typeof val==="boolean"){data[prop]=val?"true":"false"}});return data};VideoProcessorEventObserver.prototype._maybeEmitStats=function(){if(!this._stats||!this._processorInfo){return}var benchmark=this._processorInfo.processor._benchmark;if(!benchmark){return}var now=Date.now();if(now-this._lastStatsSaveTime<1e3){return}var entry={outputFrameRate:benchmark.getRate("totalProcessingDelay")};["captureFrameDelay","imageCompositionDelay","inputImageResizeDelay","processFrameDelay","segmentationDelay"].forEach(function(name){entry[name]=benchmark.getAverageDelay(name)});this._lastStatsSaveTime=now;this._stats.push(entry);if(now-this._lastStatsPublishTime<DEFAULT_VIDEO_PROCESSOR_STATS_INTERVAL_MS){return}this._lastStatsPublishTime=now;var stats=this._stats.splice(0);var averages=stats.reduce(function(averages,current,n){Object.keys(entry).forEach(function(name){if(!averages[name]){averages[name]=0}averages[name]=(averages[name]*n+current[name])/(n+1)});return averages},{});Object.keys(averages).forEach(function(name){averages[name]=parseFloat(averages[name].toFixed(2))});this._reemitEvent("stats",Object.assign({},averages,this._getEventData()))};VideoProcessorEventObserver.prototype._reemitEvent=function(name,data){this._log.debug("VideoProcessor:"+name,data);this.emit("event",{name:name,data:data})};return VideoProcessorEventObserver}(EventEmitter);module.exports=VideoProcessorEventObserver},{"../../util/constants":124,events:173}],42:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var MediaTrack=require("./mediatrack");var VideoProcessorEventObserver=require("./videoprocessoreventobserver");var DEFAULT_FRAME_RATE=require("../../util/constants").DEFAULT_FRAME_RATE;var VideoTrack=function(_super){__extends(VideoTrack,_super);function VideoTrack(mediaTrackTransceiver,options){var _this=_super.call(this,mediaTrackTransceiver,options)||this;Object.defineProperties(_this,{_captureTimeoutId:{value:null,writable:true},_isCapturing:{value:false,writable:true},_inputFrame:{value:null,writable:true},_outputFrame:{value:null,writable:true},_processorEventObserver:{value:null,writable:true},_unmuteHandler:{value:null,writable:true},dimensions:{enumerable:true,value:{width:null,height:null}},processor:{enumerable:true,value:null,writable:true}});_this._processorEventObserver=new(options.VideoProcessorEventObserver||VideoProcessorEventObserver)(_this._log);return _this}VideoTrack.prototype._checkIfCanCaptureFrames=function(isPublishing){if(isPublishing===void 0){isPublishing=false}var canCaptureFrames=true;var message="";var _a=this.mediaStreamTrack,enabled=_a.enabled,readyState=_a.readyState;if(!enabled){canCaptureFrames=false;message="MediaStreamTrack is disabled"}if(readyState==="ended"){
42
- canCaptureFrames=false;message="MediaStreamTrack is ended"}if(!this.processor){canCaptureFrames=false;message="VideoProcessor not detected."}if(!this._attachments.size&&!isPublishing){canCaptureFrames=false;message="VideoTrack is not publishing and there is no attached element."}if(message){this._log.debug(message)}return{canCaptureFrames:canCaptureFrames,message:message}};VideoTrack.prototype._captureFrames=function(){var _this=this;if(this._isCapturing){this._log.debug("Ignoring captureFrames call. Capture is already in progress");return}if(!this._checkIfCanCaptureFrames().canCaptureFrames){this._isCapturing=false;this._log.debug("Cannot capture frames. Ignoring captureFrames call.");return}this._isCapturing=true;this._processorEventObserver.emit("start");this._log.debug("Start capturing frames");var startTime=Date.now();var processFramePeriodMs;this._dummyEl.play().then(function(){var captureFrame=function(cb){clearTimeout(_this._captureTimeoutId);var _a=_this.mediaStreamTrack.getSettings().frameRate,frameRate=_a===void 0?DEFAULT_FRAME_RATE:_a;var capturePeriodMs=Math.floor(1e3/frameRate);var delay=capturePeriodMs-processFramePeriodMs;if(delay<0||typeof processFramePeriodMs!=="number"){delay=0}_this._captureTimeoutId=setTimeout(cb,delay)};var process=function(){var checkResult=_this._checkIfCanCaptureFrames();if(!checkResult.canCaptureFrames){_this._isCapturing=false;_this._processorEventObserver.emit("stop",checkResult.message);_this._log.debug("Cannot capture frames. Stopping capturing frames.");return}startTime=Date.now();var _a=_this.mediaStreamTrack.getSettings(),_b=_a.width,width=_b===void 0?0:_b,_c=_a.height,height=_c===void 0?0:_c;if(_this._inputFrame.width!==width){_this._inputFrame.width=width;_this._inputFrame.height=height;if(_this._outputFrame){_this._outputFrame.width=width;_this._outputFrame.height=height}}_this._inputFrame.getContext("2d").drawImage(_this._dummyEl,0,0,width,height);var result=null;try{result=_this.processor.processFrame(_this._inputFrame,_this._outputFrame)}catch(ex){_this._log.debug("Exception detected after calling processFrame.",ex)}(result instanceof Promise?result:Promise.resolve(result)).then(function(){if(_this._outputFrame){_this.processedTrack.requestFrame();_this._processorEventObserver.emit("stats")}}).finally(function(){processFramePeriodMs=Date.now()-startTime;captureFrame(process)})};captureFrame(process)}).catch(function(error){return _this._log.error("Video element cannot be played",{error:error,track:_this})})};VideoTrack.prototype._initialize=function(){var _this=this;_super.prototype._initialize.call(this);if(this._dummyEl){this._dummyEl.onloadedmetadata=function(){if(dimensionsChanged(_this,_this._dummyEl)){_this.dimensions.width=_this._dummyEl.videoWidth;_this.dimensions.height=_this._dummyEl.videoHeight}};this._dummyEl.onresize=function(){if(dimensionsChanged(_this,_this._dummyEl)){_this.dimensions.width=_this._dummyEl.videoWidth;_this.dimensions.height=_this._dummyEl.videoHeight;if(_this.isStarted){_this._log.debug("Dimensions changed:",_this.dimensions);_this.emit(VideoTrack.DIMENSIONS_CHANGED,_this)}}}}};VideoTrack.prototype._restartProcessor=function(){var processor=this.processor;if(processor){this.removeProcessor(processor);this.addProcessor(processor)}};VideoTrack.prototype._start=function(dummyEl){this.dimensions.width=dummyEl.videoWidth;this.dimensions.height=dummyEl.videoHeight;this._log.debug("Dimensions:",this.dimensions);this.emit(VideoTrack.DIMENSIONS_CHANGED,this);return _super.prototype._start.call(this,dummyEl)};VideoTrack.prototype.addProcessor=function(processor){var _this=this;if(typeof OffscreenCanvas!=="function"){return this._log.warn("Adding a VideoProcessor is not supported in this browser.")}if(!processor||typeof processor.processFrame!=="function"){throw new Error("Received an invalid VideoProcessor from addProcessor.")}if(this.processor){throw new Error("A VideoProcessor has already been added.")}if(!this._dummyEl){throw new Error("VideoTrack has not been initialized.")}this._log.debug("Adding VideoProcessor to the VideoTrack",processor);if(!this._unmuteHandler){this._unmuteHandler=function(){_this._log.debug("mediaStreamTrack unmuted");if(_this.processedTrack.muted){_this._log.debug("mediaStreamTrack is unmuted but processedTrack is muted. Restarting processor.");_this._restartProcessor()}};this.mediaStreamTrack.addEventListener("unmute",this._unmuteHandler)}var _a=this.mediaStreamTrack.getSettings(),_b=_a.width,width=_b===void 0?0:_b,_c=_a.height,height=_c===void 0?0:_c,_d=_a.frameRate,frameRate=_d===void 0?DEFAULT_FRAME_RATE:_d;this._inputFrame=new OffscreenCanvas(width,height);this._outputFrame=document.createElement("canvas");this._outputFrame.width=width;this._outputFrame.height=height;this.processedTrack=this._outputFrame.captureStream(0).getTracks()[0];this.processedTrack.enabled=this.mediaStreamTrack.enabled;this.processor=processor;this._processorEventObserver.emit("add",{processor:processor,captureHeight:height,captureWidth:width,inputFrameRate:frameRate,isRemoteVideoTrack:this.toString().includes("RemoteVideoTrack")});this._updateElementsMediaStreamTrack();this._captureFrames();return this};VideoTrack.prototype.attach=function(){var result=_super.prototype.attach.apply(this,arguments);if(this.processor){this._captureFrames()}return result};VideoTrack.prototype.detach=function(){return _super.prototype.detach.apply(this,arguments)};VideoTrack.prototype.removeProcessor=function(processor){if(!processor){throw new Error("Received an invalid VideoProcessor from removeProcessor.")}if(!this.processor){throw new Error("No existing VideoProcessor detected.")}if(processor!==this.processor){throw new Error("The provided VideoProcessor is different than the existing one.")}this._processorEventObserver.emit("remove");this._log.debug("Removing VideoProcessor from the VideoTrack",processor);clearTimeout(this._captureTimeoutId);this.mediaStreamTrack.removeEventListener("unmute",this._unmuteHandler);this._unmuteHandler=null;this._isCapturing=false;this.processor=null;this.processedTrack=null;this._inputFrame.getContext("2d").clearRect(0,0,this._inputFrame.width,this._inputFrame.height);this._outputFrame.getContext("2d").clearRect(0,0,this._outputFrame.width,this._outputFrame.height);this._inputFrame=null;this._outputFrame=null;this._updateElementsMediaStreamTrack();return this};return VideoTrack}(MediaTrack);VideoTrack.DIMENSIONS_CHANGED="dimensionsChanged";function dimensionsChanged(track,elem){return track.dimensions.width!==elem.videoWidth||track.dimensions.height!==elem.videoHeight}module.exports=VideoTrack},{"../../util/constants":124,"./mediatrack":27,"./videoprocessoreventobserver":41}],43:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var EventEmitter=require("events").EventEmitter;var _a=require("./util/constants"),DEFAULT_NQ_LEVEL_LOCAL=_a.DEFAULT_NQ_LEVEL_LOCAL,DEFAULT_NQ_LEVEL_REMOTE=_a.DEFAULT_NQ_LEVEL_REMOTE,MAX_NQ_LEVEL=_a.MAX_NQ_LEVEL;var inRange=require("./util").inRange;var NetworkQualityConfigurationImpl=function(_super){__extends(NetworkQualityConfigurationImpl,_super);function NetworkQualityConfigurationImpl(networkQualityConfiguration){var _this=_super.call(this)||this;networkQualityConfiguration=Object.assign({local:DEFAULT_NQ_LEVEL_LOCAL,remote:DEFAULT_NQ_LEVEL_REMOTE},networkQualityConfiguration);Object.defineProperties(_this,{local:{value:inRange(networkQualityConfiguration.local,DEFAULT_NQ_LEVEL_LOCAL,MAX_NQ_LEVEL)?networkQualityConfiguration.local:DEFAULT_NQ_LEVEL_LOCAL,writable:true},remote:{value:inRange(networkQualityConfiguration.remote,DEFAULT_NQ_LEVEL_REMOTE,MAX_NQ_LEVEL)?networkQualityConfiguration.remote:DEFAULT_NQ_LEVEL_REMOTE,writable:true}});return _this}NetworkQualityConfigurationImpl.prototype.update=function(networkQualityConfiguration){var _this=this;networkQualityConfiguration=Object.assign({local:this.local,remote:this.remote},networkQualityConfiguration);[["local",DEFAULT_NQ_LEVEL_LOCAL,3],["remote",DEFAULT_NQ_LEVEL_REMOTE,3]].forEach(function(_a){var _b=__read(_a,3),localOrRemote=_b[0],min=_b[1],max=_b[2];_this[localOrRemote]=typeof networkQualityConfiguration[localOrRemote]==="number"&&inRange(networkQualityConfiguration[localOrRemote],min,max)?networkQualityConfiguration[localOrRemote]:min})};return NetworkQualityConfigurationImpl}(EventEmitter);module.exports=NetworkQualityConfigurationImpl},{"./util":131,"./util/constants":124,events:173}],44:[function(require,module,exports){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};Object.defineProperty(exports,"__esModule",{value:true});exports.createNoiseCancellationAudioProcessor=void 0;var dynamicImport=require("./util/dynamicimport");var Log=require("./util/log");var PLUGIN_CONFIG={krisp:{supportedVersion:"1.0.0",pluginFile:"krispsdk.mjs"},rnnoise:{supportedVersion:"0.6.0",pluginFile:"rnnoise_sdk.mjs"}};var ensureVersionSupported=function(_a){var supportedVersion=_a.supportedVersion,plugin=_a.plugin,log=_a.log;if(!plugin.getVersion||!plugin.isSupported){throw new Error("Plugin does not export getVersion/isSupported api. Are you using old version of the plugin ?")}var pluginVersion=plugin.getVersion();log.debug("Plugin Version = "+pluginVersion);var supportedVersions=supportedVersion.split(".").map(function(version){return Number(version)});var pluginVersions=pluginVersion.split(".").map(function(version){return Number(version)});if(supportedVersions.length!==3||pluginVersions.length!==3){throw new Error("Unsupported Plugin version format: "+supportedVersion+", "+pluginVersion)}if(supportedVersions[0]!==pluginVersions[0]){throw new Error("Major version mismatch: [Plugin version "+pluginVersion+"], [Supported Version "+supportedVersion+"]")}if(pluginVersions[1]<supportedVersions[1]){throw new Error("Minor version mismatch: [Plugin version "+pluginVersion+"] < [Supported Version "+supportedVersion+"]")}var tempContext=new AudioContext;var isSupported=plugin.isSupported(tempContext);tempContext.close();if(!isSupported){throw new Error("Noise Cancellation plugin is not supported on your browser")}};var audioProcessors=new Map;function createNoiseCancellationAudioProcessor(noiseCancellationOptions,log){return __awaiter(this,void 0,void 0,function(){var audioProcessor,pluginConfig,supportedVersion,pluginFile,rootDir,sdkFilePath,dynamicModule,plugin_1,er_1;return __generator(this,function(_a){switch(_a.label){case 0:audioProcessor=audioProcessors.get(noiseCancellationOptions.vendor);if(!!audioProcessor)return[3,6];pluginConfig=PLUGIN_CONFIG[noiseCancellationOptions.vendor];if(!pluginConfig){throw new Error("Unsupported NoiseCancellationOptions.vendor: "+noiseCancellationOptions.vendor)}supportedVersion=pluginConfig.supportedVersion,pluginFile=pluginConfig.pluginFile;rootDir=noiseCancellationOptions.sdkAssetsPath;sdkFilePath=rootDir+"/"+pluginFile;_a.label=1;case 1:_a.trys.push([1,5,,6]);log.debug("loading noise cancellation sdk: ",sdkFilePath);return[4,dynamicImport(sdkFilePath)];case 2:dynamicModule=_a.sent();log.debug("Loaded noise cancellation sdk:",dynamicModule);plugin_1=dynamicModule.default;ensureVersionSupported({supportedVersion:supportedVersion,plugin:plugin_1,log:log});if(!!plugin_1.isInitialized())return[3,4];log.debug("initializing noise cancellation sdk: ",rootDir);return[4,plugin_1.init({rootDir:rootDir})];case 3:_a.sent();log.debug("noise cancellation sdk initialized!");_a.label=4;case 4:audioProcessor={vendor:noiseCancellationOptions.vendor,isInitialized:function(){return plugin_1.isInitialized()},isConnected:function(){return plugin_1.isConnected()},isEnabled:function(){return plugin_1.isEnabled()},disconnect:function(){return plugin_1.disconnect()},enable:function(){return plugin_1.enable()},disable:function(){return plugin_1.disable()},destroy:function(){return plugin_1.destroy()},setLogging:function(enable){return plugin_1.setLogging(enable)},connect:function(sourceTrack){log.debug("connect: ",sourceTrack.id);if(plugin_1.isConnected()){plugin_1.disconnect()}var mediaStream=plugin_1.connect(new MediaStream([sourceTrack]));if(!mediaStream){throw new Error("Error connecting with noise cancellation sdk")}var cleanTrack=mediaStream.getAudioTracks()[0];if(!cleanTrack){throw new Error("Error getting clean track from noise cancellation sdk")}plugin_1.enable();return cleanTrack}};audioProcessors.set(noiseCancellationOptions.vendor,audioProcessor);return[3,6];case 5:er_1=_a.sent();log.error("Error loading noise cancellation sdk:"+sdkFilePath,er_1);throw er_1;case 6:return[2,audioProcessor]}})})}exports.createNoiseCancellationAudioProcessor=createNoiseCancellationAudioProcessor},{"./util/dynamicimport":128,"./util/log":135}],45:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var __spreadArray=this&&this.__spreadArray||function(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to};var EventEmitter=require("./eventemitter");var RemoteAudioTrack=require("./media/track/remoteaudiotrack");var RemoteAudioTrackPublication=require("./media/track/remoteaudiotrackpublication");var RemoteDataTrack=require("./media/track/remotedatatrack");var RemoteDataTrackPublication=require("./media/track/remotedatatrackpublication");var RemoteVideoTrack=require("./media/track/remotevideotrack");var RemoteVideoTrackPublication=require("./media/track/remotevideotrackpublication");var util=require("./util");var nInstances=0;var Participant=function(_super){__extends(Participant,_super);function Participant(signaling,options){var _this=_super.call(this)||this;options=Object.assign({RemoteAudioTrack:RemoteAudioTrack,RemoteAudioTrackPublication:RemoteAudioTrackPublication,RemoteDataTrack:RemoteDataTrack,RemoteDataTrackPublication:RemoteDataTrackPublication,RemoteVideoTrack:RemoteVideoTrack,RemoteVideoTrackPublication:RemoteVideoTrackPublication,tracks:[]},options);var indexed=indexTracksById(options.tracks);var log=options.log.createLog("default",_this);var audioTracks=new Map(indexed.audioTracks);var dataTracks=new Map(indexed.dataTracks);var tracks=new Map(indexed.tracks);var videoTracks=new Map(indexed.videoTracks);Object.defineProperties(_this,{_RemoteAudioTrack:{value:options.RemoteAudioTrack},_RemoteAudioTrackPublication:{value:options.RemoteAudioTrackPublication},_RemoteDataTrack:{value:options.RemoteDataTrack},_RemoteDataTrackPublication:{value:options.RemoteDataTrackPublication},_RemoteVideoTrack:{value:options.RemoteVideoTrack},_RemoteVideoTrackPublication:{value:options.RemoteVideoTrackPublication},_audioTracks:{value:audioTracks},_dataTracks:{value:dataTracks},_instanceId:{value:++nInstances},_clientTrackSwitchOffControl:{value:options.clientTrackSwitchOffControl},_contentPreferencesMode:{value:options.contentPreferencesMode},_log:{value:log},_signaling:{value:signaling},_tracks:{value:tracks},_trackEventReemitters:{value:new Map},_trackPublicationEventReemitters:{value:new Map},_trackSignalingUpdatedEventCallbacks:{value:new Map},_videoTracks:{value:videoTracks},audioTracks:{enumerable:true,value:new Map},dataTracks:{enumerable:true,value:new Map},identity:{enumerable:true,get:function(){return signaling.identity}},networkQualityLevel:{enumerable:true,get:function(){return signaling.networkQualityLevel}},networkQualityStats:{enumerable:true,get:function(){return signaling.networkQualityStats}},sid:{enumerable:true,get:function(){return signaling.sid}},state:{enumerable:true,get:function(){return signaling.state}},tracks:{enumerable:true,value:new Map},videoTracks:{enumerable:true,value:new Map}});_this._tracks.forEach(reemitTrackEvents.bind(null,_this));signaling.on("networkQualityLevelChanged",function(){return _this.emit("networkQualityLevelChanged",_this.networkQualityLevel,_this.networkQualityStats&&(_this.networkQualityStats.audio||_this.networkQualityStats.video)?_this.networkQualityStats:null)});reemitSignalingStateChangedEvents(_this,signaling);log.info("Created a new Participant"+(_this.identity?": "+_this.identity:""));return _this}Participant.prototype._getTrackEvents=function(){return[["dimensionsChanged","trackDimensionsChanged"],["message","trackMessage"],["started","trackStarted"]]};Participant.prototype._getTrackPublicationEvents=function(){return[]};Participant.prototype.toString=function(){return"[Participant #"+this._instanceId+": "+this.sid+"]"};Participant.prototype._addTrack=function(track,id){var log=this._log;if(this._tracks.has(id)){return null}this._tracks.set(id,track);var tracksByKind={audio:this._audioTracks,video:this._videoTracks,data:this._dataTracks}[track.kind];tracksByKind.set(id,track);reemitTrackEvents(this,track,id);log.info("Added a new "+util.trackClass(track)+":",id);log.debug(util.trackClass(track)+":",track);return track};Participant.prototype._addTrackPublication=function(publication){var log=this._log;if(this.tracks.has(publication.trackSid)){return null}this.tracks.set(publication.trackSid,publication);var trackPublicationsByKind={audio:this.audioTracks,data:this.dataTracks,video:this.videoTracks}[publication.kind];trackPublicationsByKind.set(publication.trackSid,publication);reemitTrackPublicationEvents(this,publication);log.info("Added a new "+util.trackPublicationClass(publication)+":",publication.trackSid);log.debug(util.trackPublicationClass(publication)+":",publication);return publication};Participant.prototype._handleTrackSignalingEvents=function(){var _a=this,log=_a._log,clientTrackSwitchOffControl=_a._clientTrackSwitchOffControl,contentPreferencesMode=_a._contentPreferencesMode;var self=this;if(this.state==="disconnected"){return}var RemoteAudioTrack=this._RemoteAudioTrack;var RemoteAudioTrackPublication=this._RemoteAudioTrackPublication;var RemoteVideoTrack=this._RemoteVideoTrack;var RemoteVideoTrackPublication=this._RemoteVideoTrackPublication;var RemoteDataTrack=this._RemoteDataTrack;var RemoteDataTrackPublication=this._RemoteDataTrackPublication;var participantSignaling=this._signaling;function trackSignalingAdded(signaling){var RemoteTrackPublication={audio:RemoteAudioTrackPublication,data:RemoteDataTrackPublication,video:RemoteVideoTrackPublication}[signaling.kind];var publication=new RemoteTrackPublication(signaling,{log:log});self._addTrackPublication(publication);var isSubscribed=signaling.isSubscribed;if(isSubscribed){trackSignalingSubscribed(signaling)}self._trackSignalingUpdatedEventCallbacks.set(signaling.sid,function(){if(isSubscribed!==signaling.isSubscribed){isSubscribed=signaling.isSubscribed;if(isSubscribed){trackSignalingSubscribed(signaling);return}trackSignalingUnsubscribed(signaling)}});signaling.on("updated",self._trackSignalingUpdatedEventCallbacks.get(signaling.sid))}function trackSignalingRemoved(signaling){if(signaling.isSubscribed){signaling.setTrackTransceiver(null)}var updated=self._trackSignalingUpdatedEventCallbacks.get(signaling.sid);if(updated){signaling.removeListener("updated",updated);self._trackSignalingUpdatedEventCallbacks.delete(signaling.sid)}var publication=self.tracks.get(signaling.sid);if(publication){self._removeTrackPublication(publication)}}function trackSignalingSubscribed(signaling){var isEnabled=signaling.isEnabled,name=signaling.name,kind=signaling.kind,sid=signaling.sid,trackTransceiver=signaling.trackTransceiver,isSwitchedOff=signaling.isSwitchedOff;var RemoteTrack={audio:RemoteAudioTrack,video:RemoteVideoTrack,data:RemoteDataTrack}[kind];var publication=self.tracks.get(sid);if(!RemoteTrack||kind!==trackTransceiver.kind){return}var options={log:log,name:name,clientTrackSwitchOffControl:clientTrackSwitchOffControl,contentPreferencesMode:contentPreferencesMode};var setPriority=function(newPriority){return participantSignaling.updateSubscriberTrackPriority(sid,newPriority)};var setRenderHint=function(renderHint){if(signaling.isSubscribed){participantSignaling.updateTrackRenderHint(sid,renderHint)}};var track=kind==="data"?new RemoteTrack(sid,trackTransceiver,options):new RemoteTrack(sid,trackTransceiver,isEnabled,isSwitchedOff,setPriority,setRenderHint,options);self._addTrack(track,publication,trackTransceiver.id)}function trackSignalingUnsubscribed(signaling){var _a=__read(Array.from(self._tracks.entries()).find(function(_a){var _b=__read(_a,2),track=_b[1];return track.sid===signaling.sid}),2),id=_a[0],track=_a[1];var publication=self.tracks.get(signaling.sid);if(track){self._removeTrack(track,publication,id)}}participantSignaling.on("trackAdded",trackSignalingAdded);participantSignaling.on("trackRemoved",trackSignalingRemoved);participantSignaling.tracks.forEach(trackSignalingAdded);participantSignaling.on("stateChanged",function stateChanged(state){if(state==="disconnected"){log.debug("Removing event listeners");participantSignaling.removeListener("stateChanged",stateChanged);participantSignaling.removeListener("trackAdded",trackSignalingAdded);participantSignaling.removeListener("trackRemoved",trackSignalingRemoved)}else if(state==="connected"){log.info("reconnected");setTimeout(function(){return self.emit("reconnected")},0)}})};Participant.prototype._removeTrack=function(track,id){if(!this._tracks.has(id)){return null}this._tracks.delete(id);var tracksByKind={audio:this._audioTracks,video:this._videoTracks,data:this._dataTracks}[track.kind];tracksByKind.delete(id);var reemitters=this._trackEventReemitters.get(id)||new Map;reemitters.forEach(function(reemitter,event){track.removeListener(event,reemitter)});var log=this._log;log.info("Removed a "+util.trackClass(track)+":",id);log.debug(util.trackClass(track)+":",track);return track};Participant.prototype._removeTrackPublication=function(publication){publication=this.tracks.get(publication.trackSid);if(!publication){return null}this.tracks.delete(publication.trackSid);var trackPublicationsByKind={audio:this.audioTracks,data:this.dataTracks,video:this.videoTracks}[publication.kind];trackPublicationsByKind.delete(publication.trackSid);var reemitters=this._trackPublicationEventReemitters.get(publication.trackSid)||new Map;reemitters.forEach(function(reemitter,event){publication.removeListener(event,reemitter)});var log=this._log;log.info("Removed a "+util.trackPublicationClass(publication)+":",publication.trackSid);log.debug(util.trackPublicationClass(publication)+":",publication);return publication};Participant.prototype.toJSON=function(){return util.valueToJSON(this)};return Participant}(EventEmitter);function indexTracksById(tracks){var indexedTracks=tracks.map(function(track){return[track.id,track]});var indexedAudioTracks=indexedTracks.filter(function(keyValue){return keyValue[1].kind==="audio"});var indexedVideoTracks=indexedTracks.filter(function(keyValue){return keyValue[1].kind==="video"});var indexedDataTracks=indexedTracks.filter(function(keyValue){return keyValue[1].kind==="data"});return{audioTracks:indexedAudioTracks,dataTracks:indexedDataTracks,tracks:indexedTracks,videoTracks:indexedVideoTracks}}function reemitSignalingStateChangedEvents(participant,signaling){var log=participant._log;if(participant.state==="disconnected"){return}signaling.on("stateChanged",function stateChanged(state){log.debug("Transitioned to state:",state);participant.emit(state,participant);if(state==="disconnected"){log.debug("Removing Track event reemitters");signaling.removeListener("stateChanged",stateChanged);participant._tracks.forEach(function(track){var reemitters=participant._trackEventReemitters.get(track.id);if(track&&reemitters){reemitters.forEach(function(reemitter,event){track.removeListener(event,reemitter)})}});signaling.tracks.forEach(function(trackSignaling){var track=participant._tracks.get(trackSignaling.id);var reemitters=participant._trackEventReemitters.get(trackSignaling.id);if(track&&reemitters){reemitters.forEach(function(reemitter,event){track.removeListener(event,reemitter)})}});participant._trackEventReemitters.clear();participant.tracks.forEach(function(publication){participant._trackPublicationEventReemitters.get(publication.trackSid).forEach(function(reemitter,event){publication.removeListener(event,reemitter)})});participant._trackPublicationEventReemitters.clear()}})}function reemitTrackEvents(participant,track,id){var trackEventReemitters=new Map;if(participant.state==="disconnected"){return}participant._getTrackEvents().forEach(function(eventPair){var trackEvent=eventPair[0];var participantEvent=eventPair[1];trackEventReemitters.set(trackEvent,function(){var args=[participantEvent].concat([].slice.call(arguments));return participant.emit.apply(participant,__spreadArray([],__read(args)))});track.on(trackEvent,trackEventReemitters.get(trackEvent))});participant._trackEventReemitters.set(id,trackEventReemitters)}function reemitTrackPublicationEvents(participant,publication){var publicationEventReemitters=new Map;if(participant.state==="disconnected"){return}participant._getTrackPublicationEvents().forEach(function(_a){var _b=__read(_a,2),publicationEvent=_b[0],participantEvent=_b[1];publicationEventReemitters.set(publicationEvent,function(){var args=[];for(var _i=0;_i<arguments.length;_i++){args[_i]=arguments[_i]}participant.emit.apply(participant,__spreadArray(__spreadArray([participantEvent],__read(args)),[publication]))});publication.on(publicationEvent,publicationEventReemitters.get(publicationEvent))});participant._trackPublicationEventReemitters.set(publication.trackSid,publicationEventReemitters)}module.exports=Participant},{"./eventemitter":10,"./media/track/remoteaudiotrack":30,"./media/track/remoteaudiotrackpublication":31,"./media/track/remotedatatrack":32,"./media/track/remotedatatrackpublication":33,"./media/track/remotevideotrack":36,"./media/track/remotevideotrackpublication":37,"./util":131}],46:[function(require,module,exports){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};Object.defineProperty(exports,"__esModule",{value:true});exports.getCombinedConnectionStats=void 0;function getStatValues(report,statName,kind,reportTypes){var results=[];report.forEach(function(stat){if((reportTypes.length===0||reportTypes.includes(stat.type))&&(kind.length===0||kind.includes(stat.kind))&&typeof stat[statName]==="number"){results.push(stat[statName])}});return results}function getCombinedConnectionStats(_a){var publisher=_a.publisher,subscriber=_a.subscriber;return __awaiter(this,void 0,void 0,function(){var _b,publisherStats,subscriberStats,timestamps,timestamp,jitter,packets,packetsLost,trackRoundTripTime,currentRoundTripTime,roundTripTime,bytesSent,bytesReceived,selectedIceCandidatePairStats,iceCandidateStats;return __generator(this,function(_c){switch(_c.label){case 0:
43
- return[4,Promise.all([publisher,subscriber].map(function(pc){return pc.getStats()}))];case 1:_b=__read.apply(void 0,[_c.sent(),2]),publisherStats=_b[0],subscriberStats=_b[1];timestamps=getStatValues(subscriberStats,"timestamp",["audio"],["inbound-rtp"]);timestamp=timestamps.length>0?timestamps[0]:0;jitter=getStatValues(subscriberStats,"jitter",["audio"],["inbound-rtp"]).reduce(function(a,b){return Math.max(a,b)},0);packets=getStatValues(subscriberStats,"packetsReceived",["audio","video"],["inbound-rtp"]).reduce(function(a,b){return a+b},0);packetsLost=getStatValues(subscriberStats,"packetsLost",["audio","video"],["inbound-rtp"]).reduce(function(a,b){return a+b},0);trackRoundTripTime=getStatValues(publisherStats,"roundTripTime",["audio","video"],["remote-inbound-rtp"]).reduce(function(a,b){return Math.max(a,b)},0);currentRoundTripTime=getStatValues(subscriberStats,"currentRoundTripTime",[],["candidate-pair"]).reduce(function(a,b){return Math.max(a,b)},0);roundTripTime=(currentRoundTripTime||trackRoundTripTime)*1e3;bytesSent=getStatValues(publisherStats,"bytesSent",[],["candidate-pair"]).reduce(function(a,b){return a+b},0);bytesReceived=getStatValues(subscriberStats,"bytesReceived",[],["candidate-pair"]).reduce(function(a,b){return a+b},0);selectedIceCandidatePairStats=extractSelectedActiveCandidatePair(subscriberStats);iceCandidateStats=[];subscriberStats.forEach(function(stat){if(stat.type==="local-candidate"||stat.type==="remote-candidate"){iceCandidateStats.push(makeStandardCandidateStats(stat))}});return[2,{timestamp:timestamp,jitter:jitter,packets:packets,packetsLost:packetsLost,roundTripTime:roundTripTime,bytesSent:bytesSent,bytesReceived:bytesReceived,selectedIceCandidatePairStats:selectedIceCandidatePairStats,iceCandidateStats:iceCandidateStats}]}})})}exports.getCombinedConnectionStats=getCombinedConnectionStats;function makeStandardCandidateStats(input){var standardizedCandidateStatsKeys=[{key:"transportId",type:"string"},{key:"candidateType",type:"string"},{key:"port",altKeys:["portNumber"],type:"number"},{key:"address",altKeys:["ip","ipAddress"],type:"string"},{key:"priority",type:"number"},{key:"protocol",altKeys:["transport"],type:"string"},{key:"url",type:"string"},{key:"relayProtocol",type:"string"}];return standardizedCandidateStatsKeys.reduce(function(report,keyInfo){var keysToLookFor=[keyInfo.key];if(keyInfo.altKeys){keysToLookFor=keysToLookFor.concat(keyInfo.altKeys)}var key=keysToLookFor.find(function(key){return key in input});if(key&&typeof input[key]===keyInfo.type){report[keyInfo.key]=input[key]}return report},{})}function extractSelectedActiveCandidatePair(stats){var selectedCandidatePairId=null;var candidatePairs=[];stats.forEach(function(stat){if(stat.type==="transport"&&stat.selectedCandidatePairId){selectedCandidatePairId=stat.selectedCandidatePairId}else if(stat.type==="candidate-pair"){candidatePairs.push(stat)}});var activeCandidatePairStatsFound=candidatePairs.find(function(pair){return pair.selected||selectedCandidatePairId&&pair.id===selectedCandidatePairId});if(!activeCandidatePairStatsFound){return null}var activeCandidatePairStats=activeCandidatePairStatsFound;var activeLocalCandidateStats=stats.get(activeCandidatePairStats.localCandidateId);var activeRemoteCandidateStats=stats.get(activeCandidatePairStats.remoteCandidateId);if(!activeLocalCandidateStats||!activeRemoteCandidateStats){return null}return{localCandidate:makeStandardCandidateStats(activeLocalCandidateStats),remoteCandidate:makeStandardCandidateStats(activeRemoteCandidateStats)}}},{}],47:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.getTurnCredentials=void 0;var TwilioConnection=require("../twilioconnection.js");var ICE_VERSION=require("../util/constants").ICE_VERSION;var _a=require("../util/twilio-video-errors"),createTwilioError=_a.createTwilioError,SignalingConnectionError=_a.SignalingConnectionError;var events_1=require("events");function getTurnCredentials(token,wsServer){return new Promise(function(resolve,reject){var eventObserver=new events_1.EventEmitter;var connectionOptions={networkMonitor:null,eventObserver:eventObserver,helloBody:{edge:"roaming",preflight:true,token:token,type:"ice",version:ICE_VERSION}};var twilioConnection=new TwilioConnection(wsServer,connectionOptions);var done=false;twilioConnection.once("close",function(){if(!done){done=true;reject(new SignalingConnectionError)}});twilioConnection.on("message",function(messageData){var code=messageData.code,message=messageData.message,ice_servers=messageData.ice_servers,type=messageData.type;if((type==="iced"||type==="error")&&!done){done=true;if(type==="iced"){resolve(ice_servers)}else{reject(createTwilioError(code,message))}twilioConnection.close()}})})}exports.getTurnCredentials=getTurnCredentials},{"../twilioconnection.js":119,"../util/constants":124,"../util/twilio-video-errors":146,events:173}],48:[function(require,module,exports){"use strict";var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var __spreadArray=this&&this.__spreadArray||function(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to};Object.defineProperty(exports,"__esModule",{value:true});exports.makeStat=void 0;function makeStat(values){if(values&&values.length){var min=Math.min.apply(Math,__spreadArray([],__read(values)));var max=Math.max.apply(Math,__spreadArray([],__read(values)));var average=values.reduce(function(total,value){return total+value},0)/values.length;return{min:min,max:max,average:average}}return null}exports.makeStat=makeStat},{}],49:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.mosToScore=exports.calculateMOS=void 0;var r0=94.768;function calculateMOS(rtt,jitter,fractionLost){var effectiveLatency=rtt+jitter*2+10;var rFactor=0;switch(true){case effectiveLatency<160:rFactor=r0-effectiveLatency/40;break;case effectiveLatency<1e3:rFactor=r0-(effectiveLatency-120)/10;break}switch(true){case fractionLost<=rFactor/2.5:rFactor=Math.max(rFactor-fractionLost*2.5,6.52);break;default:rFactor=0;break}var mos=1+.035*rFactor+7e-6*rFactor*(rFactor-60)*(100-rFactor);return mos}exports.calculateMOS=calculateMOS;function mosToScore(mosValue){var score=0;if(!mosValue){score=0}else if(mosValue>4.2){score=5}else if(mosValue>4){score=4}else if(mosValue>3.6){score=3}else if(mosValue>3){score=2}else{score=1}return score}exports.mosToScore=mosToScore},{}],50:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __assign=this&&this.__assign||function(){__assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++){s=arguments[i];for(var p in s)if(Object.prototype.hasOwnProperty.call(s,p))t[p]=s[p]}return t};return __assign.apply(this,arguments)};var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};Object.defineProperty(exports,"__esModule",{value:true});exports.runPreflight=exports.PreflightTest=void 0;var constants_1=require("../util/constants");var timer_1=require("./timer");var mos_1=require("./mos");var getCombinedConnectionStats_1=require("./getCombinedConnectionStats");var getturncredentials_1=require("./getturncredentials");var makestat_1=require("./makestat");var syntheticaudio_1=require("./syntheticaudio");var syntheticvideo_1=require("./syntheticvideo");var index_1=require("../util/index");var WS_SERVER=require("../util/constants").WS_SERVER;var Log=require("../util/log");var EventEmitter=require("../eventemitter");var MovingAverageDelta=require("../util/movingaveragedelta");var EventObserver=require("../util/eventobserver");var InsightsPublisher=require("../util/insightspublisher");var _a=require("../util/sid"),createSID=_a.createSID,sessionSID=_a.sessionSID;var _b=require("../util/twilio-video-errors"),SignalingConnectionTimeoutError=_b.SignalingConnectionTimeoutError,MediaConnectionError=_b.MediaConnectionError;var SECOND=1e3;var DEFAULT_TEST_DURATION=10*SECOND;var PreflightProgress={mediaAcquired:"mediaAcquired",connected:"connected",mediaSubscribed:"mediaSubscribed",mediaStarted:"mediaStarted",dtlsConnected:"dtlsConnected",peerConnectionConnected:"peerConnectionConnected",iceConnected:"iceConnected"};function notEmpty(value){return value!==null&&typeof value!=="undefined"}var nInstances=0;var PreflightTest=function(_super){__extends(PreflightTest,_super);function PreflightTest(token,options){var _this=_super.call(this)||this;_this._testTiming=new timer_1.Timer;_this._dtlsTiming=new timer_1.Timer;_this._iceTiming=new timer_1.Timer;_this._peerConnectionTiming=new timer_1.Timer;_this._mediaTiming=new timer_1.Timer;_this._connectTiming=new timer_1.Timer;_this._sentBytesMovingAverage=new MovingAverageDelta;_this._packetLossMovingAverage=new MovingAverageDelta;_this._progressEvents=[];_this._receivedBytesMovingAverage=new MovingAverageDelta;var internalOptions=options;var _a=internalOptions.environment,environment=_a===void 0?"prod":_a,_b=internalOptions.region,region=_b===void 0?"gll":_b,_c=internalOptions.duration,duration=_c===void 0?DEFAULT_TEST_DURATION:_c;var wsServer=internalOptions.wsServer||WS_SERVER(environment,region);_this._log=new Log("default",_this,constants_1.DEFAULT_LOG_LEVEL,constants_1.DEFAULT_LOGGER_NAME);_this._testDuration=duration;_this._instanceId=nInstances++;_this._testTiming.start();_this._runPreflightTest(token,environment,wsServer);return _this}PreflightTest.prototype.toString=function(){return"[Preflight #"+this._instanceId+"]"};PreflightTest.prototype.stop=function(){this._stopped=true};PreflightTest.prototype._generatePreflightReport=function(collectedStats){this._testTiming.stop();return{testTiming:this._testTiming.getTimeMeasurement(),networkTiming:{dtls:this._dtlsTiming.getTimeMeasurement(),ice:this._iceTiming.getTimeMeasurement(),peerConnection:this._peerConnectionTiming.getTimeMeasurement(),connect:this._connectTiming.getTimeMeasurement(),media:this._mediaTiming.getTimeMeasurement()},stats:{jitter:makestat_1.makeStat(collectedStats===null||collectedStats===void 0?void 0:collectedStats.jitter),rtt:makestat_1.makeStat(collectedStats===null||collectedStats===void 0?void 0:collectedStats.rtt),packetLoss:makestat_1.makeStat(collectedStats===null||collectedStats===void 0?void 0:collectedStats.packetLoss)},selectedIceCandidatePairStats:collectedStats?collectedStats.selectedIceCandidatePairStats:null,iceCandidateStats:collectedStats?collectedStats.iceCandidateStats:[],progressEvents:this._progressEvents,mos:makestat_1.makeStat(collectedStats===null||collectedStats===void 0?void 0:collectedStats.mos)}};PreflightTest.prototype._executePreflightStep=function(stepName,step,timeoutError){return __awaiter(this,void 0,void 0,function(){var MAX_STEP_DURATION,stepPromise,timer,timeoutPromise,result;return __generator(this,function(_a){switch(_a.label){case 0:this._log.debug("Executing step: ",stepName);MAX_STEP_DURATION=this._testDuration+10*SECOND;if(this._stopped){throw new Error("stopped")}stepPromise=Promise.resolve().then(step);timer=null;timeoutPromise=new Promise(function(_resolve,reject){timer=setTimeout(function(){reject(timeoutError||new Error(stepName+" timeout."))},MAX_STEP_DURATION)});_a.label=1;case 1:_a.trys.push([1,,3,4]);return[4,Promise.race([timeoutPromise,stepPromise])];case 2:result=_a.sent();return[2,result];case 3:if(timer!==null){clearTimeout(timer)}return[7];case 4:return[2]}})})};PreflightTest.prototype._collectNetworkTimings=function(pc){var _this=this;return new Promise(function(resolve){var dtlsTransport;pc.addEventListener("iceconnectionstatechange",function(){if(pc.iceConnectionState==="checking"){_this._iceTiming.start()}if(pc.iceConnectionState==="connected"){_this._iceTiming.stop();_this._updateProgress(PreflightProgress.iceConnected);if(!dtlsTransport||dtlsTransport&&dtlsTransport.state==="connected"){resolve()}}});pc.addEventListener("connectionstatechange",function(){if(pc.connectionState==="connecting"){_this._peerConnectionTiming.start()}if(pc.connectionState==="connected"){_this._peerConnectionTiming.stop();_this._updateProgress(PreflightProgress.peerConnectionConnected)}});var senders=pc.getSenders();var transport=senders.map(function(sender){return sender.transport}).find(notEmpty);if(typeof transport!=="undefined"){dtlsTransport=transport;dtlsTransport.addEventListener("statechange",function(){if(dtlsTransport.state==="connecting"){_this._dtlsTiming.start()}if(dtlsTransport.state==="connected"){_this._dtlsTiming.stop();_this._updateProgress(PreflightProgress.dtlsConnected);if(pc.iceConnectionState==="connected"){resolve()}}})}})};PreflightTest.prototype._setupInsights=function(_a){var token=_a.token,_b=_a.environment,environment=_b===void 0?constants_1.DEFAULT_ENVIRONMENT:_b,_c=_a.realm,realm=_c===void 0?constants_1.DEFAULT_REALM:_c;var eventPublisherOptions={};var eventPublisher=new InsightsPublisher(token,constants_1.SDK_NAME,constants_1.SDK_VERSION,environment,realm,eventPublisherOptions);eventPublisher.connect("PREFLIGHT_ROOM_SID","PREFLIGHT_PARTICIPANT");var eventObserver=new EventObserver(eventPublisher,Date.now(),this._log);var undefinedValue=undefined;return{reportToInsights:function(_a){var _b,_c;var report=_a.report;var jitterStats=report.stats.jitter||undefinedValue;var rttStats=report.stats.rtt||undefinedValue;var packetLossStats=report.stats.packetLoss||undefinedValue;var mosStats=report.mos||undefinedValue;var candidateTypeToProtocols=new Map;report.iceCandidateStats.forEach(function(candidateStats){if(candidateStats.candidateType&&candidateStats.protocol){var protocols=candidateTypeToProtocols.get(candidateStats.candidateType)||[];if(protocols.indexOf(candidateStats.protocol)<0){protocols.push(candidateStats.protocol)}candidateTypeToProtocols.set(candidateStats.candidateType,protocols)}});var iceCandidateStats=JSON.stringify(Object.fromEntries(candidateTypeToProtocols));var insightsReport={name:"report",group:"preflight",level:report.error?"error":"info",payload:{sessionSID:sessionSID,preflightSID:createSID("PF"),progressEvents:JSON.stringify(report.progressEvents),testTiming:report.testTiming,dtlsTiming:report.networkTiming.dtls,iceTiming:report.networkTiming.ice,peerConnectionTiming:report.networkTiming.peerConnection,connectTiming:report.networkTiming.connect,mediaTiming:report.networkTiming.media,selectedLocalCandidate:(_b=report.selectedIceCandidatePairStats)===null||_b===void 0?void 0:_b.localCandidate,selectedRemoteCandidate:(_c=report.selectedIceCandidatePairStats)===null||_c===void 0?void 0:_c.remoteCandidate,iceCandidateStats:iceCandidateStats,jitterStats:jitterStats,rttStats:rttStats,packetLossStats:packetLossStats,mosStats:mosStats,error:report.error}};eventObserver.emit("event",insightsReport);setTimeout(function(){return eventPublisher.disconnect()},2e3)}}};PreflightTest.prototype._runPreflightTest=function(token,environment,wsServer){return __awaiter(this,void 0,void 0,function(){var localTracks,pcs,reportToInsights,elements_1,iceServers,senderPC_1,receiverPC_1,remoteTracks_1,collectedStats_1,report,error_1,preflightReport;var _this=this;return __generator(this,function(_a){switch(_a.label){case 0:localTracks=[];pcs=[];reportToInsights=this._setupInsights({token:token,environment:environment}).reportToInsights;_a.label=1;case 1:_a.trys.push([1,8,9,10]);elements_1=[];return[4,this._executePreflightStep("Acquire media",function(){return[syntheticaudio_1.syntheticAudio(),syntheticvideo_1.syntheticVideo({width:640,height:480})]})];case 2:localTracks=_a.sent();this._updateProgress(PreflightProgress.mediaAcquired);this.emit("debug",{localTracks:localTracks});this._connectTiming.start();return[4,this._executePreflightStep("Get turn credentials",function(){return getturncredentials_1.getTurnCredentials(token,wsServer)},new SignalingConnectionTimeoutError)];case 3:iceServers=_a.sent();this._connectTiming.stop();this._updateProgress(PreflightProgress.connected);senderPC_1=new RTCPeerConnection({iceServers:iceServers,iceTransportPolicy:"relay",bundlePolicy:"max-bundle"});receiverPC_1=new RTCPeerConnection({iceServers:iceServers,bundlePolicy:"max-bundle"});pcs.push(senderPC_1);pcs.push(receiverPC_1);this._mediaTiming.start();return[4,this._executePreflightStep("Setup Peer Connections",function(){return __awaiter(_this,void 0,void 0,function(){var remoteTracksPromise,offer,updatedOffer,answer;return __generator(this,function(_a){switch(_a.label){case 0:senderPC_1.addEventListener("icecandidate",function(event){return event.candidate&&receiverPC_1.addIceCandidate(event.candidate)});receiverPC_1.addEventListener("icecandidate",function(event){return event.candidate&&senderPC_1.addIceCandidate(event.candidate)});localTracks.forEach(function(track){return senderPC_1.addTrack(track)});remoteTracksPromise=new Promise(function(resolve){var remoteTracks=[];receiverPC_1.addEventListener("track",function(event){remoteTracks.push(event.track);if(remoteTracks.length===localTracks.length){resolve(remoteTracks)}})});return[4,senderPC_1.createOffer()];case 1:offer=_a.sent();updatedOffer=offer;return[4,senderPC_1.setLocalDescription(updatedOffer)];case 2:_a.sent();return[4,receiverPC_1.setRemoteDescription(updatedOffer)];case 3:_a.sent();return[4,receiverPC_1.createAnswer()];case 4:answer=_a.sent();return[4,receiverPC_1.setLocalDescription(answer)];case 5:_a.sent();return[4,senderPC_1.setRemoteDescription(answer)];case 6:_a.sent();return[4,this._collectNetworkTimings(senderPC_1)];case 7:_a.sent();return[2,remoteTracksPromise]}})})},new MediaConnectionError)];case 4:remoteTracks_1=_a.sent();this.emit("debug",{remoteTracks:remoteTracks_1});remoteTracks_1.forEach(function(track){track.addEventListener("ended",function(){return _this._log.warn(track.kind+":ended")});track.addEventListener("mute",function(){return _this._log.warn(track.kind+":muted")});track.addEventListener("unmute",function(){return _this._log.warn(track.kind+":unmuted")})});this._updateProgress(PreflightProgress.mediaSubscribed);return[4,this._executePreflightStep("Wait for tracks to start",function(){return new Promise(function(resolve){var element=document.createElement("video");element.autoplay=true;element.playsInline=true;element.muted=true;element.srcObject=new MediaStream(remoteTracks_1);elements_1.push(element);_this.emit("debugElement",element);element.oncanplay=resolve})},new MediaConnectionError)];case 5:_a.sent();this._mediaTiming.stop();this._updateProgress(PreflightProgress.mediaStarted);return[4,this._executePreflightStep("Collect stats for duration",function(){return _this._collectRTCStatsForDuration(_this._testDuration,initCollectedStats(),senderPC_1,receiverPC_1)})];case 6:collectedStats_1=_a.sent();return[4,this._executePreflightStep("Generate report",function(){return _this._generatePreflightReport(collectedStats_1)})];case 7:report=_a.sent();reportToInsights({report:report});this.emit("completed",report);return[3,10];case 8:error_1=_a.sent();preflightReport=this._generatePreflightReport();reportToInsights({report:__assign(__assign({},preflightReport),{error:error_1===null||error_1===void 0?void 0:error_1.toString()})});this.emit("failed",error_1,preflightReport);return[3,10];case 9:pcs.forEach(function(pc){return pc.close()});localTracks.forEach(function(track){return track.stop()});return[7];case 10:return[2]}})})};PreflightTest.prototype._collectRTCStats=function(collectedStats,senderPC,receiverPC){return __awaiter(this,void 0,void 0,function(){var combinedStats,timestamp,bytesSent,bytesReceived,packets,packetsLost,roundTripTime,jitter,selectedIceCandidatePairStats,iceCandidateStats,hasLastData,fractionPacketLost,percentPacketsLost,score;return __generator(this,function(_a){switch(_a.label){case 0:return[4,getCombinedConnectionStats_1.getCombinedConnectionStats({publisher:senderPC,subscriber:receiverPC})];case 1:combinedStats=_a.sent();timestamp=combinedStats.timestamp,bytesSent=combinedStats.bytesSent,bytesReceived=combinedStats.bytesReceived,packets=combinedStats.packets,packetsLost=combinedStats.packetsLost,roundTripTime=combinedStats.roundTripTime,jitter=combinedStats.jitter,selectedIceCandidatePairStats=combinedStats.selectedIceCandidatePairStats,iceCandidateStats=combinedStats.iceCandidateStats;hasLastData=collectedStats.jitter.length>0;collectedStats.jitter.push(jitter);collectedStats.rtt.push(roundTripTime);this._sentBytesMovingAverage.putSample(bytesSent,timestamp);this._receivedBytesMovingAverage.putSample(bytesReceived,timestamp);this._packetLossMovingAverage.putSample(packetsLost,packets);if(hasLastData){collectedStats.outgoingBitrate.push(this._sentBytesMovingAverage.get()*1e3*8);collectedStats.incomingBitrate.push(this._receivedBytesMovingAverage.get()*1e3*8);fractionPacketLost=this._packetLossMovingAverage.get();percentPacketsLost=Math.min(100,fractionPacketLost*100);collectedStats.packetLoss.push(percentPacketsLost);score=mos_1.calculateMOS(roundTripTime,jitter,fractionPacketLost);collectedStats.mos.push(score)}if(!collectedStats.selectedIceCandidatePairStats){collectedStats.selectedIceCandidatePairStats=selectedIceCandidatePairStats}if(collectedStats.iceCandidateStats.length===0){collectedStats.iceCandidateStats=iceCandidateStats}return[2]}})})};PreflightTest.prototype._collectRTCStatsForDuration=function(duration,collectedStats,senderPC,receiverPC){return __awaiter(this,void 0,void 0,function(){var startTime,STAT_INTERVAL,remainingDuration;return __generator(this,function(_a){switch(_a.label){case 0:startTime=Date.now();STAT_INTERVAL=Math.min(1e3,duration);return[4,index_1.waitForSometime(STAT_INTERVAL)];case 1:_a.sent();return[4,this._collectRTCStats(collectedStats,senderPC,receiverPC)];case 2:_a.sent();remainingDuration=duration-(Date.now()-startTime);if(!(remainingDuration>0))return[3,4];return[4,this._collectRTCStatsForDuration(remainingDuration,collectedStats,senderPC,receiverPC)];case 3:collectedStats=_a.sent();_a.label=4;case 4:return[2,collectedStats]}})})};PreflightTest.prototype._updateProgress=function(name){var duration=Date.now()-this._testTiming.getTimeMeasurement().start;this._progressEvents.push({duration:duration,name:name});this.emit("progress",name)};return PreflightTest}(EventEmitter);exports.PreflightTest=PreflightTest;function initCollectedStats(){return{mos:[],jitter:[],rtt:[],outgoingBitrate:[],incomingBitrate:[],packetLoss:[],selectedIceCandidatePairStats:null,iceCandidateStats:[]}}function runPreflight(token,options){if(options===void 0){options={}}var preflight=new PreflightTest(token,options);return preflight}exports.runPreflight=runPreflight},{"../eventemitter":10,"../util/constants":124,"../util/eventobserver":129,"../util/index":131,"../util/insightspublisher":132,"../util/log":135,"../util/movingaveragedelta":136,"../util/sid":143,"../util/twilio-video-errors":146,"./getCombinedConnectionStats":46,"./getturncredentials":47,"./makestat":48,"./mos":49,"./syntheticaudio":51,"./syntheticvideo":52,"./timer":53}],51:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.syntheticAudio=void 0;function syntheticAudio(){var audioContextFactory=require("../webaudio/audiocontext");var holder={};var audioContext=audioContextFactory.getOrCreate(holder);var oscillator=audioContext.createOscillator();var dst=oscillator.connect(audioContext.createMediaStreamDestination());oscillator.start();var track=dst.stream.getAudioTracks()[0];var originalStop=track.stop;track.stop=function(){originalStop.call(track);audioContextFactory.release(holder)};return track}exports.syntheticAudio=syntheticAudio},{"../webaudio/audiocontext":152}],52:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.syntheticVideo=void 0;function syntheticVideo(_a){var _b=_a===void 0?{}:_a,_c=_b.width,width=_c===void 0?640:_c,_d=_b.height,height=_d===void 0?480:_d;var canvas=Object.assign(document.createElement("canvas"),{width:width,height:height});var ctx=canvas.getContext("2d");ctx.fillStyle="green";ctx.fillRect(0,0,canvas.width,canvas.height);var stopped=false;requestAnimationFrame(function animate(){if(!stopped){var r=Math.round(Math.random()*255);var g=Math.round(Math.random()*255);var b=Math.round(Math.random()*255);var a=Math.round(Math.random()*255);ctx.fillStyle="rgba("+r+", "+g+", "+b+", "+a+")";ctx.fillRect(Math.random()*width,Math.random()*height,50,50);requestAnimationFrame(animate)}});var stream=canvas.captureStream(30);var track=stream.getTracks()[0];var originalStop=track.stop;track.stop=function(){stopped=true;originalStop.call(track)};return track}exports.syntheticVideo=syntheticVideo},{}],53:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Timer=void 0;var Timer=function(){function Timer(){this._end=undefined;this.start()}Timer.prototype.start=function(){this._start=Date.now();return this};Timer.prototype.stop=function(){this._end=Date.now();return this};Timer.prototype.getTimeMeasurement=function(){return{start:this._start,end:this._end,duration:this._end===undefined?undefined:this._end-this._start}};return Timer}();exports.Timer=Timer},{}],54:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var __spreadArray=this&&this.__spreadArray||function(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to};var EventEmitter=require("events").EventEmitter;var QueueingEventEmitter=function(_super){__extends(QueueingEventEmitter,_super);function QueueingEventEmitter(){var _this=_super.call(this)||this;Object.defineProperties(_this,{_queuedEvents:{value:new Map}});return _this}QueueingEventEmitter.prototype.dequeue=function(event){var _this=this;var result=true;if(!event){this._queuedEvents.forEach(function(_,queuedEvent){result=this.dequeue(queuedEvent)&&result},this);return result}var queue=this._queuedEvents.get(event)||[];this._queuedEvents.delete(event);return queue.reduce(function(result,args){return _this.emit.apply(_this,__spreadArray([],__read([event].concat(args))))&&result},result)};QueueingEventEmitter.prototype.queue=function(){var args=[].slice.call(arguments);if(this.emit.apply(this,__spreadArray([],__read(args)))){return true}var event=args[0];if(!this._queuedEvents.has(event)){this._queuedEvents.set(event,[])}this._queuedEvents.get(event).push(args.slice(1));return false};return QueueingEventEmitter}(EventEmitter);module.exports=QueueingEventEmitter},{events:173}],55:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var __spreadArray=this&&this.__spreadArray||function(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to};var Participant=require("./participant");var RemoteParticipant=function(_super){__extends(RemoteParticipant,_super);function RemoteParticipant(signaling,options){var _this=_super.call(this,signaling,options)||this;_this._handleTrackSignalingEvents();_this.once("disconnected",_this._unsubscribeTracks.bind(_this));return _this}RemoteParticipant.prototype.toString=function(){return"[RemoteParticipant #"+this._instanceId+(this.sid?": "+this.sid:"")+"]"};RemoteParticipant.prototype._addTrack=function(remoteTrack,publication,id){if(!_super.prototype._addTrack.call(this,remoteTrack,id)){return null}publication._subscribed(remoteTrack);this.emit("trackSubscribed",remoteTrack,publication);return remoteTrack};RemoteParticipant.prototype._addTrackPublication=function(publication){var addedPublication=_super.prototype._addTrackPublication.call(this,publication);if(!addedPublication){return null}this.emit("trackPublished",addedPublication);return addedPublication};RemoteParticipant.prototype._getTrackPublicationEvents=function(){
39
+ isSupported:require("./util/support")(),version:require("../package.json").version,Logger:require("./vendor/loglevel"),LocalAudioTrack:require("./media/track/es5").LocalAudioTrack,LocalDataTrack:require("./media/track/es5").LocalDataTrack,LocalVideoTrack:require("./media/track/es5").LocalVideoTrack};function connect(token,options){var internalOptions=__assign({createLocalTracks:createlocaltracks_1.createLocalTracks},options);return internals.connect(token,internalOptions)}function createLocalAudioTrack(options){var internalOptions=__assign({createLocalTracks:createlocaltracks_1.createLocalTracks},options);return internals.createLocalAudioTrack(internalOptions)}function createLocalVideoTrack(options){var internalOptions=__assign({createLocalTracks:createlocaltracks_1.createLocalTracks},options);return internals.createLocalVideoTrack(internalOptions)}var isSupported=internals.isSupported;var version=internals.version;var Logger=internals.Logger;var LocalAudioTrack=internals.LocalAudioTrack;var LocalVideoTrack=internals.LocalVideoTrack;var LocalDataTrack=internals.LocalDataTrack;module.exports={connect:connect,createLocalAudioTrack:createLocalAudioTrack,createLocalVideoTrack:createLocalVideoTrack,createLocalTracks:createlocaltracks_1.createLocalTracks,runPreflight:preflighttest_1.runPreflight,isSupported:isSupported,version:version,Logger:Logger,LocalAudioTrack:LocalAudioTrack,LocalVideoTrack:LocalVideoTrack,LocalDataTrack:LocalDataTrack}},{"../package.json":174,"./connect":2,"./createlocaltrack":3,"./createlocaltracks":4,"./media/track/es5":14,"./preflight/preflighttest":50,"./util/support":144,"./vendor/loglevel":151}],12:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var MediaStreamTrack=require("./webrtc").MediaStreamTrack;var _a=require("./util"),asLocalTrack=_a.asLocalTrack,asLocalTrackPublication=_a.asLocalTrackPublication,trackClass=_a.trackClass;var _b=require("./util/constants"),E=_b.typeErrors,trackPriority=_b.trackPriority;var validateLocalTrack=require("./util/validate").validateLocalTrack;var _c=require("./media/track/es5"),LocalAudioTrack=_c.LocalAudioTrack,LocalDataTrack=_c.LocalDataTrack,LocalVideoTrack=_c.LocalVideoTrack;var LocalAudioTrackPublication=require("./media/track/localaudiotrackpublication");var LocalDataTrackPublication=require("./media/track/localdatatrackpublication");var LocalVideoTrackPublication=require("./media/track/localvideotrackpublication");var Participant=require("./participant");var LocalParticipant=function(_super){__extends(LocalParticipant,_super);function LocalParticipant(signaling,localTracks,options){var _this=this;options=Object.assign({LocalAudioTrack:LocalAudioTrack,LocalVideoTrack:LocalVideoTrack,LocalDataTrack:LocalDataTrack,MediaStreamTrack:MediaStreamTrack,LocalAudioTrackPublication:LocalAudioTrackPublication,LocalVideoTrackPublication:LocalVideoTrackPublication,LocalDataTrackPublication:LocalDataTrackPublication,shouldStopLocalTracks:false,tracks:localTracks},options);var tracksToStop=options.shouldStopLocalTracks?new Set(localTracks.filter(function(localTrack){return localTrack.kind!=="data"})):new Set;_this=_super.call(this,signaling,options)||this;Object.defineProperties(_this,{_eventObserver:{value:options.eventObserver},_LocalAudioTrack:{value:options.LocalAudioTrack},_LocalDataTrack:{value:options.LocalDataTrack},_LocalVideoTrack:{value:options.LocalVideoTrack},_MediaStreamTrack:{value:options.MediaStreamTrack},_LocalAudioTrackPublication:{value:options.LocalAudioTrackPublication},_LocalDataTrackPublication:{value:options.LocalDataTrackPublication},_LocalVideoTrackPublication:{value:options.LocalVideoTrackPublication},_tracksToStop:{value:tracksToStop},signalingRegion:{enumerable:true,get:function(){return signaling.signalingRegion}}});_this._handleTrackSignalingEvents();return _this}LocalParticipant.prototype._addTrack=function(track,id,priority){var addedTrack=_super.prototype._addTrack.call(this,track,id);if(addedTrack&&this.state!=="disconnected"){this._addLocalTrack(track,priority)}return addedTrack};LocalParticipant.prototype._addLocalTrack=function(track,priority){var _a;var vendor=(_a=track.noiseCancellation)===null||_a===void 0?void 0:_a.vendor;this._signaling.addTrack(track._trackSender,track.name,priority,vendor);this._log.info("Added a new "+trackClass(track,true)+":",track.id);this._log.debug(trackClass(track,true)+":",track)};LocalParticipant.prototype._removeTrack=function(track,id){var removedTrack=_super.prototype._removeTrack.call(this,track,id);if(removedTrack&&this.state!=="disconnected"){this._signaling.removeTrack(track._trackSender);this._log.info("Removed a "+trackClass(track,true)+":",track.id);this._log.debug(trackClass(track,true)+":",track)}return removedTrack};LocalParticipant.prototype._getTrackEvents=function(){return _super.prototype._getTrackEvents.call(this).concat([["disabled","trackDisabled"],["enabled","trackEnabled"],["stopped","trackStopped"]])};LocalParticipant.prototype.toString=function(){return"[LocalParticipant #"+this._instanceId+(this.sid?": "+this.sid:"")+"]"};LocalParticipant.prototype._handleTrackSignalingEvents=function(){var _this=this;var log=this._log;if(this.state==="disconnected"){return}var localTrackDisabled=function(localTrack){var trackSignaling=_this._signaling.getPublication(localTrack._trackSender);if(trackSignaling){trackSignaling.disable();log.debug("Disabled the "+trackClass(localTrack,true)+":",localTrack.id)}};var localTrackEnabled=function(localTrack){var trackSignaling=_this._signaling.getPublication(localTrack._trackSender);if(trackSignaling){trackSignaling.enable();log.debug("Enabled the "+trackClass(localTrack,true)+":",localTrack.id)}};var localTrackStopped=function(localTrack){var trackSignaling=_this._signaling.getPublication(localTrack._trackSender);if(trackSignaling){trackSignaling.stop()}return trackSignaling};var stateChanged=function(state){log.debug("Transitioned to state:",state);if(state==="disconnected"){log.debug("Removing LocalTrack event listeners");_this._signaling.removeListener("stateChanged",stateChanged);_this.removeListener("trackDisabled",localTrackDisabled);_this.removeListener("trackEnabled",localTrackEnabled);_this.removeListener("trackStopped",localTrackStopped);_this._tracks.forEach(function(track){var trackSignaling=localTrackStopped(track);if(trackSignaling){track._trackSender.removeClone(trackSignaling._trackTransceiver)}});log.info("LocalParticipant disconnected. Stopping "+_this._tracksToStop.size+" automatically-acquired LocalTracks");_this._tracksToStop.forEach(function(track){track.stop()})}else if(state==="connected"){log.info("reconnected");setTimeout(function(){return _this.emit("reconnected")},0)}};this.on("trackDisabled",localTrackDisabled);this.on("trackEnabled",localTrackEnabled);this.on("trackStopped",localTrackStopped);this._signaling.on("stateChanged",stateChanged);this._tracks.forEach(function(track){_this._addLocalTrack(track,trackPriority.PRIORITY_STANDARD);_this._getOrCreateLocalTrackPublication(track).catch(function(error){log.warn("Failed to get or create LocalTrackPublication for "+track+":",error)})})};LocalParticipant.prototype._getOrCreateLocalTrackPublication=function(localTrack){var localTrackPublication=getTrackPublication(this.tracks,localTrack);if(localTrackPublication){return Promise.resolve(localTrackPublication)}var log=this._log;var self=this;var trackSignaling=this._signaling.getPublication(localTrack._trackSender);if(!trackSignaling){return Promise.reject(new Error("Unexpected error: The "+localTrack+" cannot be published"))}return new Promise(function(resolve,reject){function updated(){var error=trackSignaling.error;if(error){trackSignaling.removeListener("updated",updated);log.warn("Failed to publish the "+trackClass(localTrack,true)+": "+error.message);self._removeTrack(localTrack,localTrack.id);setTimeout(function(){self.emit("trackPublicationFailed",error,localTrack)});reject(error);return}if(!self._tracks.has(localTrack.id)){trackSignaling.removeListener("updated",updated);reject(new Error("The "+localTrack+" was unpublished"));return}var sid=trackSignaling.sid;if(!sid){return}trackSignaling.removeListener("updated",updated);var options={log:log,LocalAudioTrackPublication:self._LocalAudioTrackPublication,LocalDataTrackPublication:self._LocalDataTrackPublication,LocalVideoTrackPublication:self._LocalVideoTrackPublication};localTrackPublication=getTrackPublication(self.tracks,localTrack);var warningHandler=function(twilioWarningName){return self.emit("trackWarning",twilioWarningName,localTrackPublication)};var warningsClearedHandler=function(){return self.emit("trackWarningsCleared",localTrackPublication)};var unpublish=function(publication){localTrackPublication.removeListener("trackWarning",warningHandler);localTrackPublication.removeListener("trackWarningsCleared",warningsClearedHandler);self.unpublishTrack(publication.track)};if(!localTrackPublication){localTrackPublication=asLocalTrackPublication(localTrack,trackSignaling,unpublish,options);self._addTrackPublication(localTrackPublication)}localTrackPublication.on("warning",warningHandler);localTrackPublication.on("warningsCleared",warningsClearedHandler);var state=self._signaling.state;if(state==="connected"||state==="connecting"){if(localTrack._processorEventObserver){localTrack._processorEventObserver.on("event",function(event){self._eventObserver.emit("event",{name:event.name,payload:event.data,group:"video-processor",level:"info"})})}if(localTrack.processedTrack){localTrack._captureFrames();localTrack._setSenderMediaStreamTrack(true)}}if(state==="connected"){setTimeout(function(){self.emit("trackPublished",localTrackPublication)})}resolve(localTrackPublication)}trackSignaling.on("updated",updated)})};LocalParticipant.prototype.publishTrack=function(localTrackOrMediaStreamTrack,options){var trackPublication=getTrackPublication(this.tracks,localTrackOrMediaStreamTrack);if(trackPublication){return Promise.resolve(trackPublication)}options=Object.assign({log:this._log,priority:trackPriority.PRIORITY_STANDARD,LocalAudioTrack:this._LocalAudioTrack,LocalDataTrack:this._LocalDataTrack,LocalVideoTrack:this._LocalVideoTrack,MediaStreamTrack:this._MediaStreamTrack},options);var localTrack;try{localTrack=asLocalTrack(localTrackOrMediaStreamTrack,options)}catch(error){return Promise.reject(error)}var noiseCancellation=localTrack.noiseCancellation;var allowedAudioProcessors=this._signaling.audioProcessors;if(noiseCancellation&&!allowedAudioProcessors.includes(noiseCancellation.vendor)){this._log.warn(noiseCancellation.vendor+" is not supported in this room. disabling it permanently");noiseCancellation.disablePermanently()}var priorityValues=Object.values(trackPriority);if(!priorityValues.includes(options.priority)){return Promise.reject(E.INVALID_VALUE("LocalTrackPublishOptions.priority",priorityValues))}var addedLocalTrack=this._addTrack(localTrack,localTrack.id,options.priority)||this._tracks.get(localTrack.id);return this._getOrCreateLocalTrackPublication(addedLocalTrack)};LocalParticipant.prototype.publishTracks=function(tracks){if(!Array.isArray(tracks)){throw E.INVALID_TYPE("tracks","Array of LocalAudioTrack, LocalVideoTrack, LocalDataTrack, or MediaStreamTrack")}return Promise.all(tracks.map(this.publishTrack,this))};LocalParticipant.prototype.setBandwidthProfile=function(){this._log.warn("setBandwidthProfile is not implemented yet and may be available in future versions of twilio-video.js")};LocalParticipant.prototype.setNetworkQualityConfiguration=function(networkQualityConfiguration){if(typeof networkQualityConfiguration!=="object"||networkQualityConfiguration===null){throw E.INVALID_TYPE("networkQualityConfiguration","NetworkQualityConfiguration")}["local","remote"].forEach(function(prop){if(prop in networkQualityConfiguration&&(typeof networkQualityConfiguration[prop]!=="number"||isNaN(networkQualityConfiguration[prop]))){throw E.INVALID_TYPE("networkQualityConfiguration."+prop,"number")}});this._signaling.setNetworkQualityConfiguration(networkQualityConfiguration);return this};LocalParticipant.prototype.setParameters=function(encodingParameters){if(typeof encodingParameters!=="undefined"&&typeof encodingParameters!=="object"){throw E.INVALID_TYPE("encodingParameters","EncodingParameters, null or undefined")}if(encodingParameters){if(this._signaling.getParameters().adaptiveSimulcast&&encodingParameters.maxVideoBitrate){throw E.INVALID_TYPE("encodingParameters",'encodingParameters.maxVideoBitrate is not compatible with "preferredVideoCodecs=auto"')}["maxAudioBitrate","maxVideoBitrate"].forEach(function(prop){if(typeof encodingParameters[prop]!=="undefined"&&typeof encodingParameters[prop]!=="number"&&encodingParameters[prop]!==null){throw E.INVALID_TYPE("encodingParameters."+prop,"number, null or undefined")}})}else if(encodingParameters===null){encodingParameters={maxAudioBitrate:null,maxVideoBitrate:null}}this._signaling.setParameters(encodingParameters);return this};LocalParticipant.prototype.unpublishTrack=function(track){validateLocalTrack(track,{LocalAudioTrack:this._LocalAudioTrack,LocalDataTrack:this._LocalDataTrack,LocalVideoTrack:this._LocalVideoTrack,MediaStreamTrack:this._MediaStreamTrack});var localTrack=this._tracks.get(track.id);if(!localTrack){return null}var trackSignaling=this._signaling.getPublication(localTrack._trackSender);trackSignaling.publishFailed(new Error("The "+localTrack+" was unpublished"));localTrack=this._removeTrack(localTrack,localTrack.id);if(!localTrack){return null}var localTrackPublication=getTrackPublication(this.tracks,localTrack);if(localTrackPublication){this._removeTrackPublication(localTrackPublication)}return localTrackPublication};LocalParticipant.prototype.unpublishTracks=function(tracks){var _this=this;if(!Array.isArray(tracks)){throw E.INVALID_TYPE("tracks","Array of LocalAudioTrack, LocalVideoTrack, LocalDataTrack, or MediaStreamTrack")}return tracks.reduce(function(unpublishedTracks,track){var unpublishedTrack=_this.unpublishTrack(track);return unpublishedTrack?unpublishedTracks.concat(unpublishedTrack):unpublishedTracks},[])};return LocalParticipant}(Participant);function getTrackPublication(trackPublications,track){return Array.from(trackPublications.values()).find(function(trackPublication){return trackPublication.track===track||trackPublication.track.mediaStreamTrack===track})||null}module.exports=LocalParticipant},{"./media/track/es5":14,"./media/track/localaudiotrackpublication":20,"./media/track/localdatatrackpublication":22,"./media/track/localvideotrackpublication":26,"./participant":45,"./util":131,"./util/constants":124,"./util/validate":149,"./webrtc":157}],13:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var MediaTrack=require("./mediatrack");var AudioTrack=function(_super){__extends(AudioTrack,_super);function AudioTrack(mediaTrackTransceiver,options){return _super.call(this,mediaTrackTransceiver,options)||this}AudioTrack.prototype.attach=function(){return _super.prototype.attach.apply(this,arguments)};AudioTrack.prototype.detach=function(){return _super.prototype.detach.apply(this,arguments)};return AudioTrack}(MediaTrack);module.exports=AudioTrack},{"./mediatrack":27}],14:[function(require,module,exports){"use strict";module.exports={LocalAudioTrack:require("./localaudiotrack"),LocalVideoTrack:require("./localvideotrack"),LocalDataTrack:require("./localdatatrack")}},{"./localaudiotrack":15,"./localdatatrack":16,"./localvideotrack":17}],15:[function(require,module,exports){"use strict";var inherits=require("../../../vendor/inherits");var LocalAudioTrackClass=require("../localaudiotrack");function LocalAudioTrack(mediaStreamTrack,options){var track=new LocalAudioTrackClass(mediaStreamTrack,options);Object.setPrototypeOf(track,LocalAudioTrack.prototype);return track}inherits(LocalAudioTrack,LocalAudioTrackClass);module.exports=LocalAudioTrack},{"../../../vendor/inherits":150,"../localaudiotrack":19}],16:[function(require,module,exports){"use strict";var inherits=require("../../../vendor/inherits");var LocalDataTrackClass=require("../localdatatrack");function LocalDataTrack(options){var track=new LocalDataTrackClass(options);Object.setPrototypeOf(track,LocalDataTrack.prototype);return track}inherits(LocalDataTrack,LocalDataTrackClass);module.exports=LocalDataTrack},{"../../../vendor/inherits":150,"../localdatatrack":21}],17:[function(require,module,exports){"use strict";var inherits=require("../../../vendor/inherits");var LocalVideoTrackClass=require("../localvideotrack");function LocalVideoTrack(mediaStreamTrack,options){var track=new LocalVideoTrackClass(mediaStreamTrack,options);Object.setPrototypeOf(track,LocalVideoTrack.prototype);return track}inherits(LocalVideoTrack,LocalVideoTrackClass);module.exports=LocalVideoTrack},{"../../../vendor/inherits":150,"../localvideotrack":25}],18:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var EventEmitter=require("../../eventemitter");var _a=require("../../util"),buildLogLevels=_a.buildLogLevels,valueToJSON=_a.valueToJSON;var DEFAULT_LOG_LEVEL=require("../../util/constants").DEFAULT_LOG_LEVEL;var Log=require("../../util/log");var nInstances=0;var Track=function(_super){__extends(Track,_super);function Track(id,kind,options){var _this=this;options=Object.assign({name:id,log:null,logLevel:DEFAULT_LOG_LEVEL},options);_this=_super.call(this)||this;var name=String(options.name);var logLevels=buildLogLevels(options.logLevel);var log=options.log?options.log.createLog("media",_this):new Log("media",_this,logLevels,options.loggerName);Object.defineProperties(_this,{_instanceId:{value:++nInstances},_log:{value:log},kind:{enumerable:true,value:kind},name:{enumerable:true,value:name}});return _this}Track.prototype.toJSON=function(){return valueToJSON(this)};return Track}(EventEmitter);module.exports=Track},{"../../eventemitter":10,"../../util":131,"../../util/constants":124,"../../util/log":135}],19:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var AudioTrack=require("./audiotrack");var mixinLocalMediaTrack=require("./localmediatrack");var LocalMediaAudioTrack=mixinLocalMediaTrack(AudioTrack);var LocalAudioTrack=function(_super){__extends(LocalAudioTrack,_super);function LocalAudioTrack(mediaStreamTrack,options){var _this=this;var noiseCancellation=(options===null||options===void 0?void 0:options.noiseCancellation)||null;_this=_super.call(this,mediaStreamTrack,options)||this;Object.defineProperties(_this,{noiseCancellation:{enumerable:true,value:noiseCancellation,writable:false}});return _this}LocalAudioTrack.prototype.toString=function(){return"[LocalAudioTrack #"+this._instanceId+": "+this.id+"]"};LocalAudioTrack.prototype.attach=function(el){el=_super.prototype.attach.call(this,el);el.muted=true;return el};LocalAudioTrack.prototype._end=function(){return _super.prototype._end.apply(this,arguments)};LocalAudioTrack.prototype._reacquireTrack=function(constraints){var _this=this;this._log.debug("_reacquireTrack: ",constraints);if(this.noiseCancellation){return this.noiseCancellation.reacquireTrack(function(){return _super.prototype._reacquireTrack.call(_this,constraints)})}return _super.prototype._reacquireTrack.call(this,constraints)};LocalAudioTrack.prototype.disable=function(){return _super.prototype.disable.apply(this,arguments)};LocalAudioTrack.prototype.enable=function(){return _super.prototype.enable.apply(this,arguments)};LocalAudioTrack.prototype.restart=function(){return _super.prototype.restart.apply(this,arguments)};LocalAudioTrack.prototype.stop=function(){if(this.noiseCancellation){this.noiseCancellation.stop()}return _super.prototype.stop.apply(this,arguments)};return LocalAudioTrack}(LocalMediaAudioTrack);module.exports=LocalAudioTrack},{"./audiotrack":13,"./localmediatrack":23}],20:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var LocalTrackPublication=require("./localtrackpublication");var LocalAudioTrackPublication=function(_super){__extends(LocalAudioTrackPublication,_super);function LocalAudioTrackPublication(signaling,track,unpublish,options){return _super.call(this,signaling,track,unpublish,options)||this}LocalAudioTrackPublication.prototype.toString=function(){return"[LocalAudioTrackPublication #"+this._instanceId+": "+this.trackSid+"]"};return LocalAudioTrackPublication}(LocalTrackPublication);module.exports=LocalAudioTrackPublication},{"./localtrackpublication":24}],21:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var Track=require("./");var DefaultDataTrackSender=require("../../data/sender");var LocalDataTrack=function(_super){__extends(LocalDataTrack,_super);function LocalDataTrack(options){var _this=this;options=Object.assign({DataTrackSender:DefaultDataTrackSender,maxPacketLifeTime:null,maxRetransmits:null,ordered:true},options);var DataTrackSender=options.DataTrackSender;var dataTrackSender=new DataTrackSender(options.maxPacketLifeTime,options.maxRetransmits,options.ordered);_this=_super.call(this,dataTrackSender.id,"data",options)||this;Object.defineProperties(_this,{_trackSender:{value:dataTrackSender},id:{enumerable:true,value:dataTrackSender.id},maxPacketLifeTime:{enumerable:true,value:options.maxPacketLifeTime},maxRetransmits:{enumerable:true,value:options.maxRetransmits},ordered:{enumerable:true,value:options.ordered},reliable:{enumerable:true,value:options.maxPacketLifeTime===null&&options.maxRetransmits===null}});return _this}LocalDataTrack.prototype.send=function(data){this._trackSender.send(data)};return LocalDataTrack}(Track);module.exports=LocalDataTrack},{"../../data/sender":6,"./":18}],22:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var LocalTrackPublication=require("./localtrackpublication");var LocalDataTrackPublication=function(_super){__extends(LocalDataTrackPublication,_super);function LocalDataTrackPublication(signaling,track,unpublish,options){return _super.call(this,signaling,track,unpublish,options)||this}LocalDataTrackPublication.prototype.toString=function(){return"[LocalDataTrackPublication #"+this._instanceId+": "+this.trackSid+"]"};return LocalDataTrackPublication}(LocalTrackPublication);module.exports=LocalDataTrackPublication},{"./localtrackpublication":24}],23:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var getUserMedia=require("../../webrtc").getUserMedia;var _a=require("../../webrtc/util"),guessBrowser=_a.guessBrowser,isIOSChrome=_a.isIOSChrome;var _b=require("../../util"),capitalize=_b.capitalize,defer=_b.defer,isUserMediaTrack=_b.isUserMediaTrack,waitForSometime=_b.waitForSometime,waitForEvent=_b.waitForEvent;var ILLEGAL_INVOKE=require("../../util/constants").typeErrors.ILLEGAL_INVOKE;var detectSilentAudio=require("../../util/detectsilentaudio");var detectSilentVideo=require("../../util/detectsilentvideo");var documentVisibilityMonitor=require("../../util/documentvisibilitymonitor.js");var localMediaRestartDeferreds=require("../../util/localmediarestartdeferreds");var gUMSilentTrackWorkaround=require("../../webaudio/workaround180748");var MediaTrackSender=require("./sender");function mixinLocalMediaTrack(AudioOrVideoTrack){return function(_super){__extends(LocalMediaTrack,_super);function LocalMediaTrack(mediaStreamTrack,options){var _this=this;var workaroundWebKitBug1208516=(guessBrowser()==="safari"||isIOSChrome())&&isUserMediaTrack(mediaStreamTrack)&&typeof document==="object"&&typeof document.addEventListener==="function"&&typeof document.visibilityState==="string";options=Object.assign({getUserMedia:getUserMedia,isCreatedByCreateLocalTracks:false,workaroundWebKitBug1208516:workaroundWebKitBug1208516,gUMSilentTrackWorkaround:gUMSilentTrackWorkaround},options);var mediaTrackSender=new MediaTrackSender(mediaStreamTrack);var kind=mediaTrackSender.kind;_this=_super.call(this,mediaTrackSender,options)||this;Object.defineProperties(_this,{_constraints:{value:typeof options[kind]==="object"?options[kind]:{},writable:true},_getUserMedia:{value:options.getUserMedia},_gUMSilentTrackWorkaround:{value:options.gUMSilentTrackWorkaround},_workaroundWebKitBug1208516:{value:options.workaroundWebKitBug1208516},_workaroundWebKitBug1208516Cleanup:{value:null,writable:true},_didCallEnd:{value:false,writable:true},_isCreatedByCreateLocalTracks:{value:options.isCreatedByCreateLocalTracks},_trackSender:{value:mediaTrackSender},id:{enumerable:true,value:mediaTrackSender.id},isEnabled:{enumerable:true,get:function(){return mediaTrackSender.enabled}},isStopped:{enumerable:true,get:function(){return mediaTrackSender.readyState==="ended"}}});if(_this._workaroundWebKitBug1208516){_this._workaroundWebKitBug1208516Cleanup=restartWhenInadvertentlyStopped(_this)}return _this}LocalMediaTrack.prototype._end=function(){if(this._didCallEnd){return}_super.prototype._end.call(this);this._didCallEnd=true;this.emit("stopped",this)};LocalMediaTrack.prototype._initialize=function(){if(this._didCallEnd){this._didCallEnd=false}_super.prototype._initialize.call(this)};LocalMediaTrack.prototype._reacquireTrack=function(constraints){var _a;var _b=this,getUserMedia=_b._getUserMedia,gUMSilentTrackWorkaround=_b._gUMSilentTrackWorkaround,log=_b._log,kind=_b.mediaStreamTrack.kind;log.info("Re-acquiring the MediaStreamTrack");log.debug("Constraints:",constraints);var gUMConstraints=Object.assign({audio:false,video:false},(_a={},_a[kind]=constraints,_a));var gUMPromise=this._workaroundWebKitBug1208516Cleanup?gUMSilentTrackWorkaround(log,getUserMedia,gUMConstraints):getUserMedia(gUMConstraints);return gUMPromise.then(function(mediaStream){return mediaStream.getTracks()[0]})};LocalMediaTrack.prototype._restart=function(constraints){var _this=this;var log=this._log;constraints=constraints||this._constraints;this._stop();return this._reacquireTrack(constraints).catch(function(error){log.error("Failed to re-acquire the MediaStreamTrack:",{error:error,constraints:constraints});throw error}).then(function(newMediaStreamTrack){log.info("Re-acquired the MediaStreamTrack");log.debug("MediaStreamTrack:",newMediaStreamTrack);_this._constraints=Object.assign({},constraints);return _this._setMediaStreamTrack(newMediaStreamTrack)})};LocalMediaTrack.prototype._setMediaStreamTrack=function(mediaStreamTrack){var _this=this;mediaStreamTrack.enabled=this.mediaStreamTrack.enabled;this._stop();return(this._unprocessedTrack?Promise.resolve().then(function(){_this._unprocessedTrack=mediaStreamTrack}):this._trackSender.setMediaStreamTrack(mediaStreamTrack).catch(function(error){_this._log.warn("setMediaStreamTrack failed:",{error:error,mediaStreamTrack:mediaStreamTrack})})).then(function(){_this._initialize();_this._getAllAttachedElements().forEach(function(el){return _this._attach(el)})})};LocalMediaTrack.prototype._stop=function(){this.mediaStreamTrack.stop();this._end();return this};LocalMediaTrack.prototype.enable=function(enabled){enabled=typeof enabled==="boolean"?enabled:true;if(enabled!==this.mediaStreamTrack.enabled){this._log.info((enabled?"En":"Dis")+"abling");this.mediaStreamTrack.enabled=enabled;this.emit(enabled?"enabled":"disabled",this)}return this};LocalMediaTrack.prototype.disable=function(){return this.enable(false)};LocalMediaTrack.prototype.restart=function(constraints){var _this=this;var kind=this.kind;if(!this._isCreatedByCreateLocalTracks){return Promise.reject(ILLEGAL_INVOKE("restart","can only be called on a"+(" Local"+capitalize(kind)+"Track that is created using createLocalTracks")+(" or createLocal"+capitalize(kind)+"Track.")))}if(this._workaroundWebKitBug1208516Cleanup){this._workaroundWebKitBug1208516Cleanup();this._workaroundWebKitBug1208516Cleanup=null}var promise=this._restart(constraints)
40
+ ;if(this._workaroundWebKitBug1208516){promise=promise.finally(function(){_this._workaroundWebKitBug1208516Cleanup=restartWhenInadvertentlyStopped(_this)})}return promise};LocalMediaTrack.prototype.stop=function(){this._log.info("Stopping");if(this._workaroundWebKitBug1208516Cleanup){this._workaroundWebKitBug1208516Cleanup();this._workaroundWebKitBug1208516Cleanup=null}return this._stop()};return LocalMediaTrack}(AudioOrVideoTrack)}function restartWhenInadvertentlyStopped(localMediaTrack){var log=localMediaTrack._log,kind=localMediaTrack.kind;var detectSilence={audio:detectSilentAudio,video:detectSilentVideo}[kind];var el=localMediaTrack._dummyEl,mediaStreamTrack=localMediaTrack.mediaStreamTrack;var trackChangeInProgress=null;function checkSilence(){return el.play().then(function(){return detectSilence(el)}).then(function(isSilent){if(isSilent){log.warn("Silence detected")}else{log.info("Non-silence detected")}return isSilent}).catch(function(error){log.warn("Failed to detect silence:",error)}).finally(function(){el.pause()})}function shouldReacquireTrack(){var _workaroundWebKitBug1208516Cleanup=localMediaTrack._workaroundWebKitBug1208516Cleanup,isStopped=localMediaTrack.isStopped,muted=localMediaTrack.mediaStreamTrack.muted;var isInadvertentlyStopped=isStopped&&!!_workaroundWebKitBug1208516Cleanup;return Promise.resolve().then(function(){return document.visibilityState==="visible"&&!trackChangeInProgress&&(muted||isInadvertentlyStopped||checkSilence())})}function maybeRestart(){return Promise.race([waitForEvent(mediaStreamTrack,"unmute"),waitForSometime(50)]).then(function(){return shouldReacquireTrack()}).then(function(shouldReacquire){if(shouldReacquire&&!trackChangeInProgress){trackChangeInProgress=defer();localMediaTrack._restart().finally(function(){el=localMediaTrack._dummyEl;removeMediaStreamTrackListeners();mediaStreamTrack=localMediaTrack.mediaStreamTrack;addMediaStreamTrackListeners();trackChangeInProgress.resolve();trackChangeInProgress=null}).catch(function(error){log.error("failed to restart track: ",error)})}var promise=trackChangeInProgress&&trackChangeInProgress.promise||Promise.resolve();return promise.finally(function(){return localMediaRestartDeferreds.resolveDeferred(kind)})}).catch(function(ex){log.error("error in maybeRestart: "+ex.message)})}function onMute(){var log=localMediaTrack._log,kind=localMediaTrack.kind;log.info("Muted");log.debug("LocalMediaTrack:",localMediaTrack);localMediaRestartDeferreds.startDeferred(kind)}function addMediaStreamTrackListeners(){mediaStreamTrack.addEventListener("ended",maybeRestart);mediaStreamTrack.addEventListener("mute",onMute);mediaStreamTrack.addEventListener("unmute",maybeRestart)}function removeMediaStreamTrackListeners(){mediaStreamTrack.removeEventListener("ended",maybeRestart);mediaStreamTrack.removeEventListener("mute",onMute);mediaStreamTrack.removeEventListener("unmute",maybeRestart)}var onVisibilityChange=function(isVisible){return isVisible?maybeRestart():false};documentVisibilityMonitor.onVisibilityChange(1,onVisibilityChange);addMediaStreamTrackListeners();return function(){documentVisibilityMonitor.offVisibilityChange(1,onVisibilityChange);removeMediaStreamTrackListeners()}}module.exports=mixinLocalMediaTrack},{"../../util":131,"../../util/constants":124,"../../util/detectsilentaudio":125,"../../util/detectsilentvideo":126,"../../util/documentvisibilitymonitor.js":127,"../../util/localmediarestartdeferreds":134,"../../webaudio/workaround180748":154,"../../webrtc":157,"../../webrtc/util":170,"./sender":38}],24:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var __spreadArray=this&&this.__spreadArray||function(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to};var TrackPublication=require("./trackpublication");var _a=require("../../util/constants"),E=_a.typeErrors,trackPriority=_a.trackPriority;var LocalTrackPublication=function(_super){__extends(LocalTrackPublication,_super);function LocalTrackPublication(signaling,track,unpublish,options){var _this=_super.call(this,track.name,signaling.sid,options)||this;Object.defineProperties(_this,{_reemitSignalingEvent:{value:function(){var args=[];for(var _i=0;_i<arguments.length;_i++){args[_i]=arguments[_i]}return _this.emit.apply(_this,__spreadArray([args&&args.length?"warning":"warningsCleared"],__read(args)))}},_reemitTrackEvent:{value:function(){return _this.emit(_this.isTrackEnabled?"trackEnabled":"trackDisabled")}},_signaling:{value:signaling},_unpublish:{value:unpublish},isTrackEnabled:{enumerable:true,get:function(){return this.track.kind==="data"?true:this.track.isEnabled}},kind:{enumerable:true,value:track.kind},priority:{enumerable:true,get:function(){return signaling.updatedPriority}},track:{enumerable:true,value:track}});["disabled","enabled"].forEach(function(name){return track.on(name,_this._reemitTrackEvent)});["warning","warningsCleared"].forEach(function(name){return signaling.on(name,_this._reemitSignalingEvent)});return _this}LocalTrackPublication.prototype.toString=function(){return"[LocalTrackPublication #"+this._instanceId+": "+this.trackSid+"]"};LocalTrackPublication.prototype.setPriority=function(priority){var priorityValues=Object.values(trackPriority);if(!priorityValues.includes(priority)){throw E.INVALID_VALUE("priority",priorityValues)}this._signaling.setPriority(priority);return this};LocalTrackPublication.prototype.unpublish=function(){var _this=this;["disabled","enabled"].forEach(function(name){return _this.track.removeListener(name,_this._reemitTrackEvent)});["warning","warningsCleared"].forEach(function(name){return _this._signaling.removeListener(name,_this._reemitSignalingEvent)});this._unpublish(this);return this};return LocalTrackPublication}(TrackPublication);module.exports=LocalTrackPublication},{"../../util/constants":124,"./trackpublication":39}],25:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var _a=require("../../webrtc/util"),guessBrowser=_a.guessBrowser,isIOSChrome=_a.isIOSChrome;var detectSilentVideo=require("../../util/detectsilentvideo");var mixinLocalMediaTrack=require("./localmediatrack");var VideoTrack=require("./videotrack");var isUserMediaTrack=require("../../util").isUserMediaTrack;var LocalMediaVideoTrack=mixinLocalMediaTrack(VideoTrack);var LocalVideoTrack=function(_super){__extends(LocalVideoTrack,_super);function LocalVideoTrack(mediaStreamTrack,options){var _this=this;options=Object.assign({workaroundSilentLocalVideo:(guessBrowser()==="safari"||isIOSChrome())&&isUserMediaTrack(mediaStreamTrack)&&typeof document!=="undefined"&&typeof document.createElement==="function"},options);_this=_super.call(this,mediaStreamTrack,options)||this;Object.defineProperties(_this,{_workaroundSilentLocalVideo:{value:options.workaroundSilentLocalVideo?workaroundSilentLocalVideo:null},_workaroundSilentLocalVideoCleanup:{value:null,writable:true}});if(_this._workaroundSilentLocalVideo){_this._workaroundSilentLocalVideoCleanup=_this._workaroundSilentLocalVideo(_this,document)}return _this}LocalVideoTrack.prototype.toString=function(){return"[LocalVideoTrack #"+this._instanceId+": "+this.id+"]"};LocalVideoTrack.prototype._checkIfCanCaptureFrames=function(){return _super.prototype._checkIfCanCaptureFrames.call(this,this._trackSender.isPublishing)};LocalVideoTrack.prototype._end=function(){return _super.prototype._end.apply(this,arguments)};LocalVideoTrack.prototype._setSenderMediaStreamTrack=function(useProcessed){var _this=this;var unprocessedTrack=this.mediaStreamTrack;var mediaStreamTrack=useProcessed?this.processedTrack:unprocessedTrack;return this._trackSender.setMediaStreamTrack(mediaStreamTrack).catch(function(error){return _this._log.warn("setMediaStreamTrack failed on LocalVideoTrack RTCRtpSender",{error:error,mediaStreamTrack:mediaStreamTrack})}).then(function(){_this._unprocessedTrack=useProcessed?unprocessedTrack:null})};LocalVideoTrack.prototype.addProcessor=function(){this._log.debug("Adding VideoProcessor to the LocalVideoTrack");var result=_super.prototype.addProcessor.apply(this,arguments);if(!this.processedTrack){return this._log.warn("Unable to add a VideoProcessor to the LocalVideoTrack")}this._log.debug("Updating LocalVideoTrack's MediaStreamTrack with the processed MediaStreamTrack",this.processedTrack);this._setSenderMediaStreamTrack(true);return result};LocalVideoTrack.prototype.removeProcessor=function(){var _this=this;this._log.debug("Removing VideoProcessor from the LocalVideoTrack");var result=_super.prototype.removeProcessor.apply(this,arguments);this._log.debug("Updating LocalVideoTrack's MediaStreamTrack with the original MediaStreamTrack");this._setSenderMediaStreamTrack().then(function(){return _this._updateElementsMediaStreamTrack()});return result};LocalVideoTrack.prototype.disable=function(){var result=_super.prototype.disable.apply(this,arguments);if(this.processedTrack){this.processedTrack.enabled=false}return result};LocalVideoTrack.prototype.enable=function(enabled){if(enabled===void 0){enabled=true}var result=_super.prototype.enable.apply(this,arguments);if(this.processedTrack){this.processedTrack.enabled=enabled;if(enabled){this._captureFrames();this._log.debug("Updating LocalVideoTrack's MediaStreamTrack with the processed MediaStreamTrack",this.processedTrack);this._setSenderMediaStreamTrack(true)}}return result};LocalVideoTrack.prototype.restart=function(){var _this=this;if(this._workaroundSilentLocalVideoCleanup){this._workaroundSilentLocalVideoCleanup();this._workaroundSilentLocalVideoCleanup=null}var promise=_super.prototype.restart.apply(this,arguments);if(this.processor){promise.then(function(){_this._restartProcessor()})}if(this._workaroundSilentLocalVideo){promise.finally(function(){_this._workaroundSilentLocalVideoCleanup=_this._workaroundSilentLocalVideo(_this,document)})}return promise};LocalVideoTrack.prototype.stop=function(){if(this._workaroundSilentLocalVideoCleanup){this._workaroundSilentLocalVideoCleanup();this._workaroundSilentLocalVideoCleanup=null}return _super.prototype.stop.apply(this,arguments)};return LocalVideoTrack}(LocalMediaVideoTrack);function workaroundSilentLocalVideo(localVideoTrack,doc){var log=localVideoTrack._log;var el=localVideoTrack._dummyEl,mediaStreamTrack=localVideoTrack.mediaStreamTrack;function onUnmute(){if(!localVideoTrack.isEnabled){return}log.info("Unmuted, checking silence");el.play().then(function(){return detectSilentVideo(el,doc)}).then(function(isSilent){if(!isSilent){log.info("Non-silent frames detected, so no need to restart");return}log.warn("Silence detected, restarting");localVideoTrack._stop();return localVideoTrack._restart()}).catch(function(error){log.warn("Failed to detect silence and restart:",error)}).finally(function(){el=localVideoTrack._dummyEl;if(el&&!el.paused){el.pause()}mediaStreamTrack.removeEventListener("unmute",onUnmute);mediaStreamTrack=localVideoTrack.mediaStreamTrack;mediaStreamTrack.addEventListener("unmute",onUnmute)})}mediaStreamTrack.addEventListener("unmute",onUnmute);return function(){mediaStreamTrack.removeEventListener("unmute",onUnmute)}}module.exports=LocalVideoTrack},{"../../util":131,"../../util/detectsilentvideo":126,"../../webrtc/util":170,"./localmediatrack":23,"./videotrack":42}],26:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var LocalTrackPublication=require("./localtrackpublication");var LocalVideoTrackPublication=function(_super){__extends(LocalVideoTrackPublication,_super);function LocalVideoTrackPublication(signaling,track,unpublish,options){return _super.call(this,signaling,track,unpublish,options)||this}LocalVideoTrackPublication.prototype.toString=function(){return"[LocalVideoTrackPublication #"+this._instanceId+": "+this.trackSid+"]"};return LocalVideoTrackPublication}(LocalTrackPublication);module.exports=LocalVideoTrackPublication},{"./localtrackpublication":24}],27:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var _a=require("../../webrtc/util"),guessBrowser=_a.guessBrowser,isIOSChrome=_a.isIOSChrome;var MediaStream=require("../../webrtc").MediaStream;var _b=require("../../util"),waitForEvent=_b.waitForEvent,waitForSometime=_b.waitForSometime;var localMediaRestartDeferreds=require("../../util/localmediarestartdeferreds");var Track=require("./");var MediaTrack=function(_super){__extends(MediaTrack,_super);function MediaTrack(mediaTrackTransceiver,options){var _this=this;options=Object.assign({playPausedElementsIfNotBackgrounded:(guessBrowser()==="safari"||isIOSChrome())&&typeof document==="object"&&typeof document.addEventListener==="function"&&typeof document.visibilityState==="string"},options);_this=_super.call(this,mediaTrackTransceiver.id,mediaTrackTransceiver.kind,options)||this;var isStarted=false;options=Object.assign({MediaStream:MediaStream},options);Object.defineProperties(_this,{_attachments:{value:new Set},_dummyEl:{value:null,writable:true},_elShims:{value:new WeakMap},_isStarted:{get:function(){return isStarted},set:function(_isStarted){isStarted=_isStarted}},_playPausedElementsIfNotBackgrounded:{value:options.playPausedElementsIfNotBackgrounded},_shouldShimAttachedElements:{value:options.workaroundWebKitBug212780||options.playPausedElementsIfNotBackgrounded},_unprocessedTrack:{value:null,writable:true},_MediaStream:{value:options.MediaStream},isStarted:{enumerable:true,get:function(){return isStarted}},mediaStreamTrack:{enumerable:true,get:function(){return this._unprocessedTrack||mediaTrackTransceiver.track}},processedTrack:{enumerable:true,value:null,writable:true}});_this._initialize();return _this}MediaTrack.prototype._start=function(){this._log.debug("Started");this._isStarted=true;if(this._dummyEl){this._dummyEl.oncanplay=null}this.emit("started",this)};MediaTrack.prototype._initialize=function(){var self=this;this._log.debug("Initializing");this._dummyEl=this._createElement();this.mediaStreamTrack.addEventListener("ended",function onended(){self._end();self.mediaStreamTrack.removeEventListener("ended",onended)});if(this._dummyEl){this._dummyEl.muted=true;this._dummyEl.oncanplay=this._start.bind(this,this._dummyEl);this._attach(this._dummyEl,this.mediaStreamTrack);this._attachments.delete(this._dummyEl)}};MediaTrack.prototype._end=function(){this._log.debug("Ended");if(this._dummyEl){this._dummyEl.remove();this._dummyEl.srcObject=null;this._dummyEl.oncanplay=null;this._dummyEl=null}};MediaTrack.prototype.attach=function(el){var _this=this;if(typeof el==="string"){el=this._selectElement(el)}else if(!el){el=this._createElement()}this._log.debug("Attempting to attach to element:",el);el=this._attach(el);if(this._shouldShimAttachedElements&&!this._elShims.has(el)){var onUnintentionallyPaused=this._playPausedElementsIfNotBackgrounded?function(){return playIfPausedAndNotBackgrounded(el,_this._log)}:null;this._elShims.set(el,shimMediaElement(el,onUnintentionallyPaused))}return el};MediaTrack.prototype._attach=function(el,mediaStreamTrack){if(mediaStreamTrack===void 0){mediaStreamTrack=this.processedTrack||this.mediaStreamTrack}var mediaStream=el.srcObject;if(!(mediaStream instanceof this._MediaStream)){mediaStream=new this._MediaStream}var getTracks=mediaStreamTrack.kind==="audio"?"getAudioTracks":"getVideoTracks";mediaStream[getTracks]().forEach(function(track){mediaStream.removeTrack(track)});mediaStream.addTrack(mediaStreamTrack);el.srcObject=mediaStream;el.autoplay=true;el.playsInline=true;if(!this._attachments.has(el)){this._attachments.add(el)}return el};MediaTrack.prototype._selectElement=function(selector){var el=document.querySelector(selector);if(!el){throw new Error("Selector matched no element: "+selector)}return el};MediaTrack.prototype._updateElementsMediaStreamTrack=function(){var _this=this;this._log.debug("Reattaching all elements to update mediaStreamTrack");this._getAllAttachedElements().forEach(function(el){return _this._attach(el)})};MediaTrack.prototype._createElement=function(){return typeof document!=="undefined"?document.createElement(this.kind):null};MediaTrack.prototype.detach=function(el){var els;if(typeof el==="string"){els=[this._selectElement(el)]}else if(!el){els=this._getAllAttachedElements()}else{els=[el]}this._log.debug("Attempting to detach from elements:",els);this._detachElements(els);return el?els[0]:els};MediaTrack.prototype._detachElements=function(elements){return elements.map(this._detachElement.bind(this))};MediaTrack.prototype._detachElement=function(el){if(!this._attachments.has(el)){return el}var mediaStream=el.srcObject;if(mediaStream instanceof this._MediaStream){mediaStream.removeTrack(this.processedTrack||this.mediaStreamTrack)}this._attachments.delete(el);if(this._shouldShimAttachedElements&&this._elShims.has(el)){var shim=this._elShims.get(el);shim.unShim();this._elShims.delete(el)}return el};MediaTrack.prototype._getAllAttachedElements=function(){var els=[];this._attachments.forEach(function(el){els.push(el)});return els};return MediaTrack}(Track);function playIfPausedAndNotBackgrounded(el,log){var tag=el.tagName.toLowerCase();log.warn("Unintentionally paused:",el);Promise.race([waitForEvent(document,"visibilitychange"),waitForSometime(1e3)]).then(function(){if(document.visibilityState==="visible"){localMediaRestartDeferreds.whenResolved("audio").then(function(){log.info("Playing unintentionally paused <"+tag+"> element");log.debug("Element:",el);return el.play()}).then(function(){log.info("Successfully played unintentionally paused <"+tag+"> element");log.debug("Element:",el)}).catch(function(error){log.warn("Error while playing unintentionally paused <"+tag+"> element:",{error:error,el:el})})}})}function shimMediaElement(el,onUnintentionallyPaused){if(onUnintentionallyPaused===void 0){onUnintentionallyPaused=null}var origPause=el.pause;var origPlay=el.play;var pausedIntentionally=false;el.pause=function(){pausedIntentionally=true;return origPause.call(el)};el.play=function(){pausedIntentionally=false;return origPlay.call(el)};var onPause=onUnintentionallyPaused?function(){if(!pausedIntentionally){onUnintentionallyPaused()}}:null;if(onPause){el.addEventListener("pause",onPause)}return{pausedIntentionally:function(){return pausedIntentionally},unShim:function(){el.pause=origPause;el.play=origPlay;if(onPause){el.removeEventListener("pause",onPause)}}}}module.exports=MediaTrack},{"../../util":131,"../../util/localmediarestartdeferreds":134,"../../webrtc":157,"../../webrtc/util":170,"./":18}],28:[function(require,module,exports){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};Object.defineProperty(exports,"__esModule",{value:true});exports.applyNoiseCancellation=exports.NoiseCancellationImpl=void 0;var noisecancellationadapter_1=require("../../noisecancellationadapter");var Log=require("../../util/log");var NoiseCancellationImpl=function(){function NoiseCancellationImpl(processor,originalTrack){this._processor=processor;this._sourceTrack=originalTrack;this._disabledPermanent=false}Object.defineProperty(NoiseCancellationImpl.prototype,"vendor",{get:function(){return this._processor.vendor},enumerable:false,configurable:true});Object.defineProperty(NoiseCancellationImpl.prototype,"sourceTrack",{get:function(){return this._sourceTrack},enumerable:false,configurable:true});Object.defineProperty(NoiseCancellationImpl.prototype,"isEnabled",{get:function(){return this._processor.isEnabled()},enumerable:false,configurable:true});NoiseCancellationImpl.prototype.enable=function(){if(this._disabledPermanent){throw new Error(this.vendor+" noise cancellation is disabled permanently for this track")}this._processor.enable();return Promise.resolve()};NoiseCancellationImpl.prototype.disable=function(){this._processor.disable();return Promise.resolve()};NoiseCancellationImpl.prototype.reacquireTrack=function(reacquire){return __awaiter(this,void 0,void 0,function(){var processorWasEnabled,track,processedTrack;return __generator(this,function(_a){switch(_a.label){case 0:processorWasEnabled=this._processor.isEnabled();this._processor.disconnect();return[4,reacquire()];case 1:track=_a.sent();this._sourceTrack=track;return[4,this._processor.connect(track)];case 2:processedTrack=_a.sent();if(processorWasEnabled){this._processor.enable()}else{this._processor.disable()}return[2,processedTrack]}})})};NoiseCancellationImpl.prototype.disablePermanently=function(){this._disabledPermanent=true;return this.disable()};NoiseCancellationImpl.prototype.stop=function(){this._processor.disconnect();this._sourceTrack.stop()};return NoiseCancellationImpl}();exports.NoiseCancellationImpl=NoiseCancellationImpl;function applyNoiseCancellation(mediaStreamTrack,noiseCancellationOptions,log){return __awaiter(this,void 0,void 0,function(){var processor,cleanTrack,noiseCancellation,ex_1;return __generator(this,function(_a){switch(_a.label){case 0:_a.trys.push([0,2,,3]);return[4,noisecancellationadapter_1.createNoiseCancellationAudioProcessor(noiseCancellationOptions,log)];case 1:processor=_a.sent();cleanTrack=processor.connect(mediaStreamTrack);noiseCancellation=new NoiseCancellationImpl(processor,mediaStreamTrack);return[2,{cleanTrack:cleanTrack,noiseCancellation:noiseCancellation}];case 2:ex_1=_a.sent();log.warn("Failed to create noise cancellation. Returning normal audio track: "+ex_1);return[2,{cleanTrack:mediaStreamTrack}];case 3:return[2]}})})}exports.applyNoiseCancellation=applyNoiseCancellation},{"../../noisecancellationadapter":44,"../../util/log":135}],29:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var MediaTrackTransceiver=require("./transceiver");var MediaTrackReceiver=function(_super){__extends(MediaTrackReceiver,_super);function MediaTrackReceiver(id,mediaStreamTrack){return _super.call(this,id,mediaStreamTrack)||this}return MediaTrackReceiver}(MediaTrackTransceiver);module.exports=MediaTrackReceiver},{"./transceiver":40}],30:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var AudioTrack=require("./audiotrack");var mixinRemoteMediaTrack=require("./remotemediatrack");var RemoteMediaAudioTrack=mixinRemoteMediaTrack(AudioTrack);var RemoteAudioTrack=function(_super){__extends(RemoteAudioTrack,_super);function RemoteAudioTrack(sid,mediaTrackReceiver,isEnabled,isSwitchedOff,setPriority,setRenderHint,options){return _super.call(this,sid,mediaTrackReceiver,isEnabled,isSwitchedOff,setPriority,setRenderHint,options)||this}RemoteAudioTrack.prototype.toString=function(){return"[RemoteAudioTrack #"+this._instanceId+": "+this.sid+"]"};RemoteAudioTrack.prototype._start=function(){_super.prototype._start.call(this);if(this._dummyEl){this._dummyEl.srcObject=null;this._dummyEl=null}};RemoteAudioTrack.prototype.setPriority=function(priority){return _super.prototype.setPriority.call(this,priority)};return RemoteAudioTrack}(RemoteMediaAudioTrack);module.exports=RemoteAudioTrack},{"./audiotrack":13,"./remotemediatrack":34}],31:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var RemoteTrackPublication=require("./remotetrackpublication");var RemoteAudioTrackPublication=function(_super){__extends(RemoteAudioTrackPublication,_super);function RemoteAudioTrackPublication(signaling,options){return _super.call(this,signaling,options)||this}RemoteAudioTrackPublication.prototype.toString=function(){return"[RemoteAudioTrackPublication #"+this._instanceId+": "+this.trackSid+"]"};return RemoteAudioTrackPublication}(RemoteTrackPublication);module.exports=RemoteAudioTrackPublication},{"./remotetrackpublication":35}],32:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var __spreadArray=this&&this.__spreadArray||function(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to};var Track=require("./");var _a=require("../../util/constants"),E=_a.typeErrors,trackPriority=_a.trackPriority;var RemoteDataTrack=function(_super){__extends(RemoteDataTrack,_super);function RemoteDataTrack(sid,dataTrackReceiver,options){var _this=_super.call(this,dataTrackReceiver.id,"data",options)||this;Object.defineProperties(_this,{_isSwitchedOff:{value:false,writable:true},_priority:{value:null,writable:true},isEnabled:{enumerable:true,value:true},isSwitchedOff:{enumerable:true,get:function(){return this._isSwitchedOff}},maxPacketLifeTime:{enumerable:true,value:dataTrackReceiver.maxPacketLifeTime},maxRetransmits:{enumerable:true,value:dataTrackReceiver.maxRetransmits},ordered:{enumerable:true,value:dataTrackReceiver.ordered},priority:{enumerable:true,get:function(){return this._priority}},reliable:{enumerable:true,value:dataTrackReceiver.maxPacketLifeTime===null&&dataTrackReceiver.maxRetransmits===null},sid:{enumerable:true,value:sid}});dataTrackReceiver.on("message",function(data){_this.emit("message",data,_this)});return _this}RemoteDataTrack.prototype.setPriority=function(priority){var priorityValues=__spreadArray([null],__read(Object.values(trackPriority)));if(!priorityValues.includes(priority)){throw E.INVALID_VALUE("priority",priorityValues)}this._priority=priority;return this};RemoteDataTrack.prototype._setEnabled=function(){};RemoteDataTrack.prototype._setSwitchedOff=function(isSwitchedOff){if(this._isSwitchedOff!==isSwitchedOff){this._isSwitchedOff=isSwitchedOff;this.emit(isSwitchedOff?"switchedOff":"switchedOn",this)}};return RemoteDataTrack}(Track);module.exports=RemoteDataTrack},{"../../util/constants":124,"./":18}],
41
+ 33:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var RemoteTrackPublication=require("./remotetrackpublication");var RemoteDataTrackPublication=function(_super){__extends(RemoteDataTrackPublication,_super);function RemoteDataTrackPublication(signaling,options){return _super.call(this,signaling,options)||this}RemoteDataTrackPublication.prototype.toString=function(){return"[RemoteDataTrackPublication #"+this._instanceId+": "+this.trackSid+"]"};return RemoteDataTrackPublication}(RemoteTrackPublication);module.exports=RemoteDataTrackPublication},{"./remotetrackpublication":35}],34:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var __spreadArray=this&&this.__spreadArray||function(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to};var _a=require("../../util/constants"),E=_a.typeErrors,trackPriority=_a.trackPriority;var _b=require("../../webrtc/util"),guessBrowser=_b.guessBrowser,isIOSChrome=_b.isIOSChrome;var documentVisibilityMonitor=require("../../util/documentvisibilitymonitor.js");function mixinRemoteMediaTrack(AudioOrVideoTrack){return function(_super){__extends(RemoteMediaTrack,_super);function RemoteMediaTrack(sid,mediaTrackReceiver,isEnabled,isSwitchedOff,setPriority,setRenderHint,options){var _this=this;options=Object.assign({workaroundWebKitBug212780:(guessBrowser()==="safari"||isIOSChrome())&&typeof document==="object"&&typeof document.addEventListener==="function"&&typeof document.visibilityState==="string"},options);_this=_super.call(this,mediaTrackReceiver,options)||this;Object.defineProperties(_this,{_isEnabled:{value:isEnabled,writable:true},_isSwitchedOff:{value:isSwitchedOff,writable:true},_priority:{value:null,writable:true},_setPriority:{value:setPriority},_setRenderHint:{value:function(renderHint){_this._log.debug("updating render hint:",renderHint);setRenderHint(renderHint)}},isEnabled:{enumerable:true,get:function(){return this._isEnabled}},isSwitchedOff:{enumerable:true,get:function(){return this._isSwitchedOff}},priority:{enumerable:true,get:function(){return this._priority}},sid:{enumerable:true,value:sid},_workaroundWebKitBug212780:{value:options.workaroundWebKitBug212780},_workaroundWebKitBug212780Cleanup:{value:null,writable:true}});return _this}RemoteMediaTrack.prototype.setPriority=function(priority){var priorityValues=__spreadArray([null],__read(Object.values(trackPriority)));if(!priorityValues.includes(priority)){throw E.INVALID_VALUE("priority",priorityValues)}if(this._priority!==priority){this._priority=priority;this._setPriority(priority)}return this};RemoteMediaTrack.prototype._setEnabled=function(isEnabled){if(this._isEnabled!==isEnabled){this._isEnabled=isEnabled;this.emit(this._isEnabled?"enabled":"disabled",this)}};RemoteMediaTrack.prototype._setSwitchedOff=function(isSwitchedOff){if(this._isSwitchedOff!==isSwitchedOff){this._isSwitchedOff=isSwitchedOff;this.emit(isSwitchedOff?"switchedOff":"switchedOn",this)}};RemoteMediaTrack.prototype.attach=function(el){var result=_super.prototype.attach.call(this,el);if(this.mediaStreamTrack.enabled!==true){this.mediaStreamTrack.enabled=true;if(this.processedTrack){this.processedTrack.enabled=true}if(this.processor){this._captureFrames()}}if(this._workaroundWebKitBug212780){this._workaroundWebKitBug212780Cleanup=this._workaroundWebKitBug212780Cleanup||playIfPausedWhileInBackground(this)}return result};RemoteMediaTrack.prototype.detach=function(el){var result=_super.prototype.detach.call(this,el);if(this._attachments.size===0){this.mediaStreamTrack.enabled=false;if(this.processedTrack){this.processedTrack.enabled=false}if(this._workaroundWebKitBug212780Cleanup){this._workaroundWebKitBug212780Cleanup();this._workaroundWebKitBug212780Cleanup=null}}return result};return RemoteMediaTrack}(AudioOrVideoTrack)}function playIfPausedWhileInBackground(remoteMediaTrack){var log=remoteMediaTrack._log,kind=remoteMediaTrack.kind;function onVisibilityChanged(isVisible){if(!isVisible){return}remoteMediaTrack._attachments.forEach(function(el){var shim=remoteMediaTrack._elShims.get(el);var isInadvertentlyPaused=el.paused&&shim&&!shim.pausedIntentionally();if(isInadvertentlyPaused){log.info("Playing inadvertently paused <"+kind+"> element");log.debug("Element:",el);log.debug("RemoteMediaTrack:",remoteMediaTrack);el.play().then(function(){log.info("Successfully played inadvertently paused <"+kind+"> element");log.debug("Element:",el);log.debug("RemoteMediaTrack:",remoteMediaTrack)}).catch(function(err){log.warn("Error while playing inadvertently paused <"+kind+"> element:",{err:err,el:el,remoteMediaTrack:remoteMediaTrack})})}})}documentVisibilityMonitor.onVisibilityChange(2,onVisibilityChanged);return function(){documentVisibilityMonitor.offVisibilityChange(2,onVisibilityChanged)}}module.exports=mixinRemoteMediaTrack},{"../../util/constants":124,"../../util/documentvisibilitymonitor.js":127,"../../webrtc/util":170}],35:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var TrackPublication=require("./trackpublication");var RemoteTrackPublication=function(_super){__extends(RemoteTrackPublication,_super);function RemoteTrackPublication(signaling,options){var _this=_super.call(this,signaling.name,signaling.sid,options)||this;Object.defineProperties(_this,{_signaling:{value:signaling},_track:{value:null,writable:true},isSubscribed:{enumerable:true,get:function(){return!!this._track}},isTrackEnabled:{enumerable:true,get:function(){return signaling.isEnabled}},kind:{enumerable:true,value:signaling.kind},publishPriority:{enumerable:true,get:function(){return signaling.priority}},track:{enumerable:true,get:function(){return this._track}}});var error=signaling.error,isEnabled=signaling.isEnabled,isSwitchedOff=signaling.isSwitchedOff,priority=signaling.priority;signaling.on("updated",function(){if(error!==signaling.error){error=signaling.error;_this.emit("subscriptionFailed",signaling.error);return}if(isEnabled!==signaling.isEnabled){isEnabled=signaling.isEnabled;if(_this.track){_this.track._setEnabled(signaling.isEnabled)}_this.emit(signaling.isEnabled?"trackEnabled":"trackDisabled")}if(isSwitchedOff!==signaling.isSwitchedOff){_this._log.debug(_this.trackSid+": "+(isSwitchedOff?"OFF":"ON")+" => "+(signaling.isSwitchedOff?"OFF":"ON"));isSwitchedOff=signaling.isSwitchedOff;if(_this.track){_this.track._setSwitchedOff(signaling.isSwitchedOff);_this.emit(isSwitchedOff?"trackSwitchedOff":"trackSwitchedOn",_this.track)}else if(isSwitchedOff){_this._log.warn("Track was not subscribed when switched Off.")}}if(priority!==signaling.priority){priority=signaling.priority;_this.emit("publishPriorityChanged",priority)}});return _this}RemoteTrackPublication.prototype.toString=function(){return"[RemoteTrackPublication #"+this._instanceId+": "+this.trackSid+"]"};RemoteTrackPublication.prototype._subscribed=function(track){if(!this._track&&track){this._track=track;this.emit("subscribed",track)}};RemoteTrackPublication.prototype._unsubscribe=function(){if(this._track){var track=this._track;this._track=null;this.emit("unsubscribed",track)}};return RemoteTrackPublication}(TrackPublication);module.exports=RemoteTrackPublication},{"./trackpublication":39}],36:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var mixinRemoteMediaTrack=require("./remotemediatrack");var VideoTrack=require("./videotrack");var documentVisibilityMonitor=require("../../util/documentvisibilitymonitor.js");var NullObserver=require("../../util/nullobserver.js").NullObserver;var Timeout=require("../../util/timeout");var RemoteMediaVideoTrack=mixinRemoteMediaTrack(VideoTrack);var TRACK_TURN_OF_DELAY_MS=50;var RemoteVideoTrack=function(_super){__extends(RemoteVideoTrack,_super);function RemoteVideoTrack(sid,mediaTrackReceiver,isEnabled,isSwitchedOff,setPriority,setRenderHint,options){var _this=this;options=Object.assign({clientTrackSwitchOffControl:"auto",contentPreferencesMode:"auto",enableDocumentVisibilityTurnOff:true},options);options=Object.assign({IntersectionObserver:typeof IntersectionObserver==="undefined"||options.clientTrackSwitchOffControl!=="auto"?NullObserver:IntersectionObserver,ResizeObserver:typeof ResizeObserver==="undefined"||options.contentPreferencesMode!=="auto"?NullObserver:ResizeObserver},options);_this=_super.call(this,sid,mediaTrackReceiver,isEnabled,isSwitchedOff,setPriority,setRenderHint,options)||this;Object.defineProperties(_this,{_enableDocumentVisibilityTurnOff:{value:options.enableDocumentVisibilityTurnOff===true&&options.clientTrackSwitchOffControl==="auto"},_documentVisibilityTurnOffCleanup:{value:null,writable:true},_clientTrackSwitchOffControl:{value:options.clientTrackSwitchOffControl},_contentPreferencesMode:{value:options.contentPreferencesMode},_invisibleElements:{value:new WeakSet},_elToPipCallbacks:{value:new WeakMap},_elToPipWindows:{value:new WeakMap},_turnOffTimer:{value:new Timeout(function(){_this._setRenderHint({enabled:false})},TRACK_TURN_OF_DELAY_MS,false)},_resizeObserver:{value:new options.ResizeObserver(function(entries){var visibleElementResized=entries.find(function(entry){return!_this._invisibleElements.has(entry.target)});if(visibleElementResized){maybeUpdateDimensionHint(_this)}})},_intersectionObserver:{value:new options.IntersectionObserver(function(entries){var shouldSetRenderHint=false;entries.forEach(function(entry){var wasVisible=!_this._invisibleElements.has(entry.target);if(wasVisible!==entry.isIntersecting){if(entry.isIntersecting){_this._log.debug("intersectionObserver detected: Off => On");_this._invisibleElements.delete(entry.target)}else{_this._log.debug("intersectionObserver detected: On => Off");_this._invisibleElements.add(entry.target)}shouldSetRenderHint=true}});if(shouldSetRenderHint){maybeUpdateEnabledHint(_this);maybeUpdateDimensionHint(_this)}},{threshold:.25})}});return _this}RemoteVideoTrack.prototype._start=function(dummyEl){var result=_super.prototype._start.call(this,dummyEl);maybeUpdateEnabledHint(this);return result};RemoteVideoTrack.prototype.switchOn=function(){if(this._clientTrackSwitchOffControl!=="manual"){throw new Error('Invalid state. You can call switchOn only when bandwidthProfile.video.clientTrackSwitchOffControl is set to "manual"')}this._setRenderHint({enabled:true});return this};RemoteVideoTrack.prototype.switchOff=function(){if(this._clientTrackSwitchOffControl!=="manual"){throw new Error('Invalid state. You can call switchOff only when bandwidthProfile.video.clientTrackSwitchOffControl is set to "manual"')}this._setRenderHint({enabled:false});return this};RemoteVideoTrack.prototype.setContentPreferences=function(contentPreferences){if(this._contentPreferencesMode!=="manual"){throw new Error('Invalid state. You can call switchOn only when bandwidthProfile.video.contentPreferencesMode is set to "manual"')}if(contentPreferences.renderDimensions){this._setRenderHint({renderDimensions:contentPreferences.renderDimensions})}return this};RemoteVideoTrack.prototype._unObservePip=function(el){var pipCallbacks=this._elToPipCallbacks.get(el);if(pipCallbacks){el.removeEventListener("enterpictureinpicture",pipCallbacks.onEnterPip);el.removeEventListener("leavepictureinpicture",pipCallbacks.onLeavePip);this._elToPipCallbacks.delete(el)}};RemoteVideoTrack.prototype._observePip=function(el){var _this=this;var pipCallbacks=this._elToPipCallbacks.get(el);if(!pipCallbacks){var onEnterPip=function(event){return _this._onEnterPip(event,el)};var onLeavePip=function(event){return _this._onLeavePip(event,el)};var onResizePip=function(event){return _this._onResizePip(event,el)};el.addEventListener("enterpictureinpicture",onEnterPip);el.addEventListener("leavepictureinpicture",onLeavePip);this._elToPipCallbacks.set(el,{onEnterPip:onEnterPip,onLeavePip:onLeavePip,onResizePip:onResizePip})}};RemoteVideoTrack.prototype._onEnterPip=function(event,videoEl){this._log.debug("onEnterPip");var pipWindow=event.pictureInPictureWindow;this._elToPipWindows.set(videoEl,pipWindow);var onResizePip=this._elToPipCallbacks.get(videoEl).onResizePip;pipWindow.addEventListener("resize",onResizePip);maybeUpdateEnabledHint(this)};RemoteVideoTrack.prototype._onLeavePip=function(event,videoEl){this._log.debug("onLeavePip");this._elToPipWindows.delete(videoEl);var onResizePip=this._elToPipCallbacks.get(videoEl).onResizePip;var pipWindow=event.pictureInPictureWindow;pipWindow.removeEventListener("resize",onResizePip);maybeUpdateEnabledHint(this)};RemoteVideoTrack.prototype._onResizePip=function(){maybeUpdateDimensionHint(this)};RemoteVideoTrack.prototype.attach=function(el){var result=_super.prototype.attach.call(this,el);if(this._clientTrackSwitchOffControl==="auto"){this._invisibleElements.add(result)}this._intersectionObserver.observe(result);this._resizeObserver.observe(result);if(this._enableDocumentVisibilityTurnOff){this._documentVisibilityTurnOffCleanup=this._documentVisibilityTurnOffCleanup||setupDocumentVisibilityTurnOff(this)}this._observePip(result);return result};RemoteVideoTrack.prototype.detach=function(el){var _this=this;var result=_super.prototype.detach.call(this,el);var elements=Array.isArray(result)?result:[result];elements.forEach(function(element){_this._intersectionObserver.unobserve(element);_this._resizeObserver.unobserve(element);_this._invisibleElements.delete(element);_this._unObservePip(element)});if(this._attachments.size===0){if(this._documentVisibilityTurnOffCleanup){this._documentVisibilityTurnOffCleanup();this._documentVisibilityTurnOffCleanup=null}}maybeUpdateEnabledHint(this);maybeUpdateDimensionHint(this);return result};RemoteVideoTrack.prototype.addProcessor=function(){return _super.prototype.addProcessor.apply(this,arguments)};RemoteVideoTrack.prototype.removeProcessor=function(){return _super.prototype.removeProcessor.apply(this,arguments)};RemoteVideoTrack.prototype.toString=function(){return"[RemoteVideoTrack #"+this._instanceId+": "+this.sid+"]"};RemoteVideoTrack.prototype.setPriority=function(priority){return _super.prototype.setPriority.call(this,priority)};return RemoteVideoTrack}(RemoteMediaVideoTrack);function setupDocumentVisibilityTurnOff(removeVideoTrack){function onVisibilityChanged(){maybeUpdateEnabledHint(removeVideoTrack)}documentVisibilityMonitor.onVisibilityChange(1,onVisibilityChanged);return function(){documentVisibilityMonitor.offVisibilityChange(1,onVisibilityChanged)}}function maybeUpdateEnabledHint(remoteVideoTrack){if(remoteVideoTrack._clientTrackSwitchOffControl!=="auto"){return}var visibleElements=remoteVideoTrack._getAllAttachedElements().filter(function(el){return!remoteVideoTrack._invisibleElements.has(el)});var pipWindows=remoteVideoTrack._getAllAttachedElements().filter(function(el){return remoteVideoTrack._elToPipWindows.has(el)});var enabled=pipWindows.length>0||document.visibilityState==="visible"&&visibleElements.length>0;if(enabled===true){remoteVideoTrack._turnOffTimer.clear();remoteVideoTrack._setRenderHint({enabled:true})}else if(!remoteVideoTrack._turnOffTimer.isSet){remoteVideoTrack._turnOffTimer.start()}}function maybeUpdateDimensionHint(remoteVideoTrack){if(remoteVideoTrack._contentPreferencesMode!=="auto"){return}var visibleElements=remoteVideoTrack._getAllAttachedElements().filter(function(el){return!remoteVideoTrack._invisibleElements.has(el)});var pipElements=remoteVideoTrack._getAllAttachedElements().map(function(el){var pipWindow=remoteVideoTrack._elToPipWindows.get(el);return pipWindow?{clientHeight:pipWindow.height,clientWidth:pipWindow.width}:{clientHeight:0,clientWidth:0}});var totalElements=visibleElements.concat(pipElements);if(totalElements.length>0){var _a=__read(totalElements.sort(function(el1,el2){return el2.clientHeight+el2.clientWidth-el1.clientHeight-el1.clientWidth-1}),1),_b=_a[0],clientHeight=_b.clientHeight,clientWidth=_b.clientWidth;var renderDimensions={height:clientHeight,width:clientWidth};remoteVideoTrack._setRenderHint({renderDimensions:renderDimensions})}}module.exports=RemoteVideoTrack},{"../../util/documentvisibilitymonitor.js":127,"../../util/nullobserver.js":138,"../../util/timeout":145,"./remotemediatrack":34,"./videotrack":42}],37:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var RemoteTrackPublication=require("./remotetrackpublication");var RemoteVideoTrackPublication=function(_super){__extends(RemoteVideoTrackPublication,_super);function RemoteVideoTrackPublication(signaling,options){return _super.call(this,signaling,options)||this}RemoteVideoTrackPublication.prototype.toString=function(){return"[RemoteVideoTrackPublication #"+this._instanceId+": "+this.trackSid+"]"};return RemoteVideoTrackPublication}(RemoteTrackPublication);module.exports=RemoteVideoTrackPublication},{"./remotetrackpublication":35}],38:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var MediaTrackTransceiver=require("./transceiver");var MediaTrackSender=function(_super){__extends(MediaTrackSender,_super);function MediaTrackSender(mediaStreamTrack){var _this=_super.call(this,mediaStreamTrack.id,mediaStreamTrack)||this;Object.defineProperties(_this,{_clones:{value:new Set},_senders:{value:new Set},_senderToPublisherHintCallbacks:{value:new Map},isPublishing:{get:function(){return!!this._clones.size}}});return _this}MediaTrackSender.prototype.clone=function(){var clone=new MediaTrackSender(this.track.clone());this._clones.add(clone);return clone};MediaTrackSender.prototype.removeClone=function(clone){this._clones.delete(clone)};MediaTrackSender.prototype.setMediaStreamTrack=function(mediaStreamTrack){var _this=this;var clones=Array.from(this._clones);var senders=Array.from(this._senders);return Promise.all(clones.map(function(clone){return clone.setMediaStreamTrack(mediaStreamTrack.clone())}).concat(senders.map(function(sender){return _this._replaceTrack(sender,mediaStreamTrack)}))).finally(function(){_this._track=mediaStreamTrack})};MediaTrackSender.prototype.addSender=function(sender,publisherHintCallback){this._senders.add(sender);if(publisherHintCallback){this._senderToPublisherHintCallbacks.set(sender,publisherHintCallback)}return this};MediaTrackSender.prototype.removeSender=function(sender){this._senders.delete(sender);this._senderToPublisherHintCallbacks.delete(sender);return this};MediaTrackSender.prototype.setPublisherHint=function(encodings){var _a=__read(Array.from(this._senderToPublisherHintCallbacks.values()),1),publisherHintCallback=_a[0];return publisherHintCallback?publisherHintCallback(encodings):Promise.resolve("COULD_NOT_APPLY_HINT")};MediaTrackSender.prototype._replaceTrack=function(sender,mediaStreamTrack){var _this=this;return sender.replaceTrack(mediaStreamTrack).then(function(replaceTrackResult){_this.setPublisherHint(null).catch(function(){});_this.emit("replaced");return replaceTrackResult})};return MediaTrackSender}(MediaTrackTransceiver);module.exports=MediaTrackSender},{"./transceiver":40}],39:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var EventEmitter=require("../../eventemitter");var _a=require("../../util"),buildLogLevels=_a.buildLogLevels,valueToJSON=_a.valueToJSON;var DEFAULT_LOG_LEVEL=require("../../util/constants").DEFAULT_LOG_LEVEL;var Log=require("../../util/log");var nInstances=0;var TrackPublication=function(_super){__extends(TrackPublication,_super);function TrackPublication(trackName,trackSid,options){var _this=_super.call(this)||this;options=Object.assign({logLevel:DEFAULT_LOG_LEVEL},options);var logLevels=buildLogLevels(options.logLevel);Object.defineProperties(_this,{_instanceId:{value:nInstances++},_log:{value:options.log?options.log.createLog("default",_this):new Log("default",_this,logLevels,options.loggerName)},trackName:{enumerable:true,value:trackName},trackSid:{enumerable:true,value:trackSid}});return _this}TrackPublication.prototype.toJSON=function(){return valueToJSON(this)};TrackPublication.prototype.toString=function(){return"[TrackPublication #"+this._instanceId+": "+this.trackSid+"]"};return TrackPublication}(EventEmitter);module.exports=TrackPublication},{"../../eventemitter":10,"../../util":131,"../../util/constants":124,"../../util/log":135}],40:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var TrackTransceiver=require("../../transceiver");var MediaTrackTransceiver=function(_super){__extends(MediaTrackTransceiver,_super);function MediaTrackTransceiver(id,mediaStreamTrack){var _this=_super.call(this,id,mediaStreamTrack.kind)||this;Object.defineProperties(_this,{_track:{value:mediaStreamTrack,writable:true},enabled:{enumerable:true,get:function(){return this._track.enabled}},readyState:{enumerable:true,get:function(){return this._track.readyState}},track:{enumerable:true,get:function(){return this._track}}});return _this}MediaTrackTransceiver.prototype.stop=function(){this.track.stop();_super.prototype.stop.call(this)};return MediaTrackTransceiver}(TrackTransceiver);module.exports=MediaTrackTransceiver},{"../../transceiver":118}],41:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var EventEmitter=require("events").EventEmitter;var DEFAULT_VIDEO_PROCESSOR_STATS_INTERVAL_MS=require("../../util/constants").DEFAULT_VIDEO_PROCESSOR_STATS_INTERVAL_MS;var VideoProcessorEventObserver=function(_super){__extends(VideoProcessorEventObserver,_super);function VideoProcessorEventObserver(log){var _this=_super.call(this)||this;Object.defineProperties(_this,{_lastStatsSaveTime:{value:null,writable:true},_lastStatsPublishTime:{value:null,writable:true},_log:{value:log},_processorInfo:{value:null,writable:true},_stats:{value:null,writable:true}});_this.on("add",function(info){_this._lastStatsSaveTime=Date.now();_this._lastStatsPublishTime=Date.now();_this._processorInfo=info;_this._stats=[];_this._reemitEvent("add",_this._getEventData())});_this.on("remove",function(){var data=_this._getEventData();_this._lastStatsSaveTime=null;_this._lastStatsPublishTime=null;_this._processorInfo=null;_this._stats=null;_this._reemitEvent("remove",data)});_this.on("start",function(){_this._reemitEvent("start",_this._getEventData())});_this.on("stop",function(message){_this._reemitEvent("stop",Object.assign({message:message},_this._getEventData()))});_this.on("stats",function(){return _this._maybeEmitStats()});return _this}VideoProcessorEventObserver.prototype._getEventData=function(){if(!this._processorInfo){return{}}var _a=this._processorInfo,processor=_a.processor,captureHeight=_a.captureHeight,captureWidth=_a.captureWidth,inputFrameRate=_a.inputFrameRate,isRemoteVideoTrack=_a.isRemoteVideoTrack;var data={captureHeight:captureHeight,captureWidth:captureWidth,inputFrameRate:inputFrameRate,isRemoteVideoTrack:isRemoteVideoTrack};data.name=processor._name||"VideoProcessor";["assetsPath","blurFilterRadius","fitType","isSimdEnabled","maskBlurRadius","version"].forEach(function(prop){var val=processor["_"+prop];if(typeof val!=="undefined"){data[prop]=val}});Object.keys(data).forEach(function(prop){var val=data[prop];if(typeof val==="boolean"){data[prop]=val?"true":"false"}});return data};VideoProcessorEventObserver.prototype._maybeEmitStats=function(){if(!this._stats||!this._processorInfo){return}var benchmark=this._processorInfo.processor._benchmark;if(!benchmark){return}var now=Date.now();if(now-this._lastStatsSaveTime<1e3){return}var entry={outputFrameRate:benchmark.getRate("totalProcessingDelay")};["captureFrameDelay","imageCompositionDelay","inputImageResizeDelay","processFrameDelay","segmentationDelay"].forEach(function(name){entry[name]=benchmark.getAverageDelay(name)});this._lastStatsSaveTime=now;this._stats.push(entry);if(now-this._lastStatsPublishTime<DEFAULT_VIDEO_PROCESSOR_STATS_INTERVAL_MS){return}this._lastStatsPublishTime=now;var stats=this._stats.splice(0);var averages=stats.reduce(function(averages,current,n){Object.keys(entry).forEach(function(name){if(!averages[name]){averages[name]=0}averages[name]=(averages[name]*n+current[name])/(n+1)});return averages},{});Object.keys(averages).forEach(function(name){averages[name]=parseFloat(averages[name].toFixed(2))});this._reemitEvent("stats",Object.assign({},averages,this._getEventData()))};VideoProcessorEventObserver.prototype._reemitEvent=function(name,data){this._log.debug("VideoProcessor:"+name,data);this.emit("event",{name:name,data:data})};return VideoProcessorEventObserver}(EventEmitter);module.exports=VideoProcessorEventObserver},{"../../util/constants":124,events:173}],42:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var MediaTrack=require("./mediatrack");var VideoProcessorEventObserver=require("./videoprocessoreventobserver");var DEFAULT_FRAME_RATE=require("../../util/constants").DEFAULT_FRAME_RATE;var VideoTrack=function(_super){__extends(VideoTrack,_super);function VideoTrack(mediaTrackTransceiver,options){var _this=_super.call(this,mediaTrackTransceiver,options)||this;Object.defineProperties(_this,{_captureTimeoutId:{value:null,writable:true},_isCapturing:{value:false,writable:true},_inputFrame:{value:null,writable:true},_outputFrame:{value:null,writable:true},_processorEventObserver:{value:null,writable:true},_unmuteHandler:{value:null,writable:true},dimensions:{enumerable:true,value:{width:null,height:null}},processor:{enumerable:true,value:null,writable:true}});_this._processorEventObserver=new(options.VideoProcessorEventObserver||VideoProcessorEventObserver)(_this._log);return _this}VideoTrack.prototype._checkIfCanCaptureFrames=function(isPublishing){if(isPublishing===void 0){isPublishing=false}var canCaptureFrames=true;var message="";var _a=this.mediaStreamTrack,enabled=_a.enabled,readyState=_a.readyState;if(!enabled){canCaptureFrames=false
42
+ ;message="MediaStreamTrack is disabled"}if(readyState==="ended"){canCaptureFrames=false;message="MediaStreamTrack is ended"}if(!this.processor){canCaptureFrames=false;message="VideoProcessor not detected."}if(!this._attachments.size&&!isPublishing){canCaptureFrames=false;message="VideoTrack is not publishing and there is no attached element."}if(message){this._log.debug(message)}return{canCaptureFrames:canCaptureFrames,message:message}};VideoTrack.prototype._captureFrames=function(){var _this=this;if(this._isCapturing){this._log.debug("Ignoring captureFrames call. Capture is already in progress");return}if(!this._checkIfCanCaptureFrames().canCaptureFrames){this._isCapturing=false;this._log.debug("Cannot capture frames. Ignoring captureFrames call.");return}this._isCapturing=true;this._processorEventObserver.emit("start");this._log.debug("Start capturing frames");var startTime=Date.now();var processFramePeriodMs;this._dummyEl.play().then(function(){var captureFrame=function(cb){clearTimeout(_this._captureTimeoutId);var _a=_this.mediaStreamTrack.getSettings().frameRate,frameRate=_a===void 0?DEFAULT_FRAME_RATE:_a;var capturePeriodMs=Math.floor(1e3/frameRate);var delay=capturePeriodMs-processFramePeriodMs;if(delay<0||typeof processFramePeriodMs!=="number"){delay=0}_this._captureTimeoutId=setTimeout(cb,delay)};var process=function(){var checkResult=_this._checkIfCanCaptureFrames();if(!checkResult.canCaptureFrames){_this._isCapturing=false;_this._processorEventObserver.emit("stop",checkResult.message);_this._log.debug("Cannot capture frames. Stopping capturing frames.");return}startTime=Date.now();var _a=_this.mediaStreamTrack.getSettings(),_b=_a.width,width=_b===void 0?0:_b,_c=_a.height,height=_c===void 0?0:_c;if(_this._inputFrame.width!==width){_this._inputFrame.width=width;_this._inputFrame.height=height;if(_this._outputFrame){_this._outputFrame.width=width;_this._outputFrame.height=height}}_this._inputFrame.getContext("2d").drawImage(_this._dummyEl,0,0,width,height);var result=null;try{result=_this.processor.processFrame(_this._inputFrame,_this._outputFrame)}catch(ex){_this._log.debug("Exception detected after calling processFrame.",ex)}(result instanceof Promise?result:Promise.resolve(result)).then(function(){if(_this._outputFrame){_this.processedTrack.requestFrame();_this._processorEventObserver.emit("stats")}}).finally(function(){processFramePeriodMs=Date.now()-startTime;captureFrame(process)})};captureFrame(process)}).catch(function(error){return _this._log.error("Video element cannot be played",{error:error,track:_this})})};VideoTrack.prototype._initialize=function(){var _this=this;_super.prototype._initialize.call(this);if(this._dummyEl){this._dummyEl.onloadedmetadata=function(){if(dimensionsChanged(_this,_this._dummyEl)){_this.dimensions.width=_this._dummyEl.videoWidth;_this.dimensions.height=_this._dummyEl.videoHeight}};this._dummyEl.onresize=function(){if(dimensionsChanged(_this,_this._dummyEl)){_this.dimensions.width=_this._dummyEl.videoWidth;_this.dimensions.height=_this._dummyEl.videoHeight;if(_this.isStarted){_this._log.debug("Dimensions changed:",_this.dimensions);_this.emit(VideoTrack.DIMENSIONS_CHANGED,_this)}}}}};VideoTrack.prototype._restartProcessor=function(){var processor=this.processor;if(processor){this.removeProcessor(processor);this.addProcessor(processor)}};VideoTrack.prototype._start=function(dummyEl){this.dimensions.width=dummyEl.videoWidth;this.dimensions.height=dummyEl.videoHeight;this._log.debug("Dimensions:",this.dimensions);this.emit(VideoTrack.DIMENSIONS_CHANGED,this);return _super.prototype._start.call(this,dummyEl)};VideoTrack.prototype.addProcessor=function(processor){var _this=this;if(typeof OffscreenCanvas!=="function"){return this._log.warn("Adding a VideoProcessor is not supported in this browser.")}if(!processor||typeof processor.processFrame!=="function"){throw new Error("Received an invalid VideoProcessor from addProcessor.")}if(this.processor){throw new Error("A VideoProcessor has already been added.")}if(!this._dummyEl){throw new Error("VideoTrack has not been initialized.")}this._log.debug("Adding VideoProcessor to the VideoTrack",processor);if(!this._unmuteHandler){this._unmuteHandler=function(){_this._log.debug("mediaStreamTrack unmuted");if(_this.processedTrack.muted){_this._log.debug("mediaStreamTrack is unmuted but processedTrack is muted. Restarting processor.");_this._restartProcessor()}};this.mediaStreamTrack.addEventListener("unmute",this._unmuteHandler)}var _a=this.mediaStreamTrack.getSettings(),_b=_a.width,width=_b===void 0?0:_b,_c=_a.height,height=_c===void 0?0:_c,_d=_a.frameRate,frameRate=_d===void 0?DEFAULT_FRAME_RATE:_d;this._inputFrame=new OffscreenCanvas(width,height);this._outputFrame=document.createElement("canvas");this._outputFrame.width=width;this._outputFrame.height=height;this.processedTrack=this._outputFrame.captureStream(0).getTracks()[0];this.processedTrack.enabled=this.mediaStreamTrack.enabled;this.processor=processor;this._processorEventObserver.emit("add",{processor:processor,captureHeight:height,captureWidth:width,inputFrameRate:frameRate,isRemoteVideoTrack:this.toString().includes("RemoteVideoTrack")});this._updateElementsMediaStreamTrack();this._captureFrames();return this};VideoTrack.prototype.attach=function(){var result=_super.prototype.attach.apply(this,arguments);if(this.processor){this._captureFrames()}return result};VideoTrack.prototype.detach=function(){return _super.prototype.detach.apply(this,arguments)};VideoTrack.prototype.removeProcessor=function(processor){if(!processor){throw new Error("Received an invalid VideoProcessor from removeProcessor.")}if(!this.processor){throw new Error("No existing VideoProcessor detected.")}if(processor!==this.processor){throw new Error("The provided VideoProcessor is different than the existing one.")}this._processorEventObserver.emit("remove");this._log.debug("Removing VideoProcessor from the VideoTrack",processor);clearTimeout(this._captureTimeoutId);this.mediaStreamTrack.removeEventListener("unmute",this._unmuteHandler);this._unmuteHandler=null;this._isCapturing=false;this.processor=null;this.processedTrack=null;this._inputFrame.getContext("2d").clearRect(0,0,this._inputFrame.width,this._inputFrame.height);this._outputFrame.getContext("2d").clearRect(0,0,this._outputFrame.width,this._outputFrame.height);this._inputFrame=null;this._outputFrame=null;this._updateElementsMediaStreamTrack();return this};return VideoTrack}(MediaTrack);VideoTrack.DIMENSIONS_CHANGED="dimensionsChanged";function dimensionsChanged(track,elem){return track.dimensions.width!==elem.videoWidth||track.dimensions.height!==elem.videoHeight}module.exports=VideoTrack},{"../../util/constants":124,"./mediatrack":27,"./videoprocessoreventobserver":41}],43:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var EventEmitter=require("events").EventEmitter;var _a=require("./util/constants"),DEFAULT_NQ_LEVEL_LOCAL=_a.DEFAULT_NQ_LEVEL_LOCAL,DEFAULT_NQ_LEVEL_REMOTE=_a.DEFAULT_NQ_LEVEL_REMOTE,MAX_NQ_LEVEL=_a.MAX_NQ_LEVEL;var inRange=require("./util").inRange;var NetworkQualityConfigurationImpl=function(_super){__extends(NetworkQualityConfigurationImpl,_super);function NetworkQualityConfigurationImpl(networkQualityConfiguration){var _this=_super.call(this)||this;networkQualityConfiguration=Object.assign({local:DEFAULT_NQ_LEVEL_LOCAL,remote:DEFAULT_NQ_LEVEL_REMOTE},networkQualityConfiguration);Object.defineProperties(_this,{local:{value:inRange(networkQualityConfiguration.local,DEFAULT_NQ_LEVEL_LOCAL,MAX_NQ_LEVEL)?networkQualityConfiguration.local:DEFAULT_NQ_LEVEL_LOCAL,writable:true},remote:{value:inRange(networkQualityConfiguration.remote,DEFAULT_NQ_LEVEL_REMOTE,MAX_NQ_LEVEL)?networkQualityConfiguration.remote:DEFAULT_NQ_LEVEL_REMOTE,writable:true}});return _this}NetworkQualityConfigurationImpl.prototype.update=function(networkQualityConfiguration){var _this=this;networkQualityConfiguration=Object.assign({local:this.local,remote:this.remote},networkQualityConfiguration);[["local",DEFAULT_NQ_LEVEL_LOCAL,3],["remote",DEFAULT_NQ_LEVEL_REMOTE,3]].forEach(function(_a){var _b=__read(_a,3),localOrRemote=_b[0],min=_b[1],max=_b[2];_this[localOrRemote]=typeof networkQualityConfiguration[localOrRemote]==="number"&&inRange(networkQualityConfiguration[localOrRemote],min,max)?networkQualityConfiguration[localOrRemote]:min})};return NetworkQualityConfigurationImpl}(EventEmitter);module.exports=NetworkQualityConfigurationImpl},{"./util":131,"./util/constants":124,events:173}],44:[function(require,module,exports){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};Object.defineProperty(exports,"__esModule",{value:true});exports.createNoiseCancellationAudioProcessor=void 0;var dynamicImport=require("./util/dynamicimport");var Log=require("./util/log");var PLUGIN_CONFIG={krisp:{supportedVersion:"1.0.0",pluginFile:"krispsdk.mjs"},rnnoise:{supportedVersion:"0.6.0",pluginFile:"rnnoise_sdk.mjs"}};var ensureVersionSupported=function(_a){var supportedVersion=_a.supportedVersion,plugin=_a.plugin,log=_a.log;if(!plugin.getVersion||!plugin.isSupported){throw new Error("Plugin does not export getVersion/isSupported api. Are you using old version of the plugin ?")}var pluginVersion=plugin.getVersion();log.debug("Plugin Version = "+pluginVersion);var supportedVersions=supportedVersion.split(".").map(function(version){return Number(version)});var pluginVersions=pluginVersion.split(".").map(function(version){return Number(version)});if(supportedVersions.length!==3||pluginVersions.length!==3){throw new Error("Unsupported Plugin version format: "+supportedVersion+", "+pluginVersion)}if(supportedVersions[0]!==pluginVersions[0]){throw new Error("Major version mismatch: [Plugin version "+pluginVersion+"], [Supported Version "+supportedVersion+"]")}if(pluginVersions[1]<supportedVersions[1]){throw new Error("Minor version mismatch: [Plugin version "+pluginVersion+"] < [Supported Version "+supportedVersion+"]")}var tempContext=new AudioContext;var isSupported=plugin.isSupported(tempContext);tempContext.close();if(!isSupported){throw new Error("Noise Cancellation plugin is not supported on your browser")}};var audioProcessors=new Map;function createNoiseCancellationAudioProcessor(noiseCancellationOptions,log){return __awaiter(this,void 0,void 0,function(){var audioProcessor,pluginConfig,supportedVersion,pluginFile,rootDir,sdkFilePath,dynamicModule,plugin_1,er_1;return __generator(this,function(_a){switch(_a.label){case 0:audioProcessor=audioProcessors.get(noiseCancellationOptions.vendor);if(!!audioProcessor)return[3,6];pluginConfig=PLUGIN_CONFIG[noiseCancellationOptions.vendor];if(!pluginConfig){throw new Error("Unsupported NoiseCancellationOptions.vendor: "+noiseCancellationOptions.vendor)}supportedVersion=pluginConfig.supportedVersion,pluginFile=pluginConfig.pluginFile;rootDir=noiseCancellationOptions.sdkAssetsPath;sdkFilePath=rootDir+"/"+pluginFile;_a.label=1;case 1:_a.trys.push([1,5,,6]);log.debug("loading noise cancellation sdk: ",sdkFilePath);return[4,dynamicImport(sdkFilePath)];case 2:dynamicModule=_a.sent();log.debug("Loaded noise cancellation sdk:",dynamicModule);plugin_1=dynamicModule.default;ensureVersionSupported({supportedVersion:supportedVersion,plugin:plugin_1,log:log});if(!!plugin_1.isInitialized())return[3,4];log.debug("initializing noise cancellation sdk: ",rootDir);return[4,plugin_1.init({rootDir:rootDir})];case 3:_a.sent();log.debug("noise cancellation sdk initialized!");_a.label=4;case 4:audioProcessor={vendor:noiseCancellationOptions.vendor,isInitialized:function(){return plugin_1.isInitialized()},isConnected:function(){return plugin_1.isConnected()},isEnabled:function(){return plugin_1.isEnabled()},disconnect:function(){return plugin_1.disconnect()},enable:function(){return plugin_1.enable()},disable:function(){return plugin_1.disable()},destroy:function(){return plugin_1.destroy()},setLogging:function(enable){return plugin_1.setLogging(enable)},connect:function(sourceTrack){log.debug("connect: ",sourceTrack.id);if(plugin_1.isConnected()){plugin_1.disconnect()}var mediaStream=plugin_1.connect(new MediaStream([sourceTrack]));if(!mediaStream){throw new Error("Error connecting with noise cancellation sdk")}var cleanTrack=mediaStream.getAudioTracks()[0];if(!cleanTrack){throw new Error("Error getting clean track from noise cancellation sdk")}plugin_1.enable();return cleanTrack}};audioProcessors.set(noiseCancellationOptions.vendor,audioProcessor);return[3,6];case 5:er_1=_a.sent();log.error("Error loading noise cancellation sdk:"+sdkFilePath,er_1);throw er_1;case 6:return[2,audioProcessor]}})})}exports.createNoiseCancellationAudioProcessor=createNoiseCancellationAudioProcessor},{"./util/dynamicimport":128,"./util/log":135}],45:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var __spreadArray=this&&this.__spreadArray||function(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to};var EventEmitter=require("./eventemitter");var RemoteAudioTrack=require("./media/track/remoteaudiotrack");var RemoteAudioTrackPublication=require("./media/track/remoteaudiotrackpublication");var RemoteDataTrack=require("./media/track/remotedatatrack");var RemoteDataTrackPublication=require("./media/track/remotedatatrackpublication");var RemoteVideoTrack=require("./media/track/remotevideotrack");var RemoteVideoTrackPublication=require("./media/track/remotevideotrackpublication");var util=require("./util");var nInstances=0;var Participant=function(_super){__extends(Participant,_super);function Participant(signaling,options){var _this=_super.call(this)||this;options=Object.assign({RemoteAudioTrack:RemoteAudioTrack,RemoteAudioTrackPublication:RemoteAudioTrackPublication,RemoteDataTrack:RemoteDataTrack,RemoteDataTrackPublication:RemoteDataTrackPublication,RemoteVideoTrack:RemoteVideoTrack,RemoteVideoTrackPublication:RemoteVideoTrackPublication,tracks:[]},options);var indexed=indexTracksById(options.tracks);var log=options.log.createLog("default",_this);var audioTracks=new Map(indexed.audioTracks);var dataTracks=new Map(indexed.dataTracks);var tracks=new Map(indexed.tracks);var videoTracks=new Map(indexed.videoTracks);Object.defineProperties(_this,{_RemoteAudioTrack:{value:options.RemoteAudioTrack},_RemoteAudioTrackPublication:{value:options.RemoteAudioTrackPublication},_RemoteDataTrack:{value:options.RemoteDataTrack},_RemoteDataTrackPublication:{value:options.RemoteDataTrackPublication},_RemoteVideoTrack:{value:options.RemoteVideoTrack},_RemoteVideoTrackPublication:{value:options.RemoteVideoTrackPublication},_audioTracks:{value:audioTracks},_dataTracks:{value:dataTracks},_instanceId:{value:++nInstances},_clientTrackSwitchOffControl:{value:options.clientTrackSwitchOffControl},_contentPreferencesMode:{value:options.contentPreferencesMode},_log:{value:log},_signaling:{value:signaling},_tracks:{value:tracks},_trackEventReemitters:{value:new Map},_trackPublicationEventReemitters:{value:new Map},_trackSignalingUpdatedEventCallbacks:{value:new Map},_videoTracks:{value:videoTracks},audioTracks:{enumerable:true,value:new Map},dataTracks:{enumerable:true,value:new Map},identity:{enumerable:true,get:function(){return signaling.identity}},networkQualityLevel:{enumerable:true,get:function(){return signaling.networkQualityLevel}},networkQualityStats:{enumerable:true,get:function(){return signaling.networkQualityStats}},sid:{enumerable:true,get:function(){return signaling.sid}},state:{enumerable:true,get:function(){return signaling.state}},tracks:{enumerable:true,value:new Map},videoTracks:{enumerable:true,value:new Map}});_this._tracks.forEach(reemitTrackEvents.bind(null,_this));signaling.on("networkQualityLevelChanged",function(){return _this.emit("networkQualityLevelChanged",_this.networkQualityLevel,_this.networkQualityStats&&(_this.networkQualityStats.audio||_this.networkQualityStats.video)?_this.networkQualityStats:null)});reemitSignalingStateChangedEvents(_this,signaling);log.info("Created a new Participant"+(_this.identity?": "+_this.identity:""));return _this}Participant.prototype._getTrackEvents=function(){return[["dimensionsChanged","trackDimensionsChanged"],["message","trackMessage"],["started","trackStarted"]]};Participant.prototype._getTrackPublicationEvents=function(){return[]};Participant.prototype.toString=function(){return"[Participant #"+this._instanceId+": "+this.sid+"]"};Participant.prototype._addTrack=function(track,id){var log=this._log;if(this._tracks.has(id)){return null}this._tracks.set(id,track);var tracksByKind={audio:this._audioTracks,video:this._videoTracks,data:this._dataTracks}[track.kind];tracksByKind.set(id,track);reemitTrackEvents(this,track,id);log.info("Added a new "+util.trackClass(track)+":",id);log.debug(util.trackClass(track)+":",track);return track};Participant.prototype._addTrackPublication=function(publication){var log=this._log;if(this.tracks.has(publication.trackSid)){return null}this.tracks.set(publication.trackSid,publication);var trackPublicationsByKind={audio:this.audioTracks,data:this.dataTracks,video:this.videoTracks}[publication.kind];trackPublicationsByKind.set(publication.trackSid,publication);reemitTrackPublicationEvents(this,publication);log.info("Added a new "+util.trackPublicationClass(publication)+":",publication.trackSid);log.debug(util.trackPublicationClass(publication)+":",publication);return publication};Participant.prototype._handleTrackSignalingEvents=function(){var _a=this,log=_a._log,clientTrackSwitchOffControl=_a._clientTrackSwitchOffControl,contentPreferencesMode=_a._contentPreferencesMode;var self=this;if(this.state==="disconnected"){return}var RemoteAudioTrack=this._RemoteAudioTrack;var RemoteAudioTrackPublication=this._RemoteAudioTrackPublication;var RemoteVideoTrack=this._RemoteVideoTrack;var RemoteVideoTrackPublication=this._RemoteVideoTrackPublication;var RemoteDataTrack=this._RemoteDataTrack;var RemoteDataTrackPublication=this._RemoteDataTrackPublication;var participantSignaling=this._signaling;function trackSignalingAdded(signaling){var RemoteTrackPublication={audio:RemoteAudioTrackPublication,data:RemoteDataTrackPublication,video:RemoteVideoTrackPublication}[signaling.kind];var publication=new RemoteTrackPublication(signaling,{log:log});self._addTrackPublication(publication);var isSubscribed=signaling.isSubscribed;if(isSubscribed){trackSignalingSubscribed(signaling)}self._trackSignalingUpdatedEventCallbacks.set(signaling.sid,function(){if(isSubscribed!==signaling.isSubscribed){isSubscribed=signaling.isSubscribed;if(isSubscribed){trackSignalingSubscribed(signaling);return}trackSignalingUnsubscribed(signaling)}});signaling.on("updated",self._trackSignalingUpdatedEventCallbacks.get(signaling.sid))}function trackSignalingRemoved(signaling){if(signaling.isSubscribed){signaling.setTrackTransceiver(null)}var updated=self._trackSignalingUpdatedEventCallbacks.get(signaling.sid);if(updated){signaling.removeListener("updated",updated);self._trackSignalingUpdatedEventCallbacks.delete(signaling.sid)}var publication=self.tracks.get(signaling.sid);if(publication){self._removeTrackPublication(publication)}}function trackSignalingSubscribed(signaling){var isEnabled=signaling.isEnabled,name=signaling.name,kind=signaling.kind,sid=signaling.sid,trackTransceiver=signaling.trackTransceiver,isSwitchedOff=signaling.isSwitchedOff;var RemoteTrack={audio:RemoteAudioTrack,video:RemoteVideoTrack,data:RemoteDataTrack}[kind];var publication=self.tracks.get(sid);if(!RemoteTrack||kind!==trackTransceiver.kind){return}var options={log:log,name:name,clientTrackSwitchOffControl:clientTrackSwitchOffControl,contentPreferencesMode:contentPreferencesMode};var setPriority=function(newPriority){return participantSignaling.updateSubscriberTrackPriority(sid,newPriority)};var setRenderHint=function(renderHint){if(signaling.isSubscribed){participantSignaling.updateTrackRenderHint(sid,renderHint)}};var track=kind==="data"?new RemoteTrack(sid,trackTransceiver,options):new RemoteTrack(sid,trackTransceiver,isEnabled,isSwitchedOff,setPriority,setRenderHint,options);self._addTrack(track,publication,trackTransceiver.id)}function trackSignalingUnsubscribed(signaling){var _a=__read(Array.from(self._tracks.entries()).find(function(_a){var _b=__read(_a,2),track=_b[1];return track.sid===signaling.sid}),2),id=_a[0],track=_a[1];var publication=self.tracks.get(signaling.sid);if(track){self._removeTrack(track,publication,id)}}participantSignaling.on("trackAdded",trackSignalingAdded);participantSignaling.on("trackRemoved",trackSignalingRemoved);participantSignaling.tracks.forEach(trackSignalingAdded);participantSignaling.on("stateChanged",function stateChanged(state){if(state==="disconnected"){log.debug("Removing event listeners");participantSignaling.removeListener("stateChanged",stateChanged);participantSignaling.removeListener("trackAdded",trackSignalingAdded);participantSignaling.removeListener("trackRemoved",trackSignalingRemoved)}else if(state==="connected"){log.info("reconnected");setTimeout(function(){return self.emit("reconnected")},0)}})};Participant.prototype._removeTrack=function(track,id){if(!this._tracks.has(id)){return null}this._tracks.delete(id);var tracksByKind={audio:this._audioTracks,video:this._videoTracks,data:this._dataTracks}[track.kind];tracksByKind.delete(id);var reemitters=this._trackEventReemitters.get(id)||new Map;reemitters.forEach(function(reemitter,event){track.removeListener(event,reemitter)});var log=this._log;log.info("Removed a "+util.trackClass(track)+":",id);log.debug(util.trackClass(track)+":",track);return track};Participant.prototype._removeTrackPublication=function(publication){publication=this.tracks.get(publication.trackSid);if(!publication){return null}this.tracks.delete(publication.trackSid);var trackPublicationsByKind={audio:this.audioTracks,data:this.dataTracks,video:this.videoTracks}[publication.kind];trackPublicationsByKind.delete(publication.trackSid);var reemitters=this._trackPublicationEventReemitters.get(publication.trackSid)||new Map;reemitters.forEach(function(reemitter,event){publication.removeListener(event,reemitter)});var log=this._log;log.info("Removed a "+util.trackPublicationClass(publication)+":",publication.trackSid);log.debug(util.trackPublicationClass(publication)+":",publication);return publication};Participant.prototype.toJSON=function(){return util.valueToJSON(this)};return Participant}(EventEmitter);function indexTracksById(tracks){var indexedTracks=tracks.map(function(track){return[track.id,track]});var indexedAudioTracks=indexedTracks.filter(function(keyValue){return keyValue[1].kind==="audio"});var indexedVideoTracks=indexedTracks.filter(function(keyValue){return keyValue[1].kind==="video"});var indexedDataTracks=indexedTracks.filter(function(keyValue){return keyValue[1].kind==="data"});return{audioTracks:indexedAudioTracks,dataTracks:indexedDataTracks,tracks:indexedTracks,videoTracks:indexedVideoTracks}}function reemitSignalingStateChangedEvents(participant,signaling){var log=participant._log;if(participant.state==="disconnected"){return}signaling.on("stateChanged",function stateChanged(state){log.debug("Transitioned to state:",state);participant.emit(state,participant);if(state==="disconnected"){log.debug("Removing Track event reemitters");signaling.removeListener("stateChanged",stateChanged);participant._tracks.forEach(function(track){var reemitters=participant._trackEventReemitters.get(track.id);if(track&&reemitters){reemitters.forEach(function(reemitter,event){track.removeListener(event,reemitter)})}});signaling.tracks.forEach(function(trackSignaling){var track=participant._tracks.get(trackSignaling.id);var reemitters=participant._trackEventReemitters.get(trackSignaling.id);if(track&&reemitters){reemitters.forEach(function(reemitter,event){track.removeListener(event,reemitter)})}});participant._trackEventReemitters.clear();participant.tracks.forEach(function(publication){participant._trackPublicationEventReemitters.get(publication.trackSid).forEach(function(reemitter,event){publication.removeListener(event,reemitter)})});participant._trackPublicationEventReemitters.clear()}})}function reemitTrackEvents(participant,track,id){var trackEventReemitters=new Map;if(participant.state==="disconnected"){return}participant._getTrackEvents().forEach(function(eventPair){var trackEvent=eventPair[0];var participantEvent=eventPair[1];trackEventReemitters.set(trackEvent,function(){var args=[participantEvent].concat([].slice.call(arguments));return participant.emit.apply(participant,__spreadArray([],__read(args)))});track.on(trackEvent,trackEventReemitters.get(trackEvent))});participant._trackEventReemitters.set(id,trackEventReemitters)}function reemitTrackPublicationEvents(participant,publication){var publicationEventReemitters=new Map;if(participant.state==="disconnected"){return}participant._getTrackPublicationEvents().forEach(function(_a){var _b=__read(_a,2),publicationEvent=_b[0],participantEvent=_b[1];publicationEventReemitters.set(publicationEvent,function(){var args=[];for(var _i=0;_i<arguments.length;_i++){args[_i]=arguments[_i]}participant.emit.apply(participant,__spreadArray(__spreadArray([participantEvent],__read(args)),[publication]))});publication.on(publicationEvent,publicationEventReemitters.get(publicationEvent))});participant._trackPublicationEventReemitters.set(publication.trackSid,publicationEventReemitters)}module.exports=Participant},{"./eventemitter":10,"./media/track/remoteaudiotrack":30,"./media/track/remoteaudiotrackpublication":31,"./media/track/remotedatatrack":32,"./media/track/remotedatatrackpublication":33,"./media/track/remotevideotrack":36,"./media/track/remotevideotrackpublication":37,"./util":131}],46:[function(require,module,exports){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};Object.defineProperty(exports,"__esModule",{value:true});exports.getCombinedConnectionStats=void 0;function getStatValues(report,statName,kind,reportTypes){var results=[];report.forEach(function(stat){if((reportTypes.length===0||reportTypes.includes(stat.type))&&(kind.length===0||kind.includes(stat.kind))&&typeof stat[statName]==="number"){results.push(stat[statName])}});return results}function getCombinedConnectionStats(_a){var publisher=_a.publisher,subscriber=_a.subscriber;return __awaiter(this,void 0,void 0,function(){var _b,publisherStats,subscriberStats,timestamps,timestamp,jitter,packets,packetsLost,trackRoundTripTime,currentRoundTripTime,roundTripTime,bytesSent,bytesReceived,selectedIceCandidatePairStats,iceCandidateStats;return __generator(this,function(_c){
43
+ switch(_c.label){case 0:return[4,Promise.all([publisher,subscriber].map(function(pc){return pc.getStats()}))];case 1:_b=__read.apply(void 0,[_c.sent(),2]),publisherStats=_b[0],subscriberStats=_b[1];timestamps=getStatValues(subscriberStats,"timestamp",["audio"],["inbound-rtp"]);timestamp=timestamps.length>0?timestamps[0]:0;jitter=getStatValues(subscriberStats,"jitter",["audio"],["inbound-rtp"]).reduce(function(a,b){return Math.max(a,b)},0);packets=getStatValues(subscriberStats,"packetsReceived",["audio","video"],["inbound-rtp"]).reduce(function(a,b){return a+b},0);packetsLost=getStatValues(subscriberStats,"packetsLost",["audio","video"],["inbound-rtp"]).reduce(function(a,b){return a+b},0);trackRoundTripTime=getStatValues(publisherStats,"roundTripTime",["audio","video"],["remote-inbound-rtp"]).reduce(function(a,b){return Math.max(a,b)},0);currentRoundTripTime=getStatValues(subscriberStats,"currentRoundTripTime",[],["candidate-pair"]).reduce(function(a,b){return Math.max(a,b)},0);roundTripTime=(currentRoundTripTime||trackRoundTripTime)*1e3;bytesSent=getStatValues(publisherStats,"bytesSent",[],["candidate-pair"]).reduce(function(a,b){return a+b},0);bytesReceived=getStatValues(subscriberStats,"bytesReceived",[],["candidate-pair"]).reduce(function(a,b){return a+b},0);selectedIceCandidatePairStats=extractSelectedActiveCandidatePair(subscriberStats);iceCandidateStats=[];subscriberStats.forEach(function(stat){if(stat.type==="local-candidate"||stat.type==="remote-candidate"){iceCandidateStats.push(makeStandardCandidateStats(stat))}});return[2,{timestamp:timestamp,jitter:jitter,packets:packets,packetsLost:packetsLost,roundTripTime:roundTripTime,bytesSent:bytesSent,bytesReceived:bytesReceived,selectedIceCandidatePairStats:selectedIceCandidatePairStats,iceCandidateStats:iceCandidateStats}]}})})}exports.getCombinedConnectionStats=getCombinedConnectionStats;function makeStandardCandidateStats(input){var standardizedCandidateStatsKeys=[{key:"transportId",type:"string"},{key:"candidateType",type:"string"},{key:"port",altKeys:["portNumber"],type:"number"},{key:"address",altKeys:["ip","ipAddress"],type:"string"},{key:"priority",type:"number"},{key:"protocol",altKeys:["transport"],type:"string"},{key:"url",type:"string"},{key:"relayProtocol",type:"string"}];return standardizedCandidateStatsKeys.reduce(function(report,keyInfo){var keysToLookFor=[keyInfo.key];if(keyInfo.altKeys){keysToLookFor=keysToLookFor.concat(keyInfo.altKeys)}var key=keysToLookFor.find(function(key){return key in input});if(key&&typeof input[key]===keyInfo.type){report[keyInfo.key]=input[key]}return report},{})}function extractSelectedActiveCandidatePair(stats){var selectedCandidatePairId=null;var candidatePairs=[];stats.forEach(function(stat){if(stat.type==="transport"&&stat.selectedCandidatePairId){selectedCandidatePairId=stat.selectedCandidatePairId}else if(stat.type==="candidate-pair"){candidatePairs.push(stat)}});var activeCandidatePairStatsFound=candidatePairs.find(function(pair){return pair.selected||selectedCandidatePairId&&pair.id===selectedCandidatePairId});if(!activeCandidatePairStatsFound){return null}var activeCandidatePairStats=activeCandidatePairStatsFound;var activeLocalCandidateStats=stats.get(activeCandidatePairStats.localCandidateId);var activeRemoteCandidateStats=stats.get(activeCandidatePairStats.remoteCandidateId);if(!activeLocalCandidateStats||!activeRemoteCandidateStats){return null}return{localCandidate:makeStandardCandidateStats(activeLocalCandidateStats),remoteCandidate:makeStandardCandidateStats(activeRemoteCandidateStats)}}},{}],47:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.getTurnCredentials=void 0;var TwilioConnection=require("../twilioconnection.js");var ICE_VERSION=require("../util/constants").ICE_VERSION;var _a=require("../util/twilio-video-errors"),createTwilioError=_a.createTwilioError,SignalingConnectionError=_a.SignalingConnectionError;var events_1=require("events");function getTurnCredentials(token,wsServer){return new Promise(function(resolve,reject){var eventObserver=new events_1.EventEmitter;var connectionOptions={networkMonitor:null,eventObserver:eventObserver,helloBody:{edge:"roaming",preflight:true,token:token,type:"ice",version:ICE_VERSION}};var twilioConnection=new TwilioConnection(wsServer,connectionOptions);var done=false;twilioConnection.once("close",function(){if(!done){done=true;reject(new SignalingConnectionError)}});twilioConnection.on("message",function(messageData){var code=messageData.code,message=messageData.message,ice_servers=messageData.ice_servers,type=messageData.type;if((type==="iced"||type==="error")&&!done){done=true;if(type==="iced"){resolve(ice_servers)}else{reject(createTwilioError(code,message))}twilioConnection.close()}})})}exports.getTurnCredentials=getTurnCredentials},{"../twilioconnection.js":119,"../util/constants":124,"../util/twilio-video-errors":146,events:173}],48:[function(require,module,exports){"use strict";var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var __spreadArray=this&&this.__spreadArray||function(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to};Object.defineProperty(exports,"__esModule",{value:true});exports.makeStat=void 0;function makeStat(values){if(values&&values.length){var min=Math.min.apply(Math,__spreadArray([],__read(values)));var max=Math.max.apply(Math,__spreadArray([],__read(values)));var average=values.reduce(function(total,value){return total+value},0)/values.length;return{min:min,max:max,average:average}}return null}exports.makeStat=makeStat},{}],49:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.mosToScore=exports.calculateMOS=void 0;var r0=94.768;function calculateMOS(rtt,jitter,fractionLost){var effectiveLatency=rtt+jitter*2+10;var rFactor=0;switch(true){case effectiveLatency<160:rFactor=r0-effectiveLatency/40;break;case effectiveLatency<1e3:rFactor=r0-(effectiveLatency-120)/10;break}switch(true){case fractionLost<=rFactor/2.5:rFactor=Math.max(rFactor-fractionLost*2.5,6.52);break;default:rFactor=0;break}var mos=1+.035*rFactor+7e-6*rFactor*(rFactor-60)*(100-rFactor);return mos}exports.calculateMOS=calculateMOS;function mosToScore(mosValue){var score=0;if(!mosValue){score=0}else if(mosValue>4.2){score=5}else if(mosValue>4){score=4}else if(mosValue>3.6){score=3}else if(mosValue>3){score=2}else{score=1}return score}exports.mosToScore=mosToScore},{}],50:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __assign=this&&this.__assign||function(){__assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++){s=arguments[i];for(var p in s)if(Object.prototype.hasOwnProperty.call(s,p))t[p]=s[p]}return t};return __assign.apply(this,arguments)};var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};Object.defineProperty(exports,"__esModule",{value:true});exports.runPreflight=exports.PreflightTest=void 0;var constants_1=require("../util/constants");var timer_1=require("./timer");var mos_1=require("./mos");var getCombinedConnectionStats_1=require("./getCombinedConnectionStats");var getturncredentials_1=require("./getturncredentials");var makestat_1=require("./makestat");var syntheticaudio_1=require("./syntheticaudio");var syntheticvideo_1=require("./syntheticvideo");var index_1=require("../util/index");var WS_SERVER=require("../util/constants").WS_SERVER;var Log=require("../util/log");var EventEmitter=require("../eventemitter");var MovingAverageDelta=require("../util/movingaveragedelta");var EventObserver=require("../util/eventobserver");var InsightsPublisher=require("../util/insightspublisher");var _a=require("../util/sid"),createSID=_a.createSID,sessionSID=_a.sessionSID;var _b=require("../util/twilio-video-errors"),SignalingConnectionTimeoutError=_b.SignalingConnectionTimeoutError,MediaConnectionError=_b.MediaConnectionError;var SECOND=1e3;var DEFAULT_TEST_DURATION=10*SECOND;var PreflightProgress={mediaAcquired:"mediaAcquired",connected:"connected",mediaSubscribed:"mediaSubscribed",mediaStarted:"mediaStarted",dtlsConnected:"dtlsConnected",peerConnectionConnected:"peerConnectionConnected",iceConnected:"iceConnected"};function notEmpty(value){return value!==null&&typeof value!=="undefined"}var nInstances=0;var PreflightTest=function(_super){__extends(PreflightTest,_super);function PreflightTest(token,options){var _this=_super.call(this)||this;_this._testTiming=new timer_1.Timer;_this._dtlsTiming=new timer_1.Timer;_this._iceTiming=new timer_1.Timer;_this._peerConnectionTiming=new timer_1.Timer;_this._mediaTiming=new timer_1.Timer;_this._connectTiming=new timer_1.Timer;_this._sentBytesMovingAverage=new MovingAverageDelta;_this._packetLossMovingAverage=new MovingAverageDelta;_this._progressEvents=[];_this._receivedBytesMovingAverage=new MovingAverageDelta;var internalOptions=options;var _a=internalOptions.environment,environment=_a===void 0?"prod":_a,_b=internalOptions.region,region=_b===void 0?"gll":_b,_c=internalOptions.duration,duration=_c===void 0?DEFAULT_TEST_DURATION:_c;var wsServer=internalOptions.wsServer||WS_SERVER(environment,region);_this._log=new Log("default",_this,constants_1.DEFAULT_LOG_LEVEL,constants_1.DEFAULT_LOGGER_NAME);_this._testDuration=duration;_this._instanceId=nInstances++;_this._testTiming.start();_this._runPreflightTest(token,environment,wsServer);return _this}PreflightTest.prototype.toString=function(){return"[Preflight #"+this._instanceId+"]"};PreflightTest.prototype.stop=function(){this._stopped=true};PreflightTest.prototype._generatePreflightReport=function(collectedStats){this._testTiming.stop();return{testTiming:this._testTiming.getTimeMeasurement(),networkTiming:{dtls:this._dtlsTiming.getTimeMeasurement(),ice:this._iceTiming.getTimeMeasurement(),peerConnection:this._peerConnectionTiming.getTimeMeasurement(),connect:this._connectTiming.getTimeMeasurement(),media:this._mediaTiming.getTimeMeasurement()},stats:{jitter:makestat_1.makeStat(collectedStats===null||collectedStats===void 0?void 0:collectedStats.jitter),rtt:makestat_1.makeStat(collectedStats===null||collectedStats===void 0?void 0:collectedStats.rtt),packetLoss:makestat_1.makeStat(collectedStats===null||collectedStats===void 0?void 0:collectedStats.packetLoss)},selectedIceCandidatePairStats:collectedStats?collectedStats.selectedIceCandidatePairStats:null,iceCandidateStats:collectedStats?collectedStats.iceCandidateStats:[],progressEvents:this._progressEvents,mos:makestat_1.makeStat(collectedStats===null||collectedStats===void 0?void 0:collectedStats.mos)}};PreflightTest.prototype._executePreflightStep=function(stepName,step,timeoutError){return __awaiter(this,void 0,void 0,function(){var MAX_STEP_DURATION,stepPromise,timer,timeoutPromise,result;return __generator(this,function(_a){switch(_a.label){case 0:this._log.debug("Executing step: ",stepName);MAX_STEP_DURATION=this._testDuration+10*SECOND;if(this._stopped){throw new Error("stopped")}stepPromise=Promise.resolve().then(step);timer=null;timeoutPromise=new Promise(function(_resolve,reject){timer=setTimeout(function(){reject(timeoutError||new Error(stepName+" timeout."))},MAX_STEP_DURATION)});_a.label=1;case 1:_a.trys.push([1,,3,4]);return[4,Promise.race([timeoutPromise,stepPromise])];case 2:result=_a.sent();return[2,result];case 3:if(timer!==null){clearTimeout(timer)}return[7];case 4:return[2]}})})};PreflightTest.prototype._collectNetworkTimings=function(pc){var _this=this;return new Promise(function(resolve){var dtlsTransport;pc.addEventListener("iceconnectionstatechange",function(){if(pc.iceConnectionState==="checking"){_this._iceTiming.start()}if(pc.iceConnectionState==="connected"){_this._iceTiming.stop();_this._updateProgress(PreflightProgress.iceConnected);if(!dtlsTransport||dtlsTransport&&dtlsTransport.state==="connected"){resolve()}}});pc.addEventListener("connectionstatechange",function(){if(pc.connectionState==="connecting"){_this._peerConnectionTiming.start()}if(pc.connectionState==="connected"){_this._peerConnectionTiming.stop();_this._updateProgress(PreflightProgress.peerConnectionConnected)}});var senders=pc.getSenders();var transport=senders.map(function(sender){return sender.transport}).find(notEmpty);if(typeof transport!=="undefined"){dtlsTransport=transport;dtlsTransport.addEventListener("statechange",function(){if(dtlsTransport.state==="connecting"){_this._dtlsTiming.start()}if(dtlsTransport.state==="connected"){_this._dtlsTiming.stop();_this._updateProgress(PreflightProgress.dtlsConnected);if(pc.iceConnectionState==="connected"){resolve()}}})}})};PreflightTest.prototype._setupInsights=function(_a){var token=_a.token,_b=_a.environment,environment=_b===void 0?constants_1.DEFAULT_ENVIRONMENT:_b,_c=_a.realm,realm=_c===void 0?constants_1.DEFAULT_REALM:_c;var eventPublisherOptions={};var eventPublisher=new InsightsPublisher(token,constants_1.SDK_NAME,constants_1.SDK_VERSION,environment,realm,eventPublisherOptions);eventPublisher.connect("PREFLIGHT_ROOM_SID","PREFLIGHT_PARTICIPANT");var eventObserver=new EventObserver(eventPublisher,Date.now(),this._log);var undefinedValue=undefined;return{reportToInsights:function(_a){var _b,_c;var report=_a.report;var jitterStats=report.stats.jitter||undefinedValue;var rttStats=report.stats.rtt||undefinedValue;var packetLossStats=report.stats.packetLoss||undefinedValue;var mosStats=report.mos||undefinedValue;var candidateTypeToProtocols=new Map;report.iceCandidateStats.forEach(function(candidateStats){if(candidateStats.candidateType&&candidateStats.protocol){var protocols=candidateTypeToProtocols.get(candidateStats.candidateType)||[];if(protocols.indexOf(candidateStats.protocol)<0){protocols.push(candidateStats.protocol)}candidateTypeToProtocols.set(candidateStats.candidateType,protocols)}});var iceCandidateStats=JSON.stringify(Object.fromEntries(candidateTypeToProtocols));var insightsReport={name:"report",group:"preflight",level:report.error?"error":"info",payload:{sessionSID:sessionSID,preflightSID:createSID("PF"),progressEvents:JSON.stringify(report.progressEvents),testTiming:report.testTiming,dtlsTiming:report.networkTiming.dtls,iceTiming:report.networkTiming.ice,peerConnectionTiming:report.networkTiming.peerConnection,connectTiming:report.networkTiming.connect,mediaTiming:report.networkTiming.media,selectedLocalCandidate:(_b=report.selectedIceCandidatePairStats)===null||_b===void 0?void 0:_b.localCandidate,selectedRemoteCandidate:(_c=report.selectedIceCandidatePairStats)===null||_c===void 0?void 0:_c.remoteCandidate,iceCandidateStats:iceCandidateStats,jitterStats:jitterStats,rttStats:rttStats,packetLossStats:packetLossStats,mosStats:mosStats,error:report.error}};eventObserver.emit("event",insightsReport);setTimeout(function(){return eventPublisher.disconnect()},2e3)}}};PreflightTest.prototype._runPreflightTest=function(token,environment,wsServer){return __awaiter(this,void 0,void 0,function(){var localTracks,pcs,reportToInsights,elements_1,iceServers,senderPC_1,receiverPC_1,remoteTracks_1,collectedStats_1,report,error_1,preflightReport;var _this=this;return __generator(this,function(_a){switch(_a.label){case 0:localTracks=[];pcs=[];reportToInsights=this._setupInsights({token:token,environment:environment}).reportToInsights;_a.label=1;case 1:_a.trys.push([1,8,9,10]);elements_1=[];return[4,this._executePreflightStep("Acquire media",function(){return[syntheticaudio_1.syntheticAudio(),syntheticvideo_1.syntheticVideo({width:640,height:480})]})];case 2:localTracks=_a.sent();this._updateProgress(PreflightProgress.mediaAcquired);this.emit("debug",{localTracks:localTracks});this._connectTiming.start();return[4,this._executePreflightStep("Get turn credentials",function(){return getturncredentials_1.getTurnCredentials(token,wsServer)},new SignalingConnectionTimeoutError)];case 3:iceServers=_a.sent();this._connectTiming.stop();this._updateProgress(PreflightProgress.connected);senderPC_1=new RTCPeerConnection({iceServers:iceServers,iceTransportPolicy:"relay",bundlePolicy:"max-bundle"});receiverPC_1=new RTCPeerConnection({iceServers:iceServers,bundlePolicy:"max-bundle"});pcs.push(senderPC_1);pcs.push(receiverPC_1);this._mediaTiming.start();return[4,this._executePreflightStep("Setup Peer Connections",function(){return __awaiter(_this,void 0,void 0,function(){var remoteTracksPromise,offer,updatedOffer,answer;return __generator(this,function(_a){switch(_a.label){case 0:senderPC_1.addEventListener("icecandidate",function(event){return event.candidate&&receiverPC_1.addIceCandidate(event.candidate)});receiverPC_1.addEventListener("icecandidate",function(event){return event.candidate&&senderPC_1.addIceCandidate(event.candidate)});localTracks.forEach(function(track){return senderPC_1.addTrack(track)});remoteTracksPromise=new Promise(function(resolve){var remoteTracks=[];receiverPC_1.addEventListener("track",function(event){remoteTracks.push(event.track);if(remoteTracks.length===localTracks.length){resolve(remoteTracks)}})});return[4,senderPC_1.createOffer()];case 1:offer=_a.sent();updatedOffer=offer;return[4,senderPC_1.setLocalDescription(updatedOffer)];case 2:_a.sent();return[4,receiverPC_1.setRemoteDescription(updatedOffer)];case 3:_a.sent();return[4,receiverPC_1.createAnswer()];case 4:answer=_a.sent();return[4,receiverPC_1.setLocalDescription(answer)];case 5:_a.sent();return[4,senderPC_1.setRemoteDescription(answer)];case 6:_a.sent();return[4,this._collectNetworkTimings(senderPC_1)];case 7:_a.sent();return[2,remoteTracksPromise]}})})},new MediaConnectionError)];case 4:remoteTracks_1=_a.sent();this.emit("debug",{remoteTracks:remoteTracks_1});remoteTracks_1.forEach(function(track){track.addEventListener("ended",function(){return _this._log.warn(track.kind+":ended")});track.addEventListener("mute",function(){return _this._log.warn(track.kind+":muted")});track.addEventListener("unmute",function(){return _this._log.warn(track.kind+":unmuted")})});this._updateProgress(PreflightProgress.mediaSubscribed);return[4,this._executePreflightStep("Wait for tracks to start",function(){return new Promise(function(resolve){var element=document.createElement("video");element.autoplay=true;element.playsInline=true;element.muted=true;element.srcObject=new MediaStream(remoteTracks_1);elements_1.push(element);_this.emit("debugElement",element);element.oncanplay=resolve})},new MediaConnectionError)];case 5:_a.sent();this._mediaTiming.stop();this._updateProgress(PreflightProgress.mediaStarted);return[4,this._executePreflightStep("Collect stats for duration",function(){return _this._collectRTCStatsForDuration(_this._testDuration,initCollectedStats(),senderPC_1,receiverPC_1)})];case 6:collectedStats_1=_a.sent();return[4,this._executePreflightStep("Generate report",function(){return _this._generatePreflightReport(collectedStats_1)})];case 7:report=_a.sent();reportToInsights({report:report});this.emit("completed",report);return[3,10];case 8:error_1=_a.sent();preflightReport=this._generatePreflightReport();reportToInsights({report:__assign(__assign({},preflightReport),{error:error_1===null||error_1===void 0?void 0:error_1.toString()})});this.emit("failed",error_1,preflightReport);return[3,10];case 9:pcs.forEach(function(pc){return pc.close()});localTracks.forEach(function(track){return track.stop()});return[7];case 10:return[2]}})})};PreflightTest.prototype._collectRTCStats=function(collectedStats,senderPC,receiverPC){return __awaiter(this,void 0,void 0,function(){var combinedStats,timestamp,bytesSent,bytesReceived,packets,packetsLost,roundTripTime,jitter,selectedIceCandidatePairStats,iceCandidateStats,hasLastData,fractionPacketLost,percentPacketsLost,score;return __generator(this,function(_a){switch(_a.label){case 0:return[4,getCombinedConnectionStats_1.getCombinedConnectionStats({publisher:senderPC,subscriber:receiverPC})];case 1:combinedStats=_a.sent();timestamp=combinedStats.timestamp,bytesSent=combinedStats.bytesSent,bytesReceived=combinedStats.bytesReceived,packets=combinedStats.packets,packetsLost=combinedStats.packetsLost,roundTripTime=combinedStats.roundTripTime,jitter=combinedStats.jitter,selectedIceCandidatePairStats=combinedStats.selectedIceCandidatePairStats,iceCandidateStats=combinedStats.iceCandidateStats;hasLastData=collectedStats.jitter.length>0;collectedStats.jitter.push(jitter);collectedStats.rtt.push(roundTripTime);this._sentBytesMovingAverage.putSample(bytesSent,timestamp);this._receivedBytesMovingAverage.putSample(bytesReceived,timestamp);this._packetLossMovingAverage.putSample(packetsLost,packets);if(hasLastData){collectedStats.outgoingBitrate.push(this._sentBytesMovingAverage.get()*1e3*8);collectedStats.incomingBitrate.push(this._receivedBytesMovingAverage.get()*1e3*8);fractionPacketLost=this._packetLossMovingAverage.get();percentPacketsLost=Math.min(100,fractionPacketLost*100);collectedStats.packetLoss.push(percentPacketsLost);score=mos_1.calculateMOS(roundTripTime,jitter,fractionPacketLost);collectedStats.mos.push(score)}if(!collectedStats.selectedIceCandidatePairStats){collectedStats.selectedIceCandidatePairStats=selectedIceCandidatePairStats}if(collectedStats.iceCandidateStats.length===0){collectedStats.iceCandidateStats=iceCandidateStats}return[2]}})})};PreflightTest.prototype._collectRTCStatsForDuration=function(duration,collectedStats,senderPC,receiverPC){return __awaiter(this,void 0,void 0,function(){var startTime,STAT_INTERVAL,remainingDuration;return __generator(this,function(_a){switch(_a.label){case 0:startTime=Date.now();STAT_INTERVAL=Math.min(1e3,duration);return[4,index_1.waitForSometime(STAT_INTERVAL)];case 1:_a.sent();return[4,this._collectRTCStats(collectedStats,senderPC,receiverPC)];case 2:_a.sent();remainingDuration=duration-(Date.now()-startTime);if(!(remainingDuration>0))return[3,4];return[4,this._collectRTCStatsForDuration(remainingDuration,collectedStats,senderPC,receiverPC)];case 3:collectedStats=_a.sent();_a.label=4;case 4:return[2,collectedStats]}})})};PreflightTest.prototype._updateProgress=function(name){var duration=Date.now()-this._testTiming.getTimeMeasurement().start;this._progressEvents.push({duration:duration,name:name});this.emit("progress",name)};return PreflightTest}(EventEmitter);exports.PreflightTest=PreflightTest;function initCollectedStats(){return{mos:[],jitter:[],rtt:[],outgoingBitrate:[],incomingBitrate:[],packetLoss:[],selectedIceCandidatePairStats:null,iceCandidateStats:[]}}function runPreflight(token,options){if(options===void 0){options={}}var preflight=new PreflightTest(token,options);return preflight}exports.runPreflight=runPreflight},{"../eventemitter":10,"../util/constants":124,"../util/eventobserver":129,"../util/index":131,"../util/insightspublisher":132,"../util/log":135,"../util/movingaveragedelta":136,"../util/sid":143,"../util/twilio-video-errors":146,"./getCombinedConnectionStats":46,"./getturncredentials":47,"./makestat":48,"./mos":49,"./syntheticaudio":51,"./syntheticvideo":52,"./timer":53}],51:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.syntheticAudio=void 0;function syntheticAudio(){var audioContextFactory=require("../webaudio/audiocontext");var holder={};var audioContext=audioContextFactory.getOrCreate(holder);var oscillator=audioContext.createOscillator();var dst=oscillator.connect(audioContext.createMediaStreamDestination());oscillator.start();var track=dst.stream.getAudioTracks()[0];var originalStop=track.stop;track.stop=function(){originalStop.call(track);audioContextFactory.release(holder)};return track}exports.syntheticAudio=syntheticAudio},{"../webaudio/audiocontext":152}],52:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.syntheticVideo=void 0;function syntheticVideo(_a){var _b=_a===void 0?{}:_a,_c=_b.width,width=_c===void 0?640:_c,_d=_b.height,height=_d===void 0?480:_d;var canvas=Object.assign(document.createElement("canvas"),{width:width,height:height});var ctx=canvas.getContext("2d");ctx.fillStyle="green";ctx.fillRect(0,0,canvas.width,canvas.height);var stopped=false;requestAnimationFrame(function animate(){if(!stopped){var r=Math.round(Math.random()*255);var g=Math.round(Math.random()*255);var b=Math.round(Math.random()*255);var a=Math.round(Math.random()*255);ctx.fillStyle="rgba("+r+", "+g+", "+b+", "+a+")";ctx.fillRect(Math.random()*width,Math.random()*height,50,50);requestAnimationFrame(animate)}});var stream=canvas.captureStream(30);var track=stream.getTracks()[0];var originalStop=track.stop;track.stop=function(){stopped=true;originalStop.call(track)};return track}exports.syntheticVideo=syntheticVideo},{}],53:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Timer=void 0;var Timer=function(){function Timer(){this._end=undefined;this.start()}Timer.prototype.start=function(){this._start=Date.now();return this};Timer.prototype.stop=function(){this._end=Date.now();return this};Timer.prototype.getTimeMeasurement=function(){return{start:this._start,end:this._end,duration:this._end===undefined?undefined:this._end-this._start}};return Timer}();exports.Timer=Timer},{}],54:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var __spreadArray=this&&this.__spreadArray||function(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to};var EventEmitter=require("events").EventEmitter;var QueueingEventEmitter=function(_super){__extends(QueueingEventEmitter,_super);function QueueingEventEmitter(){var _this=_super.call(this)||this;Object.defineProperties(_this,{_queuedEvents:{value:new Map}});return _this}QueueingEventEmitter.prototype.dequeue=function(event){var _this=this;var result=true;if(!event){this._queuedEvents.forEach(function(_,queuedEvent){result=this.dequeue(queuedEvent)&&result},this);return result}var queue=this._queuedEvents.get(event)||[];this._queuedEvents.delete(event);return queue.reduce(function(result,args){return _this.emit.apply(_this,__spreadArray([],__read([event].concat(args))))&&result},result)};QueueingEventEmitter.prototype.queue=function(){var args=[].slice.call(arguments);if(this.emit.apply(this,__spreadArray([],__read(args)))){return true}var event=args[0];if(!this._queuedEvents.has(event)){this._queuedEvents.set(event,[])}this._queuedEvents.get(event).push(args.slice(1));return false};return QueueingEventEmitter}(EventEmitter);module.exports=QueueingEventEmitter},{events:173}],55:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var __spreadArray=this&&this.__spreadArray||function(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to};var Participant=require("./participant");var RemoteParticipant=function(_super){__extends(RemoteParticipant,_super);function RemoteParticipant(signaling,options){var _this=_super.call(this,signaling,options)||this;_this._handleTrackSignalingEvents();_this.once("disconnected",_this._unsubscribeTracks.bind(_this));return _this}RemoteParticipant.prototype.toString=function(){return"[RemoteParticipant #"+this._instanceId+(this.sid?": "+this.sid:"")+"]"};RemoteParticipant.prototype._addTrack=function(remoteTrack,publication,id){if(!_super.prototype._addTrack.call(this,remoteTrack,id)){return null}publication._subscribed(remoteTrack);this.emit("trackSubscribed",remoteTrack,publication);return remoteTrack};RemoteParticipant.prototype._addTrackPublication=function(publication){var addedPublication=_super.prototype._addTrackPublication.call(this,publication);if(!addedPublication){return null}this.emit("trackPublished",addedPublication);return addedPublication};RemoteParticipant.prototype._getTrackPublicationEvents=function(){
44
44
  return __spreadArray(__spreadArray([],__read(_super.prototype._getTrackPublicationEvents.call(this))),[["subscriptionFailed","trackSubscriptionFailed"],["trackDisabled","trackDisabled"],["trackEnabled","trackEnabled"],["publishPriorityChanged","trackPublishPriorityChanged"],["trackSwitchedOff","trackSwitchedOff"],["trackSwitchedOn","trackSwitchedOn"]])};RemoteParticipant.prototype._unsubscribeTracks=function(){var _this=this;this.tracks.forEach(function(publication){if(publication.isSubscribed){var track=publication.track;publication._unsubscribe();_this.emit("trackUnsubscribed",track,publication)}})};RemoteParticipant.prototype._removeTrack=function(remoteTrack,publication,id){var unsubscribedTrack=this._tracks.get(id);if(!unsubscribedTrack){return null}_super.prototype._removeTrack.call(this,unsubscribedTrack,id);publication._unsubscribe();this.emit("trackUnsubscribed",unsubscribedTrack,publication);return unsubscribedTrack};RemoteParticipant.prototype._removeTrackPublication=function(publication){this._signaling.clearTrackHint(publication.trackSid);var removedPublication=_super.prototype._removeTrackPublication.call(this,publication);if(!removedPublication){return null}this.emit("trackUnpublished",removedPublication);return removedPublication};return RemoteParticipant}(Participant);module.exports=RemoteParticipant},{"./participant":45}],56:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var __spreadArray=this&&this.__spreadArray||function(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to};var EventEmitter=require("./eventemitter");var RemoteParticipant=require("./remoteparticipant");var StatsReport=require("./stats/statsreport");var valueToJSON=require("./util").valueToJSON;var nInstances=0;var Room=function(_super){__extends(Room,_super);function Room(localParticipant,signaling,options){var _this=_super.call(this)||this;var log=options.log.createLog("default",_this);var participants=new Map;Object.defineProperties(_this,{_log:{value:log},_clientTrackSwitchOffControl:{value:options.clientTrackSwitchOffControl||"disabled"},_contentPreferencesMode:{value:options.contentPreferencesMode||"disabled"},_instanceId:{value:++nInstances},_options:{value:options},_participants:{value:participants},_signaling:{value:signaling},dominantSpeaker:{enumerable:true,get:function(){return this.participants.get(signaling.dominantSpeakerSid)||null}},isRecording:{enumerable:true,get:function(){return signaling.recording.isEnabled||false}},localParticipant:{enumerable:true,value:localParticipant},name:{enumerable:true,value:signaling.name},participants:{enumerable:true,value:participants},sid:{enumerable:true,value:signaling.sid},state:{enumerable:true,get:function(){return signaling.state}},mediaRegion:{enumerable:true,value:signaling.mediaRegion}});handleLocalParticipantEvents(_this,localParticipant);handleRecordingEvents(_this,signaling.recording);handleSignalingEvents(_this,signaling);verifyNoiseCancellation(_this);log.info("Created a new Room:",_this.name);log.debug("Initial RemoteParticipants:",Array.from(_this._participants.values()));return _this}Room.prototype.toString=function(){return"[Room #"+this._instanceId+": "+this.sid+"]"};Room.prototype.disconnect=function(){this._log.info("Disconnecting");this._signaling.disconnect();return this};Room.prototype.getStats=function(){var _this=this;return this._signaling.getStats().then(function(responses){return Array.from(responses).map(function(_a){var _b=__read(_a,2),id=_b[0],response=_b[1];return new StatsReport(id,Object.assign({},response,{localAudioTrackStats:rewriteLocalTrackIds(_this,response.localAudioTrackStats),localVideoTrackStats:rewriteLocalTrackIds(_this,response.localVideoTrackStats)}))})})};Room.prototype.toJSON=function(){return valueToJSON(this)};return Room}(EventEmitter);function verifyNoiseCancellation(room){var allowedAudioProcessors=room.localParticipant._signaling.audioProcessors;room.localParticipant.audioTracks.forEach(function(_a){var track=_a.track;var noiseCancellation=track.noiseCancellation;if(noiseCancellation&&!allowedAudioProcessors.includes(noiseCancellation.vendor)){room._log.warn(noiseCancellation.vendor+" is not supported in this room. disabling it permanently");noiseCancellation.disablePermanently()}})}function rewriteLocalTrackIds(room,trackStats){var localParticipantSignaling=room.localParticipant._signaling;return trackStats.reduce(function(trackStats,trackStat){var publication=localParticipantSignaling.tracks.get(trackStat.trackId);var trackSender=localParticipantSignaling.getSender(publication);return trackSender?[Object.assign({},trackStat,{trackId:trackSender.id})].concat(trackStats):trackStats},[])}function connectParticipant(room,participantSignaling){var log=room._log,clientTrackSwitchOffControl=room._clientTrackSwitchOffControl,contentPreferencesMode=room._contentPreferencesMode;var participant=new RemoteParticipant(participantSignaling,{log:log,clientTrackSwitchOffControl:clientTrackSwitchOffControl,contentPreferencesMode:contentPreferencesMode});log.info("A new RemoteParticipant connected:",participant);room._participants.set(participant.sid,participant);room.emit("participantConnected",participant);var eventListeners=[["reconnected","participantReconnected"],["reconnecting","participantReconnecting"],"trackDimensionsChanged","trackDisabled","trackEnabled","trackMessage","trackPublished","trackPublishPriorityChanged","trackStarted","trackSubscribed","trackSubscriptionFailed","trackSwitchedOff","trackSwitchedOn","trackUnpublished","trackUnsubscribed"].map(function(eventOrPair){var _a=__read(Array.isArray(eventOrPair)?eventOrPair:[eventOrPair,eventOrPair],2),event=_a[0],participantEvent=_a[1];function reemit(){var args=[].slice.call(arguments);args.unshift(participantEvent);args.push(participant);room.emit.apply(room,__spreadArray([],__read(args)))}participant.on(event,reemit);return[event,reemit]});participant.once("disconnected",function participantDisconnected(){var dominantSpeaker=room.dominantSpeaker;log.info("RemoteParticipant disconnected:",participant);room._participants.delete(participant.sid);eventListeners.forEach(function(args){participant.removeListener(args[0],args[1])});room.emit("participantDisconnected",participant);if(participant===dominantSpeaker){room.emit("dominantSpeakerChanged",room.dominantSpeaker)}})}function handleLocalParticipantEvents(room,localParticipant){var events=["trackWarning","trackWarningsCleared"].map(function(event){return{eventName:event,handler:function(){var args=[];for(var _i=0;_i<arguments.length;_i++){args[_i]=arguments[_i]}return room.emit.apply(room,__spreadArray([event],__read(__spreadArray(__spreadArray([],__read(args)),[localParticipant]))))}}});events.forEach(function(_a){var eventName=_a.eventName,handler=_a.handler;return localParticipant.on(eventName,handler)});room.once("disconnected",function(){return events.forEach(function(_a){var eventName=_a.eventName,handler=_a.handler;return localParticipant.removeListener(eventName,handler)})})}function handleRecordingEvents(room,recording){recording.on("updated",function updated(){var started=recording.isEnabled;room._log.info("Recording "+(started?"started":"stopped"));room.emit("recording"+(started?"Started":"Stopped"))})}function handleSignalingEvents(room,signaling){var log=room._log;log.debug("Creating a new RemoteParticipant for each ParticipantSignaling "+"in the RoomSignaling");signaling.participants.forEach(connectParticipant.bind(null,room));log.debug("Setting up RemoteParticipant creation for all subsequent "+"ParticipantSignalings that connect to the RoomSignaling");signaling.on("participantConnected",connectParticipant.bind(null,room));signaling.on("dominantSpeakerChanged",function(){return room.emit("dominantSpeakerChanged",room.dominantSpeaker)});signaling.on("stateChanged",function stateChanged(state,error){log.info("Transitioned to state:",state);switch(state){case"disconnected":room.participants.forEach(function(participant){participant._unsubscribeTracks()});room.emit(state,room,error);room.localParticipant.tracks.forEach(function(publication){publication.unpublish()});signaling.removeListener("stateChanged",stateChanged);break;case"reconnecting":setTimeout(function(){return room.emit("reconnecting",error)},0);break;default:setTimeout(function(){return room.emit("reconnected")},0)}})}module.exports=Room},{"./eventemitter":10,"./remoteparticipant":55,"./stats/statsreport":115,"./util":131}],57:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var ParticipantSignaling=require("./participant");var RoomSignaling=require("./room");var StateMachine=require("../statemachine");var states={closed:["opening"],opening:["closed","open"],open:["closed","closing"],closing:["closed","open"]};var Signaling=function(_super){__extends(Signaling,_super);function Signaling(){return _super.call(this,"closed",states)||this}Signaling.prototype._close=function(key){this.transition("closing",key);this.transition("closed",key);return Promise.resolve(this)};Signaling.prototype._connect=function(localParticipant,token,encodingParameters,preferredCodecs,options){localParticipant.connect("PA00000000000000000000000000000000","test");var sid="RM00000000000000000000000000000000";var promise=Promise.resolve(new RoomSignaling(localParticipant,sid,options));promise.cancel=function cancel(){};return promise};Signaling.prototype._open=function(key){this.transition("opening",key);this.transition("open",key);return Promise.resolve(this)};Signaling.prototype.close=function(){var _this=this;return this.bracket("close",function(key){switch(_this.state){case"closed":return _this;case"open":return _this._close(key);default:throw new Error('Unexpected Signaling state "'+_this.state+'"')}})};Signaling.prototype.connect=function(localParticipant,token,encodingParameters,preferredCodecs,options){var self=this;return this.bracket("connect",function transition(key){switch(self.state){case"closed":return self._open(key).then(transition.bind(null,key));case"open":self.releaseLockCompletely(key);return self._connect(localParticipant,token,encodingParameters,preferredCodecs,options);default:throw new Error('Unexpected Signaling state "'+self.state+'"')}})};Signaling.prototype.createLocalParticipantSignaling=function(){return new ParticipantSignaling};Signaling.prototype.open=function(){var _this=this;return this.bracket("open",function(key){switch(_this.state){case"closed":return _this._open(key);case"open":return _this;default:throw new Error('Unexpected Signaling state "'+_this.state+'"')}})};return Signaling}(StateMachine);module.exports=Signaling},{"../statemachine":87,"./participant":60,"./room":64}],58:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var ParticipantSignaling=require("./participant");var LocalParticipantSignaling=function(_super){__extends(LocalParticipantSignaling,_super);function LocalParticipantSignaling(){var _this=_super.call(this)||this;Object.defineProperties(_this,{_publicationsToTrackSenders:{value:new Map},_trackSendersToPublications:{value:new Map}});return _this}LocalParticipantSignaling.prototype.addTrack=function(trackSender,name,priority,noiseCancellationVendor){if(noiseCancellationVendor===void 0){noiseCancellationVendor=null}var publication=this._createLocalTrackPublicationSignaling(trackSender,name,priority,noiseCancellationVendor);this._trackSendersToPublications.set(trackSender,publication);this._publicationsToTrackSenders.set(publication,trackSender);_super.prototype.addTrack.call(this,publication);return this};LocalParticipantSignaling.prototype.getPublication=function(trackSender){return this._trackSendersToPublications.get(trackSender)||null};LocalParticipantSignaling.prototype.getSender=function(trackPublication){return this._publicationsToTrackSenders.get(trackPublication)||null};LocalParticipantSignaling.prototype.removeTrack=function(trackSender){var publication=this._trackSendersToPublications.get(trackSender);if(!publication){return null}this._trackSendersToPublications.delete(trackSender);this._publicationsToTrackSenders.delete(publication);var didDelete=_super.prototype.removeTrack.call(this,publication);if(didDelete){publication.stop()}return publication};return LocalParticipantSignaling}(ParticipantSignaling);module.exports=LocalParticipantSignaling},{"./participant":60}],59:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var TrackSignaling=require("./track");var LocalTrackPublicationSignaling=function(_super){__extends(LocalTrackPublicationSignaling,_super);function LocalTrackPublicationSignaling(trackSender,name,priority){var _this=this;trackSender=trackSender.clone();var enabled=trackSender.kind==="data"?true:trackSender.track.enabled;_this=_super.call(this,name,trackSender.kind,enabled,priority)||this;_this.setTrackTransceiver(trackSender);Object.defineProperties(_this,{_updatedPriority:{value:priority,writable:true},id:{enumerable:true,value:trackSender.id}});return _this}Object.defineProperty(LocalTrackPublicationSignaling.prototype,"updatedPriority",{get:function(){return this._updatedPriority},enumerable:false,configurable:true});LocalTrackPublicationSignaling.prototype.enable=function(enabled){enabled=typeof enabled==="boolean"?enabled:true;this.trackTransceiver.track.enabled=enabled;return _super.prototype.enable.call(this,enabled)};LocalTrackPublicationSignaling.prototype.publishFailed=function(error){if(setError(this,error)){this.emit("updated")}return this};LocalTrackPublicationSignaling.prototype.setPriority=function(priority){if(this._updatedPriority!==priority){this._updatedPriority=priority;this.emit("updated")}return this};LocalTrackPublicationSignaling.prototype.setSid=function(sid){if(this._error){return this}return _super.prototype.setSid.call(this,sid)};LocalTrackPublicationSignaling.prototype.stop=function(){this.trackTransceiver.stop()};return LocalTrackPublicationSignaling}(TrackSignaling);function setError(publication,error){if(publication._sid!==null||publication._error){return false}publication._error=error;return true}module.exports=LocalTrackPublicationSignaling},{"./track":65}],60:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var StateMachine=require("../statemachine");var NetworkQualityStats=require("../stats/networkqualitystats");var states={connecting:["connected"],connected:["disconnected","reconnecting"],reconnecting:["connected","disconnected"],disconnected:[]};var ParticipantSignaling=function(_super){__extends(ParticipantSignaling,_super);function ParticipantSignaling(){var _this=_super.call(this,"connecting",states)||this;Object.defineProperties(_this,{_identity:{writable:true,value:null},_networkQualityLevel:{value:null,writable:true},_networkQualityStats:{value:null,writable:true},_sid:{writable:true,value:null},identity:{enumerable:true,get:function(){return this._identity}},sid:{enumerable:true,get:function(){return this._sid}},tracks:{enumerable:true,value:new Map}});return _this}Object.defineProperty(ParticipantSignaling.prototype,"networkQualityLevel",{get:function(){return this._networkQualityLevel},enumerable:false,configurable:true});Object.defineProperty(ParticipantSignaling.prototype,"networkQualityStats",{get:function(){return this._networkQualityStats},enumerable:false,configurable:true});ParticipantSignaling.prototype.addTrack=function(track){this.tracks.set(track.id||track.sid,track);this.emit("trackAdded",track);return this};ParticipantSignaling.prototype.disconnect=function(){if(this.state!=="disconnected"){this.preempt("disconnected");return true}return false};ParticipantSignaling.prototype.removeTrack=function(track){var signaling=this.tracks.get(track.id||track.sid);this.tracks.delete(track.id||track.sid);if(signaling){this.emit("trackRemoved",track)}return signaling||null};ParticipantSignaling.prototype.setNetworkQualityLevel=function(networkQualityLevel,networkQualityLevels){if(this._networkQualityLevel!==networkQualityLevel){this._networkQualityLevel=networkQualityLevel;this._networkQualityStats=networkQualityLevels&&(networkQualityLevels.audio||networkQualityLevels.video)?new NetworkQualityStats(networkQualityLevels):null;this.emit("networkQualityLevelChanged")}};ParticipantSignaling.prototype.connect=function(sid,identity){if(this.state==="connecting"||this.state==="reconnecting"){if(!this._sid){this._sid=sid}if(!this._identity){this._identity=identity}this.preempt("connected");return true}return false};ParticipantSignaling.prototype.reconnecting=function(){if(this.state==="connecting"||this.state==="connected"){this.preempt("reconnecting");return true}return false};return ParticipantSignaling}(StateMachine);module.exports=ParticipantSignaling},{"../statemachine":87,"../stats/networkqualitystats":102}],61:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var EventEmitter=require("events").EventEmitter;var RecordingSignaling=function(_super){__extends(RecordingSignaling,_super);function RecordingSignaling(){var _this=_super.call(this)||this;Object.defineProperties(_this,{_isEnabled:{value:null,writable:true},isEnabled:{enumerable:true,get:function(){return this._isEnabled}}});return _this}RecordingSignaling.prototype.disable=function(){return this.enable(false)};RecordingSignaling.prototype.enable=function(enabled){enabled=typeof enabled==="boolean"?enabled:true;if(this.isEnabled!==enabled){this._isEnabled=enabled;this.emit("updated")}return this};return RecordingSignaling}(EventEmitter);module.exports=RecordingSignaling},{events:173}],62:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var ParticipantSignaling=require("./participant");var RemoteParticipantSignaling=function(_super){__extends(RemoteParticipantSignaling,_super);function RemoteParticipantSignaling(sid,identity){var _this=_super.call(this)||this;_this.connect(sid,identity);return _this}return RemoteParticipantSignaling}(ParticipantSignaling);module.exports=RemoteParticipantSignaling},{"./participant":60}],63:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var TrackSignaling=require("./track");var RemoteTrackPublicationSignaling=function(_super){__extends(RemoteTrackPublicationSignaling,_super);function RemoteTrackPublicationSignaling(sid,name,kind,isEnabled,priority,isSwitchedOff){var _this=_super.call(this,name,kind,isEnabled,priority)||this;Object.defineProperties(_this,{_isSwitchedOff:{value:isSwitchedOff,writable:true}});_this.setSid(sid);return _this}Object.defineProperty(RemoteTrackPublicationSignaling.prototype,"isSubscribed",{get:function(){return!!this.trackTransceiver},enumerable:false,configurable:true});Object.defineProperty(RemoteTrackPublicationSignaling.prototype,"isSwitchedOff",{get:function(){return this._isSwitchedOff},enumerable:false,configurable:true});RemoteTrackPublicationSignaling.prototype.subscribeFailed=function(error){if(!this.error){this._error=error;this.emit("updated")}return this};RemoteTrackPublicationSignaling.prototype.setPriority=function(priority){if(this._priority!==priority){this._priority=priority;this.emit("updated")}return this};RemoteTrackPublicationSignaling.prototype.setSwitchedOff=function(isSwitchedOff){if(this._isSwitchedOff!==isSwitchedOff){this._isSwitchedOff=isSwitchedOff;this.emit("updated")}return this};return RemoteTrackPublicationSignaling}(TrackSignaling);module.exports=RemoteTrackPublicationSignaling},{"./track":65}],64:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var DefaultRecordingSignaling=require("./recording");var StateMachine=require("../statemachine");var DefaultTimeout=require("../util/timeout");var buildLogLevels=require("../util").buildLogLevels;var DEFAULT_LOG_LEVEL=require("../util/constants").DEFAULT_LOG_LEVEL;var Log=require("../util/log");var _a=require("../util/twilio-video-errors"),MediaConnectionError=_a.MediaConnectionError,MediaDTLSTransportFailedError=_a.MediaDTLSTransportFailedError,SignalingConnectionDisconnectedError=_a.SignalingConnectionDisconnectedError;var nInstances=0;var states={connected:["reconnecting","disconnected"],reconnecting:["connected","disconnected"],disconnected:[]};var RoomSignaling=function(_super){__extends(RoomSignaling,_super);function RoomSignaling(localParticipant,sid,name,options){var _this=this;options=Object.assign({logLevel:DEFAULT_LOG_LEVEL,RecordingSignaling:DefaultRecordingSignaling,Timeout:DefaultTimeout},options);var logLevels=buildLogLevels(options.logLevel);_this=_super.call(this,"connected",states)||this;var RecordingSignaling=options.RecordingSignaling;var sessionTimeout=new options.Timeout(function(){_this._disconnect(_this._reconnectingError)},options.sessionTimeout,false);Object.defineProperties(_this,{_instanceId:{value:nInstances++},_log:{value:options.log?options.log.createLog("default",_this):new Log("default",_this,logLevels,options.loggerName)},_mediaConnectionIsReconnecting:{writable:true,value:false},_options:{value:options},_reconnectingError:{value:null,writable:true},_sessionTimeout:{value:sessionTimeout},dominantSpeakerSid:{enumerable:true,value:null,writable:true},localParticipant:{enumerable:true,value:localParticipant},name:{enumerable:true,value:name},participants:{enumerable:true,value:new Map},recording:{enumerable:true,value:new RecordingSignaling},sid:{enumerable:true,value:sid}});_this.on("connectionStateChanged",function(){if(_this.connectionState==="failed"&&!["disconnected","failed"].includes(_this.iceConnectionState)){_this._disconnect(new MediaDTLSTransportFailedError)}});_this.on("iceConnectionStateChanged",function(){return maybeUpdateState(_this)});_this.on("signalingConnectionStateChanged",function(){return maybeUpdateState(_this)});setTimeout(function(){return maybeUpdateState(_this)});return _this}RoomSignaling.prototype._disconnect=function(error){if(this.state!=="disconnected"){this.preempt("disconnected",null,[error]);return true}return false};RoomSignaling.prototype.toString=function(){return"[RoomSignaling #"+this._instanceId+": "+(this.localParticipant?this.localParticipant.sid:"null")+"]"};RoomSignaling.prototype.connectParticipant=function(participant){var self=this;if(participant.state==="disconnected"){return false}if(this.participants.has(participant.sid)){return false}this.participants.set(participant.sid,participant);participant.on("stateChanged",function stateChanged(state){if(state==="disconnected"){participant.removeListener("stateChanged",stateChanged);self.participants.delete(participant.sid);self.emit("participantDisconnected",participant)}});this.emit("participantConnected",participant);return true};RoomSignaling.prototype.disconnect=function(){return this._disconnect()};RoomSignaling.prototype.setDominantSpeaker=function(dominantSpeakerSid){this.dominantSpeakerSid=dominantSpeakerSid;this.emit("dominantSpeakerChanged")};return RoomSignaling}(StateMachine);function maybeUpdateState(roomSignaling){if(roomSignaling.state==="disconnected"||roomSignaling.signalingConnectionState==="disconnected"){roomSignaling._sessionTimeout.clear();return}var newState;if(roomSignaling.signalingConnectionState==="reconnecting"){newState=roomSignaling.signalingConnectionState}else if(roomSignaling.iceConnectionState==="failed"){roomSignaling._mediaConnectionIsReconnecting=true;newState="reconnecting"}else if(roomSignaling.iceConnectionState==="new"||roomSignaling.iceConnectionState==="checking"){newState=roomSignaling._mediaConnectionIsReconnecting?"reconnecting":"connected"}else{roomSignaling._mediaConnectionIsReconnecting=false;roomSignaling._reconnectingError=null;roomSignaling._sessionTimeout.clear();newState="connected"}if(newState===roomSignaling.state){return}if(newState==="reconnecting"){roomSignaling._reconnectingError=roomSignaling.signalingConnectionState==="reconnecting"?new SignalingConnectionDisconnectedError:new MediaConnectionError;roomSignaling._sessionTimeout.start();roomSignaling.preempt(newState,null,[roomSignaling._reconnectingError])}else{roomSignaling.preempt(newState)}}module.exports=RoomSignaling},{"../statemachine":87,"../util":131,"../util/constants":124,"../util/log":135,"../util/timeout":145,"../util/twilio-video-errors":146,"./recording":61}],65:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var EventEmitter=require("events").EventEmitter;var TrackSignaling=function(_super){__extends(TrackSignaling,_super);function TrackSignaling(name,kind,isEnabled,priority){var _this=_super.call(this)||this;var sid=null;Object.defineProperties(_this,{_error:{value:null,writable:true},_isEnabled:{value:isEnabled,writable:true},_priority:{value:priority,writable:true},_trackTransceiver:{value:null,writable:true},_sid:{get:function(){return sid},set:function(_sid){if(sid===null){sid=_sid}}},kind:{enumerable:true,value:kind},name:{enumerable:true,value:name}});return _this}Object.defineProperty(TrackSignaling.prototype,"error",{get:function(){return this._error},enumerable:false,configurable:true});Object.defineProperty(TrackSignaling.prototype,"isEnabled",{get:function(){return this._isEnabled},enumerable:false,configurable:true});Object.defineProperty(TrackSignaling.prototype,"priority",{get:function(){return this._priority},enumerable:false,configurable:true});Object.defineProperty(TrackSignaling.prototype,"sid",{get:function(){return this._sid},enumerable:false,configurable:true});Object.defineProperty(TrackSignaling.prototype,"trackTransceiver",{get:function(){return this._trackTransceiver},enumerable:false,configurable:true});TrackSignaling.prototype.disable=function(){return this.enable(false)};TrackSignaling.prototype.enable=function(enabled){enabled=typeof enabled==="boolean"?enabled:true;if(this.isEnabled!==enabled){this._isEnabled=enabled;this.emit("updated")}return this};TrackSignaling.prototype.setTrackTransceiver=function(trackTransceiver){trackTransceiver=trackTransceiver||null;if(this.trackTransceiver!==trackTransceiver){this._trackTransceiver=trackTransceiver;this.emit("updated")}return this};TrackSignaling.prototype.setSid=function(sid){if(this.sid===null){this._sid=sid;this.emit("updated")}return this};return TrackSignaling}(EventEmitter);module.exports=TrackSignaling},{events:173}],66:[function(require,module,exports){"use strict"
45
45
  ;var CancelablePromise=require("../../util/cancelablepromise");var DefaultPeerConnectionManager=require("./peerconnectionmanager");var DefaultRoomV2=require("./room");var DefaultTransport=require("./twilioconnectiontransport");var _a=require("../../util/twilio-video-errors"),SignalingConnectionDisconnectedError=_a.SignalingConnectionDisconnectedError,SignalingIncomingMessageInvalidError=_a.SignalingIncomingMessageInvalidError;var _b=require("../../util"),flatMap=_b.flatMap,createRoomConnectEventPayload=_b.createRoomConnectEventPayload;function createCancelableRoomSignalingPromise(token,wsServer,localParticipant,encodingParameters,preferredCodecs,options){options=Object.assign({PeerConnectionManager:DefaultPeerConnectionManager,RoomV2:DefaultRoomV2,Transport:DefaultTransport},options);var adaptiveSimulcast=preferredCodecs.video[0]&&preferredCodecs.video[0].adaptiveSimulcast===true;var PeerConnectionManager=options.PeerConnectionManager,RoomV2=options.RoomV2,Transport=options.Transport,iceServers=options.iceServers,log=options.log;var peerConnectionManager=new PeerConnectionManager(encodingParameters,preferredCodecs,options);var trackSenders=flatMap(localParticipant.tracks,function(trackV2){return[trackV2.trackTransceiver]});peerConnectionManager.setTrackSenders(trackSenders);var cancellationError=new Error("Canceled");var transport;var cancelablePromise=new CancelablePromise(function(resolve,reject,isCanceled){var onIced=function(iceServers){if(isCanceled()){reject(cancellationError);return Promise.reject(cancellationError)}log.debug("Got ICE servers:",iceServers);options.iceServers=iceServers;peerConnectionManager.setConfiguration(options);return peerConnectionManager.createAndOffer().then(function(){if(isCanceled()){reject(cancellationError);throw cancellationError}log.debug("createAndOffer() succeeded.");peerConnectionManager.dequeue("description")}).catch(function(error){log.error("createAndOffer() failed:",error);reject(error);throw error})};var automaticSubscription=options.automaticSubscription,bandwidthProfile=options.bandwidthProfile,dominantSpeaker=options.dominantSpeaker,environment=options.environment,eventObserver=options.eventObserver,loggerName=options.loggerName,logLevel=options.logLevel,name=options.name,networkMonitor=options.networkMonitor,networkQuality=options.networkQuality,notifyWarnings=options.notifyWarnings,realm=options.realm,sdpSemantics=options.sdpSemantics;var trackPriority=!!bandwidthProfile;var trackSwitchOff=!!bandwidthProfile;var renderHints=!!bandwidthProfile&&(options.clientTrackSwitchOffControl!=="disabled"||options.contentPreferencesMode!=="disabled");var transportOptions=Object.assign({adaptiveSimulcast:adaptiveSimulcast,automaticSubscription:automaticSubscription,dominantSpeaker:dominantSpeaker,environment:environment,eventObserver:eventObserver,loggerName:loggerName,logLevel:logLevel,networkMonitor:networkMonitor,networkQuality:networkQuality,notifyWarnings:notifyWarnings,iceServers:iceServers,onIced:onIced,realm:realm,renderHints:renderHints,sdpSemantics:sdpSemantics,trackPriority:trackPriority,trackSwitchOff:trackSwitchOff},bandwidthProfile?{bandwidthProfile:bandwidthProfile}:{});transport=new Transport(name,token,localParticipant,peerConnectionManager,wsServer,transportOptions);var connectEventPayload=createRoomConnectEventPayload(options);eventObserver.emit("event",connectEventPayload);transport.once("connected",function(initialState){log.debug("Transport connected:",initialState);if(isCanceled()){reject(cancellationError);return}var localParticipantState=initialState.participant;if(!localParticipantState){reject(new SignalingIncomingMessageInvalidError);return}resolve(new RoomV2(localParticipant,initialState,transport,peerConnectionManager,options))});transport.once("stateChanged",function(state,error){if(state==="disconnected"){transport=null;reject(error||new SignalingConnectionDisconnectedError)}else{log.debug("Transport state changed:",state)}})},function(){if(transport){transport.disconnect();transport=null}});cancelablePromise.catch(function(){if(transport){transport.disconnect();transport=null}peerConnectionManager.close()});return cancelablePromise}module.exports=createCancelableRoomSignalingPromise},{"../../util":131,"../../util/cancelablepromise":123,"../../util/twilio-video-errors":146,"./peerconnectionmanager":77,"./room":83,"./twilioconnectiontransport":86}],67:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var MediaSignaling=require("./mediasignaling");var DominantSpeakerSignaling=function(_super){__extends(DominantSpeakerSignaling,_super);function DominantSpeakerSignaling(getReceiver,options){var _this=_super.call(this,getReceiver,"active_speaker",options)||this;Object.defineProperties(_this,{_loudestParticipantSid:{value:null,writable:true}});_this.on("ready",function(transport){transport.on("message",function(message){switch(message.type){case"active_speaker":_this._setLoudestParticipantSid(message.participant);break;default:break}})});return _this}Object.defineProperty(DominantSpeakerSignaling.prototype,"loudestParticipantSid",{get:function(){return this._loudestParticipantSid},enumerable:false,configurable:true});DominantSpeakerSignaling.prototype._setLoudestParticipantSid=function(loudestParticipantSid){if(this.loudestParticipantSid===loudestParticipantSid){return}this._loudestParticipantSid=loudestParticipantSid;this.emit("updated")};return DominantSpeakerSignaling}(MediaSignaling);module.exports=DominantSpeakerSignaling},{"./mediasignaling":73}],68:[function(require,module,exports){"use strict";var Filter=require("../../util/filter");var IceBox=function(){function IceBox(){Object.defineProperties(this,{_filter:{value:new Filter({getKey:function getKey(iceState){return iceState.ufrag},isLessThanOrEqualTo:function isLessThanOrEqualTo(a,b){return a.revision<=b.revision}})},_ufrag:{writable:true,value:null},ufrag:{enumerable:true,get:function(){return this._ufrag}}})}IceBox.prototype.setUfrag=function(ufrag){this._ufrag=ufrag;var ice=this._filter.toMap().get(ufrag);return ice?ice.candidates:[]};IceBox.prototype.update=function(iceState){iceState.candidates=iceState.candidates||[];var oldIceState=this._filter.toMap().get(iceState.ufrag);var oldCandidates=oldIceState?oldIceState.candidates:[];return this._filter.update(iceState)&&this._ufrag===iceState.ufrag?iceState.candidates.slice(oldCandidates.length):[]};return IceBox}();module.exports=IceBox},{"../../util/filter":130}],69:[function(require,module,exports){"use strict";var _a=require("../../util/constants"),ICE_ACTIVITY_CHECK_PERIOD_MS=_a.ICE_ACTIVITY_CHECK_PERIOD_MS,ICE_INACTIVITY_THRESHOLD_MS=_a.ICE_INACTIVITY_THRESHOLD_MS;var IceConnectionMonitor=function(){function IceConnectionMonitor(peerConnection,options){options=Object.assign({activityCheckPeriodMs:ICE_ACTIVITY_CHECK_PERIOD_MS,inactivityThresholdMs:ICE_INACTIVITY_THRESHOLD_MS},options);Object.defineProperties(this,{_activityCheckPeriodMs:{value:options.activityCheckPeriodMs},_inactivityThresholdMs:{value:options.inactivityThresholdMs},_lastActivity:{value:null,writable:true},_peerConnection:{value:peerConnection},_timer:{value:null,writable:true},_onIceConnectionStateChanged:{value:null,writable:true}})}IceConnectionMonitor.prototype._getActivePairStat=function(stats){var statsArray=Array.from(stats.values());var activePairStats=statsArray.find(function(stat){return stat.type==="candidate-pair"&&stat.nominated});return activePairStats||{bytesReceived:0,timestamp:Math.round((new Date).getTime())}};IceConnectionMonitor.prototype._getIceConnectionStats=function(){var _this=this;return this._peerConnection.getStats().then(function(stats){return _this._getActivePairStat(stats)}).catch(function(){return null})};IceConnectionMonitor.prototype._scheduleInactivityCallback=function(callback){var _this=this;if(callback&&this._onIceConnectionStateChanged===null){this._onIceConnectionStateChanged=function(){if(_this._peerConnection.iceConnectionState==="disconnected"){callback()}};this._peerConnection.addEventListener("iceconnectionstatechange",this._onIceConnectionStateChanged)}else if(!callback&&this._onIceConnectionStateChanged){this._peerConnection.removeEventListener("iceconnectionstatechange",this._onIceConnectionStateChanged);this._onIceConnectionStateChanged=null}};IceConnectionMonitor.prototype.start=function(onIceConnectionInactive){var _this=this;this.stop();this._timer=setInterval(function(){_this._getIceConnectionStats().then(function(iceStats){if(!iceStats){return}if(!_this._lastActivity||_this._lastActivity.bytesReceived!==iceStats.bytesReceived){_this._lastActivity=iceStats;_this._scheduleInactivityCallback(null)}if(iceStats.timestamp-_this._lastActivity.timestamp>=_this._inactivityThresholdMs){if(_this._peerConnection.iceConnectionState==="disconnected"){onIceConnectionInactive()}else if(_this._onIceConnectionStateChanged===null){_this._scheduleInactivityCallback(onIceConnectionInactive)}}})},this._activityCheckPeriodMs)};IceConnectionMonitor.prototype.stop=function(){this._scheduleInactivityCallback(null);if(this._timer!==null){clearInterval(this._timer);this._timer=null;this._lastActivity=null}};return IceConnectionMonitor}();module.exports=IceConnectionMonitor},{"../../util/constants":124}],70:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var defaultCreateCancelableRoomSignalingPromise=require("./cancelableroomsignalingpromise");var LocalParticipantV2=require("./localparticipant");var Signaling=require("../");var SignalingV2=function(_super){__extends(SignalingV2,_super);function SignalingV2(wsServer,options){var _this=this;options=Object.assign({createCancelableRoomSignalingPromise:defaultCreateCancelableRoomSignalingPromise},options);_this=_super.call(this)||this;Object.defineProperties(_this,{_createCancelableRoomSignalingPromise:{value:options.createCancelableRoomSignalingPromise},_options:{value:options},_wsServer:{value:wsServer}});return _this}SignalingV2.prototype._connect=function(localParticipant,token,encodingParameters,preferredCodecs,options){options=Object.assign({},this._options,options);return this._createCancelableRoomSignalingPromise.bind(null,token,this._wsServer,localParticipant,encodingParameters,preferredCodecs,options)};SignalingV2.prototype.createLocalParticipantSignaling=function(encodingParameters,networkQualityConfiguration){return new LocalParticipantV2(encodingParameters,networkQualityConfiguration)};return SignalingV2}(Signaling);module.exports=SignalingV2},{"../":57,"./cancelableroomsignalingpromise":66,"./localparticipant":71}],71:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var LocalParticipantSignaling=require("../localparticipant");var LocalTrackPublicationV2=require("./localtrackpublication");var DEFAULT_LOG_LEVEL=require("../../util/constants").DEFAULT_LOG_LEVEL;var Log=require("../../util/log");var _a=require("../../util"),buildLogLevels=_a.buildLogLevels,isDeepEqual=_a.isDeepEqual;var LocalParticipantV2=function(_super){__extends(LocalParticipantV2,_super);function LocalParticipantV2(encodingParameters,networkQualityConfiguration,options){var _this=this;options=Object.assign({logLevel:DEFAULT_LOG_LEVEL,LocalTrackPublicationV2:LocalTrackPublicationV2},options);_this=_super.call(this)||this;var logLevels=buildLogLevels(options.logLevel);Object.defineProperties(_this,{_bandwidthProfile:{value:null,writable:true},_bandwidthProfileRevision:{value:0,writable:true},_encodingParameters:{value:encodingParameters},_removeListeners:{value:new Map},_LocalTrackPublicationV2:{value:options.LocalTrackPublicationV2},_log:{value:options.log?options.log.createLog("default",_this):new Log("default",_this,logLevels,options.loggerName)},_publishedRevision:{writable:true,value:0},_revision:{writable:true,value:1},_signalingRegion:{value:null,writable:true},audioProcessors:{value:[],writable:true},bandwidthProfile:{enumerable:true,get:function(){return this._bandwidthProfile}},bandwidthProfileRevision:{enumerable:true,get:function(){return this._bandwidthProfileRevision}},networkQualityConfiguration:{enumerable:true,value:networkQualityConfiguration},revision:{enumerable:true,get:function(){return this._revision}},signalingRegion:{enumerable:true,get:function(){return this._signalingRegion}}});return _this}LocalParticipantV2.prototype.toString=function(){return"[LocalParticipantSignaling: "+this.sid+"]"};LocalParticipantV2.prototype.setSignalingRegion=function(signalingRegion){if(!this._signalingRegion){this._signalingRegion=signalingRegion}};LocalParticipantV2.prototype.setBandwidthProfile=function(bandwidthProfile){if(!isDeepEqual(this._bandwidthProfile,bandwidthProfile)){this._bandwidthProfile=JSON.parse(JSON.stringify(bandwidthProfile));this._bandwidthProfileRevision++;this.didUpdate()}};LocalParticipantV2.prototype.setAudioProcessors=function(audioProcessors){this.audioProcessors=audioProcessors};LocalParticipantV2.prototype.getParameters=function(){return this._encodingParameters};LocalParticipantV2.prototype.setParameters=function(encodingParameters){this._encodingParameters.update(encodingParameters);return this};LocalParticipantV2.prototype.update=function(published){if(this._publishedRevision>=published.revision){return this}this._publishedRevision=published.revision;published.tracks.forEach(function(publicationState){var localTrackPublicationV2=this.tracks.get(publicationState.id);if(localTrackPublicationV2){localTrackPublicationV2.update(publicationState)}},this);return this};LocalParticipantV2.prototype.updateMediaStates=function(mediaStates){if(!mediaStates||!mediaStates.tracks){return this}Array.from(this.tracks.values()).forEach(function(publication){var states=mediaStates.tracks[publication.sid];if(states){publication.updateMediaStates(states)}});return this};LocalParticipantV2.prototype._createLocalTrackPublicationSignaling=function(trackSender,name,priority,noiseCancellationVendor){return new this._LocalTrackPublicationV2(trackSender,name,priority,noiseCancellationVendor,{log:this._log})};LocalParticipantV2.prototype.addTrack=function(trackSender,name,priority,noiseCancellationVendor){var _this=this;_super.prototype.addTrack.call(this,trackSender,name,priority,noiseCancellationVendor);var publication=this.getPublication(trackSender);var isEnabled=publication.isEnabled,updatedPriority=publication.updatedPriority;var updated=function(){if(isEnabled!==publication.isEnabled||updatedPriority!==publication.updatedPriority){_this.didUpdate();isEnabled=publication.isEnabled;updatedPriority=publication.updatedPriority}};publication.on("updated",updated);this._removeListener(publication);this._removeListeners.set(publication,function(){return publication.removeListener("updated",updated)});this.didUpdate();return this};LocalParticipantV2.prototype._removeListener=function(publication){var removeListener=this._removeListeners.get(publication);if(removeListener){removeListener()}};LocalParticipantV2.prototype.getState=function(){return{revision:this.revision,tracks:Array.from(this.tracks.values()).map(function(track){return track.getState()})}};LocalParticipantV2.prototype.didUpdate=function(){this._revision++;this.emit("updated")};LocalParticipantV2.prototype.removeTrack=function(trackSender){var publication=_super.prototype.removeTrack.call(this,trackSender);if(publication){trackSender.removeClone(publication.trackTransceiver);this._removeListener(publication);this.didUpdate()}return publication};LocalParticipantV2.prototype.setNetworkQualityConfiguration=function(networkQualityConfiguration){this.networkQualityConfiguration.update(networkQualityConfiguration)};LocalParticipantV2.prototype.setPublisherHint=function(trackSid,encodings){var trackSignaling=Array.from(this.tracks.values()).find(function(trackPub){return trackPub.sid===trackSid});if(!trackSignaling){this._log.warn("track:"+trackSid+" not found");return Promise.resolve("UNKNOWN_TRACK")}return trackSignaling.trackTransceiver.setPublisherHint(encodings)};return LocalParticipantV2}(LocalParticipantSignaling);module.exports=LocalParticipantV2},{"../../util":131,"../../util/constants":124,"../../util/log":135,"../localparticipant":58,"./localtrackpublication":72}],72:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var LocalTrackPublicationSignaling=require("../localtrackpublication");var TwilioWarning=require("../../util/twiliowarning");var createTwilioError=require("../../util/twilio-video-errors").createTwilioError;var LocalTrackPublicationV2=function(_super){__extends(LocalTrackPublicationV2,_super);function LocalTrackPublicationV2(trackSender,name,priority,noiseCancellationVendor,options){var _this=_super.call(this,trackSender,name,priority)||this;Object.defineProperties(_this,{_log:{value:options.log.createLog("default",_this)},_mediaStates:{value:{recordings:null},writable:true},_noiseCancellationVendor:{value:noiseCancellationVendor}});return _this}LocalTrackPublicationV2.prototype.getState=function(){var state={enabled:this.isEnabled,id:this.id,kind:this.kind,name:this.name,priority:this.updatedPriority};if(this._noiseCancellationVendor){state.audio_processor=this._noiseCancellationVendor}return state};LocalTrackPublicationV2.prototype.toString=function(){return"[LocalTrackPublicationV2: "+this.sid+"]"};LocalTrackPublicationV2.prototype.update=function(track){switch(track.state){case"ready":this.setSid(track.sid);break;case"failed":{var error=track.error;this.publishFailed(createTwilioError(error.code,error.message));break}default:break}return this};LocalTrackPublicationV2.prototype.updateMediaStates=function(mediaStates){if(!mediaStates||!mediaStates.recordings||this._mediaStates.recordings===mediaStates.recordings){return this}this._mediaStates.recordings=mediaStates.recordings;switch(this._mediaStates.recordings){case"OK":this._log.info("Warnings have cleared.");this.emit("warningsCleared");break;case"NO_MEDIA":this._log.warn("Recording media lost.");this.emit("warning",TwilioWarning.recordingMediaLost);break;default:this._log.warn("Unknown media state detected: "+this._mediaStates.recordings);break}return this};return LocalTrackPublicationV2}(LocalTrackPublicationSignaling);module.exports=LocalTrackPublicationV2},{"../../util/twilio-video-errors":146,"../../util/twiliowarning":148,"../localtrackpublication":59}],73:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var EventEmitter=require("events");var nInstances=0;var MediaSignaling=function(_super){__extends(MediaSignaling,_super);function MediaSignaling(getReceiver,channel,options){var _this=_super.call(this)||this;Object.defineProperties(_this,{_instanceId:{value:nInstances++},channel:{value:channel},_log:{value:options.log.createLog("default",_this)},_getReceiver:{value:getReceiver},_receiverPromise:{value:null,writable:true},_transport:{value:null,writable:true}});return _this}Object.defineProperty(MediaSignaling.prototype,"isSetup",{get:function(){return!!this._receiverPromise},enumerable:false,configurable:true});MediaSignaling.prototype.toString=function(){return"[MediaSignaling #"+this._instanceId+":"+this.channel+"]"};MediaSignaling.prototype.setup=function(id){var _this=this;this._teardown();this._log.info("setting up msp transport for id:",id);var receiverPromise=this._getReceiver(id).then(function(receiver){if(receiver.kind!=="data"){_this._log.error("Expected a DataTrackReceiver")}if(_this._receiverPromise!==receiverPromise){return}try{_this._transport=receiver.toDataTransport();_this.emit("ready",_this._transport)}catch(ex){_this._log.error("Failed to toDataTransport: "+ex.message)}receiver.once("close",function(){return _this._teardown()})});this._receiverPromise=receiverPromise};MediaSignaling.prototype._teardown=function(){if(this._transport){this._log.info("Tearing down");this._transport=null;this._receiverPromise=null;this.emit("teardown")}};return MediaSignaling}(EventEmitter);module.exports=MediaSignaling},{events:173}],74:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var EventEmitter=require("events");var PeerConnectionReportFactory=require("../../stats/peerconnectionreportfactory");var NetworkQualityMonitor=function(_super){__extends(NetworkQualityMonitor,_super);function NetworkQualityMonitor(manager,signaling){var _this=_super.call(this)||this;Object.defineProperties(_this,{_factories:{value:new WeakMap},_manager:{value:manager},_signaling:{value:signaling}});signaling.on("updated",function(){return _this.emit("updated")});return _this}Object.defineProperty(NetworkQualityMonitor.prototype,"level",{get:function(){return this._signaling.level},enumerable:false,configurable:true});Object.defineProperty(NetworkQualityMonitor.prototype,"levels",{get:function(){return this._signaling.levels},enumerable:false,configurable:true});Object.defineProperty(NetworkQualityMonitor.prototype,"remoteLevels",{get:function(){return this._signaling.remoteLevels},enumerable:false,configurable:true});NetworkQualityMonitor.prototype.start=function(){var _this=this;this.stop();var timeout=setTimeout(function(){if(_this._timeout!==timeout){return}next(_this).then(function(reports){if(_this._timeout!==timeout){return}if(reports.length){var _a=__read(reports,1),report=_a[0];_this._signaling.put(report)}_this.start()})},200);this._timeout=timeout};NetworkQualityMonitor.prototype.stop=function(){clearTimeout(this._timeout);this._timeout=null};return NetworkQualityMonitor}(EventEmitter);function next(monitor){var pcv2s=monitor._manager._peerConnections?Array.from(monitor._manager._peerConnections.values()):[];var pcs=pcv2s.map(function(pcv2){return pcv2._peerConnection}).filter(function(pc){return pc.signalingState!=="closed"});var factories=pcs.map(function(pc){if(monitor._factories.has(pc)){return monitor._factories.get(pc)}var factory=new PeerConnectionReportFactory(pc);monitor._factories.set(pc,factory);return factory});var reportsOrNullPromises=factories.map(function(factory){return factory.next().catch(function(){return null})});return Promise.all(reportsOrNullPromises).then(function(reportsOrNull){return reportsOrNull.filter(function(reportOrNull){return reportOrNull}).map(function(report){return report.summarize()})})}module.exports=NetworkQualityMonitor},{"../../stats/peerconnectionreportfactory":105,events:173}],75:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var MediaSignaling=require("./mediasignaling");var AsyncVar=require("../../util/asyncvar");var Timeout=require("../../util/timeout");var NETWORK_QUALITY_RESPONSE_TIME_MS=5e3;var NetworkQualitySignaling=function(_super){__extends(NetworkQualitySignaling,_super);function NetworkQualitySignaling(getReceiver,networkQualityConfiguration,options){var _this=_super.call(this,getReceiver,"network_quality",options)||this;Object.defineProperties(_this,{_level:{value:null,writable:true},_levels:{value:null,writable:true},_remoteLevels:{value:new Map,writable:true},_networkQualityInputs:{value:new AsyncVar},_resendTimer:{value:new Timeout(function(){_this._resendTimer.setDelay(_this._resendTimer.delay*1.5);_this._sendNetworkQualityInputs()},NETWORK_QUALITY_RESPONSE_TIME_MS,false)},_networkQualityReportLevels:{get:function(){return{reportLevel:networkQualityConfiguration.local,remoteReportLevel:networkQualityConfiguration.remote}}}});_this.on("ready",function(transport){transport.on("message",function(message){_this._log.debug("Incoming: ",message);switch(message.type){case"network_quality":_this._handleNetworkQualityMessage(message);break;default:break}})});_this._sendNetworkQualityInputs();return _this}Object.defineProperty(NetworkQualitySignaling.prototype,"level",{get:function(){return this._level},enumerable:false,configurable:true});Object.defineProperty(NetworkQualitySignaling.prototype,"levels",{get:function(){return this._levels},enumerable:false,configurable:true});Object.defineProperty(NetworkQualitySignaling.prototype,"remoteLevels",{get:function(){return this._remoteLevels},enumerable:false,configurable:true});NetworkQualitySignaling.prototype._handleNetworkQualityMessage=function(message){var _this=this;var updated=false;var level=null;var local=message?message.local:null;if(typeof local==="number"){level=local;this._levels=null}else if(typeof local==="object"&&local){this._levels=local;level=typeof local.level==="number"?local.level:Math.min(local.audio.send,local.audio.recv,local.video.send,local.video.recv)}if(level!==null&&this.level!==level){this._level=level;updated=true}this._remoteLevels=message&&message.remotes?message.remotes.reduce(function(levels,obj){var oldObj=_this._remoteLevels.get(obj.sid)||{};if(oldObj.level!==obj.level){updated=true}return levels.set(obj.sid,obj)},new Map):this._remoteLevels;if(updated){this.emit("updated")}this._resendTimer.setDelay(NETWORK_QUALITY_RESPONSE_TIME_MS);if(this._resendTimer.isSet){setTimeout(function(){return _this._sendNetworkQualityInputs()},1e3)}};NetworkQualitySignaling.prototype._sendNetworkQualityInputs=function(){var _this=this;this._resendTimer.clear();return this._networkQualityInputs.take().then(function(networkQualityInputs){if(_this._transport){_this._transport.publish(createNetworkQualityInputsMessage(networkQualityInputs,_this._networkQualityReportLevels))}}).finally(function(){_this._resendTimer.start()})};NetworkQualitySignaling.prototype.put=function(networkQualityInputs){this._networkQualityInputs.put(networkQualityInputs)};return NetworkQualitySignaling}(MediaSignaling);function createNetworkQualityInputsMessage(networkQualityInputs,networkQualityReportLevels){return Object.assign({type:"network_quality"},networkQualityInputs,networkQualityReportLevels)}module.exports=NetworkQualitySignaling},{"../../util/asyncvar":120,"../../util/timeout":145,"./mediasignaling":73}],76:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var __spreadArray=this&&this.__spreadArray||function(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to};var DefaultBackoff=require("../../util/backoff");var _a=require("../../webrtc"),DefaultRTCIceCandidate=_a.RTCIceCandidate,DefaultRTCPeerConnection=_a.RTCPeerConnection,DefaultRTCSessionDescription=_a.RTCSessionDescription,getStatistics=_a.getStats;var util=require("../../webrtc/util");var _b=require("../../util/constants"),DEFAULT_ICE_GATHERING_TIMEOUT_MS=_b.DEFAULT_ICE_GATHERING_TIMEOUT_MS,DEFAULT_LOG_LEVEL=_b.DEFAULT_LOG_LEVEL,DEFAULT_SESSION_TIMEOUT_SEC=_b.DEFAULT_SESSION_TIMEOUT_SEC,iceRestartBackoffConfig=_b.iceRestartBackoffConfig;var _c=require("../../util/sdp"),addOrRewriteNewTrackIds=_c.addOrRewriteNewTrackIds,addOrRewriteTrackIds=_c.addOrRewriteTrackIds,createCodecMapForMediaSection=_c.createCodecMapForMediaSection,disableRtx=_c.disableRtx,enableDtxForOpus=_c.enableDtxForOpus,filterLocalCodecs=_c.filterLocalCodecs,getMediaSections=_c.getMediaSections,removeSSRCAttributes=_c.removeSSRCAttributes,revertSimulcast=_c.revertSimulcast,setCodecPreferences=_c.setCodecPreferences,setSimulcast=_c.setSimulcast
46
46
  ;var DefaultTimeout=require("../../util/timeout");var _d=require("../../util/twilio-video-errors"),MediaClientLocalDescFailedError=_d.MediaClientLocalDescFailedError,MediaClientRemoteDescFailedError=_d.MediaClientRemoteDescFailedError;var _e=require("../../util"),buildLogLevels=_e.buildLogLevels,getPlatform=_e.getPlatform,isChromeScreenShareTrack=_e.isChromeScreenShareTrack,oncePerTick=_e.oncePerTick,defer=_e.defer;var IceBox=require("./icebox");var DefaultIceConnectionMonitor=require("./iceconnectionmonitor.js");var DataTrackReceiver=require("../../data/receiver");var MediaTrackReceiver=require("../../media/track/receiver");var StateMachine=require("../../statemachine");var Log=require("../../util/log");var TrackMatcher=require("../../util/sdp/trackmatcher");var workaroundIssue8329=require("../../util/sdp/issue8329");var guess=util.guessBrowser();var platform=getPlatform();var isAndroid=/android/.test(platform);var isChrome=guess==="chrome";var isFirefox=guess==="firefox";var isSafari=guess==="safari";var nInstances=0;var states={open:["closed","updating"],updating:["closed","open"],closed:[]};var PeerConnectionV2=function(_super){__extends(PeerConnectionV2,_super);function PeerConnectionV2(id,encodingParameters,preferredCodecs,options){var _this=_super.call(this,"open",states)||this;options=Object.assign({enableDscp:false,dummyAudioMediaStreamTrack:null,isChromeScreenShareTrack:isChromeScreenShareTrack,iceServers:[],logLevel:DEFAULT_LOG_LEVEL,offerOptions:{},revertSimulcast:revertSimulcast,sessionTimeout:DEFAULT_SESSION_TIMEOUT_SEC*1e3,setCodecPreferences:setCodecPreferences,setSimulcast:setSimulcast,Backoff:DefaultBackoff,IceConnectionMonitor:DefaultIceConnectionMonitor,RTCIceCandidate:DefaultRTCIceCandidate,RTCPeerConnection:DefaultRTCPeerConnection,RTCSessionDescription:DefaultRTCSessionDescription,Timeout:DefaultTimeout},options);var configuration=getConfiguration(options);var logLevels=buildLogLevels(options.logLevel);var RTCPeerConnection=options.RTCPeerConnection;if(options.enableDscp===true){options.chromeSpecificConstraints=options.chromeSpecificConstraints||{};options.chromeSpecificConstraints.optional=options.chromeSpecificConstraints.optional||[];options.chromeSpecificConstraints.optional.push({googDscp:true})}var log=options.log?options.log.createLog("webrtc",_this):new Log("webrtc",_this,logLevels,options.loggerName);var peerConnection=new RTCPeerConnection(configuration,options.chromeSpecificConstraints);if(options.dummyAudioMediaStreamTrack){peerConnection.addTrack(options.dummyAudioMediaStreamTrack)}Object.defineProperties(_this,{_appliedTrackIdsToAttributes:{value:new Map,writable:true},_dataChannels:{value:new Map},_dataTrackReceivers:{value:new Set},_descriptionRevision:{writable:true,value:0},_didGenerateLocalCandidates:{writable:true,value:false},_enableDscp:{value:options.enableDscp},_encodingParameters:{value:encodingParameters},_isChromeScreenShareTrack:{value:options.isChromeScreenShareTrack},_iceGatheringFailed:{value:false,writable:true},_iceGatheringTimeout:{value:new options.Timeout(function(){return _this._handleIceGatheringTimeout()},DEFAULT_ICE_GATHERING_TIMEOUT_MS,false)},_iceRestartBackoff:{value:new options.Backoff(iceRestartBackoffConfig)},_instanceId:{value:++nInstances},_isIceConnectionInactive:{writable:true,value:false},_isIceLite:{writable:true,value:false},_isIceRestartBackoffInProgress:{writable:true,value:false},_isRestartingIce:{writable:true,value:false},_lastIceConnectionState:{writable:true,value:null},_lastStableDescriptionRevision:{writable:true,value:0},_localCandidates:{writable:true,value:[]},_localCodecs:{value:new Set},_localCandidatesRevision:{writable:true,value:1},_localDescriptionWithoutSimulcast:{writable:true,value:null},_localDescription:{writable:true,value:null},_localUfrag:{writable:true,value:null},_log:{value:log},_eventObserver:{value:options.eventObserver},_remoteCodecMaps:{value:new Map},_rtpSenders:{value:new Map},_rtpNewSenders:{value:new Set},_iceConnectionMonitor:{value:new options.IceConnectionMonitor(peerConnection)},_mediaTrackReceivers:{value:new Set},_needsAnswer:{writable:true,value:false},_negotiationRole:{writable:true,value:null},_offerOptions:{writable:true,value:options.offerOptions},_onEncodingParametersChanged:{value:oncePerTick(function(){if(!_this._needsAnswer){updateEncodingParameters(_this)}})},_peerConnection:{value:peerConnection},_preferredAudioCodecs:{value:preferredCodecs.audio},_preferredVideoCodecs:{value:preferredCodecs.video},_shouldApplyDtx:{value:preferredCodecs.audio.every(function(_a){var codec=_a.codec;return codec!=="opus"})||preferredCodecs.audio.some(function(_a){var codec=_a.codec,dtx=_a.dtx;return codec==="opus"&&dtx})},_queuedDescription:{writable:true,value:null},_iceReconnectTimeout:{value:new options.Timeout(function(){log.debug("ICE reconnect timed out");_this.close()},options.sessionTimeout,false)},_recycledTransceivers:{value:{audio:[],video:[]}},_replaceTrackPromises:{value:new Map},_remoteCandidates:{writable:true,value:new IceBox},_setCodecPreferences:{value:isFirefox&&isAndroid&&preferredCodecs.video[0]&&preferredCodecs.video[0].codec.toLowerCase()!=="h264"?function(sdp){return sdp}:options.setCodecPreferences},_setSimulcast:{value:options.setSimulcast},_revertSimulcast:{value:options.revertSimulcast},_RTCIceCandidate:{value:options.RTCIceCandidate},_RTCPeerConnection:{value:options.RTCPeerConnection},_RTCSessionDescription:{value:options.RTCSessionDescription},_shouldOffer:{writable:true,value:false},_shouldRestartIce:{writable:true,value:false},_trackIdsToAttributes:{value:new Map,writable:true},_trackMatcher:{writable:true,value:null},_mediaTrackSenderToPublisherHints:{value:new Map},id:{enumerable:true,value:id}});encodingParameters.on("changed",_this._onEncodingParametersChanged);peerConnection.addEventListener("connectionstatechange",_this._handleConnectionStateChange.bind(_this));peerConnection.addEventListener("datachannel",_this._handleDataChannelEvent.bind(_this));peerConnection.addEventListener("icecandidate",_this._handleIceCandidateEvent.bind(_this));peerConnection.addEventListener("iceconnectionstatechange",_this._handleIceConnectionStateChange.bind(_this));peerConnection.addEventListener("icegatheringstatechange",_this._handleIceGatheringStateChange.bind(_this));peerConnection.addEventListener("signalingstatechange",_this._handleSignalingStateChange.bind(_this));peerConnection.addEventListener("track",_this._handleTrackEvent.bind(_this));var self=_this;_this.on("stateChanged",function stateChanged(state){if(state!=="closed"){return}self.removeListener("stateChanged",stateChanged);self._dataChannels.forEach(function(dataChannel,dataTrackSender){self.removeDataTrackSender(dataTrackSender)})});return _this}PeerConnectionV2.prototype.toString=function(){return"[PeerConnectionV2 #"+this._instanceId+": "+this.id+"]"};PeerConnectionV2.prototype.setEffectiveAdaptiveSimulcast=function(effectiveAdaptiveSimulcast){this._log.debug("Setting setEffectiveAdaptiveSimulcast: ",effectiveAdaptiveSimulcast);this._preferredVideoCodecs.forEach(function(cs){if("adaptiveSimulcast"in cs){cs.adaptiveSimulcast=effectiveAdaptiveSimulcast}})};Object.defineProperty(PeerConnectionV2.prototype,"_shouldApplySimulcast",{get:function(){if(!isChrome&&!isSafari){return false}var simulcast=this._preferredVideoCodecs.some(function(cs){return cs.codec.toLowerCase()==="vp8"&&cs.simulcast&&cs.adaptiveSimulcast!==false});return simulcast},enumerable:false,configurable:true});Object.defineProperty(PeerConnectionV2.prototype,"connectionState",{get:function(){return this.iceConnectionState==="failed"?"failed":this._peerConnection.connectionState||this.iceConnectionState},enumerable:false,configurable:true});Object.defineProperty(PeerConnectionV2.prototype,"iceConnectionState",{get:function(){return this._isIceConnectionInactive&&this._peerConnection.iceConnectionState==="disconnected"||this._iceGatheringFailed?"failed":this._peerConnection.iceConnectionState},enumerable:false,configurable:true});Object.defineProperty(PeerConnectionV2.prototype,"isApplicationSectionNegotiated",{get:function(){if(this._peerConnection.signalingState!=="closed"){return this._peerConnection.localDescription?getMediaSections(this._peerConnection.localDescription.sdp,"application").length>0:false}return true},enumerable:false,configurable:true});Object.defineProperty(PeerConnectionV2.prototype,"_isAdaptiveSimulcastEnabled",{get:function(){var adaptiveSimulcastEntry=this._preferredVideoCodecs.find(function(cs){return"adaptiveSimulcast"in cs});return adaptiveSimulcastEntry&&adaptiveSimulcastEntry.adaptiveSimulcast===true},enumerable:false,configurable:true});PeerConnectionV2.prototype._maybeUpdateEncodings=function(track,encodings,trackReplaced){if(trackReplaced===void 0){trackReplaced=false}if(track.kind!=="video"||track.readyState==="ended"){return false}var _a=track.getSettings(),height=_a.height,width=_a.width;if(typeof height!=="number"||typeof width!=="number"){return false}var browser=util.guessBrowser();if(browser==="safari"||browser==="chrome"&&this._isAdaptiveSimulcastEnabled){this._updateEncodings(track,encodings,trackReplaced);return true}return false};PeerConnectionV2.prototype._updateEncodings=function(track,encodings,trackReplaced){if(this._isChromeScreenShareTrack(track)){var screenShareActiveLayerConfig_1=[{scaleResolutionDownBy:1},{scaleResolutionDownBy:1}];encodings.forEach(function(encoding,i){var activeLayerConfig=screenShareActiveLayerConfig_1[i];if(activeLayerConfig){encoding.scaleResolutionDownBy=activeLayerConfig.scaleResolutionDownBy;if(trackReplaced){delete encoding.active}}else{encoding.active=false;delete encoding.scaleResolutionDownBy}})}else{var _a=track.getSettings(),width=_a.width,height=_a.height;var pixelsToMaxActiveLayers=[{pixels:960*540,maxActiveLayers:3},{pixels:480*270,maxActiveLayers:2},{pixels:0,maxActiveLayers:1}];var trackPixels_1=width*height;var activeLayersInfo=pixelsToMaxActiveLayers.find(function(layer){return trackPixels_1>=layer.pixels});var activeLayers_1=Math.min(encodings.length,activeLayersInfo.maxActiveLayers);encodings.forEach(function(encoding,i){var enabled=i<activeLayers_1;if(enabled){encoding.scaleResolutionDownBy=1<<activeLayers_1-i-1;if(trackReplaced){encoding.active=true}}else{encoding.active=false;delete encoding.scaleResolutionDownBy}})}this._log.debug("_updateEncodings:",encodings.map(function(_a,i){var active=_a.active,scaleResolutionDownBy=_a.scaleResolutionDownBy;return"["+i+": "+active+", "+(scaleResolutionDownBy||0)+"]"}).join(", "))};PeerConnectionV2.prototype._addIceCandidate=function(candidate){var _this=this;return Promise.resolve().then(function(){candidate=new _this._RTCIceCandidate(candidate);return _this._peerConnection.addIceCandidate(candidate)}).catch(function(error){_this._log.warn("Failed to add RTCIceCandidate "+(candidate?'"'+candidate.candidate+'"':"null")+": "+error.message)})};PeerConnectionV2.prototype._addIceCandidates=function(candidates){return Promise.all(candidates.map(this._addIceCandidate,this)).then(function(){})};PeerConnectionV2.prototype._addOrUpdateTransceiver=function(track){var _this=this;var transceiver=takeRecycledTransceiver(this,track.kind);if(transceiver&&transceiver.sender){var oldTrackId=transceiver.sender.track?transceiver.sender.track.id:null;if(oldTrackId){this._log.warn("Reusing transceiver: "+transceiver.mid+"] "+oldTrackId+" => "+track.id)}this._replaceTrackPromises.set(transceiver,transceiver.sender.replaceTrack(track).then(function(){transceiver.direction="sendrecv"},function(){}).finally(function(){_this._replaceTrackPromises.delete(transceiver)}));return transceiver}return this._peerConnection.addTransceiver(track)};PeerConnectionV2.prototype._checkIceBox=function(description){var ufrag=getUfrag(description);if(!ufrag){return Promise.resolve()}var candidates=this._remoteCandidates.setUfrag(ufrag);return this._addIceCandidates(candidates)};PeerConnectionV2.prototype._answer=function(offer){var _this=this;return Promise.resolve().then(function(){if(!_this._negotiationRole){_this._negotiationRole="answerer"}return _this._setRemoteDescription(offer)}).catch(function(){throw new MediaClientRemoteDescFailedError}).then(function(){return _this._peerConnection.createAnswer()}).then(function(answer){if(isFirefox){answer=new _this._RTCSessionDescription({sdp:disableRtx(answer.sdp),type:answer.type})}else{answer=workaroundIssue8329(answer)}var updatedSdp=removeSSRCAttributes(answer.sdp,["mslabel","label"]);if(_this._shouldApplySimulcast){var sdpWithoutSimulcast=updatedSdp;updatedSdp=_this._setSimulcast(sdpWithoutSimulcast,_this._trackIdsToAttributes);updatedSdp=_this._revertSimulcast(updatedSdp,sdpWithoutSimulcast,offer.sdp)}updatedSdp=updatedSdp.replace(/42e015/g,"42e01f");return _this._setLocalDescription({type:answer.type,sdp:updatedSdp})}).then(function(){return _this._checkIceBox(offer)}).then(function(){return _this._queuedDescription&&_this._updateDescription(_this._queuedDescription)}).then(function(){_this._queuedDescription=null;return _this._maybeReoffer(_this._peerConnection.localDescription)}).catch(function(error){var errorToThrow=error instanceof MediaClientRemoteDescFailedError?error:new MediaClientLocalDescFailedError;_this._publishMediaWarning({message:"Failed to _answer",code:errorToThrow.code,error:error});throw errorToThrow})};PeerConnectionV2.prototype._close=function(){this._iceConnectionMonitor.stop();if(this._peerConnection.signalingState!=="closed"){this._peerConnection.close();this.preempt("closed");this._encodingParameters.removeListener("changed",this._onEncodingParametersChanged);return true}return false};PeerConnectionV2.prototype._handleConnectionStateChange=function(){this.emit("connectionStateChanged")};PeerConnectionV2.prototype._handleDataChannelEvent=function(event){var _this=this;var dataChannel=event.channel;var dataTrackReceiver=new DataTrackReceiver(dataChannel);this._dataTrackReceivers.add(dataTrackReceiver);dataChannel.addEventListener("close",function(){_this._dataTrackReceivers.delete(dataTrackReceiver)});this.emit("trackAdded",dataTrackReceiver)};PeerConnectionV2.prototype._handleGlare=function(offer){var _this=this;this._log.debug("Glare detected; rolling back");if(this._isRestartingIce){this._log.debug("An ICE restart was in progress; we'll need to restart ICE again after rolling back");this._isRestartingIce=false;this._shouldRestartIce=true}return Promise.resolve().then(function(){_this._trackIdsToAttributes=new Map(_this._appliedTrackIdsToAttributes);return _this._setLocalDescription({type:"rollback"})}).then(function(){_this._needsAnswer=false;return _this._answer(offer)}).then(function(didReoffer){return didReoffer?Promise.resolve():_this._offer()})};PeerConnectionV2.prototype._publishMediaWarning=function(_a){var message=_a.message,code=_a.code,error=_a.error,sdp=_a.sdp;this._eventObserver.emit("event",{level:"warning",name:"error",group:"media",payload:{message:message,code:code,context:JSON.stringify({error:error.message,sdp:sdp})}})};PeerConnectionV2.prototype._handleIceCandidateEvent=function(event){if(event.candidate){this._log.debug("Clearing ICE gathering timeout");this._didGenerateLocalCandidates=true;this._iceGatheringTimeout.clear();this._localCandidates.push(event.candidate)}var peerConnectionState={ice:{candidates:this._isIceLite?[]:this._localCandidates.slice(),ufrag:this._localUfrag},id:this.id};if(!event.candidate){peerConnectionState.ice.complete=true}if(!(this._isIceLite&&event.candidate)){peerConnectionState.ice.revision=this._localCandidatesRevision++;this.emit("candidates",peerConnectionState)}};PeerConnectionV2.prototype._handleIceConnectionStateChange=function(){var _this=this;var iceConnectionState=this._peerConnection.iceConnectionState;var isIceConnectedOrComplete=["connected","completed"].includes(iceConnectionState);var log=this._log;log.debug('ICE connection state is "'+iceConnectionState+'"');if(isIceConnectedOrComplete){this._iceReconnectTimeout.clear();this._iceRestartBackoff.reset()}if(this._lastIceConnectionState!=="failed"&&iceConnectionState==="failed"&&!this._shouldRestartIce&&!this._isRestartingIce){log.warn("ICE failed");this._initiateIceRestartBackoff()}else if(["disconnected","failed"].includes(this._lastIceConnectionState)&&isIceConnectedOrComplete){log.debug("ICE reconnected")}if(iceConnectionState==="connected"){this._isIceConnectionInactive=false;this._iceConnectionMonitor.start(function(){_this._iceConnectionMonitor.stop();if(!_this._shouldRestartIce&&!_this._isRestartingIce){log.warn("ICE Connection Monitor detected inactivity");_this._isIceConnectionInactive=true;_this._initiateIceRestartBackoff();_this.emit("iceConnectionStateChanged");_this.emit("connectionStateChanged")}})}else if(!["disconnected","completed"].includes(iceConnectionState)){this._iceConnectionMonitor.stop();this._isIceConnectionInactive=false}this._lastIceConnectionState=iceConnectionState;this.emit("iceConnectionStateChanged")};PeerConnectionV2.prototype._handleIceGatheringTimeout=function(){this._log.warn("ICE failed to gather any local candidates");this._iceGatheringFailed=true;this._initiateIceRestartBackoff();this.emit("iceConnectionStateChanged");this.emit("connectionStateChanged")};PeerConnectionV2.prototype._handleIceGatheringStateChange=function(){var iceGatheringState=this._peerConnection.iceGatheringState;var log=this._log;log.debug('ICE gathering state is "'+iceGatheringState+'"');var _a=this._iceGatheringTimeout,delay=_a.delay,isSet=_a.isSet;if(iceGatheringState==="gathering"&&!this._didGenerateLocalCandidates&&!isSet){log.debug("Starting ICE gathering timeout: "+delay);this._iceGatheringFailed=false;this._iceGatheringTimeout.start()}};PeerConnectionV2.prototype._handleSignalingStateChange=function(){if(this._peerConnection.signalingState==="stable"){this._appliedTrackIdsToAttributes=new Map(this._trackIdsToAttributes)}};PeerConnectionV2.prototype._handleTrackEvent=function(event){var _this=this;var sdp=this._peerConnection.remoteDescription?this._peerConnection.remoteDescription.sdp:null;this._trackMatcher=this._trackMatcher||new TrackMatcher;this._trackMatcher.update(sdp);var mediaStreamTrack=event.track;var signaledTrackId=this._trackMatcher.match(event)||mediaStreamTrack.id;var mediaTrackReceiver=new MediaTrackReceiver(signaledTrackId,mediaStreamTrack);this._mediaTrackReceivers.forEach(function(trackReceiver){if(trackReceiver.track.id===mediaTrackReceiver.track.id){_this._mediaTrackReceivers.delete(trackReceiver)}});this._mediaTrackReceivers.add(mediaTrackReceiver);mediaStreamTrack.addEventListener("ended",function(){return _this._mediaTrackReceivers.delete(mediaTrackReceiver)});this.emit("trackAdded",mediaTrackReceiver)};PeerConnectionV2.prototype._initiateIceRestart=function(){if(this._peerConnection.signalingState==="closed"){return}var log=this._log;log.warn("Attempting to restart ICE");this._didGenerateLocalCandidates=false;this._isIceRestartBackoffInProgress=false;this._shouldRestartIce=true;var _a=this._iceReconnectTimeout,delay=_a.delay,isSet=_a.isSet;if(!isSet){log.debug("Starting ICE reconnect timeout: "+delay);this._iceReconnectTimeout.start()}this.offer().catch(function(ex){log.error("offer failed in _initiateIceRestart with: "+ex.message)})};PeerConnectionV2.prototype._initiateIceRestartBackoff=function(){var _this=this;if(this._peerConnection.signalingState==="closed"||this._isIceRestartBackoffInProgress){return}this._log.warn("An ICE restart has been scheduled");this._isIceRestartBackoffInProgress=true;this._iceRestartBackoff.backoff(function(){return _this._initiateIceRestart()})};PeerConnectionV2.prototype._maybeReoffer=function(localDescription){var shouldReoffer=this._shouldOffer;if(localDescription&&localDescription.sdp){var senders_1=this._peerConnection.getSenders().filter(function(sender){return sender.track});shouldReoffer=["audio","video"].reduce(function(shouldOffer,kind){var mediaSections=getMediaSections(localDescription.sdp,kind,"(sendrecv|sendonly)");var sendersOfKind=senders_1.filter(isSenderOfKind.bind(null,kind));return shouldOffer||mediaSections.length<sendersOfKind.length},shouldReoffer);var hasDataTrack=this._dataChannels.size>0;var hasApplicationMediaSection=getMediaSections(localDescription.sdp,"application").length>0;var needsApplicationMediaSection=hasDataTrack&&!hasApplicationMediaSection;shouldReoffer=shouldReoffer||needsApplicationMediaSection}var promise=shouldReoffer?this._offer():Promise.resolve();return promise.then(function(){return shouldReoffer})};PeerConnectionV2.prototype._offer=function(){var _this=this;var offerOptions=Object.assign({},this._offerOptions);this._needsAnswer=true;if(this._shouldRestartIce){this._shouldRestartIce=false;this._isRestartingIce=true;offerOptions.iceRestart=true}return Promise.all(this._replaceTrackPromises.values()).then(function(){return _this._peerConnection.createOffer(offerOptions)}).catch(function(error){var errorToThrow=new MediaClientLocalDescFailedError;_this._publishMediaWarning({message:"Failed to create offer",code:errorToThrow.code,error:error});throw errorToThrow}).then(function(offer){if(isFirefox){offer=new _this._RTCSessionDescription({sdp:disableRtx(offer.sdp),type:offer.type})}else{offer=workaroundIssue8329(offer)}var sdp=removeSSRCAttributes(offer.sdp,["mslabel","label"]);sdp=_this._peerConnection.remoteDescription?filterLocalCodecs(sdp,_this._peerConnection.remoteDescription.sdp):sdp;var updatedSdp=_this._setCodecPreferences(sdp,_this._preferredAudioCodecs,_this._preferredVideoCodecs);_this._shouldOffer=false;if(!_this._negotiationRole){_this._negotiationRole="offerer"}if(_this._shouldApplySimulcast){_this._localDescriptionWithoutSimulcast={type:"offer",sdp:updatedSdp};updatedSdp=_this._setSimulcast(updatedSdp,_this._trackIdsToAttributes)}return _this._setLocalDescription({type:"offer",sdp:updatedSdp})})};PeerConnectionV2.prototype._getMediaTrackSenderId=function(trackId){var mediaTrackSender=Array.from(this._rtpSenders.keys()).find(function(_a){var id=_a.track.id;return id===trackId});return mediaTrackSender?mediaTrackSender.id:trackId};PeerConnectionV2.prototype._addOrRewriteLocalTrackIds=function(description){var _this=this;var transceivers=this._peerConnection.getTransceivers();var activeTransceivers=transceivers.filter(function(_a){var sender=_a.sender,stopped=_a.stopped;return!stopped&&sender&&sender.track});var assignedTransceivers=activeTransceivers.filter(function(_a){var mid=_a.mid;return mid});var midsToTrackIds=new Map(assignedTransceivers.map(function(_a){var mid=_a.mid,sender=_a.sender;return[mid,_this._getMediaTrackSenderId(sender.track.id)]}));var sdp1=addOrRewriteTrackIds(description.sdp,midsToTrackIds);var unassignedTransceivers=activeTransceivers.filter(function(_a){var mid=_a.mid;return!mid});var newTrackIdsByKind=new Map(["audio","video"].map(function(kind){return[kind,unassignedTransceivers.filter(function(_a){var sender=_a.sender;return sender.track.kind===kind}).map(function(_a){var sender=_a.sender;return _this._getMediaTrackSenderId(sender.track.id)})]}));var sdp2=addOrRewriteNewTrackIds(sdp1,midsToTrackIds,newTrackIdsByKind);return new this._RTCSessionDescription({sdp:sdp2,type:description.type})};PeerConnectionV2.prototype._rollbackAndApplyOffer=function(offer){var _this=this;return this._setLocalDescription({type:"rollback"}).then(function(){return _this._setLocalDescription(offer)})};PeerConnectionV2.prototype._setLocalDescription=function(description){var _this=this;if(description.type!=="rollback"&&this._shouldApplyDtx){description=new this._RTCSessionDescription({sdp:enableDtxForOpus(description.sdp),type:description.type})}return this._peerConnection.setLocalDescription(description).catch(function(error){_this._log.warn('Calling setLocalDescription with an RTCSessionDescription of type "'+description.type+'" failed with the error "'+error.message+'".',error);var errorToThrow=new MediaClientLocalDescFailedError;var publishWarning={message:'Calling setLocalDescription with an RTCSessionDescription of type "'+description.type+'" failed',code:errorToThrow.code,error:error};if(description.sdp){_this._log.warn("The SDP was "+description.sdp);publishWarning.sdp=description.sdp}_this._publishMediaWarning(publishWarning);throw errorToThrow}).then(function(){if(description.type!=="rollback"){_this._localDescription=_this._addOrRewriteLocalTrackIds(description);if(_this._shouldApplyDtx){_this._localDescription=new _this._RTCSessionDescription({sdp:enableDtxForOpus(_this._localDescription.sdp,[]),type:_this._localDescription.type})}_this._localCandidates=[];if(description.type==="offer"){_this._descriptionRevision++}else if(description.type==="answer"){_this._lastStableDescriptionRevision=_this._descriptionRevision;negotiationCompleted(_this)}_this._localUfrag=getUfrag(description);_this.emit("description",_this.getState())}})};PeerConnectionV2.prototype._setRemoteDescription=function(description){var _this=this;if(description.sdp){description.sdp=this._setCodecPreferences(description.sdp,this._preferredAudioCodecs,this._preferredVideoCodecs);if(this._shouldApplyDtx){description.sdp=enableDtxForOpus(description.sdp)}else{description.sdp=enableDtxForOpus(description.sdp,[])}if(isFirefox){description.sdp=filterOutMediaStreamIds(description.sdp)}if(!this._peerConnection.remoteDescription){this._isIceLite=/a=ice-lite/.test(description.sdp)}}description=new this._RTCSessionDescription(description);return Promise.resolve().then(function(){if(description.type==="answer"&&_this._localDescriptionWithoutSimulcast){var adaptiveSimulcastEntry=_this._preferredVideoCodecs.find(function(cs){return"adaptiveSimulcast"in cs});var revertForAll=!!adaptiveSimulcastEntry&&adaptiveSimulcastEntry.adaptiveSimulcast===false;var sdpWithoutSimulcastForNonVP8MediaSections=_this._revertSimulcast(_this._localDescription.sdp,_this._localDescriptionWithoutSimulcast.sdp,description.sdp,revertForAll);_this._localDescriptionWithoutSimulcast=null;if(sdpWithoutSimulcastForNonVP8MediaSections!==_this._localDescription.sdp){return _this._rollbackAndApplyOffer({type:_this._localDescription.type,sdp:sdpWithoutSimulcastForNonVP8MediaSections})}}}).then(function(){return _this._peerConnection.setRemoteDescription(description)}).then(function(){if(description.type==="answer"){if(_this._isRestartingIce){_this._log.debug("An ICE restart was in-progress and is now completed");_this._isRestartingIce=false}negotiationCompleted(_this)}},function(error){_this._log.warn('Calling setRemoteDescription with an RTCSessionDescription of type "'+description.type+'" failed with the error "'+error.message+'".',error);if(description.sdp){_this._log.warn("The SDP was "+description.sdp)}throw error})};PeerConnectionV2.prototype._updateDescription=function(description){var _this=this;switch(description.type){case"answer":case"pranswer":if(description.revision!==this._descriptionRevision||this._peerConnection.signalingState!=="have-local-offer"){return Promise.resolve()}this._descriptionRevision=description.revision;break;case"close":return this._close();case"create-offer":if(description.revision<=this._lastStableDescriptionRevision){return Promise.resolve()}else if(this._needsAnswer){this._queuedDescription=description;return Promise.resolve()}this._descriptionRevision=description.revision;return this._offer();case"offer":if(description.revision<=this._lastStableDescriptionRevision||this._peerConnection.signalingState==="closed"){return Promise.resolve()}if(this._peerConnection.signalingState==="have-local-offer"){if(this._needsAnswer&&this._lastStableDescriptionRevision===0){this._queuedDescription=description;return Promise.resolve()}this._descriptionRevision=description.revision;return this._handleGlare(description)}this._descriptionRevision=description.revision;return this._answer(description).then(function(){});default:}var revision=description.revision;return Promise.resolve().then(function(){return _this._setRemoteDescription(description)}).catch(function(error){var errorToThrow=new MediaClientRemoteDescFailedError;_this._publishMediaWarning({message:'Calling setRemoteDescription with an RTCSessionDescription of type "'+description.type+'" failed',code:errorToThrow.code,error:error,sdp:description.sdp});throw errorToThrow}).then(function(){_this._lastStableDescriptionRevision=revision;_this._needsAnswer=false;return _this._checkIceBox(description)}).then(function(){return _this._queuedDescription&&_this._updateDescription(_this._queuedDescription)}).then(function(){_this._queuedDescription=null;return _this._maybeReoffer(_this._peerConnection.localDescription).then(function(){})})};PeerConnectionV2.prototype._updateIce=function(iceState){var candidates=this._remoteCandidates.update(iceState);return this._addIceCandidates(candidates)};PeerConnectionV2.prototype.addDataTrackSender=function(dataTrackSender){if(this._dataChannels.has(dataTrackSender)){return}try{var dataChannelDict={ordered:dataTrackSender.ordered};if(dataTrackSender.maxPacketLifeTime!==null){dataChannelDict.maxPacketLifeTime=dataTrackSender.maxPacketLifeTime}if(dataTrackSender.maxRetransmits!==null){dataChannelDict.maxRetransmits=dataTrackSender.maxRetransmits}var dataChannel=this._peerConnection.createDataChannel(dataTrackSender.id,dataChannelDict);dataTrackSender.addDataChannel(dataChannel);this._dataChannels.set(dataTrackSender,dataChannel)}catch(error){this._log.warn('Error creating an RTCDataChannel for DataTrack "'+dataTrackSender.id+'": '+error.message)}};PeerConnectionV2.prototype._handleQueuedPublisherHints=function(){var _this=this;if(this._peerConnection.signalingState==="stable"){this._mediaTrackSenderToPublisherHints.forEach(function(_a,mediaTrackSender){var deferred=_a.deferred,encodings=_a.encodings;_this._mediaTrackSenderToPublisherHints.delete(mediaTrackSender);_this._setPublisherHint(mediaTrackSender,encodings).then(function(result){return deferred.resolve(result)}).catch(function(error){return deferred.reject(error)})})}};PeerConnectionV2.prototype._setPublisherHint=function(mediaTrackSender,encodings){var _this=this;if(isFirefox){return Promise.resolve("COULD_NOT_APPLY_HINT")}if(this._mediaTrackSenderToPublisherHints.has(mediaTrackSender)){var queuedHint=this._mediaTrackSenderToPublisherHints.get(mediaTrackSender);queuedHint.deferred.resolve("REQUEST_SKIPPED");this._mediaTrackSenderToPublisherHints.delete(mediaTrackSender)}var sender=this._rtpSenders.get(mediaTrackSender);if(!sender){this._log.warn("Could not apply publisher hint because RTCRtpSender was not found");return Promise.resolve("UNKNOWN_TRACK")}if(this._peerConnection.signalingState==="closed"){this._log.warn('Could not apply publisher hint because signalingState was "closed"');return Promise.resolve("COULD_NOT_APPLY_HINT")}if(this._peerConnection.signalingState!=="stable"){this._log.debug("Queuing up publisher hint because signalingState:",this._peerConnection.signalingState);var deferred=defer();this._mediaTrackSenderToPublisherHints.set(mediaTrackSender,{deferred:deferred,encodings:encodings});return deferred.promise}var parameters=sender.getParameters();if(encodings!==null){encodings.forEach(function(_a){var enabled=_a.enabled,layerIndex=_a.layer_index;if(parameters.encodings.length>layerIndex){_this._log.debug("layer:"+layerIndex+", active:"+parameters.encodings[layerIndex].active+" => "+enabled);parameters.encodings[layerIndex].active=enabled}else{_this._log.warn("invalid layer:"+layerIndex+", active:"+enabled)}})}this._maybeUpdateEncodings(sender.track,parameters.encodings,encodings===null);return sender.setParameters(parameters).then(function(){return"OK"}).catch(function(error){_this._log.error("Failed to apply publisher hints:",error);return"COULD_NOT_APPLY_HINT"})};PeerConnectionV2.prototype.addMediaTrackSender=function(mediaTrackSender){var _this=this;if(this._peerConnection.signalingState==="closed"||this._rtpSenders.has(mediaTrackSender)){return}
@@ -52,6 +52,6 @@ this.transition("closed",null,[wsCloseCodesToCloseReasons.get(code)||CloseReason
52
52
  ;return local+(track.kind||"").replace(/\w{1}/,function(m){return m.toUpperCase()})+"Track"}function trackPublicationClass(publication,local){local=local?"Local":"";return local+(publication.kind||"").replace(/\w{1}/,function(m){return m.toUpperCase()})+"TrackPublication"}function hidePrivateProperties(object){Object.getOwnPropertyNames(object).forEach(function(name){if(name.startsWith("_")){hideProperty(object,name)}})}function hidePrivateAndCertainPublicPropertiesInClass(klass,props){return function(_super){__extends(class_1,_super);function class_1(){var args=[];for(var _i=0;_i<arguments.length;_i++){args[_i]=arguments[_i]}var _this=_super.apply(this,__spreadArray([],__read(args)))||this;hidePrivateProperties(_this);hidePublicProperties(_this,props);return _this}return class_1}(klass)}function hideProperty(object,name){var descriptor=Object.getOwnPropertyDescriptor(object,name);descriptor.enumerable=false;Object.defineProperty(object,name,descriptor)}function hidePublicProperties(object,props){if(props===void 0){props=[]}props.forEach(function(name){if(object.hasOwnProperty(name)){hideProperty(object,name)}})}function arrayToJSON(array){return array.map(valueToJSON)}function setToJSON(set){return arrayToJSON(__spreadArray([],__read(set)))}function mapToJSON(map){return __spreadArray([],__read(map.entries())).reduce(function(json,_a){var _b;var _c=__read(_a,2),key=_c[0],value=_c[1];return Object.assign((_b={},_b[key]=valueToJSON(value),_b),json)},{})}function objectToJSON(object){return Object.entries(object).reduce(function(json,_a){var _b;var _c=__read(_a,2),key=_c[0],value=_c[1];return Object.assign((_b={},_b[key]=valueToJSON(value),_b),json)},{})}function valueToJSON(value){if(Array.isArray(value)){return arrayToJSON(value)}else if(value instanceof Set){return setToJSON(value)}else if(value instanceof Map){return mapToJSON(value)}else if(value&&typeof value==="object"){return objectToJSON(value)}return value}function createRoomConnectEventPayload(connectOptions){function boolToString(val){return val?"true":"false"}var payload={sessionSID:sessionSID,iceServers:(connectOptions.iceServers||[]).length,audioTracks:(connectOptions.tracks||[]).filter(function(track){return track.kind==="audio"}).length,videoTracks:(connectOptions.tracks||[]).filter(function(track){return track.kind==="video"}).length,dataTracks:(connectOptions.tracks||[]).filter(function(track){return track.kind==="data"}).length};[["audio"],["automaticSubscription"],["enableDscp"],["eventListener"],["preflight"],["video"],["dominantSpeaker","enableDominantSpeaker"]].forEach(function(_a){var _b=__read(_a,2),prop=_b[0],eventProp=_b[1];eventProp=eventProp||prop;payload[eventProp]=boolToString(!!connectOptions[prop])});[["maxVideoBitrate"],["maxAudioBitrate"]].forEach(function(_a){var _b=__read(_a,2),prop=_b[0],eventProp=_b[1];eventProp=eventProp||prop;if(typeof connectOptions[prop]==="number"){payload[eventProp]=connectOptions[prop]}else if(!isNaN(Number(connectOptions[prop]))){payload[eventProp]=Number(connectOptions[prop])}});[["iceTransportPolicy"],["region"],["name","roomName"]].forEach(function(_a){var _b=__read(_a,2),prop=_b[0],eventProp=_b[1];eventProp=eventProp||prop;if(typeof connectOptions[prop]==="string"){payload[eventProp]=connectOptions[prop]}else if(typeof connectOptions[prop]==="number"&&prop==="name"){payload[eventProp]=connectOptions[prop].toString()}});["preferredAudioCodecs","preferredVideoCodecs"].forEach(function(prop){if(prop in connectOptions){payload[prop]=JSON.stringify(connectOptions[prop])}});if("networkQuality"in connectOptions){payload.networkQualityConfiguration={};if(isNonArrayObject(connectOptions.networkQuality)){["local","remote"].forEach(function(prop){if(typeof connectOptions.networkQuality[prop]==="number"){payload.networkQualityConfiguration[prop]=connectOptions.networkQuality[prop]}})}else{payload.networkQualityConfiguration.remote=0;payload.networkQualityConfiguration.local=connectOptions.networkQuality?1:0}}if(connectOptions.bandwidthProfile&&connectOptions.bandwidthProfile.video){var videoBPOptions_1=connectOptions.bandwidthProfile.video||{};payload.bandwidthProfileOptions={};["mode","maxTracks","trackSwitchOffMode","dominantSpeakerPriority","maxSubscriptionBitrate","renderDimensions","contentPreferencesMode","clientTrackSwitchOffControl"].forEach(function(prop){if(typeof videoBPOptions_1[prop]==="number"||typeof videoBPOptions_1[prop]==="string"){payload.bandwidthProfileOptions[prop]=videoBPOptions_1[prop]}else if(typeof videoBPOptions_1[prop]==="boolean"){payload.bandwidthProfileOptions[prop]=boolToString(videoBPOptions_1[prop])}else if(typeof videoBPOptions_1[prop]==="object"){payload.bandwidthProfileOptions[prop]=JSON.stringify(videoBPOptions_1[prop])}})}return{group:"room",name:"connect",level:"info",payload:payload}}function createBandwidthProfilePayload(bandwidthProfile){return createRSPPayload(bandwidthProfile,[{prop:"video",type:"object",transform:createBandwidthProfileVideoPayload}])}function createBandwidthProfileVideoPayload(bandwidthProfileVideo){return createRSPPayload(bandwidthProfileVideo,[{prop:"dominantSpeakerPriority",type:"string",payloadProp:"active_speaker_priority"},{prop:"maxSubscriptionBitrate",type:"number",payloadProp:"max_subscription_bandwidth"},{prop:"maxTracks",type:"number",payloadProp:"max_tracks"},{prop:"mode",type:"string"},{prop:"renderDimensions",type:"object",payloadProp:"render_dimensions",transform:createRenderDimensionsPayload},{prop:"trackSwitchOffMode",type:"string",payloadProp:"track_switch_off"}])}function createMediaSignalingPayload(dominantSpeaker,networkQuality,trackPriority,trackSwitchOff,adaptiveSimulcast,renderHints){var transports={transports:[{type:"data-channel"}]};return Object.assign(dominantSpeaker?{active_speaker:transports}:{},networkQuality?{network_quality:transports}:{},renderHints?{render_hints:transports}:{},adaptiveSimulcast?{publisher_hints:transports}:{},trackPriority?{track_priority:transports}:{},trackSwitchOff?{track_switch_off:transports}:{})}function createDimensionsPayload(dimensions){return createRSPPayload(dimensions,[{prop:"height",type:"number"},{prop:"width",type:"number"}])}function createRenderDimensionsPayload(renderDimensions){var PRIORITY_HIGH=trackPriority.PRIORITY_HIGH,PRIORITY_LOW=trackPriority.PRIORITY_LOW,PRIORITY_STANDARD=trackPriority.PRIORITY_STANDARD;return createRSPPayload(renderDimensions,[{prop:PRIORITY_HIGH,type:"object",transform:createDimensionsPayload},{prop:PRIORITY_LOW,type:"object",transform:createDimensionsPayload},{prop:PRIORITY_STANDARD,type:"object",transform:createDimensionsPayload}])}function createRSPPayload(object,propConversions){return propConversions.reduce(function(payload,_a){var _b;var prop=_a.prop,type=_a.type,_c=_a.payloadProp,payloadProp=_c===void 0?prop:_c,_d=_a.transform,transform=_d===void 0?function(x){return x}:_d;return typeof object[prop]===type?Object.assign((_b={},_b[payloadProp]=transform(object[prop]),_b),payload):payload},{})}function createSubscribePayload(automaticSubscription){return{rules:[{type:automaticSubscription?"include":"exclude",all:true}],revision:1}}function createMediaWarningsPayload(notifyWarnings){var _a;var mediaWarnings=(_a={},_a[TwilioWarning.recordingMediaLost]="recordings",_a);return notifyWarnings.map(function(twilioWarningName){return mediaWarnings[twilioWarningName]}).filter(function(name){return!!name})}function withJitter(value,jitter){var rand=Math.random();return value-jitter+Math.floor(2*jitter*rand+.5)}function inRange(num,min,max){return min<=num&&num<=max}function isChromeScreenShareTrack(track){return util.guessBrowser()==="chrome"&&track.kind==="video"&&"displaySurface"in track.getSettings()}function isUserMediaTrack(track){return typeof track.getSettings().deviceId==="string"}function waitForSometime(timeoutMS){if(timeoutMS===void 0){timeoutMS=10}return new Promise(function(resolve){return setTimeout(resolve,timeoutMS)})}function waitForEvent(eventTarget,event){return new Promise(function(resolve){eventTarget.addEventListener(event,function onevent(e){eventTarget.removeEventListener(event,onevent);resolve(e)})})}exports.constants=constants;exports.createBandwidthProfilePayload=createBandwidthProfilePayload;exports.createMediaSignalingPayload=createMediaSignalingPayload;exports.createMediaWarningsPayload=createMediaWarningsPayload;exports.createRoomConnectEventPayload=createRoomConnectEventPayload;exports.createSubscribePayload=createSubscribePayload;exports.asLocalTrack=asLocalTrack;exports.asLocalTrackPublication=asLocalTrackPublication;exports.capitalize=capitalize;exports.deprecateEvents=deprecateEvents;exports.difference=difference;exports.filterObject=filterObject;exports.flatMap=flatMap;exports.getPlatform=getPlatform;exports.getUserAgent=getUserAgent;exports.hidePrivateProperties=hidePrivateProperties;exports.hidePrivateAndCertainPublicPropertiesInClass=hidePrivateAndCertainPublicPropertiesInClass;exports.isDeepEqual=isDeepEqual;exports.isNonArrayObject=isNonArrayObject;exports.inRange=inRange;exports.makeUUID=makeUUID;exports.oncePerTick=oncePerTick;exports.promiseFromEvents=promiseFromEvents;exports.getOrNull=getOrNull;exports.defer=defer;exports.delegateMethods=delegateMethods;exports.proxyProperties=proxyProperties;exports.legacyPromise=legacyPromise;exports.buildLogLevels=buildLogLevels;exports.trackClass=trackClass;exports.trackPublicationClass=trackPublicationClass;exports.valueToJSON=valueToJSON;exports.withJitter=withJitter;exports.isChromeScreenShareTrack=isChromeScreenShareTrack;exports.isUserMediaTrack=isUserMediaTrack;exports.waitForSometime=waitForSometime;exports.waitForEvent=waitForEvent},{"../webrtc/util":170,"./constants":124,"./sid":143,"./twiliowarning":148}],132:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __assign=this&&this.__assign||function(){__assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++){s=arguments[i];for(var p in s)if(Object.prototype.hasOwnProperty.call(s,p))t[p]=s[p]}return t};return __assign.apply(this,arguments)};var EventEmitter=require("events").EventEmitter;var getUserAgent=require("..").getUserAgent;var MAX_RECONNECT_ATTEMPTS=5;var RECONNECT_INTERVAL_MS=50;var WS_CLOSE_NORMAL=1e3;var toplevel=globalThis;var WebSocket=toplevel.WebSocket?toplevel.WebSocket:require("ws");var _a=require("../constants"),hardwareDevicePublisheriPad=_a.hardwareDevicePublisheriPad,hardwareDevicePublisheriPhone=_a.hardwareDevicePublisheriPhone;var util=require("../../util");var browserdetection=require("../browserdetection");var InsightsPublisher=function(_super){__extends(InsightsPublisher,_super);function InsightsPublisher(token,sdkName,sdkVersion,environment,realm,options){var _this=_super.call(this)||this;options=Object.assign({gateway:createGateway(environment,realm)+"/v1/VideoEvents",maxReconnectAttempts:MAX_RECONNECT_ATTEMPTS,reconnectIntervalMs:RECONNECT_INTERVAL_MS,userAgent:getUserAgent(),WebSocket:WebSocket},options);Object.defineProperties(_this,{_connectTimestamp:{value:0,writable:true},_eventQueue:{value:[]},_readyToConnect:{value:util.defer()},_reconnectAttemptsLeft:{value:options.maxReconnectAttempts,writable:true},_ws:{value:null,writable:true},_WebSocket:{value:options.WebSocket}});_this._readyToConnect.promise.then(function(_a){var roomSid=_a.roomSid,participantSid=_a.participantSid;var self=_this;_this.on("disconnected",function maybeReconnect(error){self._session=null;if(error&&self._reconnectAttemptsLeft>0){self.emit("reconnecting");reconnect(self,token,sdkName,sdkVersion,roomSid,participantSid,options);return}self.removeListener("disconnected",maybeReconnect)});connect(_this,token,sdkName,sdkVersion,roomSid,participantSid,options)}).catch(function(){});return _this}InsightsPublisher.prototype.connect=function(roomSid,participantSid){this._readyToConnect.resolve({roomSid:roomSid,participantSid:participantSid})};InsightsPublisher.prototype._publish=function(event){event.session=this._session;this._ws.send(JSON.stringify(event))};InsightsPublisher.prototype.disconnect=function(){if(this._ws===null||this._ws.readyState===this._WebSocket.CLOSING||this._ws.readyState===this._WebSocket.CLOSED){return false}try{this._ws.close()}catch(error){}this.emit("disconnected");return true};InsightsPublisher.prototype.publish=function(groupName,eventName,payload){if(this._ws!==null&&(this._ws.readyState===this._WebSocket.CLOSING||this._ws.readyState===this._WebSocket.CLOSED)){return false}var publishOrEnqueue=typeof this._session==="string"?this._publish.bind(this):this._eventQueue.push.bind(this._eventQueue);publishOrEnqueue({group:groupName,name:eventName,payload:payload,timestamp:Date.now(),type:"event",version:1});return true};return InsightsPublisher}(EventEmitter);function connect(publisher,token,sdkName,sdkVersion,roomSid,participantSid,options){publisher._connectTimestamp=Date.now();publisher._reconnectAttemptsLeft--;publisher._ws=new options.WebSocket(options.gateway);var ws=publisher._ws;ws.addEventListener("close",function(event){if(event.code===WS_CLOSE_NORMAL){publisher.emit("disconnected");return}publisher.emit("disconnected",new Error("WebSocket Error "+event.code+": "+event.reason))});ws.addEventListener("message",function(message){handleConnectResponse(publisher,JSON.parse(message.data),options)});ws.addEventListener("open",function(){var connectRequest={type:"connect",token:token,version:1};connectRequest.publisher={name:sdkName,sdkVersion:sdkVersion,userAgent:options.userAgent,participantSid:participantSid,roomSid:roomSid};if(browserdetection.isIpad()){connectRequest.publisher=__assign(__assign({},connectRequest.publisher),hardwareDevicePublisheriPad)}else if(browserdetection.isIphone()){connectRequest.publisher=__assign(__assign({},connectRequest.publisher),hardwareDevicePublisheriPhone)}ws.send(JSON.stringify(connectRequest))})}function createGateway(environment,realm){return environment==="prod"?"wss://sdkgw."+realm+".twilio.com":"wss://sdkgw."+environment+"-"+realm+".twilio.com"}function handleConnectResponse(publisher,response,options){switch(response.type){case"connected":publisher._session=response.session;publisher._reconnectAttemptsLeft=options.maxReconnectAttempts;publisher._eventQueue.splice(0).forEach(publisher._publish,publisher);publisher.emit("connected");break;case"error":publisher._ws.close();publisher.emit("disconnected",new Error(response.message));break}}function reconnect(publisher,token,sdkName,sdkVersion,roomSid,participantSid,options){var connectInterval=Date.now()-publisher._connectTimestamp;var timeToWait=options.reconnectIntervalMs-connectInterval;if(timeToWait>0){setTimeout(function(){connect(publisher,token,sdkName,sdkVersion,roomSid,participantSid,options)},timeToWait);return}connect(publisher,token,sdkName,sdkVersion,roomSid,participantSid,options)}module.exports=InsightsPublisher},{"..":131,"../../util":131,"../browserdetection":122,"../constants":124,events:173,ws:175}],133:[function(require,module,exports){"use strict";var InsightsPublisher=function(){function InsightsPublisher(){Object.defineProperties(this,{_connected:{writable:true,value:true}})}InsightsPublisher.prototype.connect=function(){};InsightsPublisher.prototype.disconnect=function(){if(this._connected){this._connected=false;return true}return false};InsightsPublisher.prototype.publish=function(){return this._connected};return InsightsPublisher}();module.exports=InsightsPublisher},{}],134:[function(require,module,exports){"use strict";var defer=require("./").defer;var LocalMediaRestartDeferreds=function(){function LocalMediaRestartDeferreds(){Object.defineProperties(this,{_audio:{value:defer(),writable:true},_video:{value:defer(),writable:true}});this._audio.resolve();this._video.resolve()}LocalMediaRestartDeferreds.prototype.resolveDeferred=function(kind){if(kind==="audio"){this._audio.resolve()}else{this._video.resolve()}};LocalMediaRestartDeferreds.prototype.startDeferred=function(kind){if(kind==="audio"){this._audio=defer()}else{this._video=defer()}};LocalMediaRestartDeferreds.prototype.whenResolved=function(kind){return kind==="audio"?this._audio.promise:this._video.promise};return LocalMediaRestartDeferreds}();module.exports=new LocalMediaRestartDeferreds},{"./":131}],135:[function(require,module,exports){"use strict";var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var __spreadArray=this&&this.__spreadArray||function(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to};var defaultGetLogger=require("../vendor/loglevel").getLogger;var constants=require("./constants");var DEFAULT_LOG_LEVEL=constants.DEFAULT_LOG_LEVEL,DEFAULT_LOGGER_NAME=constants.DEFAULT_LOGGER_NAME;var E=require("./constants").typeErrors;var deprecationWarningsByComponentConstructor;function getDeprecationWarnings(componentConstructor){deprecationWarningsByComponentConstructor=deprecationWarningsByComponentConstructor||new Map;if(deprecationWarningsByComponentConstructor.has(componentConstructor)){return deprecationWarningsByComponentConstructor.get(componentConstructor)}var deprecationWarnings=new Set;deprecationWarningsByComponentConstructor.set(componentConstructor,deprecationWarnings);return deprecationWarnings}var Log=function(){function Log(moduleName,component,logLevels,loggerName,getLogger){if(typeof moduleName!=="string"){throw E.INVALID_TYPE("moduleName","string")}if(!component){throw E.REQUIRED_ARGUMENT("component")}if(typeof logLevels!=="object"){logLevels={}}getLogger=getLogger||defaultGetLogger;validateLogLevels(logLevels);Object.defineProperties(this,{_component:{value:component},_logLevels:{value:logLevels},_warnings:{value:new Set},_loggerName:{get:function get(){var name=loggerName&&typeof loggerName==="string"?loggerName:DEFAULT_LOGGER_NAME;if(!this._logLevelsEqual){name=name+"-"+moduleName}return name}},_logger:{get:function get(){var logger=getLogger(this._loggerName);var level=this._logLevels[moduleName]||DEFAULT_LOG_LEVEL;level=level==="off"?"silent":level;logger.setDefaultLevel(level);return logger}},_logLevelsEqual:{get:function get(){return new Set(Object.values(this._logLevels)).size===1}},logLevel:{get:function get(){return Log.getLevelByName(logLevels[moduleName]||DEFAULT_LOG_LEVEL)}},name:{get:component.toString.bind(component)}})}Log.getLevelByName=function(name){if(!isNaN(name)){return parseInt(name,10)}name=name.toUpperCase();validateLogLevel(name);return Log[name]};Log.prototype.createLog=function(moduleName,component){var name=this._loggerName;if(!this._logLevelsEqual){name=name.substring(0,name.lastIndexOf("-"))}return new Log(moduleName,component,this._logLevels,name)};Log.prototype.setLevels=function(levels){validateLogLevels(levels);Object.assign(this._logLevels,levels);return this};Log.prototype.log=function(logLevel,messages){var name=Log._levels[logLevel];if(!name){throw E.INVALID_VALUE("logLevel",LOG_LEVEL_VALUES)}name=name.toLowerCase();var prefix=[(new Date).toISOString(),name,this.name];(this._logger[name]||function noop(){}).apply(void 0,__spreadArray([],__read(prefix.concat(messages))));return this};Log.prototype.debug=function(){return this.log(Log.DEBUG,[].slice.call(arguments))};Log.prototype.deprecated=function(deprecationWarning){var deprecationWarnings=getDeprecationWarnings(this._component.constructor);if(deprecationWarnings.has(deprecationWarning)){return this}deprecationWarnings.add(deprecationWarning);return this.warn(deprecationWarning)};Log.prototype.info=function(){return this.log(Log.INFO,[].slice.call(arguments))};Log.prototype.warn=function(){return this.log(Log.WARN,[].slice.call(arguments))};Log.prototype.warnOnce=function(warning){if(this._warnings.has(warning)){return this}this._warnings.add(warning);return this.warn(warning)};Log.prototype.error=function(){return this.log(Log.ERROR,[].slice.call(arguments))};Log.prototype.throw=function(error,customMessage){if(error.clone){error=error.clone(customMessage)}this.log(Log.ERROR,error);throw error};return Log}();Object.defineProperties(Log,{DEBUG:{value:0},INFO:{value:1},WARN:{value:2},ERROR:{value:3},OFF:{value:4},_levels:{value:["DEBUG","INFO","WARN","ERROR","OFF"]}});var LOG_LEVELS_SET={};var LOG_LEVEL_VALUES=[];var LOG_LEVEL_NAMES=Log._levels.map(function(level,i){LOG_LEVELS_SET[level]=true;LOG_LEVEL_VALUES.push(i);return level});function validateLogLevel(level){if(!(level in LOG_LEVELS_SET)){throw E.INVALID_VALUE("level",LOG_LEVEL_NAMES)}}function validateLogLevels(levels){Object.keys(levels).forEach(function(moduleName){validateLogLevel(levels[moduleName].toUpperCase())})}module.exports=Log},{"../vendor/loglevel":151,"./constants":124}],136:[function(require,module,exports){"use strict";var MovingAverageDelta=function(){function MovingAverageDelta(){Object.defineProperties(this,{_samples:{value:[{denominator:0,numerator:0},{denominator:0,numerator:0}]}})}MovingAverageDelta.prototype.get=function(){var samples=this._samples;var denominatorDelta=samples[1].denominator-samples[0].denominator||Infinity;var numeratorDelta=samples[1].numerator-samples[0].numerator;return numeratorDelta/denominatorDelta};MovingAverageDelta.prototype.putSample=function(numerator,denominator){var samples=this._samples;samples.shift();samples.push({denominator:denominator,numerator:numerator})};return MovingAverageDelta}();module.exports=MovingAverageDelta},{}],137:[function(require,module,exports){"use strict";var NetworkMonitor=function(){function NetworkMonitor(onNetworkChanged,options){var _this=this;options=Object.assign({navigator:navigator,window:window},options);var nav=options.navigator;var connection=nav.connection||{type:null};var type=connection.type;var _a=connection.type?{_events:{value:["change","typechange"]},_listener:{value:function(){var networkChanged=type!==_this.type&&_this.isOnline;type=_this.type;if(networkChanged){onNetworkChanged()}}},_target:{value:connection}}:{_events:{value:["online"]},_listener:{value:onNetworkChanged},_target:{value:options.window}},_events=_a._events,_listener=_a._listener,_target=_a._target;Object.defineProperties(this,{isOnline:{enumerable:true,get:function(){return typeof nav.onLine==="boolean"?nav.onLine:true}},type:{enumerable:true,get:function(){return connection.type||null}},_listener:_listener,_events:_events,_target:_target})}NetworkMonitor.prototype.start=function(){var _this=this;this._events.forEach(function(event){_this._target.addEventListener(event,_this._listener)})};NetworkMonitor.prototype.stop=function(){var _this=this;this._events.forEach(function(event){_this._target.removeEventListener(event,_this._listener)})};return NetworkMonitor}();module.exports=NetworkMonitor},{}],138:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var NullObserver=function(){function NullObserver(callback){Object.defineProperties(this,{_callback:{value:callback}})}NullObserver.prototype.observe=function(){};NullObserver.prototype.unobserve=function(){};NullObserver.prototype.makeVisible=function(videoEl){var visibleEntry=this._makeFakeEntry(videoEl,true);this._callback([visibleEntry])};NullObserver.prototype.makeInvisible=function(videoEl){var invisibleEntry=this._makeFakeEntry(videoEl,false);this._callback([invisibleEntry])};NullObserver.prototype._makeFakeEntry=function(videoElement,isIntersecting){return{target:videoElement,isIntersecting:isIntersecting}};return NullObserver}();var NullIntersectionObserver=function(_super){__extends(NullIntersectionObserver,_super);function NullIntersectionObserver(){return _super!==null&&_super.apply(this,arguments)||this}return NullIntersectionObserver}(NullObserver);var NullResizeObserver=function(_super){__extends(NullResizeObserver,_super);function NullResizeObserver(){return _super!==null&&_super.apply(this,arguments)||this}NullResizeObserver.prototype.resize=function(videoEl){var entry=this._makeFakeEntry(videoEl,true);this._callback([entry])};return NullResizeObserver}(NullObserver);module.exports={NullIntersectionObserver:NullIntersectionObserver,NullResizeObserver:NullResizeObserver,NullObserver:NullObserver}},{}],139:[function(require,module,exports){"use strict";var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var _a=require("../"),difference=_a.difference,flatMap=_a.flatMap;var setSimulcastInMediaSection=require("./simulcast");var ptToFixedBitrateAudioCodecName={0:"PCMU",8:"PCMA"};function createCodecMapForMediaSection(section){return Array.from(createPtToCodecName(section)).reduce(function(codecMap,pair){var pt=pair[0];var codecName=pair[1];var pts=codecMap.get(codecName)||[];return codecMap.set(codecName,pts.concat(pt))},new Map)}function createMidToMediaSectionMap(sdp){return getMediaSections(sdp).reduce(function(midsToMediaSections,mediaSection){var mid=getMidForMediaSection(mediaSection);return mid?midsToMediaSections.set(mid,mediaSection):midsToMediaSections},new Map)}function createPtToCodecName(mediaSection){return getPayloadTypesInMediaSection(mediaSection).reduce(function(ptToCodecName,pt){var rtpmapPattern=new RegExp("a=rtpmap:"+pt+" ([^/]+)");var matches=mediaSection.match(rtpmapPattern);var codecName=matches?matches[1].toLowerCase():ptToFixedBitrateAudioCodecName[pt]?ptToFixedBitrateAudioCodecName[pt].toLowerCase():"";return ptToCodecName.set(pt,codecName)},new Map)}function getFmtpAttributesForPt(pt,mediaSection){var fmtpRegex=new RegExp("^a=fmtp:"+pt+" (.+)$","m");var matches=mediaSection.match(fmtpRegex);return matches&&matches[1].split(";").reduce(function(attrs,nvPair){var _a=__read(nvPair.split("="),2),name=_a[0],value=_a[1];attrs[name]=isNaN(value)?value:parseInt(value,10);return attrs},{})}function getMidForMediaSection(mediaSection){var midMatches=mediaSection.match(/^a=mid:(.+)$/m);return midMatches&&midMatches[1]}function getMediaSections(sdp,kind,direction){return sdp.replace(/\r\n\r\n$/,"\r\n").split("\r\nm=").slice(1).map(function(mediaSection){return"m="+mediaSection}).filter(function(mediaSection){var kindPattern=new RegExp("m="+(kind||".*"),"gm");var directionPattern=new RegExp("a="+(direction||".*"),"gm");return kindPattern.test(mediaSection)&&directionPattern.test(mediaSection)})}function getPayloadTypesInMediaSection(section){var mLine=section.split("\r\n")[0];var matches=mLine.match(/([0-9]+)/g);if(!matches){return[]}return matches.slice(1).map(function(match){return parseInt(match,10)})}function getReorderedPayloadTypes(codecMap,preferredCodecs){preferredCodecs=preferredCodecs.map(function(_a){var codec=_a.codec;return codec.toLowerCase()});var preferredPayloadTypes=flatMap(preferredCodecs,function(codecName){return codecMap.get(codecName)||[]});var remainingCodecs=difference(Array.from(codecMap.keys()),preferredCodecs);var remainingPayloadTypes=flatMap(remainingCodecs,function(codecName){return codecMap.get(codecName)});return preferredPayloadTypes.concat(remainingPayloadTypes)}function setPayloadTypesInMediaSection(payloadTypes,section){var lines=section.split("\r\n");var mLine=lines[0];var otherLines=lines.slice(1);mLine=mLine.replace(/([0-9]+\s?)+$/,payloadTypes.join(" "));return[mLine].concat(otherLines).join("\r\n")}function setCodecPreferences(sdp,preferredAudioCodecs,preferredVideoCodecs){var mediaSections=getMediaSections(sdp);var session=sdp.split("\r\nm=")[0];return[session].concat(mediaSections.map(function(section){if(!/^m=(audio|video)/.test(section)){return section}var kind=section.match(/^m=(audio|video)/)[1];var codecMap=createCodecMapForMediaSection(section);var preferredCodecs=kind==="audio"?preferredAudioCodecs:preferredVideoCodecs;var payloadTypes=getReorderedPayloadTypes(codecMap,preferredCodecs);var newSection=setPayloadTypesInMediaSection(payloadTypes,section);var pcmaPayloadTypes=codecMap.get("pcma")||[];var pcmuPayloadTypes=codecMap.get("pcmu")||[];var fixedBitratePayloadTypes=kind==="audio"?new Set(pcmaPayloadTypes.concat(pcmuPayloadTypes)):new Set;return fixedBitratePayloadTypes.has(payloadTypes[0])?newSection.replace(/\r\nb=(AS|TIAS):([0-9]+)/g,""):newSection})).join("\r\n")}function setSimulcast(sdp,trackIdsToAttributes){var mediaSections=getMediaSections(sdp);var session=sdp.split("\r\nm=")[0];return[session].concat(mediaSections.map(function(section){section=section.replace(/\r\n$/,"");if(!/^m=video/.test(section)){return section}var codecMap=createCodecMapForMediaSection(section);var payloadTypes=getPayloadTypesInMediaSection(section);var vp8PayloadTypes=new Set(codecMap.get("vp8")||[]);var hasVP8PayloadType=payloadTypes.some(function(payloadType){return vp8PayloadTypes.has(payloadType)});return hasVP8PayloadType?setSimulcastInMediaSection(section,trackIdsToAttributes):section})).concat("").join("\r\n")}function getMatchingPayloadTypes(peerCodec,peerPt,codecsToPts,section,peerSection){var matchingPts=codecsToPts.get(peerCodec)||[];if(matchingPts.length<=1){return matchingPts}var peerFmtpAttrs=getFmtpAttributesForPt(peerPt,peerSection);if(!peerFmtpAttrs){return matchingPts}var matchingPt=matchingPts.find(function(pt){var fmtpAttrs=getFmtpAttributesForPt(pt,section);return fmtpAttrs&&Object.keys(peerFmtpAttrs).every(function(attr){return peerFmtpAttrs[attr]===fmtpAttrs[attr]})});return typeof matchingPt==="number"?[matchingPt]:matchingPts}function filterCodecsInMediaSection(section,peerMidsToMediaSections,codecsToRemove){if(!/^m=(audio|video)/.test(section)){return section}var mid=getMidForMediaSection(section);var peerSection=mid&&peerMidsToMediaSections.get(mid);if(!peerSection){return section}var peerPtToCodecs=createPtToCodecName(peerSection);var codecsToPts=createCodecMapForMediaSection(section);var pts=flatMap(Array.from(peerPtToCodecs),function(_a){var _b=__read(_a,2),peerPt=_b[0],peerCodec=_b[1];return peerCodec!=="rtx"&&!codecsToRemove.includes(peerCodec)?getMatchingPayloadTypes(peerCodec,peerPt,codecsToPts,section,peerSection):[]});var rtxPts=codecsToPts.get("rtx")||[];pts=pts.concat(rtxPts.filter(function(rtxPt){var fmtpAttrs=getFmtpAttributesForPt(rtxPt,section);return fmtpAttrs&&pts.includes(fmtpAttrs.apt)}));var lines=section.split("\r\n").filter(function(line){var ptMatches=line.match(/^a=(rtpmap|fmtp|rtcp-fb):(.+) .+$/);var pt=ptMatches&&ptMatches[2];return!ptMatches||pt&&pts.includes(parseInt(pt,10))});var orderedPts=getPayloadTypesInMediaSection(section).filter(function(pt){return pts.includes(pt)});return setPayloadTypesInMediaSection(orderedPts,lines.join("\r\n"))}function filterLocalCodecs(localSdp,remoteSdp){
53
53
  var localMediaSections=getMediaSections(localSdp);var localSession=localSdp.split("\r\nm=")[0];var remoteMidsToMediaSections=createMidToMediaSectionMap(remoteSdp);return[localSession].concat(localMediaSections.map(function(localSection){return filterCodecsInMediaSection(localSection,remoteMidsToMediaSections,[])})).join("\r\n")}function revertSimulcast(localSdp,localSdpWithoutSimulcast,remoteSdp,revertForAll){if(revertForAll===void 0){revertForAll=false}var remoteMidToMediaSections=createMidToMediaSectionMap(remoteSdp);var localMidToMediaSectionsWithoutSimulcast=createMidToMediaSectionMap(localSdpWithoutSimulcast);var mediaSections=getMediaSections(localSdp);var session=localSdp.split("\r\nm=")[0];return[session].concat(mediaSections.map(function(section){section=section.replace(/\r\n$/,"");if(!/^m=video/.test(section)){return section}var midMatches=section.match(/^a=mid:(.+)$/m);var mid=midMatches&&midMatches[1];if(!mid){return section}var remoteSection=remoteMidToMediaSections.get(mid);var remotePtToCodecs=createPtToCodecName(remoteSection);var remotePayloadTypes=getPayloadTypesInMediaSection(remoteSection);var isVP8ThePreferredCodec=remotePayloadTypes.length&&remotePtToCodecs.get(remotePayloadTypes[0])==="vp8";var shouldRevertSimulcast=revertForAll||!isVP8ThePreferredCodec;return shouldRevertSimulcast?localMidToMediaSectionsWithoutSimulcast.get(mid).replace(/\r\n$/,""):section})).concat("").join("\r\n")}function addOrRewriteNewTrackIds(sdp,activeMidsToTrackIds,trackIdsByKind){var newMidsToTrackIds=Array.from(trackIdsByKind).reduce(function(midsToTrackIds,_a){var _b=__read(_a,2),kind=_b[0],trackIds=_b[1];var mediaSections=getMediaSections(sdp,kind,"send(only|recv)");var newMids=mediaSections.map(getMidForMediaSection).filter(function(mid){return!activeMidsToTrackIds.has(mid)});newMids.forEach(function(mid,i){return midsToTrackIds.set(mid,trackIds[i])});return midsToTrackIds},new Map);return addOrRewriteTrackIds(sdp,newMidsToTrackIds)}function addOrRewriteTrackIds(sdp,midsToTrackIds){var mediaSections=getMediaSections(sdp);var session=sdp.split("\r\nm=")[0];return[session].concat(mediaSections.map(function(mediaSection){if(!/^m=(audio|video)/.test(mediaSection)){return mediaSection}var mid=getMidForMediaSection(mediaSection);if(!mid){return mediaSection}var trackId=midsToTrackIds.get(mid);if(!trackId){return mediaSection}var attributes=(mediaSection.match(/^a=msid:(.+)$/m)||[])[1];if(!attributes){return mediaSection}var _a=__read(attributes.split(" "),2),msid=_a[0],trackIdToRewrite=_a[1];var msidRegex=new RegExp("msid:"+msid+(trackIdToRewrite?" "+trackIdToRewrite:"")+"$","gm");return mediaSection.replace(msidRegex,"msid:"+msid+" "+trackId)})).join("\r\n")}function removeSSRCAttributes(sdp,ssrcAttributesToRemove){return sdp.split("\r\n").filter(function(line){return!ssrcAttributesToRemove.find(function(srcAttribute){return new RegExp("a=ssrc:.*"+srcAttribute+":","g").test(line)})}).join("\r\n")}function disableRtx(sdp){var mediaSections=getMediaSections(sdp);var session=sdp.split("\r\nm=")[0];return[session].concat(mediaSections.map(function(mediaSection){if(!/^m=video/.test(mediaSection)){return mediaSection}var codecsToPts=createCodecMapForMediaSection(mediaSection);var rtxPts=codecsToPts.get("rtx");if(!rtxPts){return mediaSection}var pts=new Set(getPayloadTypesInMediaSection(mediaSection));rtxPts.forEach(function(rtxPt){return pts.delete(rtxPt)});var rtxSSRCMatches=mediaSection.match(/a=ssrc-group:FID [0-9]+ ([0-9]+)/);var rtxSSRC=rtxSSRCMatches&&rtxSSRCMatches[1];var filterRegexes=[/^a=fmtp:.+ apt=.+$/,/^a=rtpmap:.+ rtx\/.+$/,/^a=ssrc-group:.+$/].concat(rtxSSRC?[new RegExp("^a=ssrc:"+rtxSSRC+" .+$")]:[]);mediaSection=mediaSection.split("\r\n").filter(function(line){return filterRegexes.every(function(regex){return!regex.test(line)})}).join("\r\n");return setPayloadTypesInMediaSection(Array.from(pts),mediaSection)})).join("\r\n")}function generateFmtpLineFromPtAndAttributes(pt,fmtpAttrs){var serializedFmtpAttrs=Object.entries(fmtpAttrs).map(function(_a){var _b=__read(_a,2),name=_b[0],value=_b[1];return name+"="+value}).join(";");return"a=fmtp:"+pt+" "+serializedFmtpAttrs}function enableDtxForOpus(sdp,mids){var mediaSections=getMediaSections(sdp);var session=sdp.split("\r\nm=")[0];mids=mids||mediaSections.filter(function(section){return/^m=audio/.test(section)}).map(getMidForMediaSection);return[session].concat(mediaSections.map(function(section){if(!/^m=audio/.test(section)){return section}var codecsToPts=createCodecMapForMediaSection(section);var opusPt=codecsToPts.get("opus");if(!opusPt){return section}var opusFmtpAttrs=getFmtpAttributesForPt(opusPt,section);if(!opusFmtpAttrs){return section}var origOpusFmtpLine=generateFmtpLineFromPtAndAttributes(opusPt,opusFmtpAttrs);var origOpusFmtpRegex=new RegExp(origOpusFmtpLine);var mid=getMidForMediaSection(section);if(mids.includes(mid)){opusFmtpAttrs.usedtx=1}else{delete opusFmtpAttrs.usedtx}var opusFmtpLineWithDtx=generateFmtpLineFromPtAndAttributes(opusPt,opusFmtpAttrs);return section.replace(origOpusFmtpRegex,opusFmtpLineWithDtx)})).join("\r\n")}exports.addOrRewriteNewTrackIds=addOrRewriteNewTrackIds;exports.addOrRewriteTrackIds=addOrRewriteTrackIds;exports.createCodecMapForMediaSection=createCodecMapForMediaSection;exports.createPtToCodecName=createPtToCodecName;exports.disableRtx=disableRtx;exports.enableDtxForOpus=enableDtxForOpus;exports.filterLocalCodecs=filterLocalCodecs;exports.getMediaSections=getMediaSections;exports.removeSSRCAttributes=removeSSRCAttributes;exports.revertSimulcast=revertSimulcast;exports.setCodecPreferences=setCodecPreferences;exports.setSimulcast=setSimulcast},{"../":131,"./simulcast":141}],140:[function(require,module,exports){"use strict";var RTCSessionDescription=require("../../webrtc").RTCSessionDescription;var _a=require("./"),createPtToCodecName=_a.createPtToCodecName,getMediaSections=_a.getMediaSections;function workaround(description){var descriptionInit={type:description.type};if(description.type!=="rollback"){descriptionInit.sdp=sdpWorkaround(description.sdp)}return new RTCSessionDescription(descriptionInit)}function sdpWorkaround(sdp){var mediaSections=getMediaSections(sdp);var session=sdp.split("\r\nm=")[0];return[session].concat(mediaSections.map(mediaSectionWorkaround)).join("\r\n")}function mediaSectionWorkaround(mediaSection){var ptToCodecName=createPtToCodecName(mediaSection);mediaSection=deleteDuplicateRtxPts(mediaSection,ptToCodecName);var codecNameToPts=createCodecNameToPts(ptToCodecName);var rtxPts=codecNameToPts.get("rtx")||new Set;var invalidRtxPts=new Set;var rtxPtToAssociatedPt=createRtxPtToAssociatedPt(mediaSection,ptToCodecName,rtxPts,invalidRtxPts);var associatedPtToRtxPt=createAssociatedPtToRtxPt(rtxPtToAssociatedPt,invalidRtxPts);var unassociatedRtxPts=Array.from(invalidRtxPts);var knownCodecNames=["h264","vp8","vp9"];var unassociatedPts=knownCodecNames.reduce(function(unassociatedPts,codecName){var pts=codecNameToPts.get(codecName)||new Set;return Array.from(pts).reduce(function(unassociatedPts,pt){return associatedPtToRtxPt.has(pt)?unassociatedPts:unassociatedPts.add(pt)},unassociatedPts)},new Set);unassociatedPts.forEach(function(pt){if(unassociatedRtxPts.length){var rtxPt=unassociatedRtxPts.shift();mediaSection=deleteFmtpAttributesForRtxPt(mediaSection,rtxPt);mediaSection=addFmtpAttributeForRtxPt(mediaSection,rtxPt,pt)}});unassociatedRtxPts.forEach(function(rtxPt){mediaSection=deleteFmtpAttributesForRtxPt(mediaSection,rtxPt);mediaSection=deleteRtpmapAttributesForRtxPt(mediaSection,rtxPt)});return mediaSection}function deleteDuplicateRtxPts(mediaSection,ptToCodecName){return Array.from(ptToCodecName.keys()).reduce(function(section,pt){var rtpmapRegex=new RegExp("^a=rtpmap:"+pt+" rtx.+$","gm");return(section.match(rtpmapRegex)||[]).slice(ptToCodecName.get(pt)==="rtx"?1:0).reduce(function(section,rtpmap){var rtpmapRegex=new RegExp("\r\n"+rtpmap);var fmtpmapRegex=new RegExp("\r\na=fmtp:"+pt+" apt=[0-9]+");return section.replace(rtpmapRegex,"").replace(fmtpmapRegex,"")},section)},mediaSection)}function createCodecNameToPts(ptToCodecName){var codecNameToPts=new Map;ptToCodecName.forEach(function(codecName,pt){var pts=codecNameToPts.get(codecName)||new Set;return codecNameToPts.set(codecName,pts.add(pt))});return codecNameToPts}function createRtxPtToAssociatedPt(mediaSection,ptToCodecName,rtxPts,invalidRtxPts){return Array.from(rtxPts).reduce(function(rtxPtToAssociatedPt,rtxPt){var fmtpPattern=new RegExp("a=fmtp:"+rtxPt+" apt=(\\d+)");var matches=mediaSection.match(fmtpPattern);if(!matches){invalidRtxPts.add(rtxPt);return rtxPtToAssociatedPt}var pt=Number.parseInt(matches[1]);if(!ptToCodecName.has(pt)){invalidRtxPts.add(rtxPt);return rtxPtToAssociatedPt}var codecName=ptToCodecName.get(pt);if(codecName==="rtx"){invalidRtxPts.add(rtxPt);return rtxPtToAssociatedPt}return rtxPtToAssociatedPt.set(rtxPt,pt)},new Map)}function createAssociatedPtToRtxPt(rtxPtToAssociatedPt,invalidRtxPts){var associatedPtToRtxPts=Array.from(rtxPtToAssociatedPt).reduce(function(associatedPtToRtxPts,pair){var rtxPt=pair[0];var pt=pair[1];var rtxPts=associatedPtToRtxPts.get(pt)||new Set;return associatedPtToRtxPts.set(pt,rtxPts.add(rtxPt))},new Map);return Array.from(associatedPtToRtxPts).reduce(function(associatedPtToRtxPt,pair){var pt=pair[0];var rtxPts=Array.from(pair[1]);if(rtxPts.length>1){rtxPts.forEach(function(rtxPt){invalidRtxPts.add(rtxPt)});return associatedPtToRtxPt}return associatedPtToRtxPt.set(pt,rtxPts[0])},new Map)}function deleteFmtpAttributesForRtxPt(mediaSection,rtxPt){var pattern=new RegExp("a=fmtp:"+rtxPt+".*\r\n","gm");return mediaSection.replace(pattern,"")}function deleteRtpmapAttributesForRtxPt(mediaSection,rtxPt){var pattern=new RegExp("a=rtpmap:"+rtxPt+".*\r\n","gm");return mediaSection.replace(pattern,"")}function addFmtpAttributeForRtxPt(mediaSection,rtxPt,pt){return mediaSection.endsWith("\r\n")?mediaSection+"a=fmtp:"+rtxPt+" apt="+pt+"\r\n":mediaSection+"\r\na=fmtp:"+rtxPt+" apt="+pt}module.exports=workaround},{"../../webrtc":157,"./":139}],141:[function(require,module,exports){"use strict";var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var _a=require("../"),difference=_a.difference,flatMap=_a.flatMap;function createSSRC(){var ssrcMax=4294967295;return String(Math.floor(Math.random()*ssrcMax))}var TrackAttributes=function(){function TrackAttributes(trackId,streamId,cName){Object.defineProperties(this,{cName:{enumerable:true,value:cName},isSimulcastEnabled:{enumerable:true,value:false,writable:true},primarySSRCs:{enumerable:true,value:new Set},rtxPairs:{enumerable:true,value:new Map},streamId:{enumerable:true,value:streamId},trackId:{enumerable:true,value:trackId}})}TrackAttributes.prototype.addSimulcastSSRCs=function(){if(this.isSimulcastEnabled){return}var simulcastSSRCs=[createSSRC(),createSSRC()];simulcastSSRCs.forEach(function(ssrc){this.primarySSRCs.add(ssrc)},this);if(this.rtxPairs.size){simulcastSSRCs.forEach(function(ssrc){this.rtxPairs.set(createSSRC(),ssrc)},this)}};TrackAttributes.prototype.addSSRC=function(ssrc,primarySSRC,isSimSSRC){if(primarySSRC){this.rtxPairs.set(ssrc,primarySSRC)}else{this.primarySSRCs.add(ssrc)}this.isSimulcastEnabled=this.isSimulcastEnabled||isSimSSRC};TrackAttributes.prototype.toSdpLines=function(excludeRtx){var _this=this;var rtxPairs=excludeRtx?[]:Array.from(this.rtxPairs.entries()).map(function(rtxPair){return rtxPair.reverse()});var simSSRCs=Array.from(this.primarySSRCs.values());var ssrcs=rtxPairs.length?flatMap(rtxPairs):simSSRCs;var attrLines=flatMap(ssrcs,function(ssrc){return["a=ssrc:"+ssrc+" cname:"+_this.cName,"a=ssrc:"+ssrc+" msid:"+_this.streamId+" "+_this.trackId]});var rtxPairLines=rtxPairs.map(function(rtxPair){return"a=ssrc-group:FID "+rtxPair.join(" ")});var simGroupLines=["a=ssrc-group:SIM "+simSSRCs.join(" ")];return rtxPairLines.concat(attrLines).concat(simGroupLines)};return TrackAttributes}();function getMatches(section,pattern){var matches=section.match(new RegExp(pattern,"gm"))||[];return matches.map(function(match){var matches=match.match(new RegExp(pattern))||[];return matches.slice(1)})}function getSimulcastSSRCs(section){var simGroupPattern="^a=ssrc-group:SIM ([0-9]+) ([0-9]+) ([0-9]+)$";return new Set(flatMap(getMatches(section,simGroupPattern)))}function getSSRCAttribute(section,ssrc,attribute){var pattern="a=ssrc:"+ssrc+" "+attribute+":(.+)";return section.match(new RegExp(pattern))[1]}function getSSRCRtxPairs(section){var rtxPairPattern="^a=ssrc-group:FID ([0-9]+) ([0-9]+)$";return new Map(getMatches(section,rtxPairPattern).map(function(pair){return pair.reverse()}))}function createSSRCAttributeTuples(section){var _a=__read(flatMap(getMatches(section,"^a=msid:(.+) (.+)$")),2),streamId=_a[0],trackId=_a[1];var ssrcs=flatMap(getMatches(section,"^a=ssrc:(.+) cname:.+$"));return ssrcs.map(function(ssrc){return[ssrc,streamId,trackId]})}function createTrackIdsToAttributes(section){var simSSRCs=getSimulcastSSRCs(section);var rtxPairs=getSSRCRtxPairs(section);var ssrcAttrTuples=createSSRCAttributeTuples(section);return ssrcAttrTuples.reduce(function(trackIdsToSSRCs,tuple){var ssrc=tuple[0];var streamId=tuple[1];var trackId=tuple[2];var trackAttributes=trackIdsToSSRCs.get(trackId)||new TrackAttributes(trackId,streamId,getSSRCAttribute(section,ssrc,"cname"));var primarySSRC=rtxPairs.get(ssrc)||null;trackAttributes.addSSRC(ssrc,primarySSRC,simSSRCs.has(ssrc));return trackIdsToSSRCs.set(trackId,trackAttributes)},new Map)}function setSimulcastInMediaSection(section,trackIdsToAttributes){var newTrackIdsToAttributes=createTrackIdsToAttributes(section);var newTrackIds=Array.from(newTrackIdsToAttributes.keys());var trackIds=Array.from(trackIdsToAttributes.keys());var trackIdsToAdd=difference(newTrackIds,trackIds);var trackIdsToIgnore=difference(trackIds,newTrackIds);var trackAttributesToAdd=flatMap(trackIdsToAdd,function(trackId){return newTrackIdsToAttributes.get(trackId)});trackAttributesToAdd.forEach(function(trackAttributes){trackAttributes.addSimulcastSSRCs();trackIdsToAttributes.set(trackAttributes.trackId,trackAttributes)});trackIds=Array.from(trackIdsToAttributes.keys());var relevantTrackIds=difference(trackIds,trackIdsToIgnore);var relevantTrackAttributes=flatMap(relevantTrackIds,function(trackId){return trackIdsToAttributes.get(trackId)});var excludeRtx=!section.match(/a=rtpmap:[0-9]+ rtx/);var relevantSdpLines=flatMap(relevantTrackAttributes,function(trackAttributes){return trackAttributes.toSdpLines(excludeRtx)});var sectionLines=flatMap(new Set(section.split("\r\n").concat(relevantSdpLines)));var xGoogleFlagConference="a=x-google-flag:conference";if(!section.match(xGoogleFlagConference)){sectionLines.push(xGoogleFlagConference)}return sectionLines.join("\r\n")}module.exports=setSimulcastInMediaSection},{"../":131}],142:[function(require,module,exports){"use strict";var getMediaSections=require("./").getMediaSections;var TrackMatcher=function(){function TrackMatcher(){Object.defineProperties(this,{_midsToTrackIds:{value:new Map,writable:true}})}TrackMatcher.prototype.match=function(event){return this._midsToTrackIds.get(event.transceiver.mid)||null};TrackMatcher.prototype.update=function(sdp){var sections=getMediaSections(sdp,"(audio|video)");this._midsToTrackIds=sections.reduce(function(midsToTrackIds,section){var midMatches=section.match(/^a=mid:(.+)$/m)||[];var trackIdMatches=section.match(/^a=msid:.+ (.+)$/m)||[];var mid=midMatches[1];var trackId=trackIdMatches[1];return mid&&trackId?midsToTrackIds.set(mid,trackId):midsToTrackIds},this._midsToTrackIds)};return TrackMatcher}();module.exports=TrackMatcher},{"./":139}],143:[function(require,module,exports){var SID_CHARS="1234567890abcdef";var SID_CHAR_LENGTH=32;function createSID(prefix){var result="";for(var i=0;i<SID_CHAR_LENGTH;i++){result+=SID_CHARS.charAt(Math.floor(Math.random()*SID_CHARS.length))}return""+prefix+result}exports.sessionSID=createSID("SS");exports.createSID=createSID},{}],144:[function(require,module,exports){"use strict";var _a=require("../webrtc/util"),guessBrowser=_a.guessBrowser,isWebRTCSupported=_a.support;var getSdpFormat=require("../webrtc/util/sdp").getSdpFormat;var _b=require("./browserdetection"),isAndroid=_b.isAndroid,isMobile=_b.isMobile,isNonChromiumEdge=_b.isNonChromiumEdge,rebrandedChromeBrowser=_b.rebrandedChromeBrowser,mobileWebKitBrowser=_b.mobileWebKitBrowser;var SUPPORTED_CHROME_BASED_BROWSERS=["crios","edg","edge","electron","headlesschrome"];var SUPPORTED_ANDROID_BROWSERS=["chrome","firefox"];var SUPPORTED_IOS_BROWSERS=["chrome","safari"];var SUPPORTED_MOBILE_WEBKIT_BASED_BROWSERS=[];function isSupported(){var browser=guessBrowser();if(!browser){return false}var rebrandedChrome=rebrandedChromeBrowser(browser);var mobileWebKit=mobileWebKitBrowser(browser);var supportedMobileBrowsers=isAndroid()?SUPPORTED_ANDROID_BROWSERS:SUPPORTED_IOS_BROWSERS;return!!browser&&isWebRTCSupported()&&getSdpFormat()==="unified"&&(!rebrandedChrome||SUPPORTED_CHROME_BASED_BROWSERS.includes(rebrandedChrome))&&!isNonChromiumEdge(browser)&&(!mobileWebKit||SUPPORTED_MOBILE_WEBKIT_BASED_BROWSERS.includes(mobileWebKit))&&(!isMobile()||supportedMobileBrowsers.includes(browser))}module.exports=isSupported},{"../webrtc/util":170,"../webrtc/util/sdp":172,"./browserdetection":122}],145:[function(require,module,exports){"use strict";var Timeout=function(){function Timeout(fn,delay,autoStart){if(autoStart===void 0){autoStart=true}Object.defineProperties(this,{_delay:{value:delay,writable:true},_fn:{value:fn},_timeout:{value:null,writable:true}});if(autoStart){this.start()}}Object.defineProperty(Timeout.prototype,"delay",{get:function(){return this._delay},enumerable:false,configurable:true});Object.defineProperty(Timeout.prototype,"isSet",{get:function(){return!!this._timeout},enumerable:false,configurable:true});Timeout.prototype.setDelay=function(delay){this._delay=delay};Timeout.prototype.start=function(){var _this=this;if(!this.isSet){this._timeout=setTimeout(function(){var fn=_this._fn;_this.clear();fn()},this._delay)}};Timeout.prototype.clear=function(){clearTimeout(this._timeout);this._timeout=null};Timeout.prototype.reset=function(){this.clear();this.start()};return Timeout}();module.exports=Timeout},{}],146:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var TwilioError=require("./twilioerror");var TwilioErrorByCode={};exports.createTwilioError=function createTwilioError(code,message){code=typeof code==="number"?code:0;message=typeof message==="string"&&message?message:"Unknown error";return TwilioErrorByCode[code]?new TwilioErrorByCode[code]:new TwilioError(code,message)};var AccessTokenInvalidError=function(_super){__extends(AccessTokenInvalidError,_super);function AccessTokenInvalidError(){var _this=_super.call(this,20101,"Invalid Access Token")||this;Object.setPrototypeOf(_this,AccessTokenInvalidError.prototype);return _this}return AccessTokenInvalidError}(TwilioError);exports.AccessTokenInvalidError=AccessTokenInvalidError;Object.defineProperty(TwilioErrorByCode,20101,{value:AccessTokenInvalidError});var AccessTokenHeaderInvalidError=function(_super){__extends(AccessTokenHeaderInvalidError,_super);function AccessTokenHeaderInvalidError(){var _this=_super.call(this,20102,"Invalid Access Token header")||this;Object.setPrototypeOf(_this,AccessTokenHeaderInvalidError.prototype);return _this}return AccessTokenHeaderInvalidError}(TwilioError);exports.AccessTokenHeaderInvalidError=AccessTokenHeaderInvalidError;Object.defineProperty(TwilioErrorByCode,20102,{value:AccessTokenHeaderInvalidError});var AccessTokenIssuerInvalidError=function(_super){__extends(AccessTokenIssuerInvalidError,_super);function AccessTokenIssuerInvalidError(){var _this=_super.call(this,20103,"Invalid Access Token issuer/subject")||this;Object.setPrototypeOf(_this,AccessTokenIssuerInvalidError.prototype);return _this}return AccessTokenIssuerInvalidError}(TwilioError);exports.AccessTokenIssuerInvalidError=AccessTokenIssuerInvalidError;Object.defineProperty(TwilioErrorByCode,20103,{value:AccessTokenIssuerInvalidError});var AccessTokenExpiredError=function(_super){__extends(AccessTokenExpiredError,_super);function AccessTokenExpiredError(){var _this=_super.call(this,20104,"Access Token expired or expiration date invalid")||this;Object.setPrototypeOf(_this,AccessTokenExpiredError.prototype);return _this}return AccessTokenExpiredError}(TwilioError);exports.AccessTokenExpiredError=AccessTokenExpiredError;Object.defineProperty(TwilioErrorByCode,20104,{value:AccessTokenExpiredError});var AccessTokenNotYetValidError=function(_super){__extends(AccessTokenNotYetValidError,_super);function AccessTokenNotYetValidError(){var _this=_super.call(this,20105,"Access Token not yet valid")||this;Object.setPrototypeOf(_this,AccessTokenNotYetValidError.prototype);return _this}return AccessTokenNotYetValidError}(TwilioError);exports.AccessTokenNotYetValidError=AccessTokenNotYetValidError;Object.defineProperty(TwilioErrorByCode,20105,{value:AccessTokenNotYetValidError});var AccessTokenGrantsInvalidError=function(_super){__extends(AccessTokenGrantsInvalidError,_super);function AccessTokenGrantsInvalidError(){var _this=_super.call(this,20106,"Invalid Access Token grants")||this;Object.setPrototypeOf(_this,AccessTokenGrantsInvalidError.prototype);return _this}return AccessTokenGrantsInvalidError}(TwilioError);exports.AccessTokenGrantsInvalidError=AccessTokenGrantsInvalidError;Object.defineProperty(TwilioErrorByCode,20106,{value:AccessTokenGrantsInvalidError});var AccessTokenSignatureInvalidError=function(_super){__extends(AccessTokenSignatureInvalidError,_super);function AccessTokenSignatureInvalidError(){var _this=_super.call(this,20107,"Invalid Access Token signature")||this;Object.setPrototypeOf(_this,AccessTokenSignatureInvalidError.prototype);return _this}return AccessTokenSignatureInvalidError}(TwilioError);exports.AccessTokenSignatureInvalidError=AccessTokenSignatureInvalidError;Object.defineProperty(TwilioErrorByCode,20107,{value:AccessTokenSignatureInvalidError});var SignalingConnectionError=function(_super){__extends(SignalingConnectionError,_super);function SignalingConnectionError(){var _this=_super.call(this,53e3,"Signaling connection error")||this;Object.setPrototypeOf(_this,SignalingConnectionError.prototype);return _this}return SignalingConnectionError}(TwilioError);exports.SignalingConnectionError=SignalingConnectionError;Object.defineProperty(TwilioErrorByCode,53e3,{value:SignalingConnectionError});var SignalingConnectionDisconnectedError=function(_super){__extends(SignalingConnectionDisconnectedError,_super);function SignalingConnectionDisconnectedError(){var _this=_super.call(this,53001,"Signaling connection disconnected")||this;Object.setPrototypeOf(_this,SignalingConnectionDisconnectedError.prototype);return _this}return SignalingConnectionDisconnectedError}(TwilioError);exports.SignalingConnectionDisconnectedError=SignalingConnectionDisconnectedError;Object.defineProperty(TwilioErrorByCode,53001,{value:SignalingConnectionDisconnectedError});var SignalingConnectionTimeoutError=function(_super){__extends(SignalingConnectionTimeoutError,_super);function SignalingConnectionTimeoutError(){var _this=_super.call(this,53002,"Signaling connection timed out")||this;Object.setPrototypeOf(_this,SignalingConnectionTimeoutError.prototype);return _this}return SignalingConnectionTimeoutError}(TwilioError);exports.SignalingConnectionTimeoutError=SignalingConnectionTimeoutError;Object.defineProperty(TwilioErrorByCode,53002,{value:SignalingConnectionTimeoutError});var SignalingIncomingMessageInvalidError=function(_super){__extends(SignalingIncomingMessageInvalidError,_super);function SignalingIncomingMessageInvalidError(){var _this=_super.call(this,53003,"Client received an invalid signaling message")||this;Object.setPrototypeOf(_this,SignalingIncomingMessageInvalidError.prototype);return _this}return SignalingIncomingMessageInvalidError}(TwilioError);exports.SignalingIncomingMessageInvalidError=SignalingIncomingMessageInvalidError;Object.defineProperty(TwilioErrorByCode,53003,{value:SignalingIncomingMessageInvalidError});var SignalingOutgoingMessageInvalidError=function(_super){__extends(SignalingOutgoingMessageInvalidError,_super);function SignalingOutgoingMessageInvalidError(){var _this=_super.call(this,53004,"Client sent an invalid signaling message")||this;Object.setPrototypeOf(_this,SignalingOutgoingMessageInvalidError.prototype);return _this}return SignalingOutgoingMessageInvalidError}(TwilioError);exports.SignalingOutgoingMessageInvalidError=SignalingOutgoingMessageInvalidError;Object.defineProperty(TwilioErrorByCode,53004,{value:SignalingOutgoingMessageInvalidError});var SignalingServerBusyError=function(_super){__extends(SignalingServerBusyError,_super);function SignalingServerBusyError(){var _this=_super.call(this,53006,"Video server is busy")||this;Object.setPrototypeOf(_this,SignalingServerBusyError.prototype);return _this}return SignalingServerBusyError}(TwilioError);exports.SignalingServerBusyError=SignalingServerBusyError;Object.defineProperty(TwilioErrorByCode,53006,{value:SignalingServerBusyError});var RoomNameInvalidError=function(_super){__extends(RoomNameInvalidError,_super);function RoomNameInvalidError(){var _this=_super.call(this,53100,"Room name is invalid")||this;Object.setPrototypeOf(_this,RoomNameInvalidError.prototype);return _this}return RoomNameInvalidError}(TwilioError);exports.RoomNameInvalidError=RoomNameInvalidError;Object.defineProperty(TwilioErrorByCode,53100,{value:RoomNameInvalidError});var RoomNameTooLongError=function(_super){__extends(RoomNameTooLongError,_super);function RoomNameTooLongError(){var _this=_super.call(this,53101,"Room name is too long")||this;Object.setPrototypeOf(_this,RoomNameTooLongError.prototype);return _this}return RoomNameTooLongError}(TwilioError);exports.RoomNameTooLongError=RoomNameTooLongError;Object.defineProperty(TwilioErrorByCode,53101,{value:RoomNameTooLongError});var RoomNameCharsInvalidError=function(_super){__extends(RoomNameCharsInvalidError,_super);function RoomNameCharsInvalidError(){var _this=_super.call(this,53102,"Room name contains invalid characters")||this;Object.setPrototypeOf(_this,RoomNameCharsInvalidError.prototype);return _this}return RoomNameCharsInvalidError}(TwilioError);exports.RoomNameCharsInvalidError=RoomNameCharsInvalidError;Object.defineProperty(TwilioErrorByCode,53102,{value:RoomNameCharsInvalidError});var RoomCreateFailedError=function(_super){__extends(RoomCreateFailedError,_super);function RoomCreateFailedError(){var _this=_super.call(this,53103,"Unable to create Room")||this;Object.setPrototypeOf(_this,RoomCreateFailedError.prototype);return _this}return RoomCreateFailedError}(TwilioError);exports.RoomCreateFailedError=RoomCreateFailedError;Object.defineProperty(TwilioErrorByCode,53103,{value:RoomCreateFailedError});var RoomConnectFailedError=function(_super){__extends(RoomConnectFailedError,_super);function RoomConnectFailedError(){var _this=_super.call(this,53104,"Unable to connect to Room")||this;Object.setPrototypeOf(_this,RoomConnectFailedError.prototype);return _this}return RoomConnectFailedError}(TwilioError);exports.RoomConnectFailedError=RoomConnectFailedError;Object.defineProperty(TwilioErrorByCode,53104,{value:RoomConnectFailedError});var RoomMaxParticipantsExceededError=function(_super){__extends(RoomMaxParticipantsExceededError,_super);function RoomMaxParticipantsExceededError(){var _this=_super.call(this,53105,"Room contains too many Participants")||this;Object.setPrototypeOf(_this,RoomMaxParticipantsExceededError.prototype);return _this}return RoomMaxParticipantsExceededError}(TwilioError);exports.RoomMaxParticipantsExceededError=RoomMaxParticipantsExceededError;Object.defineProperty(TwilioErrorByCode,53105,{value:RoomMaxParticipantsExceededError});var RoomNotFoundError=function(_super){__extends(RoomNotFoundError,_super);function RoomNotFoundError(){var _this=_super.call(this,53106,"Room not found")||this;Object.setPrototypeOf(_this,RoomNotFoundError.prototype);return _this}return RoomNotFoundError}(TwilioError);exports.RoomNotFoundError=RoomNotFoundError;Object.defineProperty(TwilioErrorByCode,53106,{value:RoomNotFoundError});var RoomMaxParticipantsOutOfRangeError=function(_super){__extends(RoomMaxParticipantsOutOfRangeError,_super);function RoomMaxParticipantsOutOfRangeError(){var _this=_super.call(this,53107,"MaxParticipants is out of range")||this;Object.setPrototypeOf(_this,RoomMaxParticipantsOutOfRangeError.prototype);return _this}return RoomMaxParticipantsOutOfRangeError}(TwilioError);exports.RoomMaxParticipantsOutOfRangeError=RoomMaxParticipantsOutOfRangeError;Object.defineProperty(TwilioErrorByCode,53107,{value:RoomMaxParticipantsOutOfRangeError});var RoomTypeInvalidError=function(_super){__extends(RoomTypeInvalidError,_super);function RoomTypeInvalidError(){var _this=_super.call(this,53108,"RoomType is not valid")||this;Object.setPrototypeOf(_this,RoomTypeInvalidError.prototype);return _this}return RoomTypeInvalidError}(TwilioError);exports.RoomTypeInvalidError=RoomTypeInvalidError;Object.defineProperty(TwilioErrorByCode,53108,{value:RoomTypeInvalidError});var RoomTimeoutOutOfRangeError=function(_super){__extends(RoomTimeoutOutOfRangeError,_super);function RoomTimeoutOutOfRangeError(){var _this=_super.call(this,53109,"Timeout is out of range")||this;Object.setPrototypeOf(_this,RoomTimeoutOutOfRangeError.prototype);return _this}return RoomTimeoutOutOfRangeError}(TwilioError);exports.RoomTimeoutOutOfRangeError=RoomTimeoutOutOfRangeError;Object.defineProperty(TwilioErrorByCode,53109,{value:RoomTimeoutOutOfRangeError});var RoomStatusCallbackMethodInvalidError=function(_super){__extends(RoomStatusCallbackMethodInvalidError,_super);function RoomStatusCallbackMethodInvalidError(){var _this=_super.call(this,53110,"StatusCallbackMethod is invalid")||this;Object.setPrototypeOf(_this,RoomStatusCallbackMethodInvalidError.prototype);return _this}return RoomStatusCallbackMethodInvalidError}(TwilioError);exports.RoomStatusCallbackMethodInvalidError=RoomStatusCallbackMethodInvalidError;Object.defineProperty(TwilioErrorByCode,53110,{value:RoomStatusCallbackMethodInvalidError});var RoomStatusCallbackInvalidError=function(_super){__extends(RoomStatusCallbackInvalidError,_super);function RoomStatusCallbackInvalidError(){var _this=_super.call(this,53111,"StatusCallback is invalid")||this;Object.setPrototypeOf(_this,RoomStatusCallbackInvalidError.prototype);return _this}return RoomStatusCallbackInvalidError}(TwilioError);exports.RoomStatusCallbackInvalidError=RoomStatusCallbackInvalidError;Object.defineProperty(TwilioErrorByCode,53111,{value:RoomStatusCallbackInvalidError});var RoomStatusInvalidError=function(_super){__extends(RoomStatusInvalidError,_super);function RoomStatusInvalidError(){var _this=_super.call(this,53112,"Status is invalid")||this;Object.setPrototypeOf(_this,RoomStatusInvalidError.prototype);return _this}return RoomStatusInvalidError}(TwilioError);exports.RoomStatusInvalidError=RoomStatusInvalidError;Object.defineProperty(TwilioErrorByCode,53112,{value:RoomStatusInvalidError});var RoomRoomExistsError=function(_super){
54
54
  __extends(RoomRoomExistsError,_super);function RoomRoomExistsError(){var _this=_super.call(this,53113,"Room exists")||this;Object.setPrototypeOf(_this,RoomRoomExistsError.prototype);return _this}return RoomRoomExistsError}(TwilioError);exports.RoomRoomExistsError=RoomRoomExistsError;Object.defineProperty(TwilioErrorByCode,53113,{value:RoomRoomExistsError});var RoomInvalidParametersError=function(_super){__extends(RoomInvalidParametersError,_super);function RoomInvalidParametersError(){var _this=_super.call(this,53114,"Room creation parameter(s) incompatible with the Room type")||this;Object.setPrototypeOf(_this,RoomInvalidParametersError.prototype);return _this}return RoomInvalidParametersError}(TwilioError);exports.RoomInvalidParametersError=RoomInvalidParametersError;Object.defineProperty(TwilioErrorByCode,53114,{value:RoomInvalidParametersError});var RoomMediaRegionInvalidError=function(_super){__extends(RoomMediaRegionInvalidError,_super);function RoomMediaRegionInvalidError(){var _this=_super.call(this,53115,"MediaRegion is invalid")||this;Object.setPrototypeOf(_this,RoomMediaRegionInvalidError.prototype);return _this}return RoomMediaRegionInvalidError}(TwilioError);exports.RoomMediaRegionInvalidError=RoomMediaRegionInvalidError;Object.defineProperty(TwilioErrorByCode,53115,{value:RoomMediaRegionInvalidError});var RoomMediaRegionUnavailableError=function(_super){__extends(RoomMediaRegionUnavailableError,_super);function RoomMediaRegionUnavailableError(){var _this=_super.call(this,53116,"There are no media servers available in the MediaRegion")||this;Object.setPrototypeOf(_this,RoomMediaRegionUnavailableError.prototype);return _this}return RoomMediaRegionUnavailableError}(TwilioError);exports.RoomMediaRegionUnavailableError=RoomMediaRegionUnavailableError;Object.defineProperty(TwilioErrorByCode,53116,{value:RoomMediaRegionUnavailableError});var RoomSubscriptionOperationNotSupportedError=function(_super){__extends(RoomSubscriptionOperationNotSupportedError,_super);function RoomSubscriptionOperationNotSupportedError(){var _this=_super.call(this,53117,"The subscription operation requested is not supported for the Room type")||this;Object.setPrototypeOf(_this,RoomSubscriptionOperationNotSupportedError.prototype);return _this}return RoomSubscriptionOperationNotSupportedError}(TwilioError);exports.RoomSubscriptionOperationNotSupportedError=RoomSubscriptionOperationNotSupportedError;Object.defineProperty(TwilioErrorByCode,53117,{value:RoomSubscriptionOperationNotSupportedError});var RoomCompletedError=function(_super){__extends(RoomCompletedError,_super);function RoomCompletedError(){var _this=_super.call(this,53118,"Room completed")||this;Object.setPrototypeOf(_this,RoomCompletedError.prototype);return _this}return RoomCompletedError}(TwilioError);exports.RoomCompletedError=RoomCompletedError;Object.defineProperty(TwilioErrorByCode,53118,{value:RoomCompletedError});var RoomAudioOnlyFlagNotSupportedError=function(_super){__extends(RoomAudioOnlyFlagNotSupportedError,_super);function RoomAudioOnlyFlagNotSupportedError(){var _this=_super.call(this,53124,"The AudioOnly flag is not supported for the Room type")||this;Object.setPrototypeOf(_this,RoomAudioOnlyFlagNotSupportedError.prototype);return _this}return RoomAudioOnlyFlagNotSupportedError}(TwilioError);exports.RoomAudioOnlyFlagNotSupportedError=RoomAudioOnlyFlagNotSupportedError;Object.defineProperty(TwilioErrorByCode,53124,{value:RoomAudioOnlyFlagNotSupportedError});var RoomTrackKindNotSupportedError=function(_super){__extends(RoomTrackKindNotSupportedError,_super);function RoomTrackKindNotSupportedError(){var _this=_super.call(this,53125,"The track kind is not supported by the Room")||this;Object.setPrototypeOf(_this,RoomTrackKindNotSupportedError.prototype);return _this}return RoomTrackKindNotSupportedError}(TwilioError);exports.RoomTrackKindNotSupportedError=RoomTrackKindNotSupportedError;Object.defineProperty(TwilioErrorByCode,53125,{value:RoomTrackKindNotSupportedError});var ParticipantIdentityInvalidError=function(_super){__extends(ParticipantIdentityInvalidError,_super);function ParticipantIdentityInvalidError(){var _this=_super.call(this,53200,"Participant identity is invalid")||this;Object.setPrototypeOf(_this,ParticipantIdentityInvalidError.prototype);return _this}return ParticipantIdentityInvalidError}(TwilioError);exports.ParticipantIdentityInvalidError=ParticipantIdentityInvalidError;Object.defineProperty(TwilioErrorByCode,53200,{value:ParticipantIdentityInvalidError});var ParticipantIdentityTooLongError=function(_super){__extends(ParticipantIdentityTooLongError,_super);function ParticipantIdentityTooLongError(){var _this=_super.call(this,53201,"Participant identity is too long")||this;Object.setPrototypeOf(_this,ParticipantIdentityTooLongError.prototype);return _this}return ParticipantIdentityTooLongError}(TwilioError);exports.ParticipantIdentityTooLongError=ParticipantIdentityTooLongError;Object.defineProperty(TwilioErrorByCode,53201,{value:ParticipantIdentityTooLongError});var ParticipantIdentityCharsInvalidError=function(_super){__extends(ParticipantIdentityCharsInvalidError,_super);function ParticipantIdentityCharsInvalidError(){var _this=_super.call(this,53202,"Participant identity contains invalid characters")||this;Object.setPrototypeOf(_this,ParticipantIdentityCharsInvalidError.prototype);return _this}return ParticipantIdentityCharsInvalidError}(TwilioError);exports.ParticipantIdentityCharsInvalidError=ParticipantIdentityCharsInvalidError;Object.defineProperty(TwilioErrorByCode,53202,{value:ParticipantIdentityCharsInvalidError});var ParticipantMaxTracksExceededError=function(_super){__extends(ParticipantMaxTracksExceededError,_super);function ParticipantMaxTracksExceededError(){var _this=_super.call(this,53203,"The maximum number of published tracks allowed in the Room at the same time has been reached")||this;Object.setPrototypeOf(_this,ParticipantMaxTracksExceededError.prototype);return _this}return ParticipantMaxTracksExceededError}(TwilioError);exports.ParticipantMaxTracksExceededError=ParticipantMaxTracksExceededError;Object.defineProperty(TwilioErrorByCode,53203,{value:ParticipantMaxTracksExceededError});var ParticipantNotFoundError=function(_super){__extends(ParticipantNotFoundError,_super);function ParticipantNotFoundError(){var _this=_super.call(this,53204,"Participant not found")||this;Object.setPrototypeOf(_this,ParticipantNotFoundError.prototype);return _this}return ParticipantNotFoundError}(TwilioError);exports.ParticipantNotFoundError=ParticipantNotFoundError;Object.defineProperty(TwilioErrorByCode,53204,{value:ParticipantNotFoundError});var ParticipantDuplicateIdentityError=function(_super){__extends(ParticipantDuplicateIdentityError,_super);function ParticipantDuplicateIdentityError(){var _this=_super.call(this,53205,"Participant disconnected because of duplicate identity")||this;Object.setPrototypeOf(_this,ParticipantDuplicateIdentityError.prototype);return _this}return ParticipantDuplicateIdentityError}(TwilioError);exports.ParticipantDuplicateIdentityError=ParticipantDuplicateIdentityError;Object.defineProperty(TwilioErrorByCode,53205,{value:ParticipantDuplicateIdentityError});var TrackInvalidError=function(_super){__extends(TrackInvalidError,_super);function TrackInvalidError(){var _this=_super.call(this,53300,"Track is invalid")||this;Object.setPrototypeOf(_this,TrackInvalidError.prototype);return _this}return TrackInvalidError}(TwilioError);exports.TrackInvalidError=TrackInvalidError;Object.defineProperty(TwilioErrorByCode,53300,{value:TrackInvalidError});var TrackNameInvalidError=function(_super){__extends(TrackNameInvalidError,_super);function TrackNameInvalidError(){var _this=_super.call(this,53301,"Track name is invalid")||this;Object.setPrototypeOf(_this,TrackNameInvalidError.prototype);return _this}return TrackNameInvalidError}(TwilioError);exports.TrackNameInvalidError=TrackNameInvalidError;Object.defineProperty(TwilioErrorByCode,53301,{value:TrackNameInvalidError});var TrackNameTooLongError=function(_super){__extends(TrackNameTooLongError,_super);function TrackNameTooLongError(){var _this=_super.call(this,53302,"Track name is too long")||this;Object.setPrototypeOf(_this,TrackNameTooLongError.prototype);return _this}return TrackNameTooLongError}(TwilioError);exports.TrackNameTooLongError=TrackNameTooLongError;Object.defineProperty(TwilioErrorByCode,53302,{value:TrackNameTooLongError});var TrackNameCharsInvalidError=function(_super){__extends(TrackNameCharsInvalidError,_super);function TrackNameCharsInvalidError(){var _this=_super.call(this,53303,"Track name contains invalid characters")||this;Object.setPrototypeOf(_this,TrackNameCharsInvalidError.prototype);return _this}return TrackNameCharsInvalidError}(TwilioError);exports.TrackNameCharsInvalidError=TrackNameCharsInvalidError;Object.defineProperty(TwilioErrorByCode,53303,{value:TrackNameCharsInvalidError});var TrackNameIsDuplicatedError=function(_super){__extends(TrackNameIsDuplicatedError,_super);function TrackNameIsDuplicatedError(){var _this=_super.call(this,53304,"Track name is duplicated")||this;Object.setPrototypeOf(_this,TrackNameIsDuplicatedError.prototype);return _this}return TrackNameIsDuplicatedError}(TwilioError);exports.TrackNameIsDuplicatedError=TrackNameIsDuplicatedError;Object.defineProperty(TwilioErrorByCode,53304,{value:TrackNameIsDuplicatedError});var TrackServerTrackCapacityReachedError=function(_super){__extends(TrackServerTrackCapacityReachedError,_super);function TrackServerTrackCapacityReachedError(){var _this=_super.call(this,53305,"The server has reached capacity and cannot fulfill this request")||this;Object.setPrototypeOf(_this,TrackServerTrackCapacityReachedError.prototype);return _this}return TrackServerTrackCapacityReachedError}(TwilioError);exports.TrackServerTrackCapacityReachedError=TrackServerTrackCapacityReachedError;Object.defineProperty(TwilioErrorByCode,53305,{value:TrackServerTrackCapacityReachedError});var MediaClientLocalDescFailedError=function(_super){__extends(MediaClientLocalDescFailedError,_super);function MediaClientLocalDescFailedError(){var _this=_super.call(this,53400,"Client is unable to create or apply a local media description")||this;Object.setPrototypeOf(_this,MediaClientLocalDescFailedError.prototype);return _this}return MediaClientLocalDescFailedError}(TwilioError);exports.MediaClientLocalDescFailedError=MediaClientLocalDescFailedError;Object.defineProperty(TwilioErrorByCode,53400,{value:MediaClientLocalDescFailedError});var MediaServerLocalDescFailedError=function(_super){__extends(MediaServerLocalDescFailedError,_super);function MediaServerLocalDescFailedError(){var _this=_super.call(this,53401,"Server is unable to create or apply a local media description")||this;Object.setPrototypeOf(_this,MediaServerLocalDescFailedError.prototype);return _this}return MediaServerLocalDescFailedError}(TwilioError);exports.MediaServerLocalDescFailedError=MediaServerLocalDescFailedError;Object.defineProperty(TwilioErrorByCode,53401,{value:MediaServerLocalDescFailedError});var MediaClientRemoteDescFailedError=function(_super){__extends(MediaClientRemoteDescFailedError,_super);function MediaClientRemoteDescFailedError(){var _this=_super.call(this,53402,"Client is unable to apply a remote media description")||this;Object.setPrototypeOf(_this,MediaClientRemoteDescFailedError.prototype);return _this}return MediaClientRemoteDescFailedError}(TwilioError);exports.MediaClientRemoteDescFailedError=MediaClientRemoteDescFailedError;Object.defineProperty(TwilioErrorByCode,53402,{value:MediaClientRemoteDescFailedError});var MediaServerRemoteDescFailedError=function(_super){__extends(MediaServerRemoteDescFailedError,_super);function MediaServerRemoteDescFailedError(){var _this=_super.call(this,53403,"Server is unable to apply a remote media description")||this;Object.setPrototypeOf(_this,MediaServerRemoteDescFailedError.prototype);return _this}return MediaServerRemoteDescFailedError}(TwilioError);exports.MediaServerRemoteDescFailedError=MediaServerRemoteDescFailedError;Object.defineProperty(TwilioErrorByCode,53403,{value:MediaServerRemoteDescFailedError});var MediaNoSupportedCodecError=function(_super){__extends(MediaNoSupportedCodecError,_super);function MediaNoSupportedCodecError(){var _this=_super.call(this,53404,"No supported codec")||this;Object.setPrototypeOf(_this,MediaNoSupportedCodecError.prototype);return _this}return MediaNoSupportedCodecError}(TwilioError);exports.MediaNoSupportedCodecError=MediaNoSupportedCodecError;Object.defineProperty(TwilioErrorByCode,53404,{value:MediaNoSupportedCodecError});var MediaConnectionError=function(_super){__extends(MediaConnectionError,_super);function MediaConnectionError(){var _this=_super.call(this,53405,"Media connection failed or Media activity ceased")||this;Object.setPrototypeOf(_this,MediaConnectionError.prototype);return _this}return MediaConnectionError}(TwilioError);exports.MediaConnectionError=MediaConnectionError;Object.defineProperty(TwilioErrorByCode,53405,{value:MediaConnectionError});var MediaDTLSTransportFailedError=function(_super){__extends(MediaDTLSTransportFailedError,_super);function MediaDTLSTransportFailedError(){var _this=_super.call(this,53407,"Media connection failed due to DTLS handshake failure")||this;Object.setPrototypeOf(_this,MediaDTLSTransportFailedError.prototype);return _this}return MediaDTLSTransportFailedError}(TwilioError);exports.MediaDTLSTransportFailedError=MediaDTLSTransportFailedError;Object.defineProperty(TwilioErrorByCode,53407,{value:MediaDTLSTransportFailedError});var ConfigurationAcquireFailedError=function(_super){__extends(ConfigurationAcquireFailedError,_super);function ConfigurationAcquireFailedError(){var _this=_super.call(this,53500,"Unable to acquire configuration")||this;Object.setPrototypeOf(_this,ConfigurationAcquireFailedError.prototype);return _this}return ConfigurationAcquireFailedError}(TwilioError);exports.ConfigurationAcquireFailedError=ConfigurationAcquireFailedError;Object.defineProperty(TwilioErrorByCode,53500,{value:ConfigurationAcquireFailedError});var ConfigurationAcquireTurnFailedError=function(_super){__extends(ConfigurationAcquireTurnFailedError,_super);function ConfigurationAcquireTurnFailedError(){var _this=_super.call(this,53501,"Unable to acquire TURN credentials")||this;Object.setPrototypeOf(_this,ConfigurationAcquireTurnFailedError.prototype);return _this}return ConfigurationAcquireTurnFailedError}(TwilioError);exports.ConfigurationAcquireTurnFailedError=ConfigurationAcquireTurnFailedError;Object.defineProperty(TwilioErrorByCode,53501,{value:ConfigurationAcquireTurnFailedError})},{"./twilioerror":147}],147:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var __spreadArray=this&&this.__spreadArray||function(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to};var TwilioError=function(_super){__extends(TwilioError,_super);function TwilioError(code){var _this=this;var args=[].slice.call(arguments,1);_this=_super.apply(this,__spreadArray([],__read(args)))||this;Object.setPrototypeOf(_this,TwilioError.prototype);var error=Error.apply(_this,args);error.name="TwilioError";Object.defineProperty(_this,"code",{value:code,enumerable:true});Object.getOwnPropertyNames(error).forEach(function(prop){Object.defineProperty(this,prop,{value:error[prop],enumerable:true})},_this);return _this}TwilioError.prototype.toString=function(){var message=this.message?": "+this.message:"";return this.name+" "+this.code+message};return TwilioError}(Error);module.exports=TwilioError},{}],148:[function(require,module,exports){"use strict";var TwilioWarning={recordingMediaLost:"recording-media-lost"};module.exports=TwilioWarning},{}],149:[function(require,module,exports){"use strict";var isNonArrayObject=require("./").isNonArrayObject;var _a=require("./constants"),E=_a.typeErrors,clientTrackSwitchOffControl=_a.clientTrackSwitchOffControl,videoContentPreferencesMode=_a.videoContentPreferencesMode,subscriptionMode=_a.subscriptionMode,trackPriority=_a.trackPriority,trackSwitchOffMode=_a.trackSwitchOffMode;function validateBandwidthProfile(bandwidthProfile){var error=validateObject(bandwidthProfile,"options.bandwidthProfile");if(!bandwidthProfile||error){return error}error=validateObject(bandwidthProfile.video,"options.bandwidthProfile.video",[{prop:"contentPreferencesMode",values:Object.values(videoContentPreferencesMode)},{prop:"dominantSpeakerPriority",values:Object.values(trackPriority)},{prop:"maxSubscriptionBitrate",type:"number"},{prop:"maxTracks",type:"number"},{prop:"mode",values:Object.values(subscriptionMode)},{prop:"clientTrackSwitchOffControl",values:Object.values(clientTrackSwitchOffControl)},{prop:"trackSwitchOffMode",values:Object.values(trackSwitchOffMode)}]);if(error){return error}if(bandwidthProfile.video){if("maxTracks"in bandwidthProfile.video&&"clientTrackSwitchOffControl"in bandwidthProfile.video){return new TypeError("options.bandwidthProfile.video.maxTracks is deprecated. Use options.bandwidthProfile.video.clientTrackSwitchOffControl instead.")}if("renderDimensions"in bandwidthProfile.video&&"contentPreferencesMode"in bandwidthProfile.video){return new TypeError("options.bandwidthProfile.video.renderDimensions is deprecated. Use options.bandwidthProfile.video.contentPreferencesMode instead.")}return validateRenderDimensions(bandwidthProfile.video.renderDimensions)}return null}function validateLocalTrack(track,options){if(!(track instanceof options.LocalAudioTrack||track instanceof options.LocalDataTrack||track instanceof options.LocalVideoTrack||track instanceof options.MediaStreamTrack)){throw E.INVALID_TYPE("track","LocalAudioTrack, LocalVideoTrack, LocalDataTrack, or MediaStreamTrack")}}function validateObject(object,name,propChecks){if(propChecks===void 0){propChecks=[]}if(typeof object==="undefined"){return null}if(object===null||!isNonArrayObject(object)){return E.INVALID_TYPE(name,"object")}return propChecks.reduce(function(error,_a){var prop=_a.prop,type=_a.type,values=_a.values;if(error||!(prop in object)){return error}var value=object[prop];if(type&&typeof value!==type){return E.INVALID_TYPE(name+"."+prop,type)}if(type==="number"&&isNaN(value)){return E.INVALID_TYPE(name+"."+prop,type)}if(Array.isArray(values)&&!values.includes(value)){return E.INVALID_VALUE(name+"."+prop,values)}return error},null)}function validateRenderDimensions(renderDimensions){var name="options.bandwidthProfile.video.renderDimensions";var error=validateObject(renderDimensions,name);return renderDimensions?error||Object.values(trackPriority).reduce(function(error,prop){return error||validateObject(renderDimensions[prop],name+"."+prop,[{prop:"height",type:"number"},{prop:"width",type:"number"}])},null):error}exports.validateBandwidthProfile=validateBandwidthProfile;exports.validateLocalTrack=validateLocalTrack;exports.validateObject=validateObject},{"./":131,"./constants":124}],150:[function(require,module,exports){module.exports=function inherits(ctor,superCtor){if(ctor&&superCtor){ctor.super_=superCtor;if(typeof Object.create==="function"){ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}else{var TempCtor=function(){function TempCtor(){}return TempCtor}();TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}}},{}],151:[function(require,module,exports){var noop=function(){};var undefinedType="undefined";var isIE=typeof window!==undefinedType&&typeof window.navigator!==undefinedType&&/Trident\/|MSIE /.test(window.navigator.userAgent);var logMethods=["trace","debug","info","warn","error"];function bindMethod(obj,methodName){var method=obj[methodName];if(typeof method.bind==="function"){return method.bind(obj)}else{try{return Function.prototype.bind.call(method,obj)}catch(e){return function(){return Function.prototype.apply.apply(method,[obj,arguments])}}}}function traceForIE(){if(console.log){if(console.log.apply){console.log.apply(console,arguments)}else{Function.prototype.apply.apply(console.log,[console,arguments])}}if(console.trace)console.trace()}function realMethod(methodName){if(methodName==="debug"){methodName="log"}if(typeof console===undefinedType){return false}else if(methodName==="trace"&&isIE){return traceForIE}else if(console[methodName]!==undefined){return bindMethod(console,methodName)}else if(console.log!==undefined){return bindMethod(console,"log")}else{return noop}}function replaceLoggingMethods(level,loggerName){for(var i=0;i<logMethods.length;i++){var methodName=logMethods[i];this[methodName]=i<level?noop:this.methodFactory(methodName,level,loggerName)}this.log=this.debug}function enableLoggingWhenConsoleArrives(methodName,level,loggerName){return function(){if(typeof console!==undefinedType){replaceLoggingMethods.call(this,level,loggerName);this[methodName].apply(this,arguments)}}}function defaultMethodFactory(methodName,level,loggerName){return realMethod(methodName)||enableLoggingWhenConsoleArrives.apply(this,arguments)}function Logger(name,defaultLevel,factory){var self=this;var currentLevel;var storageKey="loglevel";if(typeof name==="string"){storageKey+=":"+name}else if(typeof name==="symbol"){storageKey=undefined}function persistLevelIfPossible(levelNum){var levelName=(logMethods[levelNum]||"silent").toUpperCase();if(typeof window===undefinedType||!storageKey)return;try{window.localStorage[storageKey]=levelName;return}catch(ignore){}try{window.document.cookie=encodeURIComponent(storageKey)+"="+levelName+";"}catch(ignore){}}function getPersistedLevel(){var storedLevel;if(typeof window===undefinedType||!storageKey)return;try{storedLevel=window.localStorage[storageKey]}catch(ignore){}if(typeof storedLevel===undefinedType){try{var cookie=window.document.cookie;var location=cookie.indexOf(encodeURIComponent(storageKey)+"=");if(location!==-1){storedLevel=/^([^;]+)/.exec(cookie.slice(location))[1]}}catch(ignore){}}if(self.levels[storedLevel]===undefined){storedLevel=undefined}return storedLevel}self.name=name;self.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5};self.methodFactory=factory||defaultMethodFactory;self.getLevel=function(){return currentLevel};self.setLevel=function(level,persist){if(typeof level==="string"&&self.levels[level.toUpperCase()]!==undefined){level=self.levels[level.toUpperCase()]}if(typeof level==="number"&&level>=0&&level<=self.levels.SILENT){currentLevel=level;if(persist!==false){persistLevelIfPossible(level)}replaceLoggingMethods.call(self,level,name);if(typeof console===undefinedType&&level<self.levels.SILENT){return"No console available for logging"}}else{throw"log.setLevel() called with invalid level: "+level}};self.setDefaultLevel=function(level){if(!getPersistedLevel()){self.setLevel(level,false)}};self.enableAll=function(persist){self.setLevel(self.levels.TRACE,persist)};self.disableAll=function(persist){self.setLevel(self.levels.SILENT,persist)};var initialLevel=getPersistedLevel();if(initialLevel==null){initialLevel=defaultLevel==null?"WARN":defaultLevel}self.setLevel(initialLevel,false)}var defaultLogger=new Logger;var _loggersByName={};defaultLogger.getLogger=function getLogger(name){if(typeof name!=="symbol"&&typeof name!=="string"||name===""){throw new TypeError("You must supply a name when creating a logger.")}var logger=_loggersByName[name];if(!logger){logger=_loggersByName[name]=new Logger(name,defaultLogger.getLevel(),defaultLogger.methodFactory)}return logger};var _log=typeof window!==undefinedType?window.log:undefined;defaultLogger.noConflict=function(){if(typeof window!==undefinedType&&window.log===defaultLogger){window.log=_log}return defaultLogger};defaultLogger.getLoggers=function getLoggers(){return _loggersByName};defaultLogger["default"]=defaultLogger;module.exports=defaultLogger},{}],152:[function(require,module,exports){"use strict";var NativeAudioContext=typeof AudioContext!=="undefined"?AudioContext:typeof webkitAudioContext!=="undefined"?webkitAudioContext:null;var AudioContextFactory=function(){function AudioContextFactory(options){options=Object.assign({AudioContext:NativeAudioContext},options);Object.defineProperties(this,{_AudioContext:{value:options.AudioContext},_audioContext:{value:null,writable:true},_holders:{value:new Set},AudioContextFactory:{enumerable:true,value:AudioContextFactory}})}AudioContextFactory.prototype.getOrCreate=function(holder){if(!this._holders.has(holder)){this._holders.add(holder);if(this._AudioContext&&!this._audioContext){try{this._audioContext=new this._AudioContext}catch(error){}}}return this._audioContext};AudioContextFactory.prototype.release=function(holder){if(this._holders.has(holder)){this._holders.delete(holder);if(!this._holders.size&&this._audioContext){this._audioContext.close();this._audioContext=null}}};return AudioContextFactory}();module.exports=new AudioContextFactory},{}],153:[function(require,module,exports){"use strict";function delay(timeout){timeout=typeof timeout==="number"?timeout:0;return new Promise(function(resolve){return setTimeout(resolve,timeout)})}function detectSilence(audioContext,stream,timeout){timeout=typeof timeout==="number"?timeout:250;var source=audioContext.createMediaStreamSource(stream);var analyser=audioContext.createAnalyser();analyser.fftSize=2048;source.connect(analyser);var samples=new Uint8Array(analyser.fftSize);var timeoutDidFire=false;setTimeout(function(){timeoutDidFire=true},timeout);function doDetectSilence(){if(timeoutDidFire){return Promise.resolve(true)}analyser.getByteTimeDomainData(samples);return samples.some(function(sample){return sample!==128&&sample!==0})?Promise.resolve(false):delay().then(doDetectSilence)}return doDetectSilence().then(function(isSilent){source.disconnect();return isSilent},function(error){source.disconnect();throw error})}module.exports=detectSilence},{}],154:[function(require,module,exports){"use strict";var detectSilence=require("./detectsilence");function workaround(log,getUserMedia,constraints,n,timeout){n=typeof n==="number"?n:3;var retry=0;var AudioContextFactory=require("./audiocontext");var holder={};var audioContext=AudioContextFactory.getOrCreate(holder);function doWorkaround(){return getUserMedia(constraints).then(function(stream){var isSilentPromise=constraints.audio?detectSilence(audioContext,stream,timeout).catch(function(err){log.warn("Encountered an error while detecting silence",err);return true}):Promise.resolve(false);return isSilentPromise.then(function(isSilent){if(!isSilent){log.info("Got a non-silent audio MediaStreamTrack; returning it.");return stream}else if(n<=0){log.warn("Got a silent audio MediaStreamTrack. Normally we would try to get a new one, but we've run out of retries; returning it anyway.");return stream}log.warn("Got a silent audio MediaStreamTrack. Stopping all MediaStreamTracks and calling getUserMedia again. This is retry #"+ ++retry+".");stream.getTracks().forEach(function(track){return track.stop()});n--;return doWorkaround()})})}return doWorkaround().then(function(stream){AudioContextFactory.release(holder);return stream},function(error){AudioContextFactory.release(holder);throw error})}module.exports=workaround},{"./audiocontext":152,"./detectsilence":153}],155:[function(require,module,exports){"use strict";var flatMap=require("./util").flatMap;var guessBrowser=require("./util").guessBrowser;var guessBrowserVersion=require("./util").guessBrowserVersion;var getSdpFormat=require("./util/sdp").getSdpFormat;var guess=guessBrowser();var guessVersion=guessBrowserVersion();var isChrome=guess==="chrome";var isFirefox=guess==="firefox";var isSafari=guess==="safari";var chromeMajorVersion=isChrome?guessVersion.major:null;var CHROME_LEGACY_MAX_AUDIO_LEVEL=32767;function getStats(peerConnection,options){if(!(peerConnection&&typeof peerConnection.getStats==="function")){return Promise.reject(new Error("Given PeerConnection does not support getStats"))}return _getStats(peerConnection,options)}function _getStats(peerConnection,options){var localAudioTracks=getTracks(peerConnection,"audio","local");var localVideoTracks=getTracks(peerConnection,"video","local");var remoteAudioTracks=getTracks(peerConnection,"audio");var remoteVideoTracks=getTracks(peerConnection,"video");var statsResponse={activeIceCandidatePair:null,localAudioTrackStats:[],localVideoTrackStats:[],remoteAudioTrackStats:[],remoteVideoTrackStats:[]};var trackStatsPromises=flatMap([[localAudioTracks,"localAudioTrackStats",false],[localVideoTracks,"localVideoTrackStats",false],[remoteAudioTracks,"remoteAudioTrackStats",true],[remoteVideoTracks,"remoteVideoTrackStats",true]],function(triple){var tracks=triple[0];var statsArrayName=triple[1];var isRemote=triple[2];return tracks.map(function(track){return getTrackStats(peerConnection,track,Object.assign({isRemote:isRemote},options)).then(function(trackStatsArray){trackStatsArray.forEach(function(trackStats){trackStats.trackId=track.id;statsResponse[statsArrayName].push(trackStats)})})})});return Promise.all(trackStatsPromises).then(function(){return getActiveIceCandidatePairStats(peerConnection,options)}).then(function(activeIceCandidatePairStatsReport){statsResponse.activeIceCandidatePair=activeIceCandidatePairStatsReport;return statsResponse})}function getActiveIceCandidatePairStats(peerConnection,options){options=options||{};if(typeof options.testForChrome!=="undefined"||isChrome||typeof options.testForSafari!=="undefined"||isSafari){return peerConnection.getStats().then(standardizeChromeOrSafariActiveIceCandidatePairStats)}if(typeof options.testForFirefox!=="undefined"||isFirefox){return peerConnection.getStats().then(standardizeFirefoxActiveIceCandidatePairStats)}return Promise.reject(new Error("RTCPeerConnection#getStats() not supported"))}function standardizeChromeOrSafariActiveIceCandidatePairStats(stats){var activeCandidatePairStats=Array.from(stats.values()).find(function(stat){return stat.type==="candidate-pair"&&stat.nominated});if(!activeCandidatePairStats){return null}var activeLocalCandidateStats=stats.get(activeCandidatePairStats.localCandidateId);var activeRemoteCandidateStats=stats.get(activeCandidatePairStats.remoteCandidateId);var standardizedCandidateStatsKeys=[{key:"candidateType",type:"string"},{key:"ip",type:"string"},{key:"port",type:"number"},{key:"priority",type:"number"},{key:"protocol",type:"string"},{key:"url",type:"string"}];var standardizedLocalCandidateStatsKeys=standardizedCandidateStatsKeys.concat([{key:"deleted",type:"boolean"},{key:"relayProtocol",type:"string"}]);var standatdizedLocalCandidateStatsReport=activeLocalCandidateStats?standardizedLocalCandidateStatsKeys.reduce(function(report,keyInfo){report[keyInfo.key]=typeof activeLocalCandidateStats[keyInfo.key]===keyInfo.type?activeLocalCandidateStats[keyInfo.key]:keyInfo.key==="deleted"?false:null;return report},{}):null;var standardizedRemoteCandidateStatsReport=activeRemoteCandidateStats?standardizedCandidateStatsKeys.reduce(function(report,keyInfo){
55
- report[keyInfo.key]=typeof activeRemoteCandidateStats[keyInfo.key]===keyInfo.type?activeRemoteCandidateStats[keyInfo.key]:null;return report},{}):null;return[{key:"availableIncomingBitrate",type:"number"},{key:"availableOutgoingBitrate",type:"number"},{key:"bytesReceived",type:"number"},{key:"bytesSent",type:"number"},{key:"consentRequestsSent",type:"number"},{key:"currentRoundTripTime",type:"number"},{key:"lastPacketReceivedTimestamp",type:"number"},{key:"lastPacketSentTimestamp",type:"number"},{key:"nominated",type:"boolean"},{key:"priority",type:"number"},{key:"readable",type:"boolean"},{key:"requestsReceived",type:"number"},{key:"requestsSent",type:"number"},{key:"responsesReceived",type:"number"},{key:"responsesSent",type:"number"},{key:"retransmissionsReceived",type:"number"},{key:"retransmissionsSent",type:"number"},{key:"state",type:"string",fixup:function(state){return state==="inprogress"?"in-progress":state}},{key:"totalRoundTripTime",type:"number"},{key:"transportId",type:"string"},{key:"writable",type:"boolean"}].reduce(function(report,keyInfo){report[keyInfo.key]=typeof activeCandidatePairStats[keyInfo.key]===keyInfo.type?keyInfo.fixup?keyInfo.fixup(activeCandidatePairStats[keyInfo.key]):activeCandidatePairStats[keyInfo.key]:null;return report},{localCandidate:standatdizedLocalCandidateStatsReport,remoteCandidate:standardizedRemoteCandidateStatsReport})}function standardizeFirefoxActiveIceCandidatePairStats(stats){var activeCandidatePairStats=Array.from(stats.values()).find(function(stat){return stat.type==="candidate-pair"&&stat.nominated});if(!activeCandidatePairStats){return null}var activeLocalCandidateStats=stats.get(activeCandidatePairStats.localCandidateId);var activeRemoteCandidateStats=stats.get(activeCandidatePairStats.remoteCandidateId);var standardizedCandidateStatsKeys=[{key:"candidateType",type:"string"},{key:"ip",ffKeys:["address","ipAddress"],type:"string"},{key:"port",ffKeys:["portNumber"],type:"number"},{key:"priority",type:"number"},{key:"protocol",ffKeys:["transport"],type:"string"},{key:"url",type:"string"}];var standardizedLocalCandidateStatsKeys=standardizedCandidateStatsKeys.concat([{key:"deleted",type:"boolean"},{key:"relayProtocol",type:"string"}]);var candidateTypes={host:"host",peerreflexive:"prflx",relayed:"relay",serverreflexive:"srflx"};var standatdizedLocalCandidateStatsReport=activeLocalCandidateStats?standardizedLocalCandidateStatsKeys.reduce(function(report,keyInfo){var key=keyInfo.ffKeys&&keyInfo.ffKeys.find(function(key){return key in activeLocalCandidateStats})||keyInfo.key;report[keyInfo.key]=typeof activeLocalCandidateStats[key]===keyInfo.type?key==="candidateType"?candidateTypes[activeLocalCandidateStats[key]]||activeLocalCandidateStats[key]:activeLocalCandidateStats[key]:key==="deleted"?false:null;return report},{}):null;var standardizedRemoteCandidateStatsReport=activeRemoteCandidateStats?standardizedCandidateStatsKeys.reduce(function(report,keyInfo){var key=keyInfo.ffKeys&&keyInfo.ffKeys.find(function(key){return key in activeRemoteCandidateStats})||keyInfo.key;report[keyInfo.key]=typeof activeRemoteCandidateStats[key]===keyInfo.type?key==="candidateType"?candidateTypes[activeRemoteCandidateStats[key]]||activeRemoteCandidateStats[key]:activeRemoteCandidateStats[key]:null;return report},{}):null;return[{key:"availableIncomingBitrate",type:"number"},{key:"availableOutgoingBitrate",type:"number"},{key:"bytesReceived",type:"number"},{key:"bytesSent",type:"number"},{key:"consentRequestsSent",type:"number"},{key:"currentRoundTripTime",type:"number"},{key:"lastPacketReceivedTimestamp",type:"number"},{key:"lastPacketSentTimestamp",type:"number"},{key:"nominated",type:"boolean"},{key:"priority",type:"number"},{key:"readable",type:"boolean"},{key:"requestsReceived",type:"number"},{key:"requestsSent",type:"number"},{key:"responsesReceived",type:"number"},{key:"responsesSent",type:"number"},{key:"retransmissionsReceived",type:"number"},{key:"retransmissionsSent",type:"number"},{key:"state",type:"string"},{key:"totalRoundTripTime",type:"number"},{key:"transportId",type:"string"},{key:"writable",type:"boolean"}].reduce(function(report,keyInfo){report[keyInfo.key]=typeof activeCandidatePairStats[keyInfo.key]===keyInfo.type?activeCandidatePairStats[keyInfo.key]:null;return report},{localCandidate:standatdizedLocalCandidateStatsReport,remoteCandidate:standardizedRemoteCandidateStatsReport})}function getTracks(peerConnection,kind,localOrRemote){var getSendersOrReceivers=localOrRemote==="local"?"getSenders":"getReceivers";if(peerConnection[getSendersOrReceivers]){return peerConnection[getSendersOrReceivers]().map(function(senderOrReceiver){return senderOrReceiver.track}).filter(function(track){return track&&track.kind===kind})}var getStreams=localOrRemote==="local"?"getLocalStreams":"getRemoteStreams";return flatMap(peerConnection[getStreams](),function(stream){var getTracks=kind==="audio"?"getAudioTracks":"getVideoTracks";return stream[getTracks]()})}function getTrackStats(peerConnection,track,options){options=options||{};if(typeof options.testForChrome!=="undefined"||isChrome){return chromeOrSafariGetTrackStats(peerConnection,track)}if(typeof options.testForFirefox!=="undefined"||isFirefox){return firefoxGetTrackStats(peerConnection,track,options.isRemote)}if(typeof options.testForSafari!=="undefined"||isSafari){if(typeof options.testForSafari!=="undefined"||getSdpFormat()==="unified"){return chromeOrSafariGetTrackStats(peerConnection,track)}return Promise.reject(new Error(["getStats() is not supported on this version of Safari","due to this bug: https://bugs.webkit.org/show_bug.cgi?id=192601"].join(" ")))}return Promise.reject(new Error("RTCPeerConnection#getStats() not supported"))}function chromeOrSafariGetTrackStats(peerConnection,track){return new Promise(function(resolve,reject){if(chromeMajorVersion&&chromeMajorVersion<67){peerConnection.getStats(function(response){resolve([standardizeChromeLegacyStats(response,track)])},null,reject);return}peerConnection.getStats(track).then(function(response){resolve(standardizeChromeOrSafariStats(response))},reject)})}function firefoxGetTrackStats(peerConnection,track,isRemote){return new Promise(function(resolve,reject){peerConnection.getStats(track).then(function(response){resolve([standardizeFirefoxStats(response,isRemote)])},reject)})}function standardizeChromeLegacyStats(response,track){var ssrcReport=response.result().find(function(report){return report.type==="ssrc"&&report.stat("googTrackId")===track.id});var standardizedStats={};if(ssrcReport){standardizedStats.timestamp=Math.round(Number(ssrcReport.timestamp));standardizedStats=ssrcReport.names().reduce(function(stats,name){switch(name){case"googCodecName":stats.codecName=ssrcReport.stat(name);break;case"googRtt":stats.roundTripTime=Number(ssrcReport.stat(name));break;case"googJitterReceived":stats.jitter=Number(ssrcReport.stat(name));break;case"googFrameWidthInput":stats.frameWidthInput=Number(ssrcReport.stat(name));break;case"googFrameHeightInput":stats.frameHeightInput=Number(ssrcReport.stat(name));break;case"googFrameWidthSent":stats.frameWidthSent=Number(ssrcReport.stat(name));break;case"googFrameHeightSent":stats.frameHeightSent=Number(ssrcReport.stat(name));break;case"googFrameWidthReceived":stats.frameWidthReceived=Number(ssrcReport.stat(name));break;case"googFrameHeightReceived":stats.frameHeightReceived=Number(ssrcReport.stat(name));break;case"googFrameRateInput":stats.frameRateInput=Number(ssrcReport.stat(name));break;case"googFrameRateSent":stats.frameRateSent=Number(ssrcReport.stat(name));break;case"googFrameRateReceived":stats.frameRateReceived=Number(ssrcReport.stat(name));break;case"ssrc":stats[name]=ssrcReport.stat(name);break;case"bytesReceived":case"bytesSent":case"packetsLost":case"packetsReceived":case"packetsSent":case"audioInputLevel":case"audioOutputLevel":stats[name]=Number(ssrcReport.stat(name));break}return stats},standardizedStats)}return standardizedStats}function standardizeChromeOrSafariStats(response){var inbound=null;var outbound=[];var remoteInbound=null;var remoteOutbound=null;var track=null;var codec=null;var localMedia=null;response.forEach(function(stat){switch(stat.type){case"inbound-rtp":inbound=stat;break;case"outbound-rtp":outbound.push(stat);break;case"media-source":localMedia=stat;break;case"track":track=stat;break;case"codec":codec=stat;break;case"remote-inbound-rtp":remoteInbound=stat;break;case"remote-outbound-rtp":remoteOutbound=stat;break}});var isRemote=track&&track.remoteSource;var mainSources=isRemote?[inbound]:outbound;var stats=[];var remoteSource=isRemote?remoteOutbound:remoteInbound;mainSources.forEach(function(source){var standardizedStats={};var statSources=[source,localMedia,track,codec,remoteSource&&remoteSource.ssrc===source.ssrc?remoteSource:null];function getStatValue(name){var sourceFound=statSources.find(function(statSource){return statSource&&typeof statSource[name]!=="undefined"})||null;return sourceFound?sourceFound[name]:null}var ssrc=getStatValue("ssrc");if(typeof ssrc==="number"){standardizedStats.ssrc=String(ssrc)}var timestamp=getStatValue("timestamp");standardizedStats.timestamp=Math.round(timestamp);var mimeType=getStatValue("mimeType");if(typeof mimeType==="string"){mimeType=mimeType.split("/");standardizedStats.codecName=mimeType[mimeType.length-1]}var roundTripTime=getStatValue("roundTripTime");if(typeof roundTripTime==="number"){standardizedStats.roundTripTime=Math.round(roundTripTime*1e3)}var jitter=getStatValue("jitter");if(typeof jitter==="number"){standardizedStats.jitter=Math.round(jitter*1e3)}var frameWidth=getStatValue("frameWidth");if(typeof frameWidth==="number"){if(isRemote){standardizedStats.frameWidthReceived=frameWidth}else{standardizedStats.frameWidthSent=frameWidth;standardizedStats.frameWidthInput=track.frameWidth}}var frameHeight=getStatValue("frameHeight");if(typeof frameHeight==="number"){if(isRemote){standardizedStats.frameHeightReceived=frameHeight}else{standardizedStats.frameHeightSent=frameHeight;standardizedStats.frameHeightInput=track.frameHeight}}var framesPerSecond=getStatValue("framesPerSecond");if(typeof framesPerSecond==="number"){standardizedStats[isRemote?"frameRateReceived":"frameRateSent"]=framesPerSecond}var bytesReceived=getStatValue("bytesReceived");if(typeof bytesReceived==="number"){standardizedStats.bytesReceived=bytesReceived}var bytesSent=getStatValue("bytesSent");if(typeof bytesSent==="number"){standardizedStats.bytesSent=bytesSent}var packetsLost=getStatValue("packetsLost");if(typeof packetsLost==="number"){standardizedStats.packetsLost=packetsLost}var packetsReceived=getStatValue("packetsReceived");if(typeof packetsReceived==="number"){standardizedStats.packetsReceived=packetsReceived}var packetsSent=getStatValue("packetsSent");if(typeof packetsSent==="number"){standardizedStats.packetsSent=packetsSent}var audioLevel=getStatValue("audioLevel");if(typeof audioLevel==="number"){audioLevel=Math.round(audioLevel*CHROME_LEGACY_MAX_AUDIO_LEVEL);if(isRemote){standardizedStats.audioOutputLevel=audioLevel}else{standardizedStats.audioInputLevel=audioLevel}}var totalPacketSendDalay=getStatValue("totalPacketSendDelay");if(typeof totalPacketSendDalay==="number"){standardizedStats.totalPacketSendDelay=totalPacketSendDalay}var totalEncodeTime=getStatValue("totalEncodeTime");if(typeof totalEncodeTime==="number"){standardizedStats.totalEncodeTime=totalEncodeTime}var framesEncoded=getStatValue("framesEncoded");if(typeof framesEncoded==="number"){standardizedStats.framesEncoded=framesEncoded}var estimatedPlayoutTimestamp=getStatValue("estimatedPlayoutTimestamp");if(typeof estimatedPlayoutTimestamp==="number"){standardizedStats.estimatedPlayoutTimestamp=estimatedPlayoutTimestamp}var totalDecodeTime=getStatValue("totalDecodeTime");if(typeof totalDecodeTime==="number"){standardizedStats.totalDecodeTime=totalDecodeTime}var framesDecoded=getStatValue("framesDecoded");if(typeof framesDecoded==="number"){standardizedStats.framesDecoded=framesDecoded}var jitterBufferDelay=getStatValue("jitterBufferDelay");if(typeof jitterBufferDelay==="number"){standardizedStats.jitterBufferDelay=jitterBufferDelay}var jitterBufferEmittedCount=getStatValue("jitterBufferEmittedCount");if(typeof jitterBufferEmittedCount==="number"){standardizedStats.jitterBufferEmittedCount=jitterBufferEmittedCount}stats.push(standardizedStats)});return stats}function standardizeFirefoxStats(response,isRemote){response=response||new Map;var inbound=null;var outbound=null;response.forEach(function(stat){if(stat.isRemote){return}switch(stat.type){case"inbound-rtp":inbound=stat;outbound=response.get(stat.remoteId);break;case"outbound-rtp":outbound=stat;inbound=response.get(stat.remoteId);break}});var first=isRemote?inbound:outbound;var second=isRemote?outbound:inbound;function getStatValue(name){if(first&&typeof first[name]!=="undefined"){return first[name]}if(second&&typeof second[name]!=="undefined"){return second[name]}return null}var standardizedStats={};var timestamp=getStatValue("timestamp");standardizedStats.timestamp=Math.round(timestamp);var ssrc=getStatValue("ssrc");if(typeof ssrc==="number"){standardizedStats.ssrc=String(ssrc)}var bytesSent=getStatValue("bytesSent");if(typeof bytesSent==="number"){standardizedStats.bytesSent=bytesSent}var packetsLost=getStatValue("packetsLost");if(typeof packetsLost==="number"){standardizedStats.packetsLost=packetsLost}var packetsSent=getStatValue("packetsSent");if(typeof packetsSent==="number"){standardizedStats.packetsSent=packetsSent}var roundTripTime=getStatValue("roundTripTime");if(typeof roundTripTime==="number"){standardizedStats.roundTripTime=Math.round(roundTripTime*1e3)}var jitter=getStatValue("jitter");if(typeof jitter==="number"){standardizedStats.jitter=Math.round(jitter*1e3)}var frameRateSent=getStatValue("framerateMean");if(typeof frameRateSent==="number"){standardizedStats.frameRateSent=Math.round(frameRateSent)}var bytesReceived=getStatValue("bytesReceived");if(typeof bytesReceived==="number"){standardizedStats.bytesReceived=bytesReceived}var packetsReceived=getStatValue("packetsReceived");if(typeof packetsReceived==="number"){standardizedStats.packetsReceived=packetsReceived}var frameRateReceived=getStatValue("framerateMean");if(typeof frameRateReceived==="number"){standardizedStats.frameRateReceived=Math.round(frameRateReceived)}var totalPacketSendDalay=getStatValue("totalPacketSendDelay");if(typeof totalPacketSendDalay==="number"){standardizedStats.totalPacketSendDelay=totalPacketSendDalay}var totalEncodeTime=getStatValue("totalEncodeTime");if(typeof totalEncodeTime==="number"){standardizedStats.totalEncodeTime=totalEncodeTime}var framesEncoded=getStatValue("framesEncoded");if(typeof framesEncoded==="number"){standardizedStats.framesEncoded=framesEncoded}var estimatedPlayoutTimestamp=getStatValue("estimatedPlayoutTimestamp");if(typeof estimatedPlayoutTimestamp==="number"){standardizedStats.estimatedPlayoutTimestamp=estimatedPlayoutTimestamp}var totalDecodeTime=getStatValue("totalDecodeTime");if(typeof totalDecodeTime==="number"){standardizedStats.totalDecodeTime=totalDecodeTime}var framesDecoded=getStatValue("framesDecoded");if(typeof framesDecoded==="number"){standardizedStats.framesDecoded=framesDecoded}var jitterBufferDelay=getStatValue("jitterBufferDelay");if(typeof jitterBufferDelay==="number"){standardizedStats.jitterBufferDelay=jitterBufferDelay}var jitterBufferEmittedCount=getStatValue("jitterBufferEmittedCount");if(typeof jitterBufferEmittedCount==="number"){standardizedStats.jitterBufferEmittedCount=jitterBufferEmittedCount}return standardizedStats}module.exports=getStats},{"./util":170,"./util/sdp":172}],156:[function(require,module,exports){"use strict";function getUserMedia(constraints){if(typeof navigator==="object"&&typeof navigator.mediaDevices==="object"&&typeof navigator.mediaDevices.getUserMedia==="function"){constraints=constraints||{audio:true,video:true};return navigator.mediaDevices.getUserMedia(constraints)}return Promise.reject(new Error("getUserMedia is not supported"))}module.exports=getUserMedia},{}],157:[function(require,module,exports){"use strict";var WebRTC={};Object.defineProperties(WebRTC,{getStats:{enumerable:true,value:require("./getstats")},getUserMedia:{enumerable:true,value:require("./getusermedia")},MediaStream:{enumerable:true,value:require("./mediastream")},MediaStreamTrack:{enumerable:true,value:require("./mediastreamtrack")},RTCIceCandidate:{enumerable:true,value:require("./rtcicecandidate")},RTCPeerConnection:{enumerable:true,value:require("./rtcpeerconnection")},RTCSessionDescription:{enumerable:true,value:require("./rtcsessiondescription")}});module.exports=WebRTC},{"./getstats":155,"./getusermedia":156,"./mediastream":158,"./mediastreamtrack":159,"./rtcicecandidate":160,"./rtcpeerconnection":163,"./rtcsessiondescription":168}],158:[function(require,module,exports){"use strict";if(typeof MediaStream==="function"){module.exports=MediaStream}else{module.exports=function MediaStream(){throw new Error("MediaStream is not supported")}}},{}],159:[function(require,module,exports){"use strict";if(typeof MediaStreamTrack==="function"){module.exports=MediaStreamTrack}else{module.exports=function MediaStreamTrack(){throw new Error("MediaStreamTrack is not supported")}}},{}],160:[function(require,module,exports){"use strict";if(typeof RTCIceCandidate==="function"){module.exports=RTCIceCandidate}else{module.exports=function RTCIceCandidate(){throw new Error("RTCIceCandidate is not supported")}}},{}],161:[function(require,module,exports){"use strict";var ChromeRTCSessionDescription=require("../rtcsessiondescription/chrome");var EventTarget=require("../util/eventtarget");var inherits=require("../../vendor/inherits");var Latch=require("../util/latch");var MediaStream=require("../mediastream");var RTCRtpSenderShim=require("../rtcrtpsender");var sdpUtils=require("../util/sdp");var util=require("../util");var isIOSChrome=require("../util").isIOSChrome;var isUnifiedPlan=sdpUtils.getSdpFormat()==="unified";function ChromeRTCPeerConnection(configuration,constraints){if(!(this instanceof ChromeRTCPeerConnection)){return new ChromeRTCPeerConnection(configuration,constraints)}EventTarget.call(this);configuration=configuration||{};var newConfiguration=Object.assign(configuration.iceTransportPolicy?{iceTransports:configuration.iceTransportPolicy}:{},configuration);util.interceptEvent(this,"datachannel");util.interceptEvent(this,"signalingstatechange");var sdpFormat=sdpUtils.getSdpFormat(newConfiguration.sdpSemantics);var peerConnection=new RTCPeerConnection(newConfiguration,constraints);Object.defineProperties(this,{_appliedTracksToSSRCs:{value:new Map,writable:true},_localStream:{value:new MediaStream},_peerConnection:{value:peerConnection},_pendingLocalOffer:{value:null,writable:true},_pendingRemoteOffer:{value:null,writable:true},_rolledBackTracksToSSRCs:{value:new Map,writable:true},_sdpFormat:{value:sdpFormat},_senders:{value:new Map},_signalingStateLatch:{value:new Latch},_tracksToSSRCs:{value:new Map,writable:true},localDescription:{enumerable:true,get:function(){return this._pendingLocalOffer?this._pendingLocalOffer:peerConnection.localDescription}},remoteDescription:{enumerable:true,get:function(){return this._pendingRemoteOffer?this._pendingRemoteOffer:peerConnection.remoteDescription}},signalingState:{enumerable:true,get:function(){if(this._pendingLocalOffer){return"have-local-offer"}else if(this._pendingRemoteOffer){return"have-remote-offer"}return peerConnection.signalingState}}});var self=this;peerConnection.addEventListener("datachannel",function ondatachannel(event){shimDataChannel(event.channel);self.dispatchEvent(event)});peerConnection.addEventListener("signalingstatechange",function onsignalingstatechange(){if(peerConnection.signalingState==="stable"){self._appliedTracksToSSRCs=new Map(self._tracksToSSRCs)}if(!self._pendingLocalOffer&&!self._pendingRemoteOffer){self.dispatchEvent.apply(self,arguments)}});peerConnection.ontrack=function ontrack(){};if(typeof RTCPeerConnection.prototype.addTrack!=="function"){peerConnection.addStream(this._localStream)}util.proxyProperties(RTCPeerConnection.prototype,this,peerConnection)}inherits(ChromeRTCPeerConnection,EventTarget);if(typeof RTCPeerConnection.prototype.addTrack!=="function"){ChromeRTCPeerConnection.prototype.addTrack=function addTrack(){var args=[].slice.call(arguments);var track=args[0];if(this._peerConnection.signalingState==="closed"){throw new Error("Cannot add MediaStreamTrack ["+track.id+", "+track.kind+"]: RTCPeerConnection is closed")}var sender=this._senders.get(track);if(sender&&sender.track){throw new Error("Cannot add MediaStreamTrack ["+track.id+", "+track.kind+"]: RTCPeerConnection already has it")}this._peerConnection.removeStream(this._localStream);this._localStream.addTrack(track);this._peerConnection.addStream(this._localStream);sender=new RTCRtpSenderShim(track);this._senders.set(track,sender);return sender};ChromeRTCPeerConnection.prototype.removeTrack=function removeTrack(sender){if(this._peerConnection.signalingState==="closed"){throw new Error("Cannot remove MediaStreamTrack: RTCPeerConnection is closed")}var track=sender.track;if(!track){return}sender=this._senders.get(track);if(sender&&sender.track){sender.track=null;this._peerConnection.removeStream(this._localStream);this._localStream.removeTrack(track);this._peerConnection.addStream(this._localStream)}};ChromeRTCPeerConnection.prototype.getSenders=function getSenders(){return Array.from(this._senders.values())}}else{ChromeRTCPeerConnection.prototype.removeTrack=function removeTrack(sender){if(this._peerConnection.signalingState==="closed"){throw new Error("Cannot remove MediaStreamTrack: RTCPeerConnection is closed")}try{this._peerConnection.removeTrack(sender)}catch(e){}}}ChromeRTCPeerConnection.prototype.addIceCandidate=function addIceCandidate(candidate){var args=[].slice.call(arguments);var promise;var self=this;if(this.signalingState==="have-remote-offer"){promise=this._signalingStateLatch.when("low").then(function signalingStatesResolved(){return self._peerConnection.addIceCandidate(candidate)})}else{promise=this._peerConnection.addIceCandidate(candidate)}return args.length>1?util.legacyPromise(promise,args[1],args[2]):promise};ChromeRTCPeerConnection.prototype.close=function close(){if(this.signalingState!=="closed"){this._pendingLocalOffer=null;this._pendingRemoteOffer=null;this._peerConnection.close()}};ChromeRTCPeerConnection.prototype.createAnswer=function createAnswer(){var args=[].slice.call(arguments);var promise;var self=this;if(this._pendingRemoteOffer){promise=this._peerConnection.setRemoteDescription(this._pendingRemoteOffer).then(function setRemoteDescriptionSucceeded(){self._signalingStateLatch.lower();return self._peerConnection.createAnswer()}).then(function createAnswerSucceeded(answer){self._pendingRemoteOffer=null;self._rolledBackTracksToSSRCs.clear();return new ChromeRTCSessionDescription({type:"answer",sdp:updateTrackIdsToSSRCs(self._sdpFormat,self._tracksToSSRCs,answer.sdp)})},function setRemoteDescriptionOrCreateAnswerFailed(error){self._pendingRemoteOffer=null;throw error})}else{promise=this._peerConnection.createAnswer().then(function(answer){self._rolledBackTracksToSSRCs.clear();return new ChromeRTCSessionDescription({type:"answer",sdp:updateTrackIdsToSSRCs(self._sdpFormat,self._tracksToSSRCs,answer.sdp)})})}return args.length>1?util.legacyPromise(promise,args[0],args[1]):promise};ChromeRTCPeerConnection.prototype.createOffer=function createOffer(){var args=[].slice.call(arguments);var options=(args.length>1?args[2]:args[0])||{};var self=this;if(isIOSChrome()){if(options.offerToReceiveVideo&&!this._audioTransceiver&&!(isUnifiedPlan&&hasReceiversForTracksOfKind(this,"audio"))){delete options.offerToReceiveAudio;try{this._audioTransceiver=isUnifiedPlan?this.addTransceiver("audio",{direction:"recvonly"}):this.addTransceiver("audio")}catch(e){return Promise.reject(e)}}if(options.offerToReceiveVideo&&!this._videoTransceiver&&!(isUnifiedPlan&&hasReceiversForTracksOfKind(this,"video"))){delete options.offerToReceiveVideo;try{this._videoTransceiver=isUnifiedPlan?this.addTransceiver("video",{direction:"recvonly"}):this.addTransceiver("video")}catch(e){return Promise.reject(e)}}}var promise=this._peerConnection.createOffer(options).then(function(offer){self._rolledBackTracksToSSRCs.clear();return new ChromeRTCSessionDescription({type:offer.type,sdp:updateTrackIdsToSSRCs(self._sdpFormat,self._tracksToSSRCs,offer.sdp)})});return args.length>1?util.legacyPromise(promise,args[0],args[1]):promise};ChromeRTCPeerConnection.prototype.createDataChannel=function createDataChannel(label,dataChannelDict){dataChannelDict=shimDataChannelInit(dataChannelDict);var dataChannel=this._peerConnection.createDataChannel(label,dataChannelDict);shimDataChannel(dataChannel);return dataChannel};ChromeRTCPeerConnection.prototype.setLocalDescription=function setLocalDescription(){var args=[].slice.call(arguments);var description=args[0];if(this._rolledBackTracksToSSRCs.size>0){this._tracksToSSRCs=new Map(this._rolledBackTracksToSSRCs);this._rolledBackTracksToSSRCs.clear()}var promise=setDescription(this,true,description);return args.length>1?util.legacyPromise(promise,args[1],args[2]):promise};ChromeRTCPeerConnection.prototype.setRemoteDescription=function setRemoteDescription(){var args=[].slice.call(arguments);var description=args[0];this._rolledBackTracksToSSRCs.clear();var promise=setDescription(this,false,description);return args.length>1?util.legacyPromise(promise,args[1],args[2]):promise};util.delegateMethods(RTCPeerConnection.prototype,ChromeRTCPeerConnection.prototype,"_peerConnection");function setDescription(peerConnection,local,description){function setPendingLocalOffer(offer){if(local){peerConnection._pendingLocalOffer=offer}else{peerConnection._pendingRemoteOffer=offer}}function clearPendingLocalOffer(){if(local){peerConnection._pendingLocalOffer=null}else{peerConnection._pendingRemoteOffer=null}}var pendingLocalOffer=local?peerConnection._pendingLocalOffer:peerConnection._pendingRemoteOffer;var pendingRemoteOffer=local?peerConnection._pendingRemoteOffer:peerConnection._pendingLocalOffer;var intermediateState=local?"have-local-offer":"have-remote-offer";var setLocalDescription=local?"setLocalDescription":"setRemoteDescription";var promise;if(!local&&pendingRemoteOffer&&description.type==="answer"){promise=setRemoteAnswer(peerConnection,description)}else if(description.type==="offer"){if(peerConnection.signalingState!==intermediateState&&peerConnection.signalingState!=="stable"){return Promise.reject(new Error("Cannot set "+(local?"local":"remote")+" offer in state "+peerConnection.signalingState))}if(!pendingLocalOffer&&peerConnection._signalingStateLatch.state==="low"){peerConnection._signalingStateLatch.raise()}var previousSignalingState=peerConnection.signalingState;setPendingLocalOffer(unwrap(description));promise=Promise.resolve();if(peerConnection.signalingState!==previousSignalingState){promise.then(function dispatchSignalingStateChangeEvent(){peerConnection.dispatchEvent(new Event("signalingstatechange"))})}}else if(description.type==="rollback"){if(peerConnection.signalingState!==intermediateState){promise=Promise.reject(new Error("Cannot rollback "+(local?"local":"remote")+" description in "+peerConnection.signalingState))}else{clearPendingLocalOffer();peerConnection._rolledBackTracksToSSRCs=new Map(peerConnection._tracksToSSRCs);peerConnection._tracksToSSRCs=new Map(peerConnection._appliedTracksToSSRCs);promise=Promise.resolve();promise.then(function dispatchSignalingStateChangeEvent(){peerConnection.dispatchEvent(new Event("signalingstatechange"))})}}return promise||peerConnection._peerConnection[setLocalDescription](unwrap(description))}function setRemoteAnswer(peerConnection,answer){var pendingLocalOffer=peerConnection._pendingLocalOffer;return peerConnection._peerConnection.setLocalDescription(pendingLocalOffer).then(function setLocalOfferSucceeded(){peerConnection._pendingLocalOffer=null;return peerConnection.setRemoteDescription(answer)}).then(function setRemoteAnswerSucceeded(){peerConnection._signalingStateLatch.lower()})}function hasReceiversForTracksOfKind(peerConnection,kind){return!!peerConnection.getTransceivers().find(function(transceiver){return transceiver.receiver&&transceiver.receiver.track&&transceiver.receiver.track.kind===kind})}function unwrap(description){if(description instanceof ChromeRTCSessionDescription){if(description._description){return description._description}}return new RTCSessionDescription(description)}function needsMaxPacketLifeTimeShim(){return"maxRetransmitTime"in RTCDataChannel.prototype&&!("maxPacketLifeTime"in RTCDataChannel.prototype)}function shimDataChannelInit(dataChannelDict){dataChannelDict=Object.assign({},dataChannelDict);if(needsMaxPacketLifeTimeShim()&&"maxPacketLifeTime"in dataChannelDict){dataChannelDict.maxRetransmitTime=dataChannelDict.maxPacketLifeTime}return dataChannelDict}function shimDataChannel(dataChannel){Object.defineProperty(dataChannel,"maxRetransmits",{value:dataChannel.maxRetransmits===65535?null:dataChannel.maxRetransmits});if(needsMaxPacketLifeTimeShim()){Object.defineProperty(dataChannel,"maxPacketLifeTime",{value:dataChannel.maxRetransmitTime===65535?null:dataChannel.maxRetransmitTime})}return dataChannel}function updateTrackIdsToSSRCs(sdpFormat,tracksToSSRCs,sdp){return sdpFormat==="unified"?sdpUtils.updateUnifiedPlanTrackIdsToSSRCs(tracksToSSRCs,sdp):sdpUtils.updatePlanBTrackIdsToSSRCs(tracksToSSRCs,sdp)}module.exports=ChromeRTCPeerConnection},{"../../vendor/inherits":150,"../mediastream":158,"../rtcrtpsender":165,"../rtcsessiondescription/chrome":166,"../util":170,"../util/eventtarget":169,"../util/latch":171,"../util/sdp":172}],162:[function(require,module,exports){"use strict";var EventTarget=require("../util/eventtarget");var FirefoxRTCSessionDescription=require("../rtcsessiondescription/firefox");var inherits=require("../../vendor/inherits");var updateTracksToSSRCs=require("../util/sdp").updateUnifiedPlanTrackIdsToSSRCs;var util=require("../util");var needsWorkaroundForBug1480277=typeof navigator==="object"&&navigator.userAgent&&(navigator.userAgent.match(/Firefox\/61/)||navigator.userAgent.match(/Firefox\/62/));function FirefoxRTCPeerConnection(configuration){if(!(this instanceof FirefoxRTCPeerConnection)){return new FirefoxRTCPeerConnection(configuration)}EventTarget.call(this);util.interceptEvent(this,"signalingstatechange");var peerConnection=new RTCPeerConnection(configuration);Object.defineProperties(this,{_initiallyNegotiatedDtlsRole:{value:null,writable:true},_isClosed:{value:false,writable:true},_peerConnection:{value:peerConnection},_rollingBack:{value:false,writable:true},_tracksToSSRCs:{value:new Map},iceGatheringState:{enumerable:true,get:function(){return this._isClosed?"complete":this._peerConnection.iceGatheringState}},localDescription:{enumerable:true,get:function(){return overwriteWithInitiallyNegotiatedDtlsRole(this._peerConnection.localDescription,this._initiallyNegotiatedDtlsRole)}},signalingState:{enumerable:true,get:function(){return this._isClosed?"closed":this._peerConnection.signalingState}}});var self=this;var previousSignalingState;peerConnection.addEventListener("signalingstatechange",function onsignalingstatechange(){if(!self._rollingBack&&self.signalingState!==previousSignalingState){previousSignalingState=self.signalingState;var dispatchEventToSelf=self.dispatchEvent.apply.bind(self.dispatchEvent,self,arguments);if(self._isClosed){setTimeout(dispatchEventToSelf)}else{dispatchEventToSelf()}}});util.proxyProperties(RTCPeerConnection.prototype,this,peerConnection)}inherits(FirefoxRTCPeerConnection,EventTarget);Object.defineProperty(FirefoxRTCPeerConnection.prototype,"peerIdentity",{enumerable:true,value:Promise.resolve({idp:"",name:""})});if(needsWorkaroundForBug1480277){
56
- FirefoxRTCPeerConnection.prototype.addTrack=function addTrack(){var track=arguments[0];var sender=this._peerConnection.addTrack.apply(this._peerConnection,arguments);sender.replaceTrack(track);return sender}}FirefoxRTCPeerConnection.prototype.createAnswer=function createAnswer(){var args=[].slice.call(arguments);var promise;var self=this;promise=this._peerConnection.createAnswer().then(function createAnswerSucceeded(answer){saveInitiallyNegotiatedDtlsRole(self,answer);return overwriteWithInitiallyNegotiatedDtlsRole(answer,self._initiallyNegotiatedDtlsRole)});return typeof args[0]==="function"?util.legacyPromise(promise,args[0],args[1]):promise};FirefoxRTCPeerConnection.prototype.createOffer=function createOffer(){var args=[].slice.call(arguments);var options=(args.length>1?args[2]:args[0])||{};var promise;var self=this;if(this.signalingState==="have-local-offer"||this.signalingState==="have-remote-offer"){var local=this.signalingState==="have-local-offer";promise=rollback(this,local,function rollbackSucceeded(){return self.createOffer(options)})}else{promise=self._peerConnection.createOffer(options)}promise=promise.then(function(offer){return new FirefoxRTCSessionDescription({type:offer.type,sdp:updateTracksToSSRCs(self._tracksToSSRCs,offer.sdp)})});return args.length>1?util.legacyPromise(promise,args[0],args[1]):promise};FirefoxRTCPeerConnection.prototype.setLocalDescription=function setLocalDescription(){var args=[].slice.call(arguments);var description=args[0];var promise;if(description&&description.type==="answer"&&this.signalingState==="have-local-offer"){promise=Promise.reject(new Error("Cannot set local answer in state have-local-offer"))}if(promise){return args.length>1?util.legacyPromise(promise,args[1],args[2]):promise}return this._peerConnection.setLocalDescription.apply(this._peerConnection,args)};FirefoxRTCPeerConnection.prototype.setRemoteDescription=function setRemoteDescription(){var args=[].slice.call(arguments);var description=args[0];var promise;var self=this;if(description&&this.signalingState==="have-remote-offer"){if(description.type==="answer"){promise=Promise.reject(new Error("Cannot set remote answer in state have-remote-offer"))}else if(description.type==="offer"){promise=rollback(this,false,function rollbackSucceeded(){return self._peerConnection.setRemoteDescription(description)})}}if(!promise){promise=this._peerConnection.setRemoteDescription(description)}promise=promise.then(function setRemoteDescriptionSucceeded(){saveInitiallyNegotiatedDtlsRole(self,description,true)});return args.length>1?util.legacyPromise(promise,args[1],args[2]):promise};FirefoxRTCPeerConnection.prototype.close=function close(){if(this.signalingState!=="closed"){this._isClosed=true;this._peerConnection.close()}};util.delegateMethods(RTCPeerConnection.prototype,FirefoxRTCPeerConnection.prototype,"_peerConnection");function rollback(peerConnection,local,onceRolledBack){var setLocalDescription=local?"setLocalDescription":"setRemoteDescription";peerConnection._rollingBack=true;return peerConnection._peerConnection[setLocalDescription](new FirefoxRTCSessionDescription({type:"rollback"})).then(onceRolledBack).then(function onceRolledBackSucceeded(result){peerConnection._rollingBack=false;return result},function rollbackOrOnceRolledBackFailed(error){peerConnection._rollingBack=false;throw error})}function saveInitiallyNegotiatedDtlsRole(peerConnection,description,remote){if(peerConnection._initiallyNegotiatedDtlsRole||description.type==="offer"){return}var match=description.sdp.match(/a=setup:([a-z]+)/);if(!match){return}var dtlsRole=match[1];peerConnection._initiallyNegotiatedDtlsRole=remote?{active:"passive",passive:"active"}[dtlsRole]:dtlsRole}function overwriteWithInitiallyNegotiatedDtlsRole(description,dtlsRole){if(description&&description.type==="answer"&&dtlsRole){return new FirefoxRTCSessionDescription({type:description.type,sdp:description.sdp.replace(/a=setup:[a-z]+/g,"a=setup:"+dtlsRole)})}return description}module.exports=FirefoxRTCPeerConnection},{"../../vendor/inherits":150,"../rtcsessiondescription/firefox":167,"../util":170,"../util/eventtarget":169,"../util/sdp":172}],163:[function(require,module,exports){"use strict";if(typeof RTCPeerConnection==="function"){var guessBrowser=require("../util").guessBrowser;switch(guessBrowser()){case"chrome":module.exports=require("./chrome");break;case"firefox":module.exports=require("./firefox");break;case"safari":module.exports=require("./safari");break;default:module.exports=RTCPeerConnection;break}}else{module.exports=function RTCPeerConnection(){throw new Error("RTCPeerConnection is not supported")}}},{"../util":170,"./chrome":161,"./firefox":162,"./safari":164}],164:[function(require,module,exports){"use strict";var EventTarget=require("../util/eventtarget");var inherits=require("../../vendor/inherits");var Latch=require("../util/latch");var sdpUtils=require("../util/sdp");var util=require("../util");var isUnifiedPlan=sdpUtils.getSdpFormat()==="unified";var updateTrackIdsToSSRCs=isUnifiedPlan?sdpUtils.updateUnifiedPlanTrackIdsToSSRCs:sdpUtils.updatePlanBTrackIdsToSSRCs;function SafariRTCPeerConnection(configuration){if(!(this instanceof SafariRTCPeerConnection)){return new SafariRTCPeerConnection(configuration)}EventTarget.call(this);util.interceptEvent(this,"datachannel");util.interceptEvent(this,"iceconnectionstatechange");util.interceptEvent(this,"signalingstatechange");util.interceptEvent(this,"track");var peerConnection=new RTCPeerConnection(configuration);Object.defineProperties(this,{_appliedTracksToSSRCs:{value:new Map,writable:true},_audioTransceiver:{value:null,writable:true},_isClosed:{value:false,writable:true},_peerConnection:{value:peerConnection},_pendingLocalOffer:{value:null,writable:true},_pendingRemoteOffer:{value:null,writable:true},_rolledBackTracksToSSRCs:{value:new Map,writable:true},_signalingStateLatch:{value:new Latch},_tracksToSSRCs:{value:new Map,writable:true},_videoTransceiver:{value:null,writable:true},localDescription:{enumerable:true,get:function(){return this._pendingLocalOffer||this._peerConnection.localDescription}},iceConnectionState:{enumerable:true,get:function(){return this._isClosed?"closed":this._peerConnection.iceConnectionState}},iceGatheringState:{enumerable:true,get:function(){return this._isClosed?"complete":this._peerConnection.iceGatheringState}},remoteDescription:{enumerable:true,get:function(){return this._pendingRemoteOffer||this._peerConnection.remoteDescription}},signalingState:{enumerable:true,get:function(){if(this._isClosed){return"closed"}else if(this._pendingLocalOffer){return"have-local-offer"}else if(this._pendingRemoteOffer){return"have-remote-offer"}return this._peerConnection.signalingState}}});var self=this;peerConnection.addEventListener("datachannel",function ondatachannel(event){shimDataChannel(event.channel);self.dispatchEvent(event)});peerConnection.addEventListener("iceconnectionstatechange",function oniceconnectionstatechange(){if(self._isClosed){return}self.dispatchEvent.apply(self,arguments)});peerConnection.addEventListener("signalingstatechange",function onsignalingstatechange(){if(self._isClosed){return}if(peerConnection.signalingState==="stable"){self._appliedTracksToSSRCs=new Map(self._tracksToSSRCs)}if(!self._pendingLocalOffer&&!self._pendingRemoteOffer){self.dispatchEvent.apply(self,arguments)}});peerConnection.addEventListener("track",function ontrack(event){self._pendingRemoteOffer=null;self.dispatchEvent(event)});util.proxyProperties(RTCPeerConnection.prototype,this,peerConnection)}inherits(SafariRTCPeerConnection,EventTarget);SafariRTCPeerConnection.prototype.addIceCandidate=function addIceCandidate(candidate){var self=this;if(this.signalingState==="have-remote-offer"){return this._signalingStateLatch.when("low").then(function signalingStatesResolved(){return self._peerConnection.addIceCandidate(candidate)})}return this._peerConnection.addIceCandidate(candidate)};SafariRTCPeerConnection.prototype.createOffer=function createOffer(options){options=Object.assign({},options);var self=this;if(options.offerToReceiveVideo&&!this._audioTransceiver&&!(isUnifiedPlan&&hasReceiversForTracksOfKind(this,"audio"))){delete options.offerToReceiveAudio;try{this._audioTransceiver=isUnifiedPlan?this.addTransceiver("audio",{direction:"recvonly"}):this.addTransceiver("audio")}catch(e){return Promise.reject(e)}}if(options.offerToReceiveVideo&&!this._videoTransceiver&&!(isUnifiedPlan&&hasReceiversForTracksOfKind(this,"video"))){delete options.offerToReceiveVideo;try{this._videoTransceiver=isUnifiedPlan?this.addTransceiver("video",{direction:"recvonly"}):this.addTransceiver("video")}catch(e){return Promise.reject(e)}}return this._peerConnection.createOffer(options).then(function(offer){self._rolledBackTracksToSSRCs.clear();return new RTCSessionDescription({type:offer.type,sdp:updateTrackIdsToSSRCs(self._tracksToSSRCs,offer.sdp)})})};SafariRTCPeerConnection.prototype.createAnswer=function createAnswer(options){var self=this;if(this._pendingRemoteOffer){return this._peerConnection.setRemoteDescription(this._pendingRemoteOffer).then(function setRemoteDescriptionSucceeded(){self._signalingStateLatch.lower();return self._peerConnection.createAnswer()}).then(function createAnswerSucceeded(answer){self._pendingRemoteOffer=null;self._rolledBackTracksToSSRCs.clear();return isUnifiedPlan?new RTCSessionDescription({type:answer.type,sdp:updateTrackIdsToSSRCs(self._tracksToSSRCs,answer.sdp)}):answer},function setRemoteDescriptionOrCreateAnswerFailed(error){self._pendingRemoteOffer=null;throw error})}return this._peerConnection.createAnswer(options).then(function createAnswerSucceeded(answer){self._rolledBackTracksToSSRCs.clear();return isUnifiedPlan?new RTCSessionDescription({type:answer.type,sdp:updateTrackIdsToSSRCs(self._tracksToSSRCs,answer.sdp)}):answer})};SafariRTCPeerConnection.prototype.createDataChannel=function createDataChannel(label,dataChannelDict){var dataChannel=this._peerConnection.createDataChannel(label,dataChannelDict);shimDataChannel(dataChannel);return dataChannel};SafariRTCPeerConnection.prototype.removeTrack=function removeTrack(sender){sender.replaceTrack(null);this._peerConnection.removeTrack(sender)};SafariRTCPeerConnection.prototype.setLocalDescription=function setLocalDescription(description){if(this._rolledBackTracksToSSRCs.size>0){this._tracksToSSRCs=new Map(this._rolledBackTracksToSSRCs);this._rolledBackTracksToSSRCs.clear()}return setDescription(this,true,description)};SafariRTCPeerConnection.prototype.setRemoteDescription=function setRemoteDescription(description){this._rolledBackTracksToSSRCs.clear();return setDescription(this,false,description)};SafariRTCPeerConnection.prototype.close=function close(){if(this._isClosed){return}this._isClosed=true;this._peerConnection.close();var self=this;setTimeout(function(){self.dispatchEvent(new Event("iceconnectionstatechange"));self.dispatchEvent(new Event("signalingstatechange"))})};util.delegateMethods(RTCPeerConnection.prototype,SafariRTCPeerConnection.prototype,"_peerConnection");function setDescription(peerConnection,local,description){function setPendingLocalOffer(offer){if(local){peerConnection._pendingLocalOffer=offer}else{peerConnection._pendingRemoteOffer=offer}}function clearPendingLocalOffer(){if(local){peerConnection._pendingLocalOffer=null}else{peerConnection._pendingRemoteOffer=null}}var pendingLocalOffer=local?peerConnection._pendingLocalOffer:peerConnection._pendingRemoteOffer;var pendingRemoteOffer=local?peerConnection._pendingRemoteOffer:peerConnection._pendingLocalOffer;var intermediateState=local?"have-local-offer":"have-remote-offer";var setLocalDescription=local?"setLocalDescription":"setRemoteDescription";if(!local&&pendingRemoteOffer&&description.type==="answer"){return setRemoteAnswer(peerConnection,description)}else if(description.type==="offer"){if(peerConnection.signalingState!==intermediateState&&peerConnection.signalingState!=="stable"){return Promise.reject(new Error("Cannot set "+(local?"local":"remote")+" offer in state "+peerConnection.signalingState))}if(!pendingLocalOffer&&peerConnection._signalingStateLatch.state==="low"){peerConnection._signalingStateLatch.raise()}var previousSignalingState=peerConnection.signalingState;setPendingLocalOffer(description);if(peerConnection.signalingState!==previousSignalingState){return Promise.resolve().then(function dispatchSignalingStateChangeEvent(){peerConnection.dispatchEvent(new Event("signalingstatechange"))})}return Promise.resolve()}else if(description.type==="rollback"){if(peerConnection.signalingState!==intermediateState){return Promise.reject(new Error("Cannot rollback "+(local?"local":"remote")+" description in "+peerConnection.signalingState))}clearPendingLocalOffer();peerConnection._rolledBackTracksToSSRCs=new Map(peerConnection._tracksToSSRCs);peerConnection._tracksToSSRCs=new Map(peerConnection._appliedTracksToSSRCs);return Promise.resolve().then(function dispatchSignalingStateChangeEvent(){peerConnection.dispatchEvent(new Event("signalingstatechange"))})}return peerConnection._peerConnection[setLocalDescription](description)}function setRemoteAnswer(peerConnection,answer){var pendingLocalOffer=peerConnection._pendingLocalOffer;return peerConnection._peerConnection.setLocalDescription(pendingLocalOffer).then(function setLocalOfferSucceeded(){peerConnection._pendingLocalOffer=null;return peerConnection.setRemoteDescription(answer)}).then(function setRemoteAnswerSucceeded(){peerConnection._signalingStateLatch.lower()})}function hasReceiversForTracksOfKind(peerConnection,kind){return!!peerConnection.getTransceivers().find(function(transceiver){return transceiver.receiver&&transceiver.receiver.track&&transceiver.receiver.track.kind===kind})}function shimDataChannel(dataChannel){return Object.defineProperties(dataChannel,{maxPacketLifeTime:{value:dataChannel.maxPacketLifeTime===65535?null:dataChannel.maxPacketLifeTime},maxRetransmits:{value:dataChannel.maxRetransmits===65535?null:dataChannel.maxRetransmits}})}module.exports=SafariRTCPeerConnection},{"../../vendor/inherits":150,"../util":170,"../util/eventtarget":169,"../util/latch":171,"../util/sdp":172}],165:[function(require,module,exports){"use strict";function RTCRtpSenderShim(track){Object.defineProperties(this,{track:{enumerable:true,value:track,writable:true}})}module.exports=RTCRtpSenderShim},{}],166:[function(require,module,exports){"use strict";function ChromeRTCSessionDescription(descriptionInitDict){if(!(this instanceof ChromeRTCSessionDescription)){return new ChromeRTCSessionDescription(descriptionInitDict)}var description=descriptionInitDict&&descriptionInitDict.type==="rollback"?null:new RTCSessionDescription(descriptionInitDict);Object.defineProperties(this,{_description:{get:function(){return description}},sdp:{enumerable:true,value:description?description.sdp:descriptionInitDict.sdp},type:{enumerable:true,value:description?description.type:descriptionInitDict.type}})}module.exports=ChromeRTCSessionDescription},{}],167:[function(require,module,exports){"use strict";module.exports=RTCSessionDescription},{}],168:[function(require,module,exports){"use strict";if(typeof RTCSessionDescription==="function"){var guessBrowser=require("../util").guessBrowser;switch(guessBrowser()){case"chrome":module.exports=require("./chrome");break;case"firefox":module.exports=require("./firefox");break;default:module.exports=RTCSessionDescription;break}}else{module.exports=function RTCSessionDescription(){throw new Error("RTCSessionDescription is not supported")}}},{"../util":170,"./chrome":166,"./firefox":167}],169:[function(require,module,exports){"use strict";var EventEmitter=require("events").EventEmitter;function EventTarget(){Object.defineProperties(this,{_eventEmitter:{value:new EventEmitter}})}EventTarget.prototype.dispatchEvent=function dispatchEvent(event){return this._eventEmitter.emit(event.type,event)};EventTarget.prototype.addEventListener=function addEventListener(){return this._eventEmitter.addListener.apply(this._eventEmitter,arguments)};EventTarget.prototype.removeEventListener=function removeEventListener(){return this._eventEmitter.removeListener.apply(this._eventEmitter,arguments)};module.exports=EventTarget},{events:173}],170:[function(require,module,exports){"use strict";function defer(){var deferred={};deferred.promise=new Promise(function(resolve,reject){deferred.resolve=resolve;deferred.reject=reject});return deferred}function delegateMethod(source,wrapper,target,methodName){if(methodName in wrapper){return}else if(methodName.match(/^on[a-z]+$/)){return}var isProperty=false;try{var propDesc=Object.getOwnPropertyDescriptor(source,methodName);isProperty=propDesc&&!!propDesc.get}catch(error){}if(isProperty){return}var type;try{type=typeof source[methodName]}catch(error){}if(type!=="function"){return}wrapper[methodName]=function(){return this[target][methodName].apply(this[target],arguments)}}function delegateMethods(source,wrapper,target){for(var methodName in source){delegateMethod(source,wrapper,target,methodName)}}function difference(list1,list2){list1=Array.isArray(list1)?new Set(list1):new Set(list1.values());list2=Array.isArray(list2)?new Set(list2):new Set(list2.values());var difference=new Set;list1.forEach(function(item){if(!list2.has(item)){difference.add(item)}});return difference}function flatMap(list,mapFn){var listArray=list instanceof Map||list instanceof Set?Array.from(list.values()):list;return listArray.reduce(function(flattened,item){var mapped=mapFn(item);return flattened.concat(mapped)},[])}function getUserAgent(){return typeof navigator!=="undefined"&&typeof navigator.userAgent==="string"?navigator.userAgent:null}function guessBrowser(userAgent){if(typeof userAgent==="undefined"){userAgent=getUserAgent()}if(/Chrome|CriOS/.test(userAgent)){return"chrome"}if(/Firefox|FxiOS/.test(userAgent)){return"firefox"}if(/Safari|iPhone|iPad|iPod/.test(userAgent)){return"safari"}return null}function guessBrowserVersion(userAgent){if(typeof userAgent==="undefined"){userAgent=getUserAgent()}var prefix={chrome:"Chrome|CriOS",firefox:"Firefox|FxiOS",safari:"Version"}[guessBrowser(userAgent)];if(!prefix){return null}var regex=new RegExp("("+prefix+")/([^\\s]+)");var match=(userAgent.match(regex)||[])[2];if(!match){return null}var versions=match.split(".").map(Number);return{major:isNaN(versions[0])?null:versions[0],minor:isNaN(versions[1])?null:versions[1]}}function isIOSChrome(userAgent){if(typeof userAgent==="undefined"){userAgent=getUserAgent()}return/Mobi/.test(userAgent)&&guessBrowser()==="chrome"&&/iPad|iPhone|iPod/.test(userAgent)}function interceptEvent(target,type){var currentListener=null;Object.defineProperty(target,"on"+type,{get:function(){return currentListener},set:function(newListener){if(currentListener){this.removeEventListener(type,currentListener)}if(typeof newListener==="function"){currentListener=newListener;this.addEventListener(type,currentListener)}else{currentListener=null}}})}function legacyPromise(promise,onSuccess,onFailure){if(onSuccess){return promise.then(function(result){onSuccess(result)},function(error){onFailure(error)})}return promise}function makeUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){var r=Math.random()*16|0;var v=c==="x"?r:r&3|8;return v.toString(16)})}function proxyProperties(source,wrapper,target){Object.getOwnPropertyNames(source).forEach(function(propertyName){proxyProperty(source,wrapper,target,propertyName)})}function proxyProperty(source,wrapper,target,propertyName){if(propertyName in wrapper){return}else if(propertyName.match(/^on[a-z]+$/)){Object.defineProperty(wrapper,propertyName,{value:null,writable:true});target.addEventListener(propertyName.slice(2),function(){wrapper.dispatchEvent.apply(wrapper,arguments)});return}Object.defineProperty(wrapper,propertyName,{enumerable:true,get:function(){return target[propertyName]}})}function support(){return typeof navigator==="object"&&typeof navigator.mediaDevices==="object"&&typeof navigator.mediaDevices.getUserMedia==="function"&&typeof RTCPeerConnection==="function"}exports.defer=defer;exports.delegateMethods=delegateMethods;exports.difference=difference;exports.flatMap=flatMap;exports.guessBrowser=guessBrowser;exports.guessBrowserVersion=guessBrowserVersion;exports.isIOSChrome=isIOSChrome;exports.interceptEvent=interceptEvent;exports.legacyPromise=legacyPromise;exports.makeUUID=makeUUID;exports.proxyProperties=proxyProperties;exports.support=support},{}],171:[function(require,module,exports){"use strict";var defer=require("./").defer;var states={high:new Set(["low"]),low:new Set(["high"])};function Latch(initialState){if(!(this instanceof Latch)){return new Latch(initialState)}var state=initialState||"low";Object.defineProperties(this,{_state:{set:function(_state){if(state!==_state){state=_state;var whenDeferreds=this._whenDeferreds.get(state);whenDeferreds.forEach(function(deferred){deferred.resolve(this)},this);whenDeferreds.clear()}},get:function(){return state}},_whenDeferreds:{value:new Map([["high",new Set],["low",new Set]])},state:{enumerable:true,get:function(){return this._state}}})}Latch.prototype.lower=function lower(){return this.transition("low")};Latch.prototype.raise=function raise(){return this.transition("high")};Latch.prototype.transition=function transition(newState){if(!states[this.state].has(newState)){throw createUnreachableStateError(this.state,newState)}this._state=newState;return this};Latch.prototype.when=function when(state){if(this.state===state){return Promise.resolve(this)}if(!states[this.state].has(state)){return Promise.reject(createUnreachableStateError(this.state,state))}var deferred=defer();this._whenDeferreds.get(state).add(deferred);return deferred.promise};function createUnreachableStateError(from,to){return new Error('Cannot transition from "'+from+'" to "'+to+'"')}module.exports=Latch},{"./":170}],172:[function(require,module,exports){"use strict";var flatMap=require("./").flatMap;var guessBrowser=require("./").guessBrowser;var isSdpSemanticsSupported=null;function checkIfSdpSemanticsIsSupported(){if(typeof isSdpSemanticsSupported==="boolean"){return isSdpSemanticsSupported}if(typeof RTCPeerConnection==="undefined"){isSdpSemanticsSupported=false;return isSdpSemanticsSupported}try{new RTCPeerConnection({sdpSemantics:"foo"});isSdpSemanticsSupported=false}catch(e){isSdpSemanticsSupported=true}return isSdpSemanticsSupported}var chromeSdpFormat=null;function clearChromeCachedSdpFormat(){chromeSdpFormat=null}function getChromeDefaultSdpFormat(){if(!chromeSdpFormat){if(typeof RTCPeerConnection!=="undefined"&&"addTransceiver"in RTCPeerConnection.prototype){var pc=new RTCPeerConnection;try{pc.addTransceiver("audio");chromeSdpFormat="unified"}catch(e){chromeSdpFormat="planb"}pc.close()}else{chromeSdpFormat="planb"}}return chromeSdpFormat}function getChromeSdpFormat(sdpSemantics){if(!sdpSemantics||!checkIfSdpSemanticsIsSupported()){return getChromeDefaultSdpFormat()}return{"plan-b":"planb","unified-plan":"unified"}[sdpSemantics]}function getSafariSdpFormat(){return typeof RTCRtpTransceiver!=="undefined"&&"currentDirection"in RTCRtpTransceiver.prototype?"unified":"planb"}function getSdpFormat(sdpSemantics){return{chrome:getChromeSdpFormat(sdpSemantics),firefox:"unified",safari:getSafariSdpFormat()}[guessBrowser()]||null}function getMatches(pattern,lines){var matches=lines.match(new RegExp(pattern,"gm"))||[];return matches.reduce(function(results,line){var match=line.match(new RegExp(pattern));return match?results.add(match[1]):results},new Set)}function getTrackIds(pattern,sdp){return getMatches(pattern,sdp)}function getPlanBTrackIds(sdp){return getTrackIds("^a=ssrc:[0-9]+ +msid:.+ +(.+) *$",sdp)}function getUnifiedPlanTrackIds(sdp){return getTrackIds("^a=msid:.+ +(.+) *$",sdp)}function getPlanBSSRCs(sdp,trackId){var pattern="^a=ssrc:([0-9]+) +msid:[^ ]+ +"+trackId+" *$";return getMatches(pattern,sdp)}function getMediaSections(sdp,kind,direction){kind=kind||".*";direction=direction||".*";return sdp.split("\r\nm=").slice(1).map(function(mediaSection){return"m="+mediaSection}).filter(function(mediaSection){var kindPattern=new RegExp("m="+kind,"gm");var directionPattern=new RegExp("a="+direction,"gm");return kindPattern.test(mediaSection)&&directionPattern.test(mediaSection)})}function getMediaSectionSSRCs(mediaSection){return Array.from(getMatches("^a=ssrc:([0-9]+) +.*$",mediaSection))}function getUnifiedPlanSSRCs(sdp,trackId){var mediaSections=getMediaSections(sdp);var msidAttrRegExp=new RegExp("^a=msid:[^ ]+ +"+trackId+" *$","gm");var matchingMediaSections=mediaSections.filter(function(mediaSection){return mediaSection.match(msidAttrRegExp)});return new Set(flatMap(matchingMediaSections,getMediaSectionSSRCs))}function getTrackIdsToSSRCs(getTrackIds,getSSRCs,sdp){return new Map(Array.from(getTrackIds(sdp)).map(function(trackId){return[trackId,getSSRCs(sdp,trackId)]}))}function getPlanBTrackIdsToSSRCs(sdp){return getTrackIdsToSSRCs(getPlanBTrackIds,getPlanBSSRCs,sdp)}function getUnifiedPlanTrackIdsToSSRCs(sdp){return getTrackIdsToSSRCs(getUnifiedPlanTrackIds,getUnifiedPlanSSRCs,sdp)}function updateTrackIdsToSSRCs(getTrackIdsToSSRCs,trackIdsToSSRCs,sdp){var newTrackIdsToSSRCs=getTrackIdsToSSRCs(sdp);var newSSRCsToOldSSRCs=new Map;newTrackIdsToSSRCs.forEach(function(ssrcs,trackId){if(!trackIdsToSSRCs.has(trackId)){trackIdsToSSRCs.set(trackId,ssrcs);return}var oldSSRCs=Array.from(trackIdsToSSRCs.get(trackId));var newSSRCs=Array.from(ssrcs);oldSSRCs.forEach(function(oldSSRC,i){var newSSRC=newSSRCs[i];newSSRCsToOldSSRCs.set(newSSRC,oldSSRC);var pattern="^a=ssrc:"+newSSRC+" (.*)$";var replacement="a=ssrc:"+oldSSRC+" $1";sdp=sdp.replace(new RegExp(pattern,"gm"),replacement)})});var pattern="^(a=ssrc-group:[^ ]+ +)(.*)$";var matches=sdp.match(new RegExp(pattern,"gm"))||[];matches.forEach(function(line){var match=line.match(new RegExp(pattern));if(!match){return}var prefix=match[1];var newSSRCs=match[2];var oldSSRCs=newSSRCs.split(" ").map(function(newSSRC){var oldSSRC=newSSRCsToOldSSRCs.get(newSSRC);return oldSSRC?oldSSRC:newSSRC}).join(" ");sdp=sdp.replace(match[0],prefix+oldSSRCs)});return sdp}function updatePlanBTrackIdsToSSRCs(trackIdsToSSRCs,sdp){return updateTrackIdsToSSRCs(getPlanBTrackIdsToSSRCs,trackIdsToSSRCs,sdp)}function updateUnifiedPlanTrackIdsToSSRCs(trackIdsToSSRCs,sdp){return updateTrackIdsToSSRCs(getUnifiedPlanTrackIdsToSSRCs,trackIdsToSSRCs,sdp)}exports.clearChromeCachedSdpFormat=clearChromeCachedSdpFormat;exports.getSdpFormat=getSdpFormat;exports.getMediaSections=getMediaSections;exports.getPlanBTrackIds=getPlanBTrackIds;exports.getUnifiedPlanTrackIds=getUnifiedPlanTrackIds;exports.getPlanBSSRCs=getPlanBSSRCs;exports.getUnifiedPlanSSRCs=getUnifiedPlanSSRCs;exports.updatePlanBTrackIdsToSSRCs=updatePlanBTrackIdsToSSRCs;exports.updateUnifiedPlanTrackIdsToSSRCs=updateUnifiedPlanTrackIdsToSSRCs},{"./":170}],173:[function(require,module,exports){"use strict";var R=typeof Reflect==="object"?Reflect:null;var ReflectApply=R&&typeof R.apply==="function"?R.apply:function ReflectApply(target,receiver,args){return Function.prototype.apply.call(target,receiver,args)};var ReflectOwnKeys;if(R&&typeof R.ownKeys==="function"){ReflectOwnKeys=R.ownKeys}else if(Object.getOwnPropertySymbols){ReflectOwnKeys=function ReflectOwnKeys(target){return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))}}else{ReflectOwnKeys=function ReflectOwnKeys(target){return Object.getOwnPropertyNames(target)}}function ProcessEmitWarning(warning){if(console&&console.warn)console.warn(warning)}var NumberIsNaN=Number.isNaN||function NumberIsNaN(value){return value!==value};function EventEmitter(){EventEmitter.init.call(this)}module.exports=EventEmitter;module.exports.once=once;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._eventsCount=0;EventEmitter.prototype._maxListeners=undefined;var defaultMaxListeners=10;function checkListener(listener){if(typeof listener!=="function"){throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof listener)}}Object.defineProperty(EventEmitter,"defaultMaxListeners",{enumerable:true,get:function(){return defaultMaxListeners},set:function(arg){if(typeof arg!=="number"||arg<0||NumberIsNaN(arg)){throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+arg+".")}defaultMaxListeners=arg}});EventEmitter.init=function(){if(this._events===undefined||this._events===Object.getPrototypeOf(this)._events){this._events=Object.create(null);this._eventsCount=0}this._maxListeners=this._maxListeners||undefined};EventEmitter.prototype.setMaxListeners=function setMaxListeners(n){if(typeof n!=="number"||n<0||NumberIsNaN(n)){throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+n+".")}this._maxListeners=n;return this};function _getMaxListeners(that){if(that._maxListeners===undefined)return EventEmitter.defaultMaxListeners;return that._maxListeners}EventEmitter.prototype.getMaxListeners=function getMaxListeners(){return _getMaxListeners(this)};EventEmitter.prototype.emit=function emit(type){var args=[];for(var i=1;i<arguments.length;i++)args.push(arguments[i]);var doError=type==="error";var events=this._events;if(events!==undefined)doError=doError&&events.error===undefined;else if(!doError)return false;if(doError){var er;if(args.length>0)er=args[0];if(er instanceof Error){throw er}var err=new Error("Unhandled error."+(er?" ("+er.message+")":""));err.context=er;throw err}var handler=events[type];if(handler===undefined)return false;if(typeof handler==="function"){ReflectApply(handler,this,args)}else{var len=handler.length;var listeners=arrayClone(handler,len);for(var i=0;i<len;++i)ReflectApply(listeners[i],this,args)}return true};function _addListener(target,type,listener,prepend){var m;var events;var existing;checkListener(listener);events=target._events;if(events===undefined){events=target._events=Object.create(null);target._eventsCount=0}else{if(events.newListener!==undefined){target.emit("newListener",type,listener.listener?listener.listener:listener);events=target._events}existing=events[type]}if(existing===undefined){existing=events[type]=listener;++target._eventsCount}else{if(typeof existing==="function"){existing=events[type]=prepend?[listener,existing]:[existing,listener]}else if(prepend){existing.unshift(listener)}else{existing.push(listener)}m=_getMaxListeners(target);if(m>0&&existing.length>m&&!existing.warned){existing.warned=true;var w=new Error("Possible EventEmitter memory leak detected. "+existing.length+" "+String(type)+" listeners "+"added. Use emitter.setMaxListeners() to "+"increase limit");w.name="MaxListenersExceededWarning";w.emitter=target;w.type=type;w.count=existing.length;ProcessEmitWarning(w)}}return target}EventEmitter.prototype.addListener=function addListener(type,listener){return _addListener(this,type,listener,false)};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.prependListener=function prependListener(type,listener){return _addListener(this,type,listener,true)};function onceWrapper(){if(!this.fired){this.target.removeListener(this.type,this.wrapFn);this.fired=true;if(arguments.length===0)return this.listener.call(this.target);return this.listener.apply(this.target,arguments)}}function _onceWrap(target,type,listener){var state={fired:false,wrapFn:undefined,target:target,type:type,listener:listener};var wrapped=onceWrapper.bind(state);wrapped.listener=listener;state.wrapFn=wrapped;return wrapped}EventEmitter.prototype.once=function once(type,listener){checkListener(listener);this.on(type,_onceWrap(this,type,listener));return this};EventEmitter.prototype.prependOnceListener=function prependOnceListener(type,listener){checkListener(listener);this.prependListener(type,_onceWrap(this,type,listener));return this}
57
- ;EventEmitter.prototype.removeListener=function removeListener(type,listener){var list,events,position,i,originalListener;checkListener(listener);events=this._events;if(events===undefined)return this;list=events[type];if(list===undefined)return this;if(list===listener||list.listener===listener){if(--this._eventsCount===0)this._events=Object.create(null);else{delete events[type];if(events.removeListener)this.emit("removeListener",type,list.listener||listener)}}else if(typeof list!=="function"){position=-1;for(i=list.length-1;i>=0;i--){if(list[i]===listener||list[i].listener===listener){originalListener=list[i].listener;position=i;break}}if(position<0)return this;if(position===0)list.shift();else{spliceOne(list,position)}if(list.length===1)events[type]=list[0];if(events.removeListener!==undefined)this.emit("removeListener",type,originalListener||listener)}return this};EventEmitter.prototype.off=EventEmitter.prototype.removeListener;EventEmitter.prototype.removeAllListeners=function removeAllListeners(type){var listeners,events,i;events=this._events;if(events===undefined)return this;if(events.removeListener===undefined){if(arguments.length===0){this._events=Object.create(null);this._eventsCount=0}else if(events[type]!==undefined){if(--this._eventsCount===0)this._events=Object.create(null);else delete events[type]}return this}if(arguments.length===0){var keys=Object.keys(events);var key;for(i=0;i<keys.length;++i){key=keys[i];if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events=Object.create(null);this._eventsCount=0;return this}listeners=events[type];if(typeof listeners==="function"){this.removeListener(type,listeners)}else if(listeners!==undefined){for(i=listeners.length-1;i>=0;i--){this.removeListener(type,listeners[i])}}return this};function _listeners(target,type,unwrap){var events=target._events;if(events===undefined)return[];var evlistener=events[type];if(evlistener===undefined)return[];if(typeof evlistener==="function")return unwrap?[evlistener.listener||evlistener]:[evlistener];return unwrap?unwrapListeners(evlistener):arrayClone(evlistener,evlistener.length)}EventEmitter.prototype.listeners=function listeners(type){return _listeners(this,type,true)};EventEmitter.prototype.rawListeners=function rawListeners(type){return _listeners(this,type,false)};EventEmitter.listenerCount=function(emitter,type){if(typeof emitter.listenerCount==="function"){return emitter.listenerCount(type)}else{return listenerCount.call(emitter,type)}};EventEmitter.prototype.listenerCount=listenerCount;function listenerCount(type){var events=this._events;if(events!==undefined){var evlistener=events[type];if(typeof evlistener==="function"){return 1}else if(evlistener!==undefined){return evlistener.length}}return 0}EventEmitter.prototype.eventNames=function eventNames(){return this._eventsCount>0?ReflectOwnKeys(this._events):[]};function arrayClone(arr,n){var copy=new Array(n);for(var i=0;i<n;++i)copy[i]=arr[i];return copy}function spliceOne(list,index){for(;index+1<list.length;index++)list[index]=list[index+1];list.pop()}function unwrapListeners(arr){var ret=new Array(arr.length);for(var i=0;i<ret.length;++i){ret[i]=arr[i].listener||arr[i]}return ret}function once(emitter,name){return new Promise(function(resolve,reject){function errorListener(err){emitter.removeListener(name,resolver);reject(err)}function resolver(){if(typeof emitter.removeListener==="function"){emitter.removeListener("error",errorListener)}resolve([].slice.call(arguments))}eventTargetAgnosticAddListener(emitter,name,resolver,{once:true});if(name!=="error"){addErrorHandlerIfEventEmitter(emitter,errorListener,{once:true})}})}function addErrorHandlerIfEventEmitter(emitter,handler,flags){if(typeof emitter.on==="function"){eventTargetAgnosticAddListener(emitter,"error",handler,flags)}}function eventTargetAgnosticAddListener(emitter,name,listener,flags){if(typeof emitter.on==="function"){if(flags.once){emitter.once(name,listener)}else{emitter.on(name,listener)}}else if(typeof emitter.addEventListener==="function"){emitter.addEventListener(name,function wrapListener(arg){if(flags.once){emitter.removeEventListener(name,wrapListener)}listener(arg)})}else{throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof emitter)}}},{}],174:[function(require,module,exports){module.exports={name:"twilio-video",title:"Twilio Video",description:"Twilio Video JavaScript Library",version:"2.24.2",homepage:"https://twilio.com",author:"Mark Andrus Roberts <mroberts@twilio.com>",contributors:["Ryan Rowland <rrowland@twilio.com>","Manjesh Malavalli <mmalavalli@twilio.com>","Makarand Patwardhan <mpatwardhan@twilio.com>"],keywords:["twilio","webrtc","library","javascript","video","rooms"],repository:{type:"git",url:"https://github.com/twilio/twilio-video.js.git"},devDependencies:{"@babel/core":"^7.14.2","@babel/preset-env":"^7.14.2","@babel/preset-typescript":"^7.13.0","@types/express":"^4.11.0","@types/node":"^8.5.1","@types/selenium-webdriver":"^3.0.8","@types/ws":"^3.2.1","@typescript-eslint/eslint-plugin":"^4.13.0","@typescript-eslint/parser":"^4.0.0","babel-cli":"^6.26.0","babel-preset-es2015":"^6.24.1",browserify:"^17.0.0",cheerio:"^0.22.0",cors:"^2.8.5",electron:"^17.2.0",envify:"^4.0.0",eslint:"^6.2.1","eslint-config-standard":"^14.0.0","eslint-plugin-import":"^2.18.2","eslint-plugin-node":"^9.1.0","eslint-plugin-promise":"^4.2.1","eslint-plugin-standard":"^4.0.1",express:"^4.16.2",glob:"^7.1.7","ink-docstrap":"^1.3.2",inquirer:"^7.0.0","is-docker":"^2.0.0",jsdoc:"^3.5.5","jsdoc-babel":"^0.5.0","json-loader":"^0.5.7",karma:"^5.0.2","karma-browserify":"^8.0.0","karma-chrome-launcher":"^2.0.0","karma-edgium-launcher":"^4.0.0-0","karma-electron":"^6.1.0","karma-firefox-launcher":"^1.3.0","karma-htmlfile-reporter":"^0.3.8","karma-junit-reporter":"^1.2.0","karma-mocha":"^1.3.0","karma-safari-launcher":"^1.0.0","karma-spec-reporter":"0.0.32","karma-typescript":"^5.5.1","karma-typescript-es6-transform":"^5.5.1",mocha:"^3.2.0","mock-require":"^3.0.3",ncp:"^2.0.0","node-http-server":"^8.1.2","npm-run-all":"^4.0.2",nyc:"^15.1.0",requirejs:"^2.3.3",rimraf:"^2.6.1","simple-git":"^1.126.0",sinon:"^4.0.1","ts-node":"4.0.1",tslint:"5.8.0",twilio:"^3.49.0","twilio-release-tool":"^1.0.2",typescript:"4.2.2","uglify-js":"^2.8.22","vinyl-fs":"^2.4.4","vinyl-source-stream":"^1.1.0",watchify:"^3.11.1","webrtc-adapter":"^7.7.1"},engines:{node:">=0.12"},license:"BSD-3-Clause",main:"./es5/index.js",types:"./tsdef/index.d.ts",scripts:{"lint:js":"eslint ./lib ./test/*.js ./docker/**/*.js ./test/framework/*.js ./test/lib/*.js ./test/integration/** ./test/unit/** ","lint:ts":"eslint ./tsdef/*.ts ./lib/**/*.ts",lint:"npm-run-all lint:js lint:ts",printVersion:"node --version && npm --version","test:unit":"npm-run-all printVersion build:es5 && nyc --report-dir=./coverage --include=lib/**/* --reporter=html --reporter=lcov --reporter=text mocha -r ts-node/register ./test/unit/*","test:unit:quick":"nyc --report-dir=./coverage --include=lib/**/* --reporter=html --reporter=lcov mocha -r ts-node/register","test:serversiderender":"mocha ./test/serversiderender/index.js","test:integration:adapter":"node ./scripts/karma.js karma/integration.adapter.conf.js","test:integration":"npm run build:es5 && node ./scripts/karma.js karma/integration.conf.js","test:umd:install":"npm install puppeteer@5.5.0","test:umd":"mocha ./test/umd/index.js","test:crossbrowser:build:clean":"rimraf ./test/crossbrowser/lib ./test/crossbrowser/src/browser/index.js","test:crossbrowser:build:lint":"cd ./test/crossbrowser && tslint --project tsconfig.json","test:crossbrowser:build:tsc":"cd ./test/crossbrowser && tsc","test:crossbrowser:build:browser":"cd ./test/crossbrowser && browserify lib/crossbrowser/src/browser/index.js > src/browser/index.js","test:crossbrowser:build":"npm-run-all test:crossbrowser:build:*","test:crossbrowser:test":"cd ./test/crossbrowser && mocha --compilers ts:ts-node/register test/integration/spec/**/*.ts","test:crossbrowser":"npm-run-all test:crossbrowser:*","test:sdkdriver:build:clean":"rimraf ./test/lib/sdkdriver/lib ./test/lib/sdkdriver/test/integration/browser/index.js","test:sdkdriver:build:lint":"cd ./test/lib/sdkdriver && tslint --project tsconfig.json","test:sdkdriver:build:tsc":"cd ./test/lib/sdkdriver && tsc --rootDir src","test:sdkdriver:build":"npm-run-all test:sdkdriver:build:*","test:sdkdriver:test:unit":"cd ./test/lib/sdkdriver && mocha --compilers ts:ts-node/register test/unit/spec/**/*.ts","test:sdkdriver:test:integration:browser":"cd ./test/lib/sdkdriver/test/integration && browserify browser/browser.js > browser/index.js","test:sdkdriver:test:integration:run":"cd ./test/lib/sdkdriver && mocha --compilers ts:ts-node/register test/integration/spec/**/*.ts","test:sdkdriver:test:integration":"npm-run-all test:sdkdriver:test:integration:*","test:sdkdriver:test":"npm-run-all test:sdkdriver:test:*","test:sdkdriver":"npm-run-all test:sdkdriver:*","test:framework:angular:install":"cd ./test/framework/twilio-video-angular && rimraf ./node_modules package-lock.json && npm install","test:framework:angular:run":"mocha ./test/framework/twilio-video-angular.js","test:framework:angular":"npm-run-all test:framework:angular:*","test:framework:no-framework:run":"mocha ./test/framework/twilio-video-no-framework.js","test:framework:no-framework":"npm-run-all test:framework:no-framework:*","test:framework:react:install":"cd ./test/framework/twilio-video-react && rimraf ./node_modules package-lock.json && npm install","test:framework:react:test":"node ./scripts/framework.js twilio-video-react","test:framework:react:build":"cd ./test/framework/twilio-video-react && npm run build","test:framework:react:run":"mocha ./test/framework/twilio-video-react.js","test:framework:react":"npm-run-all test:framework:react:*","test:framework:install":"npm install chromedriver && npm install selenium-webdriver && npm install geckodriver && npm install puppeteer","test:framework":"npm-run-all test:framework:install test:framework:no-framework test:framework:react",test:"npm-run-all test:unit test:integration","build:es5":"rimraf ./es5 && mkdir -p es5 && tsc tsdef/twilio-video-tests.ts --noEmit --lib es2018,dom && tsc","build:js":"node ./scripts/build.js ./src/twilio-video.js ./LICENSE.md ./dist/twilio-video.js","build:min.js":'uglifyjs ./dist/twilio-video.js -o ./dist/twilio-video.min.js --comments "/^! twilio-video.js/" -b beautify=false,ascii_only=true',build:"npm-run-all clean lint docs test:unit test:integration build:es5 build:js build:min.js test:umd","build:quick":"npm-run-all clean lint docs build:es5 build:js build:min.js",docs:"node ./scripts/docs.js ./dist/docs",watch:"tsc -w",clean:"rimraf ./coverage ./es5 ./dist"},dependencies:{events:"^3.3.0",util:"^0.12.4",ws:"^7.4.6",xmlhttprequest:"^1.8.0"},browser:{ws:"./src/ws.js",xmlhttprequest:"./src/xmlhttprequest.js"}}},{}],175:[function(require,module,exports){module.exports=WebSocket},{}]},{},[11]);var Video=bundle(11);if(typeof define==="function"&&define.amd){define([],function(){return Video})}else{var Twilio=root.Twilio=root.Twilio||{};Twilio.Video=Twilio.Video||Video}})(typeof window!=="undefined"?window:typeof global!=="undefined"?global:this);
55
+ report[keyInfo.key]=typeof activeRemoteCandidateStats[keyInfo.key]===keyInfo.type?activeRemoteCandidateStats[keyInfo.key]:null;return report},{}):null;return[{key:"availableIncomingBitrate",type:"number"},{key:"availableOutgoingBitrate",type:"number"},{key:"bytesReceived",type:"number"},{key:"bytesSent",type:"number"},{key:"consentRequestsSent",type:"number"},{key:"currentRoundTripTime",type:"number"},{key:"lastPacketReceivedTimestamp",type:"number"},{key:"lastPacketSentTimestamp",type:"number"},{key:"nominated",type:"boolean"},{key:"priority",type:"number"},{key:"readable",type:"boolean"},{key:"requestsReceived",type:"number"},{key:"requestsSent",type:"number"},{key:"responsesReceived",type:"number"},{key:"responsesSent",type:"number"},{key:"retransmissionsReceived",type:"number"},{key:"retransmissionsSent",type:"number"},{key:"state",type:"string",fixup:function(state){return state==="inprogress"?"in-progress":state}},{key:"totalRoundTripTime",type:"number"},{key:"transportId",type:"string"},{key:"writable",type:"boolean"}].reduce(function(report,keyInfo){report[keyInfo.key]=typeof activeCandidatePairStats[keyInfo.key]===keyInfo.type?keyInfo.fixup?keyInfo.fixup(activeCandidatePairStats[keyInfo.key]):activeCandidatePairStats[keyInfo.key]:null;return report},{localCandidate:standatdizedLocalCandidateStatsReport,remoteCandidate:standardizedRemoteCandidateStatsReport})}function standardizeFirefoxActiveIceCandidatePairStats(stats){var activeCandidatePairStats=Array.from(stats.values()).find(function(stat){return stat.type==="candidate-pair"&&stat.nominated});if(!activeCandidatePairStats){return null}var activeLocalCandidateStats=stats.get(activeCandidatePairStats.localCandidateId);var activeRemoteCandidateStats=stats.get(activeCandidatePairStats.remoteCandidateId);var standardizedCandidateStatsKeys=[{key:"candidateType",type:"string"},{key:"ip",ffKeys:["address","ipAddress"],type:"string"},{key:"port",ffKeys:["portNumber"],type:"number"},{key:"priority",type:"number"},{key:"protocol",ffKeys:["transport"],type:"string"},{key:"url",type:"string"}];var standardizedLocalCandidateStatsKeys=standardizedCandidateStatsKeys.concat([{key:"deleted",type:"boolean"},{key:"relayProtocol",type:"string"}]);var candidateTypes={host:"host",peerreflexive:"prflx",relayed:"relay",serverreflexive:"srflx"};var standatdizedLocalCandidateStatsReport=activeLocalCandidateStats?standardizedLocalCandidateStatsKeys.reduce(function(report,keyInfo){var key=keyInfo.ffKeys&&keyInfo.ffKeys.find(function(key){return key in activeLocalCandidateStats})||keyInfo.key;report[keyInfo.key]=typeof activeLocalCandidateStats[key]===keyInfo.type?key==="candidateType"?candidateTypes[activeLocalCandidateStats[key]]||activeLocalCandidateStats[key]:activeLocalCandidateStats[key]:key==="deleted"?false:null;return report},{}):null;var standardizedRemoteCandidateStatsReport=activeRemoteCandidateStats?standardizedCandidateStatsKeys.reduce(function(report,keyInfo){var key=keyInfo.ffKeys&&keyInfo.ffKeys.find(function(key){return key in activeRemoteCandidateStats})||keyInfo.key;report[keyInfo.key]=typeof activeRemoteCandidateStats[key]===keyInfo.type?key==="candidateType"?candidateTypes[activeRemoteCandidateStats[key]]||activeRemoteCandidateStats[key]:activeRemoteCandidateStats[key]:null;return report},{}):null;return[{key:"availableIncomingBitrate",type:"number"},{key:"availableOutgoingBitrate",type:"number"},{key:"bytesReceived",type:"number"},{key:"bytesSent",type:"number"},{key:"consentRequestsSent",type:"number"},{key:"currentRoundTripTime",type:"number"},{key:"lastPacketReceivedTimestamp",type:"number"},{key:"lastPacketSentTimestamp",type:"number"},{key:"nominated",type:"boolean"},{key:"priority",type:"number"},{key:"readable",type:"boolean"},{key:"requestsReceived",type:"number"},{key:"requestsSent",type:"number"},{key:"responsesReceived",type:"number"},{key:"responsesSent",type:"number"},{key:"retransmissionsReceived",type:"number"},{key:"retransmissionsSent",type:"number"},{key:"state",type:"string"},{key:"totalRoundTripTime",type:"number"},{key:"transportId",type:"string"},{key:"writable",type:"boolean"}].reduce(function(report,keyInfo){report[keyInfo.key]=typeof activeCandidatePairStats[keyInfo.key]===keyInfo.type?activeCandidatePairStats[keyInfo.key]:null;return report},{localCandidate:standatdizedLocalCandidateStatsReport,remoteCandidate:standardizedRemoteCandidateStatsReport})}function getTracks(peerConnection,kind,localOrRemote){var getSendersOrReceivers=localOrRemote==="local"?"getSenders":"getReceivers";if(peerConnection[getSendersOrReceivers]){return peerConnection[getSendersOrReceivers]().map(function(senderOrReceiver){return senderOrReceiver.track}).filter(function(track){return track&&track.kind===kind})}var getStreams=localOrRemote==="local"?"getLocalStreams":"getRemoteStreams";return flatMap(peerConnection[getStreams](),function(stream){var getTracks=kind==="audio"?"getAudioTracks":"getVideoTracks";return stream[getTracks]()})}function getTrackStats(peerConnection,track,options){options=options||{};if(typeof options.testForChrome!=="undefined"||isChrome){return chromeOrSafariGetTrackStats(peerConnection,track)}if(typeof options.testForFirefox!=="undefined"||isFirefox){return firefoxGetTrackStats(peerConnection,track,options.isRemote)}if(typeof options.testForSafari!=="undefined"||isSafari){if(typeof options.testForSafari!=="undefined"||getSdpFormat()==="unified"){return chromeOrSafariGetTrackStats(peerConnection,track)}return Promise.reject(new Error(["getStats() is not supported on this version of Safari","due to this bug: https://bugs.webkit.org/show_bug.cgi?id=192601"].join(" ")))}return Promise.reject(new Error("RTCPeerConnection#getStats() not supported"))}function chromeOrSafariGetTrackStats(peerConnection,track){return new Promise(function(resolve,reject){if(chromeMajorVersion&&chromeMajorVersion<67){peerConnection.getStats(function(response){resolve([standardizeChromeLegacyStats(response,track)])},null,reject);return}peerConnection.getStats(track).then(function(response){resolve(standardizeChromeOrSafariStats(response))},reject)})}function firefoxGetTrackStats(peerConnection,track,isRemote){return new Promise(function(resolve,reject){peerConnection.getStats(track).then(function(response){resolve([standardizeFirefoxStats(response,isRemote)])},reject)})}function standardizeChromeLegacyStats(response,track){var ssrcReport=response.result().find(function(report){return report.type==="ssrc"&&report.stat("googTrackId")===track.id});var standardizedStats={};if(ssrcReport){standardizedStats.timestamp=Math.round(Number(ssrcReport.timestamp));standardizedStats=ssrcReport.names().reduce(function(stats,name){switch(name){case"googCodecName":stats.codecName=ssrcReport.stat(name);break;case"googRtt":stats.roundTripTime=Number(ssrcReport.stat(name));break;case"googJitterReceived":stats.jitter=Number(ssrcReport.stat(name));break;case"googFrameWidthInput":stats.frameWidthInput=Number(ssrcReport.stat(name));break;case"googFrameHeightInput":stats.frameHeightInput=Number(ssrcReport.stat(name));break;case"googFrameWidthSent":stats.frameWidthSent=Number(ssrcReport.stat(name));break;case"googFrameHeightSent":stats.frameHeightSent=Number(ssrcReport.stat(name));break;case"googFrameWidthReceived":stats.frameWidthReceived=Number(ssrcReport.stat(name));break;case"googFrameHeightReceived":stats.frameHeightReceived=Number(ssrcReport.stat(name));break;case"googFrameRateInput":stats.frameRateInput=Number(ssrcReport.stat(name));break;case"googFrameRateSent":stats.frameRateSent=Number(ssrcReport.stat(name));break;case"googFrameRateReceived":stats.frameRateReceived=Number(ssrcReport.stat(name));break;case"ssrc":stats[name]=ssrcReport.stat(name);break;case"bytesReceived":case"bytesSent":case"packetsLost":case"packetsReceived":case"packetsSent":case"audioInputLevel":case"audioOutputLevel":stats[name]=Number(ssrcReport.stat(name));break}return stats},standardizedStats)}return standardizedStats}function standardizeChromeOrSafariStats(response){var inbound=null;var outbound=[];var remoteInbound=null;var remoteOutbound=null;var track=null;var codec=null;var localMedia=null;response.forEach(function(stat){switch(stat.type){case"inbound-rtp":inbound=stat;break;case"outbound-rtp":outbound.push(stat);break;case"media-source":localMedia=stat;break;case"track":track=stat;break;case"codec":codec=stat;break;case"remote-inbound-rtp":remoteInbound=stat;break;case"remote-outbound-rtp":remoteOutbound=stat;break}});var isRemote=track&&track.remoteSource;var mainSources=isRemote?[inbound]:outbound;var stats=[];var remoteSource=isRemote?remoteOutbound:remoteInbound;mainSources.forEach(function(source){var standardizedStats={};var statSources=[source,localMedia,track,codec,remoteSource&&remoteSource.ssrc===source.ssrc?remoteSource:null];function getStatValue(name){var sourceFound=statSources.find(function(statSource){return statSource&&typeof statSource[name]!=="undefined"})||null;return sourceFound?sourceFound[name]:null}var ssrc=getStatValue("ssrc");if(typeof ssrc==="number"){standardizedStats.ssrc=String(ssrc)}var timestamp=getStatValue("timestamp");standardizedStats.timestamp=Math.round(timestamp);var mimeType=getStatValue("mimeType");if(typeof mimeType==="string"){mimeType=mimeType.split("/");standardizedStats.codecName=mimeType[mimeType.length-1]}var roundTripTime=getStatValue("roundTripTime");if(typeof roundTripTime==="number"){standardizedStats.roundTripTime=Math.round(roundTripTime*1e3)}var jitter=getStatValue("jitter");if(typeof jitter==="number"){standardizedStats.jitter=Math.round(jitter*1e3)}var frameWidth=getStatValue("frameWidth");if(typeof frameWidth==="number"){if(isRemote){standardizedStats.frameWidthReceived=frameWidth}else{standardizedStats.frameWidthSent=frameWidth;standardizedStats.frameWidthInput=track.frameWidth}}var frameHeight=getStatValue("frameHeight");if(typeof frameHeight==="number"){if(isRemote){standardizedStats.frameHeightReceived=frameHeight}else{standardizedStats.frameHeightSent=frameHeight;standardizedStats.frameHeightInput=track.frameHeight}}var framesPerSecond=getStatValue("framesPerSecond");if(typeof framesPerSecond==="number"){standardizedStats[isRemote?"frameRateReceived":"frameRateSent"]=framesPerSecond}var bytesReceived=getStatValue("bytesReceived");if(typeof bytesReceived==="number"){standardizedStats.bytesReceived=bytesReceived}var bytesSent=getStatValue("bytesSent");if(typeof bytesSent==="number"){standardizedStats.bytesSent=bytesSent}var packetsLost=getStatValue("packetsLost");if(typeof packetsLost==="number"){standardizedStats.packetsLost=packetsLost}var packetsReceived=getStatValue("packetsReceived");if(typeof packetsReceived==="number"){standardizedStats.packetsReceived=packetsReceived}var packetsSent=getStatValue("packetsSent");if(typeof packetsSent==="number"){standardizedStats.packetsSent=packetsSent}var audioLevel=getStatValue("audioLevel");if(typeof audioLevel==="number"){audioLevel=Math.round(audioLevel*CHROME_LEGACY_MAX_AUDIO_LEVEL);if(isRemote){standardizedStats.audioOutputLevel=audioLevel}else{standardizedStats.audioInputLevel=audioLevel}}var totalPacketSendDalay=getStatValue("totalPacketSendDelay");if(typeof totalPacketSendDalay==="number"){standardizedStats.totalPacketSendDelay=totalPacketSendDalay}var totalEncodeTime=getStatValue("totalEncodeTime");if(typeof totalEncodeTime==="number"){standardizedStats.totalEncodeTime=totalEncodeTime}var framesEncoded=getStatValue("framesEncoded");if(typeof framesEncoded==="number"){standardizedStats.framesEncoded=framesEncoded}var estimatedPlayoutTimestamp=getStatValue("estimatedPlayoutTimestamp");if(typeof estimatedPlayoutTimestamp==="number"){standardizedStats.estimatedPlayoutTimestamp=estimatedPlayoutTimestamp}var totalDecodeTime=getStatValue("totalDecodeTime");if(typeof totalDecodeTime==="number"){standardizedStats.totalDecodeTime=totalDecodeTime}var framesDecoded=getStatValue("framesDecoded");if(typeof framesDecoded==="number"){standardizedStats.framesDecoded=framesDecoded}var jitterBufferDelay=getStatValue("jitterBufferDelay");if(typeof jitterBufferDelay==="number"){standardizedStats.jitterBufferDelay=jitterBufferDelay}var jitterBufferEmittedCount=getStatValue("jitterBufferEmittedCount");if(typeof jitterBufferEmittedCount==="number"){standardizedStats.jitterBufferEmittedCount=jitterBufferEmittedCount}stats.push(standardizedStats)});return stats}function standardizeFirefoxStats(response,isRemote){response=response||new Map;var inbound=null;var outbound=null;response.forEach(function(stat){if(stat.isRemote){return}switch(stat.type){case"inbound-rtp":inbound=stat;outbound=response.get(stat.remoteId);break;case"outbound-rtp":outbound=stat;inbound=response.get(stat.remoteId);break}});var first=isRemote?inbound:outbound;var second=isRemote?outbound:inbound;function getStatValue(name){if(first&&typeof first[name]!=="undefined"){return first[name]}if(second&&typeof second[name]!=="undefined"){return second[name]}return null}var standardizedStats={};var timestamp=getStatValue("timestamp");standardizedStats.timestamp=Math.round(timestamp);var ssrc=getStatValue("ssrc");if(typeof ssrc==="number"){standardizedStats.ssrc=String(ssrc)}var bytesSent=getStatValue("bytesSent");if(typeof bytesSent==="number"){standardizedStats.bytesSent=bytesSent}var packetsLost=getStatValue("packetsLost");if(typeof packetsLost==="number"){standardizedStats.packetsLost=packetsLost}var packetsSent=getStatValue("packetsSent");if(typeof packetsSent==="number"){standardizedStats.packetsSent=packetsSent}var roundTripTime=getStatValue("roundTripTime");if(typeof roundTripTime==="number"){standardizedStats.roundTripTime=Math.round(roundTripTime*1e3)}var jitter=getStatValue("jitter");if(typeof jitter==="number"){standardizedStats.jitter=Math.round(jitter*1e3)}var frameRateSent=getStatValue("framerateMean");if(typeof frameRateSent==="number"){standardizedStats.frameRateSent=Math.round(frameRateSent)}var bytesReceived=getStatValue("bytesReceived");if(typeof bytesReceived==="number"){standardizedStats.bytesReceived=bytesReceived}var packetsReceived=getStatValue("packetsReceived");if(typeof packetsReceived==="number"){standardizedStats.packetsReceived=packetsReceived}var frameRateReceived=getStatValue("framerateMean");if(typeof frameRateReceived==="number"){standardizedStats.frameRateReceived=Math.round(frameRateReceived)}var totalPacketSendDalay=getStatValue("totalPacketSendDelay");if(typeof totalPacketSendDalay==="number"){standardizedStats.totalPacketSendDelay=totalPacketSendDalay}var totalEncodeTime=getStatValue("totalEncodeTime");if(typeof totalEncodeTime==="number"){standardizedStats.totalEncodeTime=totalEncodeTime}var framesEncoded=getStatValue("framesEncoded");if(typeof framesEncoded==="number"){standardizedStats.framesEncoded=framesEncoded}var estimatedPlayoutTimestamp=getStatValue("estimatedPlayoutTimestamp");if(typeof estimatedPlayoutTimestamp==="number"){standardizedStats.estimatedPlayoutTimestamp=estimatedPlayoutTimestamp}var totalDecodeTime=getStatValue("totalDecodeTime");if(typeof totalDecodeTime==="number"){standardizedStats.totalDecodeTime=totalDecodeTime}var framesDecoded=getStatValue("framesDecoded");if(typeof framesDecoded==="number"){standardizedStats.framesDecoded=framesDecoded}var jitterBufferDelay=getStatValue("jitterBufferDelay");if(typeof jitterBufferDelay==="number"){standardizedStats.jitterBufferDelay=jitterBufferDelay}var jitterBufferEmittedCount=getStatValue("jitterBufferEmittedCount");if(typeof jitterBufferEmittedCount==="number"){standardizedStats.jitterBufferEmittedCount=jitterBufferEmittedCount}return standardizedStats}module.exports=getStats},{"./util":170,"./util/sdp":172}],156:[function(require,module,exports){"use strict";function getUserMedia(constraints){if(typeof navigator==="object"&&typeof navigator.mediaDevices==="object"&&typeof navigator.mediaDevices.getUserMedia==="function"){constraints=constraints||{audio:true,video:true};return navigator.mediaDevices.getUserMedia(constraints)}return Promise.reject(new Error("getUserMedia is not supported"))}module.exports=getUserMedia},{}],157:[function(require,module,exports){"use strict";var WebRTC={};Object.defineProperties(WebRTC,{getStats:{enumerable:true,value:require("./getstats")},getUserMedia:{enumerable:true,value:require("./getusermedia")},MediaStream:{enumerable:true,value:require("./mediastream")},MediaStreamTrack:{enumerable:true,value:require("./mediastreamtrack")},RTCIceCandidate:{enumerable:true,value:require("./rtcicecandidate")},RTCPeerConnection:{enumerable:true,value:require("./rtcpeerconnection")},RTCSessionDescription:{enumerable:true,value:require("./rtcsessiondescription")}});module.exports=WebRTC},{"./getstats":155,"./getusermedia":156,"./mediastream":158,"./mediastreamtrack":159,"./rtcicecandidate":160,"./rtcpeerconnection":163,"./rtcsessiondescription":168}],158:[function(require,module,exports){"use strict";if(typeof MediaStream==="function"){module.exports=MediaStream}else{module.exports=function MediaStream(){throw new Error("MediaStream is not supported")}}},{}],159:[function(require,module,exports){"use strict";if(typeof MediaStreamTrack==="function"){module.exports=MediaStreamTrack}else{module.exports=function MediaStreamTrack(){throw new Error("MediaStreamTrack is not supported")}}},{}],160:[function(require,module,exports){"use strict";if(typeof RTCIceCandidate==="function"){module.exports=RTCIceCandidate}else{module.exports=function RTCIceCandidate(){throw new Error("RTCIceCandidate is not supported")}}},{}],161:[function(require,module,exports){"use strict";var ChromeRTCSessionDescription=require("../rtcsessiondescription/chrome");var EventTarget=require("../util/eventtarget");var inherits=require("../../vendor/inherits");var Latch=require("../util/latch");var MediaStream=require("../mediastream");var RTCRtpSenderShim=require("../rtcrtpsender");var sdpUtils=require("../util/sdp");var util=require("../util");var isIOSChrome=require("../util").isIOSChrome;var isUnifiedPlan=sdpUtils.getSdpFormat()==="unified";function ChromeRTCPeerConnection(configuration,constraints){if(!(this instanceof ChromeRTCPeerConnection)){return new ChromeRTCPeerConnection(configuration,constraints)}EventTarget.call(this);configuration=configuration||{};var newConfiguration=Object.assign(configuration.iceTransportPolicy?{iceTransports:configuration.iceTransportPolicy}:{},configuration);util.interceptEvent(this,"datachannel");util.interceptEvent(this,"signalingstatechange");var sdpFormat=sdpUtils.getSdpFormat(newConfiguration.sdpSemantics);var peerConnection=new RTCPeerConnection(newConfiguration,constraints);Object.defineProperties(this,{_appliedTracksToSSRCs:{value:new Map,writable:true},_localStream:{value:new MediaStream},_peerConnection:{value:peerConnection},_pendingLocalOffer:{value:null,writable:true},_pendingRemoteOffer:{value:null,writable:true},_rolledBackTracksToSSRCs:{value:new Map,writable:true},_sdpFormat:{value:sdpFormat},_senders:{value:new Map},_signalingStateLatch:{value:new Latch},_tracksToSSRCs:{value:new Map,writable:true},localDescription:{enumerable:true,get:function(){return this._pendingLocalOffer?this._pendingLocalOffer:peerConnection.localDescription}},remoteDescription:{enumerable:true,get:function(){return this._pendingRemoteOffer?this._pendingRemoteOffer:peerConnection.remoteDescription}},signalingState:{enumerable:true,get:function(){if(this._pendingLocalOffer){return"have-local-offer"}else if(this._pendingRemoteOffer){return"have-remote-offer"}return peerConnection.signalingState}}});var self=this;peerConnection.addEventListener("datachannel",function ondatachannel(event){shimDataChannel(event.channel);self.dispatchEvent(event)});peerConnection.addEventListener("signalingstatechange",function onsignalingstatechange(){if(peerConnection.signalingState==="stable"){self._appliedTracksToSSRCs=new Map(self._tracksToSSRCs)}if(!self._pendingLocalOffer&&!self._pendingRemoteOffer){self.dispatchEvent.apply(self,arguments)}});peerConnection.ontrack=function ontrack(){};if(typeof RTCPeerConnection.prototype.addTrack!=="function"){peerConnection.addStream(this._localStream)}util.proxyProperties(RTCPeerConnection.prototype,this,peerConnection)}inherits(ChromeRTCPeerConnection,EventTarget);if(typeof RTCPeerConnection.prototype.addTrack!=="function"){ChromeRTCPeerConnection.prototype.addTrack=function addTrack(){var args=[].slice.call(arguments);var track=args[0];if(this._peerConnection.signalingState==="closed"){throw new Error("Cannot add MediaStreamTrack ["+track.id+", "+track.kind+"]: RTCPeerConnection is closed")}var sender=this._senders.get(track);if(sender&&sender.track){throw new Error("Cannot add MediaStreamTrack ["+track.id+", "+track.kind+"]: RTCPeerConnection already has it")}this._peerConnection.removeStream(this._localStream);this._localStream.addTrack(track);this._peerConnection.addStream(this._localStream);sender=new RTCRtpSenderShim(track);this._senders.set(track,sender);return sender};ChromeRTCPeerConnection.prototype.removeTrack=function removeTrack(sender){if(this._peerConnection.signalingState==="closed"){throw new Error("Cannot remove MediaStreamTrack: RTCPeerConnection is closed")}var track=sender.track;if(!track){return}sender=this._senders.get(track);if(sender&&sender.track){sender.track=null;this._peerConnection.removeStream(this._localStream);this._localStream.removeTrack(track);this._peerConnection.addStream(this._localStream)}};ChromeRTCPeerConnection.prototype.getSenders=function getSenders(){return Array.from(this._senders.values())}}else{ChromeRTCPeerConnection.prototype.removeTrack=function removeTrack(sender){if(this._peerConnection.signalingState==="closed"){throw new Error("Cannot remove MediaStreamTrack: RTCPeerConnection is closed")}try{this._peerConnection.removeTrack(sender)}catch(e){}}}ChromeRTCPeerConnection.prototype.addIceCandidate=function addIceCandidate(candidate){var args=[].slice.call(arguments);var promise;var self=this;if(this.signalingState==="have-remote-offer"){promise=this._signalingStateLatch.when("low").then(function signalingStatesResolved(){return self._peerConnection.addIceCandidate(candidate)})}else{promise=this._peerConnection.addIceCandidate(candidate)}return args.length>1?util.legacyPromise(promise,args[1],args[2]):promise};ChromeRTCPeerConnection.prototype.close=function close(){if(this.signalingState!=="closed"){this._pendingLocalOffer=null;this._pendingRemoteOffer=null;this._peerConnection.close()}};ChromeRTCPeerConnection.prototype.createAnswer=function createAnswer(){var args=[].slice.call(arguments);var promise;var self=this;if(this._pendingRemoteOffer){promise=this._peerConnection.setRemoteDescription(this._pendingRemoteOffer).then(function setRemoteDescriptionSucceeded(){self._signalingStateLatch.lower();return self._peerConnection.createAnswer()}).then(function createAnswerSucceeded(answer){self._pendingRemoteOffer=null;self._rolledBackTracksToSSRCs.clear();return new ChromeRTCSessionDescription({type:"answer",sdp:updateTrackIdsToSSRCs(self._sdpFormat,self._tracksToSSRCs,answer.sdp)})},function setRemoteDescriptionOrCreateAnswerFailed(error){self._pendingRemoteOffer=null;throw error})}else{promise=this._peerConnection.createAnswer().then(function(answer){self._rolledBackTracksToSSRCs.clear();return new ChromeRTCSessionDescription({type:"answer",sdp:updateTrackIdsToSSRCs(self._sdpFormat,self._tracksToSSRCs,answer.sdp)})})}return args.length>1?util.legacyPromise(promise,args[0],args[1]):promise};ChromeRTCPeerConnection.prototype.createOffer=function createOffer(){var args=[].slice.call(arguments);var options=(args.length>1?args[2]:args[0])||{};var self=this;if(isIOSChrome()){if(options.offerToReceiveVideo&&!this._audioTransceiver&&!(isUnifiedPlan&&hasReceiversForTracksOfKind(this,"audio"))){delete options.offerToReceiveAudio;try{this._audioTransceiver=isUnifiedPlan?this.addTransceiver("audio",{direction:"recvonly"}):this.addTransceiver("audio")}catch(e){return Promise.reject(e)}}if(options.offerToReceiveVideo&&!this._videoTransceiver&&!(isUnifiedPlan&&hasReceiversForTracksOfKind(this,"video"))){delete options.offerToReceiveVideo;try{this._videoTransceiver=isUnifiedPlan?this.addTransceiver("video",{direction:"recvonly"}):this.addTransceiver("video")}catch(e){return Promise.reject(e)}}}var promise=this._peerConnection.createOffer(options).then(function(offer){self._rolledBackTracksToSSRCs.clear();return new ChromeRTCSessionDescription({type:offer.type,sdp:updateTrackIdsToSSRCs(self._sdpFormat,self._tracksToSSRCs,offer.sdp)})});return args.length>1?util.legacyPromise(promise,args[0],args[1]):promise};ChromeRTCPeerConnection.prototype.createDataChannel=function createDataChannel(label,dataChannelDict){dataChannelDict=shimDataChannelInit(dataChannelDict);var dataChannel=this._peerConnection.createDataChannel(label,dataChannelDict);shimDataChannel(dataChannel);return dataChannel};ChromeRTCPeerConnection.prototype.setLocalDescription=function setLocalDescription(){var args=[].slice.call(arguments);var description=args[0];if(this._rolledBackTracksToSSRCs.size>0){this._tracksToSSRCs=new Map(this._rolledBackTracksToSSRCs);this._rolledBackTracksToSSRCs.clear()}var promise=setDescription(this,true,description);return args.length>1?util.legacyPromise(promise,args[1],args[2]):promise};ChromeRTCPeerConnection.prototype.setRemoteDescription=function setRemoteDescription(){var args=[].slice.call(arguments);var description=args[0];this._rolledBackTracksToSSRCs.clear();var promise=setDescription(this,false,description);return args.length>1?util.legacyPromise(promise,args[1],args[2]):promise};util.delegateMethods(RTCPeerConnection.prototype,ChromeRTCPeerConnection.prototype,"_peerConnection");function setDescription(peerConnection,local,description){function setPendingLocalOffer(offer){if(local){peerConnection._pendingLocalOffer=offer}else{peerConnection._pendingRemoteOffer=offer}}function clearPendingLocalOffer(){if(local){peerConnection._pendingLocalOffer=null}else{peerConnection._pendingRemoteOffer=null}}var pendingLocalOffer=local?peerConnection._pendingLocalOffer:peerConnection._pendingRemoteOffer;var pendingRemoteOffer=local?peerConnection._pendingRemoteOffer:peerConnection._pendingLocalOffer;var intermediateState=local?"have-local-offer":"have-remote-offer";var setLocalDescription=local?"setLocalDescription":"setRemoteDescription";var promise;if(!local&&pendingRemoteOffer&&description.type==="answer"){promise=setRemoteAnswer(peerConnection,description)}else if(description.type==="offer"){if(peerConnection.signalingState!==intermediateState&&peerConnection.signalingState!=="stable"){return Promise.reject(new Error("Cannot set "+(local?"local":"remote")+" offer in state "+peerConnection.signalingState))}if(!pendingLocalOffer&&peerConnection._signalingStateLatch.state==="low"){peerConnection._signalingStateLatch.raise()}var previousSignalingState=peerConnection.signalingState;setPendingLocalOffer(unwrap(description));promise=Promise.resolve();if(peerConnection.signalingState!==previousSignalingState){promise.then(function dispatchSignalingStateChangeEvent(){peerConnection.dispatchEvent(new Event("signalingstatechange"))})}}else if(description.type==="rollback"){if(peerConnection.signalingState!==intermediateState){promise=Promise.reject(new Error("Cannot rollback "+(local?"local":"remote")+" description in "+peerConnection.signalingState))}else{clearPendingLocalOffer();peerConnection._rolledBackTracksToSSRCs=new Map(peerConnection._tracksToSSRCs);peerConnection._tracksToSSRCs=new Map(peerConnection._appliedTracksToSSRCs);promise=Promise.resolve();promise.then(function dispatchSignalingStateChangeEvent(){peerConnection.dispatchEvent(new Event("signalingstatechange"))})}}return promise||peerConnection._peerConnection[setLocalDescription](unwrap(description))}function setRemoteAnswer(peerConnection,answer){var pendingLocalOffer=peerConnection._pendingLocalOffer;return peerConnection._peerConnection.setLocalDescription(pendingLocalOffer).then(function setLocalOfferSucceeded(){peerConnection._pendingLocalOffer=null;return peerConnection.setRemoteDescription(answer)}).then(function setRemoteAnswerSucceeded(){peerConnection._signalingStateLatch.lower()})}function hasReceiversForTracksOfKind(peerConnection,kind){return!!peerConnection.getTransceivers().find(function(transceiver){return transceiver.receiver&&transceiver.receiver.track&&transceiver.receiver.track.kind===kind})}function unwrap(description){if(description instanceof ChromeRTCSessionDescription){if(description._description){return description._description}}return new RTCSessionDescription(description)}function needsMaxPacketLifeTimeShim(){return"maxRetransmitTime"in RTCDataChannel.prototype&&!("maxPacketLifeTime"in RTCDataChannel.prototype)}function shimDataChannelInit(dataChannelDict){dataChannelDict=Object.assign({},dataChannelDict);if(needsMaxPacketLifeTimeShim()&&"maxPacketLifeTime"in dataChannelDict){dataChannelDict.maxRetransmitTime=dataChannelDict.maxPacketLifeTime}return dataChannelDict}function shimDataChannel(dataChannel){Object.defineProperty(dataChannel,"maxRetransmits",{value:dataChannel.maxRetransmits===65535?null:dataChannel.maxRetransmits});if(needsMaxPacketLifeTimeShim()){Object.defineProperty(dataChannel,"maxPacketLifeTime",{value:dataChannel.maxRetransmitTime===65535?null:dataChannel.maxRetransmitTime})}return dataChannel}function updateTrackIdsToSSRCs(sdpFormat,tracksToSSRCs,sdp){return sdpFormat==="unified"?sdpUtils.updateUnifiedPlanTrackIdsToSSRCs(tracksToSSRCs,sdp):sdpUtils.updatePlanBTrackIdsToSSRCs(tracksToSSRCs,sdp)}module.exports=ChromeRTCPeerConnection},{"../../vendor/inherits":150,"../mediastream":158,"../rtcrtpsender":165,"../rtcsessiondescription/chrome":166,"../util":170,"../util/eventtarget":169,"../util/latch":171,"../util/sdp":172}],162:[function(require,module,exports){"use strict";var EventTarget=require("../util/eventtarget");var FirefoxRTCSessionDescription=require("../rtcsessiondescription/firefox");var inherits=require("../../vendor/inherits");var updateTracksToSSRCs=require("../util/sdp").updateUnifiedPlanTrackIdsToSSRCs;var util=require("../util");function FirefoxRTCPeerConnection(configuration){if(!(this instanceof FirefoxRTCPeerConnection)){return new FirefoxRTCPeerConnection(configuration)}EventTarget.call(this);util.interceptEvent(this,"signalingstatechange");var peerConnection=new RTCPeerConnection(configuration);Object.defineProperties(this,{_initiallyNegotiatedDtlsRole:{value:null,writable:true},_isClosed:{value:false,writable:true},_peerConnection:{value:peerConnection},_rollingBack:{value:false,writable:true},_tracksToSSRCs:{value:new Map},iceGatheringState:{enumerable:true,get:function(){return this._isClosed?"complete":this._peerConnection.iceGatheringState}},localDescription:{enumerable:true,get:function(){return overwriteWithInitiallyNegotiatedDtlsRole(this._peerConnection.localDescription,this._initiallyNegotiatedDtlsRole)}},signalingState:{enumerable:true,get:function(){return this._isClosed?"closed":this._peerConnection.signalingState}}});var self=this;var previousSignalingState;peerConnection.addEventListener("signalingstatechange",function onsignalingstatechange(){if(!self._rollingBack&&self.signalingState!==previousSignalingState){previousSignalingState=self.signalingState;var dispatchEventToSelf=self.dispatchEvent.apply.bind(self.dispatchEvent,self,arguments);if(self._isClosed){setTimeout(dispatchEventToSelf)}else{dispatchEventToSelf()}}});util.proxyProperties(RTCPeerConnection.prototype,this,peerConnection)}inherits(FirefoxRTCPeerConnection,EventTarget);Object.defineProperty(FirefoxRTCPeerConnection.prototype,"peerIdentity",{enumerable:true,value:Promise.resolve({idp:"",name:""})});FirefoxRTCPeerConnection.prototype.createAnswer=function createAnswer(){var args=[].slice.call(arguments);var promise;var self=this;promise=this._peerConnection.createAnswer().then(function createAnswerSucceeded(answer){
56
+ saveInitiallyNegotiatedDtlsRole(self,answer);return overwriteWithInitiallyNegotiatedDtlsRole(answer,self._initiallyNegotiatedDtlsRole)});return typeof args[0]==="function"?util.legacyPromise(promise,args[0],args[1]):promise};FirefoxRTCPeerConnection.prototype.createOffer=function createOffer(){var args=[].slice.call(arguments);var options=(args.length>1?args[2]:args[0])||{};var promise;var self=this;if(this.signalingState==="have-local-offer"||this.signalingState==="have-remote-offer"){var local=this.signalingState==="have-local-offer";promise=rollback(this,local,function rollbackSucceeded(){return self.createOffer(options)})}else{promise=self._peerConnection.createOffer(options)}promise=promise.then(function(offer){return new FirefoxRTCSessionDescription({type:offer.type,sdp:updateTracksToSSRCs(self._tracksToSSRCs,offer.sdp)})});return args.length>1?util.legacyPromise(promise,args[0],args[1]):promise};FirefoxRTCPeerConnection.prototype.setLocalDescription=function setLocalDescription(){var args=[].slice.call(arguments);var description=args[0];var promise;if(description&&description.type==="answer"&&this.signalingState==="have-local-offer"){promise=Promise.reject(new Error("Cannot set local answer in state have-local-offer"))}if(promise){return args.length>1?util.legacyPromise(promise,args[1],args[2]):promise}return this._peerConnection.setLocalDescription.apply(this._peerConnection,args)};FirefoxRTCPeerConnection.prototype.setRemoteDescription=function setRemoteDescription(){var args=[].slice.call(arguments);var description=args[0];var promise;var self=this;if(description&&this.signalingState==="have-remote-offer"){if(description.type==="answer"){promise=Promise.reject(new Error("Cannot set remote answer in state have-remote-offer"))}else if(description.type==="offer"){promise=rollback(this,false,function rollbackSucceeded(){return self._peerConnection.setRemoteDescription(description)})}}if(!promise){promise=this._peerConnection.setRemoteDescription(description)}promise=promise.then(function setRemoteDescriptionSucceeded(){saveInitiallyNegotiatedDtlsRole(self,description,true)});return args.length>1?util.legacyPromise(promise,args[1],args[2]):promise};FirefoxRTCPeerConnection.prototype.close=function close(){if(this.signalingState!=="closed"){this._isClosed=true;this._peerConnection.close()}};util.delegateMethods(RTCPeerConnection.prototype,FirefoxRTCPeerConnection.prototype,"_peerConnection");function rollback(peerConnection,local,onceRolledBack){var setLocalDescription=local?"setLocalDescription":"setRemoteDescription";peerConnection._rollingBack=true;return peerConnection._peerConnection[setLocalDescription](new FirefoxRTCSessionDescription({type:"rollback"})).then(onceRolledBack).then(function onceRolledBackSucceeded(result){peerConnection._rollingBack=false;return result},function rollbackOrOnceRolledBackFailed(error){peerConnection._rollingBack=false;throw error})}function saveInitiallyNegotiatedDtlsRole(peerConnection,description,remote){if(peerConnection._initiallyNegotiatedDtlsRole||description.type==="offer"){return}var match=description.sdp.match(/a=setup:([a-z]+)/);if(!match){return}var dtlsRole=match[1];peerConnection._initiallyNegotiatedDtlsRole=remote?{active:"passive",passive:"active"}[dtlsRole]:dtlsRole}function overwriteWithInitiallyNegotiatedDtlsRole(description,dtlsRole){if(description&&description.type==="answer"&&dtlsRole){return new FirefoxRTCSessionDescription({type:description.type,sdp:description.sdp.replace(/a=setup:[a-z]+/g,"a=setup:"+dtlsRole)})}return description}module.exports=FirefoxRTCPeerConnection},{"../../vendor/inherits":150,"../rtcsessiondescription/firefox":167,"../util":170,"../util/eventtarget":169,"../util/sdp":172}],163:[function(require,module,exports){"use strict";if(typeof RTCPeerConnection==="function"){var guessBrowser=require("../util").guessBrowser;switch(guessBrowser()){case"chrome":module.exports=require("./chrome");break;case"firefox":module.exports=require("./firefox");break;case"safari":module.exports=require("./safari");break;default:module.exports=RTCPeerConnection;break}}else{module.exports=function RTCPeerConnection(){throw new Error("RTCPeerConnection is not supported")}}},{"../util":170,"./chrome":161,"./firefox":162,"./safari":164}],164:[function(require,module,exports){"use strict";var EventTarget=require("../util/eventtarget");var inherits=require("../../vendor/inherits");var Latch=require("../util/latch");var sdpUtils=require("../util/sdp");var util=require("../util");var isUnifiedPlan=sdpUtils.getSdpFormat()==="unified";var updateTrackIdsToSSRCs=isUnifiedPlan?sdpUtils.updateUnifiedPlanTrackIdsToSSRCs:sdpUtils.updatePlanBTrackIdsToSSRCs;function SafariRTCPeerConnection(configuration){if(!(this instanceof SafariRTCPeerConnection)){return new SafariRTCPeerConnection(configuration)}EventTarget.call(this);util.interceptEvent(this,"datachannel");util.interceptEvent(this,"iceconnectionstatechange");util.interceptEvent(this,"signalingstatechange");util.interceptEvent(this,"track");var peerConnection=new RTCPeerConnection(configuration);Object.defineProperties(this,{_appliedTracksToSSRCs:{value:new Map,writable:true},_audioTransceiver:{value:null,writable:true},_isClosed:{value:false,writable:true},_peerConnection:{value:peerConnection},_pendingLocalOffer:{value:null,writable:true},_pendingRemoteOffer:{value:null,writable:true},_rolledBackTracksToSSRCs:{value:new Map,writable:true},_signalingStateLatch:{value:new Latch},_tracksToSSRCs:{value:new Map,writable:true},_videoTransceiver:{value:null,writable:true},localDescription:{enumerable:true,get:function(){return this._pendingLocalOffer||this._peerConnection.localDescription}},iceConnectionState:{enumerable:true,get:function(){return this._isClosed?"closed":this._peerConnection.iceConnectionState}},iceGatheringState:{enumerable:true,get:function(){return this._isClosed?"complete":this._peerConnection.iceGatheringState}},remoteDescription:{enumerable:true,get:function(){return this._pendingRemoteOffer||this._peerConnection.remoteDescription}},signalingState:{enumerable:true,get:function(){if(this._isClosed){return"closed"}else if(this._pendingLocalOffer){return"have-local-offer"}else if(this._pendingRemoteOffer){return"have-remote-offer"}return this._peerConnection.signalingState}}});var self=this;peerConnection.addEventListener("datachannel",function ondatachannel(event){shimDataChannel(event.channel);self.dispatchEvent(event)});peerConnection.addEventListener("iceconnectionstatechange",function oniceconnectionstatechange(){if(self._isClosed){return}self.dispatchEvent.apply(self,arguments)});peerConnection.addEventListener("signalingstatechange",function onsignalingstatechange(){if(self._isClosed){return}if(peerConnection.signalingState==="stable"){self._appliedTracksToSSRCs=new Map(self._tracksToSSRCs)}if(!self._pendingLocalOffer&&!self._pendingRemoteOffer){self.dispatchEvent.apply(self,arguments)}});peerConnection.addEventListener("track",function ontrack(event){self._pendingRemoteOffer=null;self.dispatchEvent(event)});util.proxyProperties(RTCPeerConnection.prototype,this,peerConnection)}inherits(SafariRTCPeerConnection,EventTarget);SafariRTCPeerConnection.prototype.addIceCandidate=function addIceCandidate(candidate){var self=this;if(this.signalingState==="have-remote-offer"){return this._signalingStateLatch.when("low").then(function signalingStatesResolved(){return self._peerConnection.addIceCandidate(candidate)})}return this._peerConnection.addIceCandidate(candidate)};SafariRTCPeerConnection.prototype.createOffer=function createOffer(options){options=Object.assign({},options);var self=this;if(options.offerToReceiveVideo&&!this._audioTransceiver&&!(isUnifiedPlan&&hasReceiversForTracksOfKind(this,"audio"))){delete options.offerToReceiveAudio;try{this._audioTransceiver=isUnifiedPlan?this.addTransceiver("audio",{direction:"recvonly"}):this.addTransceiver("audio")}catch(e){return Promise.reject(e)}}if(options.offerToReceiveVideo&&!this._videoTransceiver&&!(isUnifiedPlan&&hasReceiversForTracksOfKind(this,"video"))){delete options.offerToReceiveVideo;try{this._videoTransceiver=isUnifiedPlan?this.addTransceiver("video",{direction:"recvonly"}):this.addTransceiver("video")}catch(e){return Promise.reject(e)}}return this._peerConnection.createOffer(options).then(function(offer){self._rolledBackTracksToSSRCs.clear();return new RTCSessionDescription({type:offer.type,sdp:updateTrackIdsToSSRCs(self._tracksToSSRCs,offer.sdp)})})};SafariRTCPeerConnection.prototype.createAnswer=function createAnswer(options){var self=this;if(this._pendingRemoteOffer){return this._peerConnection.setRemoteDescription(this._pendingRemoteOffer).then(function setRemoteDescriptionSucceeded(){self._signalingStateLatch.lower();return self._peerConnection.createAnswer()}).then(function createAnswerSucceeded(answer){self._pendingRemoteOffer=null;self._rolledBackTracksToSSRCs.clear();return isUnifiedPlan?new RTCSessionDescription({type:answer.type,sdp:updateTrackIdsToSSRCs(self._tracksToSSRCs,answer.sdp)}):answer},function setRemoteDescriptionOrCreateAnswerFailed(error){self._pendingRemoteOffer=null;throw error})}return this._peerConnection.createAnswer(options).then(function createAnswerSucceeded(answer){self._rolledBackTracksToSSRCs.clear();return isUnifiedPlan?new RTCSessionDescription({type:answer.type,sdp:updateTrackIdsToSSRCs(self._tracksToSSRCs,answer.sdp)}):answer})};SafariRTCPeerConnection.prototype.createDataChannel=function createDataChannel(label,dataChannelDict){var dataChannel=this._peerConnection.createDataChannel(label,dataChannelDict);shimDataChannel(dataChannel);return dataChannel};SafariRTCPeerConnection.prototype.removeTrack=function removeTrack(sender){sender.replaceTrack(null);this._peerConnection.removeTrack(sender)};SafariRTCPeerConnection.prototype.setLocalDescription=function setLocalDescription(description){if(this._rolledBackTracksToSSRCs.size>0){this._tracksToSSRCs=new Map(this._rolledBackTracksToSSRCs);this._rolledBackTracksToSSRCs.clear()}return setDescription(this,true,description)};SafariRTCPeerConnection.prototype.setRemoteDescription=function setRemoteDescription(description){this._rolledBackTracksToSSRCs.clear();return setDescription(this,false,description)};SafariRTCPeerConnection.prototype.close=function close(){if(this._isClosed){return}this._isClosed=true;this._peerConnection.close();var self=this;setTimeout(function(){self.dispatchEvent(new Event("iceconnectionstatechange"));self.dispatchEvent(new Event("signalingstatechange"))})};util.delegateMethods(RTCPeerConnection.prototype,SafariRTCPeerConnection.prototype,"_peerConnection");function setDescription(peerConnection,local,description){function setPendingLocalOffer(offer){if(local){peerConnection._pendingLocalOffer=offer}else{peerConnection._pendingRemoteOffer=offer}}function clearPendingLocalOffer(){if(local){peerConnection._pendingLocalOffer=null}else{peerConnection._pendingRemoteOffer=null}}var pendingLocalOffer=local?peerConnection._pendingLocalOffer:peerConnection._pendingRemoteOffer;var pendingRemoteOffer=local?peerConnection._pendingRemoteOffer:peerConnection._pendingLocalOffer;var intermediateState=local?"have-local-offer":"have-remote-offer";var setLocalDescription=local?"setLocalDescription":"setRemoteDescription";if(!local&&pendingRemoteOffer&&description.type==="answer"){return setRemoteAnswer(peerConnection,description)}else if(description.type==="offer"){if(peerConnection.signalingState!==intermediateState&&peerConnection.signalingState!=="stable"){return Promise.reject(new Error("Cannot set "+(local?"local":"remote")+" offer in state "+peerConnection.signalingState))}if(!pendingLocalOffer&&peerConnection._signalingStateLatch.state==="low"){peerConnection._signalingStateLatch.raise()}var previousSignalingState=peerConnection.signalingState;setPendingLocalOffer(description);if(peerConnection.signalingState!==previousSignalingState){return Promise.resolve().then(function dispatchSignalingStateChangeEvent(){peerConnection.dispatchEvent(new Event("signalingstatechange"))})}return Promise.resolve()}else if(description.type==="rollback"){if(peerConnection.signalingState!==intermediateState){return Promise.reject(new Error("Cannot rollback "+(local?"local":"remote")+" description in "+peerConnection.signalingState))}clearPendingLocalOffer();peerConnection._rolledBackTracksToSSRCs=new Map(peerConnection._tracksToSSRCs);peerConnection._tracksToSSRCs=new Map(peerConnection._appliedTracksToSSRCs);return Promise.resolve().then(function dispatchSignalingStateChangeEvent(){peerConnection.dispatchEvent(new Event("signalingstatechange"))})}return peerConnection._peerConnection[setLocalDescription](description)}function setRemoteAnswer(peerConnection,answer){var pendingLocalOffer=peerConnection._pendingLocalOffer;return peerConnection._peerConnection.setLocalDescription(pendingLocalOffer).then(function setLocalOfferSucceeded(){peerConnection._pendingLocalOffer=null;return peerConnection.setRemoteDescription(answer)}).then(function setRemoteAnswerSucceeded(){peerConnection._signalingStateLatch.lower()})}function hasReceiversForTracksOfKind(peerConnection,kind){return!!peerConnection.getTransceivers().find(function(transceiver){return transceiver.receiver&&transceiver.receiver.track&&transceiver.receiver.track.kind===kind})}function shimDataChannel(dataChannel){return Object.defineProperties(dataChannel,{maxPacketLifeTime:{value:dataChannel.maxPacketLifeTime===65535?null:dataChannel.maxPacketLifeTime},maxRetransmits:{value:dataChannel.maxRetransmits===65535?null:dataChannel.maxRetransmits}})}module.exports=SafariRTCPeerConnection},{"../../vendor/inherits":150,"../util":170,"../util/eventtarget":169,"../util/latch":171,"../util/sdp":172}],165:[function(require,module,exports){"use strict";function RTCRtpSenderShim(track){Object.defineProperties(this,{track:{enumerable:true,value:track,writable:true}})}module.exports=RTCRtpSenderShim},{}],166:[function(require,module,exports){"use strict";function ChromeRTCSessionDescription(descriptionInitDict){if(!(this instanceof ChromeRTCSessionDescription)){return new ChromeRTCSessionDescription(descriptionInitDict)}var description=descriptionInitDict&&descriptionInitDict.type==="rollback"?null:new RTCSessionDescription(descriptionInitDict);Object.defineProperties(this,{_description:{get:function(){return description}},sdp:{enumerable:true,value:description?description.sdp:descriptionInitDict.sdp},type:{enumerable:true,value:description?description.type:descriptionInitDict.type}})}module.exports=ChromeRTCSessionDescription},{}],167:[function(require,module,exports){"use strict";module.exports=RTCSessionDescription},{}],168:[function(require,module,exports){"use strict";if(typeof RTCSessionDescription==="function"){var guessBrowser=require("../util").guessBrowser;switch(guessBrowser()){case"chrome":module.exports=require("./chrome");break;case"firefox":module.exports=require("./firefox");break;default:module.exports=RTCSessionDescription;break}}else{module.exports=function RTCSessionDescription(){throw new Error("RTCSessionDescription is not supported")}}},{"../util":170,"./chrome":166,"./firefox":167}],169:[function(require,module,exports){"use strict";var EventEmitter=require("events").EventEmitter;function EventTarget(){Object.defineProperties(this,{_eventEmitter:{value:new EventEmitter}})}EventTarget.prototype.dispatchEvent=function dispatchEvent(event){return this._eventEmitter.emit(event.type,event)};EventTarget.prototype.addEventListener=function addEventListener(){return this._eventEmitter.addListener.apply(this._eventEmitter,arguments)};EventTarget.prototype.removeEventListener=function removeEventListener(){return this._eventEmitter.removeListener.apply(this._eventEmitter,arguments)};module.exports=EventTarget},{events:173}],170:[function(require,module,exports){"use strict";function defer(){var deferred={};deferred.promise=new Promise(function(resolve,reject){deferred.resolve=resolve;deferred.reject=reject});return deferred}function delegateMethod(source,wrapper,target,methodName){if(methodName in wrapper){return}else if(methodName.match(/^on[a-z]+$/)){return}var isProperty=false;try{var propDesc=Object.getOwnPropertyDescriptor(source,methodName);isProperty=propDesc&&!!propDesc.get}catch(error){}if(isProperty){return}var type;try{type=typeof source[methodName]}catch(error){}if(type!=="function"){return}wrapper[methodName]=function(){return this[target][methodName].apply(this[target],arguments)}}function delegateMethods(source,wrapper,target){for(var methodName in source){delegateMethod(source,wrapper,target,methodName)}}function difference(list1,list2){list1=Array.isArray(list1)?new Set(list1):new Set(list1.values());list2=Array.isArray(list2)?new Set(list2):new Set(list2.values());var difference=new Set;list1.forEach(function(item){if(!list2.has(item)){difference.add(item)}});return difference}function flatMap(list,mapFn){var listArray=list instanceof Map||list instanceof Set?Array.from(list.values()):list;return listArray.reduce(function(flattened,item){var mapped=mapFn(item);return flattened.concat(mapped)},[])}function getUserAgent(){return typeof navigator!=="undefined"&&typeof navigator.userAgent==="string"?navigator.userAgent:null}function guessBrowser(userAgent){if(typeof userAgent==="undefined"){userAgent=getUserAgent()}if(/Chrome|CriOS/.test(userAgent)){return"chrome"}if(/Firefox|FxiOS/.test(userAgent)){return"firefox"}if(/Safari|iPhone|iPad|iPod/.test(userAgent)){return"safari"}return null}function guessBrowserVersion(userAgent){if(typeof userAgent==="undefined"){userAgent=getUserAgent()}var prefix={chrome:"Chrome|CriOS",firefox:"Firefox|FxiOS",safari:"Version"}[guessBrowser(userAgent)];if(!prefix){return null}var regex=new RegExp("("+prefix+")/([^\\s]+)");var match=(userAgent.match(regex)||[])[2];if(!match){return null}var versions=match.split(".").map(Number);return{major:isNaN(versions[0])?null:versions[0],minor:isNaN(versions[1])?null:versions[1]}}function isIOSChrome(userAgent){if(typeof userAgent==="undefined"){userAgent=getUserAgent()}return/Mobi/.test(userAgent)&&guessBrowser()==="chrome"&&/iPad|iPhone|iPod/.test(userAgent)}function interceptEvent(target,type){var currentListener=null;Object.defineProperty(target,"on"+type,{get:function(){return currentListener},set:function(newListener){if(currentListener){this.removeEventListener(type,currentListener)}if(typeof newListener==="function"){currentListener=newListener;this.addEventListener(type,currentListener)}else{currentListener=null}}})}function legacyPromise(promise,onSuccess,onFailure){if(onSuccess){return promise.then(function(result){onSuccess(result)},function(error){onFailure(error)})}return promise}function makeUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){var r=Math.random()*16|0;var v=c==="x"?r:r&3|8;return v.toString(16)})}function proxyProperties(source,wrapper,target){Object.getOwnPropertyNames(source).forEach(function(propertyName){proxyProperty(source,wrapper,target,propertyName)})}function proxyProperty(source,wrapper,target,propertyName){if(propertyName in wrapper){return}else if(propertyName.match(/^on[a-z]+$/)){Object.defineProperty(wrapper,propertyName,{value:null,writable:true});target.addEventListener(propertyName.slice(2),function(){wrapper.dispatchEvent.apply(wrapper,arguments)});return}Object.defineProperty(wrapper,propertyName,{enumerable:true,get:function(){return target[propertyName]}})}function support(){return typeof navigator==="object"&&typeof navigator.mediaDevices==="object"&&typeof navigator.mediaDevices.getUserMedia==="function"&&typeof RTCPeerConnection==="function"}exports.defer=defer;exports.delegateMethods=delegateMethods;exports.difference=difference;exports.flatMap=flatMap;exports.guessBrowser=guessBrowser;exports.guessBrowserVersion=guessBrowserVersion;exports.isIOSChrome=isIOSChrome;exports.interceptEvent=interceptEvent;exports.legacyPromise=legacyPromise;exports.makeUUID=makeUUID;exports.proxyProperties=proxyProperties;exports.support=support},{}],171:[function(require,module,exports){"use strict";var defer=require("./").defer;var states={high:new Set(["low"]),low:new Set(["high"])};function Latch(initialState){if(!(this instanceof Latch)){return new Latch(initialState)}var state=initialState||"low";Object.defineProperties(this,{_state:{set:function(_state){if(state!==_state){state=_state;var whenDeferreds=this._whenDeferreds.get(state);whenDeferreds.forEach(function(deferred){deferred.resolve(this)},this);whenDeferreds.clear()}},get:function(){return state}},_whenDeferreds:{value:new Map([["high",new Set],["low",new Set]])},state:{enumerable:true,get:function(){return this._state}}})}Latch.prototype.lower=function lower(){return this.transition("low")};Latch.prototype.raise=function raise(){return this.transition("high")};Latch.prototype.transition=function transition(newState){if(!states[this.state].has(newState)){throw createUnreachableStateError(this.state,newState)}this._state=newState;return this};Latch.prototype.when=function when(state){if(this.state===state){return Promise.resolve(this)}if(!states[this.state].has(state)){return Promise.reject(createUnreachableStateError(this.state,state))}var deferred=defer();this._whenDeferreds.get(state).add(deferred);return deferred.promise};function createUnreachableStateError(from,to){return new Error('Cannot transition from "'+from+'" to "'+to+'"')}module.exports=Latch},{"./":170}],172:[function(require,module,exports){"use strict";var flatMap=require("./").flatMap;var guessBrowser=require("./").guessBrowser;var isSdpSemanticsSupported=null;function checkIfSdpSemanticsIsSupported(){if(typeof isSdpSemanticsSupported==="boolean"){return isSdpSemanticsSupported}if(typeof RTCPeerConnection==="undefined"){isSdpSemanticsSupported=false;return isSdpSemanticsSupported}try{new RTCPeerConnection({sdpSemantics:"foo"});isSdpSemanticsSupported=false}catch(e){isSdpSemanticsSupported=true}return isSdpSemanticsSupported}var chromeSdpFormat=null;function clearChromeCachedSdpFormat(){chromeSdpFormat=null}function getChromeDefaultSdpFormat(){if(!chromeSdpFormat){if(typeof RTCPeerConnection!=="undefined"&&"addTransceiver"in RTCPeerConnection.prototype){var pc=new RTCPeerConnection;try{pc.addTransceiver("audio");chromeSdpFormat="unified"}catch(e){chromeSdpFormat="planb"}pc.close()}else{chromeSdpFormat="planb"}}return chromeSdpFormat}function getChromeSdpFormat(sdpSemantics){if(!sdpSemantics||!checkIfSdpSemanticsIsSupported()){return getChromeDefaultSdpFormat()}return{"plan-b":"planb","unified-plan":"unified"}[sdpSemantics]}function getSafariSdpFormat(){return typeof RTCRtpTransceiver!=="undefined"&&"currentDirection"in RTCRtpTransceiver.prototype?"unified":"planb"}function getSdpFormat(sdpSemantics){return{chrome:getChromeSdpFormat(sdpSemantics),firefox:"unified",safari:getSafariSdpFormat()}[guessBrowser()]||null}function getMatches(pattern,lines){var matches=lines.match(new RegExp(pattern,"gm"))||[];return matches.reduce(function(results,line){var match=line.match(new RegExp(pattern));return match?results.add(match[1]):results},new Set)}function getTrackIds(pattern,sdp){return getMatches(pattern,sdp)}function getPlanBTrackIds(sdp){return getTrackIds("^a=ssrc:[0-9]+ +msid:.+ +(.+) *$",sdp)}function getUnifiedPlanTrackIds(sdp){return getTrackIds("^a=msid:.+ +(.+) *$",sdp)}function getPlanBSSRCs(sdp,trackId){var pattern="^a=ssrc:([0-9]+) +msid:[^ ]+ +"+trackId+" *$";return getMatches(pattern,sdp)}function getMediaSections(sdp,kind,direction){kind=kind||".*";direction=direction||".*";return sdp.split("\r\nm=").slice(1).map(function(mediaSection){return"m="+mediaSection}).filter(function(mediaSection){var kindPattern=new RegExp("m="+kind,"gm");var directionPattern=new RegExp("a="+direction,"gm");return kindPattern.test(mediaSection)&&directionPattern.test(mediaSection)})}function getMediaSectionSSRCs(mediaSection){return Array.from(getMatches("^a=ssrc:([0-9]+) +.*$",mediaSection))}function getUnifiedPlanSSRCs(sdp,trackId){var mediaSections=getMediaSections(sdp);var msidAttrRegExp=new RegExp("^a=msid:[^ ]+ +"+trackId+" *$","gm");var matchingMediaSections=mediaSections.filter(function(mediaSection){return mediaSection.match(msidAttrRegExp)});return new Set(flatMap(matchingMediaSections,getMediaSectionSSRCs))}function getTrackIdsToSSRCs(getTrackIds,getSSRCs,sdp){return new Map(Array.from(getTrackIds(sdp)).map(function(trackId){return[trackId,getSSRCs(sdp,trackId)]}))}function getPlanBTrackIdsToSSRCs(sdp){return getTrackIdsToSSRCs(getPlanBTrackIds,getPlanBSSRCs,sdp)}function getUnifiedPlanTrackIdsToSSRCs(sdp){return getTrackIdsToSSRCs(getUnifiedPlanTrackIds,getUnifiedPlanSSRCs,sdp)}function updateTrackIdsToSSRCs(getTrackIdsToSSRCs,trackIdsToSSRCs,sdp){var newTrackIdsToSSRCs=getTrackIdsToSSRCs(sdp);var newSSRCsToOldSSRCs=new Map;newTrackIdsToSSRCs.forEach(function(ssrcs,trackId){if(!trackIdsToSSRCs.has(trackId)){trackIdsToSSRCs.set(trackId,ssrcs);return}var oldSSRCs=Array.from(trackIdsToSSRCs.get(trackId));var newSSRCs=Array.from(ssrcs);oldSSRCs.forEach(function(oldSSRC,i){var newSSRC=newSSRCs[i];newSSRCsToOldSSRCs.set(newSSRC,oldSSRC);var pattern="^a=ssrc:"+newSSRC+" (.*)$";var replacement="a=ssrc:"+oldSSRC+" $1";sdp=sdp.replace(new RegExp(pattern,"gm"),replacement)})});var pattern="^(a=ssrc-group:[^ ]+ +)(.*)$";var matches=sdp.match(new RegExp(pattern,"gm"))||[];matches.forEach(function(line){var match=line.match(new RegExp(pattern));if(!match){return}var prefix=match[1];var newSSRCs=match[2];var oldSSRCs=newSSRCs.split(" ").map(function(newSSRC){var oldSSRC=newSSRCsToOldSSRCs.get(newSSRC);return oldSSRC?oldSSRC:newSSRC}).join(" ");sdp=sdp.replace(match[0],prefix+oldSSRCs)});return sdp}function updatePlanBTrackIdsToSSRCs(trackIdsToSSRCs,sdp){return updateTrackIdsToSSRCs(getPlanBTrackIdsToSSRCs,trackIdsToSSRCs,sdp)}function updateUnifiedPlanTrackIdsToSSRCs(trackIdsToSSRCs,sdp){return updateTrackIdsToSSRCs(getUnifiedPlanTrackIdsToSSRCs,trackIdsToSSRCs,sdp)}exports.clearChromeCachedSdpFormat=clearChromeCachedSdpFormat;exports.getSdpFormat=getSdpFormat;exports.getMediaSections=getMediaSections;exports.getPlanBTrackIds=getPlanBTrackIds;exports.getUnifiedPlanTrackIds=getUnifiedPlanTrackIds;exports.getPlanBSSRCs=getPlanBSSRCs;exports.getUnifiedPlanSSRCs=getUnifiedPlanSSRCs;exports.updatePlanBTrackIdsToSSRCs=updatePlanBTrackIdsToSSRCs;exports.updateUnifiedPlanTrackIdsToSSRCs=updateUnifiedPlanTrackIdsToSSRCs},{"./":170}],173:[function(require,module,exports){"use strict";var R=typeof Reflect==="object"?Reflect:null;var ReflectApply=R&&typeof R.apply==="function"?R.apply:function ReflectApply(target,receiver,args){return Function.prototype.apply.call(target,receiver,args)};var ReflectOwnKeys;if(R&&typeof R.ownKeys==="function"){ReflectOwnKeys=R.ownKeys}else if(Object.getOwnPropertySymbols){ReflectOwnKeys=function ReflectOwnKeys(target){return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))}}else{ReflectOwnKeys=function ReflectOwnKeys(target){return Object.getOwnPropertyNames(target)}}function ProcessEmitWarning(warning){if(console&&console.warn)console.warn(warning)}var NumberIsNaN=Number.isNaN||function NumberIsNaN(value){return value!==value};function EventEmitter(){EventEmitter.init.call(this)}module.exports=EventEmitter;module.exports.once=once;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._eventsCount=0;EventEmitter.prototype._maxListeners=undefined;var defaultMaxListeners=10;function checkListener(listener){if(typeof listener!=="function"){throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof listener)}}Object.defineProperty(EventEmitter,"defaultMaxListeners",{enumerable:true,get:function(){return defaultMaxListeners},set:function(arg){if(typeof arg!=="number"||arg<0||NumberIsNaN(arg)){throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+arg+".")}defaultMaxListeners=arg}});EventEmitter.init=function(){if(this._events===undefined||this._events===Object.getPrototypeOf(this)._events){this._events=Object.create(null);this._eventsCount=0}this._maxListeners=this._maxListeners||undefined};EventEmitter.prototype.setMaxListeners=function setMaxListeners(n){if(typeof n!=="number"||n<0||NumberIsNaN(n)){throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+n+".")}this._maxListeners=n;return this};function _getMaxListeners(that){if(that._maxListeners===undefined)return EventEmitter.defaultMaxListeners;return that._maxListeners}EventEmitter.prototype.getMaxListeners=function getMaxListeners(){return _getMaxListeners(this)};EventEmitter.prototype.emit=function emit(type){var args=[];for(var i=1;i<arguments.length;i++)args.push(arguments[i]);var doError=type==="error";var events=this._events;if(events!==undefined)doError=doError&&events.error===undefined;else if(!doError)return false;if(doError){var er;if(args.length>0)er=args[0];if(er instanceof Error){throw er}var err=new Error("Unhandled error."+(er?" ("+er.message+")":""));err.context=er;throw err}var handler=events[type];if(handler===undefined)return false;if(typeof handler==="function"){ReflectApply(handler,this,args)}else{var len=handler.length;var listeners=arrayClone(handler,len);for(var i=0;i<len;++i)ReflectApply(listeners[i],this,args)}return true};function _addListener(target,type,listener,prepend){var m;var events;var existing;checkListener(listener);events=target._events;if(events===undefined){events=target._events=Object.create(null);target._eventsCount=0}else{if(events.newListener!==undefined){target.emit("newListener",type,listener.listener?listener.listener:listener);events=target._events}existing=events[type]}if(existing===undefined){existing=events[type]=listener;++target._eventsCount}else{if(typeof existing==="function"){existing=events[type]=prepend?[listener,existing]:[existing,listener]}else if(prepend){existing.unshift(listener)}else{existing.push(listener)}m=_getMaxListeners(target);if(m>0&&existing.length>m&&!existing.warned){existing.warned=true;var w=new Error("Possible EventEmitter memory leak detected. "+existing.length+" "+String(type)+" listeners "+"added. Use emitter.setMaxListeners() to "+"increase limit");w.name="MaxListenersExceededWarning";w.emitter=target;w.type=type;w.count=existing.length;ProcessEmitWarning(w)}}return target}EventEmitter.prototype.addListener=function addListener(type,listener){return _addListener(this,type,listener,false)};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.prependListener=function prependListener(type,listener){return _addListener(this,type,listener,true)};function onceWrapper(){if(!this.fired){this.target.removeListener(this.type,this.wrapFn);this.fired=true;if(arguments.length===0)return this.listener.call(this.target);return this.listener.apply(this.target,arguments)}}function _onceWrap(target,type,listener){var state={fired:false,wrapFn:undefined,target:target,type:type,listener:listener};var wrapped=onceWrapper.bind(state);wrapped.listener=listener;state.wrapFn=wrapped;return wrapped}EventEmitter.prototype.once=function once(type,listener){checkListener(listener);this.on(type,_onceWrap(this,type,listener));return this};EventEmitter.prototype.prependOnceListener=function prependOnceListener(type,listener){checkListener(listener);this.prependListener(type,_onceWrap(this,type,listener));return this};EventEmitter.prototype.removeListener=function removeListener(type,listener){var list,events,position,i,originalListener;checkListener(listener);events=this._events;if(events===undefined)return this;list=events[type];if(list===undefined)return this;if(list===listener||list.listener===listener){if(--this._eventsCount===0)this._events=Object.create(null);else{delete events[type]
57
+ ;if(events.removeListener)this.emit("removeListener",type,list.listener||listener)}}else if(typeof list!=="function"){position=-1;for(i=list.length-1;i>=0;i--){if(list[i]===listener||list[i].listener===listener){originalListener=list[i].listener;position=i;break}}if(position<0)return this;if(position===0)list.shift();else{spliceOne(list,position)}if(list.length===1)events[type]=list[0];if(events.removeListener!==undefined)this.emit("removeListener",type,originalListener||listener)}return this};EventEmitter.prototype.off=EventEmitter.prototype.removeListener;EventEmitter.prototype.removeAllListeners=function removeAllListeners(type){var listeners,events,i;events=this._events;if(events===undefined)return this;if(events.removeListener===undefined){if(arguments.length===0){this._events=Object.create(null);this._eventsCount=0}else if(events[type]!==undefined){if(--this._eventsCount===0)this._events=Object.create(null);else delete events[type]}return this}if(arguments.length===0){var keys=Object.keys(events);var key;for(i=0;i<keys.length;++i){key=keys[i];if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events=Object.create(null);this._eventsCount=0;return this}listeners=events[type];if(typeof listeners==="function"){this.removeListener(type,listeners)}else if(listeners!==undefined){for(i=listeners.length-1;i>=0;i--){this.removeListener(type,listeners[i])}}return this};function _listeners(target,type,unwrap){var events=target._events;if(events===undefined)return[];var evlistener=events[type];if(evlistener===undefined)return[];if(typeof evlistener==="function")return unwrap?[evlistener.listener||evlistener]:[evlistener];return unwrap?unwrapListeners(evlistener):arrayClone(evlistener,evlistener.length)}EventEmitter.prototype.listeners=function listeners(type){return _listeners(this,type,true)};EventEmitter.prototype.rawListeners=function rawListeners(type){return _listeners(this,type,false)};EventEmitter.listenerCount=function(emitter,type){if(typeof emitter.listenerCount==="function"){return emitter.listenerCount(type)}else{return listenerCount.call(emitter,type)}};EventEmitter.prototype.listenerCount=listenerCount;function listenerCount(type){var events=this._events;if(events!==undefined){var evlistener=events[type];if(typeof evlistener==="function"){return 1}else if(evlistener!==undefined){return evlistener.length}}return 0}EventEmitter.prototype.eventNames=function eventNames(){return this._eventsCount>0?ReflectOwnKeys(this._events):[]};function arrayClone(arr,n){var copy=new Array(n);for(var i=0;i<n;++i)copy[i]=arr[i];return copy}function spliceOne(list,index){for(;index+1<list.length;index++)list[index]=list[index+1];list.pop()}function unwrapListeners(arr){var ret=new Array(arr.length);for(var i=0;i<ret.length;++i){ret[i]=arr[i].listener||arr[i]}return ret}function once(emitter,name){return new Promise(function(resolve,reject){function errorListener(err){emitter.removeListener(name,resolver);reject(err)}function resolver(){if(typeof emitter.removeListener==="function"){emitter.removeListener("error",errorListener)}resolve([].slice.call(arguments))}eventTargetAgnosticAddListener(emitter,name,resolver,{once:true});if(name!=="error"){addErrorHandlerIfEventEmitter(emitter,errorListener,{once:true})}})}function addErrorHandlerIfEventEmitter(emitter,handler,flags){if(typeof emitter.on==="function"){eventTargetAgnosticAddListener(emitter,"error",handler,flags)}}function eventTargetAgnosticAddListener(emitter,name,listener,flags){if(typeof emitter.on==="function"){if(flags.once){emitter.once(name,listener)}else{emitter.on(name,listener)}}else if(typeof emitter.addEventListener==="function"){emitter.addEventListener(name,function wrapListener(arg){if(flags.once){emitter.removeEventListener(name,wrapListener)}listener(arg)})}else{throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof emitter)}}},{}],174:[function(require,module,exports){module.exports={name:"twilio-video",title:"Twilio Video",description:"Twilio Video JavaScript Library",version:"2.24.3",homepage:"https://twilio.com",author:"Mark Andrus Roberts <mroberts@twilio.com>",contributors:["Ryan Rowland <rrowland@twilio.com>","Manjesh Malavalli <mmalavalli@twilio.com>","Makarand Patwardhan <mpatwardhan@twilio.com>"],keywords:["twilio","webrtc","library","javascript","video","rooms"],repository:{type:"git",url:"https://github.com/twilio/twilio-video.js.git"},devDependencies:{"@babel/core":"^7.14.2","@babel/preset-env":"^7.14.2","@babel/preset-typescript":"^7.13.0","@types/express":"^4.11.0","@types/node":"^8.5.1","@types/selenium-webdriver":"^3.0.8","@types/ws":"^3.2.1","@typescript-eslint/eslint-plugin":"^4.13.0","@typescript-eslint/parser":"^4.0.0","babel-cli":"^6.26.0","babel-preset-es2015":"^6.24.1",browserify:"^17.0.0",cheerio:"^0.22.0",cors:"^2.8.5",electron:"^17.2.0",envify:"^4.0.0",eslint:"^6.2.1","eslint-config-standard":"^14.0.0","eslint-plugin-import":"^2.18.2","eslint-plugin-node":"^9.1.0","eslint-plugin-promise":"^4.2.1","eslint-plugin-standard":"^4.0.1",express:"^4.16.2",glob:"^7.1.7","ink-docstrap":"^1.3.2",inquirer:"^7.0.0","is-docker":"^2.0.0",jsdoc:"^3.5.5","jsdoc-babel":"^0.5.0","json-loader":"^0.5.7",karma:"^5.0.2","karma-browserify":"^8.0.0","karma-chrome-launcher":"^2.0.0","karma-edgium-launcher":"^4.0.0-0","karma-electron":"^6.1.0","karma-firefox-launcher":"^1.3.0","karma-htmlfile-reporter":"^0.3.8","karma-junit-reporter":"^1.2.0","karma-mocha":"^1.3.0","karma-safari-launcher":"^1.0.0","karma-spec-reporter":"0.0.32","karma-typescript":"^5.5.1","karma-typescript-es6-transform":"^5.5.1",mocha:"^3.2.0","mock-require":"^3.0.3",ncp:"^2.0.0","node-http-server":"^8.1.2","npm-run-all":"^4.0.2",nyc:"^15.1.0",requirejs:"^2.3.3",rimraf:"^2.6.1","simple-git":"^1.126.0",sinon:"^4.0.1","ts-node":"4.0.1",tslint:"5.8.0",twilio:"^3.49.0","twilio-release-tool":"^1.0.2",typescript:"4.2.2","uglify-js":"^2.8.22","vinyl-fs":"^2.4.4","vinyl-source-stream":"^1.1.0",watchify:"^3.11.1","webrtc-adapter":"^7.7.1"},engines:{node:">=0.12"},license:"BSD-3-Clause",main:"./es5/index.js",types:"./tsdef/index.d.ts",scripts:{"lint:js":"eslint ./lib ./test/*.js ./docker/**/*.js ./test/framework/*.js ./test/lib/*.js ./test/integration/** ./test/unit/** ","lint:ts":"eslint ./tsdef/*.ts ./lib/**/*.ts",lint:"npm-run-all lint:js lint:ts",printVersion:"node --version && npm --version","test:unit":"npm-run-all printVersion build:es5 && nyc --report-dir=./coverage --include=lib/**/* --reporter=html --reporter=lcov --reporter=text mocha -r ts-node/register ./test/unit/*","test:unit:quick":"nyc --report-dir=./coverage --include=lib/**/* --reporter=html --reporter=lcov mocha -r ts-node/register","test:serversiderender":"mocha ./test/serversiderender/index.js","test:integration:adapter":"node ./scripts/karma.js karma/integration.adapter.conf.js","test:integration":"npm run build:es5 && node ./scripts/karma.js karma/integration.conf.js","test:umd:install":"npm install puppeteer@5.5.0","test:umd":"mocha ./test/umd/index.js","test:crossbrowser:build:clean":"rimraf ./test/crossbrowser/lib ./test/crossbrowser/src/browser/index.js","test:crossbrowser:build:lint":"cd ./test/crossbrowser && tslint --project tsconfig.json","test:crossbrowser:build:tsc":"cd ./test/crossbrowser && tsc","test:crossbrowser:build:browser":"cd ./test/crossbrowser && browserify lib/crossbrowser/src/browser/index.js > src/browser/index.js","test:crossbrowser:build":"npm-run-all test:crossbrowser:build:*","test:crossbrowser:test":"cd ./test/crossbrowser && mocha --compilers ts:ts-node/register test/integration/spec/**/*.ts","test:crossbrowser":"npm-run-all test:crossbrowser:*","test:sdkdriver:build:clean":"rimraf ./test/lib/sdkdriver/lib ./test/lib/sdkdriver/test/integration/browser/index.js","test:sdkdriver:build:lint":"cd ./test/lib/sdkdriver && tslint --project tsconfig.json","test:sdkdriver:build:tsc":"cd ./test/lib/sdkdriver && tsc --rootDir src","test:sdkdriver:build":"npm-run-all test:sdkdriver:build:*","test:sdkdriver:test:unit":"cd ./test/lib/sdkdriver && mocha --compilers ts:ts-node/register test/unit/spec/**/*.ts","test:sdkdriver:test:integration:browser":"cd ./test/lib/sdkdriver/test/integration && browserify browser/browser.js > browser/index.js","test:sdkdriver:test:integration:run":"cd ./test/lib/sdkdriver && mocha --compilers ts:ts-node/register test/integration/spec/**/*.ts","test:sdkdriver:test:integration":"npm-run-all test:sdkdriver:test:integration:*","test:sdkdriver:test":"npm-run-all test:sdkdriver:test:*","test:sdkdriver":"npm-run-all test:sdkdriver:*","test:framework:angular:install":"cd ./test/framework/twilio-video-angular && rimraf ./node_modules package-lock.json && npm install","test:framework:angular:run":"mocha ./test/framework/twilio-video-angular.js","test:framework:angular":"npm-run-all test:framework:angular:*","test:framework:no-framework:run":"mocha ./test/framework/twilio-video-no-framework.js","test:framework:no-framework":"npm-run-all test:framework:no-framework:*","test:framework:react:install":"cd ./test/framework/twilio-video-react && rimraf ./node_modules package-lock.json && npm install","test:framework:react:test":"node ./scripts/framework.js twilio-video-react","test:framework:react:build":"cd ./test/framework/twilio-video-react && npm run build","test:framework:react:run":"mocha ./test/framework/twilio-video-react.js","test:framework:react":"npm-run-all test:framework:react:*","test:framework:install":"npm install chromedriver && npm install selenium-webdriver && npm install geckodriver && npm install puppeteer","test:framework":"npm-run-all test:framework:install test:framework:no-framework test:framework:react",test:"npm-run-all test:unit test:integration","build:es5":"rimraf ./es5 && mkdir -p es5 && tsc tsdef/twilio-video-tests.ts --noEmit --lib es2018,dom && tsc","build:js":"node ./scripts/build.js ./src/twilio-video.js ./LICENSE.md ./dist/twilio-video.js","build:min.js":'uglifyjs ./dist/twilio-video.js -o ./dist/twilio-video.min.js --comments "/^! twilio-video.js/" -b beautify=false,ascii_only=true',build:"npm-run-all clean lint docs test:unit test:integration build:es5 build:js build:min.js test:umd","build:quick":"npm-run-all clean lint docs build:es5 build:js build:min.js",docs:"node ./scripts/docs.js ./dist/docs",watch:"tsc -w",clean:"rimraf ./coverage ./es5 ./dist"},dependencies:{events:"^3.3.0",util:"^0.12.4",ws:"^7.4.6",xmlhttprequest:"^1.8.0"},browser:{ws:"./src/ws.js",xmlhttprequest:"./src/xmlhttprequest.js"}}},{}],175:[function(require,module,exports){module.exports=WebSocket},{}]},{},[11]);var Video=bundle(11);if(typeof define==="function"&&define.amd){define([],function(){return Video})}else{var Twilio=root.Twilio=root.Twilio||{};Twilio.Video=Twilio.Video||Video}})(typeof window!=="undefined"?window:typeof global!=="undefined"?global:this);