ceee01a57c9e1c9874f5b10463b825a472426b37523e2775a3b49093d517c667

Source Code:

!function(e){var t={};function r(i){if(t[i])return t[i].exports;var n=t[i]={i:i,l:!1,exports:{}};return e[i].call(n.exports,n,n.exports,r),n.l=!0,n.exports}r.m=e,r.c=t,r.d=function(e,t,i){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var i=Object.create(null);if(r.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)r.d(i,n,function(t){return e[t]}.bind(null,n));return i},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=13)}([function(e,t,r){var i;
/**
 * @license NanoTools 2.1.0
 * Copyright (c) 2016-2019 nanocosmos IT GmbH. All rights reserved.
 * http://www.nanocosmos.de
 */void 0===(i=function(){"use strict";var e=Math.floor,t=Math.random,r={browserInfo:void 0,debugLevel:0,debugCount:0,debugMax:30,ELEMENT_DEBUG:"debug",ELEMENT_MESSAGES:"messages",ELEMENT_ERRORS:"errors",parseJSON:function(e,t,i){if("object"==typeof e)return e;try{return JSON.parse(e,t)}catch(t){r.error("Error:"+t+" parsing from json: "+e,i)}},stringifyJSON:function(e,t,i,n){if(r.isString(e))return e;try{return JSON.stringify(e,t,i)}catch(t){r.error("Error:"+t+" stringifying to json: "+e,n)}},encodeURIComponent:function(e,t){if(r.isString(e))return decodeURIComponent(e)===e?encodeURIComponent(e):e;r.error("Error: could not uri encode: "+e+"(must be of type string)",t)},getElement:function(e){var t=document.getElementById(e);return t||(r.debug("DOM element not found "+e),{value:void 0,checked:void 0,enabled:void 0,textContent:void 0,options:{length:0},style:{},innerHTML:"",src:"",classList:"",click:function(){return null},show:function(){return null},hide:function(){return null},removeChild:function(){return null}})},print:function(e){r._log(e,"messages")},success:function(e){r._log(e,"messages","green")},warning:function(e){r._log(e,"messages","orange")},error:function(e,t){t||(t=1),r._log(e,r.ELEMENT_MESSAGES,"red"),r._log(e,r.ELEMENT_ERRORS,"red",t)},debug:function(e){0!==r.debugLevel&&r._log(e,r.ELEMENT_DEBUG)},_log:function(e,t,i,n){switch(r.isObject(e)&&(e=r.stringifyJSON(e,null," ")),i){case"green":e="Success: "+e;break;case"orange":e="Warning: "+e;break;case"red":e="Error: "+e;break;default:i=""}i?console.log("%c"+e,"color:"+i):console.log(e);var o=document.getElementById(t);if(o&&(t===r.ELEMENT_DEBUG&&r.debugCount>r.debugMax&&(o.removeChild(o.firstChild),r.debugCount++),o.innerHTML+="<span"+(i?' style="color:'+i+';">':">")+e+"</span><br>"),n>1)throw new Error(e)},isBool:function(e){return!0===e||!1===e},isIntString:function(e){return r.isString(e)&&r.isInt(Number(e))},isNumber:function(e){return Number(e)===e&&isFinite(e)},isIntInRange:function(e,t,i){return r.isNumber(e)&&e>=t&&e<=i},isInt:function(e){return e===Number(e)&&e%1==0},isUint:function(e){return e===Number(e)&&e%1==0&&e>=0},isString:function(e){return"string"==typeof e||e instanceof String},isFunction:function(e){return"function"==typeof e},isObject:function(e){return!!e&&e.constructor!==Array&&("object"==typeof e||e instanceof Object)},isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)},isEmpty:function(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0},getRandomUint:function(i){return i=r.isUint(i)?i:10,e(t()*i)},getRandomString:function(e,t){var i;switch(e){case 0:i="0123456789";break;case 1:i="0123456789abcdefghijklmnopqrstuvwxyz";break;case 2:i="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";break;default:i="0123456789abcdefghijklmnopqrstuvwxyz"}for(var n="",o=r.getRandomUint,s=r.isUint(t)?t:6,a=i.length,c=0;c<s;c++)n+=i[o(a)];return n},getTime:function(){return(new Date).toISOString()},getKeyByValue:function(e,t){if(r.isObject(e))return Object.keys(e).filter((function(r){return e[r]===t}))[0]},enumContainsValue:function(e,t){for(var r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&e[r]===t)return!0;return!1},enumToString:function(e){var t=[];for(var i in e)if(Object.prototype.hasOwnProperty.call(e,i)){var n=e[i];r.isFunction(n)||t.push(e[i])}return t.join()},getVersionText:function(e,t,r){var i="Your browser: "+e+" v."+t;return r&&(i+=" (mobile)"),i},getSupportText:function(e,t,i,n){var o=r.getVersionText(e,t,i),s="";return n>0&&(s=o+" is not supported.",n>1&&(s=o+" is not fully supported. ",s+="You may try to use it, but it may show issues. Please report any issues to https://webrtc.live.")),s},createBrowserInfo:function(){var e="";screen.width&&(e+=(screen.width?screen.width:"")+" x "+(screen.height?screen.height:""));var t,i,n,o=navigator.appVersion,s=navigator.userAgent,a=navigator.appName,c=""+parseFloat(o),d=parseInt(o,10);-1!==(i=s.indexOf("Opera"))&&(a="Opera",c=s.substring(i+6),-1!==(i=s.indexOf("Version"))&&(c=s.substring(i+8))),-1!==(i=s.indexOf("OPR/"))?(a="Opera",c=s.substring(i+4)):-1!==(i=s.indexOf("MSIE"))?(a="Microsoft Internet Explorer",c=s.substring(i+5)):"Netscape"===a&&-1!==(i=s.indexOf("Trident/"))?(a="Microsoft Internet Explorer",c=s.substring(i+8),-1!==(i=s.indexOf("rv:"))&&(c=s.substring(i+3))):"Netscape"===a&&-1!==(i=s.indexOf("Edge/"))?(a="Microsoft Edge",c=s.substring(i+5)):-1!==(i=s.indexOf("Chrome"))?(a="Chrome",c=s.substring(i+7)):-1!==(i=s.indexOf("Safari"))?(a="Safari",c=s.substring(i+7),-1!==(i=s.indexOf("Version"))&&(c=s.substring(i+8)),-1!==s.indexOf("CriOS")&&(a="Chrome")):-1!==(i=s.indexOf("Firefox"))?(a="Firefox",c=s.substring(i+8)):(t=s.lastIndexOf(" ")+1)<(i=s.lastIndexOf("/"))&&(a=s.substring(t,i),c=s.substring(i+1),a.toLowerCase()===a.toUpperCase()&&(a=navigator.appName)),-1!==(n=c.indexOf(";"))&&(c=c.substring(0,n)),-1!==(n=c.indexOf(" "))&&(c=c.substring(0,n)),-1!==(n=c.indexOf(")"))&&(c=c.substring(0,n)),d=parseInt(""+c,10),isNaN(d)&&(c=""+parseFloat(o),d=parseInt(o,10));var l=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(o),u=navigator.cookieEnabled;void 0!==navigator.cookieEnabled||u||(document.cookie="testcookie",u=-1!==document.cookie.indexOf("testcookie"));for(var p="Unknown",h=[{os:"Windows XP",regex:/(Windows NT 5.1|Windows XP)/},{os:"Windows Server 2003",regex:/Windows NT 5.2/},{os:"Windows Vista",regex:/Windows NT 6.0/},{os:"Windows 7",regex:/(Windows 7|Windows NT 6.1)/},{os:"Windows 8.1",regex:/(Windows 8.1|Windows NT 6.3)/},{os:"Windows 8",regex:/(Windows 8|Windows NT 6.2)/},{os:"Windows NT 4.0",regex:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},{os:"Windows ME",regex:/Windows ME/},{os:"Android",regex:/Android/},{os:"Open BSD",regex:/OpenBSD/},{os:"Sun OS",regex:/SunOS/},{os:"Linux",regex:/(Linux|X11)/},{os:"iOS",regex:/(iPhone|iPad|iPod)/},{os:"Mac OS X",regex:/Mac OS X/},{os:"Mac OS",regex:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},{os:"QNX",regex:/QNX/},{os:"UNIX",regex:/UNIX/},{os:"BeOS",regex:/BeOS/},{os:"OS/2",regex:/OS\/2/},{os:"Search Bot",regex:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}],m=0,g=h.length;m<g;++m)if(h[m].regex.test(s)){p=h[m].os;break}var v="Unknown";switch(/Windows/.test(p)&&(v=(/Windows (.*)/.exec(p)||[])[1],p="Windows"),p){case"Mac OS X":v=(/Mac OS X (10[\.\_\d]+)/.exec(s)||[])[1];break;case"Android":v=(/Android ([\.\_\d]+)/.exec(s)||[])[1];break;case"iOS":v=(v=/OS (\d+)_(\d+)_?(\d+)?/.exec(o)||[])[1]+"."+v[2]+"."+(0|v[3])}r.browserInfo={screenSize:e,browser:a,browserVersion:c,mobile:l,os:p,osVersion:v,cookiesEnabled:u}}};return r.createBrowserInfo(),r}.apply(t,[]))||(e.exports=i)},function(e,t,r){var i,n;i=[r(0),r(4),r(2),r(8),r(18)],void 0===(n=function(e,t,r,i,n){"use strict";var o=e.getTime,s=e.stringifyJSON,a=e.isObject,c=e.isNumber,d=e.isIntInRange,l=e.isString,u=e.isEmpty,p=0,h={_console:{loggers:[],level:t.LOG_LEVEL.INFO},_graylog:{loggers:[],credentials:{accountId:"",accountKey:""},baseUrl:"https://glog1.nanocosmos.de/gelf/"},_globalPrefix:"nanowebrtc",setConfig:function(e){if(console.log(o()+": ["+h._globalPrefix+"][LoggerController] - setConfig("+s(e)+")"),!a(e)||u(e))throw r.TypeNotValidError("config","Object");if(a(e.console)){if(c(e.console.level)&&d(e.console.level,t.LOG_LEVEL.DISABLED,t.LOG_LEVEL.VERBOSE))h._console.level=e.console.level;else{var i=r.ValueNotValidError("config.console.level","0|1|2|3|4");console.error(o()+": ["+h._globalPrefix+"][LoggerController] - setConfig(): "+s(i))}h._console.loggers.forEach((function(e){e._level=h._console.level}))}if(a(e.graylog)){if(!a(e.graylog.credentials)||u(e.graylog.credentials))throw r.TypeNotValidError("config.graylog.credentials","Object");if(!l(e.graylog.credentials.accountId))throw r.TypeNotValidError("config.graylog.credentials.accountId","String");if(0==e.graylog.credentials.accountId.length)throw r.ValueNotValidError("config.graylog.credentials.accountId","1..n characters");if(!l(e.graylog.credentials.accountKey))throw r.TypeNotValidError("config.graylog.credentials.accountKey","String");if(0==e.graylog.credentials.accountKey.length)throw r.TypeNotValidError("config.graylog.credentials.accountKey","1..n characters");h._graylog.credentials.accountId=""+e.graylog.credentials.accountId,h._graylog.credentials.accountKey=""+e.graylog.credentials.accountKey,h._graylog.loggers.forEach((function(e){e._credentials.accountId=h._graylog.credentials.accountId,e._credentials.accountKey=h._graylog.credentials.accountKey}))}},create:function(a,c){if(e.enumContainsValue(t.LOGGER_TYPE,c)){var d=void 0;return p++,c===t.LOGGER_TYPE.GRAYLOG?(d=new n(h._globalPrefix,h._console.level,h._graylog.baseUrl,h._graylog.credentials.accountId,h._graylog.credentials.accountKey,p),h._graylog.loggers.push(d)):(d=new i(h._globalPrefix,a,h._console.level,p),h._console.loggers.push(d)),d}var l=r.EnumValueNotValidError(c,t.LOGGER_TYPE);console.log(o()+": ["+h._globalPrefix+"][LoggerController] - create(): "+s(l))},delete:function(e){for(var t,r,i=!1,n=0;n<h._console.loggers.length;n++)if(t=h._console.loggers[n],e._id===t._id){h._console.loggers.splice(n,1),i=!0;break}if(i)return i;for(var o=0;o<h._graylog.loggers.length;o++)if(r=h._graylog.loggers[o],e._id===r._id){h._graylog.loggers.splice(o,1),i=!0;break}return i}};return h}.apply(t,i))||(e.exports=n)},function(e,t,r){var i,n;i=[r(0)],void 0===(n=function(e){"use strict";var t=e.enumToString,r=function(e,t,r,i){this.name=e,this.type="NanoError",this.code=t,this.message=r,this.userinfo=i,this.toJSON=function(){return{error:{name:this.name,type:this.type,code:this.errorCode,message:this.message,userinfo:this.userinfo}}}},i=function(){};return i.GeneralError=function(e){return new r("GeneralError",1e3,e=e)},i.TypeNotValidError=function(e,t){return new r("TypeNotValidError",1001,'"'+e+'" type not valid',{value:e,expected_type:t})},i.ValueNotValidError=function(e,t){return new r("ValueNotValidError",1002,'"'+e+'" value not valid',{value:e,expected_value:t})},i.EnumValueNotValidError=function(e,i){return new r("EnumValueNotValidError",1003,'"'+e+'" enum value not valid',{value:e,expected_values:t(i)})},i.ObjectNotExistError=function(e,t){return new r("ObjectNotExistError",1004,'"'+e+'" object not exist',{value:e,expected_type:t})},i.FunctionNotDefinedError=function(e){return new r("FunctionNotDefinedError",1005,'"'+e+'" function not defined',{func:e})},i.RequestError=function(e,t){return new r("RequestError",2e3,"",{status:e,statusText:t})},i.WebSocketError=function(e,t){return new r("WebSocketError",3e3,e,{server:t})},i.WrongStateError=function(e){return new r("WrongStateError",3001,"Wrong state",{state:e})},i.CreateWebSocketError=function(e,t){return new r("CreateWebSocketError",3002,e,{server:t})},i.SignInError=function(e){return new r("SignInError",4e3,"Sign in failed",{reason:e})},i.NotSignedInError=function(){return new r("NotSignedInError",4001,"Session not signed in")},i.StartBroadcastError=function(e){return new r("StartBroadcastError",5001,"Starting broadcast failed",{reason:e})},i.BroadcastError=function(e){return new r("BroadcastError",5002,"Broadcast failed",{reason:e})},i.StopBroadcastError=function(e){return new r("StopBroadcastError",5003,"Stopping broadcast failed",{reason:e})},i.DeviceBlockedError=function(e,t){return new r("DeviceBlockedError",6e3,"Media stream received, but no "+(e?e+" ":"")+"data from device"+(t?' "'+t+'". ':". ")+"Device could be in use from another application",{kind:e,label:t})},i.MediaStreamTrackError=function(){return new r("MediaStreamTrackError",6001,"Media stream received, but no tracks",{})},i.MediaStreamNotFoundError=function(){return new r("MediaStreamNotFoundError",6002,"Media stream not found",{})},i.MediaStreamNotRemovedError=function(){return new r("MediaStreamNotRemovedError",6003,"Media stream not removed",{})},i.DevicesNotFoundError=function(){return new r("DevicesNotFoundError",6004,'Devices not set for "getUserMedia"',{})},i.GetUserMediaError=function(e,t){var i=e&&e.constraint?e.constraint:void 0,n=e&&e.name&&!i?e.name:i?"OverconstrainedError":"GetUserMediaError",o=e&&e.message?e.message:"Failed to get user / display media.";return new r(n,6005,o,{constraint:i,retry:t})},i.EnumerateDevicesError=function(e){var t=e&&e.name?e.name:"EnumerateDevicesError",i=e&&e.message?e.message:"Failed to enumerate devices.";return new r(t,6006,i,{})},i.GetDisplayMediaError=function(e,t){return new r(e,6008,t=t||'Failed to call "getDisplayMedia".',{})},i.ServerError=function(e){return new r("ServerError",7e3,"An error has occurred on server side",{reason:e})},i.composeEvent=function(e,t){var r="",i=void 0,n="",o=void 0;switch(e.name){case"GeneralError":r="GeneralError",n=e.message||"General error";break;case"TypeNotValidError":r="TypeNotValidError",n=e.message;break;case"ValueNotValidError":r="ValueNotValidError",n=e.message;break;case"EnumValueNotValidError":r="EnumValueNotValidError",n=e.message;break;case"ObjectNotExistError":r="ObjectNotExistError",n=e.message;break;case"FunctionNotDefinedError":e.userinfo&&e.userinfo.func&&(-1!==e.userinfo.func.indexOf("getUserMedia")?r="GetUserMediaError":-1!==e.userinfo.func.indexOf("getDisplayMedia")?r="GetDisplayMediaError":-1!==e.userinfo.func.indexOf("enumerateDevices")&&(r="EnumerateDevicesError"),n=e.userinfo.func+" not defined");break;case"RequestError":r="RequestError",n=e.message;break;case"WebSocketError":r="RequestError";break;case"WrongStateError":r="WrongStateError",n=e.message;break;case"SignInError":r="SignInError",n=e.message;break;case"NotSignedInError":r="NotSignedInError",n=e.message;break;case"StartBroadcastError":r="StartBroadcastError",n=e.message;break;case"BroadcastError":r="BroadcastError",n=e.message;break;case"StopBroadcastError":r="StopBroadcastError",n=e.message;break;case"DeviceBlockedError":case"MediaStreamTrackError":r="MediaStreamError",n=e.message;break;case"MediaStreamNotFoundError":r="NoStreamError",n="No stream is available for the device.";break;case"MediaStreamNotRemovedError":r="MediaStreamNotRemovedError",n=e.message;break;case"DevicesNotFoundError":r="NoDeviceError",n='No device is available for "getUserMedia".';break;case"GetUserMediaError":case"PermissionDenied":case"NotAllowedError":case"NotReadableError":case"NotFoundError":case"OverconstrainedError":case"AbortError":case"GetMediaError":case"NoDeviceError":case"NoStreamError":r=e.name,n=e.message,i=e.userinfo.constraint,o=e.userinfo.retry;break;case"EnumerateDevicesError":r="EnumerateDevicesError",n=e.message;break;case"ServerError":r="ServerError",n=e.message;break;case"WebrtcServerError":r="WebrtcServerError",n=e.message;break;default:r=e.name||"UnknownError",n=e.message||"Unknown error."}var s={};return s.name=t||e.name,s.data={error:r+": "+n,message:n,text:n,constraint:i,errorType:r,retry:o},s.error={name:e.name,type:e.type,code:e.code,message:e.message,text:e.message,userinfo:e.userinfo},s},i}.apply(t,i))||(e.exports=n)},function(e,t,r){var i;
/*!
 * EventEmitter v4.2.11 - git.io/ee
 * Unlicense - http://unlicense.org/
 * Oliver Caldwell - http://oli.me.uk/
 * @preserve
 */(function(){"use strict";function t(){}var n=t.prototype,o=this,s=o.EventEmitter;function a(e,t){for(var r=e.length;r--;)if(e[r].listener===t)return r;return-1}function c(e){return function(){return this[e].apply(this,arguments)}}n.getListeners=function(e){var t,r,i=this._getEvents();if(e instanceof RegExp)for(r in t={},i)i.hasOwnProperty(r)&&e.test(r)&&(t[r]=i[r]);else t=i[e]||(i[e]=[]);return t},n.flattenListeners=function(e){var t,r=[];for(t=0;t<e.length;t+=1)r.push(e[t].listener);return r},n.getListenersAsObject=function(e){var t,r=this.getListeners(e);return r instanceof Array&&((t={})[e]=r),t||r},n.addListener=function(e,t){var r,i=this.getListenersAsObject(e),n="object"==typeof t;for(r in i)i.hasOwnProperty(r)&&-1===a(i[r],t)&&i[r].push(n?t:{listener:t,once:!1});return this},n.on=c("addListener"),n.addOnceListener=function(e,t){return this.addListener(e,{listener:t,once:!0})},n.once=c("addOnceListener"),n.defineEvent=function(e){return this.getListeners(e),this},n.defineEvents=function(e){for(var t=0;t<e.length;t+=1)this.defineEvent(e[t]);return this},n.removeListener=function(e,t){var r,i,n=this.getListenersAsObject(e);for(i in n)n.hasOwnProperty(i)&&-1!==(r=a(n[i],t))&&n[i].splice(r,1);return this},n.off=c("removeListener"),n.addListeners=function(e,t){return this.manipulateListeners(!1,e,t)},n.removeListeners=function(e,t){return this.manipulateListeners(!0,e,t)},n.manipulateListeners=function(e,t,r){var i,n,o=e?this.removeListener:this.addListener,s=e?this.removeListeners:this.addListeners;if("object"!=typeof t||t instanceof RegExp)for(i=r.length;i--;)o.call(this,t,r[i]);else for(i in t)t.hasOwnProperty(i)&&(n=t[i])&&("function"==typeof n?o.call(this,i,n):s.call(this,i,n));return this},n.removeEvent=function(e){var t,r=typeof e,i=this._getEvents();if("string"===r)delete i[e];else if(e instanceof RegExp)for(t in i)i.hasOwnProperty(t)&&e.test(t)&&delete i[t];else delete this._events;return this},n.removeAllListeners=c("removeEvent"),n.emitEvent=function(e,t){var r,i,n,o,s=this.getListenersAsObject(e);for(o in s)if(s.hasOwnProperty(o))for(n=(r=s[o].slice(0)).length;n--;)!0===(i=r[n]).once&&this.removeListener(e,i.listener),i.listener.apply(this,t||[])===this._getOnceReturnValue()&&this.removeListener(e,i.listener);return this},n.trigger=c("emitEvent"),n.emit=function(e){var t=Array.prototype.slice.call(arguments,1);return this.emitEvent(e,t)},n.emitSimple=function(e,t,r){return this.emitEvent(e,[{name:e||"AnonymousEvent",data:t||{},error:r||{}}])},n.setOnceReturnValue=function(e){return this._onceReturnValue=e,this},n._getOnceReturnValue=function(){return!this.hasOwnProperty("_onceReturnValue")||this._onceReturnValue},n._getEvents=function(){return this._events||(this._events={})},t.noConflict=function(){return o.EventEmitter=s,t},void 0===(i=function(){return t}.call(o,r,o,e))||(e.exports=i)}).call(this)},function(e,t,r){var i;void 0===(i=function(){"use strict";return{STREAM_NOMEDIASTREAM:1,STREAM_ACTIVE:2,STREAM_INACTIVE:3,STREAM_ENDED:4,MEDIA_SOURCES:{CAMERA:"camera",SCREEN:"screen"},ELEMENT_TYPES:{VIDEO:"video",AUDIO:"audio"},LOGGER_TYPE:{CONSOLE:"console",GRAYLOG:"graylog"},LOG_LEVEL:{DISABLED:0,ERROR:1,WARNING:2,INFO:3,VERBOSE:4},BROADCAST_STATE:{IDLE:1,INITIALIZED:2,STARTED:3,SIGNALING:4,CONNECTED:5,BROADCASTING:6,RECONNECTING:7,DISCONNECTED:8,FAILED:9,STOPPED:10},CHATPEER_STATE:{IDLE:1,INITIALIZED:2,SIGNALING:3,SIGNALLING_DONE:4,CALLING:5,NEGOTIATION_NEEDED:7,DISCONNECTED:8,FAILED:9,STOPPED:10},SCREEN_CAPTURE_BROWSER:{CHROME:"chrome",FIREFOX:"firefox"},EVENT_NAMES:{webcast:["SignInSuccess","SignInError","ServerError","SignOutSuccess","SignOutError","SetConfigError","ReceivedServerStats","ReceivedWebRTCStats","StartBroadcastSuccess","StartBroadcastError","BroadcastStatus","BroadcastError","StopBroadcastSuccess","StopBroadcastError","Error","ReceivedDeviceList","SetVideoDeviceError","SetAudioDeviceError","GetSelectedVideoDeviceError","GetSelectedAudioDeviceError","GetSelectedDeviceError","StartPreviewSuccess","StartPreviewError","StopPreviewSuccess","StopPreviewError","MuteDeviceError","StreamTrackEnded"],chat:["EnterRoomSuccess","EnterRoomError","LeaveRoomSuccess","LeaveRoomError","InvokeCall","HangUpCall","AnswerCall","DeclineCall","PeerListUpdated","CallIncoming","CallDeclined","CallActive","RemoteStreamError"]}}}.apply(t,[]))||(e.exports=i)},function(e,t,r){var i,n;i=[r(3),r(17),r(6),r(0),r(2),r(1)],void 0===(n=function(e,t,r,i,n,o){"use strict";var s=i.stringifyJSON,a=i.isObject,c=i.isString,d={IDLE:1,SIGNED_IN:2,SIGNED_OUT:3,RECONNECTING:4,FAILED:5};function l(){e.call(this),this._sessionId=void 0,this._serverUrl=void 0,this._state=d.IDLE,this._logger=o.create("Session","console"),this._websocketClient=new t}var u=l.prototype=Object.create(e.prototype);return u.isSignedIn=function(){return this._state===d.SIGNED_IN},u.signIn=function(e){this._logger.verbose("signIn("+s(e)+")");if(this.isSignedIn())return Promise.reject(n.SignInError("Already signed in"));if(!a(e))return Promise.reject(n.TypeNotValidError("data","Object"));if(!e.server||!c(e.server))return Promise.reject(n.TypeNotValidError("data.serverUrl","String"));if(e.bintuApiKey&&!c(e.bintuApiKey))return Promise.reject(n.TypeNotValidError("data.bintuApiKey","String"));if(e.token&&!c(e.token))return Promise.reject(n.TypeNotValidError("data.token","String"));this._serverUrl=e.server;var t={user_name:"defaultUserName",room:"defaultRoom"};e.bintuApiKey&&(t.bintu_api_key=e.bintuApiKey),e.token&&(t.token=e.token),t.api_version=r.webrtc.release_version;var i=this;return this._websocketClient.connect(this._serverUrl,this._onMessage.bind(this)).then((function(){return i._websocketClient.sendMessage("sign_in",t)})).then((function(e){return i._logger.verbose("signIn(): Signed in: "+s(e)),i._sessionId=e.session_id,i._setState(d.SIGNED_IN),{data:{server:i._serverUrl,userId:e.user_id,iceServers:e.ice_servers?e.ice_servers:void 0}}})).catch((function(e){return i._logger.error("signIn(): "+s(e)),"CreateWebSocketError"!==e.name&&i._websocketClient.close(),Promise.reject(e)}))},u.signOut=function(){this._logger.verbose("signOut(), sessionId"+this._sessionId);if(!this.isSignedIn())return Promise.reject(n.NotSignedInError());var e=this;return this._websocketClient.sendMessage("sign_out",{session_id:this._sessionId}).then((function(t){return e._logger.verbose("signOut(): "+t),e.removeAllListeners(),e._sessionId=void 0,e._setState(d.SIGNED_OUT),e._websocketClient.close(),t})).catch((function(t){return e._logger.error("signOut(): "+t),e._websocketClient.close(),e._sessionId=void 0,Promise.reject(t)}))},u.echo=function(e){return this._websocketClient.sendMessage("echo",{session_id:this._sessionId,message:e})},u.sendSignalingMessage=function(e){this._logger.verbose("sendSignalingMessage("+s(e)+")");if(!this.isSignedIn())return Promise.reject(n.NotSignedInError());var t=this;return this._checkPeerMessage(e).then((function(){return t._websocketClient.sendMessage("signaling_message",e)})).catch((function(e){return t._logger.error("sendSignalingMessage(): "+s(e)),Promise.reject(e)}))},u.enterRoom=function(e){return this._logger.verbose("enterRoom("+s(e)+"), sessionId: "+this._sessionId),this.isSignedIn()?a(e)?c(e.roomName)?c(e.userName)?this._checkRoomName(e.roomName)?this._websocketClient.sendMessage("enter_room",{session_id:this._sessionId,room_name:e.roomName,user_name:e.userName}):Promise.reject(n.ValueNotValidError("data.room","Alphanumeric characters / underscore (_) / dash (-) / dot (.)")):Promise.reject(n.TypeNotValidError("data.userName","String")):Promise.reject(n.TypeNotValidError("data.roomName","String")):Promise.reject(n.TypeNotValidError("data","Object")):Promise.reject(n.NotSignedInError())},u.leaveRoom=function(e){return this._logger.verbose("leaveRoom("+s(e)+"), sessionId: "+this._sessionId),this.isSignedIn()?a(e)?c(e.roomName)?this._websocketClient.sendMessage("leave_room",{session_id:this._sessionId,room_name:e.roomName}):Promise.reject(n.TypeNotValidError("data.roomName","String")):Promise.reject(n.TypeNotValidError("data","Object")):Promise.reject(n.NotSignedInError())},u.callUser=function(e){return this._logger.verbose("callUser("+s(e)+")"),this.isSignedIn()?a(e)?c(e.userId)?c(e.roomName)?this._websocketClient.sendMessage("call_user",{session_id:this._sessionId,user_id:e.userId,room_name:e.roomName}):Promise.reject(n.TypeNotValidError("data.roomName","String")):Promise.reject(n.TypeNotValidError("data.userId","String")):Promise.reject(n.TypeNotValidError("data","Object")):Promise.reject(n.NotSignedInError())},u.answerCall=function(e){return this._logger.verbose("answerCall("+s(e)+")"),this.isSignedIn()?a(e)?c(e.userId)?c(e.roomName)?this._websocketClient.sendMessage("answer_call",{session_id:this._sessionId,user_id:e.userId,room_name:e.roomName}):Promise.reject(n.TypeNotValidError("data.roomName","String")):Promise.reject(n.TypeNotValidError("data.userId","String")):Promise.reject(n.TypeNotValidError("data","Object")):Promise.reject(n.NotSignedInError())},u.declineCall=function(e){return this._logger.verbose("declineCall("+s(e)+")"),this.isSignedIn()?a(e)?c(e.userId)?c(e.roomName)?this._websocketClient.sendMessage("decline_call",{session_id:this._sessionId,user_id:e.userId,room_name:e.roomName}):Promise.reject(n.TypeNotValidError("data.roomName","String")):Promise.reject(n.TypeNotValidError("data.userId","String")):Promise.reject(n.TypeNotValidError("data","Object")):Promise.reject(n.NotSignedInError())},u.hangUpCall=function(e){return this._logger.verbose("hangUpCall("+s(e)+")"),this.isSignedIn()?this._websocketClient.sendMessage("hangup_call",{session_id:this._sessionId,user_id:e.userId,room_name:e.roomName}):Promise.reject(n.NotSignedInError())},u.startBroadcast=function(e){this._logger.verbose("startBroadcast("+s(e)+")");if(!this.isSignedIn())return Promise.reject(n.NotSignedInError());if(!a(e))return Promise.reject(n.TypeNotValidError("broadcastParams","Object"));e.session_id=this._sessionId;var t=this;return this._websocketClient.sendMessage("start_broadcast",e).catch((function(e){t._logger.error("startBroadcast(): "+s(e));var r=e.error;return"WebrtcServerError"===r.name&&(r.type="NanoError"),Promise.reject(r)}))},u.stopBroadcast=function(e){this._logger.verbose("stopBroadcast("+s(e)+")");if(!this.isSignedIn())return Promise.reject(n.NotSignedInError());if(!a(e))return Promise.reject(n.TypeNotValidError("data","Object"));if(!c(e.sender_peer))return Promise.reject(n.TypeNotValidError("data.sender_peer","String"));if(!c(e.receiver_peer))return Promise.reject(n.TypeNotValidError("data.receiver_peer","String"));var t=this;return this._checkPeerMessage(e).then(t._websocketClient.sendMessage("stop_broadcast",{session_id:t._sessionId,sender_peer:e.sender_peer,receiver_peer:e.receiver_peer})).catch((function(e){return t._logger.error("stopBroadcast(): "+s(e)),Promise.reject(e)}))},u.sendMetaData=function(e){this._logger.verbose("sendMetaData("+s(e)+")");if(!this.isSignedIn())return Promise.reject(n.NotSignedInError());var t=this;return this._checkPeerMessage(e).then(t._websocketClient.sendMessage("send_metadata",e)).catch((function(e){return t._logger.error("sendMetaData(): "+s(e)),Promise.reject(e)}))},u.status=function(){this._logger.verbose("status()");if(!this.isSignedIn())return Promise.reject(n.NotSignedInError());var e=this;return this._websocketClient.sendMessage("status",{}).catch((function(t){return e._logger.error("status(): "+s(t)),Promise.reject(t)}))},u._onMessage=function(e){this._logger.verbose("_onMessage("+JSON.stringify(e)+")");var t;if(e){if(e.receiver_peer)return t=e.receiver_peer,void this.emit("receiver_peer_"+t,e);switch(e.type){case"room_update":case"call_incoming":case"call_declined":case"start_as_caller":case"hang_up":return this.emit("RoomMessage",e);case"close":this._state!==d.SIGNED_OUT&&(this.emit("SessionMessage",{type:"close",reason:"disconnect"}),this._setState(d.IDLE));break;default:this._logger.warning("_onMessage(): Unhandled message received: "+e)}}},u._setState=function(e){this._logger.verbose("_setState("+e+")");if(e!==this._state){var t=this._state;this._state=e;var r="_setState(): State: "+i.getKeyByValue(d,t)+" -> "+i.getKeyByValue(d,this._state);this._logger.verbose(r)}},u._checkPeerMessage=function(e){return this._logger.verbose("_checkPeerMessage("+s(e)+")"),a(e)?e.sender_peer?e.receiver_peer?Promise.resolve():Promise.reject(n.TypeNotValidError("message.receiver_peer","String")):Promise.reject(n.TypeNotValidError("message.sender_peer","String")):Promise.reject(n.TypeNotValidError("message","Object"))},u._checkRoomName=function(e){return/^([a-zA-Z0-9_\-.]{1,})$/gm.test(e)},l}.apply(t,i))||(e.exports=n)},function(e,t,r){var i;
/**
 * @license WebRTC Release Version 5
 * Copyright (c) 2016-2019 nanocosmos IT GmbH. All rights reserved.
 * http://www.nanocosmos.de
 */void 0===(i=function(){"use strict";return JSON.parse(JSON.stringify({webrtc:{release_version:"5.7.3"}}))}.apply(t,[]))||(e.exports=i)},function(e,t,r){var i,n;i=[r(4),r(0),r(24),r(2),r(3),r(1)],void 0===(n=function(e,t,r,i,n,o){"use strict";var s=t.stringifyJSON,a=t.isObject,c=t.isBool,d=t.isFunction;function l(e){n.call(this),this._medias={local:[],remote:[]},this._constraints={},this._error=void 0,this._deviceController=e,this._logger=o.create("MediaController","console")}var u=l.prototype=Object.create(n.prototype);return u.getMediaForDevices=function(t,r){this._logger.verbose("getMediaForDevices("+s(t)+", "+r+")");var n="getMediaForDevices(): ",o=void 0,a=this;return new Promise((function(s,d){return a._verifyDevicesExistence(t).then((function(){return o=t.videoinput.videoDeviceConfig?t.videoinput.videoDeviceConfig.source:c(t.videoinput)?e.MEDIA_SOURCES.CAMERA:void 0,a._verifySourceValidity(o)})).then((function(){return a._deviceController.composeConstraints(t)})).then((function(e){return a._constraints=e,a._getMedia(o,e)})).then((function(e){var t=e.data.stream;a._error=void 0,a._reenumerateDevices(r).then((function(o){if(t)return a._deviceController.updateSelected(t,r),s({stream:e,devices:o});var c=a._deviceController._selected.videoinput,l=a._deviceController._selected.audioinput;if(!1!==c||!1!==l){var u=i.MediaStreamNotFoundError(),p=i.composeEvent(u);return a._logger.error(n+JSON.stringify(u)),d(p)}}))})).catch((function(e){var t=i.composeEvent(e);return a._logger.error(n+JSON.stringify(e)),d(t)}))}))},u.addLocalMedia=function(e){this._logger.verbose("addLocalMedia("+s(e)+")");try{var t=new r(e)}catch(e){var n=i.composeEvent(e);return this._logger.error("addLocalMedia(): "+JSON.stringify(e)),Promise.reject(n)}var o=t.kind;return this._medias[o].push(t),Promise.resolve(t)},u.addRemoteMedia=function(e){this._logger.verbose("addRemoteMedia("+e+")");try{var t=new r(e)}catch(e){var n=i.composeEvent(e);return this._logger.error("addRemoteMedia(): "+JSON.stringify(e)),Promise.reject(n)}var o=t.kind;return this._medias[o].push(t),this._setupMedia(t)},u.removeMedia=function(e){this._logger.verbose("removeMedia("+e+")");for(var t=this.getLocalMedias(),r=0;r<t.length;r++){var i=t[r];i.stream.id===e&&(i.unbind(),t.splice(r,1))}var n=this.getRemoteMedias();for(r=0;r<n.length;r++){var o=n[r];o.stream.id===e&&(o.unbind(),n.splice(r,1))}},u.removeRemoteMedias=function(){this._logger.verbose("removeRemoteMedias()");for(var e=this._medias.remote,t=0;t<e.length;t++){e[t].unbind(),e.splice(t,1)}if(0==e.length)return Promise.resolve({data:{}});var r=i.MediaStreamNotRemovedError();return this._logger.error("removeRemoteMedias(): "+JSON.stringify(r)),Promise.reject(r)},u.removeLocalMedias=function(){this._logger.verbose("removeLocalMedias()");for(var e=this._medias.local,t=0;t<e.length;t++){e[t].unbind(),e.splice(t,1)}if(0==e.length)return Promise.resolve({data:{stream:null}});var r=i.MediaStreamNotRemovedError(),n=i.composeEvent(r);return this._logger.error("removeLocalMedias(): "+JSON.stringify(r)),Promise.reject(n)},u.getLocalMedias=function(){return this._logger.verbose("getLocalMedias()"),this._medias.local},u.getRemoteMedias=function(){return this._logger.verbose("getRemoteMedias()"),this._medias.remote},u.muteVideoTracks=function(e){this._logger.verbose("muteVideoTracks("+e+")"),this._muteTracks("videoinput",e)},u.muteAudioTracks=function(e){this._logger.verbose("muteAudioTracks("+e+")"),this._muteTracks("audioinput",e)},u.muteTracks=function(e){this._logger.verbose("muteTracks("+s(e)+")");var t="muteTracks(): ";if(!a(e)){var r=i.TypeNotValidError("config","Object");return this._logger.error(t+JSON.stringify(r)),Promise.reject(r)}if(void 0===e.kind||"videoinput"!==e.kind&&"audioinput"!==e.kind){r=i.ValueNotValidError("config.kind","video/audio");return this._logger.error(t+JSON.stringify(r)),Promise.reject(r)}if(void 0===e.mute||!c(e.mute)){r=i.TypeNotValidError("config.mute","Boolean");return this._logger.error(t+JSON.stringify(r)),Promise.reject(r)}return this._muteTracks(e.kind,e.mute),Promise.resolve({data:{}})},u._getMedia=function(t,r){this._logger.verbose("_getMedia("+t+", "+s(r)+")");var i=this;return this._verifySourceValidity(t).then((function(){return i._getReadyForMedia()})).then((function(){return t===e.MEDIA_SOURCES.CAMERA?i._getUserMedia(r):t===e.MEDIA_SOURCES.SCREEN?i._getDisplayMedia(r):void 0})).then((function(e){return i.addLocalMedia(e)})).then((function(e){return e.bind(i),i._setupMedia(e)})).catch((function(e){var t="_getMedia(): "+JSON.stringify(e);return i._logger.error(t),Promise.reject(e)}))},u._getUserMedia=function(e){this._logger.verbose("_getUserMedia("+s(e)+")");var t="_getUserMedia(): ",r=this;return this._verifyGetUserMediaExistence().then((function(t){return t.getUserMedia(e)})).then((function(e){return Promise.resolve({stream:e,kind:"local"})})).catch((function(e){if(!e){var n=i.ObjectNotExistError("error","Error");return r._logger.error(t+JSON.stringify(n)),Promise.reject(n)}if("NanoError"===e.type)return r._logger.error(t+JSON.stringify(e)),Promise.reject(e);var o=!r._error||r._error&&"OverconstrainedError"!==r._error.name;n=i.GetUserMediaError(e,o);return r._error=n,r._logger.error(t+JSON.stringify(n)),Promise.reject(n)}))},u._getDisplayMedia=function(e){this._logger.verbose("_getDisplayMedia("+s(e)+")");var r="_getDisplayMedia(): ",n="Chrome"===t.browserInfo.browser,o=this;return this._verifyGetDisplayMediaExistence().then((function(t){return t.getDisplayMedia({video:e.video,audio:!n&&e.audio})})).then((function(t){return n&&e.audio?o._getUserMedia({video:!1,audio:e.audio}).then((function(e){return o._addAudioToStream(e,t)})):t})).then((function(e){return Promise.resolve({stream:e,kind:"local"})})).catch((function(e){if(!e){var t=i.ObjectNotExistError("error","Error");return o._logger.error(r+JSON.stringify(t)),Promise.reject(t)}if("NanoError"===e.type)return o._logger.error(r+JSON.stringify(e)),Promise.reject(e);t=i.GetUserMediaError(e);return o._logger.error(r+JSON.stringify(t)),Promise.reject(t)}))},u._getReadyForMedia=function(){this._logger.verbose("_getReadyForMedia()");var e=this.getLocalMedias()[0];return e&&this.removeMedia(e.stream.id),Promise.resolve()},u._setupMedia=function(e){this._logger.verbose("_setupMedia("+s(e)+")");var t="_setupMedia(): ",r=this;return new Promise((function(n,o){var s=e.getVideoTracks(),a=e.getAudioTracks();if(!s&&!a){p=i.MediaStreamTrackError();return r._logger.error(t+JSON.stringify(p)),o(p)}for(var c=[].concat(s).concat(a),d=!0,l=0;l<c.length;l++){var u=c[l];if(u.readyState&&(!d||"live"!==u.readyState)){d=!1;var p=i.DeviceBlockedError(u.kind,u.label);return r._logger.error(t+JSON.stringify(p)),o(p)}}r._composeMetadata(e).then((function(e){return n(e)})).catch((function(e){return r._logger.error(t+JSON.stringify(e)),o(e)}))}))},u._muteTracks=function(e,t){this._logger.verbose("_muteTracks("+e+", "+t+")");var r=this.getLocalMedias()[0];r&&r.muteTracks(e,t)},u._composeMetadata=function(e){this._logger.verbose("_composeMetadata("+s(e)+")");var t="_composeMetadata(): ";if(!e){var r=i.ObjectNotExistError("media","Media");return this._logger.error(t+JSON.stringify(r)),Promise.reject(r)}var n=e.metadata;if(!n){r=i.ObjectNotExistError("metadata","Metadata");return this._logger.error(t+JSON.stringify(r)),Promise.reject(r)}var o=e.hasVideoTracks()||e.metadata.hasVideo,a=e.hasAudioTracks()||e.metadata.hasAudio,c=e.getVideoTracksSettings(),d=c?c.width:e.metadata.width,l=c?c.height:e.metadata.height,u=c?Object.prototype.hasOwnProperty.call(c,"frameRate")?c.frameRate:Object.prototype.hasOwnProperty.call(c,"framerate")?c.framerate:e.metadata.framerate:e.metadata.framerate;return n.hasVideo=o,n.hasAudio=a,n.width=d,n.height=l,n.framerate=Math.round(u),Promise.resolve({data:{stream:e.stream,metadata:n,constraints:this._constraints}})},u._addAudioToStream=function(e,t){this._logger.verbose("_addAudioToStream("+s(e)+", "+s(t)+")");var r="_addAudioToStream(): ";if(!e){var n=i.ObjectNotExistError("audio","MediaStream");return this._logger.error(r+JSON.stringify(n)),Promise.reject(n)}if(!t){n=i.ObjectNotExistError("streamInfo","MediaStream");return this._logger.error(r+JSON.stringify(n)),Promise.reject(n)}var o=e.stream.getAudioTracks()[0];return t.addTrack(o),Promise.resolve(t)},u._reenumerateDevices=function(e){return this._logger.verbose("_reenumerateDevices("+e+")"),this._deviceController.shouldReenumerate(e)?this._deviceController.enumerateDevices():Promise.resolve()},u._verifyDevicesExistence=function(e){this._logger.verbose("_verifyDevicesExistence("+s(e)+")");var t="_verifyDevicesExistence(): ";if(!e){var r=i.ObjectNotExistError("devices","Array");return this._logger.error(t+JSON.stringify(r)),Promise.reject(r)}if(!e.videoinput&&!e.audioinput){r=i.DevicesNotFoundError();return this._logger.error(t+JSON.stringify(r)),Promise.reject(r)}return Promise.resolve()},u._verifySourceValidity=function(r){this._logger.verbose("_verifySourceValidity("+r+")");if(t.enumContainsValue(e.MEDIA_SOURCES,r))return Promise.resolve();var n=i.EnumValueNotValidError(r,e.MEDIA_SOURCES);return this._logger.error("_verifySourceValidity(): "+JSON.stringify(n)),Promise.reject(n)},u._verifyGetUserMediaExistence=function(){this._logger.verbose("_verifyGetUserMediaExistence()");var e=navigator.mediaDevices;if(!e||!d(e.getUserMedia)){var t=i.FunctionNotDefinedError("getUserMedia");return this._logger.error("_verifyGetUserMediaExistence(): "+JSON.stringify(t)),Promise.reject(t)}return Promise.resolve(e)},u._verifyGetDisplayMediaExistence=function(){this._logger.verbose("_verifyGetDisplayMediaExistence()");var e=navigator.mediaDevices;if(!e||!d(e.getDisplayMedia)){var t=i.FunctionNotDefinedError("getDisplayMedia");return this._logger.error("_verifyGetDisplayMediaExistence(): "+JSON.stringify(t)),Promise.reject(t)}return Promise.resolve(e)},u._onTrackEnded=function(e){this._logger.verbose("_onTrackEnded("+s(e)+")"),this._logger.info("StreamTrackEnded"),this.emit("StreamTrackEnded",{track:e.target.kind,type:e.type,device:e.target.label})},l}.apply(t,i))||(e.exports=n)},function(e,t,r){var i,n;i=[r(0),r(4)],void 0===(n=function(e,t){"use strict";var r=e.getTime;return function(i,n,o,s){this._globalPrefix=i,this._label=n,this._level=o,this._id=s,this.error=function(e){this._log(e,t.LOG_LEVEL.ERROR)},this.warning=function(e){this._log(e,t.LOG_LEVEL.WARNING)},this.info=function(e){this._log(e,t.LOG_LEVEL.INFO)},this.debug=function(e){this._log(e,t.LOG_LEVEL.DEBUG)},this.verbose=function(e){this._log(e,t.LOG_LEVEL.VERBOSE)},this._log=function(i,n){if(this._level>=n)switch(e.isObject(i)&&(i=JSON.stringify(i,null," ")),i=r()+": ["+this._globalPrefix+"]["+this._label+"] - "+i,n){case t.LOG_LEVEL.ERROR:console.error(i);break;case t.LOG_LEVEL.WARNING:console.warn(i);break;case t.LOG_LEVEL.INFO:console.info(i);break;case t.LOG_LEVEL.VERBOSE:console.log(i)}}}}.apply(t,i))||(e.exports=n)},function(e,t,r){var i,n;i=[r(19),r(10),r(3),r(2),r(0),r(1),r(11)],void 0===(n=function(e,t,r,i,n,o,s){"use strict";var a=n.parseJSON,c=n.stringifyJSON,d=n.isFunction,l=n.isArray,u={offerToReceiveAudio:!0,offerToReceiveVideo:!0};function p(e,t){r.call(this),this._logger=o.create("PeerConnectionClient","console"),this._logger.verbose("PeerConnectionClient("+c(e)+", "+t+")");if(!l(e.peerConnectionConfig.iceServers)||0===e.peerConnectionConfig.iceServers.length){this._logger.warning("PeerConnectionClient(): params.peerConnectionConfig.iceServers parameter is malformed, must be an array with at least one entry")}this._params=e,this._startTime=t,this._pc=null,this._hasRemoteSdp=!1,this._messageQueue=[],this._isInitiator=!1,this._started=!1,this._closedIceConnectionStateSent=!1,this._create()}var h=p.prototype=Object.create(r.prototype);return h.isStarted=function(){return this._started},h.isInitiator=function(){return this._isInitiator},h._create=function(){this._logger.verbose("_create()");this.close();try{this._pc=new RTCPeerConnection(this._params.peerConnectionConfig,this._params.peerConnectionConstraints),this._bind(),this._logger.verbose("_create(): PeerConnectionCreated")}catch(e){this._onError("CreatePeerConnection",e)}},h.close=function(){this._logger.verbose("close()");var e=this;this._pc?(this._pc.close(),setTimeout((function(){e._closedIceConnectionStateSent||e.emitSimple("IceConnectionStateChange",{state:"closed"}),e._reset(),e._logger.verbose("close(): Peer connection closed"),o.delete(e._logger)}),500)):this._logger.verbose("close(): No PeerConnection")},h.addStream=function(e){this._logger.verbose("addStream("+c(e)+")");this._pc&&this._pc.addStream(e)},h.updateEncodingSettings=function(t,r){this._logger.verbose("updateEncodingSettings("+t+", "+r+")");var i="updateEncoderOptions(): ",n=this;e.setSenderBitrates(this._pc,{video:r||0,audio:t||0}).then((function(){n._logger.info(i+"Sucessfully set bitrates")})).catch((function(e){n._logger.warning(i+"Could not set bitrates "+e)}))},h.removeStream=function(e){var t,r,i;if(this._logger.verbose("removeStream("+c(e)+")"),this._pc)if(d(this._pc.removeTrack)&&d(this._pc.getSenders)){var n=e.getTracks(),o=this._pc.getSenders();for(t=0,i=o.length;t<i;++t)for(r=0,i=n.length;r<i;++r)o[t].track===n[r]&&this._pc.removeTrack(o[t])}else d(this._pc.removeStream)&&this._pc.removeStream(e)},h.startAsCaller=function(e){this._logger.verbose("startAsCaller("+c(e)+")");if(this._pc&&!this._started){this._isInitiator=!0,this._started=!0;var t=this._buildConstraints(e);this._logger.verbose("startAsCaller(): Sending offer to peer with constraints: \n'"+c(t));var r=this;this._pc.createOffer(t).then((function(e){return r._setLocalDescription(e)})).then((function(e){r.emitSimple("SignalingMessage",e)})).catch((function(e){r._logger.error("startAsCaller(): "+c(e)),r._onError("createOffer",e)}))}},h.startAsCallee=function(e){var t,r;if(this._logger.verbose("startAsCallee("+c(e)+")"),this._pc&&!this._started){if(this._isInitiator=!1,this._started=!0,e&&e.length>0)for(t=0,r=e.length;t<r;t++)this.queueSignalingMessage(e[t]);this._messageQueue.length>0&&this._drainMessageQueue()}},h.queueSignalingMessage=function(e){this._logger.verbose("queueSignalingMessage("+c(e)+")");var t=a(e);t&&(this._isInitiator&&"answer"===t.type||!this._isInitiator&&"offer"===t.type?(this._hasRemoteSdp=!0,this._messageQueue.unshift(t)):t.candidate?this._messageQueue.push(t):this._logger.error("queueSignalingMessage(): Unknown message: "+c(e)))},h.setRemoteDescription=function(e){this._logger.verbose("setRemoteDescription("+c(e)+")");var t=this,r=t._adjustRemoteDescription(e);return t._pc.setRemoteDescription(new RTCSessionDescription(r)).then((function(){t._hasRemoteSdp=!0})).then((function(){for(var e=0,r=t._messageQueue.length;e<r;e++)t.addIceCandidate(t._messageQueue[e]);t._messageQueue=[]})).catch((function(e){return t._onError(t,"setRemoteDescription"),t._logger.error("setRemoteDescription(): "+c(e)),Promise.reject(e)}))},h.doAnswer=function(){this._logger.verbose("doAnswer()");var e=this,t=this._buildConstraints();return this._logger.verbose("doAnswer(): Sending answer to peer with constraints: "+c(t,null," ")),this._pc.createAnswer(t).then((function(t){return e._setLocalDescription(t)})).catch((function(t){return e._onError("doAnswer",t),Promise.reject(t)}))},h.addIceCandidate=function(e){this._logger.verbose("addIceCandidate("+c(e)+")");var t,r,i="addIceCandidate(): ",n=this;return this._hasRemoteSdp?(t=a(e),r=new RTCIceCandidate({sdpMLineIndex:t.sdpMLineIndex,sdpMid:t.sdpMid,candidate:t.candidate}),this._logger.verbose(i+"Adding ice candidate:"+c(r.toJSON())),this._recordIceCandidate("Remote",r),this._pc.addIceCandidate(r).then((function(){n._logger.verbose(i+"MSG: Remote candidate added successfully")})).catch((function(e){n._logger.error(i+c(e))}))):(this._messageQueue.push(e),this._logger.verbose(i+"Queueing candidate, not reveiced remote sdp, yet"),Promise.resolve())},h.getStats=function(e){var t,r,n,o;if(this._logger.verbose("getStats("+e+")"),!this._pc)return Promise.reject(new Error("No PeerConnection"));if(e&&"video"!==e&&"audio"!==e)return Promise.reject(i.ValueNotValidError("kind","video / audio"));if(d(this._pc.getSenders)){var s=this._pc.getSenders().filter((function(t){return!!(n=t.track)&&(n.kind&&n.kind===e)}));s&&s.length&&(t=s[0].track)}else(o=this._pc.getRemoteStreams())&&o.length&&(r="video"===e?o[0].getVideoTracks():"audio"===e?o[0].getAudioTracks():void 0).length&&(t=r[0]);return this._pc.getStats(t)},h._reset=function(){this._logger.verbose("_reset()"),this._unbind(),this._pc=null,this._hasRemoteSdp=!1,this._messageQueue=[],this._isInitiator=!1,this._started=!1},h._bind=function(){this._logger.verbose("_bind()");this._pc?(this._pc.onicecandidate=this._onIceCandidate.bind(this),this._pc.ontrack=this._onRemoteStreamAdded.bind(this),this._pc.onremovestream=this._onRemoteStreamRemoved.bind(this),this._pc.onsignalingstatechange=this._onSignalingStateChanged.bind(this),this._pc.oniceconnectionstatechange=this._onIceConnectionStateChanged.bind(this),this._pc.onnegotiationneeded=this._onNegotiationNeeded.bind(this)):this._logger.error("_bind(): No PeerConnection")},h._unbind=function(){this._logger.verbose("_unbind()");this._pc?(this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.onremovestream=null,this._pc.onsignalingstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onnegotiationneeded=null):this._logger.warning("_unbind(): No PeerConnection")},h._setLocalDescription=function(e){this._logger.verbose("_setLocalDescription("+c(e)+")");var t="_setLocalDescription(): ",r=this;try{this._params.sdpPatches&&!this._params.sdpPatches.preventReplaceSendReceive&&(e.sdp=this._replaceSendReceive(e.sdp,this._params.send,this._params.receive)),e.sdp=maybePreferVideoReceiveCodec(e.sdp,this._params)}catch(e){return this._logger.verbose(t+e),Promise.reject(e)}return this._pc.setLocalDescription(e).then((function(){return r._logger.verbose(t+"setLocalDescription success"),{sdp:e.sdp,type:e.type}})).catch((function(e){r._onError("_setLocalDescription",e)}))},h._buildConstraints=function(e){return this._logger.verbose("_buildConstraints("+c(e)+")"),mergeConstraints(e,u)},h._adjustRemoteDescription=function(e){return this._logger.verbose("_adjustRemoteDescription("+c(e)+")"),e.sdp=maybePreferVideoReceiveCodec(e.sdp,this._params),e.sdp=maybePreferVideoSendCodec(e.sdp,this._params),this._params.videoSendBitrate&&(e.sdp=maybeSetVideoSendBitRate(e.sdp,this._params)),this._params.videoSendInitialBitrate&&(e.sdp=maybeSetVideoSendInitialBitRate(e.sdp,this._params)),e},h._drainMessageQueue=function(){var e,t;if(this._logger.verbose("_drainMessageQueue()"),this._pc&&this._started&&this._hasRemoteSdp){for(e=0,t=this._messageQueue.length;e<t;e++)this._processSignalingMessage(this._messageQueue[e]);this._messageQueue=[]}},h._processSignalingMessage=function(e){this._logger.verbose("_processSignalingMessage("+c(e)+")");var t="_processSignalingMessage(): ";if("offer"!==e.type||this._isInitiator)if("answer"===e.type&&this._isInitiator){if(this._logger.verbose(t+"Received answer"),"have-local-offer"!==this._pc.signalingState){e="MSG: ERROR: remote answer received in unexpected state: "+this._pc.signalingState;return void this._logger.verbose(t+e)}this._setRemoteSdp(e)}else if(e.candidate||"candidate"===e.type){this._logger.verbose(t+"New ice candidate");var r=new RTCIceCandidate({sdpMLineIndex:e.sdpMLineIndex,sdpMid:e.sdpMid,candidate:e.candidate});this._recordIceCandidate("Remote",r);var i=this;this._pc.addIceCandidate(r).then((function(){i._logger.verbose(t+"MSG: Remote candidate added successfully")})).catch((function(e){i._onError("addIceCandidate",e)}))}else this._logger.warning(t+"Unexpected message: "+c(e));else{if(this._logger.verbose(t+"Received offer"),"stable"!==this._pc.signalingState){var e="ERROR: remote offer received in unexpected state: "+this._pc.signalingState;return void this._logger.verbose(t+e)}this._setRemoteSdp(e),this.doAnswer()}},h._onIceCandidate=function(e){this._logger.verbose("_onIceCandidate("+c(e)+")");var t=e.candidate;if(!t)return this._logger.verbose("_onIceCandidate(): End of candidates"),void this.emitSimple("EndOfLocalCandidates",{});this._isValidIceCandidate(t)&&(this.emitSimple("SignalingMessage",{sdpMLineIndex:t.sdpMLineIndex,sdpMid:t.sdpMid,candidate:t.candidate}),this._recordIceCandidate("Local",t))},h._isValidIceCandidate=function(e){this._logger.verbose("_isValidIceCandidate("+c(e)+")");var t=e.candidate;return-1===t.indexOf("tcp")&&("relay"!==this._params.peerConnectionConfig.iceTransports||"relay"===iceCandidateType(t))},h._onSignalingStateChanged=function(){this._logger.verbose("_onSignalingStateChanged()");if(!this._pc)return!1;this._logger.verbose("_onSignalingStateChanged(): Signaling state changed to: "+this._pc.signalingState),this.emitSimple("SignalingStateChanged",{state:this._pc.signalingState})},h._onIceConnectionStateChanged=function(){this._logger.verbose("_onIceConnectionStateChanged()");var e="_onIceConnectionStateChanged(): ";if(!this._pc)return!1;if("completed"===this._pc.iceConnectionState){var t=e+"ICE complete time: "+(window.performance.now()-this._startTime).toFixed(0)+"ms";this._logger.verbose(t)}this._logger.verbose(e+"ICE connection state changed to: "+this._pc.iceConnectionState),this.emitSimple("IceConnectionStateChange",{state:this._pc.iceConnectionState}),"closed"===this._pc.iceConnectionState&&(this._closedIceConnectionStateSent=!0)},h._onNegotiationNeeded=function(e){this._logger.verbose("_onNegotiationNeeded("+c(e)+")");if(!this._pc)return!1;this._logger.verbose("_onNegotiationNeeded(): NegotiationNeeded Event"),this.emitSimple("NegotiationNeeded",e)},h._recordIceCandidate=function(e,t){this._logger.verbose("_recordIceCandidate("+c(e)+", "+c(t)+")");this._logger.verbose("_recordIceCandidate(): New ICE candidate for "+e),this.emitSimple("NewIceCandidate",{location:e,candidate:t})},h._onRemoteStreamAdded=function(e){this._logger.verbose("_onRemoteStreamAdded("+c(e)+")");this._logger.verbose("_onRemoteStreamAdded(): Remote stream added to peer connection"),this.emitSimple("RemoteStreamAdded",{stream:e.streams[0]})},h._onRemoteStreamRemoved=function(e){this._logger.verbose("_onRemoteStreamRemoved("+c(e)+")");this._logger.verbose("_onRemoteStreamRemoved(): Remote stream removed from peer connection"),this.emitSimple("RemoteStreamRemoved",{stream:e.stream})},h._onError=function(e,t){this._logger.error("_onError("+e+", "+t.toString()),this.emitSimple("PeerConnectionError",{tag:e,error:t.toString()})},h._replaceSendReceive=function(e,t,r){this._logger.verbose("_replaceSendReceive("+c(e)+", "+c(t)+", "+c(r)+")");var i,n,o="";t&&r?o="a=sendrecv":t?o="a=sendonly":r&&(o="a=recvonly");var s,a=e.split("\r\n");for(i=0,n=a.length;i<n;i++)-1===(s=a[i]).indexOf("a=sendrecv")&&-1===s.indexOf("a=sendonly")&&-1===s.indexOf("a=recvonly")||(a[i]=o);return a.join("\r\n")},p}.apply(t,i))||(e.exports=n)},function(e,t,r){var i,n;i=[r(20)],void 0===(n=function(e){window.trace=function(e){if("\n"===e[e.length-1]&&(e=e.substring(0,e.length-1)),window.performance){var t=(window.performance.now()/1e3).toFixed(3);console.log(t+": "+e)}else console.log(e)}}.apply(t,i))||(e.exports=n)},function(e,t,r){var i;e.exports=function e(t,r,n){function o(a,c){if(!r[a]){if(!t[a]){if(!c&&"function"==typeof i&&i)return i(a,!0);if(s)return s(a,!0);var d=new Error("Cannot find module '"+a+"'");throw d.code="MODULE_NOT_FOUND",d}var l=r[a]={exports:{}};t[a][0].call(l.exports,(function(e){return o(t[a][1][e]||e)}),l,l.exports,e,t,r,n)}return r[a].exports}for(var s="function"==typeof i&&i,a=0;a<n.length;a++)o(n[a]);return o}({1:[function(e,t,r){"use strict";var i=(0,e("./adapter_factory.js").adapterFactory)({window:window});t.exports=i},{"./adapter_factory.js":2}],2:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.adapterFactory=function(){var e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).window,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0},r=i.log,d=i.detectBrowser(e),l={browserDetails:d,commonShim:c,extractVersion:i.extractVersion,disableLog:i.disableLog,disableWarnings:i.disableWarnings};switch(d.browser){case"chrome":if(!n||!n.shimPeerConnection||!t.shimChrome)return r("Chrome shim is not included in this adapter release."),l;r("adapter.js shimming chrome."),l.browserShim=n,n.shimGetUserMedia(e),n.shimMediaStream(e),n.shimPeerConnection(e),n.shimOnTrack(e),n.shimAddTrackRemoveTrack(e),n.shimGetSendersWithDtmf(e),n.shimGetStats(e),n.shimSenderReceiverGetStats(e),n.fixNegotiationNeeded(e),c.shimRTCIceCandidate(e),c.shimConnectionState(e),c.shimMaxMessageSize(e),c.shimSendThrowTypeError(e),c.removeAllowExtmapMixed(e);break;case"firefox":if(!s||!s.shimPeerConnection||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),l;r("adapter.js shimming firefox."),l.browserShim=s,s.shimGetUserMedia(e),s.shimPeerConnection(e),s.shimOnTrack(e),s.shimRemoveStream(e),s.shimSenderGetStats(e),s.shimReceiverGetStats(e),s.shimRTCDataChannel(e),s.shimAddTransceiver(e),s.shimCreateOffer(e),s.shimCreateAnswer(e),c.shimRTCIceCandidate(e),c.shimConnectionState(e),c.shimMaxMessageSize(e),c.shimSendThrowTypeError(e);break;case"edge":if(!o||!o.shimPeerConnection||!t.shimEdge)return r("MS edge shim is not included in this adapter release."),l;r("adapter.js shimming edge."),l.browserShim=o,o.shimGetUserMedia(e),o.shimGetDisplayMedia(e),o.shimPeerConnection(e),o.shimReplaceTrack(e),c.shimMaxMessageSize(e),c.shimSendThrowTypeError(e);break;case"safari":if(!a||!t.shimSafari)return r("Safari shim is not included in this adapter release."),l;r("adapter.js shimming safari."),l.browserShim=a,a.shimRTCIceServerUrls(e),a.shimCreateOfferLegacy(e),a.shimCallbacksAPI(e),a.shimLocalStreamsAPI(e),a.shimRemoteStreamsAPI(e),a.shimTrackEventTransceiver(e),a.shimGetUserMedia(e),c.shimRTCIceCandidate(e),c.shimMaxMessageSize(e),c.shimSendThrowTypeError(e),c.removeAllowExtmapMixed(e);break;default:r("Unsupported browser!")}return l};var i=d(e("./utils")),n=d(e("./chrome/chrome_shim")),o=d(e("./edge/edge_shim")),s=d(e("./firefox/firefox_shim")),a=d(e("./safari/safari_shim")),c=d(e("./common_shim"));function d(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}},{"./chrome/chrome_shim":3,"./common_shim":6,"./edge/edge_shim":7,"./firefox/firefox_shim":11,"./safari/safari_shim":14,"./utils":15}],3:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.shimGetDisplayMedia=r.shimGetUserMedia=void 0;var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n=e("./getusermedia");Object.defineProperty(r,"shimGetUserMedia",{enumerable:!0,get:function(){return n.shimGetUserMedia}});var o=e("./getdisplaymedia");Object.defineProperty(r,"shimGetDisplayMedia",{enumerable:!0,get:function(){return o.shimGetDisplayMedia}}),r.shimMediaStream=function(e){e.MediaStream=e.MediaStream||e.webkitMediaStream},r.shimOnTrack=function(e){if("object"!==(void 0===e?"undefined":i(e))||!e.RTCPeerConnection||"ontrack"in e.RTCPeerConnection.prototype)s.wrapPeerConnectionEvent(e,"track",(function(e){return e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e}));else{Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get:function(){return this._ontrack},set:function(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});var t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){var r=this;return this._ontrackpoly||(this._ontrackpoly=function(t){t.stream.addEventListener("addtrack",(function(i){var n=void 0;n=e.RTCPeerConnection.prototype.getReceivers?r.getReceivers().find((function(e){return e.track&&e.track.id===i.track.id})):{track:i.track};var o=new Event("track");o.track=i.track,o.receiver=n,o.transceiver={receiver:n},o.streams=[t.stream],r.dispatchEvent(o)})),t.stream.getTracks().forEach((function(i){var n=void 0;n=e.RTCPeerConnection.prototype.getReceivers?r.getReceivers().find((function(e){return e.track&&e.track.id===i.id})):{track:i};var o=new Event("track");o.track=i,o.receiver=n,o.transceiver={receiver:n},o.streams=[t.stream],r.dispatchEvent(o)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}},r.shimGetSendersWithDtmf=function(e){if("object"===(void 0===e?"undefined":i(e))&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){var t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};var r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){var n=r.apply(this,arguments);return n||(n=t(this,e),this._senders.push(n)),n};var n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);var t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}var o=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){var r=this;this._senders=this._senders||[],o.apply(this,[e]),e.getTracks().forEach((function(e){r._senders.push(t(r,e))}))};var s=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){var t=this;this._senders=this._senders||[],s.apply(this,[e]),e.getTracks().forEach((function(e){var r=t._senders.find((function(t){return t.track===e}));r&&t._senders.splice(t._senders.indexOf(r),1)}))}}else if("object"===(void 0===e?"undefined":i(e))&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){var a=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){var e=this,t=a.apply(this,[]);return t.forEach((function(t){return t._pc=e})),t},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get:function(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}},r.shimGetStats=function(e){if(e.RTCPeerConnection){var t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){var e=this,r=Array.prototype.slice.call(arguments),i=r[0],n=r[1],o=r[2];if(arguments.length>0&&"function"==typeof i)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof i))return t.apply(this,[]);var s=function(e){var t={};return e.result().forEach((function(e){var r={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((function(t){r[t]=e.stat(t)})),t[r.id]=r})),t},a=function(e){return new Map(Object.keys(e).map((function(t){return[t,e[t]]})))};if(arguments.length>=2){var c=function(e){n(a(s(e)))};return t.apply(this,[c,i])}return new Promise((function(r,i){t.apply(e,[function(e){r(a(s(e)))},i])})).then(n,o)}}},r.shimSenderReceiverGetStats=function(e){if("object"===(void 0===e?"undefined":i(e))&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver){if(!("getStats"in e.RTCRtpSender.prototype)){var t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){var e=this,r=t.apply(this,[]);return r.forEach((function(t){return t._pc=e})),r});var r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){var e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){var e=this;return this._pc.getStats().then((function(t){return s.filterStats(t,e.track,!0)}))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){var n=e.RTCPeerConnection.prototype.getReceivers;n&&(e.RTCPeerConnection.prototype.getReceivers=function(){var e=this,t=n.apply(this,[]);return t.forEach((function(t){return t._pc=e})),t}),s.wrapPeerConnectionEvent(e,"track",(function(e){return e.receiver._pc=e.srcElement,e})),e.RTCRtpReceiver.prototype.getStats=function(){var e=this;return this._pc.getStats().then((function(t){return s.filterStats(t,e.track,!1)}))}}if("getStats"in e.RTCRtpSender.prototype&&"getStats"in e.RTCRtpReceiver.prototype){var o=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){var t=arguments[0],r=void 0,i=void 0,n=void 0;return this.getSenders().forEach((function(e){e.track===t&&(r?n=!0:r=e)})),this.getReceivers().forEach((function(e){return e.track===t&&(i?n=!0:i=e),e.track===t})),n||r&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):r?r.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return o.apply(this,arguments)}}}},r.shimAddTrackRemoveTrackWithNative=c,r.shimAddTrackRemoveTrack=function(e){if(e.RTCPeerConnection){var t=s.detectBrowser(e);if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return c(e);var r=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){var e=this,t=r.apply(this);return this._reverseStreams=this._reverseStreams||{},t.map((function(t){return e._reverseStreams[t.id]}))};var i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){var r=this;if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((function(e){if(r.getSenders().find((function(t){return t.track===e})))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){var n=new e.MediaStream(t.getTracks());this._streams[t.id]=n,this._reverseStreams[n.id]=t,t=n}i.apply(this,[t])};var n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,r){var i=this;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");var n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find((function(e){return e===t})))throw new DOMException("The adapter.js addTrack polyfill only supports a single  stream which is associated with the specified track.","NotSupportedError");var o=this.getSenders().find((function(e){return e.track===t}));if(o)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};var s=this._streams[r.id];if(s)s.addTrack(t),Promise.resolve().then((function(){i.dispatchEvent(new Event("negotiationneeded"))}));else{var a=new e.MediaStream([t]);this._streams[r.id]=a,this._reverseStreams[a.id]=r,this.addStream(a)}return this.getSenders().find((function(e){return e.track===t}))},["createOffer","createAnswer"].forEach((function(t){var r=e.RTCPeerConnection.prototype[t],i=a({},t,(function(){var e=this,t=arguments,i=arguments.length&&"function"==typeof arguments[0];return i?r.apply(this,[function(r){var i=l(e,r);t[0].apply(null,[i])},function(e){t[1]&&t[1].apply(null,e)},arguments[2]]):r.apply(this,arguments).then((function(t){return l(e,t)}))}));e.RTCPeerConnection.prototype[t]=i[t]}));var o=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=u(this,arguments[0]),o.apply(this,arguments)):o.apply(this,arguments)};var d=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get:function(){var e=d.get.apply(this);return""===e.type?e:l(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){var t=this;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(e._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};var r=void 0;Object.keys(this._streams).forEach((function(i){t._streams[i].getTracks().find((function(t){return e.track===t}))&&(r=t._streams[i])})),r&&(1===r.getTracks().length?this.removeStream(this._reverseStreams[r.id]):r.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function l(e,t){var r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((function(t){var i=e._reverseStreams[t],n=e._streams[i.id];r=r.replace(new RegExp(n.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:r})}function u(e,t){var r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((function(t){var i=e._reverseStreams[t],n=e._streams[i.id];r=r.replace(new RegExp(i.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:r})}},r.shimPeerConnection=function(e){var t=s.detectBrowser(e);if(!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection){t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){var r=e.RTCPeerConnection.prototype[t],i=a({},t,(function(){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}));e.RTCPeerConnection.prototype[t]=i[t]}));var r=e.RTCPeerConnection.prototype.addIceCandidate;e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?t.version<78&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():r.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())}}},r.fixNegotiationNeeded=function(e){s.wrapPeerConnectionEvent(e,"negotiationneeded",(function(e){if("stable"===e.target.signalingState)return e}))};var s=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("../utils.js"));function a(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function c(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){var e=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((function(t){return e._shimmedLocalStreams[t][0]}))};var t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){if(!r)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var i=t.apply(this,arguments);return this._shimmedLocalStreams[r.id]?-1===this._shimmedLocalStreams[r.id].indexOf(i)&&this._shimmedLocalStreams[r.id].push(i):this._shimmedLocalStreams[r.id]=[r,i],i};var r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){var t=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((function(e){if(t.getSenders().find((function(t){return t.track===e})))throw new DOMException("Track already exists.","InvalidAccessError")}));var i=this.getSenders();r.apply(this,arguments);var n=this.getSenders().filter((function(e){return-1===i.indexOf(e)}));this._shimmedLocalStreams[e.id]=[e].concat(n)};var i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],i.apply(this,arguments)};var n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){var t=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((function(r){var i=t._shimmedLocalStreams[r].indexOf(e);-1!==i&&t._shimmedLocalStreams[r].splice(i,1),1===t._shimmedLocalStreams[r].length&&delete t._shimmedLocalStreams[r]})),n.apply(this,arguments)}}},{"../utils.js":15,"./getdisplaymedia":4,"./getusermedia":5}],4:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.shimGetDisplayMedia=function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(r){return t(r).then((function(t){var i=r.video&&r.video.width,n=r.video&&r.video.height,o=r.video&&r.video.frameRate;return r.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:o||3}},i&&(r.video.mandatory.maxWidth=i),n&&(r.video.mandatory.maxHeight=n),e.navigator.mediaDevices.getUserMedia(r)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}},{}],5:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};r.shimGetUserMedia=function(e){var t=e&&e.navigator;if(t.mediaDevices){var r=n.detectBrowser(e),s=function(e){if("object"!==(void 0===e?"undefined":i(e))||e.mandatory||e.optional)return e;var t={};return Object.keys(e).forEach((function(r){if("require"!==r&&"advanced"!==r&&"mediaSource"!==r){var n="object"===i(e[r])?e[r]:{ideal:e[r]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);var o=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];var s={};"number"==typeof n.ideal?(s[o("min",r)]=n.ideal,t.optional.push(s),(s={})[o("max",r)]=n.ideal,t.optional.push(s)):(s[o("",r)]=n.ideal,t.optional.push(s))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[o("",r)]=n.exact):["min","max"].forEach((function(e){void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[o(e,r)]=n[e])}))}})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},a=function(e,n){if(r.version>=61)return n(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"===i(e.audio)){var a=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])};a((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),a(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=s(e.audio)}if(e&&"object"===i(e.video)){var c=e.video.facingMode;c=c&&("object"===(void 0===c?"undefined":i(c))?c:{ideal:c});var d=r.version<66;if(c&&("user"===c.exact||"environment"===c.exact||"user"===c.ideal||"environment"===c.ideal)&&(!t.mediaDevices.getSupportedConstraints||!t.mediaDevices.getSupportedConstraints().facingMode||d)){delete e.video.facingMode;var l=void 0;if("environment"===c.exact||"environment"===c.ideal?l=["back","rear"]:"user"!==c.exact&&"user"!==c.ideal||(l=["front"]),l)return t.mediaDevices.enumerateDevices().then((function(t){var r=(t=t.filter((function(e){return"videoinput"===e.kind}))).find((function(e){return l.some((function(t){return e.label.toLowerCase().includes(t)}))}));return!r&&t.length&&l.includes("back")&&(r=t[t.length-1]),r&&(e.video.deviceId=c.exact?{exact:r.deviceId}:{ideal:r.deviceId}),e.video=s(e.video),o("chrome: "+JSON.stringify(e)),n(e)}))}e.video=s(e.video)}return o("chrome: "+JSON.stringify(e)),n(e)},c=function(e){return r.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString:function(){return this.name+(this.message&&": ")+this.message}}};if(t.getUserMedia=function(e,r,i){a(e,(function(e){t.webkitGetUserMedia(e,r,(function(e){i&&i(c(e))}))}))}.bind(t),t.mediaDevices.getUserMedia){var d=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(e){return a(e,(function(e){return d(e).then((function(t){if(e.audio&&!t.getAudioTracks().length||e.video&&!t.getVideoTracks().length)throw t.getTracks().forEach((function(e){e.stop()})),new DOMException("","NotFoundError");return t}),(function(e){return Promise.reject(c(e))}))}))}}}};var n=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("../utils.js")),o=n.log},{"../utils.js":15}],6:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};r.shimRTCIceCandidate=function(e){if(e.RTCIceCandidate&&!(e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)){var t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"===(void 0===e?"undefined":i(e))&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substr(2)),e.candidate&&e.candidate.length){var r=new t(e),n=s.default.parseCandidate(e.candidate),o=Object.assign(r,n);return o.toJSON=function(){return{candidate:o.candidate,sdpMid:o.sdpMid,sdpMLineIndex:o.sdpMLineIndex,usernameFragment:o.usernameFragment}},o}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,a.wrapPeerConnectionEvent(e,"icecandidate",(function(t){return t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t}))}},r.shimMaxMessageSize=function(e){if(e.RTCPeerConnection){var t=a.detectBrowser(e);"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get:function(){return void 0===this._sctp?null:this._sctp}});var r=function(e){if(!e||!e.sdp)return!1;var t=s.default.splitSections(e.sdp);return t.shift(),t.some((function(e){var t=s.default.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))},i=function(e){var t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;var r=parseInt(t[1],10);return r!=r?-1:r},n=function(e){var r=65536;return"firefox"===t.browser&&(r=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),r},o=function(e,r){var i=65536;"firefox"===t.browser&&57===t.version&&(i=65535);var n=s.default.matchPrefix(e.sdp,"a=max-message-size:");return n.length>0?i=parseInt(n[0].substr(19),10):"firefox"===t.browser&&-1!==r&&(i=2147483637),i},c=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){var e=this.getConfiguration(),s=e.sdpSemantics;"plan-b"===s&&Object.defineProperty(this,"sctp",{get:function(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(r(arguments[0])){var a=i(arguments[0]),d=n(a),l=o(arguments[0],a),u=void 0;u=0===d&&0===l?Number.POSITIVE_INFINITY:0===d||0===l?Math.max(d,l):Math.min(d,l);var p={};Object.defineProperty(p,"maxMessageSize",{get:function(){return u}}),this._sctp=p}return c.apply(this,arguments)}}},r.shimSendThrowTypeError=function(e){if(e.RTCPeerConnection&&"createDataChannel"in e.RTCPeerConnection.prototype){var t=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){var e=t.apply(this,arguments);return r(e,this),e},a.wrapPeerConnectionEvent(e,"datachannel",(function(e){return r(e.channel,e.target),e}))}function r(e,t){var r=e.send;e.send=function(){var i=arguments[0],n=i.length||i.size||i.byteLength;if("open"===e.readyState&&t.sctp&&n>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return r.apply(e,arguments)}}},r.shimConnectionState=function(e){if(e.RTCPeerConnection&&!("connectionState"in e.RTCPeerConnection.prototype)){var t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get:function(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get:function(){return this._onconnectionstatechange||null},set:function(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((function(e){var r=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=function(e){var t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;var r=new Event("connectionstatechange",e);t.dispatchEvent(r)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}}))}},r.removeAllowExtmapMixed=function(e){if(e.RTCPeerConnection){var t=a.detectBrowser(e);if(!("chrome"===t.browser&&t.version>=71)){var r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(e){return e&&e.sdp&&-1!==e.sdp.indexOf("\na=extmap-allow-mixed")&&(e.sdp=e.sdp.split("\n").filter((function(e){return"a=extmap-allow-mixed"!==e.trim()})).join("\n")),r.apply(this,arguments)}}}};var n,o=e("sdp"),s=(n=o)&&n.__esModule?n:{default:n},a=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("./utils"))},{"./utils":15,sdp:17}],7:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.shimGetDisplayMedia=r.shimGetUserMedia=void 0;var i=e("./getusermedia");Object.defineProperty(r,"shimGetUserMedia",{enumerable:!0,get:function(){return i.shimGetUserMedia}});var n=e("./getdisplaymedia");Object.defineProperty(r,"shimGetDisplayMedia",{enumerable:!0,get:function(){return n.shimGetDisplayMedia}}),r.shimPeerConnection=function(e){var t=s.detectBrowser(e);if(e.RTCIceGatherer&&(e.RTCIceCandidate||(e.RTCIceCandidate=function(e){return e}),e.RTCSessionDescription||(e.RTCSessionDescription=function(e){return e}),t.version<15025)){var r=Object.getOwnPropertyDescriptor(e.MediaStreamTrack.prototype,"enabled");Object.defineProperty(e.MediaStreamTrack.prototype,"enabled",{set:function(e){r.set.call(this,e);var t=new Event("enabled");t.enabled=e,this.dispatchEvent(t)}})}!e.RTCRtpSender||"dtmf"in e.RTCRtpSender.prototype||Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get:function(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=new e.RTCDtmfSender(this):"video"===this.track.kind&&(this._dtmf=null)),this._dtmf}}),e.RTCDtmfSender&&!e.RTCDTMFSender&&(e.RTCDTMFSender=e.RTCDtmfSender);var i=(0,d.default)(e,t.version);e.RTCPeerConnection=function(e){return e&&e.iceServers&&(e.iceServers=(0,a.filterIceServers)(e.iceServers,t.version),s.log("ICE servers after filtering:",e.iceServers)),new i(e)},e.RTCPeerConnection.prototype=i.prototype},r.shimReplaceTrack=function(e){!e.RTCRtpSender||"replaceTrack"in e.RTCRtpSender.prototype||(e.RTCRtpSender.prototype.replaceTrack=e.RTCRtpSender.prototype.setTrack)};var o,s=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("../utils")),a=e("./filtericeservers"),c=e("rtcpeerconnection-shim"),d=(o=c)&&o.__esModule?o:{default:o}},{"../utils":15,"./filtericeservers":8,"./getdisplaymedia":9,"./getusermedia":10,"rtcpeerconnection-shim":16}],8:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.filterIceServers=function(e,t){var r=!1;return(e=JSON.parse(JSON.stringify(e))).filter((function(e){if(e&&(e.urls||e.url)){var t=e.urls||e.url;e.url&&!e.urls&&i.deprecated("RTCIceServer.url","RTCIceServer.urls");var n="string"==typeof t;return n&&(t=[t]),t=t.filter((function(e){if(0===e.indexOf("stun:"))return!1;var t=e.startsWith("turn")&&!e.startsWith("turn:[")&&e.includes("transport=udp");return t&&!r?(r=!0,!0):t&&!r})),delete e.url,e.urls=n?t[0]:t,!!t.length}}))};var i=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("../utils"))},{"../utils":15}],9:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.shimGetDisplayMedia=function(e){"getDisplayMedia"in e.navigator&&e.navigator.mediaDevices&&(e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||(e.navigator.mediaDevices.getDisplayMedia=e.navigator.getDisplayMedia.bind(e.navigator)))}},{}],10:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.shimGetUserMedia=function(e){var t=e&&e.navigator,r=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(e){return r(e).catch((function(e){return Promise.reject(function(e){return{name:{PermissionDeniedError:"NotAllowedError"}[e.name]||e.name,message:e.message,constraint:e.constraint,toString:function(){return this.name}}}(e))}))}}},{}],11:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.shimGetDisplayMedia=r.shimGetUserMedia=void 0;var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n=e("./getusermedia");Object.defineProperty(r,"shimGetUserMedia",{enumerable:!0,get:function(){return n.shimGetUserMedia}});var o=e("./getdisplaymedia");Object.defineProperty(r,"shimGetDisplayMedia",{enumerable:!0,get:function(){return o.shimGetDisplayMedia}}),r.shimOnTrack=function(e){"object"===(void 0===e?"undefined":i(e))&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})},r.shimPeerConnection=function(e){var t=s.detectBrowser(e);if("object"===(void 0===e?"undefined":i(e))&&(e.RTCPeerConnection||e.mozRTCPeerConnection)){if(!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){var r,i,n,o=e.RTCPeerConnection.prototype[t],s=(n=function(){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),o.apply(this,arguments)},(i=t)in(r={})?Object.defineProperty(r,i,{value:n,enumerable:!0,configurable:!0,writable:!0}):r[i]=n,r);e.RTCPeerConnection.prototype[t]=s[t]})),t.version<68){var r=e.RTCPeerConnection.prototype.addIceCandidate;e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?arguments[0]&&""===arguments[0].candidate?Promise.resolve():r.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())}}var n={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},o=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){var e=Array.prototype.slice.call(arguments),r=e[0],i=e[1],s=e[2];return o.apply(this,[r||null]).then((function(e){if(t.version<53&&!i)try{e.forEach((function(e){e.type=n[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach((function(t,r){e.set(r,Object.assign({},t,{type:n[t.type]||t.type}))}))}return e})).then(i,s)}}},r.shimSenderGetStats=function(e){if("object"===(void 0===e?"undefined":i(e))&&e.RTCPeerConnection&&e.RTCRtpSender&&!(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)){var t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){var e=this,r=t.apply(this,[]);return r.forEach((function(t){return t._pc=e})),r});var r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){var e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}},r.shimReceiverGetStats=function(e){if("object"===(void 0===e?"undefined":i(e))&&e.RTCPeerConnection&&e.RTCRtpSender&&!(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)){var t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){var e=this,r=t.apply(this,[]);return r.forEach((function(t){return t._pc=e})),r}),s.wrapPeerConnectionEvent(e,"track",(function(e){return e.receiver._pc=e.srcElement,e})),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}},r.shimRemoveStream=function(e){!e.RTCPeerConnection||"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){var t=this;s.deprecated("removeStream","removeTrack"),this.getSenders().forEach((function(r){r.track&&e.getTracks().includes(r.track)&&t.removeTrack(r)}))})},r.shimRTCDataChannel=function(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)},r.shimAddTransceiver=function(e){if("object"===(void 0===e?"undefined":i(e))&&e.RTCPeerConnection){var t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];var e=arguments[1],r=e&&"sendEncodings"in e;r&&e.sendEncodings.forEach((function(e){if("rid"in e&&!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));var i=t.apply(this,arguments);if(r){var n=i.sender,o=n.getParameters();"encodings"in o||(o.encodings=e.sendEncodings,this.setParametersPromises.push(n.setParameters(o).catch((function(){}))))}return i})}},r.shimCreateOffer=function(e){if("object"===(void 0===e?"undefined":i(e))&&e.RTCPeerConnection){var t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){var e=this,r=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((function(){return t.apply(e,r)})).finally((function(){e.setParametersPromises=[]})):t.apply(this,arguments)}}},r.shimCreateAnswer=function(e){if("object"===(void 0===e?"undefined":i(e))&&e.RTCPeerConnection){var t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){var e=this,r=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((function(){return t.apply(e,r)})).finally((function(){e.setParametersPromises=[]})):t.apply(this,arguments)}}};var s=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("../utils"))},{"../utils":15,"./getdisplaymedia":12,"./getusermedia":13}],12:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.shimGetDisplayMedia=function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(r){if(!r||!r.video){var i=new DOMException("getDisplayMedia without video constraints is undefined");return i.name="NotFoundError",i.code=8,Promise.reject(i)}return!0===r.video?r.video={mediaSource:t}:r.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(r)})}},{}],13:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};r.shimGetUserMedia=function(e){var t=n.detectBrowser(e),r=e&&e.navigator,o=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,i){n.deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(e).then(t,i)},!(t.version>55&&"autoGainControl"in r.mediaDevices.getSupportedConstraints())){var s=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])},a=r.mediaDevices.getUserMedia.bind(r.mediaDevices);if(r.mediaDevices.getUserMedia=function(e){return"object"===(void 0===e?"undefined":i(e))&&"object"===i(e.audio)&&(e=JSON.parse(JSON.stringify(e)),s(e.audio,"autoGainControl","mozAutoGainControl"),s(e.audio,"noiseSuppression","mozNoiseSuppression")),a(e)},o&&o.prototype.getSettings){var c=o.prototype.getSettings;o.prototype.getSettings=function(){var e=c.apply(this,arguments);return s(e,"mozAutoGainControl","autoGainControl"),s(e,"mozNoiseSuppression","noiseSuppression"),e}}if(o&&o.prototype.applyConstraints){var d=o.prototype.applyConstraints;o.prototype.applyConstraints=function(e){return"audio"===this.kind&&"object"===(void 0===e?"undefined":i(e))&&(e=JSON.parse(JSON.stringify(e)),s(e,"autoGainControl","mozAutoGainControl"),s(e,"noiseSuppression","mozNoiseSuppression")),d.apply(this,[e])}}}};var n=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("../utils"))},{"../utils":15}],14:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};r.shimLocalStreamsAPI=function(e){if("object"===(void 0===e?"undefined":i(e))&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){var t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){var r=this;this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((function(i){return t.call(r,i,e)})),e.getVideoTracks().forEach((function(i){return t.call(r,i,e)}))},e.RTCPeerConnection.prototype.addTrack=function(e){var r=arguments[1];return r&&(this._localStreams?this._localStreams.includes(r)||this._localStreams.push(r):this._localStreams=[r]),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){var t=this;this._localStreams||(this._localStreams=[]);var r=this._localStreams.indexOf(e);if(-1!==r){this._localStreams.splice(r,1);var i=e.getTracks();this.getSenders().forEach((function(e){i.includes(e.track)&&t.removeTrack(e)}))}})}},r.shimRemoteStreamsAPI=function(e){if("object"===(void 0===e?"undefined":i(e))&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get:function(){return this._onaddstream},set:function(e){var t=this;this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=function(e){e.streams.forEach((function(e){if(t._remoteStreams||(t._remoteStreams=[]),!t._remoteStreams.includes(e)){t._remoteStreams.push(e);var r=new Event("addstream");r.stream=e,t.dispatchEvent(r)}}))})}});var t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){var e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((function(t){if(e._remoteStreams||(e._remoteStreams=[]),!(e._remoteStreams.indexOf(t)>=0)){e._remoteStreams.push(t);var r=new Event("addstream");r.stream=t,e.dispatchEvent(r)}}))}),t.apply(e,arguments)}}},r.shimCallbacksAPI=function(e){if("object"===(void 0===e?"undefined":i(e))&&e.RTCPeerConnection){var t=e.RTCPeerConnection.prototype,r=t.createOffer,n=t.createAnswer,o=t.setLocalDescription,s=t.setRemoteDescription,a=t.addIceCandidate;t.createOffer=function(e,t){var i=arguments.length>=2?arguments[2]:arguments[0],n=r.apply(this,[i]);return t?(n.then(e,t),Promise.resolve()):n},t.createAnswer=function(e,t){var r=arguments.length>=2?arguments[2]:arguments[0],i=n.apply(this,[r]);return t?(i.then(e,t),Promise.resolve()):i};var c=function(e,t,r){var i=o.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i};t.setLocalDescription=c,c=function(e,t,r){var i=s.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.setRemoteDescription=c,c=function(e,t,r){var i=a.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.addIceCandidate=c}},r.shimGetUserMedia=function(e){var t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){var r=t.mediaDevices,i=r.getUserMedia.bind(r);t.mediaDevices.getUserMedia=function(e){return i(o(e))}}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,r,i){t.mediaDevices.getUserMedia(e).then(r,i)}.bind(t))},r.shimConstraints=o,r.shimRTCIceServerUrls=function(e){var t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,r){if(e&&e.iceServers){for(var i=[],o=0;o<e.iceServers.length;o++){var s=e.iceServers[o];!s.hasOwnProperty("urls")&&s.hasOwnProperty("url")?(n.deprecated("RTCIceServer.url","RTCIceServer.urls"),(s=JSON.parse(JSON.stringify(s))).urls=s.url,delete s.url,i.push(s)):i.push(e.iceServers[o])}e.iceServers=i}return new t(e,r)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in e.RTCPeerConnection&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:function(){return t.generateCertificate}})},r.shimTrackEventTransceiver=function(e){"object"===(void 0===e?"undefined":i(e))&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})},r.shimCreateOfferLegacy=function(e){var t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);var r=this.getTransceivers().find((function(e){return"audio"===e.receiver.track.kind}));!1===e.offerToReceiveAudio&&r?"sendrecv"===r.direction?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":"recvonly"===r.direction&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):!0!==e.offerToReceiveAudio||r||this.addTransceiver("audio"),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);var i=this.getTransceivers().find((function(e){return"video"===e.receiver.track.kind}));!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video")}return t.apply(this,arguments)}};var n=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("../utils"));function o(e){return e&&void 0!==e.video?Object.assign({},e,{video:n.compactObject(e.video)}):e}},{"../utils":15}],15:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};r.extractVersion=s,r.wrapPeerConnectionEvent=function(e,t,r){if(e.RTCPeerConnection){var i=e.RTCPeerConnection.prototype,n=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return n.apply(this,arguments);var o=function(e){var t=r(e);t&&i(t)};return this._eventMap=this._eventMap||{},this._eventMap[i]=o,n.apply(this,[e,o])};var o=i.removeEventListener;i.removeEventListener=function(e,r){if(e!==t||!this._eventMap||!this._eventMap[r])return o.apply(this,arguments);var i=this._eventMap[r];return delete this._eventMap[r],o.apply(this,[e,i])},Object.defineProperty(i,"on"+t,{get:function(){return this["_on"+t]},set:function(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}},r.disableLog=function(e){return"boolean"!=typeof e?new Error("Argument type: "+(void 0===e?"undefined":i(e))+". Please use a boolean."):(n=e,e?"adapter.js logging disabled":"adapter.js logging enabled")},r.disableWarnings=function(e){return"boolean"!=typeof e?new Error("Argument type: "+(void 0===e?"undefined":i(e))+". Please use a boolean."):(o=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))},r.log=function(){if("object"===("undefined"==typeof window?"undefined":i(window))){if(n)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}},r.deprecated=function(e,t){o&&console.warn(e+" is deprecated, please use "+t+" instead.")},r.detectBrowser=function(e){var t=e.navigator,r={browser:null,version:null};if(void 0===e||!e.navigator)return r.browser="Not a browser.",r;if(t.mozGetUserMedia)r.browser="firefox",r.version=s(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection&&!e.RTCIceGatherer)r.browser="chrome",r.version=s(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(t.mediaDevices&&t.userAgent.match(/Edge\/(\d+).(\d+)$/))r.browser="edge",r.version=s(t.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!e.RTCPeerConnection||!t.userAgent.match(/AppleWebKit\/(\d+)\./))return r.browser="Not a supported browser.",r;r.browser="safari",r.version=s(t.userAgent,/AppleWebKit\/(\d+)\./,1),r.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return r},r.compactObject=function e(t){return a(t)?Object.keys(t).reduce((function(r,i){var n=a(t[i]),o=n?e(t[i]):t[i],s=n&&!Object.keys(o).length;return void 0===o||s?r:Object.assign(r,function(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}({},i,o))}),{}):t},r.walkStats=c,r.filterStats=function(e,t,r){var i=r?"outbound-rtp":"inbound-rtp",n=new Map;if(null===t)return n;var o=[];return e.forEach((function(e){"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)})),o.forEach((function(t){e.forEach((function(r){r.type===i&&r.trackId===t.id&&c(e,r,n)}))})),n};var n=!0,o=!0;function s(e,t,r){var i=e.match(t);return i&&i.length>=r&&parseInt(i[r],10)}function a(e){return"[object Object]"===Object.prototype.toString.call(e)}function c(e,t,r){t&&!r.has(t.id)&&(r.set(t.id,t),Object.keys(t).forEach((function(i){i.endsWith("Id")?c(e,e.get(t[i]),r):i.endsWith("Ids")&&t[i].forEach((function(t){c(e,e.get(t),r)}))})))}},{}],16:[function(e,t,r){"use strict";var i=e("sdp");function n(e,t,r,n,o){var s=i.writeRtpDescription(e.kind,t);if(s+=i.writeIceParameters(e.iceGatherer.getLocalParameters()),s+=i.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===r?"actpass":o||"active"),s+="a=mid:"+e.mid+"\r\n",e.rtpSender&&e.rtpReceiver?s+="a=sendrecv\r\n":e.rtpSender?s+="a=sendonly\r\n":e.rtpReceiver?s+="a=recvonly\r\n":s+="a=inactive\r\n",e.rtpSender){var a=e.rtpSender._initialTrackId||e.rtpSender.track.id;e.rtpSender._initialTrackId=a;var c="msid:"+(n?n.id:"-")+" "+a+"\r\n";s+="a="+c,s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+c,e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+c,s+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+i.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+i.localCName+"\r\n"),s}function o(e,t){var r={codecs:[],headerExtensions:[],fecMechanisms:[]},i=function(e,t){e=parseInt(e,10);for(var r=0;r<t.length;r++)if(t[r].payloadType===e||t[r].preferredPayloadType===e)return t[r]},n=function(e,t,r,n){var o=i(e.parameters.apt,r),s=i(t.parameters.apt,n);return o&&s&&o.name.toLowerCase()===s.name.toLowerCase()};return e.codecs.forEach((function(i){for(var o=0;o<t.codecs.length;o++){var s=t.codecs[o];if(i.name.toLowerCase()===s.name.toLowerCase()&&i.clockRate===s.clockRate){if("rtx"===i.name.toLowerCase()&&i.parameters&&s.parameters.apt&&!n(i,s,e.codecs,t.codecs))continue;(s=JSON.parse(JSON.stringify(s))).numChannels=Math.min(i.numChannels,s.numChannels),r.codecs.push(s),s.rtcpFeedback=s.rtcpFeedback.filter((function(e){for(var t=0;t<i.rtcpFeedback.length;t++)if(i.rtcpFeedback[t].type===e.type&&i.rtcpFeedback[t].parameter===e.parameter)return!0;return!1}));break}}})),e.headerExtensions.forEach((function(e){for(var i=0;i<t.headerExtensions.length;i++){var n=t.headerExtensions[i];if(e.uri===n.uri){r.headerExtensions.push(n);break}}})),r}function s(e,t,r){return-1!=={offer:{setLocalDescription:["stable","have-local-offer"],setRemoteDescription:["stable","have-remote-offer"]},answer:{setLocalDescription:["have-remote-offer","have-local-pranswer"],setRemoteDescription:["have-local-offer","have-remote-pranswer"]}}[t][e].indexOf(r)}function a(e,t){var r=e.getRemoteCandidates().find((function(e){return t.foundation===e.foundation&&t.ip===e.ip&&t.port===e.port&&t.priority===e.priority&&t.protocol===e.protocol&&t.type===e.type}));return r||e.addRemoteCandidate(t),!r}function c(e,t){var r=new Error(t);return r.name=e,r.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[e],r}t.exports=function(e,t){function r(t,r){r.addTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("addtrack",{track:t}))}function d(t,r,i,n){var o=new Event("track");o.track=r,o.receiver=i,o.transceiver={receiver:i},o.streams=n,e.setTimeout((function(){t._dispatchEvent("track",o)}))}var l=function(r){var n=this,o=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach((function(e){n[e]=o[e].bind(o)})),this.canTrickleIceCandidates=null,this.needNegotiation=!1,this.localStreams=[],this.remoteStreams=[],this._localDescription=null,this._remoteDescription=null,this.signalingState="stable",this.iceConnectionState="new",this.connectionState="new",this.iceGatheringState="new",r=JSON.parse(JSON.stringify(r||{})),this.usingBundle="max-bundle"===r.bundlePolicy,"negotiate"===r.rtcpMuxPolicy)throw c("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(r.rtcpMuxPolicy||(r.rtcpMuxPolicy="require"),r.iceTransportPolicy){case"all":case"relay":break;default:r.iceTransportPolicy="all"}switch(r.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:r.bundlePolicy="balanced"}if(r.iceServers=function(e,t){var r=!1;return(e=JSON.parse(JSON.stringify(e))).filter((function(e){if(e&&(e.urls||e.url)){var i=e.urls||e.url;e.url&&!e.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var n="string"==typeof i;return n&&(i=[i]),i=i.filter((function(e){return 0!==e.indexOf("turn:")||-1===e.indexOf("transport=udp")||-1!==e.indexOf("turn:[")||r?0===e.indexOf("stun:")&&t>=14393&&-1===e.indexOf("?transport=udp"):(r=!0,!0)})),delete e.url,e.urls=n?i[0]:i,!!i.length}}))}(r.iceServers||[],t),this._iceGatherers=[],r.iceCandidatePoolSize)for(var s=r.iceCandidatePoolSize;s>0;s--)this._iceGatherers.push(new e.RTCIceGatherer({iceServers:r.iceServers,gatherPolicy:r.iceTransportPolicy}));else r.iceCandidatePoolSize=0;this._config=r,this.transceivers=[],this._sdpSessionId=i.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(l.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(l.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),l.prototype.onicecandidate=null,l.prototype.onaddstream=null,l.prototype.ontrack=null,l.prototype.onremovestream=null,l.prototype.onsignalingstatechange=null,l.prototype.oniceconnectionstatechange=null,l.prototype.onconnectionstatechange=null,l.prototype.onicegatheringstatechange=null,l.prototype.onnegotiationneeded=null,l.prototype.ondatachannel=null,l.prototype._dispatchEvent=function(e,t){this._isClosed||(this.dispatchEvent(t),"function"==typeof this["on"+e]&&this["on"+e](t))},l.prototype._emitGatheringStateChange=function(){var e=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",e)},l.prototype.getConfiguration=function(){return this._config},l.prototype.getLocalStreams=function(){return this.localStreams},l.prototype.getRemoteStreams=function(){return this.remoteStreams},l.prototype._createTransceiver=function(e,t){var r=this.transceivers.length>0,i={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:e,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&r)i.iceTransport=this.transceivers[0].iceTransport,i.dtlsTransport=this.transceivers[0].dtlsTransport;else{var n=this._createIceAndDtlsTransports();i.iceTransport=n.iceTransport,i.dtlsTransport=n.dtlsTransport}return t||this.transceivers.push(i),i},l.prototype.addTrack=function(t,r){if(this._isClosed)throw c("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var i;if(this.transceivers.find((function(e){return e.track===t})))throw c("InvalidAccessError","Track already exists.");for(var n=0;n<this.transceivers.length;n++)this.transceivers[n].track||this.transceivers[n].kind!==t.kind||(i=this.transceivers[n]);return i||(i=this._createTransceiver(t.kind)),this._maybeFireNegotiationNeeded(),-1===this.localStreams.indexOf(r)&&this.localStreams.push(r),i.track=t,i.stream=r,i.rtpSender=new e.RTCRtpSender(t,i.dtlsTransport),i.rtpSender},l.prototype.addStream=function(e){var r=this;if(t>=15025)e.getTracks().forEach((function(t){r.addTrack(t,e)}));else{var i=e.clone();e.getTracks().forEach((function(e,t){var r=i.getTracks()[t];e.addEventListener("enabled",(function(e){r.enabled=e.enabled}))})),i.getTracks().forEach((function(e){r.addTrack(e,i)}))}},l.prototype.removeTrack=function(t){if(this._isClosed)throw c("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(t instanceof e.RTCRtpSender))throw new TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var r=this.transceivers.find((function(e){return e.rtpSender===t}));if(!r)throw c("InvalidAccessError","Sender was not created by this connection.");var i=r.stream;r.rtpSender.stop(),r.rtpSender=null,r.track=null,r.stream=null,-1===this.transceivers.map((function(e){return e.stream})).indexOf(i)&&this.localStreams.indexOf(i)>-1&&this.localStreams.splice(this.localStreams.indexOf(i),1),this._maybeFireNegotiationNeeded()},l.prototype.removeStream=function(e){var t=this;e.getTracks().forEach((function(e){var r=t.getSenders().find((function(t){return t.track===e}));r&&t.removeTrack(r)}))},l.prototype.getSenders=function(){return this.transceivers.filter((function(e){return!!e.rtpSender})).map((function(e){return e.rtpSender}))},l.prototype.getReceivers=function(){return this.transceivers.filter((function(e){return!!e.rtpReceiver})).map((function(e){return e.rtpReceiver}))},l.prototype._createIceGatherer=function(t,r){var i=this;if(r&&t>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var n=new e.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(n,"state",{value:"new",writable:!0}),this.transceivers[t].bufferedCandidateEvents=[],this.transceivers[t].bufferCandidates=function(e){var r=!e.candidate||0===Object.keys(e.candidate).length;n.state=r?"completed":"gathering",null!==i.transceivers[t].bufferedCandidateEvents&&i.transceivers[t].bufferedCandidateEvents.push(e)},n.addEventListener("localcandidate",this.transceivers[t].bufferCandidates),n},l.prototype._gather=function(t,r){var n=this,o=this.transceivers[r].iceGatherer;if(!o.onlocalcandidate){var s=this.transceivers[r].bufferedCandidateEvents;this.transceivers[r].bufferedCandidateEvents=null,o.removeEventListener("localcandidate",this.transceivers[r].bufferCandidates),o.onlocalcandidate=function(e){if(!(n.usingBundle&&r>0)){var s=new Event("icecandidate");s.candidate={sdpMid:t,sdpMLineIndex:r};var a=e.candidate,c=!a||0===Object.keys(a).length;if(c)"new"!==o.state&&"gathering"!==o.state||(o.state="completed");else{"new"===o.state&&(o.state="gathering"),a.component=1,a.ufrag=o.getLocalParameters().usernameFragment;var d=i.writeCandidate(a);s.candidate=Object.assign(s.candidate,i.parseCandidate(d)),s.candidate.candidate=d,s.candidate.toJSON=function(){return{candidate:s.candidate.candidate,sdpMid:s.candidate.sdpMid,sdpMLineIndex:s.candidate.sdpMLineIndex,usernameFragment:s.candidate.usernameFragment}}}var l=i.getMediaSections(n._localDescription.sdp);l[s.candidate.sdpMLineIndex]+=c?"a=end-of-candidates\r\n":"a="+s.candidate.candidate+"\r\n",n._localDescription.sdp=i.getDescription(n._localDescription.sdp)+l.join("");var u=n.transceivers.every((function(e){return e.iceGatherer&&"completed"===e.iceGatherer.state}));"gathering"!==n.iceGatheringState&&(n.iceGatheringState="gathering",n._emitGatheringStateChange()),c||n._dispatchEvent("icecandidate",s),u&&(n._dispatchEvent("icecandidate",new Event("icecandidate")),n.iceGatheringState="complete",n._emitGatheringStateChange())}},e.setTimeout((function(){s.forEach((function(e){o.onlocalcandidate(e)}))}),0)}},l.prototype._createIceAndDtlsTransports=function(){var t=this,r=new e.RTCIceTransport(null);r.onicestatechange=function(){t._updateIceConnectionState(),t._updateConnectionState()};var i=new e.RTCDtlsTransport(r);return i.ondtlsstatechange=function(){t._updateConnectionState()},i.onerror=function(){Object.defineProperty(i,"state",{value:"failed",writable:!0}),t._updateConnectionState()},{iceTransport:r,dtlsTransport:i}},l.prototype._disposeIceAndDtlsTransports=function(e){var t=this.transceivers[e].iceGatherer;t&&(delete t.onlocalcandidate,delete this.transceivers[e].iceGatherer);var r=this.transceivers[e].iceTransport;r&&(delete r.onicestatechange,delete this.transceivers[e].iceTransport);var i=this.transceivers[e].dtlsTransport;i&&(delete i.ondtlsstatechange,delete i.onerror,delete this.transceivers[e].dtlsTransport)},l.prototype._transceive=function(e,r,n){var s=o(e.localCapabilities,e.remoteCapabilities);r&&e.rtpSender&&(s.encodings=e.sendEncodingParameters,s.rtcp={cname:i.localCName,compound:e.rtcpParameters.compound},e.recvEncodingParameters.length&&(s.rtcp.ssrc=e.recvEncodingParameters[0].ssrc),e.rtpSender.send(s)),n&&e.rtpReceiver&&s.codecs.length>0&&("video"===e.kind&&e.recvEncodingParameters&&t<15019&&e.recvEncodingParameters.forEach((function(e){delete e.rtx})),e.recvEncodingParameters.length?s.encodings=e.recvEncodingParameters:s.encodings=[{}],s.rtcp={compound:e.rtcpParameters.compound},e.rtcpParameters.cname&&(s.rtcp.cname=e.rtcpParameters.cname),e.sendEncodingParameters.length&&(s.rtcp.ssrc=e.sendEncodingParameters[0].ssrc),e.rtpReceiver.receive(s))},l.prototype.setLocalDescription=function(e){var t,r,n=this;if(-1===["offer","answer"].indexOf(e.type))return Promise.reject(c("TypeError",'Unsupported type "'+e.type+'"'));if(!s("setLocalDescription",e.type,n.signalingState)||n._isClosed)return Promise.reject(c("InvalidStateError","Can not set local "+e.type+" in state "+n.signalingState));if("offer"===e.type)t=i.splitSections(e.sdp),r=t.shift(),t.forEach((function(e,t){var r=i.parseRtpParameters(e);n.transceivers[t].localCapabilities=r})),n.transceivers.forEach((function(e,t){n._gather(e.mid,t)}));else if("answer"===e.type){t=i.splitSections(n._remoteDescription.sdp),r=t.shift();var a=i.matchPrefix(r,"a=ice-lite").length>0;t.forEach((function(e,t){var s=n.transceivers[t],c=s.iceGatherer,d=s.iceTransport,l=s.dtlsTransport,u=s.localCapabilities,p=s.remoteCapabilities;if(!(i.isRejected(e)&&0===i.matchPrefix(e,"a=bundle-only").length||s.rejected)){var h=i.getIceParameters(e,r),m=i.getDtlsParameters(e,r);a&&(m.role="server"),n.usingBundle&&0!==t||(n._gather(s.mid,t),"new"===d.state&&d.start(c,h,a?"controlling":"controlled"),"new"===l.state&&l.start(m));var g=o(u,p);n._transceive(s,g.codecs.length>0,!1)}}))}return n._localDescription={type:e.type,sdp:e.sdp},"offer"===e.type?n._updateSignalingState("have-local-offer"):n._updateSignalingState("stable"),Promise.resolve()},l.prototype.setRemoteDescription=function(n){var l=this;if(-1===["offer","answer"].indexOf(n.type))return Promise.reject(c("TypeError",'Unsupported type "'+n.type+'"'));if(!s("setRemoteDescription",n.type,l.signalingState)||l._isClosed)return Promise.reject(c("InvalidStateError","Can not set remote "+n.type+" in state "+l.signalingState));var u={};l.remoteStreams.forEach((function(e){u[e.id]=e}));var p=[],h=i.splitSections(n.sdp),m=h.shift(),g=i.matchPrefix(m,"a=ice-lite").length>0,v=i.matchPrefix(m,"a=group:BUNDLE ").length>0;l.usingBundle=v;var f=i.matchPrefix(m,"a=ice-options:")[0];return l.canTrickleIceCandidates=!!f&&f.substr(14).split(" ").indexOf("trickle")>=0,h.forEach((function(s,c){var d=i.splitLines(s),h=i.getKind(s),f=i.isRejected(s)&&0===i.matchPrefix(s,"a=bundle-only").length,_=d[0].substr(2).split(" ")[2],S=i.getDirection(s,m),C=i.parseMsid(s),b=i.getMid(s)||i.generateIdentifier();if(f||"application"===h&&("DTLS/SCTP"===_||"UDP/DTLS/SCTP"===_))l.transceivers[c]={mid:b,kind:h,protocol:_,rejected:!0};else{var y,E,T,P,R,w,I,N,D;!f&&l.transceivers[c]&&l.transceivers[c].rejected&&(l.transceivers[c]=l._createTransceiver(h,!0));var O,k,M=i.parseRtpParameters(s);f||(O=i.getIceParameters(s,m),(k=i.getDtlsParameters(s,m)).role="client"),I=i.parseRtpEncodingParameters(s);var x=i.parseRtcpParameters(s),L=i.matchPrefix(s,"a=end-of-candidates",m).length>0,A=i.matchPrefix(s,"a=candidate:").map((function(e){return i.parseCandidate(e)})).filter((function(e){return 1===e.component}));if(("offer"===n.type||"answer"===n.type)&&!f&&v&&c>0&&l.transceivers[c]&&(l._disposeIceAndDtlsTransports(c),l.transceivers[c].iceGatherer=l.transceivers[0].iceGatherer,l.transceivers[c].iceTransport=l.transceivers[0].iceTransport,l.transceivers[c].dtlsTransport=l.transceivers[0].dtlsTransport,l.transceivers[c].rtpSender&&l.transceivers[c].rtpSender.setTransport(l.transceivers[0].dtlsTransport),l.transceivers[c].rtpReceiver&&l.transceivers[c].rtpReceiver.setTransport(l.transceivers[0].dtlsTransport)),"offer"!==n.type||f)"answer"!==n.type||f||(E=(y=l.transceivers[c]).iceGatherer,T=y.iceTransport,P=y.dtlsTransport,R=y.rtpReceiver,w=y.sendEncodingParameters,N=y.localCapabilities,l.transceivers[c].recvEncodingParameters=I,l.transceivers[c].remoteCapabilities=M,l.transceivers[c].rtcpParameters=x,A.length&&"new"===T.state&&(!g&&!L||v&&0!==c?A.forEach((function(e){a(y.iceTransport,e)})):T.setRemoteCandidates(A)),v&&0!==c||("new"===T.state&&T.start(E,O,"controlling"),"new"===P.state&&P.start(k)),!o(y.localCapabilities,y.remoteCapabilities).codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&y.sendEncodingParameters[0].rtx&&delete y.sendEncodingParameters[0].rtx,l._transceive(y,"sendrecv"===S||"recvonly"===S,"sendrecv"===S||"sendonly"===S),!R||"sendrecv"!==S&&"sendonly"!==S?delete y.rtpReceiver:(D=R.track,C?(u[C.stream]||(u[C.stream]=new e.MediaStream),r(D,u[C.stream]),p.push([D,R,u[C.stream]])):(u.default||(u.default=new e.MediaStream),r(D,u.default),p.push([D,R,u.default]))));else{(y=l.transceivers[c]||l._createTransceiver(h)).mid=b,y.iceGatherer||(y.iceGatherer=l._createIceGatherer(c,v)),A.length&&"new"===y.iceTransport.state&&(!L||v&&0!==c?A.forEach((function(e){a(y.iceTransport,e)})):y.iceTransport.setRemoteCandidates(A)),N=e.RTCRtpReceiver.getCapabilities(h),t<15019&&(N.codecs=N.codecs.filter((function(e){return"rtx"!==e.name}))),w=y.sendEncodingParameters||[{ssrc:1001*(2*c+2)}];var j,U=!1;"sendrecv"===S||"sendonly"===S?(U=!y.rtpReceiver,R=y.rtpReceiver||new e.RTCRtpReceiver(y.dtlsTransport,h),U&&(D=R.track,C&&"-"===C.stream||(C?(u[C.stream]||(u[C.stream]=new e.MediaStream,Object.defineProperty(u[C.stream],"id",{get:function(){return C.stream}})),Object.defineProperty(D,"id",{get:function(){return C.track}}),j=u[C.stream]):(u.default||(u.default=new e.MediaStream),j=u.default)),j&&(r(D,j),y.associatedRemoteMediaStreams.push(j)),p.push([D,R,j]))):y.rtpReceiver&&y.rtpReceiver.track&&(y.associatedRemoteMediaStreams.forEach((function(t){var r=t.getTracks().find((function(e){return e.id===y.rtpReceiver.track.id}));r&&function(t,r){r.removeTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("removetrack",{track:t}))}(r,t)})),y.associatedRemoteMediaStreams=[]),y.localCapabilities=N,y.remoteCapabilities=M,y.rtpReceiver=R,y.rtcpParameters=x,y.sendEncodingParameters=w,y.recvEncodingParameters=I,l._transceive(l.transceivers[c],!1,U)}}})),void 0===l._dtlsRole&&(l._dtlsRole="offer"===n.type?"active":"passive"),l._remoteDescription={type:n.type,sdp:n.sdp},"offer"===n.type?l._updateSignalingState("have-remote-offer"):l._updateSignalingState("stable"),Object.keys(u).forEach((function(t){var r=u[t];if(r.getTracks().length){if(-1===l.remoteStreams.indexOf(r)){l.remoteStreams.push(r);var i=new Event("addstream");i.stream=r,e.setTimeout((function(){l._dispatchEvent("addstream",i)}))}p.forEach((function(e){var t=e[0],i=e[1];r.id===e[2].id&&d(l,t,i,[r])}))}})),p.forEach((function(e){e[2]||d(l,e[0],e[1],[])})),e.setTimeout((function(){l&&l.transceivers&&l.transceivers.forEach((function(e){e.iceTransport&&"new"===e.iceTransport.state&&e.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),e.iceTransport.addRemoteCandidate({}))}))}),4e3),Promise.resolve()},l.prototype.close=function(){this.transceivers.forEach((function(e){e.iceTransport&&e.iceTransport.stop(),e.dtlsTransport&&e.dtlsTransport.stop(),e.rtpSender&&e.rtpSender.stop(),e.rtpReceiver&&e.rtpReceiver.stop()})),this._isClosed=!0,this._updateSignalingState("closed")},l.prototype._updateSignalingState=function(e){this.signalingState=e;var t=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",t)},l.prototype._maybeFireNegotiationNeeded=function(){var t=this;"stable"===this.signalingState&&!0!==this.needNegotiation&&(this.needNegotiation=!0,e.setTimeout((function(){if(t.needNegotiation){t.needNegotiation=!1;var e=new Event("negotiationneeded");t._dispatchEvent("negotiationneeded",e)}}),0))},l.prototype._updateIceConnectionState=function(){var e,t={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(e){e.iceTransport&&!e.rejected&&t[e.iceTransport.state]++})),e="new",t.failed>0?e="failed":t.checking>0?e="checking":t.disconnected>0?e="disconnected":t.new>0?e="new":t.connected>0?e="connected":t.completed>0&&(e="completed"),e!==this.iceConnectionState){this.iceConnectionState=e;var r=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",r)}},l.prototype._updateConnectionState=function(){var e,t={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(e){e.iceTransport&&e.dtlsTransport&&!e.rejected&&(t[e.iceTransport.state]++,t[e.dtlsTransport.state]++)})),t.connected+=t.completed,e="new",t.failed>0?e="failed":t.connecting>0?e="connecting":t.disconnected>0?e="disconnected":t.new>0?e="new":t.connected>0&&(e="connected"),e!==this.connectionState){this.connectionState=e;var r=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",r)}},l.prototype.createOffer=function(){var r=this;if(r._isClosed)return Promise.reject(c("InvalidStateError","Can not call createOffer after close"));var o=r.transceivers.filter((function(e){return"audio"===e.kind})).length,s=r.transceivers.filter((function(e){return"video"===e.kind})).length,a=arguments[0];if(a){if(a.mandatory||a.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");void 0!==a.offerToReceiveAudio&&(o=!0===a.offerToReceiveAudio?1:!1===a.offerToReceiveAudio?0:a.offerToReceiveAudio),void 0!==a.offerToReceiveVideo&&(s=!0===a.offerToReceiveVideo?1:!1===a.offerToReceiveVideo?0:a.offerToReceiveVideo)}for(r.transceivers.forEach((function(e){"audio"===e.kind?--o<0&&(e.wantReceive=!1):"video"===e.kind&&--s<0&&(e.wantReceive=!1)}));o>0||s>0;)o>0&&(r._createTransceiver("audio"),o--),s>0&&(r._createTransceiver("video"),s--);var d=i.writeSessionBoilerplate(r._sdpSessionId,r._sdpSessionVersion++);r.transceivers.forEach((function(n,o){var s=n.track,a=n.kind,c=n.mid||i.generateIdentifier();n.mid=c,n.iceGatherer||(n.iceGatherer=r._createIceGatherer(o,r.usingBundle));var d=e.RTCRtpSender.getCapabilities(a);t<15019&&(d.codecs=d.codecs.filter((function(e){return"rtx"!==e.name}))),d.codecs.forEach((function(e){"H264"===e.name&&void 0===e.parameters["level-asymmetry-allowed"]&&(e.parameters["level-asymmetry-allowed"]="1"),n.remoteCapabilities&&n.remoteCapabilities.codecs&&n.remoteCapabilities.codecs.forEach((function(t){e.name.toLowerCase()===t.name.toLowerCase()&&e.clockRate===t.clockRate&&(e.preferredPayloadType=t.payloadType)}))})),d.headerExtensions.forEach((function(e){(n.remoteCapabilities&&n.remoteCapabilities.headerExtensions||[]).forEach((function(t){e.uri===t.uri&&(e.id=t.id)}))}));var l=n.sendEncodingParameters||[{ssrc:1001*(2*o+1)}];s&&t>=15019&&"video"===a&&!l[0].rtx&&(l[0].rtx={ssrc:l[0].ssrc+1}),n.wantReceive&&(n.rtpReceiver=new e.RTCRtpReceiver(n.dtlsTransport,a)),n.localCapabilities=d,n.sendEncodingParameters=l})),"max-compat"!==r._config.bundlePolicy&&(d+="a=group:BUNDLE "+r.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),d+="a=ice-options:trickle\r\n",r.transceivers.forEach((function(e,t){d+=n(e,e.localCapabilities,"offer",e.stream,r._dtlsRole),d+="a=rtcp-rsize\r\n",!e.iceGatherer||"new"===r.iceGatheringState||0!==t&&r.usingBundle||(e.iceGatherer.getLocalCandidates().forEach((function(e){e.component=1,d+="a="+i.writeCandidate(e)+"\r\n"})),"completed"===e.iceGatherer.state&&(d+="a=end-of-candidates\r\n"))}));var l=new e.RTCSessionDescription({type:"offer",sdp:d});return Promise.resolve(l)},l.prototype.createAnswer=function(){var r=this;if(r._isClosed)return Promise.reject(c("InvalidStateError","Can not call createAnswer after close"));if("have-remote-offer"!==r.signalingState&&"have-local-pranswer"!==r.signalingState)return Promise.reject(c("InvalidStateError","Can not call createAnswer in signalingState "+r.signalingState));var s=i.writeSessionBoilerplate(r._sdpSessionId,r._sdpSessionVersion++);r.usingBundle&&(s+="a=group:BUNDLE "+r.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),s+="a=ice-options:trickle\r\n";var a=i.getMediaSections(r._remoteDescription.sdp).length;r.transceivers.forEach((function(e,i){if(!(i+1>a)){if(e.rejected)return"application"===e.kind?"DTLS/SCTP"===e.protocol?s+="m=application 0 DTLS/SCTP 5000\r\n":s+="m=application 0 "+e.protocol+" webrtc-datachannel\r\n":"audio"===e.kind?s+="m=audio 0 UDP/TLS/RTP/SAVPF 0\r\na=rtpmap:0 PCMU/8000\r\n":"video"===e.kind&&(s+="m=video 0 UDP/TLS/RTP/SAVPF 120\r\na=rtpmap:120 VP8/90000\r\n"),void(s+="c=IN IP4 0.0.0.0\r\na=inactive\r\na=mid:"+e.mid+"\r\n");var c;e.stream&&("audio"===e.kind?c=e.stream.getAudioTracks()[0]:"video"===e.kind&&(c=e.stream.getVideoTracks()[0]),c&&t>=15019&&"video"===e.kind&&!e.sendEncodingParameters[0].rtx&&(e.sendEncodingParameters[0].rtx={ssrc:e.sendEncodingParameters[0].ssrc+1}));var d=o(e.localCapabilities,e.remoteCapabilities);!d.codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&e.sendEncodingParameters[0].rtx&&delete e.sendEncodingParameters[0].rtx,s+=n(e,d,"answer",e.stream,r._dtlsRole),e.rtcpParameters&&e.rtcpParameters.reducedSize&&(s+="a=rtcp-rsize\r\n")}}));var d=new e.RTCSessionDescription({type:"answer",sdp:s});return Promise.resolve(d)},l.prototype.addIceCandidate=function(e){var t,r=this;return e&&void 0===e.sdpMLineIndex&&!e.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise((function(n,o){if(!r._remoteDescription)return o(c("InvalidStateError","Can not add ICE candidate without a remote description"));if(e&&""!==e.candidate){var s=e.sdpMLineIndex;if(e.sdpMid)for(var d=0;d<r.transceivers.length;d++)if(r.transceivers[d].mid===e.sdpMid){s=d;break}var l=r.transceivers[s];if(!l)return o(c("OperationError","Can not add ICE candidate"));if(l.rejected)return n();var u=Object.keys(e.candidate).length>0?i.parseCandidate(e.candidate):{};if("tcp"===u.protocol&&(0===u.port||9===u.port))return n();if(u.component&&1!==u.component)return n();if((0===s||s>0&&l.iceTransport!==r.transceivers[0].iceTransport)&&!a(l.iceTransport,u))return o(c("OperationError","Can not add ICE candidate"));var p=e.candidate.trim();0===p.indexOf("a=")&&(p=p.substr(2)),(t=i.getMediaSections(r._remoteDescription.sdp))[s]+="a="+(u.type?p:"end-of-candidates")+"\r\n",r._remoteDescription.sdp=i.getDescription(r._remoteDescription.sdp)+t.join("")}else for(var h=0;h<r.transceivers.length&&(r.transceivers[h].rejected||(r.transceivers[h].iceTransport.addRemoteCandidate({}),(t=i.getMediaSections(r._remoteDescription.sdp))[h]+="a=end-of-candidates\r\n",r._remoteDescription.sdp=i.getDescription(r._remoteDescription.sdp)+t.join(""),!r.usingBundle));h++);n()}))},l.prototype.getStats=function(t){if(t&&t instanceof e.MediaStreamTrack){var r=null;if(this.transceivers.forEach((function(e){e.rtpSender&&e.rtpSender.track===t?r=e.rtpSender:e.rtpReceiver&&e.rtpReceiver.track===t&&(r=e.rtpReceiver)})),!r)throw c("InvalidAccessError","Invalid selector.");return r.getStats()}var i=[];return this.transceivers.forEach((function(e){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach((function(t){e[t]&&i.push(e[t].getStats())}))})),Promise.all(i).then((function(e){var t=new Map;return e.forEach((function(e){e.forEach((function(e){t.set(e.id,e)}))})),t}))},["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach((function(t){var r=e[t];if(r&&r.prototype&&r.prototype.getStats){var i=r.prototype.getStats;r.prototype.getStats=function(){return i.apply(this).then((function(e){var t=new Map;return Object.keys(e).forEach((function(r){var i;e[r].type={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[(i=e[r]).type]||i.type,t.set(r,e[r])})),t}))}}}));var u=["createOffer","createAnswer"];return u.forEach((function(e){var t=l.prototype[e];l.prototype[e]=function(){var e=arguments;return"function"==typeof e[0]||"function"==typeof e[1]?t.apply(this,[arguments[2]]).then((function(t){"function"==typeof e[0]&&e[0].apply(null,[t])}),(function(t){"function"==typeof e[1]&&e[1].apply(null,[t])})):t.apply(this,arguments)}})),(u=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach((function(e){var t=l.prototype[e];l.prototype[e]=function(){var e=arguments;return"function"==typeof e[1]||"function"==typeof e[2]?t.apply(this,arguments).then((function(){"function"==typeof e[1]&&e[1].apply(null)}),(function(t){"function"==typeof e[2]&&e[2].apply(null,[t])})):t.apply(this,arguments)}})),["getStats"].forEach((function(e){var t=l.prototype[e];l.prototype[e]=function(){var e=arguments;return"function"==typeof e[1]?t.apply(this,arguments).then((function(){"function"==typeof e[1]&&e[1].apply(null)})):t.apply(this,arguments)}})),l}},{sdp:17}],17:[function(e,t,r){"use strict";var i={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};i.localCName=i.generateIdentifier(),i.splitLines=function(e){return e.trim().split("\n").map((function(e){return e.trim()}))},i.splitSections=function(e){return e.split("\nm=").map((function(e,t){return(t>0?"m="+e:e).trim()+"\r\n"}))},i.getDescription=function(e){var t=i.splitSections(e);return t&&t[0]},i.getMediaSections=function(e){var t=i.splitSections(e);return t.shift(),t},i.matchPrefix=function(e,t){return i.splitLines(e).filter((function(e){return 0===e.indexOf(t)}))},i.parseCandidate=function(e){for(var t,r={foundation:(t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" "))[0],component:parseInt(t[1],10),protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]},i=8;i<t.length;i+=2)switch(t[i]){case"raddr":r.relatedAddress=t[i+1];break;case"rport":r.relatedPort=parseInt(t[i+1],10);break;case"tcptype":r.tcpType=t[i+1];break;case"ufrag":r.ufrag=t[i+1],r.usernameFragment=t[i+1];break;default:r[t[i]]=t[i+1]}return r},i.writeCandidate=function(e){var t=[];t.push(e.foundation),t.push(e.component),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);var r=e.type;return t.push("typ"),t.push(r),"host"!==r&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},i.parseIceOptions=function(e){return e.substr(14).split(" ")},i.parseRtpMap=function(e){var t=e.substr(9).split(" "),r={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),r.name=t[0],r.clockRate=parseInt(t[1],10),r.channels=3===t.length?parseInt(t[2],10):1,r.numChannels=r.channels,r},i.writeRtpMap=function(e){var t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);var r=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==r?"/"+r:"")+"\r\n"},i.parseExtmap=function(e){var t=e.substr(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1]}},i.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+"\r\n"},i.parseFmtp=function(e){for(var t,r={},i=e.substr(e.indexOf(" ")+1).split(";"),n=0;n<i.length;n++)r[(t=i[n].trim().split("="))[0].trim()]=t[1];return r},i.writeFmtp=function(e){var t="",r=e.payloadType;if(void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){var i=[];Object.keys(e.parameters).forEach((function(t){e.parameters[t]?i.push(t+"="+e.parameters[t]):i.push(t)})),t+="a=fmtp:"+r+" "+i.join(";")+"\r\n"}return t},i.parseRtcpFb=function(e){var t=e.substr(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},i.writeRtcpFb=function(e){var t="",r=e.payloadType;return void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((function(e){t+="a=rtcp-fb:"+r+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},i.parseSsrcMedia=function(e){var t=e.indexOf(" "),r={ssrc:parseInt(e.substr(7,t-7),10)},i=e.indexOf(":",t);return i>-1?(r.attribute=e.substr(t+1,i-t-1),r.value=e.substr(i+1)):r.attribute=e.substr(t+1),r},i.parseSsrcGroup=function(e){var t=e.substr(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((function(e){return parseInt(e,10)}))}},i.getMid=function(e){var t=i.matchPrefix(e,"a=mid:")[0];if(t)return t.substr(6)},i.parseFingerprint=function(e){var t=e.substr(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1]}},i.getDtlsParameters=function(e,t){return{role:"auto",fingerprints:i.matchPrefix(e+t,"a=fingerprint:").map(i.parseFingerprint)}},i.writeDtlsParameters=function(e,t){var r="a=setup:"+t+"\r\n";return e.fingerprints.forEach((function(e){r+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),r},i.getIceParameters=function(e,t){var r=i.splitLines(e);return{usernameFragment:(r=r.concat(i.splitLines(t))).filter((function(e){return 0===e.indexOf("a=ice-ufrag:")}))[0].substr(12),password:r.filter((function(e){return 0===e.indexOf("a=ice-pwd:")}))[0].substr(10)}},i.writeIceParameters=function(e){return"a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n"},i.parseRtpParameters=function(e){for(var t={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},r=i.splitLines(e)[0].split(" "),n=3;n<r.length;n++){var o=r[n],s=i.matchPrefix(e,"a=rtpmap:"+o+" ")[0];if(s){var a=i.parseRtpMap(s),c=i.matchPrefix(e,"a=fmtp:"+o+" ");switch(a.parameters=c.length?i.parseFmtp(c[0]):{},a.rtcpFeedback=i.matchPrefix(e,"a=rtcp-fb:"+o+" ").map(i.parseRtcpFb),t.codecs.push(a),a.name.toUpperCase()){case"RED":case"ULPFEC":t.fecMechanisms.push(a.name.toUpperCase())}}}return i.matchPrefix(e,"a=extmap:").forEach((function(e){t.headerExtensions.push(i.parseExtmap(e))})),t},i.writeRtpDescription=function(e,t){var r="";r+="m="+e+" ",r+=t.codecs.length>0?"9":"0",r+=" UDP/TLS/RTP/SAVPF ",r+=t.codecs.map((function(e){return void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType})).join(" ")+"\r\n",r+="c=IN IP4 0.0.0.0\r\n",r+="a=rtcp:9 IN IP4 0.0.0.0\r\n",t.codecs.forEach((function(e){r+=i.writeRtpMap(e),r+=i.writeFmtp(e),r+=i.writeRtcpFb(e)}));var n=0;return t.codecs.forEach((function(e){e.maxptime>n&&(n=e.maxptime)})),n>0&&(r+="a=maxptime:"+n+"\r\n"),r+="a=rtcp-mux\r\n",t.headerExtensions&&t.headerExtensions.forEach((function(e){r+=i.writeExtmap(e)})),r},i.parseRtpEncodingParameters=function(e){var t,r=[],n=i.parseRtpParameters(e),o=-1!==n.fecMechanisms.indexOf("RED"),s=-1!==n.fecMechanisms.indexOf("ULPFEC"),a=i.matchPrefix(e,"a=ssrc:").map((function(e){return i.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute})),c=a.length>0&&a[0].ssrc,d=i.matchPrefix(e,"a=ssrc-group:FID").map((function(e){return e.substr(17).split(" ").map((function(e){return parseInt(e,10)}))}));d.length>0&&d[0].length>1&&d[0][0]===c&&(t=d[0][1]),n.codecs.forEach((function(e){if("RTX"===e.name.toUpperCase()&&e.parameters.apt){var i={ssrc:c,codecPayloadType:parseInt(e.parameters.apt,10)};c&&t&&(i.rtx={ssrc:t}),r.push(i),o&&((i=JSON.parse(JSON.stringify(i))).fec={ssrc:c,mechanism:s?"red+ulpfec":"red"},r.push(i))}})),0===r.length&&c&&r.push({ssrc:c});var l=i.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substr(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substr(5),10)*.95-16e3:void 0,r.forEach((function(e){e.maxBitrate=l}))),r},i.parseRtcpParameters=function(e){var t={},r=i.matchPrefix(e,"a=ssrc:").map((function(e){return i.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute}))[0];r&&(t.cname=r.value,t.ssrc=r.ssrc);var n=i.matchPrefix(e,"a=rtcp-rsize");t.reducedSize=n.length>0,t.compound=0===n.length;var o=i.matchPrefix(e,"a=rtcp-mux");return t.mux=o.length>0,t},i.parseMsid=function(e){var t,r=i.matchPrefix(e,"a=msid:");if(1===r.length)return{stream:(t=r[0].substr(7).split(" "))[0],track:t[1]};var n=i.matchPrefix(e,"a=ssrc:").map((function(e){return i.parseSsrcMedia(e)})).filter((function(e){return"msid"===e.attribute}));return n.length>0?{stream:(t=n[0].value.split(" "))[0],track:t[1]}:void 0},i.parseSctpDescription=function(e){var t,r=i.parseMLine(e),n=i.matchPrefix(e,"a=max-message-size:");n.length>0&&(t=parseInt(n[0].substr(19),10)),isNaN(t)&&(t=65536);var o=i.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substr(12),10),protocol:r.fmt,maxMessageSize:t};if(i.matchPrefix(e,"a=sctpmap:").length>0){var s=i.matchPrefix(e,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(s[0],10),protocol:s[1],maxMessageSize:t}}},i.writeSctpDescription=function(e,t){var r=[];return r="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&r.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),r.join("")},i.generateSessionId=function(){return Math.random().toString().substr(2,21)},i.writeSessionBoilerplate=function(e,t,r){var n=void 0!==t?t:2;return"v=0\r\no="+(r||"thisisadapterortc")+" "+(e||i.generateSessionId())+" "+n+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},i.writeMediaSection=function(e,t,r,n){var o=i.writeRtpDescription(e.kind,t);if(o+=i.writeIceParameters(e.iceGatherer.getLocalParameters()),o+=i.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===r?"actpass":"active"),o+="a=mid:"+e.mid+"\r\n",e.direction?o+="a="+e.direction+"\r\n":e.rtpSender&&e.rtpReceiver?o+="a=sendrecv\r\n":e.rtpSender?o+="a=sendonly\r\n":e.rtpReceiver?o+="a=recvonly\r\n":o+="a=inactive\r\n",e.rtpSender){var s="msid:"+n.id+" "+e.rtpSender.track.id+"\r\n";o+="a="+s,o+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+s,e.sendEncodingParameters[0].rtx&&(o+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+s,o+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return o+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+i.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(o+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+i.localCName+"\r\n"),o},i.getDirection=function(e,t){for(var r=i.splitLines(e),n=0;n<r.length;n++)switch(r[n]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[n].substr(2)}return t?i.getDirection(t):"sendrecv"},i.getKind=function(e){return i.splitLines(e)[0].split(" ")[0].substr(2)},i.isRejected=function(e){return"0"===e.split(" ",2)[1]},i.parseMLine=function(e){var t=i.splitLines(e)[0].substr(2).split(" ");return{kind:t[0],port:parseInt(t[1],10),protocol:t[2],fmt:t.slice(3).join(" ")}},i.parseOLine=function(e){var t=i.matchPrefix(e,"o=")[0].substr(2).split(" ");return{username:t[0],sessionId:t[1],sessionVersion:parseInt(t[2],10),netType:t[3],addressType:t[4],address:t[5]}},i.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;for(var t=i.splitLines(e),r=0;r<t.length;r++)if(t[r].length<2||"="!==t[r].charAt(1))return!1;return!0},"object"==typeof t&&(t.exports=i)},{}]},{},[1])(1)},function(e,t,r){var i,n;i=[r(0),r(3),r(1)],void 0===(n=function(e,t,r){"use strict";var i=e.stringifyJSON,n=e.isObject,o=e.isNumber,s=e.isBool;function a(){t.call(this),this._logger=r.create("RtcStats","console"),this._logger.verbose("RtcStats()"),this.videoTimestampPrev=null,this.videoFramesPrev=null,this.videoBytesPrev=0,this.audioTimestampPrev=null,this.audioBytesPrev=0,this.firstReportTimestamp=0,this.videoSsrcPrev=0,this.frameWidthPrev=void 0,this.frameHeightPrev=void 0,this.resolutionChanged=void 0}var c=a.prototype=Object.create(t.prototype);return a.logger=r.create("RtcStats","console"),c.putReport=function(e,t,r){this._logger.verbose("putReport("+i(e)+", "+t+", "+r+")");var n=this._filterStats(e,t,r);this.emitSimple("ReceivedWebRTCStats",{results:n})},c._filterStats=function(e,t,r){if(this._logger.verbose("_filterStats("+i(e)+", "+t+")"),n(e)){var a=this,c={};return e.forEach((function(i){if((!t||"video"===t)&&("track"===i.type&&("video"===i.kind||i.id&&-1!==i.id.indexOf("RTCMediaStreamTrack_sender")||s(i.remoteSource)&&!1===i.remoteSource)&&(i.framesPerSecond&&(c.framerate=Math.round(10*i.framesPerSecond)/10),i.frameWidth&&(c.frameWidth=i.frameWidth,c.frameHeight=i.frameHeight,o(a.frameWidthPrev)&&o(a.frameHeightPrev)?a.frameWidthPrev!==i.frameWidth||a.frameHeightPrev!==i.frameHeight?(a.resolutionChanged=1,a.frameWidthPrev=i.frameWidth,a.frameHeightPrev=i.frameHeight):a.resolutionChanged=0:(a.frameWidthPrev=i.frameWidth,a.frameHeightPrev=i.frameHeight,a.resolutionChanged=0))),"outbound-rtp"===i.type&&"video"===i.mediaType)){if(i.codecId)if(f=e.get(i.codecId)){var n=f.mimeType;c.videoCodec=n}else c.videoCodec=i.codecId;var d=i.timestamp;if(i.bytesSent){var l=i.bytesSent;if(a.videoBytesPrev&&a.videoTimestampPrev){var u=8*(l-a.videoBytesPrev)/(d-a.videoTimestampPrev);c.videoBitrate=Math.round(u)}a.videoBytesPrev=l}if(i.framesEncoded&&a.videoTimestampPrev){if(a.videoFramesPrev){var p=1e3*(i.framesEncoded-a.videoFramesPrev)/(d-a.videoTimestampPrev);c.framerate=Math.round(10*p)/10}a.videoFramesPrev=i.framesEncoded}if(r){if(c.extended={nackCount:void 0,framesEncoded:void 0,keyFramesEncoded:void 0,totalEncodeTime:void 0,averageEncodeTime:void 0,encodeTimePercentage:void 0,idleTimePercentage:void 0,firCount:void 0,pliCount:void 0,resolutionChanged:void 0,priority:0},c.extended.nackCount=i.nackCount,c.extended.framesEncoded=i.framesEncoded,c.extended.keyFramesEncoded=i.keyFramesEncoded,c.extended.totalEncodeTime=i.totalEncodeTime,o(i.totalEncodeTime)&&o(i.framesEncoded)){var h=i.totalEncodeTime/i.framesEncoded;c.extended.averageEncodeTime=Math.round(1e3*h)/1e3}if(a.firstReportTimestamp&&o(i.totalEncodeTime)){var m=(d-a.firstReportTimestamp)/1e3,g=100*i.totalEncodeTime/m,v=100-g;c.extended.encodeTimePercentage=Math.round(1e3*g)/1e3,c.extended.idleTimePercentage=Math.round(1e3*v)/1e3}i.ssrc&&a.videoSsrcPrev!==i.ssrc&&(a.videoSsrcPrev=i.ssrc,a.firstReportTimestamp=i.timestamp),c.extended.firCount=i.firCount,c.extended.pliCount=i.pliCount,c.extended.resolutionChanged=a.resolutionChanged,1===a.resolutionChanged&&(c.extended.priority=1)}a.videoTimestampPrev=d}if((!t||"audio"===t)&&"outbound-rtp"===i.type&&"audio"===i.mediaType){var f;if(i.codecId)if(f=e.get(i.codecId)){n=f.mimeType;c.audioCodec=n}else c.audioCodec=i.codecId;d=i.timestamp;if(i.bytesSent){l=i.bytesSent;if(a.audioBytesPrev&&a.audioTimestampPrev){u=8*(l-a.audioBytesPrev)/(d-a.audioTimestampPrev);c.audioBitrate=Math.round(u)}a.audioBytesPrev=l}a.audioTimestampPrev=d}})),c}},a}.apply(t,i))||(e.exports=n)},function(e,t,r){var i,n;i=[r(14),r(15),r(4),r(0),r(30),r(6)],void 0===(n=function(e,t,r,i,n,o){"use strict";window.nanowebrtc={user:e,userinternal:t,tools:i,const:r,audioprocess:n,version:o.webrtc.release_version,release_description:o.webrtc.release_description}}.apply(t,i))||(e.exports=n)},function(e,t,r){var i,n;i=[r(3),r(0),r(4)],void 0===(n=function(e,t,r){"use strict";var i=t.parseJSON,n=t.stringifyJSON;function o(){e.call(this);var t=window.nanowebrtc.userinternal;this._rtcUser=new t;var i=this;r.EVENT_NAMES.webcast.forEach((function(e){i._rtcUser.on(e,(function(e){i.emitSimple(e.name,e.data,e.error)}))})),r.EVENT_NAMES.chat.forEach((function(e){i._rtcUser.on(e,(function(e){i.emit(e.name,e.data)}))})),o.browserSupport=t.browserSupport}var s=o.prototype=Object.create(e.prototype);return o.browserSupport={supportLevel:-1,supportText:""},o.checkSupport=function(){var e=window.nanowebrtc.userinternal;return o.browserSupport=e.checkSupport(),i(n(o.browserSupport))},s.signIn=function(e){return this._rtcUser.signIn(e)},s.signOut=function(){this._rtcUser.signOut()},s.isSignedIn=function(){return this._rtcUser.isSignedIn()},s.setConfig=function(e){this._rtcUser.setConfig(e)},s.setIceServers=function(e){this._rtcUser.setIceServers(e)},s.checkServer=function(e){this._rtcUser.checkServer(e)},s.enableStats=function(e,t){this._rtcUser.enableStats(e,t)},s.startBroadcast=function(e){this._rtcUser.startBroadcast(e)},s.stopBroadcast=function(){this._rtcUser.stopBroadcast()},s.sendMetaData=function(e,t){this._rtcUser.sendMetaData(e,t)},s.enterRoom=function(e){this._rtcUser.enterRoom(e)},s.leaveRoom=function(){this._rtcUser.leaveRoom()},s.invokeCall=function(e){this._rtcUser.invokeCall(e)},s.hangUpCall=function(e){this._rtcUser.hangUpCall(e)},s.answerCall=function(e){this._rtcUser.answerCall(e)},s.declineCall=function(e){this._rtcUser.declineCall(e)},s.addScreenCaptureExtension=function(e){this._rtcUser.addScreenCaptureExtension(e)},s.isScreenCaptureAvailable=function(){return this._rtcUser.isScreenCaptureAvailable()},s.getDevices=function(){this._rtcUser.getDevices()},s.setVideoDevice=function(e){this._rtcUser.setVideoDevice(e)},s.setAudioDevice=function(e){this._rtcUser.setAudioDevice(e)},s.getSelectedVideoDevice=function(){this._rtcUser.getSelectedVideoDevice()},s.getSelectedAudioDevice=function(){this._rtcUser.getSelectedAudioDevice()},s.getSelectedDevice=function(e){this._rtcUser.getSelectedDevice(e)},s.startPreview=function(e){this._rtcUser.startPreview(e)},s.stopPreview=function(){this._rtcUser.stopPreview()},s.muteVideo=function(e){this._rtcUser.muteVideo(e)},s.muteAudio=function(e){this._rtcUser.muteAudio(e)},s.muteDevice=function(e){this._rtcUser.muteDevice(e)},s.injectExternalMediaStream=function(e){return this._rtcUser.injectExternalMediaStream(e)},o}.apply(t,i))||(e.exports=n)},function(e,t,r){var i,n;i=[r(16),r(4),r(0),r(3),r(21),r(22),r(7),r(25),r(5),r(26),r(2),r(1),r(28)],void 0===(n=function(e,t,r,i,n,o,s,a,c,d,l,u,p){"use strict";var h=r.getElement,m=r.stringifyJSON,g=r.parseJSON,v=r.isObject,f=r.isArray,_=r.isString,S=r.isBool,C=r.isNumber,b=r.isIntInRange,y=r.isEmpty,E={Chrome:{versions:{current:72,minimal:50},mobile:!0},Firefox:{versions:{current:66,minimal:42},mobile:!0},Opera:{versions:{current:60,minimal:40},mobile:!0},"Microsoft Edge":{versions:void 0,mobile:void 0},Safari:{versions:{current:12,minimal:11},mobile:!1}};function T(){i.call(this),this._logger=u.create("RtcUser","console"),this._logger.verbose("RtcUser()"),this._userId=void 0,this._iceServers=[{urls:["stun:stun.l.google.com:19302"]},{urls:["stun:stun.nanocosmos.net:80"],username:"nano",credential:"nano"}],this._iceServersOverride=void 0,this._config={codecs:{videoCodec:"H264"},bitrates:{videoSendInitialBitrate:0,videoSendBitrate:0},sdpPatches:{preventReplaceSendReceive:!1}},this._streamProtected=!1,this._statsEnabled=!1,this._statsIntervalTime=1e3,this._metricsEnabled=!1,this._broadcaster=void 0,this._isBroadcasting=!1,this._audioMixer=new n,this._session=void 0,this._deviceController=new o,this._mediaController=new s(this._deviceController),this._mediaController.on("StreamTrackEnded",this._onStreamTrackEnded.bind(this)),this._screenCaptureExtension=new a;var e=this._screenCaptureExtension.getScreenCaptureName(),t=this._deviceController.addScreenCaptureDevice(e);t.length>0&&(t.updated=!0,this.emitSimple("ReceivedDeviceList",t)),this._videoDeviceConfig={},T.checkSupport()}var P=T.prototype=Object.create(i.prototype);return T.browserSupport={supportLevel:-1,supportText:""},T.logger=u.create("RtcUser","console"),T.checkSupport=function(){T.logger.verbose("checkSupport()");var e=r.browserInfo.browser,t=parseInt(r.browserInfo.browserVersion.split(".")[0],10),i=r.browserInfo.mobile,n=r.getVersionText(e,t,i);T.logger.verbose("checkSupport(): "+n);var o=1,s=E[e];void 0!==s&&(void 0!==s.versions&&void 0!==s.mobile?(o=0,t<s.versions.current&&t>=s.versions.minimal&&(o=2),(t<s.versions.minimal||i&&!1===s.mobile)&&(o=3)):o=3);var a=r.getSupportText(e,t,i,o);return 1===o&&T.logger.error("checkSupport(): "+a),T.browserSupport.supportLevel=o,T.browserSupport.supportText=a,T.browserSupport},P.signIn=function(e){this._logger.verbose("signIn("+m(e)+")");var t="signIn(): ",r=this;if(!v(e)){var i=l.TypeNotValidError("options","Object");this._logger.error(t+m(i));var n=l.composeEvent(i,"SignInError");return this.emitSimple(n.name,n.data,n.error),void this._sendMetrics(n)}return e.userName&&this._logger.warning(t+'"userName" parameter is deprecated and will be removed in the WebRTC-Client v.6'),e.room&&(this._logger.warning(t+'"room" parameter is deprecated and will be removed in the WebRTC-Client v.6'),/_/.test(e.room)&&(e.room=e.room.replace(/_/g,""),this._logger.warning(t+'"room" parameter should not contain underscores (_)'))),e.serverUserName&&this._logger.warning(t+'"serverUserName" parameter is deprecated and will be removed in the WebRTC-Client v.6'),e.serverPassword&&this._logger.warning(t+'"serverPassword" parameter is deprecated and will be removed in the WebRTC-Client v.6'),this.isSignedIn()?Promise.reject(l.SignInError("Already signed in")):(this._session=new c,this._session.on("SessionMessage",r._onSessionMessage.bind(r)),this._session.signIn(e).then((function(e){if(e.data){e.data.iceServers&&(r._iceServers=e.data.iceServers),r._userId=e.data.userId;var i=JSON.parse(JSON.stringify(e));i.name="SignInSuccess",delete i.data.iceServers,r._logger.info(t+i.name+": "+m(i)),r.emitSimple(i.name,i.data),r._sendMetrics(i)}})).catch((function(e){"NanoError"!==e.type&&(e=l.GeneralError("Failed to sign in")),r._logger.error(t+m(e));var i=l.composeEvent(e,"SignInError");r.emitSimple(i.name,i.data,i.error),r._sendMetrics(i),r._session.removeAllListeners()})))},P.signOut=function(){this._logger.verbose("signOut()");var e=this;if(!this.isSignedIn())return Promise.reject(l.NotSignedInError());this._session.signOut().then((function(){return e._destroy()})).then((function(){var t={name:"SignOutSuccess",data:{}};e.emitSimple(t.name,t.data),e._sendMetrics(t)})).catch((function(t){"NanoError"!==t.type&&(t=l.GeneralError("Failed to sign out")),e._logger.error("signOut(): "+m(t));var r=l.composeEvent(t,"SignOutError");e.emitSimple(r.name,r.data,r.error),e._sendMetrics(r)})).then((function(){e._session.removeAllListeners(),e._session=void 0}))},P.isSignedIn=function(){return this._logger.verbose("isSignedIn()"),!!this._session&&this._session.isSignedIn()},P.setConfig=function(e){this._logger.verbose("setConfig("+m(e)+")");var r="setConfig(): ";if(v(e)){var i={};if(v(e.metrics)){var n=""+e.metrics.accountId,o=""+e.metrics.accountKey;if(n.length>0&&o.length>0){i.graylog={credentials:{accountId:n,accountKey:o}};var s=JSON.parse(JSON.stringify(e.metrics));delete s.accountId,delete s.accountKey;try{this._metricsController=new p(this,s),this._metricsEnabled=!0}catch(a){this._logger.error(r+m(a)),this._metricsEnabled=!1}}}if(C(e.logLevel)&&b(e.logLevel,t.LOG_LEVEL.DISABLED,t.LOG_LEVEL.VERBOSE)&&(i.console={level:e.logLevel}),y(i)||u.setConfig(i),e.codecs)if(_(e.codecs.videoCodec))this._config.codecs.videoCodec=e.codecs.videoCodec;else if(void 0!==e.codecs.videoCodec){a=l.TypeNotValidError("config.bitrates.videoCodec","String");this._logger.error(r+m(a));c=l.composeEvent(a,"SetConfigError");this.emitSimple(c.name,c.data,c.error),this._sendMetrics(c)}if(e.bitrates){if(C(e.bitrates.videoSendInitialBitrate))this._config.bitrates.videoSendInitialBitrate=e.bitrates.videoSendInitialBitrate;else if(void 0!==e.bitrates.videoSendInitialBitrate){a=l.TypeNotValidError("config.bitrates.videoSendInitialBitrate","Number");this._logger.error(r+m(a));c=l.composeEvent(a,"SetConfigError");this.emitSimple(c.name,c.data,c.error),this._sendMetrics(c)}if(C(e.bitrates.videoSendBitrate))this._config.bitrates.videoSendBitrate=e.bitrates.videoSendBitrate;else if(void 0!==e.bitrates.videoSendBitrate){a=l.TypeNotValidError("config.bitrates.videoSendBitrate","Number");this._logger.error(r+m(a));c=l.composeEvent(a,"SetConfigError");this.emitSimple(c.name,c.data,c.error),this._sendMetrics(c)}if(C(e.bitrates.audioSendBitrate))this._config.bitrates.audioSendBitrate=e.bitrates.audioSendBitrate;else if(void 0!==e.bitrates.audioSendBitrate){a=l.TypeNotValidError("config.bitrates.audioSendBitrate","Number");this._logger.error(r+m(a));c=l.composeEvent(a,"SetConfigError");this.emitSimple(c.name,c.data,c.error),this._sendMetrics(c)}}if(e.sdpPatches)if(S(e.sdpPatches.preventReplaceSendReceive))this._config.sdpPatches.preventReplaceSendReceive=e.sdpPatches.preventReplaceSendReceive;else{a=l.TypeNotValidError("config.sdpPatches.preventReplaceSendReceive","Bool");this._logger.error(r+m(a));c=l.composeEvent(a,"SetConfigError");this.emitSimple(c.name,c.data,c.error),this._sendMetrics(c)}e.iceServers&&f(e.iceServers)&&(this._config.iceServers=e.iceServers)}else{var a=l.TypeNotValidError("config","Object");this._logger.error(r+m(a));var c=l.composeEvent(a,"SetConfigError");this.emitSimple(c.name,c.data,c.error)}},P.setIceServers=function(e){this._logger.verbose("setIceServers("+m(e)+")"),this._logger.warning('"setIceServers()" function is deprecated and will be removed in the WebRTC-Client v.6'),this._iceServersOverride=e},P.checkServer=function(e){this._logger.verbose("checkServer()");var t=this;if(!this.isSignedIn())return Promise.reject(l.NotSignedInError());this._session.status().then((function(e){t.emitSimple("ReceivedServerStats",{stats:g(e.data)||{error:{message:"Could not parse response from server",code:-1,userinfo:null}}})})).catch((function(e){t._logger.error("checkServer: "+m(e))}))},P.enableStats=function(e,t){this._logger.verbose("enableStats("+e+", "+t+")"),this._statsEnabled=void 0===e||e,this._statsIntervalTime=t||1e3},P.startBroadcast=function(t){this._logger.debug("startBroadcast("+m(t)+")");var i,n,o="startBroadcast(): ",s=this;if(!s.isSignedIn())return i=l.NotSignedInError(),this._logger.error(o+m(i)),n=l.composeEvent(i,"StartBroadcastError"),this.emitSimple(n.name,n.data,n.error),void this._sendMetrics(n);if(this._broadcaster)return i=l.WrongStateError("Already broadcasting"),this._logger.error(o+m(i)),n=l.composeEvent(i,"StartBroadcastError"),this.emitSimple(n.name,n.data,n.error),void this._sendMetrics(n);var a=this._mediaController.getLocalMedias()[0];if(!a)return i=l.WrongStateError("No Local Media"),this._logger.error(o+m(i)),n=l.composeEvent(i,"StartBroadcastError"),this.emitSimple(n.name,n.data,n.error),void this._sendMetrics(n);this._broadcaster=new e(this._userId,this._session),this._config.extended=this._metricsEnabled,this._broadcaster.setConfig(this._config);var c=this._iceServersOverride||this._config.iceServers||this._iceServers;this._broadcaster.setIceServers(c),this._broadcaster.enableStats(this._statsEnabled,this._statsIntervalTime),this._listenToBroadcaster(this._broadcaster);var d=a.stream;this._broadcaster.addStream(d);var u=a.metadata;t.transcodingTargets.videowidth=u.width,t.transcodingTargets.videoheight=u.height,this._deviceController.getDevice("videoinput").then((function(e){var i=S(e)?s._videoDeviceConfig:e.videoDeviceConfig;return(!S(e)||S(e)&&!0===e)&&(t.transcodingTargets.targetvideowidth=i.width.ideal||0,t.transcodingTargets.targetvideoheight=i.height.ideal||0,t.transcodingTargets.source=i.source||"",t.transcodingTargets.ismobile=r.browserInfo.mobile?1:0),s._broadcaster.setTranscodingSettings(t.transcodingTargets),s._broadcaster.start()})).then((function(e){s._streamProtected=!0,s._logger.info(o+"StartBroadcastSuccess: stream name: "+d),e.name="StartBroadcastSuccess",s.emitSimple(e.name,e.data),s._sendMetrics(e)})).catch((function(e){s._isBroadcasting=!1,s._broadcaster.destroy(),s._broadcaster=void 0,s._streamProtected=s._chatRoom&&!!s._chatRoom.getUsersCount()||!1,"NanoError"!==e.type&&(e=l.GeneralError("Failed to start broadcast")),s._logger.error(o+m(e)),n=l.composeEvent(e,"StartBroadcastError"),s.emitSimple(n.name,n.data,n.error),s._sendMetrics(n)}))},P.stopBroadcast=function(){this._logger.verbose("stopBroadcast()");var e="stopBroadcast(): ",t=this,r=t._broadcaster;if(this._broadcaster=void 0,r)r.stop().catch((function(r){"NanoError"!==r.type&&(r=l.GeneralError("Failed to stop broadcast")),t._logger.error(e+m(r));var i=l.composeEvent(r,"StopBroadcastError");t.emitSimple(i.name,i.data,i.error),t._sendMetrics(i)})).then((function(r){t._isBroadcasting=!1,t._streamProtected=t._chatRoom&&!!t._chatRoom.getUsersCount()||!1,t._logger.info(e+"StopBroadcastSuccess"),r.name="StopBroadcastSuccess",t.emitSimple(r.name,r.data),t._sendMetrics(r)}));else{var i=l.StopBroadcastError("No broadcast is running");this._logger.error(e+m(i));var n=l.composeEvent(i);this.emitSimple(n.name,n.data,n.error),this._sendMetrics(n)}},P.sendMetaData=function(e,t){this._logger.verbose("sendMetaData("+e+", "+m(t)+")");var r="sendMetaData(): ",i=this;if(!_(e)){var n=l.TypeNotValidError("handlerName","String");this._logger.error(r+m(n));var o=l.composeEvent(n,"Error");return this.emitSimple(o.name,o.data,o.error),void this._sendMetrics(o)}if(!v(t)){n=l.TypeNotValidError("jsonValues","Object");this._logger.error(r+m(n));o=l.composeEvent(n,"Error");return this.emitSimple(o.name,o.data,o.error),void this._sendMetrics(o)}if(this._isBroadcasting){this._channels.getBroadcaster().sendMetaData(e,t).catch((function(e){"NanoError"!==e.type&&(e=l.GeneralError("Failed to send metadata")),i._logger.error(r+m(e));var t=l.composeEvent(e,"Error");i.emitSimple(t.name,t.data,t.error),i._sendMetrics(t)}))}else{n=l.WrongStateError("Not broadcasting");this._logger.error(r+m(n));o=l.composeEvent(n,"Error");this.emitSimple(o.name,o.data,o.error),this._sendMetrics(o)}},P.enterRoom=function(e){this._logger.verbose("enterRoom("+m(e)+")");var t,r,i=this;if(!i.isSignedIn())return t=l.NotSignedInError(),r=l.composeEvent(t,"EnterRoomError"),void this.emitSimple(r.name,r.data,r.error);if(i._chatRoom)return t=l.WrongStateError("Already in room"),r=l.composeEvent(t,"EnterRoomError"),void this.emitSimple(r.name,r.data,r.error);if(!v(e))return t=l.TypeNotValidError("roomOptions","Object"),r=l.composeEvent(t,"EnterRoomError"),void i.emitSimple(r.name,r.data,r.error);if(!_(e.userName))return t=l.TypeNotValidError("roomOptions.userName","String"),r=l.composeEvent(t,"EnterRoomError"),void i.emitSimple(r.name,r.data,r.error);if(!_(e.room))return t=l.TypeNotValidError("roomOptions.room","String"),r=l.composeEvent(t,"EnterRoomError"),void i.emitSimple(r.name,r.data,r.error);e.userId=i._userId,i._chatRoom=new d(e,i._session,i._mediaController),i._chatRoom.setConfig(i._config);var n=i._iceServersOverride||i._iceServers;i._chatRoom.setIceServers(n),i._chatRoom.on("RoomUpdate",i._onRoomUpdate.bind(i)),i._chatRoom.on("RemoteStreamAdded",i._onRemoteStreamAdded.bind(this)),i._chatRoom.enter().then((function(){i._logger.info("enterRoom(): EnterRoomSuccess: user name: "+e.userName+", room name: "+e.room),i.emitSimple("EnterRoomSuccess",{})})).catch((function(e){"NanoError"!==e.type&&(e=l.GeneralError("Failed to enter room"));var t=l.composeEvent(e,"EnterRoomError");i.emitSimple(t.name,t.data,t.error),i._chatRoom.removeEvent("RoomUpdate"),i._chatRoom=void 0}))},P.leaveRoom=function(){this._logger.verbose("leaveRoom()");var e=this;if(e._chatRoom)e._chatRoom.removeEvent("RoomUpdate"),e._chatRoom.removeEvent("RemoteStreamAdded"),e._chatRoom.leave().then((function(){e._logger.info("leaveRoom(): LeaveRoomSuccess: user name:"+e._chatRoom._userName+", room name: "+e._chatRoom._roomName),e.emitSimple("LeaveRoomSuccess",{})})).catch((function(t){"NanoError"!==t.type&&(t=l.GeneralError("Failed to leave room"));var r=l.composeEvent(t,"LeaveRoomError");e.emitSimple(r.name,r.data,r.error)})).then((function(){e._chatRoom=void 0}));else{var t=l.ObjectNotExistError("_chatRoom","String"),r=l.composeEvent(t,"LeaveRoomError");e.emitSimple(r.name,r.data,r.error)}},P.invokeCall=function(e){this._logger.verbose("invokeCall("+e+")");var t=this;if(t._chatRoom)if(_(e))t._chatRoom.callUser(e).then((function(){t._logger.info("invokeCall(): Invoke call: remote user id: "+e),t._streamProtected=!0})).catch((function(e){t._streamProtected=!!t._chatRoom.getUsersCount()||t._isBroadcasting,"NanoError"!==e.type&&(e=l.GeneralError("Failed to invoke call"));var r=l.composeEvent(e,"InvokeCall");t.emitSimple(r.name,r.data,r.error)}));else{r=l.TypeNotValidError("remoteUserId","String"),i=l.composeEvent(r,"InvokeCall");t.emitSimple(i.name,i.data,i.error)}else{var r=l.ObjectNotExistError("_chatRoom","String"),i=l.composeEvent(r,"InvokeCall");t.emitSimple(i.name,i.data,i.error)}},P.hangUpCall=function(e){this._logger.verbose("hangUpCall("+e+")");var t=this;if(t._chatRoom)if(_(e))t._chatRoom.hangUpCall(e).then((function(){t._logger.info("hangUpCall(): Hang up call: remote user id: "+e),t._streamProtected=!!t._chatRoom.getUsersCount()||t._isBroadcasting})).catch((function(e){t._streamProtected=!!t._chatRoom.getUsersCount()||t._isBroadcasting,"NanoError"!==e.type&&(e=l.GeneralError("Failed to hang up call"));var r=l.composeEvent(e,"HangUpCall");t.emitSimple(r.name,r.data,r.error)}));else{r=l.TypeNotValidError("remoteUserId","String"),i=l.composeEvent(r,"HangUpCall");t.emitSimple(i.name,i.data,i.error)}else{var r=l.ObjectNotExistError("_chatRoom","String"),i=l.composeEvent(r,"HangUpCall");t.emitSimple(i.name,i.data,i.error)}},P.answerCall=function(e){this._logger.verbose("answerCall("+e+")");var t=this;if(t._chatRoom)if(_(e))t._chatRoom.answerCall(e).then((function(){t._logger.info("answerCall(): Answer call: remote user id: "+e),t._streamProtected=!0})).catch((function(e){t._streamProtected=!!t._chatRoom.getUsersCount()||t._isBroadcasting,"NanoError"!==e.type&&(e=l.GeneralError("Failed to answer call")),t._logger.error("answerCall(): "+m(e));var r=l.composeEvent(e,"AnswerCall");t.emitSimple(r.name,r.data,r.error)}));else{r=l.TypeNotValidError("remoteUserId","String"),i=l.composeEvent(r,"AnswerCall");t.emitSimple(i.name,i.data,i.error)}else{var r=l.ObjectNotExistError("_chatRoom","String"),i=l.composeEvent(r,"AnswerCall");t.emitSimple(i.name,i.data,i.error)}},P.declineCall=function(e){this._logger.verbose("declineCall("+e+")");var t=this;if(t._chatRoom)if(_(e))t._chatRoom.declineCall(e).then((function(){t._logger.info("declineCall(): Decline call: remote user id: "+e)})).catch((function(e){"NanoError"!==e.type&&(e=l.GeneralError("Failed to decline call")),t._logger.error("declineCall(): "+m(e));var r=l.composeEvent(e,"DeclineCall");t.emitSimple(r.name,r.data,r.error)}));else{r=l.TypeNotValidError("remoteUserId","String"),i=l.composeEvent(r,"DeclineCall");t.emitSimple(i.name,i.data,i.error)}else{var r=l.ObjectNotExistError("_chatRoom","String"),i=l.composeEvent(r,"DeclineCall");t.emitSimple(i.name,i.data,i.error)}},P.addScreenCaptureExtension=function(e){this._logger.verbose("addScreenCaptureExtension("+e+")");var t=r.browserInfo.browser,i=parseInt(r.browserInfo.browserVersion.split(".")[0],10);if("Chrome"===t&&i<72){e=_(e)?e:"nanoScreenCapture",this._screenCaptureExtension.addChromeExtension(e);var n=this._deviceController.addScreenCaptureDevice(e);n.length>0&&(n.updated=!0,this.emitSimple("ReceivedDeviceList",n))}else this._logger.warning("addScreenCaptureExtension(): Screen capture extension is only required for Chrome versions < 72")},P.isScreenCaptureAvailable=function(){return this._logger.verbose("isScreenCaptureAvailable()"),!!this._screenCaptureExtension&&this._screenCaptureExtension.isScreenCaptureAvailable()},P.getDevices=function(){this._logger.verbose("getDevices()"),this._deviceController.enumerateDevices().then(this._getDevicesSuccess.bind(this)).catch(this._getDevicesError.bind(this))},P.setVideoDevice=function(e){if(this._logger.verbose("setVideoDevice("+m(e)+")"),this._logger.warning('"setVideoDevice()" function is deprecated and will be removed in the WebRTC-Client v.6'),this._streamProtected){var t=l.WrongStateError("Stream is already in use"),r=l.composeEvent(t,"SetVideoDeviceError");this.emitSimple(r.name,r.data,r.error)}else e.kind="videoinput",this._deviceController.setDevice(e)},P.setAudioDevice=function(e){if(this._logger.verbose("setAudioDevice("+m(e)+")"),this._logger.warning('"setAudioDevice()" function is deprecated and will be removed in the WebRTC-Client v.6'),this._streamProtected){var t=l.WrongStateError("Stream is already in use"),r=l.composeEvent(t,"SetAudioDeviceError");this.emitSimple(r.name,r.data,r.error)}else e.kind="audioinput",this._deviceController.setDevice(e)},P.getSelectedVideoDevice=function(){if(this._logger.verbose("getSelectedVideoDevice()"),this._logger.warning('"getSelectedVideoDevice()" function is deprecated and will be removed in the WebRTC-Client v.6'),this._streamProtected){var e=l.WrongStateError("Stream is already in use"),t=l.composeEvent(e,"GetSelectedVideoDeviceError");this.emitSimple(t.name,t.data,t.error)}else this._deviceController.getDevice("videoinput").then((function(e){return e})).catch((function(e){"NanoError"!==e.type&&(e=l.GeneralError("Failed to get device"));var t=l.composeEvent(e,"GetSelectedVideoDeviceError");self.emitSimple(t.name,t.data,t.error)}))},P.getSelectedAudioDevice=function(){if(this._logger.verbose("getSelectedAudioDevice()"),this._logger.warning('"getSelectedAudioDevice()" function is deprecated and will be removed in the WebRTC-Client v.6'),this._streamProtected){var e=l.WrongStateError("Stream is already in use"),t=l.composeEvent(e,"GetSelectedAudioDeviceError");this.emitSimple(t.name,t.data,t.error)}else this._deviceController.getDevice("audioinput").then((function(e){return e})).catch((function(e){"NanoError"!==e.type&&(e=l.GeneralError("Failed to get device"));var t=l.composeEvent(e,"GetSelectedAudioDeviceError");self.emitSimple(t.name,t.data,t.error)}))},P.getSelectedDevice=function(e){this._logger.verbose("getSelectedDevice("+m(e)+")");var t="getSelectedDevice(): ",r=this;if(this._streamProtected){var i=l.WrongStateError("Stream is already in use");this._logger.error(t+m(i));var n=l.composeEvent(i,"GetSelectedDeviceError");return this.emitSimple(n.name,n.data,n.error),void this._sendMetrics(n)}this._deviceController.getDevice(e.kind).then((function(i){return r._logger.info(t+"Selected "+("videoinput"===e.kind?"video":"audio")+" device: "+m(i)),i})).catch((function(e){"NanoError"!==e.type&&(e=l.GeneralError("Failed to get device")),r._logger.error(t+m(e));var i=l.composeEvent(e,"GetSelectedDeviceError");r.emitSimple(i.name,i.data,i.error),r._sendMetrics(i)}))},P.startPreview=function(e){this._logger.verbose("startPreview("+m(e)+")");var t="startPreview(): ",r=this;if(this._streamProtected){var i=l.WrongStateError("Stream is already in use");this._logger.error(t+m(i));var n=l.composeEvent(i,"StartPreviewError");return this.emitSimple(n.name,n.data,n.error),void this._sendMetrics(n)}if(!v(e)){i=l.TypeNotValidError("config","Object");this._logger.error(t+m(i));n=l.composeEvent(i,"StartPreviewError");return this.emitSimple(n.name,n.data,n.error),void this._sendMetrics(n)}if(!v(e.videoDeviceConfig)){i=l.TypeNotValidError("config.videoDeviceConfig","Object");this._logger.error(t+m(i));n=l.composeEvent(i,"StartPreviewError");return this.emitSimple(n.name,n.data,n.error),void this._sendMetrics(n)}if(!v(e.audioDeviceConfig)){i=l.TypeNotValidError("config.audioDeviceConfig","Object");this._logger.error(t+m(i));n=l.composeEvent(i,"StartPreviewError");return this.emitSimple(n.name,n.data,n.error),void this._sendMetrics(n)}var o=e.videoDeviceConfig;o.kind="videoinput";var s=e.audioDeviceConfig;s.kind="audioinput";var a=e.elementId,c=!!e.useWebView;this._videoDeviceConfig.height={ideal:o.height},this._videoDeviceConfig.width={ideal:o.width},this._videoDeviceConfig.source=o.source,this._deviceController.setDevice(o).then((function(e){return r._logger.verbose(t+"Selected video device: "+m(e)),r._deviceController.setDevice(s)})).then((function(e){return r._logger.verbose(t+"Selected audio device: "+m(e)),r._getStream(c,!1)})).then((function(e){if(e&&e.stream&&e.stream.data&&e.stream.data.stream){var i=e.stream.data.stream;if(a)h(a).srcObject=i;r._logger.info(t+"StartPreviewSuccess: stream: "+m(e.stream)),e.name="StartPreviewSuccess",e.data=e.stream.data,delete e.stream,r.emitSimple(e.name,e.data),r._sendMetrics(e),e.devices&&(e.name="ReceivedDeviceList",r.emitSimple(e.name,e.devices.data))}})).catch((function(e){"NanoError"!==e.type&&(e=l.GeneralError("Failed to start preview")),r._logger.error(t+m(e));var i=l.composeEvent(e,"StartPreviewError");r.emitSimple(i.name,i.data,i.error),r._sendMetrics(i)}))},P.stopPreview=function(){this._logger.verbose("stopPreview()");var e=this;if(this._streamProtected){var t=l.WrongStateError("Stream is already in use"),r=l.composeEvent(t,"StopPreviewError");return this.emitSimple(r.name,r.data,r.error),void this._sendMetrics(r)}this._mediaController.removeLocalMedias().then((function(t){null===t.data.stream&&(t.name="StopPreviewSuccess",e.emitSimple(t.name,t.data),e._sendMetrics(t))})).catch((function(t){"NanoError"!==t.type&&(t=l.GeneralError("Failed to stop preview")),e._logger.error("stopPreview(): "+m(t));var r=l.composeEvent(t,"StopPreviewError");e.emitSimple(r.name,r.data,r.error),e._sendMetrics(r)}))},P.muteVideo=function(e){this._logger.verbose("muteVideo("+e+")"),this._logger.warning('"muteVideo()" function is deprecated and will be removed in the WebRTC-Client v.6'),this._mediaController.muteVideoTracks(e)},P.muteAudio=function(e){this._logger.verbose("muteAudio("+e+")"),this._logger.warning('"muteAudio()" function is deprecated and will be removed in the WebRTC-Client v.6'),this._mediaController.muteAudioTracks(e)},P.muteDevice=function(e){this._logger.verbose("muteDevice("+m(e)+")");var t=this;this._mediaController.muteTracks(e).catch((function(e){"NanoError"!==e.type&&(e=l.GeneralError("Failed to mute")),t._logger.error("muteDevice(): "+m(e));var r=l.composeEvent(e,"MuteDeviceError");t.emitSimple(r.name,r.data,r.error),t._sendMetrics(r)}))},P.injectExternalMediaStream=function(e){return this._logger.verbose("injectExternalMediaStream("+m(e)+")"),e&&e.stream?r.isArray(e.tracks)&&e.tracks.length?this._streamProtected?Promise.reject(new Error("Cant inject, stream is already beeing used")):-1!==e.tracks.indexOf("audio")?this._mixExternalAudio(e.stream):Promise.reject(new Error('Mixing in tracks other than "audio" is not supported at the moment')):Promise.reject(new Error("Parameter config.tracks must contain an array with track types to be replaced")):Promise.reject(new Error("You need to provide a stream config object"))},P._listenToBroadcaster=function(e){this._logger.verbose("_listenToBroadcaster()"),e.on("BroadcastStatus",this._onBroadcastStatus.bind(this)),e.on("ReceivedWebRTCStats",this._onReceivedWebRTCStats.bind(this))},P._getStream=function(e,t,r){this._logger.verbose("_getStream("+e+", "+t+", "+m(r)+")");var i=this,n={};return Promise.resolve().then((function(){return t?i._deviceController.enumerateDevices():Promise.resolve()})).then((function(e){if(e&&e.data){if(!e.data.updated)return Promise.reject(r);i._getDevicesSuccess(e)}return i._deviceController.getDevice("videoinput")})).then((function(e){return n.videoinput=e,i._deviceController.getDevice("audioinput")})).then((function(t){return n.audioinput=t,i._mediaController.getMediaForDevices(n,e)})).catch((function(r){return"OverconstrainedError"===r.name&&r.userinfo&&"deviceId"===r.userinfo.constraint&&r.userinfo.retry&&!t?i._getStream(e,!0,r):Promise.reject(r)}))},P._mixExternalAudio=function(e){if(this._logger.verbose("_mixExternalAudio("+m(e)+")"),!e)return Promise.reject(new Error("No external stream passed"));var t,r,i=this;return Promise.resolve(this._mediaController.getLocalMedias()[0]).then((function(e){if(e&&e[0])return e[0];throw new Error("No local stream")})).then((function(e){if((r=(t=e).getAudioTracks()).length>0)return i._audioMixer.connect(t,0);throw new Error("Local stream has no audio")})).then((function(){return i._audioMixer.connect(e,1)})).then((function(){return i._audioMixer.getOutputStream()})).then((function(e){var i=r[0],n=e.getAudioTracks()[0];t.removeTrack(i),t.addTrack(n)})).catch((function(e){throw i._logger.error("_mixExternalAudio(): Could not mix audioTracks: "+e),e}))},P._sendMetrics=function(e){this._metricsController&&this._metricsController.onEvent(e)},P._destroy=function(){this._logger.verbose("destroy()");var e=this;e._broadcaster&&e._broadcaster.stop().catch((function(t){e._logger.verbose(t)})).then((function(){e._broadcaster=void 0})),e._chatRoom&&e._chatRoom.destroy().catch((function(t){e._logger.verbose("_destroy(): "+m(t))})).then((function(){e._chatRoom=void 0}))},P._onBroadcastStatus=function(e){this._logger.verbose("_onBroadcastStatus("+m(e)+")");var r={name:"BroadcastStatus"};switch(e.data.state){case t.BROADCAST_STATE.INITIALIZED:case t.BROADCAST_STATE.STARTED:case t.BROADCAST_STATE.SIGNALING:case t.BROADCAST_STATE.CONNECTED:case t.BROADCAST_STATE.RECONNECTING:case t.BROADCAST_STATE.DISCONNECTED:case t.BROADCAST_STATE.STOPPED:r.data=e.data;break;case t.BROADCAST_STATE.BROADCASTING:r.data=e.data,this._isBroadcasting=!0;break;case t.BROADCAST_STATE.FAILED:this._isBroadcasting?(r.name="BroadcastError",r.error=l.BroadcastError("Unknown reason")):(r.name="StartBroadcastError",r.error=l.StartBroadcastError("Unknown reason")),this._isBroadcasting=!1,this._broadcaster.destroy(),this._broadcaster=void 0}this.emitSimple(r.name,r.data,r.error),this._sendMetrics(r)},P._onRemoteStreamAdded=function(e){this._logger.verbose("_onRemoteStreamAdded("+m(e)+")"),e.data.stream&&e.data.stream.id;for(var t=this._mediaController.getRemoteMedias(),r=0;r<t.length;r++){var i=t[r];if(i.stream.id===e.data.stream)return void this.emitSimple("CallActive",{data:i})}e.name="RemoteStreamError",this.emitSimple(e.name,e)},P._onReceivedWebRTCStats=function(e){if(this._logger.verbose("_onReceivedWebRTCStats("+m(e)+")"),this._metricsController){var t=JSON.parse(JSON.stringify(e));this._metricsController.onEvent(t)}e.data&&e.data.results&&e.data.results.extended&&!y(e.data.results.extended)&&delete e.data.results.extended,this.emitSimple(e.name,e.data,e.error)},P._onSessionMessage=function(e){this._logger.verbose("_onSessionMessage("+m(e)+")");switch(e.type){case"close":if(this._destroy(),"disconnect"===e.reason){var t=l.ServerError("disconnect");this._logger.error("_onSessionMessage(): "+m(t));var r=l.composeEvent(t,"ServerError");this.emitSimple(r.name,r.data,r.error),this._sendMetrics(r)}}},P._onRoomUpdate=function(e){switch(this._logger.verbose("_onRoomUpdate("+m(e)+")"),e.type){case"room_update":this._streamProtected=!!this._chatRoom.getUsersCount()||this._isBroadcasting,this.emitSimple("PeerListUpdated",{data:e.data});break;case"call_incoming":this.emitSimple("CallIncoming",{data:e.data});break;case"call_declined":this._streamProtected=!!this._chatRoom.getUsersCount()||this._isBroadcasting,this.emitSimple("CallDeclined",{data:e.data})}},P._onStreamTrackEnded=function(e){this._logger.verbose("_onStreamTrackEnded("+m(e)+")"),this.emitSimple("StreamTrackEnded",{data:e})},P._getDevicesSuccess=function(e){this._logger.info("_getDevicesSuccess("+m(e)+")"),this.emitSimple("ReceivedDeviceList",e.data)},P._getDevicesError=function(e){var t=e.data.error.message||e.data.error.toString();this._logger.error(t)},T}.apply(t,i))||(e.exports=n)},function(e,t,r){var i,n;i=[r(5),r(9),r(4),r(3),r(0),r(12),r(2),r(1)],void 0===(n=function(e,t,r,i,n,o,s,a){"use strict";var c=n.isString,d=n.isIntString,l=n.stringifyJSON,u=n.isObject,p=n.isArray,h=n.isFunction,m=r.BROADCAST_STATE;function g(e,t){if(i.call(this),this._logger=a.create("Broadcaster","console"),this._logger.verbose("Broadcaster("+e+")"),d(e)||this._logger.error("Param userId must be an integer"),!t||!t||!h(t.signIn))throw s.TypeNotValidError("session","Session");this._userId=e,this._remoteUserId=e,this._peerId=void 0,this._remotePeerId=void 0,this._remoteUserName="webrtc2H264",this._pcClient=void 0,this._streams=[],this._transcodingSettings={output:null,streamname:null,videobitrate:null,videowidth:null,videoheight:null,targetvideowidth:null,targetvideoheight:null,source:null,ismobile:null,audiobitrate:null,framerate:null,dropframes:null,h264passthrough:1,icecast_audio:null,icecast_event_id:null,rtmpconnectinfo:null},this._startTime=null,this._iceServers=[],this._config={},this._state=m.IDLE,this._messageQueue=[],this._remoteStream=null,this._statsEnabled=!1,this._statsIntervalTime=1e3,this._statsInterval=0,this._rtcStats=null,this._session=t}var v=g.prototype=Object.create(i.prototype);return v.setIceServers=function(e){this._iceServers=e},v.setConfig=function(e){this._config=e},v.getState=function(){return this._state},v.getPeerId=function(){return this._peerId},v.setTranscodingSettings=function(e){var t;for(t in e)Object.prototype.hasOwnProperty.call(this._transcodingSettings,t)&&(this._transcodingSettings[t]=e[t])},v.start=function(){this._logger.verbose("start()");var e,t=this;return this._session.startBroadcast(this._getBroadcastParameters()).then((function(r){return t._peerId=r.peer_id,t._setState(m.INITIALIZED),e="receiver_peer_"+t._peerId,t._session.on(e,t._onServerMessage.bind(t)),Promise.resolve({data:{output:t._transcodingSettings.output,streamname:t._transcodingSettings.streamname}})})).catch((function(e){return t._setState(m.FAILED),Promise.reject(e)}))},v.stop=function(){this._logger.verbose("stop()");var e=this;return e._stopCollectRtcStats(),e._peerId&&e._remotePeerId?e._session.isSignedIn()?this._session.stopBroadcast({sender_peer:this._peerId,receiver_peer:this._remotePeerId}).then((function(){var t="receiver_peer_"+e._peerId;return e._session.removeEvent(t),t="receiver_peer_"+e._remotePeerId,e._session.removeEvent(t),e.destroy(),e._logger.verbose("stop(): Broadcast stopped"),Promise.resolve({data:{output:e._transcodingSettings.output,streamname:e._transcodingSettings.streamname}})})).catch((function(t){return t&&"NanoError"===t.type&&e._logger.error(s.StopBroadcastError("Stopping broadcast failed: "+t)),e.destroy(),e._logger.verbose("stop(): Broadcast stopped"),Promise.reject(t)})):(e.destroy(),Promise.resolve()):Promise.reject(s.StopBroadcastError("Not connected to any peer"))},v.addStream=function(e){this._logger.verbose("addStream()");e?2!==this._streams.length?p(e)?this._streams=e:this._streams.push(e):this._logger.warning("addStream(): [_peerId: r "+this._peerId+"] Stream count is already = 2, we only support 2 streams/Broadcaster"):this._logger.error("addStream(): [_peerId: "+this._peerId+'] Parameter "stream" must not be undefined')},v.sendMetaData=function(e,t){this._logger.verbose("sendMetaData()");if(this.getState()===m.BROADCASTING){this._logger.verbose("sendMetaData(): [_peerId: "+this._peerId+"] Sending metaData: "+e+" - "+l(t));var r={eventType:"metaData",eventName:e,strLabel:this._streams[0].id,payload:t},i={sender_peer:this._peerId,receiver_peer:this._remotePeerId,data:r};return this._session.sendMetaData(i)}var n="[_peerId: "+this._peerId+"] Tried to send metaData but Broadcaster is not in active state";return this._logger.error(n),Promise.reject(n)},v.enableStats=function(e,t){this._logger.verbose("enableStats()"),this._statsEnabled=void 0===e||e,this._statsIntervalTime=t||1e3,this._rtcStats=null,this._statsEnabled&&(this._rtcStats=new o,this._rtcStats.on("ReceivedWebRTCStats",this._reemit.bind(this)))},v.destroy=function(){this._logger.verbose("destroy()"),this._unbind(),this._closePCClient(),this._setState(m.STOPPED),a.delete(this._logger)},v._getBroadcastParameters=function(){this._logger.verbose("_getBroadcastParameters()");var e,t={};for(e in t.peer=this._peerId,this._transcodingSettings){var r=this._transcodingSettings[e];null!==r&&((u(r)||c(r))&&(r=l(r)),t[e.toString()]=r.toString())}return t.stream_label=this._streams[0]&&this._streams[0].id?this._streams[0].id:"",t.stream_label2=this._streams[1]&&this._streams[1].id?this._streams[1].id:"",t.videocodec=this._config.codecs.videoCodec?this._config.codecs.videoCodec:"H264",t.audio=this._streams[0].getAudioTracks().length>0?"1":"0",t.video=this._streams[0].getVideoTracks().length>0?"1":"0",t},v._onServerMessage=function(e){this._logger.verbose("_onServerMessage()");var t="_onServerMessage(): ",r=this;switch(e.type){case"transcoder_message":"started"===e.state?r._pcClient?r._logger.error(t+"We should not have a pcClient at this moment"):(r._createPCClient(),r._pcClient.startAsCallee(r._messageQueue),r._setState(m.STARTED)):"disconnected"===e.state&&(r._setState(m.DISCONNECTED),r._logger.verbose(t+"Disconnected"));break;case"sdp_message":if(!e.sender_peer)return void r._logger.error(t+"Received sdp_message, but message has no sender_peer");r._remotePeerId=e.sender_peer,r._pcClient&&r._pcClient.isStarted()?r._pcClient.setRemoteDescription(e.data.sdp).catch((function(e){return r._logger.error(t+"setRemoteDescription failed: "+e),Promise.reject(e)})).then((function(){return r._logger.verbose(t+"setRemoteDescription succeded"),r._pcClient.doAnswer()})).catch((function(e){return r._logger.error(t+"doAnswer failed:"+e),Promise.reject(e)})).then((function(e){r._logger.verbose(t+"doAnswer succeded: "+l(e));var i={};return i.sender_peer=r._peerId,i.receiver_peer=r._remotePeerId,i.data=e,r.emitSimple("SDPAnswer",i),r._session.sendSignalingMessage(i).catch((function(e){r._logger.error(t+"sendSignalingMessage failed: "+e)}))})).catch((function(e){r._logger.error(t+"sendSignalingMessage failed: "+e)})):r._messageQueue.push(e.data.sdp);break;case"ice_candidate":r._pcClient&&r._pcClient.isStarted()?r._pcClient.addIceCandidate(e.data.candidate):r._messageQueue.push(e.data.candidate);break;case"rtmp_status":r._logger.verbose(t+"Received rtmp status: "+l(e.data)),e.data&&"status"===e.data.status&&("connected"===e.data.message?r._setState(m.BROADCASTING):"reconnecting"===e.data.message&&r._setState(m.RECONNECTING)),e.data&&"error"===e.data.status&&4711===e.data.number&&r._setState(m.FAILED);var i=r._addEventPayload({data:e.data});r.emit("BroadcastStatus",i);break;case"server_error":r._setState(m.FAILED),r._logger.error(t+"Server error: "+e.error);break;default:r._logger.verbose(t+"Unknown message:"+e)}},v._addEventPayload=function(e){return(e=e||{}).data=e.data||{},e.data.streamname=this._transcodingSettings.streamname,e.data.state=this._state,e.data.message=n.getKeyByValue(m,this._state).toLowerCase(),e.data.text=e.data.message,e},v._reemit=function(e){e=this._addEventPayload(e),this.emit(e.name,e)},v._collectRtcStats=function(){this._logger.verbose("_collectRtcStats()");var e=this,t=e._config.extended;clearInterval(e._statsInterval),this._statsInterval=setInterval((function(){if(e._pcClient){var r=void 0,i=e._getBroadcastParameters();if("1"===i.video&&"0"===i.audio)r="video";else if("0"===i.video&&"1"===i.audio)r="audio";else if("0"===i.video&&"0"===i.audio)return void e._logger.error('_collectRtcStatsAttempts to show stats for "no video" and "no audio" stream');e._pcClient.getStats(r).then((function(i){e._rtcStats||(e._rtcStats=new o),e._rtcStats.putReport(i,r,t)})).catch((function(t){e._logger.error("_collectRtcStats[_peerId: "+e._peerId+"] "+t)}))}else clearInterval(e._statsInterval)}),this._statsIntervalTime)},v._stopCollectRtcStats=function(){this._logger.verbose("_stopCollectRtcStats()");this._statsInterval&&(this._logger.verbose("_stopCollectRtcStats(): Stopping rtc stats collection"),this._rtcStats.removeEvent("ReceivedWebRTCStats"),clearInterval(this._statsInterval),this._rtcStats=null)},v._getPeerConnectionConfig=function(){this._logger.verbose("_getPeerConnectionConfig()");var e={iceServers:this._iceServers,iceTransports:"all"},t={optional:[],mandatory:[]};return t.optional.push({googCpuOveruseDetection:!1}),t.optional.push({RtpDataChannels:!1}),{mediaConstraints:{audio:!0,video:!0},sdpPatches:this._config.sdpPatches,peerConnectionConfig:e,peerConnectionConstraints:t,send:0!==this._streams.length,receive:!1,audioSendBitrate:this._config.bitrates.audioSendBitrate||0,videoSendCodec:this._config.codecs.videoCodec||"H264",videoRecvCodec:this._config.codecs.videoCodec||"H264",videoSendBitrate:this._config.bitrates.videoSendBitrate||0,videoSendInitialBitrate:this._config.bitrates.videoSendInitialBitrate||0}},v._createPCClient=function(){this._logger.verbose("_createPCClient()");var e="_createPCClient(): ";if(this._pcClient)this._logger.verbose(e+"[_peerId:  "+this._peerId+"] PeerConnection still alive, do not create!");else try{if(this._pcClient=new t(this._getPeerConnectionConfig(),this._startTime),"object"==typeof callstats&&callstats&&callstats.fabricUsage){try{var r=callstats.fabricUsage.multiplex,i=this._remoteUserName,n=this._remoteUserName+"_"+this._peerId+"_"+this._userId+"__"+this._remotePeerId+"_"+this._remoteUserId;callstats.addNewFabric(this._pcClient._pc,i,r,n,(function(t,r){this._logger.verbose(e+"Callstats Monitoring status: "+t+" msg: "+r)}))}catch(t){this._logger.warning(e+"Error in callstats")}}this._bind();for(var o=0;o<this._streams.length;o++)this._pcClient.addStream(this._streams[o]);this._logger.verbose(e+"Created PeerConnectionClient")}catch(t){this._logger.error(e+"[_peerId: "+this._peerId+"] Create PeerConnection exception: "+t.message),this.emitSimple("CreatePeerConnectionClientError")}},v._bind=function(){this._logger.verbose("_bind()"),this._pcClient.on("SignalingMessage",this._onSignalingMessage.bind(this)),this._pcClient.on("RemoteStreamRemoved",this._onRemoteStreamRemoved.bind(this)),this._pcClient.on("RemoteStreamAdded",this._onRemoteStreamAdded.bind(this)),this._pcClient.on("IceConnectionStateChange",this._onIceConnectionStateChange.bind(this)),this._pcClient.on("EndOfLocalCandidates",this._onEndOfLocalCandidates.bind(this)),this._pcClient.on("NegotiationNeeded",this._onNegotiationNeeded.bind(this))},v._unbind=function(){this._logger.verbose("_unbind()"),this._pcClient&&(this._pcClient.off("SignalingMessage",this._onSignalingMessage.bind(this)),this._pcClient.off("RemoteStreamRemoved",this._onRemoteStreamRemoved.bind(this)),this._pcClient.off("RemoteStreamAdded",this._onRemoteStreamAdded.bind(this)),this._pcClient.off("IceConnectionStateChange",this._onIceConnectionStateChange.bind(this)),this._pcClient.off("EndOfLocalCandidates",this._onEndOfLocalCandidates.bind(this)),this._pcClient.off("NegotiationNeeded",this._onNegotiationNeeded.bind(this)))},v._setState=function(e){if(e!==this._state){var t=this._state;this._state=e,this._logger.verbose("_setState(): State: "+n.getKeyByValue(m,t)+" -> "+n.getKeyByValue(m,this._state))}},v._onIceConnectionStateChange=function(e){this._logger.verbose("_onIceConnectionStateChange("+l(e)+")");switch(this._logger.verbose("_onIceConnectionStateChange(): Ice connection state: "+e.data.state),e.data.state){case"new":case"checking":this._setState(m.SIGNALING);break;case"connected":case"completed":this._setState(m.CONNECTED),this._statsEnabled&&this._pcClient&&this._collectRtcStats(),this._config&&this._config.bitrates&&this._pcClient.updateEncodingSettings(this._config.bitrates.audioSendBitrate||0,this._config.bitrates.videoSendBitrate||0);break;case"failed":this._setState(m.FAILED),this._statsEnabled&&this._pcClient&&this._stopCollectRtcStats();break;case"disconnected":this._setState(m.DISCONNECTED);break;case"closed":this._setState(m.STOPPED)}e=this._addEventPayload(e),this.emit("BroadcastStatus",e)},v._onNegotiationNeeded=function(e){this._logger.verbose("NegotiationNeeded event has been fired")},v._onEndOfLocalCandidates=function(e){this._logger.verbose("_onEndOfLocalCandidates()")},v._onRemoteStreamAdded=function(e){this._logger.verbose("_onRemoteStreamAdded()"),this._remoteStream=e.data.stream},v._onRemoteStreamRemoved=function(e){this._logger.verbose("_onRemoteStreamRemoved()"),this._remoteStream=null},v._closePCClient=function(){this._logger.verbose("_closePCClient()");if(this._pcClient){var e,t,r=this._streams;for(e=0,t=r.length;e<t;++e)try{this._pcClient.removeStream(r[e])}catch(e){this._logger.error("_closePCClient(): [_peerId: "+this._peerId+"] Could not remove stream from peerconnectionclient")}this._pcClient.close(),this._pcClient=null}},v._sendMessageToPeer=function(e){this._logger.verbose("_sendMessageToPeer()");var t="_sendMessageToPeer(): ",r=this,i={},n=void 0;return this._remotePeerId&&c(this._remotePeerId)||(n=this._remotePeerId?s.TypeNotValidError("_remotePeerId","String"):s.ObjectNotExistError("_remotePeerId","String")),this._peerId&&c(this._peerId)||(n=this._peerId?s.TypeNotValidError("_peerId","String"):s.ObjectNotExistError("_peerId","String")),u(e)||(n=s.TypeNotValidError("message","Object")),n?(this._logger.error(t+l(n)),Promise.reject(n)):(i.sender_peer=this._peerId,i.receiver_peer=this._remotePeerId,i.data=e,i.data&&""===i.data.candidate?Promise.resolve():this._session.sendSignalingMessage(i).catch((function(e){return r._logger.error(t+l(e)),Promise.reject(e)})))},v._onSignalingMessage=function(e){this._logger.verbose("_onSignalingMessage - "+l(e.data));var t="_onSignalingMessage(): ",r=this;this._remotePeerId?this._sendMessageToPeer(e.data).then((function(){})).catch((function(e){r._logger.error(t+l(e))})):this._logger.error(t+"Trying to send message, but no remote peer set! This should not happen!")},g}.apply(t,i))||(e.exports=n)},function(e,t,r){var i,n;i=[r(3),r(0),r(2),r(1)],void 0===(n=function(e,t,r,i){"use strict";var n=t.isString,o=t.stringifyJSON,s=t.isObject,a=t.isInt,c=t.isFunction,d=0,l={IDLE:1,CONNECTED:2,CLOSED:3};function u(){this._websocket=void 0,this._url=void 0,this._callback=void 0,this._state=l.IDLE,this._resolvers={},this._logger=i.create("WebsocketClient","console")}var p=u.prototype;return p.connect=function(e,t){if(this._logger.verbose("connect()"),!n(e))return Promise.reject(r.TypeNotValidError("url","String"));if(!c(t))return Promise.reject(r.TypeNotValidError("callback","Function"));if(this._state!==l.IDLE&&this._state!==l.CLOSED)return Promise.reject(r.WrongStateError());this._url=e,this._callback=t;var i=this;try{this._websocket=new WebSocket(this._url)}catch(e){return Promise.reject(r.CreateWebSocketError("Creating websocket failed",this._url))}return this._websocket.onclose=function(e){i._onClose(e)},this._websocket.onmessage=function(e){i._onMessage(e)},this._websocket.onerror=function(e){i._onError(e)},this._websocket.onopen=function(e){i._onOpen(e)},this._createResolver("connect")},p.close=function(){var e;return this._logger.verbose("close()"),this._websocket?(e=this._createResolver("close"),this._websocket.close(),this._setState(l.CLOSED),this._websocket=void 0):e=Promise.reject(r.WebSocketError("No websocket",this._url)),e},p.sendMessage=function(e,t){if(this._logger.verbose("sendMessage("+e+", "+o(t)+")"),!n(e))return Promise.reject(r.TypeNotValidError("type","String"));if(!s(t))return Promise.reject(r.TypeNotValidError("message","Object"));if(!this._websocket||this._websocket.readyState>1)return Promise.reject(r.WebSocketError("Sending message failed",this._url));var i=d++,a=this._createResolver(i);return this._websocket.send(o({type:e,message:t,message_id:i})),a},p._setState=function(e){this._logger.verbose("_setState("+e+")");if(e!==this._state){var r=this._state;this._state=e;var i="_setState(): State: "+t.getKeyByValue(l,r)+" -> "+t.getKeyByValue(l,this._state);this._logger.verbose(i)}},p._onOpen=function(e){this._logger.verbose("_onOpen("+o(e)+")"),this._setState(l.CONNECTED),this._resolve("connect",{event:e})},p._onClose=function(e){this._logger.verbose("_onClose("+o(e)+")"),this._setState(l.CLOSED),this._resolve("close",{type:e.type,code:e.code})},p._onMessage=function(e){this._logger.verbose("_onMessage("+o(e.data)+")");var t,r;if(e&&e.data){try{t=JSON.parse(e.data)}catch(e){return void this._logger.error("_onMessage(): "+o(e))}r=t.message_id,this._resolve(r,t)}else this._logger.error('_onMessage(): event has no "data" property')},p._onError=function(e){this._logger.error("_onError("+o(e)+")"),this._resolve("connect",{event:e})},p._createResolver=function(e){if(this._logger.verbose("_createResolver("+e+")"),!a(e)&&!n(e))return Promise.reject("resolver error"+e);var t,r,i=new Promise((function(e,i){t=e,r=i}));return this._resolvers[e]={resolve:t,reject:r},i},p._resolve=function(e,t){this._logger.verbose("_resolve("+e+", "+o(t)+")");var i="_resolve(): ",n=this._resolvers[e];if(n){if(this._logger.verbose(i+"Message id: "+e),delete this._resolvers[e],t&&t.event&&"error"===t.event.type&&"connect"===e)return n.reject(r.WebSocketError("Could not connect to server, please check server url",this._url));t.error?(this._logger.verbose(i+"Rejecting id: "+e),n.reject(t.error)):(this._logger.verbose(i+"Resolving id: "+e),n.resolve(t))}else this._logger.verbose(i+"Passive message"),this._callback(t)},u}.apply(t,i))||(e.exports=n)},function(e,t,r){var i,n;i=[r(0),r(8)],void 0===(n=function(e,t){"use strict";var r=e.stringifyJSON,i=e.isString;return function(e,n,o,s,a,c){this._globalPrefix=e,this._level=n,this._url=o,this._credentials={accountId:s,accountKey:a},this._id=c,this._logger=new t(e,"GrayLogger",n),this._logger.verbose("GrayLogger("+e+", "+n+", "+o+")");var d=0,l={};this.send=function(e,t){this._logger.verbose("send("+e+", "+r(t)+")");var n="send(): ",o=this;if(i(this._credentials.accountId)&&(""!==this._credentials.accountId||i(this._credentials.accountKey))&&""!==this._credentials.accountKey)try{d+=1;var s=new XMLHttpRequest;if(l[d]=s,s.open("POST",o._url+o._credentials.accountKey,!0),s.onreadystatechange=function(e,t){if(this&&4===this.readyState){var r=this.status>=400?"fail":this.status>=200?"success":"unknown";o._done.call(o,e,t,r)}}.bind(s,d,e),void 0!==t){if("string"==typeof t)try{t=JSON.parse(t)}catch(e){this._logger.error(n+r(e)),t=null}if("object"==typeof t)try{t=JSON.stringify(t),setTimeout(o._done.bind(o,d,e,"suspend"),5e3),s.send(t)}catch(e){this._logger.error(n+r(e)),o._done.call(o,d,"catch "+e.message)}}else this._logger.verbose(n+'"data" is undefined and will not be sent')}catch(e){this._logger.error(n+r(e)),o._done.call(o,d,"catch "+e.message)}else o._logger.verbose(n+"No credentials is set; graylogger is disabled. Returning")},this.destroy=function(){for(var e in this._logger.verbose("destroy()"),l)if(l.hasOwnProperty(e)){var t=l[e];"function"==typeof t.onreadystatechange&&(t.onreadystatechange=null),delete l[e]}},this._done=function(e,t,r){if(this._logger.verbose("_done("+e+", "+t+", "+r+")"),void 0!==l[e]){var i=l[e];"function"==typeof i.onreadystatechange&&(i.onreadystatechange=null),delete l[e]}}}}.apply(t,i))||(e.exports=n)},function(e,t,r){var i,n;i=[r(4),r(10),r(0),r(1),r(2)],void 0===(n=function(e,t,r,i,n){"use strict";var o=r.isInt,s=r.isObject,a=r.stringifyJSON,c=r.browserInfo,d={_logger:i.create("EncodingUtils","console"),setSenderBitrates:function(e,t){d._logger.verbose("setSenderBitrates("+a(e)+", "+a(t)+")");var r="setSenderBitrates(): ";if(!(e&&e instanceof window.RTCPeerConnection)){var i=n.TypeNotValidError("peerConnection","RTCPeerConnection");return d._logger.error(r+JSON.stringify(i)),Promise.reject(i)}if(!s(t)){i=n.TypeNotValidError("bitrates","Object");return d._logger.error(r+JSON.stringify(i)),Promise.reject(i)}var l=parseInt(c.browserVersion,10);if(("Chrome"===c.browser||"Firefox"===c.browser&&l>=64||"Safari"===c.browser&&l>=13)&&"RTCRtpSender"in window&&"setParameters"in window.RTCRtpSender.prototype)return Promise.resolve().then((function(){if(o(t.video)){var i=d.getVideoSenders(e)[0];if(i)return d.setVideoSenderMaxBitrate(i,t.video);d._logger.verbose(r+'No sender of type "video" in peerconnection, skipping')}})).catch((function(e){d._logger.warning(r+e)})).then((function(){if(o(t.audio)){var i=d.getAudioSenders(e)[0];if(i)return d.setAudioSenderMaxBitrate(i,t.audio);d._logger.verbose(r+'No sender of type "audio" in peerconnection, skipping')}})).catch((function(e){d._logger.warning(r+e)}));i=n.GeneralError("Can not set bitrates on RTCRtpSender, browser not supported");return d._logger.error(r+JSON.stringify(i)),Promise.reject(i)},setAudioSenderMaxBitrate:function(e,t){d._logger.verbose("setAudioSenderMaxBitrate("+e+", "+t+")");var r=e.getParameters();return(!r.encodings||r.encodings.length<=0)&&(r.encodings=[{}]),0===t?delete r.encodings[0].maxBitrate:r.encodings[0].maxBitrate=1e3*t,e.setParameters(r)},setVideoSenderMaxBitrate:function(e,t){d._logger.verbose("setVideoSenderMaxBitrate("+e+", "+t+")");var r=e.getParameters();return(!r.encodings||r.encodings.length<=0)&&(r.encodings=[{}]),0===t?delete r.encodings[0].maxBitrate:r.encodings[0].maxBitrate=1e3*t,e.setParameters(r)},getAudioSenders:function(e){return e.getSenders().filter((function(e){return e.track&&"audio"===e.track.kind}))},getVideoSenders:function(e){return e.getSenders().filter((function(e){return e.track&&"video"===e.track.kind}))},setDegradationPreference:function(e,t){},setSDPAudioOptions:function(e,t){parseInt(c.browserVersion,10);return t&&(t.bitrate&&(e.sdp=setCodecParam(sdp,"opus/48000","maxaveragebitrate",t.bitrate)),!0===t.cbr&&(e.sdp=setCodecParam(sdp,"opus/48000","cbr",1)),!0===t.stereo&&(e.sdp=maybeSetOpusOptions(e.sdp,{opusStereo:"true"}))),e}};return d}.apply(t,i))||(e.exports=n)},function(e,t,r){"use strict";window.mergeConstraints=function(e,t){if(!e||!t)return e||t;var r=e;for(var i in t)r[i]=t[i];return r},window.iceCandidateType=function(e){return e.split(" ")[7]},window.maybeSetOpusOptions=function(e,t){return"true"===t.opusStereo?e=setCodecParam(e,"opus/48000","stereo","1"):"false"===t.opusStereo&&(e=removeCodecParam(e,"opus/48000","stereo")),"true"===t.opusFec?e=setCodecParam(e,"opus/48000","useinbandfec","1"):"false"===t.opusFec&&(e=removeCodecParam(e,"opus/48000","useinbandfec")),"true"===t.opusDtx?e=setCodecParam(e,"opus/48000","usedtx","1"):"false"===t.opusDtx&&(e=removeCodecParam(e,"opus/48000","usedtx")),t.opusMaxPbr&&(e=setCodecParam(e,"opus/48000","maxplaybackrate",t.opusMaxPbr)),e},window.maybeSetAudioSendBitRate=function(e,t){return t.audioSendBitrate?(trace("Prefer audio send bitrate: "+t.audioSendBitrate),preferBitRate(e,t.audioSendBitrate,"audio")):e},window.maybeSetAudioReceiveBitRate=function(e,t){return t.audioRecvBitrate?(trace("Prefer audio receive bitrate: "+t.audioRecvBitrate),preferBitRate(e,t.audioRecvBitrate,"audio")):e},window.maybeSetVideoSendBitRate=function(e,t){return t.videoSendBitrate?(trace("Prefer video send bitrate: "+t.videoSendBitrate),preferBitRate(e,t.videoSendBitrate,"video")):e},window.maybeSetVideoReceiveBitRate=function(e,t){return t.videoRecvBitrate?(trace("Prefer video receive bitrate: "+t.videoRecvBitrate),preferBitRate(e,t.videoRecvBitrate,"video")):e},window.preferBitRate=function(e,t,r){var i=e.split("\r\n"),n=findLine(i,"m=",r);if(null===n)return trace("Failed to add bandwidth line to sdp, as no m-line found"),e;var o=findLineInRange(i,n+1,-1,"m=");null===o&&(o=i.length);var s=findLineInRange(i,n+1,o,"c=");if(null===s)return trace("Failed to add bandwidth line to sdp, as no c-line found"),e;var a=findLineInRange(i,s+1,o,"b=AS");a&&i.splice(a,1);var c="b=AS:"+t;return i.splice(s+1,0,c),e=i.join("\r\n")},window.maybeSetVideoSendInitialBitRate=function(e,t){var r=parseInt(t.videoSendInitialBitrate);if(!r)return e;var i=parseInt(r),n=parseInt(t.videoSendBitrate);n&&(r>n&&(trace("Clamping initial bitrate to max bitrate of "+n+" kbps."),r=n,t.videoSendInitialBitrate=r),i=n);var o=e.split("\r\n"),s=findLine(o,"m=","video");if(null===s)return trace("Failed to find video m-line"),e;var a=o[s],c=new RegExp("m=video\\s\\d+\\s[A-Z/]+\\s"),d=a.split(c)[1].split(" ")[0],l=o[findLine(o,"a=rtpmap",d)].split("a=rtpmap:"+d)[1].split("/")[0],u=t.videoSendCodec||l;return e=setCodecParam(e,u,"x-google-min-bitrate",t.videoSendInitialBitrate.toString()),e=setCodecParam(e,u,"x-google-max-bitrate",i.toString())},window.removePayloadTypeFromMline=function(e,t){e=e.split(" ");for(var r=0;r<e.length;++r)e[r]===t.toString()&&e.splice(r,1);return e.join(" ")},window.removeCodecByName=function(e,t){var r=findLine(e,"a=rtpmap",t);if(null===r)return e;var i=getCodecPayloadTypeFromLine(e[r]);e.splice(r,1);var n=findLine(e,"m=","video");return null===n?e:(e[n]=removePayloadTypeFromMline(e[n],i),e)},window.removeCodecByPayloadType=function(e,t){var r=findLine(e,"a=rtpmap",t.toString());if(null===r)return e;e.splice(r,1);var i=findLine(e,"m=","video");return null===i?e:(e[i]=removePayloadTypeFromMline(e[i],t),e)},window.maybeRemoveVideoFec=function(e,t){if("false"!==t.videoFec)return e;var r=e.split("\r\n"),i=findLine(r,"a=rtpmap","red");if(null===i)return e;var n=getCodecPayloadTypeFromLine(r[i]);if(r=removeCodecByPayloadType(r,n),r=removeCodecByName(r,"ulpfec"),null===(i=findLine(r,"a=fmtp",n.toString())))return e;var o=parseFmtpLine(r[i]).pt;return null===o?e:(r.splice(i,1),(r=removeCodecByPayloadType(r,o)).join("\r\n"))},window.maybePreferAudioSendCodec=function(e,t){return maybePreferCodec(e,"audio","send",t.audioSendCodec)},window.maybePreferAudioReceiveCodec=function(e,t){return maybePreferCodec(e,"audio","receive",t.audioRecvCodec)},window.maybePreferVideoSendCodec=function(e,t){return maybePreferCodec(e,"video","send",t.videoSendCodec)},window.maybePreferVideoReceiveCodec=function(e,t){return maybePreferCodec(e,"video","receive",t.videoRecvCodec)},window.maybePreferCodec=function(e,t,r,i){var n=t+" "+r+" codec";if(!i)return trace("No preference on "+n+"."),e;trace("Prefer "+n+": "+i);var o=e.split("\r\n"),s=findLine(o,"m=",t);if(null===s)return e;for(var a=null,c=o.length-1;c>=0;--c){var d=findLineInRange(o,c,0,"a=rtpmap",i,"desc");if(null===d)break;c=d,(a=getCodecPayloadTypeFromLine(o[d]))&&(o[s]=setDefaultCodec(o[s],a))}return e=o.join("\r\n")},window.setCodecParam=function(e,t,r,i){var n=e.split("\r\n"),o=findFmtpLine(n,t),s={};if(null===o){var a=findLine(n,"a=rtpmap",t);if(null===a)return e;var c=getCodecPayloadTypeFromLine(n[a]);s.pt=c.toString(),s.params={},s.params[r]=i,n.splice(a+1,0,writeFmtpLine(s))}else(s=parseFmtpLine(n[o])).params[r]=i,n[o]=writeFmtpLine(s);return e=n.join("\r\n")},window.removeCodecParam=function(e,t,r){var i=e.split("\r\n"),n=findFmtpLine(i,t);if(null===n)return e;var o=parseFmtpLine(i[n]);delete o.params[r];var s=writeFmtpLine(o);return null===s?i.splice(n,1):i[n]=s,e=i.join("\r\n")},window.parseFmtpLine=function(e){var t={},r=e.indexOf(" "),i=e.substring(r+1).split(";"),n=new RegExp("a=fmtp:(\\d+)"),o=e.match(n);if(!o||2!==o.length)return null;t.pt=o[1];for(var s={},a=0;a<i.length;++a){var c=i[a].split("=");2===c.length&&(s[c[0]]=c[1])}return t.params=s,t},window.writeFmtpLine=function(e){if(!e.hasOwnProperty("pt")||!e.hasOwnProperty("params"))return null;var t=e.pt,r=e.params,i=[],n=0;for(var o in r)i[n]=o+"="+r[o],++n;return 0===n?null:"a=fmtp:"+t.toString()+" "+i.join(";")},window.findFmtpLine=function(e,t){var r=getCodecPayloadType(e,t);return r?findLine(e,"a=fmtp:"+r.toString()):null},window.findLine=function(e,t,r){return findLineInRange(e,0,-1,t,r)},window.findLineInRange=function(e,t,r,i,n,o){if(void 0===o&&(o="asc"),"asc"===(o=o||"asc")){for(var s=-1!==r?r:e.length,a=t;a<s;++a)if(0===e[a].indexOf(i)&&(!n||-1!==e[a].toLowerCase().indexOf(n.toLowerCase())))return a}else for(var c=-1!==t?t:e.length-1;c>=0;--c)if(0===e[c].indexOf(i)&&(!n||-1!==e[c].toLowerCase().indexOf(n.toLowerCase())))return c;return null},window.getCodecPayloadType=function(e,t){var r=findLine(e,"a=rtpmap",t);return r?getCodecPayloadTypeFromLine(e[r]):null},window.getCodecPayloadTypeFromLine=function(e){var t=new RegExp("a=rtpmap:(\\d+) [a-zA-Z0-9-]+\\/\\d+"),r=e.match(t);return r&&2===r.length?r[1]:null},window.setDefaultCodec=function(e,t){var r=e.split(" "),i=r.slice(0,3);i.push(t);for(var n=3;n<r.length;n++)r[n]!==t&&i.push(r[n]);return i.join(" ")}},function(e,t,r){var i,n;i=[r(3),r(0),r(1)],void 0===(n=function(e,t,r){"use strict";var i=t.stringifyJSON,n=t.isNumber;function o(){e.call(this),this._logger=r.create("AudioMixer","console"),this._logger.verbose("AudioMixer()"),this._name="AudioMixer",this._audioContext,this._streams=[],this._output}var s=o.prototype=Object.create(e.prototype);return s.connect=function(e,t){if(this._logger.verbose("connect("+i(e)+", "+t+")"),!e||0===e.getAudioTracks().length)return Promise.reject(new Error(this._name+'.connect parameter "stream" must contain a AudioStreamTrack'));if(!n(t)||t>1)return Promise.reject(new Error(this._name+'.connect parameter "input" must be 0 or 1'));var r=e.clone();return this._streams[t]=r,this._listenToStream(r)},s.disconnect=function(e){this._logger.verbose("disconnect("+e+")"),r.delete(this._logger)},s.getOutputStream=function(){return this._logger.verbose("getOutputStream()"),this._streams.length<2?Promise.reject(new Error(this._name+" needs exactly 2 input streams")):this._getMixedStream()},s._listenToStream=function(e){return this._logger.verbose("_listenToStream("+i(e)+")"),e.onactive=this._onactive.bind(this),e.oninactive=this._oninactive.bind(this),e.onaddtrack=this._onaddtrack.bind(this),e.onended=this._onended.bind(this),Promise.resolve()},s._unregisterAudioTrackListeners=function(e){this._logger.verbose("_unregisterAudioTrackListeners("+e+")")},s._onactive=function(e){this._logger.verbose("_onactive("+i(e)+")")},s._oninactive=function(e){this._logger.verbose("_oninactive("+i(e)+")")},s._onaddtrack=function(e){this._logger.verbose("_onaddtrack("+i(e)+")")},s._onended=function(e){this._logger.verbose("_onended("+i(e)+")")},s._getMixedStream=function(){this._logger.verbose("_getMixedStream()"),this._audioContext||(this._audioContext=new AudioContext);var e=this._audioContext.createMediaStreamSource(this._streams[0]),t=this._audioContext.createMediaStreamSource(this._streams[1]),r=this._audioContext.createChannelSplitter(2),i=this._audioContext.createChannelSplitter(2);e.connect(r),t.connect(i);var n=this._audioContext.createChannelMerger(4);r.connect(n,0,0),r.connect(n,1,1),i.connect(n,0,2),i.connect(n,1,3);var o=this._createDownMixerNode();return n.connect(o),this._output=this._audioContext.createMediaStreamDestination(),o.connect(this._output),Promise.resolve(this._output.stream)},s._createDownMixerNode=function(){this._logger.verbose("_createDownMixerNode()");var e=this._audioContext.createScriptProcessor(4096,4,2);return e.onaudioprocess=function(e){for(var t,r=e.inputBuffer.getChannelData(0),i=e.inputBuffer.getChannelData(1),n=e.inputBuffer.getChannelData(2),o=e.inputBuffer.getChannelData(3),s=e.outputBuffer.getChannelData(0),a=e.outputBuffer.getChannelData(1),c=0;c<r.length;c++)t=.25*(r[c]+i[c])+.25*(n[c]+o[c]),s[c]=t,a[c]=t},e},o}.apply(t,i))||(e.exports=n)},function(e,t,r){var i,n;i=[r(4),r(0),r(23),r(2),r(1)],void 0===(n=function(e,t,r,i,n){"use strict";var o=t.stringifyJSON,s=t.isObject,a=t.isBool,c=t.isInt,d=t.isFunction;function l(){this._devices={videoinput:[],audioinput:[]},this._selected={videoinput:!0,audioinput:!0},this._tempDevice=void 0,this._reenumeratedOnce=!1,this._logger=n.create("DeviceController","console")}var u=l.prototype;return u.enumerateDevices=function(){this._logger.verbose("enumerateDevices()");var e="enumerateDevices(): ",t=this;return this._verifyEnumerateDevicesExistence().then((function(e){return e.enumerateDevices()})).then((function(e){var r,i=t._createDevices(e);r=t._updateDevices(i);var n=t._tempDevice;if(n&&!t._hasSCD()){var o=t._devices.videoinput.length;n.displayIndex=o,t._devices[n.kind].push(n)}return Promise.resolve({data:{devices:{videodevices:t._listed().videoinput,audiodevices:t._listed().audioinput},updated:r}})})).catch((function(r){if(!r){var n=i.ObjectNotExistError("error","Error");return t._logger.error(e+JSON.stringify(n)),Promise.reject(n)}if("NanoError"===r.type){var o=i.composeEvent(r);return t._logger.error(e+JSON.stringify(r)),Promise.reject(o)}n=i.EnumerateDevicesError(r),o=i.composeEvent(n);return t._logger.error(e+JSON.stringify(n)),Promise.reject(o)}))},u.addScreenCaptureDevice=function(i){this._logger.verbose("addScreenCaptureDevice("+i+")");var n=t.browserInfo.browser;if(!t.enumContainsValue(e.SCREEN_CAPTURE_BROWSER,n.toLowerCase()))return{};var o=new r({deviceId:"screen",kind:"videoinput",label:i+" ("+n+")",displayLabel:i+" ("+n+")"});if("Chrome"!==n||this._hasDevices())return this._tempDevice=o,{};var s=this._devices.videoinput.length;return o.displayIndex=s,this._devices.videoinput.push(o),{data:{devices:{videodevices:this._listed().videoinput,audiodevices:this._listed().audioinput},updated:!0}}},u.setDevice=function(e){this._logger.verbose("setDevice("+o(e)+")");var t="setDevice(): ";if(!s(e)){var r=i.TypeNotValidError("config","Object");return this._logger.error(t+JSON.stringify(r)),Promise.reject(r)}if(void 0===e.kind||"videoinput"!==e.kind&&"audioinput"!==e.kind){r=i.ValueNotValidError("config.kind","video/audio");return this._logger.error(t+JSON.stringify(r)),Promise.reject(r)}if(void 0===e.device||!a(e.device)&&!c(e.device)){r=i.TypeNotValidError("config.device","Boolean/Int");return this._logger.error(t+JSON.stringify(r)),Promise.reject(r)}var n=e.device,d=this._devices[e.kind],l=void 0;if(a(n))l=n;else if(void 0!==(n=d[n]))for(var u=0;u<d.length;u++)if(n.deviceId===d[u].deviceId){"videoinput"===e.kind&&n.setVideoDeviceConfig(e),l=n;break}if(void 0===l){this._selected[e.kind]=!1;r=i.DevicesNotFoundError();return this._logger.error(t+JSON.stringify(r)),Promise.reject(r)}return this._selected[e.kind]=l,Promise.resolve({device:l})},u.getDevice=function(e){this._logger.verbose("getDevice("+e+")");if("videoinput"!==e&&"audioinput"!==e){var t=i.ValueNotValidError("config.kind","video/audio");return this._logger.error("getDevice(): "+JSON.stringify(t)),Promise.reject(t)}var r=this._selected;return Promise.resolve(r[e])},u.updateSelected=function(e,t){this._logger.verbose("updateSelected("+e+", "+t+")");var r=e.getVideoTracks(),i=e.getAudioTracks(),n=this;r&&r.length>0&&this.getDevice("videoinput").then((function(e){if(t||"screen"!==!e.deviceId){if(!a(e)){s=e.videoDeviceConfig||{};e.setVideoDeviceConfig(s)}n._selected.videoinput=e}else{var i=r[0].label,o=n._getDeviceForLabel(i);if(!0===e||o.label!==e.label){var s=e.videoDeviceConfig||{};o.setVideoDeviceConfig(s),n._selected.videoinput=o}}})).catch((function(e){n._logger.error("updateSelected(): "+JSON.stringify(e))})),i&&i.length>0&&n.getDevice("audioinput").then((function(e){if(t)n._selected.audioinput=e;else{var r=i[0].label,o=n._getDeviceForLabel(r);!0!==e&&o.label===e.label||(n._selected.audioinput=o)}})).catch((function(e){n._logger.error("updateSelected(): "+JSON.stringify(e))}))},u.shouldReenumerate=function(e){if(this._logger.verbose("shouldReenumerate("+e+")"),e&&this._reenumeratedOnce)return!1;this._reenumeratedOnce=!0;for(var t=0,r=this._getAllDevices(),i=0;i<r.length;i++){""===(r[i].label||"")&&(t+=1)}return t==(this._hasSCD()?r.length-1:r.length)},u.composeConstraints=function(e){this._logger.verbose("composeConstraints("+o(e)+")");var t="composeConstraints(): ",r=this;return this._getConstraintTypes(e).then((function(i){for(var n={audio:!1,video:!1},o=0;o<i.length;o++)switch(i[o]){case"video":a(e.videoinput)?n.video=e.videoinput:(n.video=e.videoinput.videoDeviceConfig,n.video.deviceId={exact:e.videoinput.deviceId});break;case"audio":a(e.audioinput)?n.audio=e.audioinput:(n.audio={},n.audio.deviceId={exact:e.audioinput.deviceId});break;case"screen":var s=e.videoinput.videoDeviceConfig;n.video={width:s.width.ideal,height:s.height.ideal,frameRate:s.frameRate.ideal},a(e.audioinput)?n.audio=e.audioinput:(n.audio={},n.audio.deviceId={exact:e.audioinput.deviceId})}var c=t+JSON.stringify(n);return r._logger.verbose(c),Promise.resolve(n)})).catch((function(e){var i=t+JSON.stringify(e);return r._logger.error(i),Promise.reject(e)}))},u._getAllDevices=function(){return[].concat(this._devices.videoinput).concat(this._devices.audioinput)},u._hasDevices=function(){return!(this._getAllDevices().length>0)},u._hasSCD=function(){var t=this._devices.videoinput.length-1,r=this._devices.videoinput[t];return r&&r.deviceId===e.MEDIA_SOURCES.SCREEN},u._listed=function(){var e=this._getAllDevices();return this._getListedFromDevices(e)},u._createDevices=function(e){this._logger.verbose("_createDevices("+o(n)+")");for(var t={videoinput:[],audioinput:[]},i=0;i<e.length;i++){var n=e[i],s=n.kind;if("videoinput"===s||"audioinput"===s){var a=t[s].length;n.displayIndex=a;var c=new r(n);t[s].push(c)}}return t},u._addDevices=function(e){for(this._logger.verbose("_addDevices("+o(e)+")");this._devices.videoinput.length;)this._devices.videoinput.pop();for(;this._devices.audioinput.length;)this._devices.audioinput.pop();this._devices.videoinput=e.videoinput,this._devices.audioinput=e.audioinput},u._updateDevices=function(e){this._logger.verbose("_updateDevices("+o(a)+")");var t=[].concat(e.videoinput).concat(e.audioinput),r=this._getAllDevices().filter((function(e){return"screen"!==e.deviceId})),i=!1;if(r.length!==t.length)i=!0;else for(var n=0;n<r.length;n++){var s=r[n],a=t[n],c=["constraints","setVideoDeviceConfig","videoDeviceConfig"];for(var d in s)if(Object.prototype.hasOwnProperty.call(s,d)&&Object.prototype.hasOwnProperty.call(a,d)&&-1===c.indexOf(d)&&-1===c.indexOf(d)&&s[d]!==a[d]){i=!0;break}}return this._addDevices(e),i},u._getDeviceForLabel=function(e){this._logger.verbose("_getDeviceForLabel("+e+")");var t=this._getAllDevices();if(-1!==e.indexOf("screen"))for(var r=0;r<t.length;r++){if("screen"===(i=t[r]).deviceId)return i}else for(r=0;r<t.length;r++){var i;if((i=t[r]).label===e)return i}},u._getListedFromDevices=function(e){this._logger.verbose("_getListedFromDevices("+o(e)+")");for(var t={videoinput:[],audioinput:[]},r=0;r<e.length;r++){var i=e[r];t[i.kind].push({index:i.displayIndex,id:i.label||i.displayId})}return t},u._getConstraintTypes=function(r){this._logger.verbose("_getConstraintTypes("+o(r)+")");var n="_getConstraintTypes(): ";if(!r){var s=i.ObjectNotExistError("devices","Array");return this._logger.error(n+JSON.stringify(s)),Promise.reject(s)}var c=[];if(r.videoinput){var d=r.videoinput.videoDeviceConfig?r.videoinput.videoDeviceConfig.source:a(r.videoinput)?e.MEDIA_SOURCES.CAMERA:void 0;if(!t.enumContainsValue(e.MEDIA_SOURCES,d)){s=i.EnumValueNotValidError(d,e.MEDIA_SOURCES);return this._logger.error(n+JSON.stringify(s)),Promise.reject(s)}c.push(d===e.MEDIA_SOURCES.SCREEN?"screen":"video")}return r.audioinput&&(r.videoinput&&"screen"!==r.videoinput.deviceId||!r.videoinput)&&c.push("audio"),Promise.resolve(c)},u._verifyEnumerateDevicesExistence=function(){this._logger.verbose("_verifyEnumerateDevicesExistence()");var e=navigator.mediaDevices;if(!e||!d(e.enumerateDevices)){var t=i.FunctionNotDefinedError("enumerateDevices");return this._logger.error("_verifyEnumerateDevicesExistence(): "+JSON.stringify(t)),Promise.reject(t)}return Promise.resolve(e)},l}.apply(t,i))||(e.exports=n)},function(e,t,r){var i,n;i=[r(4)],void 0===(n=function(e){"use strict";return function(t){this.deviceId=t.deviceId,this.kind=t.kind,this.label=t.label,this.groupId=t.groupId,this.displayIndex=t.displayIndex,this.displayId=t.kind+"device ID: "+t.deviceId.substr(0,10),this.videoDeviceConfig={},this.constraints={},this.setVideoDeviceConfig=function(t){var r=(t=t||{}).source||e.MEDIA_SOURCES.CAMERA,i=t.width||0,n=t.height||0,o=t.framerate||0,s=t.minFramerate||0;r!==e.MEDIA_SOURCES.CAMERA&&r!==e.MEDIA_SOURCES.SCREEN||(this.videoDeviceConfig.source=r),o<s&&(o=s),i>0&&n>0&&(this.videoDeviceConfig.width={ideal:i},this.videoDeviceConfig.height={ideal:n}),o>0&&(this.videoDeviceConfig.frameRate={ideal:o})}}}.apply(t,i))||(e.exports=n)},function(e,t,r){var i,n;i=[r(0),r(2),r(1)],void 0===(n=function(e,t,r){"use strict";var i=e.stringifyJSON,n=e.isObject,o=e.isEmpty,s=e.isString;return function(e){this._logger=r.create("MediaController","console");if(!n(e)||o(e)){var a=t.TypeNotValidError("config","Object");throw this._logger.error("Media(): "+i(a)),a}if(!n(e.stream)){a=t.TypeNotValidError("config.stream","Object");throw this._consoleLogger.error("Media(): "+i(a)),a}if(!s(e.kind)||"local"!==e.kind&&"remote"!==e.kind){a=t.ValueNotValidError("config.kind","local/remote");throw this._consoleLogger.error("Media(): "+i(a)),a}this.stream=e.stream,this.kind=e.kind,this.metadata={hasVideo:0,hasAudio:0,width:0,height:0,framerate:0},this.remoteUserName=e.remoteUserName,this.remoteUserId=e.remoteUserId,this.getTracks=function(){return[].concat(this.getVideoTracks()).concat(this.getAudioTracks())},this.getVideoTracks=function(){return this.stream.getVideoTracks()},this.getAudioTracks=function(){return this.stream.getAudioTracks()},this.hasVideoTracks=function(){return this.stream.getVideoTracks().length>0?1:0},this.hasAudioTracks=function(){return this.stream.getAudioTracks().length>0?1:0},this.getVideoTracksSettings=function(){var e=this.stream.getVideoTracks();return e&&e.length>0?this.stream.getVideoTracks()[0].getSettings():void 0},this.getAudioTracksSettings=function(){var e=this.stream.getAudioTracks();return e&&e.length>0?this.stream.getAudioTracks()[0].getSettings():void 0},this.muteTracks=function(e,t){var r="videoinput"===e?this.getVideoTracks():"audioinput"===e?this.getAudioTracks():void 0;if(r)for(var i=0;i<r.length;i++)r[i].enabled=!t},this.bind=function(e){for(var t=this.getTracks(),r=0;r<t.length;r++)t[r].onended=e._onTrackEnded.bind(e)},this.unbind=function(){if(this.stream){for(var e=this.getTracks(),t=0;t<e.length;t++)e[t].onended=void 0;this._stopTracks(e),this.stream=void 0}this.metadata={hasAudio:0,hasVideo:0,width:0,height:0,framerate:0}},this._stopTracks=function(e){for(var t=0;t<e.length;t++)e[t].stop()}}}.apply(t,i))||(e.exports=n)},function(e,t,r){var i,n;i=[r(4),r(0),r(3),r(1),r(2),r(11)],void 0===(n=function(e,t,r,i,n,o){"use strict";var s=t.isObject,a=t.isString,c=t.isFunction,d=t.stringifyJSON;function l(){r.call(this),this._logger=i.create("ScreenCapture","console"),this._logger.verbose("ScreenCapture()");this._screenCaptureName=void 0,this._isScreenCaptureAvailable=!1,this._isChromeScreenCaptureExtensionInstalled=!1,this._sourceId=null,this._onGetSourceId=null;var e=this;window.addEventListener("message",(function(t){e._logger.verbose("window.addEventListener("+d(t)+")");var r="addEventListener(): ",i=t.origin;if(a(i)&&e._isValidOrigin(i)&&s(t.data)){var o=t.data.type;if(a(o)&&e._isValidType(o)){var c=t.data.command;if(a(c)){var l=t.data.value;if(a(l)){if("message"===c){if("isReady"===l||"isLoaded"===l){e._isChromeScreenCaptureExtensionInstalled=!0;var u=r+e._screenCaptureName+" event: "+l;e._logger.verbose(u)}}else if("error"===c){u=r+e._screenCaptureName+" error: "+l;if(e._logger.verbose(u),"PermissionDeniedError"===l){var p=n.GetDisplayMediaError("PermissionDenied",u);e.emit(p.name,p)}}else if("setSourceId"===c){var h=l;u=r+e._screenCaptureName+"event: "+c;e._logger.verbose(u),e._setSourceId(h)}e._isScreenCaptureAvailable=!!("getDisplayMedia"in navigator.mediaDevices&&e._isChromeScreenCaptureExtensionInstalled)}}}}})),"chrome"===o.browserDetails.browser&&o.browserDetails.version<72?this._logger.warning('ScreenCapture(): Chrome screen capture extension is required for Chrome < v.72; use RTCUser\'s "addScreenCaptureExtension()" call to enable an extension'):this._initWithNativeAPISupport()}var u=l.prototype=Object.create(r.prototype);return u.addChromeExtension=function(e){this._logger.verbose("addChromeExtension("+e+")");if(!a(e)){var t=n.TypeNotValidError("name","String");throw self._logger.error("addChromeExtension(): "+d(t)),t}this._screenCaptureName=e,this._checkChromeExtensionAliveness(),this._initWithChromeExtensionSupport()},u.getScreenCaptureName=function(){return this._logger.verbose("getScreenCaptureName()"),this._screenCaptureName},u.isScreenCaptureAvailable=function(){return this._logger.verbose("isScreenCaptureAvailable()"),this._isScreenCaptureAvailable},u._initWithNativeAPISupport=function(){this._logger.verbose("_initWithNativeAPISupport()"),t.enumContainsValue(e.SCREEN_CAPTURE_BROWSER,o.browserDetails.browser.toLowerCase())?(this._screenCaptureName="nanoScreenCapture","firefox"==o.browserDetails.browser&&o.browserShim.shimGetDisplayMedia(window,"screen"),this._isScreenCaptureAvailable="getDisplayMedia"in navigator.mediaDevices):this._isScreenCaptureAvailable=!1},u._initWithChromeExtensionSupport=function(){this._logger.verbose("_initWithChromeExtensionSupport()");var e="_initWithChromeExtensionSupport(): ",t=this;o.browserShim.shimGetDisplayMedia(window,(function(){return new Promise((function(r,i){t.once("PermissionDenied",(function(){var r=n.GetDisplayMediaError("PermissionDenied");t._logger.error(e+d(r)),i(r)})),t._getSourceId((function(){if(t._sourceId)r(t._sourceId);else{var o=n.GetDisplayMediaError("NotAllowedError");t._logger.error(e+d(o)),i(o)}}))}))}))},u._checkChromeExtensionAliveness=function(){this._logger.verbose("_checkChromeExtensionAliveness()");var e=this;setTimeout((function(){e._isChromeScreenCaptureExtensionInstalled||(e._isChromeScreenCaptureExtensionInstalled=!1)}),500),this._logger.verbose("_checkChromeExtensionAliveness(): "+this._screenCaptureName+"alive?"),this._toWindow(this._screenCaptureName,"isAlive","")},u._isValidOrigin=function(e){return this._logger.verbose("_isValidOrigin("+e+")"),e===window.location.origin},u._isValidType=function(e){return this._logger.verbose("_isValidType("+e+")"),e===this._screenCaptureName},u._getSourceId=function(e){this._logger.verbose("_getSourceId()");c(e)&&(this._onGetSourceId=e,this._logger.verbose("_getSourceId(): "+this._screenCaptureName),this._toWindow(this._screenCaptureName,"getSourceId",""))},u._setSourceId=function(e){this._logger.verbose("_setSourceId("+e+")"),this._sourceId=void 0!==e?e:null,this._onGetSourceId&&this._onGetSourceId()},u._toWindow=function(e,t,r){this._logger.verbose("_toWindow("+this._screenCaptureName+e+", "+t+", "+r+")"),window.postMessage({type:e,command:t,value:r},"*")},l}.apply(t,i))||(e.exports=n)},function(e,t,r){var i,n;i=[r(5),r(4),r(3),r(0),r(27),r(7),r(2),r(1)],void 0===(n=function(e,t,r,i,n,o,s,a){"use strict";var c=i.stringifyJSON,d={IDLE:1,ROOM_ENTERED:2,STOPPED:3},l=t.CHATPEER_STATE;function u(e,t,i){r.call(this),this._logger=a.create("ChatRoom","console"),this._logger.verbose("ChatRoom("+c(e)+")"),this._roomName=e.room,this._userName=e.userName,this._userId=e.userId,this._peers=[],this._serverUserList=[],this._state=d.IDLE,this._iceServers=[],this._config={},this._session=t,this._mediaController=i}var p=u.prototype=Object.create(r.prototype);return p.setConfig=function(e){this._logger.verbose("setConfig("+c(e)+")"),this._config=e},p.setIceServers=function(e){this._iceServers=e},p.enter=function(){this._logger.verbose("enter()");var e=this;return e._state==d.ROOM_ENTERED?Promise.reject(s.WrongStateError("Already in room")):(this._session.on("RoomMessage",e._onRoomMessage.bind(e)),this._session.enterRoom({roomName:this._roomName,userName:this._userName}).then((function(t){e._state=d.ROOM_ENTERED})))},p.leave=function(){this._logger.verbose("leave()");var e=this;return this._session.removeEvent("RoomMessage"),this._session.leaveRoom({roomName:this._roomName}).then((function(){e.destroy(),e._state=d.STOPPED})).catch((function(t){return e.destroy(),e._state=d.STOPPED,e._logger.error("leave(): "+c(t)),Promise.reject(t)}))},p.callUser=function(e){this._logger.verbose("callUser("+e+")");var t=this;return this._session.callUser({userId:e,roomName:this._roomName}).catch((function(e){return t._logger.error("callUser(): "+c(e)),Promise.reject(e)}))},p.answerCall=function(e){this._logger.verbose("answerCall("+e+")");var t=this;return this._session.answerCall({userId:e,roomName:this._roomName}).then((function(r){t._createChatPeer(!1,e,r.user_name,r.caller_peer_id,r.callee_peer_id)})).catch((function(e){return t._logger.error("answerCall(): "+c(e)),Promise.reject(e)}))},p.declineCall=function(e){this._logger.verbose("declineCall("+e+")");var t=this;return this._session.declineCall({userId:e,roomName:this._roomName}).catch((function(e){return t._logger.error("declineCall(): "+c(e)),Promise.reject(e)}))},p.hangUpCall=function(e){this._logger.verbose("hangUpCall("+e+")");var t=this;return this._session.hangUpCall({userId:e,roomName:this._roomName}).then((function(){t._destroyPeer(e),t._createPublicUserList()})).catch((function(e){return t._logger.error("hangUpCall(): "+c(e)),Promise.reject(e)}))},p.getUsersCount=function(){return this._logger.verbose("getUsersCount()"),this._peers.length},p.destroy=function(){this._logger.verbose("destroy()"),this._session.removeEvent("RoomMessage");for(var e=0;e<this._peers.length;e++)this._peers[e].destroy();return this._peers=[],a.delete(this._logger),Promise.resolve()},p._addEventPayload=function(e){return(e=e||{}).data=e.data||{},e.data.state=this._state,e},p._reemit=function(e){e=this._addEventPayload(e),this.emit(e.name,e)},p._createChatPeer=function(e,t,r,i,o){this._logger.verbose("_createChatPeer("+e+", "+t+", "+r+", "+i+", "+o+")");var s=new n(this._userName,this._userId,t,r,this._roomName,this._session,this._mediaController);s.setIceServers(this._iceServers),s.addStream(this._mediaController.getLocalMedias()[0].stream),s.setConfig(this._config),s.start(e,i,o),this._peers.push(s),this._bind(s)},p._destroyPeer=function(e){this._logger.verbose("_destroyPeer("+e+")");var t=this._removePeerFromPeerList(e);this._unbind(t),t.destroy()},p._bind=function(e){this._logger.verbose("_bind("+c(e)+")"),e.on("RemoteStreamAdded",this._reemit.bind(this)),e.on("StateChanged",this._handlePeerState.bind(this))},p._unbind=function(e){this._logger.verbose("_unbind("+c(e)+")"),e.removeEvent("RemoteStreamAdded"),e.removeEvent("StateChanged")},p._handlePeerState=function(e){switch(this._logger.verbose("_handlePeerState( "+c(e)+")"),e.data.state){case t.CHATPEER_STATE.INITIALIZED:case t.CHATPEER_STATE.SIGNALING:case t.CHATPEER_STATE.SIGNALLING_DONE:case t.CHATPEER_STATE.CALLING:case t.CHATPEER_STATE.NEGOTIATION_NEEDED:break;case t.CHATPEER_STATE.DISCONNECTED:case t.CHATPEER_STATE.FAILED:this._destroyPeer(e.target.getRemoteUserId());break;case t.CHATPEER_STATE.STOPPED:}this._createPublicUserList()},p._createPublicUserList=function(){this._logger.verbose("_createPublicUserList()");for(var e,t,r,n,o="_createPublicUserList(): ",s=[],a=0;a<this._peers.length;a++)n={},t=(e=this._peers[a]).getState(),r=i.getKeyByValue(l,t).toLowerCase(),n.state=r,n.remoteUserName=e.getRemoteUserName(),n.remoteUserId=e.getRemoteUserId(),s.push(n);var d=this._serverUserList.filter((function(e){for(var t=0;t<s.length;t++)if(s[t].remoteUserId==e.remoteUserId)return!1;return!0})),u=d.concat(s).sort((function(e,t){return e.remoteUserName.toUpperCase()<t.remoteUserName.toUpperCase()?-1:e.remoteUserName.toUpperCase()>t.remoteUserName.toUpperCase()?1:0}));return this._logger.verbose(o+"publicList: "+c(d)),this._logger.verbose(o+"peerList: "+c(s)),this._logger.verbose(o+"sortedList: "+c(u)),this.emit("RoomUpdate",{type:"room_update",data:{userlist:u}}),u},p._getPeerByRemoteUserId=function(e){var t;this._logger.verbose("_getPeerByRemoteUserId("+e+")");for(var r=0;r<this._peers.length;r++)if((t=this._peers[r]).getRemoteUserId()===e)return t},p._removePeerFromPeerList=function(e){var t;this._logger.verbose("_removePeerFromPeerList("+e+")");for(var r=0;r<this._peers.length;r++)if((t=this._peers[r]).getRemoteUserId()===e)return this._peers.splice(r,1),t},p._onRoomMessage=function(e){this._logger.verbose("_onRoomMessage("+c(e)+")");var t={};switch(e.type){case"room_update":this._logger.verbose("_onRoomMessage(): room_update: "+c(e)),this._serverUserList=e.data.userlist,this._createPublicUserList();break;case"call_incoming":t.remoteUserId=e.user_id,t.remoteUserName=e.user_name,this.emit("RoomUpdate",{type:"call_incoming",data:t});break;case"call_declined":t.remoteUserName=e.data.user_name,t.remoteUserId=e.data.user_id,this.emit("RoomUpdate",{type:"call_declined",data:t});break;case"hang_up":this._destroyPeer(e.data.user_id),this._createPublicUserList();break;case"start_as_caller":this._createChatPeer(!0,e.user_id,e.user_name,e.caller_peer_id,e.callee_peer_id)}},u}.apply(t,i))||(e.exports=n)},function(e,t,r){var i,n;i=[r(5),r(9),r(4),r(3),r(0),r(12),r(7),r(1)],void 0===(n=function(e,t,r,i,n,o,s,a){"use strict";var c=n.isString,d=n.isIntString,l=n.stringifyJSON,u=n.isArray,p=r.CHATPEER_STATE;function h(e,t,r,n,o,s,l){i.call(this),this._logger=a.create("ChatPeer","console"),this._logger.verbose("ChatPeer("+e+", "+t+", "+r+", "+n+", "+o+")");var u="ChatPeer(): ";c(e)||this._logger.error(u+"Param userName must be a string"),c(o)||this._logger.error(u+"Param room must be a string"),d(t)||this._logger.error(u+"Param userId must be an integer"),this._userName=e,this._userId=t,this._peerId=void 0,this._remoteUserName=n,this._remoteUserId=r,this._remotePeerId=void 0,this._room=o,this._pcClient=void 0,this._streams=[],this._startTime=null,this._iceServers=[],this._config={},this._state=p.IDLE,this._messageQueue=[],this._isCaller=!1,this._remoteStream=null,this._statsEnabled=!1,this._statsIntervalTime=1e3,this._statsInterval=0,this._rtcStats=null,this._session=s,this._mediaController=l}var m=h.prototype=Object.create(i.prototype);return m.setIceServers=function(e){this._iceServers=e},m.setConfig=function(e){this._config=e},m.getState=function(){return this._state},m.getPeerId=function(){return this._peerId},m.getRemoteUserId=function(){return this._remoteUserId},m.getRemoteUserName=function(){return this._remoteUserName},m.start=function(e,t,r){var i;this._logger.verbose("start("+e+", "+t+", "+r+")"),this._isCaller=e,this._createPCClient(),this._isCaller?(this._peerId=t,this._remotePeerId=r):(this._peerId=r,this._remotePeerId=t),i="receiver_peer_"+this._peerId,this._session.on(i,this._onServerMessage.bind(this)),this._isCaller?this._pcClient.startAsCaller(null):this._pcClient.startAsCallee(this._messageQueue),this._setState(p.INITIALIZED)},m.addStream=function(e){this._logger.verbose("addStream("+l(e)+")");e?2!==this._streams.length?u(e)?this._streams=e:this._streams.push(e):this._logger.__warning("addStream(): [peer id: "+this._peerId+"] stream count is already=2, we only support 2 streams/Chatpeer"):this._logger.error("addStream(): [peer id: "+this._peerId+'] parameter "stream" must not be undefined')},m.enableStats=function(e,t){this._logger.verbose("enableStats("+e+", "+t+")"),this._statsEnabled=void 0===e||e,this._statsIntervalTime=t||1e3,this._rtcStats=null,this._statsEnabled&&(this._rtcStats=new o,this._rtcStats.on("ReceivedWebRTCStats",this._reemit.bind(this)))},m.destroy=function(){this._logger.verbose("destroy()"),this._unbind(),this._closePCClient(),this._setState(p.STOPPED),this._remoteStream&&(this._mediaController.removeMedia(this._remoteStream.id),this._remoteStream=null),a.delete(this._logger)},m._onServerMessage=function(e){this._logger.verbose("_onServerMessage("+l(e)+")");var t="_onServerMessage(): ",r=this;switch(e.type){case"sdp_message":r._pcClient&&r._pcClient.isStarted()?r._pcClient.setRemoteDescription(e.data).catch((function(e){return r._logger.error(t+"setRemoteDescription failed:"+e),Promise.reject(e)})).then((function(){if(r._logger.verbose(t+"setRemoteDescription succeded"),!r._isCaller)return r._pcClient.doAnswer()})).catch((function(e){return r._logger.error(t+"doAnswer failed:"+e),Promise.reject(e)})).then((function(e){if(!r._isCaller){r._logger.verbose(t+"doAnswer succeded "+e);var i={};return i.sender_peer=r._peerId,i.receiver_peer=r._remotePeerId,i.data=e,r._session.sendSignalingMessage(i).catch((function(e){r._logger.error(t+"sendSignalingMessage - "+e)}))}})).catch((function(e){r._logger.error(t+"doAnswer failed:",e)})):r._messageQueue.push(e.data.sdp);break;case"ice_candidate":r._pcClient&&r._pcClient.isStarted()?r._pcClient.addIceCandidate(e.data.candidate):r._messageQueue.push(e.data.candidate);break;case"server_error":r._setState(p.FAILED),r._logger.error(t+"Server error: "+e.error);break;default:r._logger.verbose(t+"Unknown message:"+e)}},m._addEventPayload=function(e){return(e=e||{}).target=this,e.data=e.data||{},e.data.state=this._state,e.data.message=n.getKeyByValue(p,this._state).toLowerCase(),e.data.text=e.data.message,e},m._reemit=function(e){e=this._addEventPayload(e),this.emit(e.name,e)},m._collectRtcStats=function(){this._logger.verbose("_collectRtcStats()");var e=this;clearInterval(e._statsInterval),this._statsInterval=setInterval((function(){e._pcClient?e._pcClient.getStats().then((function(t){e._rtcStats||(e._rtcStats=new o),e._rtcStats.putReport(t)})).catch((function(t){e._logger.error("_collectRtcStats(): [peer id: "+e._peerId+"] "+t)})):clearInterval(e._statsInterval)}),this._statsIntervalTime)},m._stopCollectRtcStats=function(){this._logger.verbose("_stopCollectRtcStats()");this._statsInterval&&(this._logger.verbose("_stopCollectRtcStats(): Stopping rtc stats collection"),clearInterval(this._statsInterval))},m._getPeerConnectionConfig=function(){this._logger.verbose("_getPeerConnectionConfig()");var e={iceServers:this._iceServers,iceTransports:"all"},t={optional:[],mandatory:[]};return t.optional.push({googCpuOveruseDetection:!1}),t.optional.push({RtpDataChannels:!1}),{mediaConstraints:{audio:!0,video:!0},sdpPatches:this._config.sdpPatches,peerConnectionConfig:e,peerConnectionConstraints:t,send:!0,receive:!0,videoSendCodec:this._config.codecs.videoCodec||"H264",videoRecvCodec:this._config.codecs.videoCodec||"H264",videoSendBitrate:this._config.bitrates.videoSendBitrate||0,videoSendInitialBitrate:this._config.bitrates.videoSendInitialBitrate||0}},m._createPCClient=function(){this._logger.verbose("_createPCClient()");var e="_createPCClient(): ";if(this._pcClient)this._logger.verbose(e+"[peer id:  "+this._peerId+"] PeerConnection still alive, do not create!");else try{this._pcClient=new t(this._getPeerConnectionConfig(),this._startTime),this._bind();for(var r=0;r<this._streams.length;r++)this._pcClient.addStream(this._streams[r]);this._logger.verbose(e+"Created PeerConnectionClient")}catch(t){this._logger.error(e+"[peer id: "+this._peerId+"] Create PeerConnection exception: "+t.message),this.emitSimple("CreatePeerConnectionClientError")}},m._bind=function(){this._logger.verbose("_bind()"),this._pcClient.on("SignalingMessage",this._onSignalingMessage.bind(this)),this._pcClient.on("RemoteStreamRemoved",this._onRemoteStreamRemoved.bind(this)),this._pcClient.on("RemoteStreamAdded",this._onRemoteStreamAdded.bind(this)),this._pcClient.on("IceConnectionStateChange",this._onIceConnectionStateChange.bind(this)),this._pcClient.on("EndOfLocalCandidates",this._onEndOfLocalCandidates.bind(this)),this._pcClient.on("NegotiationNeeded",this._onNegotiationNeeded.bind(this))},m._unbind=function(){this._logger.verbose("_unbind()"),this._pcClient.off("SignalingMessage",this._onSignalingMessage.bind(this)),this._pcClient.off("RemoteStreamRemoved",this._onRemoteStreamRemoved.bind(this)),this._pcClient.off("RemoteStreamAdded",this._onRemoteStreamAdded.bind(this)),this._pcClient.off("IceConnectionStateChange",this._onIceConnectionStateChange.bind(this)),this._pcClient.off("EndOfLocalCandidates",this._onEndOfLocalCandidates.bind(this)),this._pcClient.off("NegotiationNeeded",this._onNegotiationNeeded.bind(this))},m._setState=function(e){this._logger.verbose("_setState("+e+")");if(e!==this._state){if(this._state!==p.CALLING||e!==p.SIGNALING&&e!==p.SIGNALLING_DONE){var t,r=this._state;this._state=e,this._logger.verbose("_setState(): State: "+n.getKeyByValue(p,r)+" -> "+n.getKeyByValue(p,this._state)),t=this._addEventPayload({}),this.emit("StateChanged",t)}}else this._logger.verbose("_setState(): No state change")},m._onIceConnectionStateChange=function(e){switch(this._logger.verbose("_onIceConnectionStateChange("+l(e)+")"),e.data.state){case"new":case"checking":this._setState(p.SIGNALING);break;case"connected":case"completed":this._setState(p.SIGNALLING_DONE),this._statsEnabled&&this._pcClient&&this._collectRtcStats();break;case"failed":this._setState(p.FAILED),this._statsEnabled&&this._pcClient&&this._stopCollectRtcStats();break;case"disconnected":this._setState(p.DISCONNECTED)}},m._onNegotiationNeeded=function(e){this._logger.verbose("_onNegotiationNeeded("+l(e)+")");this._logger.warning("_onNegotiationNeeded(): NegotiationNeeded event has been fired")},m._onEndOfLocalCandidates=function(e){this._logger.verbose("_onEndOfLocalCandidates("+l(e)+")")},m._onRemoteStreamAdded=function(e){this._logger.verbose("_onRemoteStreamAdded("+l(e)+")");var t=this;if(!this._remoteStream){this._remoteStream=e.data.stream;var r={stream:this._remoteStream,kind:"remote",remoteUserId:this._remoteUserId,remoteUserName:this._remoteUserName};this._mediaController.addRemoteMedia(r).then((function(){t._setState(p.CALLING),t.emitSimple(e.name,{stream:t._remoteStream.id})})).catch((function(e){var r="_onRemoteStreamAdded(): Failed to add remote media to MediaController list of medias:"+e;t._logger.error(r)}))}},m._onRemoteStreamRemoved=function(e){this._logger.verbose("_onRemoteStreamRemoved("+l(e)+")"),this._remoteStream&&(this._mediaController.removeMedia(this._remoteStream.id),this._remoteStream=null)},m._closePCClient=function(){this._logger.verbose("_closePCClient()");if(this._pcClient){var e,t,r=this._streams;for(e=0,t=r.length;e<t;++e)try{this._pcClient.removeStream(r[e])}catch(e){this._logger.error("_closePCClient(): [peer id: "+this._peerId+"] Could not remove stream from peerconnectionclient")}this._pcClient.close(),this._streams=null,this._pcClient=null}else this._logger.warning("_closePCClient(): No PeerConenctionClient")},m._sendMessageToPeer=function(e){this._logger.verbose("_sendMessageToPeer("+l(e)+")");var t="_sendMessageToPeer(): ",r=this,i={};if(!this._remotePeerId){var n=t+"Trying to send message, but no remote peer id set! This should not happen!";return this._logger.error(n),Promise.reject(n)}if(!this._peerId){n=t+"Trying to send message, but no peer id set! This should not happen!";return this._logger.error(n),Promise.reject(n)}return i.sender_peer=this._peerId,i.receiver_peer=this._remotePeerId,i.data=e,this._session.sendSignalingMessage(i).catch((function(e){return r._logger.error(t+e),Promise.reject(e)}))},m._onSignalingMessage=function(e){this._logger.verbose("_onSignalingMessage("+l(e)+")");var t="_onSignalingMessage(): ",r=this;this._remotePeerId?this._sendMessageToPeer(e.data).then((function(){})).catch((function(e){r._logger.error(t+e)})):this._logger.error(t+"Trying to send message, but no remote peer set! This should not happen!")},h}.apply(t,i))||(e.exports=n)},function(e,t,r){var i,n;i=[r(0),r(6),r(1),r(29),r(2)],void 0===(n=function(e,t,r,i,n){"use strict";var o=e.isObject,s=e.isBool,a=e.isInt,c=e.isEmpty,d=e.stringifyJSON;function l(e,t){this._consoleLogger=r.create("MetricsController","console"),this._grayLogger=r.create("MetricsController","graylog"),this._consoleLogger.verbose("MetricsController("+d(t)+")");var s="MetricsController(): ";if(this._statsInterval=10,this._lastStatsUpdate=void 0,this._broadcastSignallingTime=void 0,this._broadcastStartingTime=void 0,this._lastPLICount=void 0,this._lastPLICountUpdate=void 0,!o(e)||c(e)){var l=n.TypeNotValidError("rtcUser","Object");throw this._consoleLogger.error(s+d(l)),l}if(this._rtcUser=e,this._metrics=new i(t),t&&a(t.statsInterval)){if(t.statsInterval<1||t.statsInterval>10){l=n.ValueNotValidError("config.statsInterval","1...10");throw this._consoleLogger.error(s+d(l)),l}this._statsInterval=t.statsInterval}this._rtcUser._statsEnabled||this._rtcUser.enableStats(!0,1e3*this._statsInterval)}var u=l.prototype;return u.onEvent=function(e){this._consoleLogger.verbose("onEvent("+d(e)+")");var t=this;return Promise.resolve().then((function(){switch(e.name){case"SignInSuccess":return t._rtcUser._session.status().then((function(r){t._metrics.session.serverUrl=t._rtcUser._session._serverUrl,t._metrics.session.sessionId=t._rtcUser._session._sessionId;var i=r&&r.data?r.data.hostname:"";return t._metrics.session.hostName=i,t._getPayload(e)}));case"SignOutSuccess":t._metrics.cleanUpSession();break;case"StartPreviewSuccess":return t._rtcUser._deviceController.getDevice("videoinput").then((function(e){return t._metrics.devices.videoinput=e,t._rtcUser._deviceController.getDevice("audioinput")})).then((function(r){return t._metrics.devices.audioinput=r,t._getPayload(e)}));case"StopPreviewSuccess":t._metrics.cleanUpDevices();break;case"StartBroadcastSuccess":var r=e&&e.data?e.data.output:"",i=e&&e.data?e.data.streamname:"";t._metrics.rtmp.url=r,t._metrics.rtmp.streamname=i,t._broadcastStartingTime=(new Date).getTime();break;case"StopBroadcastSuccess":if(void 0!==t._broadcastStartingTime){var n=(new Date).getTime()-t._broadcastStartingTime;t._metrics.broadcast.totalTime=n/1e3}t._metrics.broadcast.status="stopped",t._metrics.cleanUpStats();break;case"BroadcastStatus":var o=e&&e.data?e.data.message:"";if(t._metrics.broadcast.status=o,"signaling"===o)t._broadcastSignallingTime=(new Date).getTime();else if("broadcasting"===o&&void 0!==t._broadcastSignallingTime){var s=(new Date).getTime()-t._broadcastSignallingTime;t._metrics.broadcast.startupTime=s/1e3}break;case"ReceivedWebRTCStats":e.name="ReceivedWebRtcStats";var a=(new Date).getTime(),c=t._lastStatsUpdate;if(void 0!==c)if((a-c)/1e3<t._statsInterval&&e.data&&e.data.results&&e.data.results.extended&&1!==e.data.results.extended.priority)return;if(t._lastStatsUpdate=a,e&&e.data&&e.data.results){var d=e.data.results,l={};for(var u in d)d.hasOwnProperty(u)&&"extended"!==u&&(l[u]=d[u]);if(d.extended){var p=d.extended;for(var u in p)p.hasOwnProperty(u)&&(l[u]=p[u]);var h=t._metrics.devices;h.videoinput&&h.videoinput.videoDeviceConfig&&(l.contentType=""+h.videoinput.videoDeviceConfig.source);a=(new Date).getTime();var m=e.data.results.extended.pliCount,g=t._lastPLICount,v=t._lastPLICountUpdate;if(void 0!==g&&void 0!==v){var f=m-g;if(f>0){var _=(a-v)/1e3/f;l.pliFrequency=_,t._lastPLICount=m,t._lastPLICountUpdate=a}else t._consoleLogger.verbose("Connection issue: PLI is not increasing")}else t._lastPLICount=m,t._lastPLICountUpdate=a}t._metrics.stats=l}if(void 0!==t._broadcastStartingTime){var S=a-t._broadcastStartingTime;t._metrics.broadcast.totalTime=S/1e3}break;default:if(e.name&&-1!==e.name.indexOf("Error")){var C={};C.code=e.error.code,C.message=e.error.message,t._metrics.error=C,t._metrics.broadcast.status="error"}}return t._getPayload(e)})).then((function(r){o(r)&&!c(r)&&t._grayLogger.send(e.name,r)})).then((function(){("StopBroadcastSuccess"===e.name||e.name&&-1!==e.name.indexOf("Error"))&&(t._metrics.cleanUpRtmp(),t._metrics.cleanUpBroadcast(),t._metrics.cleanUpStats()),t._metrics.cleanUpError()})).catch((function(r){"NanoError"!==r.type&&(r=n.GeneralError("Failed to handle an event: "+e.name)),t._consoleLogger.error("onEvent(): "+d(r)),t._metrics.cleanUpRtmp(),t._metrics.cleanUpBroadcast(),t._metrics.cleanUpStats(),t._metrics.cleanUpError()}))},u._getPayload=function(i){var n=e.browserInfo,o=r._graylog.credentials,a=this._metrics;return Promise.resolve().then((function(){var e={application_name:"webrtc-client",application_event_id:a.eventId,application_account_id:o.accountId,application_account_key:o.accountKey,message:i.name.replace(/\b\w/g,(function(e){return e.toLowerCase()})).replace(/([A-Z])/g,"_$1").toUpperCase(),origin:document.location.origin,path_name:document.location.pathname,referrer:document.location.href,search:document.location.search,os:n.os,os_version:n.osVersion,browser:n.browser,browser_version:n.browserVersion,webrtc_client_version:t.webrtc.release_version,server_url:a.session.serverUrl,server_hostname:a.session.hostName,session_id:a.session.sessionId,rtmp_url:a.rtmp.url,rtmp_streamname:a.rtmp.streamname,broadcast_status:a.broadcast.status,broadcast_startup_time:a.broadcast.startupTime,broadcast_total_time:a.broadcast.totalTime,bintu_orga_hash:-1!==a.rtmp.url.indexOf("bintu")?a.rtmp.streamname.split("-")[0]:"",video_device:a.devices.videoinput.label||(s(a.devices.videoinput)?a.devices.videoinput+"":a.devices.videoinput.label),audio_device:a.devices.audioinput.label||(s(a.devices.audioinput)?a.devices.audioinput+"":a.devices.audioinput.label),stats_content_type:a.stats.contentType,stats_audio_codec:a.stats.audioCodec,stats_audio_bitrate:a.stats.audioBitrate,stats_video_codec:a.stats.videoCodec,stats_frame_height:a.stats.frameHeight,stats_frame_width:a.stats.frameWidth,stats_framerate:a.stats.framerate,stats_video_bitrate:a.stats.videoBitrate,stats_nack_count:a.stats.nackCount,stats_frames_encoded:a.stats.framesEncoded,stats_key_frames_encoded:a.stats.keyFramesEncoded,stats_total_encode_time:a.stats.totalEncodeTime,stats_average_encode_time:a.stats.averageEncodeTime,stats_encode_time_percentage:a.stats.encodeTimePercentage,stats_idle_time_percentage:a.stats.idleTimePercentage,stats_fir_count:a.stats.firCount,stats_pli_count:a.stats.pliCount,stats_pli_frequency:a.stats.pliFrequency,stats_resolution_changed:a.stats.resolutionChanged,error_code:a.error.code,error_message:a.error.message};for(var r in a.customFields)a.customFields.hasOwnProperty(r)&&(e[r]=""+a.customFields[r]);return Promise.resolve(e)})).catch((function(e){return Promise.reject(e)}))},l}.apply(t,i))||(e.exports=n)},function(e,t,r){var i,n;i=[r(0),r(1),r(2)],void 0===(n=function(e,t,r){"use strict";var i=e.isObject,n=e.isEmpty,o=e.stringifyJSON;return function(e){if(this.logger=t.create("Metrics","console"),this.logger.verbose("Metrics("+o(e)+")"),this.eventId="",this.customFields={},this.session={},this.devices={videoinput:{},audioinput:{}},this.rtmp={url:"",streamname:""},this.broadcast={status:"",startupTime:void 0,totalTime:void 0},this.stats={},this.error={},i(e)&&!n(e))for(var s in this.eventId=""+e.eventId,e)if(0===s.indexOf("customField")){var a=s.split("customField");if(!(a.length>1&&0===a[0].length)){d=r.GeneralError("Custom field property is invalid");throw this.logger.error(o(d)),d}var c=parseInt(a[1]);if(isNaN(c)||c.toString()!=a[1]){var d=r.GeneralError("Invalid or incorrect custom field index");throw this.logger.error(o(d)),d}if(c<1||c>10){var d=r.GeneralError("Custom field index exceeds the range 1 to 10");throw this.logger.error(o(d)),d}this.customFields["application_custom_field_"+a[1]]=e[s]}this.cleanUpSession=function(){this.session={}},this.cleanUpDevices=function(){this.devices={videoinput:{},audioinput:{}}},this.cleanUpRtmp=function(){this.rtmp={url:"",streamname:""}},this.cleanUpBroadcast=function(){this.broadcast={status:"",startupTime:void 0,totalTime:void 0}},this.cleanUpStats=function(){this.stats={}},this.cleanUpError=function(){this.error={}}}}.apply(t,i))||(e.exports=n)},function(e,t,r){var i,n;i=[r(3),r(0),r(1)],void 0===(n=function(e,t,r){"use strict";var i=Math.max,n=Math.sqrt,o=t.stringifyJSON,s=t.isObject,a=t.isFunction;function c(){e.call(this),this._logger=r.create("AudioProcess","console"),this._logger.verbose("AudioProcess()");this._bufferSize=1024,this._numInputChannels=2,this._numOutputChannels=2,this._channels=[],this._microphone=null,this._scriptProcessorNode=null,this.active=!1;var t=window.AudioContext||window.webkitAudioContext;a(t)?this._audioContext=new t:(this._logger.error("AudioProcess(): No browser audio context found"),this._audioContext=null)}var d=c.prototype=Object.create(e.prototype);function l(e,t){this._logger=r.create("AudioChannel","console"),this._logger.verbose("AudioChannel("+o(e)+", "+t+")");e=e||{},s(t)||this._logger.error("AudioChannel(): Param audioProcess must be of type object",2),this._audioProcess=t,this._level=0,this._maxLevel=0,this._oldLevel=0,this._id=e.id,this._name=e.name,this._channelData=void 0}return d.connect=function(e,t){var r,i;for(this._logger.verbose("connect("+o(e)+", "+o(t)+")"),t=t||{bufferSize:1024,numInputChannels:2,numOutputChannels:2,channels:[{name:"left",id:0},{name:"right",id:1}]},this._bufferSize=t.bufferSize||1024,this._numInputChannels=t.numInputChannels||2,this._numOutputChannels=t.numOutputChannels||2,this._channels=[],r=0,i=t.channels.length;r<i;r++)this._channels.push(new l(t.channels[r],this));if(e){var n=e.getAudioTracks();if(n&&n.length>0){var s=this._scriptProcessorNode=this._audioContext.createScriptProcessor(this._bufferSize,this._numInputChannels,this._numOutputChannels);this._microphone=this._audioContext.createMediaStreamSource(e),this._microphone.connect(s),s.connect(this._audioContext.destination),s.onaudioprocess=this._onAudioProcess.bind(this),this.active=!0}else this.emitSimple("AudioNoTrack",{stream:e})}else this.emitSimple("AudioNoStream",{stream:e})},d.reset=function(){this._logger.verbose("reset()"),this.active=!1,this._microphone=null,this._scriptProcessorNode=null},d._onAudioProcess=function(e){if(this.active){var t,r,i=e.inputBuffer,n=this._channels,o=this;setTimeout((function(){var e=[];for(t=0,r=n.length;t<r;t++)n[t].update(i.getChannelData(t)),e.push(n[t].getChannelData());o.emitSimple("AudioProcess",{channels:e})}),0)}},l.prototype.update=function(e){this._channelData=e;var t,r=0,o=e.length;for(t=0;t<o;t++)r+=e[t]*e[t];this._level=n(r/(o||1)),this._maxLevel=i(this._level,this._maxLevel),this._oldLevel=i(this._level,this._oldLevel-.008)},l.prototype.getChannelData=function(){return{maxLevel:this._maxLevel,oldLevel:this._oldLevel,avgLevel:this._level,name:this._name,id:this._id}},c}.apply(t,i))||(e.exports=n)}]);