@flashphoner/websdk 2.0.274 → 2.0.276
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/docTemplate/README.md +1 -1
- package/flashphoner-no-flash.js +19697 -11620
- package/flashphoner-no-flash.min.js +3 -3
- package/flashphoner-no-webrtc.js +19666 -11593
- package/flashphoner-no-webrtc.min.js +3 -3
- package/flashphoner-no-wsplayer.js +18916 -10839
- package/flashphoner-no-wsplayer.min.js +3 -3
- package/flashphoner-room-api-webrtc-only.js +16370 -8293
- package/flashphoner-room-api-webrtc-only.min.js +2 -2
- package/flashphoner-room-api.js +9725 -1763
- package/flashphoner-room-api.min.js +4 -4
- package/flashphoner-temasys-flash-websocket-without-adapterjs.js +20669 -12596
- package/flashphoner-temasys-flash-websocket.js +20666 -12593
- package/flashphoner-temasys-flash-websocket.min.js +3 -3
- package/flashphoner-webrtc-only.js +18941 -10864
- package/flashphoner-webrtc-only.min.js +2 -2
- package/flashphoner.js +19697 -11620
- package/flashphoner.min.js +3 -3
- package/package.json +2 -1
- package/src/flashphoner-core.js +63 -39
- package/src/stats-collector.js +0 -528
- package/src/util.js +0 -47
- package/src/webrtc-media-provider.js +5 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
!function(f){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=f();else if("function"==typeof define&&define.amd)define([],f);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Flashphoner=f()}}((function(){return function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,(function(r){return o(e[i][1][r]||r)}),p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}({1:[function(require,module,exports){},{}],2:[function(require,module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}
|
|
1
|
+
!function(f){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=f();else if("function"==typeof define&&define.amd)define([],f);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Flashphoner=f()}}((function(){return function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,(function(r){return o(e[i][1][r]||r)}),p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}({1:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.RTCMetricsWebsocketSender=exports.RTCMetricsHttpSender=exports.RTCMetricsMessageType=exports.RTCMetricsCollectorBuilder=exports.InactiveInboundTrackRTCStatsReportFilter=exports.InactiveOutboundTrackRTCStatsReportFilter=exports.RTCMetricsCollectType=exports.RTCMetricsCollector=void 0;var collector_1=require("./sdk/collector");Object.defineProperty(exports,"RTCMetricsCollector",{enumerable:!0,get:function(){return collector_1.RTCMetricsCollector}});var constants_1=require("./sdk/constants");Object.defineProperty(exports,"RTCMetricsCollectType",{enumerable:!0,get:function(){return constants_1.RTCMetricsCollectType}});var filter_1=require("./sdk/filter");Object.defineProperty(exports,"InactiveInboundTrackRTCStatsReportFilter",{enumerable:!0,get:function(){return filter_1.InactiveInboundTrackRTCStatsReportFilter}}),Object.defineProperty(exports,"InactiveOutboundTrackRTCStatsReportFilter",{enumerable:!0,get:function(){return filter_1.InactiveOutboundTrackRTCStatsReportFilter}});var builder_1=require("./sdk/builder");Object.defineProperty(exports,"RTCMetricsCollectorBuilder",{enumerable:!0,get:function(){return builder_1.RTCMetricsCollectorBuilder}});var sender_1=require("./sdk/sender");Object.defineProperty(exports,"RTCMetricsHttpSender",{enumerable:!0,get:function(){return sender_1.RTCMetricsHttpSender}}),Object.defineProperty(exports,"RTCMetricsWebsocketSender",{enumerable:!0,get:function(){return sender_1.RTCMetricsWebsocketSender}});var message_1=require("./sdk/message");Object.defineProperty(exports,"RTCMetricsMessageType",{enumerable:!0,get:function(){return message_1.RTCMetricsMessageType}})},{"./sdk/builder":3,"./sdk/collector":4,"./sdk/constants":6,"./sdk/filter":7,"./sdk/message":9,"./sdk/sender":10}],2:[function(require,module,exports){"use strict";function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}function _toConsumableArray(r){return function(r){if(Array.isArray(r))return _arrayLikeToArray(r)}(r)||function(r){if("undefined"!=typeof Symbol&&null!=r[Symbol.iterator]||null!=r["@@iterator"])return Array.from(r)}(r)||function(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}(r)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}function _defineProperties(e,r){for(var t=0;t<r.length;t++){var o=r[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,_toPropertyKey(o.key),o)}}function _toPropertyKey(t){var i=function(t,r){if("object"!=_typeof(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||"default");if("object"!=_typeof(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}(t,"string");return"symbol"==_typeof(i)?i:i+""}Object.defineProperty(exports,"__esModule",{value:!0}),exports.RTCMetricsBatch=void 0;var constants_1=require("./constants"),RTCMetricsBatch=function(){return e=function RTCMetricsBatch(size){!function(a,n){if(!(a instanceof n))throw new TypeError("Cannot call a class as a function")}(this,RTCMetricsBatch),this._size=size,this._data=[]},(r=[{key:"addMetrics",value:function(metrics){this._data.push(metrics)}},{key:"fulfilled",value:function(){return this._data.length>=this._size}},{key:"empty",value:function(){return 0===this._data.length}},{key:"release",value:function(){var metrics=this._data;return this._data=[],metrics}},{key:"flat",value:function(){return this._data.map((function(line){return line.join(constants_1.RTCMetricsDelimiter.VALUES)}))}},{key:"size",get:function(){return this._size}},{key:"data",get:function(){return this._data}},{key:"deduplicate",value:function(){if(!(this._size<=1))for(var previousLine=this._data[0],row=1;row<this._data.length;++row){for(var currentLine=_toConsumableArray(this._data[row]),col=0;col<this._data[row].length;col++)this._data[row][col]==previousLine[col]&&(this._data[row][col]="");previousLine=currentLine}}}])&&_defineProperties(e.prototype,r),t&&_defineProperties(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,r,t}();exports.RTCMetricsBatch=RTCMetricsBatch},{"./constants":6}],3:[function(require,module,exports){"use strict";function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}function _defineProperties(e,r){for(var t=0;t<r.length;t++){var o=r[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,_toPropertyKey(o.key),o)}}function _toPropertyKey(t){var i=function(t,r){if("object"!=_typeof(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||"default");if("object"!=_typeof(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}(t,"string");return"symbol"==_typeof(i)?i:i+""}Object.defineProperty(exports,"__esModule",{value:!0}),exports.RTCMetricsCollectorBuilder=void 0;var sender_1=require("./sender"),logger_1=require("./logger"),collector_1=require("./collector"),uuid_1=require("uuid"),RTCMetricsCollectorBuilder=function(){return e=function RTCMetricsCollectorBuilder(){!function(a,n){if(!(a instanceof n))throw new TypeError("Cannot call a class as a function")}(this,RTCMetricsCollectorBuilder),this._description=null,this._peerConnection=null,this._sender=null,this._websocketSender=null,this._httpSender=null,this._websocket=null,this._logger=null,this._id=null,this._maxErrors=null,this._filters=[]},(r=[{key:"description",value:function(_description){return this._description=_description,this}},{key:"peerConnection",value:function(_peerConnection){return this._peerConnection=_peerConnection,this}},{key:"websocketSender",value:function(sender){return this._websocketSender=sender,this}},{key:"httpSender",value:function(sender){return this._httpSender=sender,this}},{key:"websocket",value:function(_websocket){return this._websocket=_websocket,this}},{key:"logger",value:function(_logger){return this._logger=_logger,this}},{key:"id",value:function(_id){return this._id=_id,this}},{key:"maxErrors",value:function(_maxErrors){return this._maxErrors=_maxErrors,this}},{key:"addFilter",value:function(filter){return this._filters.push(filter),this}},{key:"build",value:function(){this._validateBeforeBuild(),this._initializeNullFields();var collector=new collector_1.RTCMetricsCollector(this._id,this._description,this._peerConnection,this._sender,this._logger,this._maxErrors);return this._filters.forEach((function(filter){return collector.addStatsReportFilter(filter)})),collector}},{key:"_validateBeforeBuild",value:function(){if(null==this._description)throw new Error("RTCMetricsServerDescription must be specified to build RTCMetricsCollector");if(null==this._peerConnection)throw new Error("RTCPeerConnection must be specified to build RTCMetricsCollector");if(null==this._description.ingestPoint&&null==this._websocket&&null==this._websocketSender)throw new Error("Server description specified WebSocket connection, but none of [websocket, websocketSender] fields was not determined due to building RTCMetricsCollector")}},{key:"_initializeNullFields",value:function(){if(null==this._description.ingestPoint)null!=this._websocketSender?this._sender=this._websocketSender:this._sender=new sender_1.RTCMetricsWebsocketSender(this._websocket);else if(null!=this._httpSender)this._sender=this._httpSender;else{var headers=null!=this._description.authorization?{Authorization:this._description.authorization}:null;this._sender=new sender_1.RTCMetricsHttpSender(this._description.ingestPoint,headers)}null==this._logger&&(this._logger=new logger_1.ConsoleLogger(logger_1.LogLevel.INFO)),null==this._id&&(this._id=(0,uuid_1.v4)()),null==this._maxErrors&&(this._maxErrors=3)}}])&&_defineProperties(e.prototype,r),t&&_defineProperties(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,r,t}();exports.RTCMetricsCollectorBuilder=RTCMetricsCollectorBuilder},{"./collector":4,"./logger":8,"./sender":10,uuid:41}],4:[function(require,module,exports){"use strict";function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}function _slicedToArray(r,e){return function(r){if(Array.isArray(r))return r}(r)||function(r,l){var t=null==r?null:"undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(null!=t){var e,n,i,u,a=[],f=!0,o=!1;try{if(i=(t=t.call(r)).next,0===l){if(Object(t)!==t)return;f=!1}else for(;!(f=(e=i.call(t)).done)&&(a.push(e.value),a.length!==l);f=!0);}catch(r){o=!0,n=r}finally{try{if(!f&&null!=t.return&&(u=t.return(),Object(u)!==u))return}finally{if(o)throw n}}return a}}(r,e)||function(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}(r,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}function _regenerator(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function i(r,n,o,i){var c=n&&n.prototype instanceof Generator?n:Generator,u=Object.create(c.prototype);return _regeneratorDefine2(u,"_invoke",function(r,n,o){var i,c,u,f=0,p=o||[],y=!1,G={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return i=t,c=0,u=e,G.n=r,a}};function d(r,n){for(c=r,u=n,t=0;!y&&f&&!o&&t<p.length;t++){var o,i=p[t],d=G.p,l=i[2];r>3?(o=l===n)&&(u=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&d<i[1])?(c=0,G.v=n,G.n=i[1]):d<l&&(o=r<3||i[0]>n||n>l)&&(i[4]=r,i[5]=n,G.n=l,c=0))}if(o||r>1)return a;throw y=!0,n}return function(o,p,l){if(f>1)throw TypeError("Generator is already running");for(y&&1===p&&d(p,l),c=p,u=l;(t=c<2?e:u)||!y;){i||(c?c<3?(c>1&&(G.n=-1),d(c,u)):G.n=u:G.v=u);try{if(f=2,i){if(c||(o="next"),t=i[o]){if(!(t=t.call(i,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);i=e}else if((t=(y=G.n<0)?u:r.call(n,G))!==a)break}catch(t){i=e,c=1,u=t}finally{f=1}}return{value:t,done:y}}}(r,o,i),!0),u}var a={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}t=Object.getPrototypeOf;var c=[][n]?t(t([][n]())):(_regeneratorDefine2(t={},n,(function(){return this})),t),u=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(c);function f(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,GeneratorFunctionPrototype):(e.__proto__=GeneratorFunctionPrototype,_regeneratorDefine2(e,o,"GeneratorFunction")),e.prototype=Object.create(u),e}return GeneratorFunction.prototype=GeneratorFunctionPrototype,_regeneratorDefine2(u,"constructor",GeneratorFunctionPrototype),_regeneratorDefine2(GeneratorFunctionPrototype,"constructor",GeneratorFunction),GeneratorFunction.displayName="GeneratorFunction",_regeneratorDefine2(GeneratorFunctionPrototype,o,"GeneratorFunction"),_regeneratorDefine2(u),_regeneratorDefine2(u,o,"Generator"),_regeneratorDefine2(u,n,(function(){return this})),_regeneratorDefine2(u,"toString",(function(){return"[object Generator]"})),(_regenerator=function(){return{w:i,m:f}})()}function _regeneratorDefine2(e,r,n,t){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}(_regeneratorDefine2=function(e,r,n,t){function o(r,n){_regeneratorDefine2(e,r,(function(e){return this._invoke(r,n,e)}))}r?i?i(e,r,{value:n,enumerable:!t,configurable:!t,writable:!t}):e[r]=n:(o("next",0),o("throw",1),o("return",2))})(e,r,n,t)}function _defineProperties(e,r){for(var t=0;t<r.length;t++){var o=r[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,_toPropertyKey(o.key),o)}}function _toPropertyKey(t){var i=function(t,r){if("object"!=_typeof(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||"default");if("object"!=_typeof(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}(t,"string");return"symbol"==_typeof(i)?i:i+""}var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){var value;result.done?resolve(result.value):(value=result.value,value instanceof P?value:new P((function(resolve){resolve(value)}))).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0}),exports.RTCMetricsCollector=void 0;var batch_1=require("./batch"),compressor_1=require("./compressor"),async_mutex_1=require("async-mutex"),constants_1=require("./constants"),RTCMetricsCollector=function(){return e=function RTCMetricsCollector(id,webRTCMetricsServerDescription,peerConnection,sender,logger,maxErrors){!function(a,n){if(!(a instanceof n))throw new TypeError("Cannot call a class as a function")}(this,RTCMetricsCollector),this._metricsScheduler=null,this._logger=logger,this._mediaSessionId=id,this._metricsSender=sender,this._peerConnection=peerConnection,this._description=webRTCMetricsServerDescription,this._headers="",this._errorsCount=0,this._reportFilters=[],this._mutex=new async_mutex_1.Mutex,this._maxErrors=maxErrors,this._description.compression&&this._description.compression.includes(constants_1.RTCMetricsCompressionType.gzip)?this._compressor=new compressor_1.GzipRTCMetricsCompressor:this._compressor=new compressor_1.NoneRTCMetricsCompressor,this._batch=new batch_1.RTCMetricsBatch(this._description.batchSize),this._collectMetrics=this._collectMetrics.bind(this)},(r=[{key:"start",value:function(){return __awaiter(this,void 0,void 0,_regenerator().m((function _callee(){var stats;return _regenerator().w((function(_context){for(;;)switch(_context.n){case 0:return this._logger.info(constants_1.LOG_PREFIX,"Startup collecting metrics"),this._validateBeforeStartup(),_context.n=1,this._peerConnection.getStats();case 1:return stats=_context.v,_context.n=2,this._extractHeaders(stats,this._description);case 2:return this._headers=_context.v,_context.n=3,this._sendHeaders();case 3:this._description.collect===constants_1.RTCMetricsCollectType.on&&this.collect(!0);case 4:return _context.a(2)}}),_callee,this)})))}},{key:"stop",value:function(){this._logger.info(constants_1.LOG_PREFIX,"Stopping collecting metrics"),this.collect(!1),this._resetFields()}},{key:"collect",value:function(enable){this._logger.info(constants_1.LOG_PREFIX,"Collecting state changed: ",enable?"enabled":"disabled"),enable?null==this._metricsScheduler&&(this._metricsScheduler=setInterval(this._collectMetrics,this._description.sampling)):null!=this._metricsScheduler&&(clearInterval(this._metricsScheduler),this._metricsScheduler=null)}},{key:"addStatsReportFilter",value:function(filter){this._reportFilters.push(filter)}},{key:"sender",get:function(){return this._metricsSender}},{key:"id",get:function(){return this._mediaSessionId}},{key:"peerConnection",get:function(){return this._peerConnection}},{key:"_validateBeforeStartup",value:function(){var error="Can't collect WebRTC stats to send: ";if(!this._description.types)throw new Error(error+"no report types defined");if(!this._description.sampling)throw new Error(error+"no sampling interval defined");if(!this._description.batchSize)throw new Error(error+"no metrics batch size defined");if(!this._peerConnection)throw new Error(error+"no RTCPeerConnection available")}},{key:"_extractHeaders",value:function(stats,description){return __awaiter(this,void 0,void 0,_regenerator().m((function _callee2(){var _this=this;return _regenerator().w((function(_context2){for(;;)switch(_context2.n){case 0:return _context2.a(2,Object.entries(description.types).reduce((function(accumulator,_ref){var _ref2=_slicedToArray(_ref,2),typename=_ref2[0],descriptor=_ref2[1];return stats.forEach((function(report){_this._mismatchTypename(report,typename)||_this._mismatchContains(report,descriptor.contains)||_this._mismatchFilters(report)||(accumulator=descriptor.metrics.split(constants_1.RTCMetricsDelimiter.HEADERS).reduce((function(acc,metricName){return _this._isNullOrUndefined(report[metricName])?acc:acc+(acc.length?constants_1.RTCMetricsDelimiter.HEADERS:"")+"".concat(report.type,".").concat(report.id,".").concat(metricName)}),accumulator))})),accumulator}),""))}}),_callee2)})))}},{key:"_collectMetrics",value:function(){return __awaiter(this,void 0,void 0,_regenerator().m((function _callee3(){var unlock,stats,headers,metrics,lostMetrics,_this2=this;return _regenerator().w((function(_context3){for(;;)switch(_context3.p=_context3.n){case 0:return _context3.n=1,this._mutex.acquire();case 1:return unlock=_context3.v,_context3.p=2,_context3.n=3,this._peerConnection.getStats();case 3:return stats=_context3.v,_context3.n=4,this._extractHeaders(stats,this._description);case 4:if(headers=_context3.v,this._headers==headers){_context3.n=6;break}return this._headers=headers,_context3.n=5,this._sendMetricsAndFlushBatch();case 5:return _context3.n=6,this._sendHeaders();case 6:if(this._headers.length){_context3.n=7;break}return _context3.a(2);case 7:if(metrics=[],lostMetrics=[],this._headers.split(constants_1.RTCMetricsDelimiter.HEADERS).forEach((function(header){var components=header.split(".");if(3==components.length){var descriptor={type:components[0],id:components[1],name:components[2]},value=void 0;stats.forEach((function(report){report.id==descriptor.id&&(value=report[descriptor.name])})),_this2._isNullOrUndefined(value)?lostMetrics.push(descriptor):metrics.push(_this2._stringifyValue(value))}})),!lostMetrics.length){_context3.n=9;break}return this._logger.error(constants_1.LOG_PREFIX,"Failed to fully collect the stated metrics. Send correctly accumulated metrics ahead of time"),_context3.n=8,this._sendMetricsAndFlushBatch();case 8:_context3.n=10;break;case 9:if(this._batch.addMetrics(metrics),!this._batch.fulfilled()){_context3.n=10;break}return _context3.n=10,this._sendMetricsAndFlushBatch();case 10:return _context3.p=10,unlock(),_context3.f(10);case 11:this._errorsCount>this._maxErrors&&this.stop();case 12:return _context3.a(2)}}),_callee3,this,[[2,,10,11]])})))}},{key:"_sendHeaders",value:function(){return __awaiter(this,void 0,void 0,_regenerator().m((function _callee4(){return _regenerator().w((function(_context4){for(;;)switch(_context4.n){case 0:return this._logger.info(constants_1.LOG_PREFIX,"Send headers:",this._headers),_context4.n=1,this._metricsSender.sendDescription({headers:this._headers,compression:this._compressor.type.toString(),mediaSessionId:this._mediaSessionId});case 1:return _context4.a(2)}}),_callee4,this)})))}},{key:"_sendMetricsAndFlushBatch",value:function(){return __awaiter(this,void 0,void 0,_regenerator().m((function _callee5(){var status;return _regenerator().w((function(_context5){for(;;)switch(_context5.n){case 0:if(!this._batch.empty()){_context5.n=1;break}return _context5.a(2);case 1:return this._batch.deduplicate(),_context5.n=2,this._metricsSender.sendBatch({mediaSessionId:this._mediaSessionId,metrics:this._compressor.compress(this._batch)});case 2:(status=_context5.v)==constants_1.CONNECTION_STATUS.OK?(this._logger.debug(constants_1.LOG_PREFIX,"Successfully sent metrics batch"),this._errorsCount=0):(this._logger.error(constants_1.LOG_PREFIX,"Failed to send metrics batch with status:",status),this._errorsCount++),this._batch.release();case 3:return _context5.a(2)}}),_callee5,this)})))}},{key:"_stringifyValue",value:function(value){return"object"===_typeof(value)?JSON.stringify(value):value.toString()}},{key:"_mismatchTypename",value:function(report,typename){return report.type!==typename}},{key:"_mismatchContains",value:function(report,contains){return contains&&Object.entries(contains).some((function(_ref3){var _ref4=_slicedToArray(_ref3,2),field=_ref4[0],desiredValues=_ref4[1];return!report[field]||!desiredValues.includes(report[field])}))}},{key:"_mismatchFilters",value:function(report){return this._reportFilters.some((function(filter){return!filter.allowed(report)}))}},{key:"_isNullOrUndefined",value:function(value){return null==value}},{key:"_resetFields",value:function(){this._headers="",this._batch.release(),this._errorsCount=0}}])&&_defineProperties(e.prototype,r),t&&_defineProperties(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,r,t}();exports.RTCMetricsCollector=RTCMetricsCollector},{"./batch":2,"./compressor":5,"./constants":6,"async-mutex":14}],5:[function(require,module,exports){"use strict";function _toConsumableArray(r){return function(r){if(Array.isArray(r))return _arrayLikeToArray(r)}(r)||function(r){if("undefined"!=typeof Symbol&&null!=r[Symbol.iterator]||null!=r["@@iterator"])return Array.from(r)}(r)||function(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}(r)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}function _classCallCheck(a,n){if(!(a instanceof n))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,r){for(var t=0;t<r.length;t++){var o=r[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,_toPropertyKey(o.key),o)}}function _createClass(e,r,t){return r&&_defineProperties(e.prototype,r),t&&_defineProperties(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function _toPropertyKey(t){var i=function(t,r){if("object"!=_typeof(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||"default");if("object"!=_typeof(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}(t,"string");return"symbol"==_typeof(i)?i:i+""}Object.defineProperty(exports,"__esModule",{value:!0}),exports.GzipRTCMetricsCompressor=exports.NoneRTCMetricsCompressor=void 0;var constants_1=require("./constants"),pako_1=require("pako"),NoneRTCMetricsCompressor=function(){return _createClass((function NoneRTCMetricsCompressor(){_classCallCheck(this,NoneRTCMetricsCompressor)}),[{key:"compress",value:function(batch){return JSON.stringify(batch.flat())}},{key:"type",get:function(){return constants_1.RTCMetricsCompressionType.none}}])}();exports.NoneRTCMetricsCompressor=NoneRTCMetricsCompressor;var GzipRTCMetricsCompressor=function(){return _createClass((function GzipRTCMetricsCompressor(){_classCallCheck(this,GzipRTCMetricsCompressor)}),[{key:"compress",value:function(batch){var utf8=JSON.stringify(batch.flat()),gzipped=(0,pako_1.gzip)(utf8);return btoa(String.fromCharCode.apply(String,_toConsumableArray(gzipped)))}},{key:"type",get:function(){return constants_1.RTCMetricsCompressionType.gzip}}])}();exports.GzipRTCMetricsCompressor=GzipRTCMetricsCompressor},{"./constants":6,pako:19}],6:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.RTCMetricsDelimiter=exports.RTCMetricsCompressionType=exports.RTCMetricsCollectType=exports.CONNECTION_STATUS=exports.MAX_SEND_ERRORS=exports.CONNECTION_TYPE=exports.LOG_PREFIX=void 0,exports.LOG_PREFIX="stats-collector -",exports.CONNECTION_TYPE={WEBSOCKET:"ws",HTTP:"http"},exports.MAX_SEND_ERRORS=3,exports.CONNECTION_STATUS={INIT:0,OK:200,BAD_REQUEST:400,INTERNAL_SERVER_ERROR:500},function(RTCMetricsCollectType){RTCMetricsCollectType.on="on",RTCMetricsCollectType.off="off"}(exports.RTCMetricsCollectType||(exports.RTCMetricsCollectType={})),function(RTCMetricsCompressionType){RTCMetricsCompressionType.gzip="gzip",RTCMetricsCompressionType.none="none",RTCMetricsCompressionType.deflate="deflate"}(exports.RTCMetricsCompressionType||(exports.RTCMetricsCompressionType={})),function(RTCMetricsDelimiter){RTCMetricsDelimiter.HEADERS=",",RTCMetricsDelimiter.VALUES=";"}(exports.RTCMetricsDelimiter||(exports.RTCMetricsDelimiter={}))},{}],7:[function(require,module,exports){"use strict";function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}function _classCallCheck(a,n){if(!(a instanceof n))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,r){for(var t=0;t<r.length;t++){var o=r[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,_toPropertyKey(o.key),o)}}function _createClass(e,r,t){return r&&_defineProperties(e.prototype,r),t&&_defineProperties(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function _toPropertyKey(t){var i=function(t,r){if("object"!=_typeof(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||"default");if("object"!=_typeof(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}(t,"string");return"symbol"==_typeof(i)?i:i+""}Object.defineProperty(exports,"__esModule",{value:!0}),exports.InactiveInboundTrackRTCStatsReportFilter=exports.InactiveOutboundTrackRTCStatsReportFilter=void 0;var InactiveOutboundTrackRTCStatsReportFilter=function(){return _createClass((function InactiveOutboundTrackRTCStatsReportFilter(){_classCallCheck(this,InactiveOutboundTrackRTCStatsReportFilter)}),[{key:"allowed",value:function(report){return"outbound-rtp"!==report.type||report.mediaSourceId&&""!==report.mediaSourceId&&"(removed)"!==report.mediaSourceId}}])}();exports.InactiveOutboundTrackRTCStatsReportFilter=InactiveOutboundTrackRTCStatsReportFilter;var InactiveInboundTrackRTCStatsReportFilter=function(){return _createClass((function InactiveInboundTrackRTCStatsReportFilter(){_classCallCheck(this,InactiveInboundTrackRTCStatsReportFilter)}),[{key:"allowed",value:function(report){return"inbound-rtp"!==report.type||report.framesPerSecond&&"(removed)"!==report.framesPerSecond}}])}();exports.InactiveInboundTrackRTCStatsReportFilter=InactiveInboundTrackRTCStatsReportFilter},{}],8:[function(require,module,exports){"use strict";function _toConsumableArray(r){return function(r){if(Array.isArray(r))return _arrayLikeToArray(r)}(r)||function(r){if("undefined"!=typeof Symbol&&null!=r[Symbol.iterator]||null!=r["@@iterator"])return Array.from(r)}(r)||function(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}(r)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}function _callSuper(t,o,e){return o=_getPrototypeOf(o),function(t,e){if(e&&("object"==_typeof(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(t)}(t,function(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(t){}return function(){return!!t}()}()?Reflect.construct(o,e||[],_getPrototypeOf(t).constructor):o.apply(t,e))}function _getPrototypeOf(t){return(_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function _setPrototypeOf(t,e){return(_setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t})(t,e)}function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}function _classCallCheck(a,n){if(!(a instanceof n))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,r){for(var t=0;t<r.length;t++){var o=r[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,_toPropertyKey(o.key),o)}}function _createClass(e,r,t){return r&&_defineProperties(e.prototype,r),t&&_defineProperties(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function _toPropertyKey(t){var i=function(t,r){if("object"!=_typeof(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||"default");if("object"!=_typeof(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}(t,"string");return"symbol"==_typeof(i)?i:i+""}var LogLevel;Object.defineProperty(exports,"__esModule",{value:!0}),exports.ConsoleLogger=exports.BaseLogger=exports.LogLevel=void 0,function(LogLevel){LogLevel[LogLevel.DEBUG=0]="DEBUG",LogLevel[LogLevel.INFO=1]="INFO",LogLevel[LogLevel.WARN=2]="WARN",LogLevel[LogLevel.ERROR=3]="ERROR",LogLevel[LogLevel.NONE=4]="NONE"}(LogLevel=exports.LogLevel||(exports.LogLevel={}));var BaseLogger=function(){return _createClass((function BaseLogger(level){_classCallCheck(this,BaseLogger),this.level=level}),[{key:"debug",value:function(message){if(this.level<=LogLevel.DEBUG){for(var _len=arguments.length,args=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++)args[_key-1]=arguments[_key];this.write("DEBUG",message,args)}}},{key:"info",value:function(message){if(this.level<=LogLevel.INFO){for(var _len2=arguments.length,args=new Array(_len2>1?_len2-1:0),_key2=1;_key2<_len2;_key2++)args[_key2-1]=arguments[_key2];this.write("INFO",message,args)}}},{key:"warn",value:function(message){if(this.level<=LogLevel.WARN){for(var _len3=arguments.length,args=new Array(_len3>1?_len3-1:0),_key3=1;_key3<_len3;_key3++)args[_key3-1]=arguments[_key3];this.write("WARN",message,args)}}},{key:"error",value:function(message){if(this.level<=LogLevel.ERROR){for(var _len4=arguments.length,args=new Array(_len4>1?_len4-1:0),_key4=1;_key4<_len4;_key4++)args[_key4-1]=arguments[_key4];this.write("ERROR",message,args)}}}])}();exports.BaseLogger=BaseLogger;var ConsoleLogger=function(_BaseLogger){function ConsoleLogger(level){return _classCallCheck(this,ConsoleLogger),_callSuper(this,ConsoleLogger,[level])}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&_setPrototypeOf(t,e)}(ConsoleLogger,_BaseLogger),_createClass(ConsoleLogger,[{key:"write",value:function(level,message,args){var _console,_console2,_console3,_console4,prefix="[".concat(level,"]");switch(level){case"ERROR":(_console=console).error.apply(_console,[prefix,message].concat(_toConsumableArray(args)));break;case"WARN":(_console2=console).warn.apply(_console2,[prefix,message].concat(_toConsumableArray(args)));break;case"INFO":(_console3=console).info.apply(_console3,[prefix,message].concat(_toConsumableArray(args)));break;default:(_console4=console).log.apply(_console4,[prefix,message].concat(_toConsumableArray(args)))}}}])}(BaseLogger);exports.ConsoleLogger=ConsoleLogger},{}],9:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.RTCMetricsMessageType=void 0,function(RTCMetricsMessageType){RTCMetricsMessageType.description="webRTCMetricsClientDescription",RTCMetricsMessageType.batch="webRTCMetricsBatch"}(exports.RTCMetricsMessageType||(exports.RTCMetricsMessageType={}))},{}],10:[function(require,module,exports){"use strict";function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}function _regenerator(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function i(r,n,o,i){var c=n&&n.prototype instanceof Generator?n:Generator,u=Object.create(c.prototype);return _regeneratorDefine2(u,"_invoke",function(r,n,o){var i,c,u,f=0,p=o||[],y=!1,G={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return i=t,c=0,u=e,G.n=r,a}};function d(r,n){for(c=r,u=n,t=0;!y&&f&&!o&&t<p.length;t++){var o,i=p[t],d=G.p,l=i[2];r>3?(o=l===n)&&(u=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&d<i[1])?(c=0,G.v=n,G.n=i[1]):d<l&&(o=r<3||i[0]>n||n>l)&&(i[4]=r,i[5]=n,G.n=l,c=0))}if(o||r>1)return a;throw y=!0,n}return function(o,p,l){if(f>1)throw TypeError("Generator is already running");for(y&&1===p&&d(p,l),c=p,u=l;(t=c<2?e:u)||!y;){i||(c?c<3?(c>1&&(G.n=-1),d(c,u)):G.n=u:G.v=u);try{if(f=2,i){if(c||(o="next"),t=i[o]){if(!(t=t.call(i,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);i=e}else if((t=(y=G.n<0)?u:r.call(n,G))!==a)break}catch(t){i=e,c=1,u=t}finally{f=1}}return{value:t,done:y}}}(r,o,i),!0),u}var a={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}t=Object.getPrototypeOf;var c=[][n]?t(t([][n]())):(_regeneratorDefine2(t={},n,(function(){return this})),t),u=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(c);function f(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,GeneratorFunctionPrototype):(e.__proto__=GeneratorFunctionPrototype,_regeneratorDefine2(e,o,"GeneratorFunction")),e.prototype=Object.create(u),e}return GeneratorFunction.prototype=GeneratorFunctionPrototype,_regeneratorDefine2(u,"constructor",GeneratorFunctionPrototype),_regeneratorDefine2(GeneratorFunctionPrototype,"constructor",GeneratorFunction),GeneratorFunction.displayName="GeneratorFunction",_regeneratorDefine2(GeneratorFunctionPrototype,o,"GeneratorFunction"),_regeneratorDefine2(u),_regeneratorDefine2(u,o,"Generator"),_regeneratorDefine2(u,n,(function(){return this})),_regeneratorDefine2(u,"toString",(function(){return"[object Generator]"})),(_regenerator=function(){return{w:i,m:f}})()}function _regeneratorDefine2(e,r,n,t){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}(_regeneratorDefine2=function(e,r,n,t){function o(r,n){_regeneratorDefine2(e,r,(function(e){return this._invoke(r,n,e)}))}r?i?i(e,r,{value:n,enumerable:!t,configurable:!t,writable:!t}):e[r]=n:(o("next",0),o("throw",1),o("return",2))})(e,r,n,t)}function _classCallCheck(a,n){if(!(a instanceof n))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,r){for(var t=0;t<r.length;t++){var o=r[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,_toPropertyKey(o.key),o)}}function _createClass(e,r,t){return r&&_defineProperties(e.prototype,r),t&&_defineProperties(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function _toPropertyKey(t){var i=function(t,r){if("object"!=_typeof(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||"default");if("object"!=_typeof(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}(t,"string");return"symbol"==_typeof(i)?i:i+""}var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){var value;result.done?resolve(result.value):(value=result.value,value instanceof P?value:new P((function(resolve){resolve(value)}))).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0}),exports.RTCMetricsHttpSender=exports.RTCMetricsWebsocketSender=void 0;var message_1=require("./message"),constants_1=require("./constants"),RTCMetricsWebsocketSender=function(){return _createClass((function RTCMetricsWebsocketSender(websocket){_classCallCheck(this,RTCMetricsWebsocketSender),this.websocket=websocket}),[{key:"sendDescription",value:function(message){return __awaiter(this,void 0,void 0,_regenerator().m((function _callee(){return _regenerator().w((function(_context){for(;;)switch(_context.n){case 0:return _context.a(2,this._send(message_1.RTCMetricsMessageType.description,message))}}),_callee,this)})))}},{key:"sendBatch",value:function(message){return __awaiter(this,void 0,void 0,_regenerator().m((function _callee2(){return _regenerator().w((function(_context2){for(;;)switch(_context2.n){case 0:return _context2.a(2,this._send(message_1.RTCMetricsMessageType.batch,message))}}),_callee2,this)})))}},{key:"_send",value:function(messageType,message){return this.websocket?(this.websocket.send(JSON.stringify({message:messageType,data:[message]})),constants_1.CONNECTION_STATUS.OK):constants_1.CONNECTION_STATUS.BAD_REQUEST}}])}();exports.RTCMetricsWebsocketSender=RTCMetricsWebsocketSender;var RTCMetricsHttpSender=function(){return _createClass((function RTCMetricsHttpSender(url,headers){_classCallCheck(this,RTCMetricsHttpSender),this._url=url,this._headers=headers}),[{key:"sendDescription",value:function(message){return __awaiter(this,void 0,void 0,_regenerator().m((function _callee3(){return _regenerator().w((function(_context3){for(;;)switch(_context3.n){case 0:return _context3.a(2,this._send(message_1.RTCMetricsMessageType.description,message))}}),_callee3,this)})))}},{key:"sendBatch",value:function(message){return __awaiter(this,void 0,void 0,_regenerator().m((function _callee4(){return _regenerator().w((function(_context4){for(;;)switch(_context4.n){case 0:return _context4.a(2,this._send(message_1.RTCMetricsMessageType.batch,message))}}),_callee4,this)})))}},{key:"headers",set:function(headers){this._headers=headers}},{key:"_send",value:function(pathname,message){return __awaiter(this,void 0,void 0,_regenerator().m((function _callee5(){var headers;return _regenerator().w((function(_context5){for(;;)switch(_context5.p=_context5.n){case 0:if(this._url){_context5.n=1;break}return _context5.a(2,constants_1.CONNECTION_STATUS.BAD_REQUEST);case 1:return _context5.p=1,headers=new Headers(Object.assign({"Content-Type":"application/json"},this._headers)),_context5.n=2,fetch("".concat(this._url,"/").concat(pathname),{method:"POST",mode:"cors",headers:headers,body:JSON.stringify(message)});case 2:return _context5.a(2,constants_1.CONNECTION_STATUS.OK);case 3:return _context5.p=3,_context5.v,_context5.a(2,constants_1.CONNECTION_STATUS.INTERNAL_SERVER_ERROR)}}),_callee5,this,[[1,3]])})))}}])}();exports.RTCMetricsHttpSender=RTCMetricsHttpSender},{"./constants":6,"./message":9}],11:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var tslib_1=require("tslib"),Semaphore_1=require("./Semaphore"),Mutex=function(){function Mutex(cancelError){this._semaphore=new Semaphore_1.default(1,cancelError)}return Mutex.prototype.acquire=function(){return tslib_1.__awaiter(this,void 0,void 0,(function(){var _a;return tslib_1.__generator(this,(function(_b){switch(_b.label){case 0:return[4,this._semaphore.acquire()];case 1:return _a=_b.sent(),[2,_a[1]]}}))}))},Mutex.prototype.runExclusive=function(callback){return this._semaphore.runExclusive((function(){return callback()}))},Mutex.prototype.isLocked=function(){return this._semaphore.isLocked()},Mutex.prototype.waitForUnlock=function(){return this._semaphore.waitForUnlock()},Mutex.prototype.release=function(){this._semaphore.isLocked()&&this._semaphore.release()},Mutex.prototype.cancel=function(){return this._semaphore.cancel()},Mutex}();exports.default=Mutex},{"./Semaphore":12,tslib:40}],12:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var tslib_1=require("tslib"),errors_1=require("./errors"),Semaphore=function(){function Semaphore(_value,_cancelError){void 0===_cancelError&&(_cancelError=errors_1.E_CANCELED),this._value=_value,this._cancelError=_cancelError,this._weightedQueues=[],this._weightedWaiters=[]}return Semaphore.prototype.acquire=function(weight){var _this=this;if(void 0===weight&&(weight=1),weight<=0)throw new Error("invalid weight ".concat(weight,": must be positive"));return new Promise((function(resolve,reject){_this._weightedQueues[weight-1]||(_this._weightedQueues[weight-1]=[]),_this._weightedQueues[weight-1].push({resolve:resolve,reject:reject}),_this._dispatch()}))},Semaphore.prototype.runExclusive=function(callback,weight){return void 0===weight&&(weight=1),tslib_1.__awaiter(this,void 0,void 0,(function(){var _a,value,release;return tslib_1.__generator(this,(function(_b){switch(_b.label){case 0:return[4,this.acquire(weight)];case 1:_a=_b.sent(),value=_a[0],release=_a[1],_b.label=2;case 2:return _b.trys.push([2,,4,5]),[4,callback(value)];case 3:return[2,_b.sent()];case 4:return release(),[7];case 5:return[2]}}))}))},Semaphore.prototype.waitForUnlock=function(weight){var _this=this;if(void 0===weight&&(weight=1),weight<=0)throw new Error("invalid weight ".concat(weight,": must be positive"));return new Promise((function(resolve){_this._weightedWaiters[weight-1]||(_this._weightedWaiters[weight-1]=[]),_this._weightedWaiters[weight-1].push(resolve),_this._dispatch()}))},Semaphore.prototype.isLocked=function(){return this._value<=0},Semaphore.prototype.getValue=function(){return this._value},Semaphore.prototype.setValue=function(value){this._value=value,this._dispatch()},Semaphore.prototype.release=function(weight){if(void 0===weight&&(weight=1),weight<=0)throw new Error("invalid weight ".concat(weight,": must be positive"));this._value+=weight,this._dispatch()},Semaphore.prototype.cancel=function(){var _this=this;this._weightedQueues.forEach((function(queue){return queue.forEach((function(entry){return entry.reject(_this._cancelError)}))})),this._weightedQueues=[]},Semaphore.prototype._dispatch=function(){for(var _a,weight=this._value;weight>0;weight--){var queueEntry=null===(_a=this._weightedQueues[weight-1])||void 0===_a?void 0:_a.shift();if(queueEntry){var previousValue=this._value,previousWeight=weight;this._value-=weight,weight=this._value+1,queueEntry.resolve([previousValue,this._newReleaser(previousWeight)])}}this._drainUnlockWaiters()},Semaphore.prototype._newReleaser=function(weight){var _this=this,called=!1;return function(){called||(called=!0,_this.release(weight))}},Semaphore.prototype._drainUnlockWaiters=function(){for(var weight=this._value;weight>0;weight--)this._weightedWaiters[weight-1]&&(this._weightedWaiters[weight-1].forEach((function(waiter){return waiter()})),this._weightedWaiters[weight-1]=[])},Semaphore}();exports.default=Semaphore},{"./errors":13,tslib:40}],13:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.E_CANCELED=exports.E_ALREADY_LOCKED=exports.E_TIMEOUT=void 0,exports.E_TIMEOUT=new Error("timeout while waiting for mutex to become available"),exports.E_ALREADY_LOCKED=new Error("mutex already locked"),exports.E_CANCELED=new Error("request for lock canceled")},{}],14:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.tryAcquire=exports.withTimeout=exports.Semaphore=exports.Mutex=void 0;var tslib_1=require("tslib"),Mutex_1=require("./Mutex");Object.defineProperty(exports,"Mutex",{enumerable:!0,get:function(){return Mutex_1.default}});var Semaphore_1=require("./Semaphore");Object.defineProperty(exports,"Semaphore",{enumerable:!0,get:function(){return Semaphore_1.default}});var withTimeout_1=require("./withTimeout");Object.defineProperty(exports,"withTimeout",{enumerable:!0,get:function(){return withTimeout_1.withTimeout}});var tryAcquire_1=require("./tryAcquire");Object.defineProperty(exports,"tryAcquire",{enumerable:!0,get:function(){return tryAcquire_1.tryAcquire}}),tslib_1.__exportStar(require("./errors"),exports)},{"./Mutex":11,"./Semaphore":12,"./errors":13,"./tryAcquire":15,"./withTimeout":16,tslib:40}],15:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.tryAcquire=void 0;var errors_1=require("./errors"),withTimeout_1=require("./withTimeout");exports.tryAcquire=function(sync,alreadyAcquiredError){return void 0===alreadyAcquiredError&&(alreadyAcquiredError=errors_1.E_ALREADY_LOCKED),(0,withTimeout_1.withTimeout)(sync,0,alreadyAcquiredError)}},{"./errors":13,"./withTimeout":16}],16:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.withTimeout=void 0;var tslib_1=require("tslib"),errors_1=require("./errors");exports.withTimeout=function(sync,timeout,timeoutError){var _this=this;return void 0===timeoutError&&(timeoutError=errors_1.E_TIMEOUT),{acquire:function(weight){if(void 0!==weight&&weight<=0)throw new Error("invalid weight ".concat(weight,": must be positive"));return new Promise((function(resolve,reject){return tslib_1.__awaiter(_this,void 0,void 0,(function(){var isTimeout,handle,ticket,e_1;return tslib_1.__generator(this,(function(_a){switch(_a.label){case 0:isTimeout=!1,handle=setTimeout((function(){isTimeout=!0,reject(timeoutError)}),timeout),_a.label=1;case 1:return _a.trys.push([1,3,,4]),[4,sync.acquire(weight)];case 2:return ticket=_a.sent(),isTimeout?(Array.isArray(ticket)?ticket[1]:ticket)():(clearTimeout(handle),resolve(ticket)),[3,4];case 3:return e_1=_a.sent(),isTimeout||(clearTimeout(handle),reject(e_1)),[3,4];case 4:return[2]}}))}))}))},runExclusive:function(callback,weight){return tslib_1.__awaiter(this,void 0,void 0,(function(){var release,ticket;return tslib_1.__generator(this,(function(_a){switch(_a.label){case 0:release=function(){},_a.label=1;case 1:return _a.trys.push([1,,7,8]),[4,this.acquire(weight)];case 2:return ticket=_a.sent(),Array.isArray(ticket)?(release=ticket[1],[4,callback(ticket[0])]):[3,4];case 3:return[2,_a.sent()];case 4:return release=ticket,[4,callback()];case 5:return[2,_a.sent()];case 6:return[3,8];case 7:return release(),[7];case 8:return[2]}}))}))},release:function(weight){sync.release(weight)},cancel:function(){return sync.cancel()},waitForUnlock:function(weight){if(void 0!==weight&&weight<=0)throw new Error("invalid weight ".concat(weight,": must be positive"));return new Promise((function(resolve,reject){var handle=setTimeout((function(){return reject(timeoutError)}),timeout);sync.waitForUnlock(weight).then((function(){clearTimeout(handle),resolve()}))}))},isLocked:function(){return sync.isLocked()},getValue:function(){return sync.getValue()},setValue:function(value){return sync.setValue(value)}}}},{"./errors":13,tslib:40}],17:[function(require,module,exports){},{}],18:[function(require,module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}
|
|
2
2
|
/**
|
|
3
3
|
* KalmanFilter
|
|
4
4
|
* @class
|
|
@@ -9,4 +9,4 @@
|
|
|
9
9
|
* @license MIT License
|
|
10
10
|
* @preserve
|
|
11
11
|
*/
|
|
12
|
-
var KalmanFilter=function(){function KalmanFilter(){var _ref=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},_ref$R=_ref.R,R=void 0===_ref$R?1:_ref$R,_ref$Q=_ref.Q,Q=void 0===_ref$Q?1:_ref$Q,_ref$A=_ref.A,A=void 0===_ref$A?1:_ref$A,_ref$B=_ref.B,B=void 0===_ref$B?0:_ref$B,_ref$C=_ref.C,C=void 0===_ref$C?1:_ref$C;_classCallCheck(this,KalmanFilter),this.R=R,this.Q=Q,this.A=A,this.C=C,this.B=B,this.cov=NaN,this.x=NaN}var Constructor,protoProps,staticProps;return Constructor=KalmanFilter,(protoProps=[{key:"filter",value:function(z){var u=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(isNaN(this.x))this.x=1/this.C*z,this.cov=1/this.C*this.Q*(1/this.C);else{var predX=this.predict(u),predCov=this.uncertainty(),K=predCov*this.C*(1/(this.C*predCov*this.C+this.Q));this.x=predX+K*(z-this.C*predX),this.cov=predCov-K*this.C*predCov}return this.x}},{key:"predict",value:function(){var u=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return this.A*this.x+this.B*u}},{key:"uncertainty",value:function(){return this.A*this.cov*this.A+this.R}},{key:"lastMeasurement",value:function(){return this.x}},{key:"setMeasurementNoise",value:function(noise){this.Q=noise}},{key:"setProcessNoise",value:function(noise){this.R=noise}}])&&_defineProperties(Constructor.prototype,protoProps),staticProps&&_defineProperties(Constructor,staticProps),KalmanFilter}();module.exports=KalmanFilter},{}],3:[function(require,module,exports){var cachedSetTimeout,cachedClearTimeout,process=module.exports={};function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}function runTimeout(fun){if(cachedSetTimeout===setTimeout)return setTimeout(fun,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(fun,0);try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}!function(){try{cachedSetTimeout="function"==typeof setTimeout?setTimeout:defaultSetTimout}catch(e){cachedSetTimeout=defaultSetTimout}try{cachedClearTimeout="function"==typeof clearTimeout?clearTimeout:defaultClearTimeout}catch(e){cachedClearTimeout=defaultClearTimeout}}();var currentQueue,queue=[],draining=!1,queueIndex=-1;function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var timeout=runTimeout(cleanUpNextTick);draining=!0;for(var len=queue.length;len;){for(currentQueue=queue,queue=[];++queueIndex<len;)currentQueue&¤tQueue[queueIndex].run();queueIndex=-1,len=queue.length}currentQueue=null,draining=!1,function(marker){if(cachedClearTimeout===clearTimeout)return clearTimeout(marker);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(marker);try{cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}(timeout)}}function Item(fun,array){this.fun=fun,this.array=array}function noop(){}process.nextTick=function(fun){var args=new Array(arguments.length-1);if(arguments.length>1)for(var i=1;i<arguments.length;i++)args[i-1]=arguments[i];queue.push(new Item(fun,args)),1!==queue.length||draining||runTimeout(drainQueue)},Item.prototype.run=function(){this.fun.apply(null,this.array)},process.title="browser",process.browser=!0,process.env={},process.argv=[],process.version="",process.versions={},process.on=noop,process.addListener=noop,process.once=noop,process.off=noop,process.removeListener=noop,process.removeAllListeners=noop,process.emit=noop,process.prependListener=noop,process.prependOnceListener=noop,process.listeners=function(name){return[]},process.binding=function(name){throw new Error("process.binding is not supported")},process.cwd=function(){return"/"},process.chdir=function(dir){throw new Error("process.chdir is not supported")},process.umask=function(){return 0}},{}],4:[function(require,module,exports){(function(setImmediate){(function(){function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}!function(root){var setTimeoutFunc=setTimeout;function noop(){}function Promise(fn){if(!(this instanceof Promise))throw new TypeError("Promises must be constructed via new");if("function"!=typeof fn)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=void 0,this._deferreds=[],doResolve(fn,this)}function handle(self,deferred){for(;3===self._state;)self=self._value;0!==self._state?(self._handled=!0,Promise._immediateFn((function(){var cb=1===self._state?deferred.onFulfilled:deferred.onRejected;if(null!==cb){var ret;try{ret=cb(self._value)}catch(e){return void reject(deferred.promise,e)}resolve(deferred.promise,ret)}else(1===self._state?resolve:reject)(deferred.promise,self._value)}))):self._deferreds.push(deferred)}function resolve(self,newValue){try{if(newValue===self)throw new TypeError("A promise cannot be resolved with itself.");if(newValue&&("object"===_typeof(newValue)||"function"==typeof newValue)){var then=newValue.then;if(newValue instanceof Promise)return self._state=3,self._value=newValue,void finale(self);if("function"==typeof then)return void doResolve((fn=then,thisArg=newValue,function(){fn.apply(thisArg,arguments)}),self)}self._state=1,self._value=newValue,finale(self)}catch(e){reject(self,e)}var fn,thisArg}function reject(self,newValue){self._state=2,self._value=newValue,finale(self)}function finale(self){2===self._state&&0===self._deferreds.length&&Promise._immediateFn((function(){self._handled||Promise._unhandledRejectionFn(self._value)}));for(var i=0,len=self._deferreds.length;i<len;i++)handle(self,self._deferreds[i]);self._deferreds=null}function Handler(onFulfilled,onRejected,promise){this.onFulfilled="function"==typeof onFulfilled?onFulfilled:null,this.onRejected="function"==typeof onRejected?onRejected:null,this.promise=promise}function doResolve(fn,self){var done=!1;try{fn((function(value){done||(done=!0,resolve(self,value))}),(function(reason){done||(done=!0,reject(self,reason))}))}catch(ex){if(done)return;done=!0,reject(self,ex)}}Promise.prototype.catch=function(onRejected){return this.then(null,onRejected)},Promise.prototype.then=function(onFulfilled,onRejected){var prom=new this.constructor(noop);return handle(this,new Handler(onFulfilled,onRejected,prom)),prom},Promise.all=function(arr){return new Promise((function(resolve,reject){if(!arr||"undefined"==typeof arr.length)throw new TypeError("Promise.all accepts an array");var args=Array.prototype.slice.call(arr);if(0===args.length)return resolve([]);var remaining=args.length;function res(i,val){try{if(val&&("object"===_typeof(val)||"function"==typeof val)){var then=val.then;if("function"==typeof then)return void then.call(val,(function(val){res(i,val)}),reject)}args[i]=val,0==--remaining&&resolve(args)}catch(ex){reject(ex)}}for(var i=0;i<args.length;i++)res(i,args[i])}))},Promise.resolve=function(value){return value&&"object"===_typeof(value)&&value.constructor===Promise?value:new Promise((function(resolve){resolve(value)}))},Promise.reject=function(value){return new Promise((function(resolve,reject){reject(value)}))},Promise.race=function(values){return new Promise((function(resolve,reject){for(var i=0,len=values.length;i<len;i++)values[i].then(resolve,reject)}))},Promise._immediateFn="function"==typeof setImmediate&&function(fn){setImmediate(fn)}||function(fn){setTimeoutFunc(fn,0)},Promise._unhandledRejectionFn=function(err){"undefined"!=typeof console&&console&&console.warn("Possible Unhandled Promise Rejection:",err)},Promise._setImmediateFn=function(fn){Promise._immediateFn=fn},Promise._setUnhandledRejectionFn=function(fn){Promise._unhandledRejectionFn=fn},"undefined"!=typeof module&&module.exports?module.exports=Promise:root.Promise||(root.Promise=Promise)}(this)}).call(this)}).call(this,require("timers").setImmediate)},{timers:7}],5:[function(require,module,exports){"use strict";var SDPUtils=require("sdp");function writeMediaSection(transceiver,caps,type,stream,dtlsRole){var sdp=SDPUtils.writeRtpDescription(transceiver.kind,caps);if(sdp+=SDPUtils.writeIceParameters(transceiver.iceGatherer.getLocalParameters()),sdp+=SDPUtils.writeDtlsParameters(transceiver.dtlsTransport.getLocalParameters(),"offer"===type?"actpass":dtlsRole||"active"),sdp+="a=mid:"+transceiver.mid+"\r\n",transceiver.rtpSender&&transceiver.rtpReceiver?sdp+="a=sendrecv\r\n":transceiver.rtpSender?sdp+="a=sendonly\r\n":transceiver.rtpReceiver?sdp+="a=recvonly\r\n":sdp+="a=inactive\r\n",transceiver.rtpSender){var trackId=transceiver.rtpSender._initialTrackId||transceiver.rtpSender.track.id;transceiver.rtpSender._initialTrackId=trackId;var msid="msid:"+(stream?stream.id:"-")+" "+trackId+"\r\n";sdp+="a="+msid,sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].ssrc+" "+msid,transceiver.sendEncodingParameters[0].rtx&&(sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].rtx.ssrc+" "+msid,sdp+="a=ssrc-group:FID "+transceiver.sendEncodingParameters[0].ssrc+" "+transceiver.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].ssrc+" cname:"+SDPUtils.localCName+"\r\n",transceiver.rtpSender&&transceiver.sendEncodingParameters[0].rtx&&(sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].rtx.ssrc+" cname:"+SDPUtils.localCName+"\r\n"),sdp}function getCommonCapabilities(localCapabilities,remoteCapabilities){var commonCapabilities={codecs:[],headerExtensions:[],fecMechanisms:[]},findCodecByPayloadType=function(pt,codecs){pt=parseInt(pt,10);for(var i=0;i<codecs.length;i++)if(codecs[i].payloadType===pt||codecs[i].preferredPayloadType===pt)return codecs[i]},rtxCapabilityMatches=function(lRtx,rRtx,lCodecs,rCodecs){var lCodec=findCodecByPayloadType(lRtx.parameters.apt,lCodecs),rCodec=findCodecByPayloadType(rRtx.parameters.apt,rCodecs);return lCodec&&rCodec&&lCodec.name.toLowerCase()===rCodec.name.toLowerCase()};return localCapabilities.codecs.forEach((function(lCodec){for(var i=0;i<remoteCapabilities.codecs.length;i++){var rCodec=remoteCapabilities.codecs[i];if(lCodec.name.toLowerCase()===rCodec.name.toLowerCase()&&lCodec.clockRate===rCodec.clockRate){if("rtx"===lCodec.name.toLowerCase()&&lCodec.parameters&&rCodec.parameters.apt&&!rtxCapabilityMatches(lCodec,rCodec,localCapabilities.codecs,remoteCapabilities.codecs))continue;(rCodec=JSON.parse(JSON.stringify(rCodec))).numChannels=Math.min(lCodec.numChannels,rCodec.numChannels),commonCapabilities.codecs.push(rCodec),rCodec.rtcpFeedback=rCodec.rtcpFeedback.filter((function(fb){for(var j=0;j<lCodec.rtcpFeedback.length;j++)if(lCodec.rtcpFeedback[j].type===fb.type&&lCodec.rtcpFeedback[j].parameter===fb.parameter)return!0;return!1}));break}}})),localCapabilities.headerExtensions.forEach((function(lHeaderExtension){for(var i=0;i<remoteCapabilities.headerExtensions.length;i++){var rHeaderExtension=remoteCapabilities.headerExtensions[i];if(lHeaderExtension.uri===rHeaderExtension.uri){commonCapabilities.headerExtensions.push(rHeaderExtension);break}}})),commonCapabilities}function isActionAllowedInSignalingState(action,type,signalingState){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"]}}[type][action].indexOf(signalingState)}function maybeAddCandidate(iceTransport,candidate){var alreadyAdded=iceTransport.getRemoteCandidates().find((function(remoteCandidate){return candidate.foundation===remoteCandidate.foundation&&candidate.ip===remoteCandidate.ip&&candidate.port===remoteCandidate.port&&candidate.priority===remoteCandidate.priority&&candidate.protocol===remoteCandidate.protocol&&candidate.type===remoteCandidate.type}));return alreadyAdded||iceTransport.addRemoteCandidate(candidate),!alreadyAdded}function makeError(name,description){var e=new Error(description);return e.name=name,e.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[name],e}module.exports=function(window,edgeVersion){function addTrackToStreamAndFireEvent(track,stream){stream.addTrack(track),stream.dispatchEvent(new window.MediaStreamTrackEvent("addtrack",{track:track}))}function fireAddTrack(pc,track,receiver,streams){var trackEvent=new Event("track");trackEvent.track=track,trackEvent.receiver=receiver,trackEvent.transceiver={receiver:receiver},trackEvent.streams=streams,window.setTimeout((function(){pc._dispatchEvent("track",trackEvent)}))}var RTCPeerConnection=function(config){var pc=this,_eventTarget=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach((function(method){pc[method]=_eventTarget[method].bind(_eventTarget)})),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",config=JSON.parse(JSON.stringify(config||{})),this.usingBundle="max-bundle"===config.bundlePolicy,"negotiate"===config.rtcpMuxPolicy)throw makeError("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(config.rtcpMuxPolicy||(config.rtcpMuxPolicy="require"),config.iceTransportPolicy){case"all":case"relay":break;default:config.iceTransportPolicy="all"}switch(config.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:config.bundlePolicy="balanced"}if(config.iceServers=function(iceServers,edgeVersion){var hasTurn=!1;return(iceServers=JSON.parse(JSON.stringify(iceServers))).filter((function(server){if(server&&(server.urls||server.url)){var urls=server.urls||server.url;server.url&&!server.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var isString="string"==typeof urls;return isString&&(urls=[urls]),urls=urls.filter((function(url){return 0===url.indexOf("turn:")&&-1!==url.indexOf("transport=udp")&&-1===url.indexOf("turn:[")&&!hasTurn?(hasTurn=!0,!0):0===url.indexOf("stun:")&&edgeVersion>=14393&&-1===url.indexOf("?transport=udp")})),delete server.url,server.urls=isString?urls[0]:urls,!!urls.length}}))}(config.iceServers||[],edgeVersion),this._iceGatherers=[],config.iceCandidatePoolSize)for(var i=config.iceCandidatePoolSize;i>0;i--)this._iceGatherers.push(new window.RTCIceGatherer({iceServers:config.iceServers,gatherPolicy:config.iceTransportPolicy}));else config.iceCandidatePoolSize=0;this._config=config,this.transceivers=[],this._sdpSessionId=SDPUtils.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(RTCPeerConnection.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(RTCPeerConnection.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),RTCPeerConnection.prototype.onicecandidate=null,RTCPeerConnection.prototype.onaddstream=null,RTCPeerConnection.prototype.ontrack=null,RTCPeerConnection.prototype.onremovestream=null,RTCPeerConnection.prototype.onsignalingstatechange=null,RTCPeerConnection.prototype.oniceconnectionstatechange=null,RTCPeerConnection.prototype.onconnectionstatechange=null,RTCPeerConnection.prototype.onicegatheringstatechange=null,RTCPeerConnection.prototype.onnegotiationneeded=null,RTCPeerConnection.prototype.ondatachannel=null,RTCPeerConnection.prototype._dispatchEvent=function(name,event){this._isClosed||(this.dispatchEvent(event),"function"==typeof this["on"+name]&&this["on"+name](event))},RTCPeerConnection.prototype._emitGatheringStateChange=function(){var event=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",event)},RTCPeerConnection.prototype.getConfiguration=function(){return this._config},RTCPeerConnection.prototype.getLocalStreams=function(){return this.localStreams},RTCPeerConnection.prototype.getRemoteStreams=function(){return this.remoteStreams},RTCPeerConnection.prototype._createTransceiver=function(kind,doNotAdd){var hasBundleTransport=this.transceivers.length>0,transceiver={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:kind,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&hasBundleTransport)transceiver.iceTransport=this.transceivers[0].iceTransport,transceiver.dtlsTransport=this.transceivers[0].dtlsTransport;else{var transports=this._createIceAndDtlsTransports();transceiver.iceTransport=transports.iceTransport,transceiver.dtlsTransport=transports.dtlsTransport}return doNotAdd||this.transceivers.push(transceiver),transceiver},RTCPeerConnection.prototype.addTrack=function(track,stream){if(this._isClosed)throw makeError("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var transceiver;if(this.transceivers.find((function(s){return s.track===track})))throw makeError("InvalidAccessError","Track already exists.");for(var i=0;i<this.transceivers.length;i++)this.transceivers[i].track||this.transceivers[i].kind!==track.kind||(transceiver=this.transceivers[i]);return transceiver||(transceiver=this._createTransceiver(track.kind)),this._maybeFireNegotiationNeeded(),-1===this.localStreams.indexOf(stream)&&this.localStreams.push(stream),transceiver.track=track,transceiver.stream=stream,transceiver.rtpSender=new window.RTCRtpSender(track,transceiver.dtlsTransport),transceiver.rtpSender},RTCPeerConnection.prototype.addStream=function(stream){var pc=this;if(edgeVersion>=15025)stream.getTracks().forEach((function(track){pc.addTrack(track,stream)}));else{var clonedStream=stream.clone();stream.getTracks().forEach((function(track,idx){var clonedTrack=clonedStream.getTracks()[idx];track.addEventListener("enabled",(function(event){clonedTrack.enabled=event.enabled}))})),clonedStream.getTracks().forEach((function(track){pc.addTrack(track,clonedStream)}))}},RTCPeerConnection.prototype.removeTrack=function(sender){if(this._isClosed)throw makeError("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(sender instanceof window.RTCRtpSender))throw new TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var transceiver=this.transceivers.find((function(t){return t.rtpSender===sender}));if(!transceiver)throw makeError("InvalidAccessError","Sender was not created by this connection.");var stream=transceiver.stream;transceiver.rtpSender.stop(),transceiver.rtpSender=null,transceiver.track=null,transceiver.stream=null,-1===this.transceivers.map((function(t){return t.stream})).indexOf(stream)&&this.localStreams.indexOf(stream)>-1&&this.localStreams.splice(this.localStreams.indexOf(stream),1),this._maybeFireNegotiationNeeded()},RTCPeerConnection.prototype.removeStream=function(stream){var pc=this;stream.getTracks().forEach((function(track){var sender=pc.getSenders().find((function(s){return s.track===track}));sender&&pc.removeTrack(sender)}))},RTCPeerConnection.prototype.getSenders=function(){return this.transceivers.filter((function(transceiver){return!!transceiver.rtpSender})).map((function(transceiver){return transceiver.rtpSender}))},RTCPeerConnection.prototype.getReceivers=function(){return this.transceivers.filter((function(transceiver){return!!transceiver.rtpReceiver})).map((function(transceiver){return transceiver.rtpReceiver}))},RTCPeerConnection.prototype._createIceGatherer=function(sdpMLineIndex,usingBundle){var pc=this;if(usingBundle&&sdpMLineIndex>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var iceGatherer=new window.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(iceGatherer,"state",{value:"new",writable:!0}),this.transceivers[sdpMLineIndex].bufferedCandidateEvents=[],this.transceivers[sdpMLineIndex].bufferCandidates=function(event){var end=!event.candidate||0===Object.keys(event.candidate).length;iceGatherer.state=end?"completed":"gathering",null!==pc.transceivers[sdpMLineIndex].bufferedCandidateEvents&&pc.transceivers[sdpMLineIndex].bufferedCandidateEvents.push(event)},iceGatherer.addEventListener("localcandidate",this.transceivers[sdpMLineIndex].bufferCandidates),iceGatherer},RTCPeerConnection.prototype._gather=function(mid,sdpMLineIndex){var pc=this,iceGatherer=this.transceivers[sdpMLineIndex].iceGatherer;if(!iceGatherer.onlocalcandidate){var bufferedCandidateEvents=this.transceivers[sdpMLineIndex].bufferedCandidateEvents;this.transceivers[sdpMLineIndex].bufferedCandidateEvents=null,iceGatherer.removeEventListener("localcandidate",this.transceivers[sdpMLineIndex].bufferCandidates),iceGatherer.onlocalcandidate=function(evt){if(!(pc.usingBundle&&sdpMLineIndex>0)){var event=new Event("icecandidate");event.candidate={sdpMid:mid,sdpMLineIndex:sdpMLineIndex};var cand=evt.candidate,end=!cand||0===Object.keys(cand).length;if(end)"new"!==iceGatherer.state&&"gathering"!==iceGatherer.state||(iceGatherer.state="completed");else{"new"===iceGatherer.state&&(iceGatherer.state="gathering"),cand.component=1,cand.ufrag=iceGatherer.getLocalParameters().usernameFragment;var serializedCandidate=SDPUtils.writeCandidate(cand);event.candidate=Object.assign(event.candidate,SDPUtils.parseCandidate(serializedCandidate)),event.candidate.candidate=serializedCandidate,event.candidate.toJSON=function(){return{candidate:event.candidate.candidate,sdpMid:event.candidate.sdpMid,sdpMLineIndex:event.candidate.sdpMLineIndex,usernameFragment:event.candidate.usernameFragment}}}var sections=SDPUtils.getMediaSections(pc._localDescription.sdp);sections[event.candidate.sdpMLineIndex]+=end?"a=end-of-candidates\r\n":"a="+event.candidate.candidate+"\r\n",pc._localDescription.sdp=SDPUtils.getDescription(pc._localDescription.sdp)+sections.join("");var complete=pc.transceivers.every((function(transceiver){return transceiver.iceGatherer&&"completed"===transceiver.iceGatherer.state}));"gathering"!==pc.iceGatheringState&&(pc.iceGatheringState="gathering",pc._emitGatheringStateChange()),end||pc._dispatchEvent("icecandidate",event),complete&&(pc._dispatchEvent("icecandidate",new Event("icecandidate")),pc.iceGatheringState="complete",pc._emitGatheringStateChange())}},window.setTimeout((function(){bufferedCandidateEvents.forEach((function(e){iceGatherer.onlocalcandidate(e)}))}),0)}},RTCPeerConnection.prototype._createIceAndDtlsTransports=function(){var pc=this,iceTransport=new window.RTCIceTransport(null);iceTransport.onicestatechange=function(){pc._updateIceConnectionState(),pc._updateConnectionState()};var dtlsTransport=new window.RTCDtlsTransport(iceTransport);return dtlsTransport.ondtlsstatechange=function(){pc._updateConnectionState()},dtlsTransport.onerror=function(){Object.defineProperty(dtlsTransport,"state",{value:"failed",writable:!0}),pc._updateConnectionState()},{iceTransport:iceTransport,dtlsTransport:dtlsTransport}},RTCPeerConnection.prototype._disposeIceAndDtlsTransports=function(sdpMLineIndex){var iceGatherer=this.transceivers[sdpMLineIndex].iceGatherer;iceGatherer&&(delete iceGatherer.onlocalcandidate,delete this.transceivers[sdpMLineIndex].iceGatherer);var iceTransport=this.transceivers[sdpMLineIndex].iceTransport;iceTransport&&(delete iceTransport.onicestatechange,delete this.transceivers[sdpMLineIndex].iceTransport);var dtlsTransport=this.transceivers[sdpMLineIndex].dtlsTransport;dtlsTransport&&(delete dtlsTransport.ondtlsstatechange,delete dtlsTransport.onerror,delete this.transceivers[sdpMLineIndex].dtlsTransport)},RTCPeerConnection.prototype._transceive=function(transceiver,send,recv){var params=getCommonCapabilities(transceiver.localCapabilities,transceiver.remoteCapabilities);send&&transceiver.rtpSender&&(params.encodings=transceiver.sendEncodingParameters,params.rtcp={cname:SDPUtils.localCName,compound:transceiver.rtcpParameters.compound},transceiver.recvEncodingParameters.length&&(params.rtcp.ssrc=transceiver.recvEncodingParameters[0].ssrc),transceiver.rtpSender.send(params)),recv&&transceiver.rtpReceiver&¶ms.codecs.length>0&&("video"===transceiver.kind&&transceiver.recvEncodingParameters&&edgeVersion<15019&&transceiver.recvEncodingParameters.forEach((function(p){delete p.rtx})),transceiver.recvEncodingParameters.length?params.encodings=transceiver.recvEncodingParameters:params.encodings=[{}],params.rtcp={compound:transceiver.rtcpParameters.compound},transceiver.rtcpParameters.cname&&(params.rtcp.cname=transceiver.rtcpParameters.cname),transceiver.sendEncodingParameters.length&&(params.rtcp.ssrc=transceiver.sendEncodingParameters[0].ssrc),transceiver.rtpReceiver.receive(params))},RTCPeerConnection.prototype.setLocalDescription=function(description){var sections,sessionpart,pc=this;if(-1===["offer","answer"].indexOf(description.type))return Promise.reject(makeError("TypeError",'Unsupported type "'+description.type+'"'));if(!isActionAllowedInSignalingState("setLocalDescription",description.type,pc.signalingState)||pc._isClosed)return Promise.reject(makeError("InvalidStateError","Can not set local "+description.type+" in state "+pc.signalingState));if("offer"===description.type)sections=SDPUtils.splitSections(description.sdp),sessionpart=sections.shift(),sections.forEach((function(mediaSection,sdpMLineIndex){var caps=SDPUtils.parseRtpParameters(mediaSection);pc.transceivers[sdpMLineIndex].localCapabilities=caps})),pc.transceivers.forEach((function(transceiver,sdpMLineIndex){pc._gather(transceiver.mid,sdpMLineIndex)}));else if("answer"===description.type){sections=SDPUtils.splitSections(pc._remoteDescription.sdp),sessionpart=sections.shift();var isIceLite=SDPUtils.matchPrefix(sessionpart,"a=ice-lite").length>0;sections.forEach((function(mediaSection,sdpMLineIndex){var transceiver=pc.transceivers[sdpMLineIndex],iceGatherer=transceiver.iceGatherer,iceTransport=transceiver.iceTransport,dtlsTransport=transceiver.dtlsTransport,localCapabilities=transceiver.localCapabilities,remoteCapabilities=transceiver.remoteCapabilities;if(!(SDPUtils.isRejected(mediaSection)&&0===SDPUtils.matchPrefix(mediaSection,"a=bundle-only").length)&&!transceiver.rejected){var remoteIceParameters=SDPUtils.getIceParameters(mediaSection,sessionpart),remoteDtlsParameters=SDPUtils.getDtlsParameters(mediaSection,sessionpart);isIceLite&&(remoteDtlsParameters.role="server"),pc.usingBundle&&0!==sdpMLineIndex||(pc._gather(transceiver.mid,sdpMLineIndex),"new"===iceTransport.state&&iceTransport.start(iceGatherer,remoteIceParameters,isIceLite?"controlling":"controlled"),"new"===dtlsTransport.state&&dtlsTransport.start(remoteDtlsParameters));var params=getCommonCapabilities(localCapabilities,remoteCapabilities);pc._transceive(transceiver,params.codecs.length>0,!1)}}))}return pc._localDescription={type:description.type,sdp:description.sdp},"offer"===description.type?pc._updateSignalingState("have-local-offer"):pc._updateSignalingState("stable"),Promise.resolve()},RTCPeerConnection.prototype.setRemoteDescription=function(description){var pc=this;if(-1===["offer","answer"].indexOf(description.type))return Promise.reject(makeError("TypeError",'Unsupported type "'+description.type+'"'));if(!isActionAllowedInSignalingState("setRemoteDescription",description.type,pc.signalingState)||pc._isClosed)return Promise.reject(makeError("InvalidStateError","Can not set remote "+description.type+" in state "+pc.signalingState));var streams={};pc.remoteStreams.forEach((function(stream){streams[stream.id]=stream}));var receiverList=[],sections=SDPUtils.splitSections(description.sdp),sessionpart=sections.shift(),isIceLite=SDPUtils.matchPrefix(sessionpart,"a=ice-lite").length>0,usingBundle=SDPUtils.matchPrefix(sessionpart,"a=group:BUNDLE ").length>0;pc.usingBundle=usingBundle;var iceOptions=SDPUtils.matchPrefix(sessionpart,"a=ice-options:")[0];return pc.canTrickleIceCandidates=!!iceOptions&&iceOptions.substr(14).split(" ").indexOf("trickle")>=0,sections.forEach((function(mediaSection,sdpMLineIndex){var lines=SDPUtils.splitLines(mediaSection),kind=SDPUtils.getKind(mediaSection),rejected=SDPUtils.isRejected(mediaSection)&&0===SDPUtils.matchPrefix(mediaSection,"a=bundle-only").length,protocol=lines[0].substr(2).split(" ")[2],direction=SDPUtils.getDirection(mediaSection,sessionpart),remoteMsid=SDPUtils.parseMsid(mediaSection),mid=SDPUtils.getMid(mediaSection)||SDPUtils.generateIdentifier();if(rejected||"application"===kind&&("DTLS/SCTP"===protocol||"UDP/DTLS/SCTP"===protocol))pc.transceivers[sdpMLineIndex]={mid:mid,kind:kind,protocol:protocol,rejected:!0};else{var transceiver,iceGatherer,iceTransport,dtlsTransport,rtpReceiver,sendEncodingParameters,recvEncodingParameters,localCapabilities,track;!rejected&&pc.transceivers[sdpMLineIndex]&&pc.transceivers[sdpMLineIndex].rejected&&(pc.transceivers[sdpMLineIndex]=pc._createTransceiver(kind,!0));var remoteIceParameters,remoteDtlsParameters,remoteCapabilities=SDPUtils.parseRtpParameters(mediaSection);rejected||(remoteIceParameters=SDPUtils.getIceParameters(mediaSection,sessionpart),(remoteDtlsParameters=SDPUtils.getDtlsParameters(mediaSection,sessionpart)).role="client"),recvEncodingParameters=SDPUtils.parseRtpEncodingParameters(mediaSection);var rtcpParameters=SDPUtils.parseRtcpParameters(mediaSection),isComplete=SDPUtils.matchPrefix(mediaSection,"a=end-of-candidates",sessionpart).length>0,cands=SDPUtils.matchPrefix(mediaSection,"a=candidate:").map((function(cand){return SDPUtils.parseCandidate(cand)})).filter((function(cand){return 1===cand.component}));if(("offer"===description.type||"answer"===description.type)&&!rejected&&usingBundle&&sdpMLineIndex>0&&pc.transceivers[sdpMLineIndex]&&(pc._disposeIceAndDtlsTransports(sdpMLineIndex),pc.transceivers[sdpMLineIndex].iceGatherer=pc.transceivers[0].iceGatherer,pc.transceivers[sdpMLineIndex].iceTransport=pc.transceivers[0].iceTransport,pc.transceivers[sdpMLineIndex].dtlsTransport=pc.transceivers[0].dtlsTransport,pc.transceivers[sdpMLineIndex].rtpSender&&pc.transceivers[sdpMLineIndex].rtpSender.setTransport(pc.transceivers[0].dtlsTransport),pc.transceivers[sdpMLineIndex].rtpReceiver&&pc.transceivers[sdpMLineIndex].rtpReceiver.setTransport(pc.transceivers[0].dtlsTransport)),"offer"!==description.type||rejected){if("answer"===description.type&&!rejected){iceGatherer=(transceiver=pc.transceivers[sdpMLineIndex]).iceGatherer,iceTransport=transceiver.iceTransport,dtlsTransport=transceiver.dtlsTransport,rtpReceiver=transceiver.rtpReceiver,sendEncodingParameters=transceiver.sendEncodingParameters,localCapabilities=transceiver.localCapabilities,pc.transceivers[sdpMLineIndex].recvEncodingParameters=recvEncodingParameters,pc.transceivers[sdpMLineIndex].remoteCapabilities=remoteCapabilities,pc.transceivers[sdpMLineIndex].rtcpParameters=rtcpParameters,cands.length&&"new"===iceTransport.state&&(!isIceLite&&!isComplete||usingBundle&&0!==sdpMLineIndex?cands.forEach((function(candidate){maybeAddCandidate(transceiver.iceTransport,candidate)})):iceTransport.setRemoteCandidates(cands)),usingBundle&&0!==sdpMLineIndex||("new"===iceTransport.state&&iceTransport.start(iceGatherer,remoteIceParameters,"controlling"),"new"===dtlsTransport.state&&dtlsTransport.start(remoteDtlsParameters)),!getCommonCapabilities(transceiver.localCapabilities,transceiver.remoteCapabilities).codecs.filter((function(c){return"rtx"===c.name.toLowerCase()})).length&&transceiver.sendEncodingParameters[0].rtx&&delete transceiver.sendEncodingParameters[0].rtx,pc._transceive(transceiver,"sendrecv"===direction||"recvonly"===direction,"sendrecv"===direction||"sendonly"===direction),!rtpReceiver||"sendrecv"!==direction&&"sendonly"!==direction?delete transceiver.rtpReceiver:(track=rtpReceiver.track,remoteMsid?(streams[remoteMsid.stream]||(streams[remoteMsid.stream]=new window.MediaStream),addTrackToStreamAndFireEvent(track,streams[remoteMsid.stream]),receiverList.push([track,rtpReceiver,streams[remoteMsid.stream]])):(streams.default||(streams.default=new window.MediaStream),addTrackToStreamAndFireEvent(track,streams.default),receiverList.push([track,rtpReceiver,streams.default])))}}else{(transceiver=pc.transceivers[sdpMLineIndex]||pc._createTransceiver(kind)).mid=mid,transceiver.iceGatherer||(transceiver.iceGatherer=pc._createIceGatherer(sdpMLineIndex,usingBundle)),cands.length&&"new"===transceiver.iceTransport.state&&(!isComplete||usingBundle&&0!==sdpMLineIndex?cands.forEach((function(candidate){maybeAddCandidate(transceiver.iceTransport,candidate)})):transceiver.iceTransport.setRemoteCandidates(cands)),localCapabilities=window.RTCRtpReceiver.getCapabilities(kind),edgeVersion<15019&&(localCapabilities.codecs=localCapabilities.codecs.filter((function(codec){return"rtx"!==codec.name}))),sendEncodingParameters=transceiver.sendEncodingParameters||[{ssrc:1001*(2*sdpMLineIndex+2)}];var stream,isNewTrack=!1;if("sendrecv"===direction||"sendonly"===direction){if(isNewTrack=!transceiver.rtpReceiver,rtpReceiver=transceiver.rtpReceiver||new window.RTCRtpReceiver(transceiver.dtlsTransport,kind),isNewTrack)track=rtpReceiver.track,remoteMsid&&"-"===remoteMsid.stream||(remoteMsid?(streams[remoteMsid.stream]||(streams[remoteMsid.stream]=new window.MediaStream,Object.defineProperty(streams[remoteMsid.stream],"id",{get:function(){return remoteMsid.stream}})),Object.defineProperty(track,"id",{get:function(){return remoteMsid.track}}),stream=streams[remoteMsid.stream]):(streams.default||(streams.default=new window.MediaStream),stream=streams.default)),stream&&(addTrackToStreamAndFireEvent(track,stream),transceiver.associatedRemoteMediaStreams.push(stream)),receiverList.push([track,rtpReceiver,stream])}else transceiver.rtpReceiver&&transceiver.rtpReceiver.track&&(transceiver.associatedRemoteMediaStreams.forEach((function(s){var nativeTrack=s.getTracks().find((function(t){return t.id===transceiver.rtpReceiver.track.id}));nativeTrack&&function(track,stream){stream.removeTrack(track),stream.dispatchEvent(new window.MediaStreamTrackEvent("removetrack",{track:track}))}(nativeTrack,s)})),transceiver.associatedRemoteMediaStreams=[]);transceiver.localCapabilities=localCapabilities,transceiver.remoteCapabilities=remoteCapabilities,transceiver.rtpReceiver=rtpReceiver,transceiver.rtcpParameters=rtcpParameters,transceiver.sendEncodingParameters=sendEncodingParameters,transceiver.recvEncodingParameters=recvEncodingParameters,pc._transceive(pc.transceivers[sdpMLineIndex],!1,isNewTrack)}}})),void 0===pc._dtlsRole&&(pc._dtlsRole="offer"===description.type?"active":"passive"),pc._remoteDescription={type:description.type,sdp:description.sdp},"offer"===description.type?pc._updateSignalingState("have-remote-offer"):pc._updateSignalingState("stable"),Object.keys(streams).forEach((function(sid){var stream=streams[sid];if(stream.getTracks().length){if(-1===pc.remoteStreams.indexOf(stream)){pc.remoteStreams.push(stream);var event=new Event("addstream");event.stream=stream,window.setTimeout((function(){pc._dispatchEvent("addstream",event)}))}receiverList.forEach((function(item){var track=item[0],receiver=item[1];stream.id===item[2].id&&fireAddTrack(pc,track,receiver,[stream])}))}})),receiverList.forEach((function(item){item[2]||fireAddTrack(pc,item[0],item[1],[])})),window.setTimeout((function(){pc&&pc.transceivers&&pc.transceivers.forEach((function(transceiver){transceiver.iceTransport&&"new"===transceiver.iceTransport.state&&transceiver.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),transceiver.iceTransport.addRemoteCandidate({}))}))}),4e3),Promise.resolve()},RTCPeerConnection.prototype.close=function(){this.transceivers.forEach((function(transceiver){transceiver.iceTransport&&transceiver.iceTransport.stop(),transceiver.dtlsTransport&&transceiver.dtlsTransport.stop(),transceiver.rtpSender&&transceiver.rtpSender.stop(),transceiver.rtpReceiver&&transceiver.rtpReceiver.stop()})),this._isClosed=!0,this._updateSignalingState("closed")},RTCPeerConnection.prototype._updateSignalingState=function(newState){this.signalingState=newState;var event=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",event)},RTCPeerConnection.prototype._maybeFireNegotiationNeeded=function(){var pc=this;"stable"===this.signalingState&&!0!==this.needNegotiation&&(this.needNegotiation=!0,window.setTimeout((function(){if(pc.needNegotiation){pc.needNegotiation=!1;var event=new Event("negotiationneeded");pc._dispatchEvent("negotiationneeded",event)}}),0))},RTCPeerConnection.prototype._updateIceConnectionState=function(){var newState,states={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(transceiver){transceiver.iceTransport&&!transceiver.rejected&&states[transceiver.iceTransport.state]++})),newState="new",states.failed>0?newState="failed":states.checking>0?newState="checking":states.disconnected>0?newState="disconnected":states.new>0?newState="new":states.connected>0?newState="connected":states.completed>0&&(newState="completed"),newState!==this.iceConnectionState){this.iceConnectionState=newState;var event=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",event)}},RTCPeerConnection.prototype._updateConnectionState=function(){var newState,states={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(transceiver){transceiver.iceTransport&&transceiver.dtlsTransport&&!transceiver.rejected&&(states[transceiver.iceTransport.state]++,states[transceiver.dtlsTransport.state]++)})),states.connected+=states.completed,newState="new",states.failed>0?newState="failed":states.connecting>0?newState="connecting":states.disconnected>0?newState="disconnected":states.new>0?newState="new":states.connected>0&&(newState="connected"),newState!==this.connectionState){this.connectionState=newState;var event=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",event)}},RTCPeerConnection.prototype.createOffer=function(){var pc=this;if(pc._isClosed)return Promise.reject(makeError("InvalidStateError","Can not call createOffer after close"));var numAudioTracks=pc.transceivers.filter((function(t){return"audio"===t.kind})).length,numVideoTracks=pc.transceivers.filter((function(t){return"video"===t.kind})).length,offerOptions=arguments[0];if(offerOptions){if(offerOptions.mandatory||offerOptions.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");void 0!==offerOptions.offerToReceiveAudio&&(numAudioTracks=!0===offerOptions.offerToReceiveAudio?1:!1===offerOptions.offerToReceiveAudio?0:offerOptions.offerToReceiveAudio),void 0!==offerOptions.offerToReceiveVideo&&(numVideoTracks=!0===offerOptions.offerToReceiveVideo?1:!1===offerOptions.offerToReceiveVideo?0:offerOptions.offerToReceiveVideo)}for(pc.transceivers.forEach((function(transceiver){"audio"===transceiver.kind?--numAudioTracks<0&&(transceiver.wantReceive=!1):"video"===transceiver.kind&&--numVideoTracks<0&&(transceiver.wantReceive=!1)}));numAudioTracks>0||numVideoTracks>0;)numAudioTracks>0&&(pc._createTransceiver("audio"),numAudioTracks--),numVideoTracks>0&&(pc._createTransceiver("video"),numVideoTracks--);var sdp=SDPUtils.writeSessionBoilerplate(pc._sdpSessionId,pc._sdpSessionVersion++);pc.transceivers.forEach((function(transceiver,sdpMLineIndex){var track=transceiver.track,kind=transceiver.kind,mid=transceiver.mid||SDPUtils.generateIdentifier();transceiver.mid=mid,transceiver.iceGatherer||(transceiver.iceGatherer=pc._createIceGatherer(sdpMLineIndex,pc.usingBundle));var localCapabilities=window.RTCRtpSender.getCapabilities(kind);edgeVersion<15019&&(localCapabilities.codecs=localCapabilities.codecs.filter((function(codec){return"rtx"!==codec.name}))),localCapabilities.codecs.forEach((function(codec){"H264"===codec.name&&void 0===codec.parameters["level-asymmetry-allowed"]&&(codec.parameters["level-asymmetry-allowed"]="1"),transceiver.remoteCapabilities&&transceiver.remoteCapabilities.codecs&&transceiver.remoteCapabilities.codecs.forEach((function(remoteCodec){codec.name.toLowerCase()===remoteCodec.name.toLowerCase()&&codec.clockRate===remoteCodec.clockRate&&(codec.preferredPayloadType=remoteCodec.payloadType)}))})),localCapabilities.headerExtensions.forEach((function(hdrExt){(transceiver.remoteCapabilities&&transceiver.remoteCapabilities.headerExtensions||[]).forEach((function(rHdrExt){hdrExt.uri===rHdrExt.uri&&(hdrExt.id=rHdrExt.id)}))}));var sendEncodingParameters=transceiver.sendEncodingParameters||[{ssrc:1001*(2*sdpMLineIndex+1)}];track&&edgeVersion>=15019&&"video"===kind&&!sendEncodingParameters[0].rtx&&(sendEncodingParameters[0].rtx={ssrc:sendEncodingParameters[0].ssrc+1}),transceiver.wantReceive&&(transceiver.rtpReceiver=new window.RTCRtpReceiver(transceiver.dtlsTransport,kind)),transceiver.localCapabilities=localCapabilities,transceiver.sendEncodingParameters=sendEncodingParameters})),"max-compat"!==pc._config.bundlePolicy&&(sdp+="a=group:BUNDLE "+pc.transceivers.map((function(t){return t.mid})).join(" ")+"\r\n"),sdp+="a=ice-options:trickle\r\n",pc.transceivers.forEach((function(transceiver,sdpMLineIndex){sdp+=writeMediaSection(transceiver,transceiver.localCapabilities,"offer",transceiver.stream,pc._dtlsRole),sdp+="a=rtcp-rsize\r\n",!transceiver.iceGatherer||"new"===pc.iceGatheringState||0!==sdpMLineIndex&&pc.usingBundle||(transceiver.iceGatherer.getLocalCandidates().forEach((function(cand){cand.component=1,sdp+="a="+SDPUtils.writeCandidate(cand)+"\r\n"})),"completed"===transceiver.iceGatherer.state&&(sdp+="a=end-of-candidates\r\n"))}));var desc=new window.RTCSessionDescription({type:"offer",sdp:sdp});return Promise.resolve(desc)},RTCPeerConnection.prototype.createAnswer=function(){var pc=this;if(pc._isClosed)return Promise.reject(makeError("InvalidStateError","Can not call createAnswer after close"));if("have-remote-offer"!==pc.signalingState&&"have-local-pranswer"!==pc.signalingState)return Promise.reject(makeError("InvalidStateError","Can not call createAnswer in signalingState "+pc.signalingState));var sdp=SDPUtils.writeSessionBoilerplate(pc._sdpSessionId,pc._sdpSessionVersion++);pc.usingBundle&&(sdp+="a=group:BUNDLE "+pc.transceivers.map((function(t){return t.mid})).join(" ")+"\r\n"),sdp+="a=ice-options:trickle\r\n";var mediaSectionsInOffer=SDPUtils.getMediaSections(pc._remoteDescription.sdp).length;pc.transceivers.forEach((function(transceiver,sdpMLineIndex){if(!(sdpMLineIndex+1>mediaSectionsInOffer)){if(transceiver.rejected)return"application"===transceiver.kind?"DTLS/SCTP"===transceiver.protocol?sdp+="m=application 0 DTLS/SCTP 5000\r\n":sdp+="m=application 0 "+transceiver.protocol+" webrtc-datachannel\r\n":"audio"===transceiver.kind?sdp+="m=audio 0 UDP/TLS/RTP/SAVPF 0\r\na=rtpmap:0 PCMU/8000\r\n":"video"===transceiver.kind&&(sdp+="m=video 0 UDP/TLS/RTP/SAVPF 120\r\na=rtpmap:120 VP8/90000\r\n"),void(sdp+="c=IN IP4 0.0.0.0\r\na=inactive\r\na=mid:"+transceiver.mid+"\r\n");var localTrack;if(transceiver.stream)"audio"===transceiver.kind?localTrack=transceiver.stream.getAudioTracks()[0]:"video"===transceiver.kind&&(localTrack=transceiver.stream.getVideoTracks()[0]),localTrack&&edgeVersion>=15019&&"video"===transceiver.kind&&!transceiver.sendEncodingParameters[0].rtx&&(transceiver.sendEncodingParameters[0].rtx={ssrc:transceiver.sendEncodingParameters[0].ssrc+1});var commonCapabilities=getCommonCapabilities(transceiver.localCapabilities,transceiver.remoteCapabilities);!commonCapabilities.codecs.filter((function(c){return"rtx"===c.name.toLowerCase()})).length&&transceiver.sendEncodingParameters[0].rtx&&delete transceiver.sendEncodingParameters[0].rtx,sdp+=writeMediaSection(transceiver,commonCapabilities,"answer",transceiver.stream,pc._dtlsRole),transceiver.rtcpParameters&&transceiver.rtcpParameters.reducedSize&&(sdp+="a=rtcp-rsize\r\n")}}));var desc=new window.RTCSessionDescription({type:"answer",sdp:sdp});return Promise.resolve(desc)},RTCPeerConnection.prototype.addIceCandidate=function(candidate){var sections,pc=this;return candidate&&void 0===candidate.sdpMLineIndex&&!candidate.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise((function(resolve,reject){if(!pc._remoteDescription)return reject(makeError("InvalidStateError","Can not add ICE candidate without a remote description"));if(candidate&&""!==candidate.candidate){var sdpMLineIndex=candidate.sdpMLineIndex;if(candidate.sdpMid)for(var i=0;i<pc.transceivers.length;i++)if(pc.transceivers[i].mid===candidate.sdpMid){sdpMLineIndex=i;break}var transceiver=pc.transceivers[sdpMLineIndex];if(!transceiver)return reject(makeError("OperationError","Can not add ICE candidate"));if(transceiver.rejected)return resolve();var cand=Object.keys(candidate.candidate).length>0?SDPUtils.parseCandidate(candidate.candidate):{};if("tcp"===cand.protocol&&(0===cand.port||9===cand.port))return resolve();if(cand.component&&1!==cand.component)return resolve();if((0===sdpMLineIndex||sdpMLineIndex>0&&transceiver.iceTransport!==pc.transceivers[0].iceTransport)&&!maybeAddCandidate(transceiver.iceTransport,cand))return reject(makeError("OperationError","Can not add ICE candidate"));var candidateString=candidate.candidate.trim();0===candidateString.indexOf("a=")&&(candidateString=candidateString.substr(2)),(sections=SDPUtils.getMediaSections(pc._remoteDescription.sdp))[sdpMLineIndex]+="a="+(cand.type?candidateString:"end-of-candidates")+"\r\n",pc._remoteDescription.sdp=SDPUtils.getDescription(pc._remoteDescription.sdp)+sections.join("")}else for(var j=0;j<pc.transceivers.length&&(pc.transceivers[j].rejected||(pc.transceivers[j].iceTransport.addRemoteCandidate({}),(sections=SDPUtils.getMediaSections(pc._remoteDescription.sdp))[j]+="a=end-of-candidates\r\n",pc._remoteDescription.sdp=SDPUtils.getDescription(pc._remoteDescription.sdp)+sections.join(""),!pc.usingBundle));j++);resolve()}))},RTCPeerConnection.prototype.getStats=function(selector){if(selector&&selector instanceof window.MediaStreamTrack){var senderOrReceiver=null;if(this.transceivers.forEach((function(transceiver){transceiver.rtpSender&&transceiver.rtpSender.track===selector?senderOrReceiver=transceiver.rtpSender:transceiver.rtpReceiver&&transceiver.rtpReceiver.track===selector&&(senderOrReceiver=transceiver.rtpReceiver)})),!senderOrReceiver)throw makeError("InvalidAccessError","Invalid selector.");return senderOrReceiver.getStats()}var promises=[];return this.transceivers.forEach((function(transceiver){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach((function(method){transceiver[method]&&promises.push(transceiver[method].getStats())}))})),Promise.all(promises).then((function(allStats){var results=new Map;return allStats.forEach((function(stats){stats.forEach((function(stat){results.set(stat.id,stat)}))})),results}))};["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach((function(ortcObjectName){var obj=window[ortcObjectName];if(obj&&obj.prototype&&obj.prototype.getStats){var nativeGetstats=obj.prototype.getStats;obj.prototype.getStats=function(){return nativeGetstats.apply(this).then((function(nativeStats){var mapStats=new Map;return Object.keys(nativeStats).forEach((function(id){var stat;nativeStats[id].type={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[(stat=nativeStats[id]).type]||stat.type,mapStats.set(id,nativeStats[id])})),mapStats}))}}}));var methods=["createOffer","createAnswer"];return methods.forEach((function(method){var nativeMethod=RTCPeerConnection.prototype[method];RTCPeerConnection.prototype[method]=function(){var args=arguments;return"function"==typeof args[0]||"function"==typeof args[1]?nativeMethod.apply(this,[arguments[2]]).then((function(description){"function"==typeof args[0]&&args[0].apply(null,[description])}),(function(error){"function"==typeof args[1]&&args[1].apply(null,[error])})):nativeMethod.apply(this,arguments)}})),(methods=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach((function(method){var nativeMethod=RTCPeerConnection.prototype[method];RTCPeerConnection.prototype[method]=function(){var args=arguments;return"function"==typeof args[1]||"function"==typeof args[2]?nativeMethod.apply(this,arguments).then((function(){"function"==typeof args[1]&&args[1].apply(null)}),(function(error){"function"==typeof args[2]&&args[2].apply(null,[error])})):nativeMethod.apply(this,arguments)}})),["getStats"].forEach((function(method){var nativeMethod=RTCPeerConnection.prototype[method];RTCPeerConnection.prototype[method]=function(){var args=arguments;return"function"==typeof args[1]?nativeMethod.apply(this,arguments).then((function(){"function"==typeof args[1]&&args[1].apply(null)})):nativeMethod.apply(this,arguments)}})),RTCPeerConnection}},{sdp:6}],6:[function(require,module,exports){"use strict";function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}var SDPUtils={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};SDPUtils.localCName=SDPUtils.generateIdentifier(),SDPUtils.splitLines=function(blob){return blob.trim().split("\n").map((function(line){return line.trim()}))},SDPUtils.splitSections=function(blob){return blob.split("\nm=").map((function(part,index){return(index>0?"m="+part:part).trim()+"\r\n"}))},SDPUtils.getDescription=function(blob){var sections=SDPUtils.splitSections(blob);return sections&§ions[0]},SDPUtils.getMediaSections=function(blob){var sections=SDPUtils.splitSections(blob);return sections.shift(),sections},SDPUtils.matchPrefix=function(blob,prefix){return SDPUtils.splitLines(blob).filter((function(line){return 0===line.indexOf(prefix)}))},SDPUtils.parseCandidate=function(line){for(var parts,candidate={foundation:(parts=0===line.indexOf("a=candidate:")?line.substring(12).split(" "):line.substring(10).split(" "))[0],component:parseInt(parts[1],10),protocol:parts[2].toLowerCase(),priority:parseInt(parts[3],10),ip:parts[4],address:parts[4],port:parseInt(parts[5],10),type:parts[7]},i=8;i<parts.length;i+=2)switch(parts[i]){case"raddr":candidate.relatedAddress=parts[i+1];break;case"rport":candidate.relatedPort=parseInt(parts[i+1],10);break;case"tcptype":candidate.tcpType=parts[i+1];break;case"ufrag":candidate.ufrag=parts[i+1],candidate.usernameFragment=parts[i+1];break;default:candidate[parts[i]]=parts[i+1]}return candidate},SDPUtils.writeCandidate=function(candidate){var sdp=[];sdp.push(candidate.foundation),sdp.push(candidate.component),sdp.push(candidate.protocol.toUpperCase()),sdp.push(candidate.priority),sdp.push(candidate.address||candidate.ip),sdp.push(candidate.port);var type=candidate.type;return sdp.push("typ"),sdp.push(type),"host"!==type&&candidate.relatedAddress&&candidate.relatedPort&&(sdp.push("raddr"),sdp.push(candidate.relatedAddress),sdp.push("rport"),sdp.push(candidate.relatedPort)),candidate.tcpType&&"tcp"===candidate.protocol.toLowerCase()&&(sdp.push("tcptype"),sdp.push(candidate.tcpType)),(candidate.usernameFragment||candidate.ufrag)&&(sdp.push("ufrag"),sdp.push(candidate.usernameFragment||candidate.ufrag)),"candidate:"+sdp.join(" ")},SDPUtils.parseIceOptions=function(line){return line.substr(14).split(" ")},SDPUtils.parseRtpMap=function(line){var parts=line.substr(9).split(" "),parsed={payloadType:parseInt(parts.shift(),10)};return parts=parts[0].split("/"),parsed.name=parts[0],parsed.clockRate=parseInt(parts[1],10),parsed.channels=3===parts.length?parseInt(parts[2],10):1,parsed.numChannels=parsed.channels,parsed},SDPUtils.writeRtpMap=function(codec){var pt=codec.payloadType;void 0!==codec.preferredPayloadType&&(pt=codec.preferredPayloadType);var channels=codec.channels||codec.numChannels||1;return"a=rtpmap:"+pt+" "+codec.name+"/"+codec.clockRate+(1!==channels?"/"+channels:"")+"\r\n"},SDPUtils.parseExtmap=function(line){var parts=line.substr(9).split(" ");return{id:parseInt(parts[0],10),direction:parts[0].indexOf("/")>0?parts[0].split("/")[1]:"sendrecv",uri:parts[1]}},SDPUtils.writeExtmap=function(headerExtension){return"a=extmap:"+(headerExtension.id||headerExtension.preferredId)+(headerExtension.direction&&"sendrecv"!==headerExtension.direction?"/"+headerExtension.direction:"")+" "+headerExtension.uri+"\r\n"},SDPUtils.parseFmtp=function(line){for(var kv,parsed={},parts=line.substr(line.indexOf(" ")+1).split(";"),j=0;j<parts.length;j++)parsed[(kv=parts[j].trim().split("="))[0].trim()]=kv[1];return parsed},SDPUtils.writeFmtp=function(codec){var line="",pt=codec.payloadType;if(void 0!==codec.preferredPayloadType&&(pt=codec.preferredPayloadType),codec.parameters&&Object.keys(codec.parameters).length){var params=[];Object.keys(codec.parameters).forEach((function(param){codec.parameters[param]?params.push(param+"="+codec.parameters[param]):params.push(param)})),line+="a=fmtp:"+pt+" "+params.join(";")+"\r\n"}return line},SDPUtils.parseRtcpFb=function(line){var parts=line.substr(line.indexOf(" ")+1).split(" ");return{type:parts.shift(),parameter:parts.join(" ")}},SDPUtils.writeRtcpFb=function(codec){var lines="",pt=codec.payloadType;return void 0!==codec.preferredPayloadType&&(pt=codec.preferredPayloadType),codec.rtcpFeedback&&codec.rtcpFeedback.length&&codec.rtcpFeedback.forEach((function(fb){lines+="a=rtcp-fb:"+pt+" "+fb.type+(fb.parameter&&fb.parameter.length?" "+fb.parameter:"")+"\r\n"})),lines},SDPUtils.parseSsrcMedia=function(line){var sp=line.indexOf(" "),parts={ssrc:parseInt(line.substr(7,sp-7),10)},colon=line.indexOf(":",sp);return colon>-1?(parts.attribute=line.substr(sp+1,colon-sp-1),parts.value=line.substr(colon+1)):parts.attribute=line.substr(sp+1),parts},SDPUtils.parseSsrcGroup=function(line){var parts=line.substr(13).split(" ");return{semantics:parts.shift(),ssrcs:parts.map((function(ssrc){return parseInt(ssrc,10)}))}},SDPUtils.getMid=function(mediaSection){var mid=SDPUtils.matchPrefix(mediaSection,"a=mid:")[0];if(mid)return mid.substr(6)},SDPUtils.parseFingerprint=function(line){var parts=line.substr(14).split(" ");return{algorithm:parts[0].toLowerCase(),value:parts[1]}},SDPUtils.getDtlsParameters=function(mediaSection,sessionpart){return{role:"auto",fingerprints:SDPUtils.matchPrefix(mediaSection+sessionpart,"a=fingerprint:").map(SDPUtils.parseFingerprint)}},SDPUtils.writeDtlsParameters=function(params,setupType){var sdp="a=setup:"+setupType+"\r\n";return params.fingerprints.forEach((function(fp){sdp+="a=fingerprint:"+fp.algorithm+" "+fp.value+"\r\n"})),sdp},SDPUtils.parseCryptoLine=function(line){var parts=line.substr(9).split(" ");return{tag:parseInt(parts[0],10),cryptoSuite:parts[1],keyParams:parts[2],sessionParams:parts.slice(3)}},SDPUtils.writeCryptoLine=function(parameters){return"a=crypto:"+parameters.tag+" "+parameters.cryptoSuite+" "+("object"===_typeof(parameters.keyParams)?SDPUtils.writeCryptoKeyParams(parameters.keyParams):parameters.keyParams)+(parameters.sessionParams?" "+parameters.sessionParams.join(" "):"")+"\r\n"},SDPUtils.parseCryptoKeyParams=function(keyParams){if(0!==keyParams.indexOf("inline:"))return null;var parts=keyParams.substr(7).split("|");return{keyMethod:"inline",keySalt:parts[0],lifeTime:parts[1],mkiValue:parts[2]?parts[2].split(":")[0]:void 0,mkiLength:parts[2]?parts[2].split(":")[1]:void 0}},SDPUtils.writeCryptoKeyParams=function(keyParams){return keyParams.keyMethod+":"+keyParams.keySalt+(keyParams.lifeTime?"|"+keyParams.lifeTime:"")+(keyParams.mkiValue&&keyParams.mkiLength?"|"+keyParams.mkiValue+":"+keyParams.mkiLength:"")},SDPUtils.getCryptoParameters=function(mediaSection,sessionpart){return SDPUtils.matchPrefix(mediaSection+sessionpart,"a=crypto:").map(SDPUtils.parseCryptoLine)},SDPUtils.getIceParameters=function(mediaSection,sessionpart){var ufrag=SDPUtils.matchPrefix(mediaSection+sessionpart,"a=ice-ufrag:")[0],pwd=SDPUtils.matchPrefix(mediaSection+sessionpart,"a=ice-pwd:")[0];return ufrag&&pwd?{usernameFragment:ufrag.substr(12),password:pwd.substr(10)}:null},SDPUtils.writeIceParameters=function(params){return"a=ice-ufrag:"+params.usernameFragment+"\r\na=ice-pwd:"+params.password+"\r\n"},SDPUtils.parseRtpParameters=function(mediaSection){for(var description={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},mline=SDPUtils.splitLines(mediaSection)[0].split(" "),i=3;i<mline.length;i++){var pt=mline[i],rtpmapline=SDPUtils.matchPrefix(mediaSection,"a=rtpmap:"+pt+" ")[0];if(rtpmapline){var codec=SDPUtils.parseRtpMap(rtpmapline),fmtps=SDPUtils.matchPrefix(mediaSection,"a=fmtp:"+pt+" ");switch(codec.parameters=fmtps.length?SDPUtils.parseFmtp(fmtps[0]):{},codec.rtcpFeedback=SDPUtils.matchPrefix(mediaSection,"a=rtcp-fb:"+pt+" ").map(SDPUtils.parseRtcpFb),description.codecs.push(codec),codec.name.toUpperCase()){case"RED":case"ULPFEC":description.fecMechanisms.push(codec.name.toUpperCase())}}}return SDPUtils.matchPrefix(mediaSection,"a=extmap:").forEach((function(line){description.headerExtensions.push(SDPUtils.parseExtmap(line))})),description},SDPUtils.writeRtpDescription=function(kind,caps){var sdp="";sdp+="m="+kind+" ",sdp+=caps.codecs.length>0?"9":"0",sdp+=" UDP/TLS/RTP/SAVPF ",sdp+=caps.codecs.map((function(codec){return void 0!==codec.preferredPayloadType?codec.preferredPayloadType:codec.payloadType})).join(" ")+"\r\n",sdp+="c=IN IP4 0.0.0.0\r\n",sdp+="a=rtcp:9 IN IP4 0.0.0.0\r\n",caps.codecs.forEach((function(codec){sdp+=SDPUtils.writeRtpMap(codec),sdp+=SDPUtils.writeFmtp(codec),sdp+=SDPUtils.writeRtcpFb(codec)}));var maxptime=0;return caps.codecs.forEach((function(codec){codec.maxptime>maxptime&&(maxptime=codec.maxptime)})),maxptime>0&&(sdp+="a=maxptime:"+maxptime+"\r\n"),sdp+="a=rtcp-mux\r\n",caps.headerExtensions&&caps.headerExtensions.forEach((function(extension){sdp+=SDPUtils.writeExtmap(extension)})),sdp},SDPUtils.parseRtpEncodingParameters=function(mediaSection){var secondarySsrc,encodingParameters=[],description=SDPUtils.parseRtpParameters(mediaSection),hasRed=-1!==description.fecMechanisms.indexOf("RED"),hasUlpfec=-1!==description.fecMechanisms.indexOf("ULPFEC"),ssrcs=SDPUtils.matchPrefix(mediaSection,"a=ssrc:").map((function(line){return SDPUtils.parseSsrcMedia(line)})).filter((function(parts){return"cname"===parts.attribute})),primarySsrc=ssrcs.length>0&&ssrcs[0].ssrc,flows=SDPUtils.matchPrefix(mediaSection,"a=ssrc-group:FID").map((function(line){return line.substr(17).split(" ").map((function(part){return parseInt(part,10)}))}));flows.length>0&&flows[0].length>1&&flows[0][0]===primarySsrc&&(secondarySsrc=flows[0][1]),description.codecs.forEach((function(codec){if("RTX"===codec.name.toUpperCase()&&codec.parameters.apt){var encParam={ssrc:primarySsrc,codecPayloadType:parseInt(codec.parameters.apt,10)};primarySsrc&&secondarySsrc&&(encParam.rtx={ssrc:secondarySsrc}),encodingParameters.push(encParam),hasRed&&((encParam=JSON.parse(JSON.stringify(encParam))).fec={ssrc:primarySsrc,mechanism:hasUlpfec?"red+ulpfec":"red"},encodingParameters.push(encParam))}})),0===encodingParameters.length&&primarySsrc&&encodingParameters.push({ssrc:primarySsrc});var bandwidth=SDPUtils.matchPrefix(mediaSection,"b=");return bandwidth.length&&(bandwidth=0===bandwidth[0].indexOf("b=TIAS:")?parseInt(bandwidth[0].substr(7),10):0===bandwidth[0].indexOf("b=AS:")?1e3*parseInt(bandwidth[0].substr(5),10)*.95-16e3:void 0,encodingParameters.forEach((function(params){params.maxBitrate=bandwidth}))),encodingParameters},SDPUtils.parseRtcpParameters=function(mediaSection){var rtcpParameters={},remoteSsrc=SDPUtils.matchPrefix(mediaSection,"a=ssrc:").map((function(line){return SDPUtils.parseSsrcMedia(line)})).filter((function(obj){return"cname"===obj.attribute}))[0];remoteSsrc&&(rtcpParameters.cname=remoteSsrc.value,rtcpParameters.ssrc=remoteSsrc.ssrc);var rsize=SDPUtils.matchPrefix(mediaSection,"a=rtcp-rsize");rtcpParameters.reducedSize=rsize.length>0,rtcpParameters.compound=0===rsize.length;var mux=SDPUtils.matchPrefix(mediaSection,"a=rtcp-mux");return rtcpParameters.mux=mux.length>0,rtcpParameters},SDPUtils.parseMsid=function(mediaSection){var parts,spec=SDPUtils.matchPrefix(mediaSection,"a=msid:");if(1===spec.length)return{stream:(parts=spec[0].substr(7).split(" "))[0],track:parts[1]};var planB=SDPUtils.matchPrefix(mediaSection,"a=ssrc:").map((function(line){return SDPUtils.parseSsrcMedia(line)})).filter((function(msidParts){return"msid"===msidParts.attribute}));return planB.length>0?{stream:(parts=planB[0].value.split(" "))[0],track:parts[1]}:void 0},SDPUtils.parseSctpDescription=function(mediaSection){var maxMessageSize,mline=SDPUtils.parseMLine(mediaSection),maxSizeLine=SDPUtils.matchPrefix(mediaSection,"a=max-message-size:");maxSizeLine.length>0&&(maxMessageSize=parseInt(maxSizeLine[0].substr(19),10)),isNaN(maxMessageSize)&&(maxMessageSize=65536);var sctpPort=SDPUtils.matchPrefix(mediaSection,"a=sctp-port:");if(sctpPort.length>0)return{port:parseInt(sctpPort[0].substr(12),10),protocol:mline.fmt,maxMessageSize:maxMessageSize};if(SDPUtils.matchPrefix(mediaSection,"a=sctpmap:").length>0){var parts=SDPUtils.matchPrefix(mediaSection,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(parts[0],10),protocol:parts[1],maxMessageSize:maxMessageSize}}},SDPUtils.writeSctpDescription=function(media,sctp){var output=[];return output="DTLS/SCTP"!==media.protocol?["m="+media.kind+" 9 "+media.protocol+" "+sctp.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+sctp.port+"\r\n"]:["m="+media.kind+" 9 "+media.protocol+" "+sctp.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+sctp.port+" "+sctp.protocol+" 65535\r\n"],void 0!==sctp.maxMessageSize&&output.push("a=max-message-size:"+sctp.maxMessageSize+"\r\n"),output.join("")},SDPUtils.generateSessionId=function(){return Math.random().toString().substr(2,21)},SDPUtils.writeSessionBoilerplate=function(sessId,sessVer,sessUser){var version=void 0!==sessVer?sessVer:2;return"v=0\r\no="+(sessUser||"thisisadapterortc")+" "+(sessId||SDPUtils.generateSessionId())+" "+version+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},SDPUtils.writeMediaSection=function(transceiver,caps,type,stream){var sdp=SDPUtils.writeRtpDescription(transceiver.kind,caps);if(sdp+=SDPUtils.writeIceParameters(transceiver.iceGatherer.getLocalParameters()),sdp+=SDPUtils.writeDtlsParameters(transceiver.dtlsTransport.getLocalParameters(),"offer"===type?"actpass":"active"),sdp+="a=mid:"+transceiver.mid+"\r\n",transceiver.direction?sdp+="a="+transceiver.direction+"\r\n":transceiver.rtpSender&&transceiver.rtpReceiver?sdp+="a=sendrecv\r\n":transceiver.rtpSender?sdp+="a=sendonly\r\n":transceiver.rtpReceiver?sdp+="a=recvonly\r\n":sdp+="a=inactive\r\n",transceiver.rtpSender){var msid="msid:"+stream.id+" "+transceiver.rtpSender.track.id+"\r\n";sdp+="a="+msid,sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].ssrc+" "+msid,transceiver.sendEncodingParameters[0].rtx&&(sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].rtx.ssrc+" "+msid,sdp+="a=ssrc-group:FID "+transceiver.sendEncodingParameters[0].ssrc+" "+transceiver.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].ssrc+" cname:"+SDPUtils.localCName+"\r\n",transceiver.rtpSender&&transceiver.sendEncodingParameters[0].rtx&&(sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].rtx.ssrc+" cname:"+SDPUtils.localCName+"\r\n"),sdp},SDPUtils.getDirection=function(mediaSection,sessionpart){for(var lines=SDPUtils.splitLines(mediaSection),i=0;i<lines.length;i++)switch(lines[i]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return lines[i].substr(2)}return sessionpart?SDPUtils.getDirection(sessionpart):"sendrecv"},SDPUtils.getKind=function(mediaSection){return SDPUtils.splitLines(mediaSection)[0].split(" ")[0].substr(2)},SDPUtils.isRejected=function(mediaSection){return"0"===mediaSection.split(" ",2)[1]},SDPUtils.parseMLine=function(mediaSection){var parts=SDPUtils.splitLines(mediaSection)[0].substr(2).split(" ");return{kind:parts[0],port:parseInt(parts[1],10),protocol:parts[2],fmt:parts.slice(3).join(" ")}},SDPUtils.parseOLine=function(mediaSection){var parts=SDPUtils.matchPrefix(mediaSection,"o=")[0].substr(2).split(" ");return{username:parts[0],sessionId:parts[1],sessionVersion:parseInt(parts[2],10),netType:parts[3],addressType:parts[4],address:parts[5]}},SDPUtils.isValidSDP=function(blob){if("string"!=typeof blob||0===blob.length)return!1;for(var lines=SDPUtils.splitLines(blob),i=0;i<lines.length;i++)if(lines[i].length<2||"="!==lines[i].charAt(1))return!1;return!0},"object"===("undefined"==typeof module?"undefined":_typeof(module))&&(module.exports=SDPUtils)},{}],7:[function(require,module,exports){(function(setImmediate,clearImmediate){(function(){var nextTick=require("process/browser.js").nextTick,apply=Function.prototype.apply,slice=Array.prototype.slice,immediateIds={},nextImmediateId=0;function Timeout(id,clearFn){this._id=id,this._clearFn=clearFn}exports.setTimeout=function(){return new Timeout(apply.call(setTimeout,window,arguments),clearTimeout)},exports.setInterval=function(){return new Timeout(apply.call(setInterval,window,arguments),clearInterval)},exports.clearTimeout=exports.clearInterval=function(timeout){timeout.close()},Timeout.prototype.unref=Timeout.prototype.ref=function(){},Timeout.prototype.close=function(){this._clearFn.call(window,this._id)},exports.enroll=function(item,msecs){clearTimeout(item._idleTimeoutId),item._idleTimeout=msecs},exports.unenroll=function(item){clearTimeout(item._idleTimeoutId),item._idleTimeout=-1},exports._unrefActive=exports.active=function(item){clearTimeout(item._idleTimeoutId);var msecs=item._idleTimeout;msecs>=0&&(item._idleTimeoutId=setTimeout((function(){item._onTimeout&&item._onTimeout()}),msecs))},exports.setImmediate="function"==typeof setImmediate?setImmediate:function(fn){var id=nextImmediateId++,args=!(arguments.length<2)&&slice.call(arguments,1);return immediateIds[id]=!0,nextTick((function(){immediateIds[id]&&(args?fn.apply(null,args):fn.call(null),exports.clearImmediate(id))})),id},exports.clearImmediate="function"==typeof clearImmediate?clearImmediate:function(id){delete immediateIds[id]}}).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate)},{"process/browser.js":3,timers:7}],8:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"v1",{enumerable:!0,get:function(){return _v.default}}),Object.defineProperty(exports,"v3",{enumerable:!0,get:function(){return _v2.default}}),Object.defineProperty(exports,"v4",{enumerable:!0,get:function(){return _v3.default}}),Object.defineProperty(exports,"v5",{enumerable:!0,get:function(){return _v4.default}}),Object.defineProperty(exports,"NIL",{enumerable:!0,get:function(){return _nil.default}}),Object.defineProperty(exports,"version",{enumerable:!0,get:function(){return _version.default}}),Object.defineProperty(exports,"validate",{enumerable:!0,get:function(){return _validate.default}}),Object.defineProperty(exports,"stringify",{enumerable:!0,get:function(){return _stringify.default}}),Object.defineProperty(exports,"parse",{enumerable:!0,get:function(){return _parse.default}});var _v=_interopRequireDefault(require("./v1.js")),_v2=_interopRequireDefault(require("./v3.js")),_v3=_interopRequireDefault(require("./v4.js")),_v4=_interopRequireDefault(require("./v5.js")),_nil=_interopRequireDefault(require("./nil.js")),_version=_interopRequireDefault(require("./version.js")),_validate=_interopRequireDefault(require("./validate.js")),_stringify=_interopRequireDefault(require("./stringify.js")),_parse=_interopRequireDefault(require("./parse.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}},{"./nil.js":10,"./parse.js":11,"./stringify.js":15,"./v1.js":16,"./v3.js":17,"./v4.js":19,"./v5.js":20,"./validate.js":21,"./version.js":22}],9:[function(require,module,exports){"use strict";function getOutputLength(inputLength8){return 14+(inputLength8+64>>>9<<4)+1}function safeAdd(x,y){var lsw=(65535&x)+(65535&y);return(x>>16)+(y>>16)+(lsw>>16)<<16|65535&lsw}function md5cmn(q,a,b,x,s,t){return safeAdd((num=safeAdd(safeAdd(a,q),safeAdd(x,t)))<<(cnt=s)|num>>>32-cnt,b);var num,cnt}function md5ff(a,b,c,d,x,s,t){return md5cmn(b&c|~b&d,a,b,x,s,t)}function md5gg(a,b,c,d,x,s,t){return md5cmn(b&d|c&~d,a,b,x,s,t)}function md5hh(a,b,c,d,x,s,t){return md5cmn(b^c^d,a,b,x,s,t)}function md5ii(a,b,c,d,x,s,t){return md5cmn(c^(b|~d),a,b,x,s,t)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _default=function(bytes){if("string"==typeof bytes){var msg=unescape(encodeURIComponent(bytes));bytes=new Uint8Array(msg.length);for(var i=0;i<msg.length;++i)bytes[i]=msg.charCodeAt(i)}return function(input){for(var output=[],length32=32*input.length,i=0;i<length32;i+=8){var x=input[i>>5]>>>i%32&255,hex=parseInt("0123456789abcdef".charAt(x>>>4&15)+"0123456789abcdef".charAt(15&x),16);output.push(hex)}return output}(function(x,len){x[len>>5]|=128<<len%32,x[getOutputLength(len)-1]=len;for(var a=1732584193,b=-271733879,c=-1732584194,d=271733878,i=0;i<x.length;i+=16){var olda=a,oldb=b,oldc=c,oldd=d;a=md5ff(a,b,c,d,x[i],7,-680876936),d=md5ff(d,a,b,c,x[i+1],12,-389564586),c=md5ff(c,d,a,b,x[i+2],17,606105819),b=md5ff(b,c,d,a,x[i+3],22,-1044525330),a=md5ff(a,b,c,d,x[i+4],7,-176418897),d=md5ff(d,a,b,c,x[i+5],12,1200080426),c=md5ff(c,d,a,b,x[i+6],17,-1473231341),b=md5ff(b,c,d,a,x[i+7],22,-45705983),a=md5ff(a,b,c,d,x[i+8],7,1770035416),d=md5ff(d,a,b,c,x[i+9],12,-1958414417),c=md5ff(c,d,a,b,x[i+10],17,-42063),b=md5ff(b,c,d,a,x[i+11],22,-1990404162),a=md5ff(a,b,c,d,x[i+12],7,1804603682),d=md5ff(d,a,b,c,x[i+13],12,-40341101),c=md5ff(c,d,a,b,x[i+14],17,-1502002290),b=md5ff(b,c,d,a,x[i+15],22,1236535329),a=md5gg(a,b,c,d,x[i+1],5,-165796510),d=md5gg(d,a,b,c,x[i+6],9,-1069501632),c=md5gg(c,d,a,b,x[i+11],14,643717713),b=md5gg(b,c,d,a,x[i],20,-373897302),a=md5gg(a,b,c,d,x[i+5],5,-701558691),d=md5gg(d,a,b,c,x[i+10],9,38016083),c=md5gg(c,d,a,b,x[i+15],14,-660478335),b=md5gg(b,c,d,a,x[i+4],20,-405537848),a=md5gg(a,b,c,d,x[i+9],5,568446438),d=md5gg(d,a,b,c,x[i+14],9,-1019803690),c=md5gg(c,d,a,b,x[i+3],14,-187363961),b=md5gg(b,c,d,a,x[i+8],20,1163531501),a=md5gg(a,b,c,d,x[i+13],5,-1444681467),d=md5gg(d,a,b,c,x[i+2],9,-51403784),c=md5gg(c,d,a,b,x[i+7],14,1735328473),b=md5gg(b,c,d,a,x[i+12],20,-1926607734),a=md5hh(a,b,c,d,x[i+5],4,-378558),d=md5hh(d,a,b,c,x[i+8],11,-2022574463),c=md5hh(c,d,a,b,x[i+11],16,1839030562),b=md5hh(b,c,d,a,x[i+14],23,-35309556),a=md5hh(a,b,c,d,x[i+1],4,-1530992060),d=md5hh(d,a,b,c,x[i+4],11,1272893353),c=md5hh(c,d,a,b,x[i+7],16,-155497632),b=md5hh(b,c,d,a,x[i+10],23,-1094730640),a=md5hh(a,b,c,d,x[i+13],4,681279174),d=md5hh(d,a,b,c,x[i],11,-358537222),c=md5hh(c,d,a,b,x[i+3],16,-722521979),b=md5hh(b,c,d,a,x[i+6],23,76029189),a=md5hh(a,b,c,d,x[i+9],4,-640364487),d=md5hh(d,a,b,c,x[i+12],11,-421815835),c=md5hh(c,d,a,b,x[i+15],16,530742520),b=md5hh(b,c,d,a,x[i+2],23,-995338651),a=md5ii(a,b,c,d,x[i],6,-198630844),d=md5ii(d,a,b,c,x[i+7],10,1126891415),c=md5ii(c,d,a,b,x[i+14],15,-1416354905),b=md5ii(b,c,d,a,x[i+5],21,-57434055),a=md5ii(a,b,c,d,x[i+12],6,1700485571),d=md5ii(d,a,b,c,x[i+3],10,-1894986606),c=md5ii(c,d,a,b,x[i+10],15,-1051523),b=md5ii(b,c,d,a,x[i+1],21,-2054922799),a=md5ii(a,b,c,d,x[i+8],6,1873313359),d=md5ii(d,a,b,c,x[i+15],10,-30611744),c=md5ii(c,d,a,b,x[i+6],15,-1560198380),b=md5ii(b,c,d,a,x[i+13],21,1309151649),a=md5ii(a,b,c,d,x[i+4],6,-145523070),d=md5ii(d,a,b,c,x[i+11],10,-1120210379),c=md5ii(c,d,a,b,x[i+2],15,718787259),b=md5ii(b,c,d,a,x[i+9],21,-343485551),a=safeAdd(a,olda),b=safeAdd(b,oldb),c=safeAdd(c,oldc),d=safeAdd(d,oldd)}return[a,b,c,d]}(function(input){if(0===input.length)return[];for(var length8=8*input.length,output=new Uint32Array(getOutputLength(length8)),i=0;i<length8;i+=8)output[i>>5]|=(255&input[i/8])<<i%32;return output}(bytes),8*bytes.length))};exports.default=_default},{}],10:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;exports.default="00000000-0000-0000-0000-000000000000"},{}],11:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var obj,_validate=(obj=require("./validate.js"))&&obj.__esModule?obj:{default:obj};var _default=function(uuid){if(!(0,_validate.default)(uuid))throw TypeError("Invalid UUID");var v,arr=new Uint8Array(16);return arr[0]=(v=parseInt(uuid.slice(0,8),16))>>>24,arr[1]=v>>>16&255,arr[2]=v>>>8&255,arr[3]=255&v,arr[4]=(v=parseInt(uuid.slice(9,13),16))>>>8,arr[5]=255&v,arr[6]=(v=parseInt(uuid.slice(14,18),16))>>>8,arr[7]=255&v,arr[8]=(v=parseInt(uuid.slice(19,23),16))>>>8,arr[9]=255&v,arr[10]=(v=parseInt(uuid.slice(24,36),16))/1099511627776&255,arr[11]=v/4294967296&255,arr[12]=v>>>24&255,arr[13]=v>>>16&255,arr[14]=v>>>8&255,arr[15]=255&v,arr};exports.default=_default},{"./validate.js":21}],12:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;exports.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i},{}],13:[function(require,module,exports){"use strict";var getRandomValues;Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(){if(!getRandomValues&&!(getRandomValues="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return getRandomValues(rnds8)};var rnds8=new Uint8Array(16)},{}],14:[function(require,module,exports){"use strict";function f(s,x,y,z){switch(s){case 0:return x&y^~x&z;case 1:return x^y^z;case 2:return x&y^x&z^y&z;case 3:return x^y^z}}function ROTL(x,n){return x<<n|x>>>32-n}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _default=function(bytes){var K=[1518500249,1859775393,2400959708,3395469782],H=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof bytes){var msg=unescape(encodeURIComponent(bytes));bytes=[];for(var i=0;i<msg.length;++i)bytes.push(msg.charCodeAt(i))}else Array.isArray(bytes)||(bytes=Array.prototype.slice.call(bytes));bytes.push(128);for(var l=bytes.length/4+2,N=Math.ceil(l/16),M=new Array(N),_i=0;_i<N;++_i){for(var arr=new Uint32Array(16),j=0;j<16;++j)arr[j]=bytes[64*_i+4*j]<<24|bytes[64*_i+4*j+1]<<16|bytes[64*_i+4*j+2]<<8|bytes[64*_i+4*j+3];M[_i]=arr}M[N-1][14]=8*(bytes.length-1)/Math.pow(2,32),M[N-1][14]=Math.floor(M[N-1][14]),M[N-1][15]=8*(bytes.length-1)&4294967295;for(var _i2=0;_i2<N;++_i2){for(var W=new Uint32Array(80),t=0;t<16;++t)W[t]=M[_i2][t];for(var _t=16;_t<80;++_t)W[_t]=ROTL(W[_t-3]^W[_t-8]^W[_t-14]^W[_t-16],1);for(var a=H[0],b=H[1],c=H[2],d=H[3],e=H[4],_t2=0;_t2<80;++_t2){var s=Math.floor(_t2/20),T=ROTL(a,5)+f(s,b,c,d)+e+K[s]+W[_t2]>>>0;e=d,d=c,c=ROTL(b,30)>>>0,b=a,a=T}H[0]=H[0]+a>>>0,H[1]=H[1]+b>>>0,H[2]=H[2]+c>>>0,H[3]=H[3]+d>>>0,H[4]=H[4]+e>>>0}return[H[0]>>24&255,H[0]>>16&255,H[0]>>8&255,255&H[0],H[1]>>24&255,H[1]>>16&255,H[1]>>8&255,255&H[1],H[2]>>24&255,H[2]>>16&255,H[2]>>8&255,255&H[2],H[3]>>24&255,H[3]>>16&255,H[3]>>8&255,255&H[3],H[4]>>24&255,H[4]>>16&255,H[4]>>8&255,255&H[4]]};exports.default=_default},{}],15:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var obj,_validate=(obj=require("./validate.js"))&&obj.__esModule?obj:{default:obj};for(var byteToHex=[],i=0;i<256;++i)byteToHex.push((i+256).toString(16).substr(1));var _default=function(arr){var offset=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,uuid=(byteToHex[arr[offset+0]]+byteToHex[arr[offset+1]]+byteToHex[arr[offset+2]]+byteToHex[arr[offset+3]]+"-"+byteToHex[arr[offset+4]]+byteToHex[arr[offset+5]]+"-"+byteToHex[arr[offset+6]]+byteToHex[arr[offset+7]]+"-"+byteToHex[arr[offset+8]]+byteToHex[arr[offset+9]]+"-"+byteToHex[arr[offset+10]]+byteToHex[arr[offset+11]]+byteToHex[arr[offset+12]]+byteToHex[arr[offset+13]]+byteToHex[arr[offset+14]]+byteToHex[arr[offset+15]]).toLowerCase();if(!(0,_validate.default)(uuid))throw TypeError("Stringified UUID is invalid");return uuid};exports.default=_default},{"./validate.js":21}],16:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _nodeId,_clockseq,_rng=_interopRequireDefault(require("./rng.js")),_stringify=_interopRequireDefault(require("./stringify.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _lastMSecs=0,_lastNSecs=0;var _default=function(options,buf,offset){var i=buf&&offset||0,b=buf||new Array(16),node=(options=options||{}).node||_nodeId,clockseq=void 0!==options.clockseq?options.clockseq:_clockseq;if(null==node||null==clockseq){var seedBytes=options.random||(options.rng||_rng.default)();null==node&&(node=_nodeId=[1|seedBytes[0],seedBytes[1],seedBytes[2],seedBytes[3],seedBytes[4],seedBytes[5]]),null==clockseq&&(clockseq=_clockseq=16383&(seedBytes[6]<<8|seedBytes[7]))}var msecs=void 0!==options.msecs?options.msecs:Date.now(),nsecs=void 0!==options.nsecs?options.nsecs:_lastNSecs+1,dt=msecs-_lastMSecs+(nsecs-_lastNSecs)/1e4;if(dt<0&&void 0===options.clockseq&&(clockseq=clockseq+1&16383),(dt<0||msecs>_lastMSecs)&&void 0===options.nsecs&&(nsecs=0),nsecs>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");_lastMSecs=msecs,_lastNSecs=nsecs,_clockseq=clockseq;var tl=(1e4*(268435455&(msecs+=122192928e5))+nsecs)%4294967296;b[i++]=tl>>>24&255,b[i++]=tl>>>16&255,b[i++]=tl>>>8&255,b[i++]=255&tl;var tmh=msecs/4294967296*1e4&268435455;b[i++]=tmh>>>8&255,b[i++]=255&tmh,b[i++]=tmh>>>24&15|16,b[i++]=tmh>>>16&255,b[i++]=clockseq>>>8|128,b[i++]=255&clockseq;for(var n=0;n<6;++n)b[i+n]=node[n];return buf||(0,_stringify.default)(b)};exports.default=_default},{"./rng.js":13,"./stringify.js":15}],17:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _v=_interopRequireDefault(require("./v35.js")),_md=_interopRequireDefault(require("./md5.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _default=(0,_v.default)("v3",48,_md.default);exports.default=_default},{"./md5.js":9,"./v35.js":18}],18:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(name,version,hashfunc){function generateUUID(value,namespace,buf,offset){if("string"==typeof value&&(value=function(str){str=unescape(encodeURIComponent(str));for(var bytes=[],i=0;i<str.length;++i)bytes.push(str.charCodeAt(i));return bytes}(value)),"string"==typeof namespace&&(namespace=(0,_parse.default)(namespace)),16!==namespace.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var bytes=new Uint8Array(16+value.length);if(bytes.set(namespace),bytes.set(value,namespace.length),(bytes=hashfunc(bytes))[6]=15&bytes[6]|version,bytes[8]=63&bytes[8]|128,buf){offset=offset||0;for(var i=0;i<16;++i)buf[offset+i]=bytes[i];return buf}return(0,_stringify.default)(bytes)}try{generateUUID.name=name}catch(err){}return generateUUID.DNS=DNS,generateUUID.URL=URL,generateUUID},exports.URL=exports.DNS=void 0;var _stringify=_interopRequireDefault(require("./stringify.js")),_parse=_interopRequireDefault(require("./parse.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8";exports.DNS=DNS;var URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8";exports.URL=URL},{"./parse.js":11,"./stringify.js":15}],19:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _rng=_interopRequireDefault(require("./rng.js")),_stringify=_interopRequireDefault(require("./stringify.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _default=function(options,buf,offset){var rnds=(options=options||{}).random||(options.rng||_rng.default)();if(rnds[6]=15&rnds[6]|64,rnds[8]=63&rnds[8]|128,buf){offset=offset||0;for(var i=0;i<16;++i)buf[offset+i]=rnds[i];return buf}return(0,_stringify.default)(rnds)};exports.default=_default},{"./rng.js":13,"./stringify.js":15}],20:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _v=_interopRequireDefault(require("./v35.js")),_sha=_interopRequireDefault(require("./sha1.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _default=(0,_v.default)("v5",80,_sha.default);exports.default=_default},{"./sha1.js":14,"./v35.js":18}],21:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var obj,_regex=(obj=require("./regex.js"))&&obj.__esModule?obj:{default:obj};var _default=function(uuid){return"string"==typeof uuid&&_regex.default.test(uuid)};exports.default=_default},{"./regex.js":12}],22:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var obj,_validate=(obj=require("./validate.js"))&&obj.__esModule?obj:{default:obj};var _default=function(uuid){if(!(0,_validate.default)(uuid))throw TypeError("Invalid UUID");return parseInt(uuid.substr(14,1),16)};exports.default=_default},{"./validate.js":21}],23:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var adapter=(0,require("./adapter_factory.js").adapterFactory)({window:"undefined"==typeof window?void 0:window});exports.default=adapter},{"./adapter_factory.js":24}],24:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.adapterFactory=function(){var _ref=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},window=_ref.window,options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0},logging=utils.log,browserDetails=utils.detectBrowser(window),adapter={browserDetails:browserDetails,commonShim:commonShim,extractVersion:utils.extractVersion,disableLog:utils.disableLog,disableWarnings:utils.disableWarnings};switch(browserDetails.browser){case"chrome":if(!chromeShim||!chromeShim.shimPeerConnection||!options.shimChrome)return logging("Chrome shim is not included in this adapter release."),adapter;if(null===browserDetails.version)return logging("Chrome shim can not determine version, not shimming."),adapter;logging("adapter.js shimming chrome."),adapter.browserShim=chromeShim,commonShim.shimAddIceCandidateNullOrEmpty(window,browserDetails),chromeShim.shimGetUserMedia(window,browserDetails),chromeShim.shimMediaStream(window,browserDetails),chromeShim.shimPeerConnection(window,browserDetails),chromeShim.shimOnTrack(window,browserDetails),chromeShim.shimAddTrackRemoveTrack(window,browserDetails),chromeShim.shimGetSendersWithDtmf(window,browserDetails),chromeShim.shimGetStats(window,browserDetails),chromeShim.shimSenderReceiverGetStats(window,browserDetails),chromeShim.fixNegotiationNeeded(window,browserDetails),commonShim.shimRTCIceCandidate(window,browserDetails),commonShim.shimConnectionState(window,browserDetails),commonShim.shimMaxMessageSize(window,browserDetails),commonShim.shimSendThrowTypeError(window,browserDetails),commonShim.removeExtmapAllowMixed(window,browserDetails);break;case"firefox":if(!firefoxShim||!firefoxShim.shimPeerConnection||!options.shimFirefox)return logging("Firefox shim is not included in this adapter release."),adapter;logging("adapter.js shimming firefox."),adapter.browserShim=firefoxShim,commonShim.shimAddIceCandidateNullOrEmpty(window,browserDetails),firefoxShim.shimGetUserMedia(window,browserDetails),firefoxShim.shimPeerConnection(window,browserDetails),firefoxShim.shimOnTrack(window,browserDetails),firefoxShim.shimRemoveStream(window,browserDetails),firefoxShim.shimSenderGetStats(window,browserDetails),firefoxShim.shimReceiverGetStats(window,browserDetails),firefoxShim.shimRTCDataChannel(window,browserDetails),firefoxShim.shimAddTransceiver(window,browserDetails),firefoxShim.shimGetParameters(window,browserDetails),firefoxShim.shimCreateOffer(window,browserDetails),firefoxShim.shimCreateAnswer(window,browserDetails),commonShim.shimRTCIceCandidate(window,browserDetails),commonShim.shimConnectionState(window,browserDetails),commonShim.shimMaxMessageSize(window,browserDetails),commonShim.shimSendThrowTypeError(window,browserDetails);break;case"edge":if(!edgeShim||!edgeShim.shimPeerConnection||!options.shimEdge)return logging("MS edge shim is not included in this adapter release."),adapter;logging("adapter.js shimming edge."),adapter.browserShim=edgeShim,edgeShim.shimGetUserMedia(window,browserDetails),edgeShim.shimGetDisplayMedia(window,browserDetails),edgeShim.shimPeerConnection(window,browserDetails),edgeShim.shimReplaceTrack(window,browserDetails),commonShim.shimMaxMessageSize(window,browserDetails),commonShim.shimSendThrowTypeError(window,browserDetails);break;case"safari":if(!safariShim||!options.shimSafari)return logging("Safari shim is not included in this adapter release."),adapter;logging("adapter.js shimming safari."),adapter.browserShim=safariShim,commonShim.shimAddIceCandidateNullOrEmpty(window,browserDetails),safariShim.shimRTCIceServerUrls(window,browserDetails),safariShim.shimCreateOfferLegacy(window,browserDetails),safariShim.shimCallbacksAPI(window,browserDetails),safariShim.shimLocalStreamsAPI(window,browserDetails),safariShim.shimRemoteStreamsAPI(window,browserDetails),safariShim.shimTrackEventTransceiver(window,browserDetails),safariShim.shimGetUserMedia(window,browserDetails),safariShim.shimAudioContext(window,browserDetails),commonShim.shimRTCIceCandidate(window,browserDetails),commonShim.shimMaxMessageSize(window,browserDetails),commonShim.shimSendThrowTypeError(window,browserDetails),commonShim.removeExtmapAllowMixed(window,browserDetails);break;default:logging("Unsupported browser!")}return adapter};var utils=_interopRequireWildcard(require("./utils")),chromeShim=_interopRequireWildcard(require("./chrome/chrome_shim")),edgeShim=_interopRequireWildcard(require("./edge/edge_shim")),firefoxShim=_interopRequireWildcard(require("./firefox/firefox_shim")),safariShim=_interopRequireWildcard(require("./safari/safari_shim")),commonShim=_interopRequireWildcard(require("./common_shim"));function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}},{"./chrome/chrome_shim":25,"./common_shim":28,"./edge/edge_shim":29,"./firefox/firefox_shim":33,"./safari/safari_shim":36,"./utils":37}],25:[function(require,module,exports){"use strict";function _typeof2(o){return(_typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=exports.shimGetUserMedia=void 0;var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(obj){return _typeof2(obj)}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":_typeof2(obj)},_getusermedia=require("./getusermedia");Object.defineProperty(exports,"shimGetUserMedia",{enumerable:!0,get:function(){return _getusermedia.shimGetUserMedia}});var _getdisplaymedia=require("./getdisplaymedia");Object.defineProperty(exports,"shimGetDisplayMedia",{enumerable:!0,get:function(){return _getdisplaymedia.shimGetDisplayMedia}}),exports.shimMediaStream=function(window){window.MediaStream=window.MediaStream||window.webkitMediaStream},exports.shimOnTrack=function(window){if("object"===("undefined"==typeof window?"undefined":_typeof(window))&&window.RTCPeerConnection&&!("ontrack"in window.RTCPeerConnection.prototype)){Object.defineProperty(window.RTCPeerConnection.prototype,"ontrack",{get:function(){return this._ontrack},set:function(f){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=f)},enumerable:!0,configurable:!0});var origSetRemoteDescription=window.RTCPeerConnection.prototype.setRemoteDescription;window.RTCPeerConnection.prototype.setRemoteDescription=function(){var _this=this;return this._ontrackpoly||(this._ontrackpoly=function(e){e.stream.addEventListener("addtrack",(function(te){var receiver=void 0;receiver=window.RTCPeerConnection.prototype.getReceivers?_this.getReceivers().find((function(r){return r.track&&r.track.id===te.track.id})):{track:te.track};var event=new Event("track");event.track=te.track,event.receiver=receiver,event.transceiver={receiver:receiver},event.streams=[e.stream],_this.dispatchEvent(event)})),e.stream.getTracks().forEach((function(track){var receiver=void 0;receiver=window.RTCPeerConnection.prototype.getReceivers?_this.getReceivers().find((function(r){return r.track&&r.track.id===track.id})):{track:track};var event=new Event("track");event.track=track,event.receiver=receiver,event.transceiver={receiver:receiver},event.streams=[e.stream],_this.dispatchEvent(event)}))},this.addEventListener("addstream",this._ontrackpoly)),origSetRemoteDescription.apply(this,arguments)}}else utils.wrapPeerConnectionEvent(window,"track",(function(e){return e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e}))},exports.shimGetSendersWithDtmf=function(window){if("object"===("undefined"==typeof window?"undefined":_typeof(window))&&window.RTCPeerConnection&&!("getSenders"in window.RTCPeerConnection.prototype)&&"createDTMFSender"in window.RTCPeerConnection.prototype){var shimSenderWithDtmf=function(pc,track){return{track:track,get dtmf(){return void 0===this._dtmf&&("audio"===track.kind?this._dtmf=pc.createDTMFSender(track):this._dtmf=null),this._dtmf},_pc:pc}};if(!window.RTCPeerConnection.prototype.getSenders){window.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};var origAddTrack=window.RTCPeerConnection.prototype.addTrack;window.RTCPeerConnection.prototype.addTrack=function(track,stream){var sender=origAddTrack.apply(this,arguments);return sender||(sender=shimSenderWithDtmf(this,track),this._senders.push(sender)),sender};var origRemoveTrack=window.RTCPeerConnection.prototype.removeTrack;window.RTCPeerConnection.prototype.removeTrack=function(sender){origRemoveTrack.apply(this,arguments);var idx=this._senders.indexOf(sender);-1!==idx&&this._senders.splice(idx,1)}}var origAddStream=window.RTCPeerConnection.prototype.addStream;window.RTCPeerConnection.prototype.addStream=function(stream){var _this2=this;this._senders=this._senders||[],origAddStream.apply(this,[stream]),stream.getTracks().forEach((function(track){_this2._senders.push(shimSenderWithDtmf(_this2,track))}))};var origRemoveStream=window.RTCPeerConnection.prototype.removeStream;window.RTCPeerConnection.prototype.removeStream=function(stream){var _this3=this;this._senders=this._senders||[],origRemoveStream.apply(this,[stream]),stream.getTracks().forEach((function(track){var sender=_this3._senders.find((function(s){return s.track===track}));sender&&_this3._senders.splice(_this3._senders.indexOf(sender),1)}))}}else if("object"===("undefined"==typeof window?"undefined":_typeof(window))&&window.RTCPeerConnection&&"getSenders"in window.RTCPeerConnection.prototype&&"createDTMFSender"in window.RTCPeerConnection.prototype&&window.RTCRtpSender&&!("dtmf"in window.RTCRtpSender.prototype)){var origGetSenders=window.RTCPeerConnection.prototype.getSenders;window.RTCPeerConnection.prototype.getSenders=function(){var _this4=this,senders=origGetSenders.apply(this,[]);return senders.forEach((function(sender){return sender._pc=_this4})),senders},Object.defineProperty(window.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}})}},exports.shimGetStats=function(window){if(!window.RTCPeerConnection)return;var origGetStats=window.RTCPeerConnection.prototype.getStats;window.RTCPeerConnection.prototype.getStats=function(){var _this5=this,_arguments=Array.prototype.slice.call(arguments),selector=_arguments[0],onSucc=_arguments[1],onErr=_arguments[2];if(arguments.length>0&&"function"==typeof selector)return origGetStats.apply(this,arguments);if(0===origGetStats.length&&(0===arguments.length||"function"!=typeof selector))return origGetStats.apply(this,[]);var fixChromeStats_=function(response){var standardReport={};return response.result().forEach((function(report){var standardStats={id:report.id,timestamp:report.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[report.type]||report.type};report.names().forEach((function(name){standardStats[name]=report.stat(name)})),standardReport[standardStats.id]=standardStats})),standardReport},makeMapStats=function(stats){return new Map(Object.keys(stats).map((function(key){return[key,stats[key]]})))};if(arguments.length>=2){var successCallbackWrapper_=function(response){onSucc(makeMapStats(fixChromeStats_(response)))};return origGetStats.apply(this,[successCallbackWrapper_,selector])}return new Promise((function(resolve,reject){origGetStats.apply(_this5,[function(response){resolve(makeMapStats(fixChromeStats_(response)))},reject])})).then(onSucc,onErr)}},exports.shimSenderReceiverGetStats=function(window){if(!("object"===("undefined"==typeof window?"undefined":_typeof(window))&&window.RTCPeerConnection&&window.RTCRtpSender&&window.RTCRtpReceiver))return;if(!("getStats"in window.RTCRtpSender.prototype)){var origGetSenders=window.RTCPeerConnection.prototype.getSenders;origGetSenders&&(window.RTCPeerConnection.prototype.getSenders=function(){var _this6=this,senders=origGetSenders.apply(this,[]);return senders.forEach((function(sender){return sender._pc=_this6})),senders});var origAddTrack=window.RTCPeerConnection.prototype.addTrack;origAddTrack&&(window.RTCPeerConnection.prototype.addTrack=function(){var sender=origAddTrack.apply(this,arguments);return sender._pc=this,sender}),window.RTCRtpSender.prototype.getStats=function(){var sender=this;return this._pc.getStats().then((function(result){return utils.filterStats(result,sender.track,!0)}))}}if(!("getStats"in window.RTCRtpReceiver.prototype)){var origGetReceivers=window.RTCPeerConnection.prototype.getReceivers;origGetReceivers&&(window.RTCPeerConnection.prototype.getReceivers=function(){var _this7=this,receivers=origGetReceivers.apply(this,[]);return receivers.forEach((function(receiver){return receiver._pc=_this7})),receivers}),utils.wrapPeerConnectionEvent(window,"track",(function(e){return e.receiver._pc=e.srcElement,e})),window.RTCRtpReceiver.prototype.getStats=function(){var receiver=this;return this._pc.getStats().then((function(result){return utils.filterStats(result,receiver.track,!1)}))}}if(!("getStats"in window.RTCRtpSender.prototype)||!("getStats"in window.RTCRtpReceiver.prototype))return;var origGetStats=window.RTCPeerConnection.prototype.getStats;window.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof window.MediaStreamTrack){var track=arguments[0],sender=void 0,receiver=void 0,err=void 0;return this.getSenders().forEach((function(s){s.track===track&&(sender?err=!0:sender=s)})),this.getReceivers().forEach((function(r){return r.track===track&&(receiver?err=!0:receiver=r),r.track===track})),err||sender&&receiver?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):sender?sender.getStats():receiver?receiver.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return origGetStats.apply(this,arguments)}},exports.shimAddTrackRemoveTrackWithNative=shimAddTrackRemoveTrackWithNative,exports.shimAddTrackRemoveTrack=function(window,browserDetails){if(!window.RTCPeerConnection)return;if(window.RTCPeerConnection.prototype.addTrack&&browserDetails.version>=65)return shimAddTrackRemoveTrackWithNative(window);var origGetLocalStreams=window.RTCPeerConnection.prototype.getLocalStreams;window.RTCPeerConnection.prototype.getLocalStreams=function(){var _this11=this,nativeStreams=origGetLocalStreams.apply(this);return this._reverseStreams=this._reverseStreams||{},nativeStreams.map((function(stream){return _this11._reverseStreams[stream.id]}))};var origAddStream=window.RTCPeerConnection.prototype.addStream;window.RTCPeerConnection.prototype.addStream=function(stream){var _this12=this;if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},stream.getTracks().forEach((function(track){if(_this12.getSenders().find((function(s){return s.track===track})))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[stream.id]){var newStream=new window.MediaStream(stream.getTracks());this._streams[stream.id]=newStream,this._reverseStreams[newStream.id]=stream,stream=newStream}origAddStream.apply(this,[stream])};var origRemoveStream=window.RTCPeerConnection.prototype.removeStream;function replaceInternalStreamId(pc,description){var sdp=description.sdp;return Object.keys(pc._reverseStreams||[]).forEach((function(internalId){var externalStream=pc._reverseStreams[internalId],internalStream=pc._streams[externalStream.id];sdp=sdp.replace(new RegExp(internalStream.id,"g"),externalStream.id)})),new RTCSessionDescription({type:description.type,sdp:sdp})}function replaceExternalStreamId(pc,description){var sdp=description.sdp;return Object.keys(pc._reverseStreams||[]).forEach((function(internalId){var externalStream=pc._reverseStreams[internalId],internalStream=pc._streams[externalStream.id];sdp=sdp.replace(new RegExp(externalStream.id,"g"),internalStream.id)})),new RTCSessionDescription({type:description.type,sdp:sdp})}window.RTCPeerConnection.prototype.removeStream=function(stream){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},origRemoveStream.apply(this,[this._streams[stream.id]||stream]),delete this._reverseStreams[this._streams[stream.id]?this._streams[stream.id].id:stream.id],delete this._streams[stream.id]},window.RTCPeerConnection.prototype.addTrack=function(track,stream){var _this13=this;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");var streams=[].slice.call(arguments,1);if(1!==streams.length||!streams[0].getTracks().find((function(t){return t===track})))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");var alreadyExists=this.getSenders().find((function(s){return s.track===track}));if(alreadyExists)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};var oldStream=this._streams[stream.id];if(oldStream)oldStream.addTrack(track),Promise.resolve().then((function(){_this13.dispatchEvent(new Event("negotiationneeded"))}));else{var newStream=new window.MediaStream([track]);this._streams[stream.id]=newStream,this._reverseStreams[newStream.id]=stream,this.addStream(newStream)}return this.getSenders().find((function(s){return s.track===track}))},["createOffer","createAnswer"].forEach((function(method){var nativeMethod=window.RTCPeerConnection.prototype[method],methodObj=_defineProperty({},method,(function(){var _this14=this,args=arguments,isLegacyCall=arguments.length&&"function"==typeof arguments[0];return isLegacyCall?nativeMethod.apply(this,[function(description){var desc=replaceInternalStreamId(_this14,description);args[0].apply(null,[desc])},function(err){args[1]&&args[1].apply(null,err)},arguments[2]]):nativeMethod.apply(this,arguments).then((function(description){return replaceInternalStreamId(_this14,description)}))}));window.RTCPeerConnection.prototype[method]=methodObj[method]}));var origSetLocalDescription=window.RTCPeerConnection.prototype.setLocalDescription;window.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=replaceExternalStreamId(this,arguments[0]),origSetLocalDescription.apply(this,arguments)):origSetLocalDescription.apply(this,arguments)};var origLocalDescription=Object.getOwnPropertyDescriptor(window.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(window.RTCPeerConnection.prototype,"localDescription",{get:function(){var description=origLocalDescription.get.apply(this);return""===description.type?description:replaceInternalStreamId(this,description)}}),window.RTCPeerConnection.prototype.removeTrack=function(sender){var _this15=this;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!sender._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(sender._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};var stream=void 0;Object.keys(this._streams).forEach((function(streamid){_this15._streams[streamid].getTracks().find((function(track){return sender.track===track}))&&(stream=_this15._streams[streamid])})),stream&&(1===stream.getTracks().length?this.removeStream(this._reverseStreams[stream.id]):stream.removeTrack(sender.track),this.dispatchEvent(new Event("negotiationneeded")))}},exports.shimPeerConnection=function(window,browserDetails){!window.RTCPeerConnection&&window.webkitRTCPeerConnection&&(window.RTCPeerConnection=window.webkitRTCPeerConnection);if(!window.RTCPeerConnection)return;browserDetails.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(method){var nativeMethod=window.RTCPeerConnection.prototype[method],methodObj=_defineProperty({},method,(function(){return arguments[0]=new("addIceCandidate"===method?window.RTCIceCandidate:window.RTCSessionDescription)(arguments[0]),nativeMethod.apply(this,arguments)}));window.RTCPeerConnection.prototype[method]=methodObj[method]}))},exports.fixNegotiationNeeded=function(window,browserDetails){utils.wrapPeerConnectionEvent(window,"negotiationneeded",(function(e){var pc=e.target;if(!(browserDetails.version<72||pc.getConfiguration&&"plan-b"===pc.getConfiguration().sdpSemantics)||"stable"===pc.signalingState)return e}))};var utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils.js"));function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function shimAddTrackRemoveTrackWithNative(window){window.RTCPeerConnection.prototype.getLocalStreams=function(){var _this8=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((function(streamId){return _this8._shimmedLocalStreams[streamId][0]}))};var origAddTrack=window.RTCPeerConnection.prototype.addTrack;window.RTCPeerConnection.prototype.addTrack=function(track,stream){if(!stream)return origAddTrack.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var sender=origAddTrack.apply(this,arguments);return this._shimmedLocalStreams[stream.id]?-1===this._shimmedLocalStreams[stream.id].indexOf(sender)&&this._shimmedLocalStreams[stream.id].push(sender):this._shimmedLocalStreams[stream.id]=[stream,sender],sender};var origAddStream=window.RTCPeerConnection.prototype.addStream;window.RTCPeerConnection.prototype.addStream=function(stream){var _this9=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},stream.getTracks().forEach((function(track){if(_this9.getSenders().find((function(s){return s.track===track})))throw new DOMException("Track already exists.","InvalidAccessError")}));var existingSenders=this.getSenders();origAddStream.apply(this,arguments);var newSenders=this.getSenders().filter((function(newSender){return-1===existingSenders.indexOf(newSender)}));this._shimmedLocalStreams[stream.id]=[stream].concat(newSenders)};var origRemoveStream=window.RTCPeerConnection.prototype.removeStream;window.RTCPeerConnection.prototype.removeStream=function(stream){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[stream.id],origRemoveStream.apply(this,arguments)};var origRemoveTrack=window.RTCPeerConnection.prototype.removeTrack;window.RTCPeerConnection.prototype.removeTrack=function(sender){var _this10=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},sender&&Object.keys(this._shimmedLocalStreams).forEach((function(streamId){var idx=_this10._shimmedLocalStreams[streamId].indexOf(sender);-1!==idx&&_this10._shimmedLocalStreams[streamId].splice(idx,1),1===_this10._shimmedLocalStreams[streamId].length&&delete _this10._shimmedLocalStreams[streamId]})),origRemoveTrack.apply(this,arguments)}}},{"../utils.js":37,"./getdisplaymedia":26,"./getusermedia":27}],26:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=function(window,getSourceId){if(window.navigator.mediaDevices&&"getDisplayMedia"in window.navigator.mediaDevices)return;if(!window.navigator.mediaDevices)return;if("function"!=typeof getSourceId)return void console.error("shimGetDisplayMedia: getSourceId argument is not a function");window.navigator.mediaDevices.getDisplayMedia=function(constraints){return getSourceId(constraints).then((function(sourceId){var widthSpecified=constraints.video&&constraints.video.width,heightSpecified=constraints.video&&constraints.video.height,frameRateSpecified=constraints.video&&constraints.video.frameRate;return constraints.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:sourceId,maxFrameRate:frameRateSpecified||3}},widthSpecified&&(constraints.video.mandatory.maxWidth=widthSpecified),heightSpecified&&(constraints.video.mandatory.maxHeight=heightSpecified),window.navigator.mediaDevices.getUserMedia(constraints)}))}}},{}],27:[function(require,module,exports){"use strict";function _typeof2(o){return(_typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(obj){return _typeof2(obj)}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":_typeof2(obj)};exports.shimGetUserMedia=function(window,browserDetails){var navigator=window&&window.navigator;if(!navigator.mediaDevices)return;var constraintsToChrome_=function(c){if("object"!==("undefined"==typeof c?"undefined":_typeof(c))||c.mandatory||c.optional)return c;var cc={};return Object.keys(c).forEach((function(key){if("require"!==key&&"advanced"!==key&&"mediaSource"!==key){var r="object"===_typeof(c[key])?c[key]:{ideal:c[key]};void 0!==r.exact&&"number"==typeof r.exact&&(r.min=r.max=r.exact);var oldname_=function(prefix,name){return prefix?prefix+name.charAt(0).toUpperCase()+name.slice(1):"deviceId"===name?"sourceId":name};if(void 0!==r.ideal){cc.optional=cc.optional||[];var oc={};"number"==typeof r.ideal?(oc[oldname_("min",key)]=r.ideal,cc.optional.push(oc),(oc={})[oldname_("max",key)]=r.ideal,cc.optional.push(oc)):(oc[oldname_("",key)]=r.ideal,cc.optional.push(oc))}void 0!==r.exact&&"number"!=typeof r.exact?(cc.mandatory=cc.mandatory||{},cc.mandatory[oldname_("",key)]=r.exact):["min","max"].forEach((function(mix){void 0!==r[mix]&&(cc.mandatory=cc.mandatory||{},cc.mandatory[oldname_(mix,key)]=r[mix])}))}})),c.advanced&&(cc.optional=(cc.optional||[]).concat(c.advanced)),cc},shimConstraints_=function(constraints,func){if(browserDetails.version>=61)return func(constraints);if((constraints=JSON.parse(JSON.stringify(constraints)))&&"object"===_typeof(constraints.audio)){var remap=function(obj,a,b){a in obj&&!(b in obj)&&(obj[b]=obj[a],delete obj[a])};remap((constraints=JSON.parse(JSON.stringify(constraints))).audio,"autoGainControl","googAutoGainControl"),remap(constraints.audio,"noiseSuppression","googNoiseSuppression"),constraints.audio=constraintsToChrome_(constraints.audio)}if(constraints&&"object"===_typeof(constraints.video)){var face=constraints.video.facingMode;face=face&&("object"===("undefined"==typeof face?"undefined":_typeof(face))?face:{ideal:face});var getSupportedFacingModeLies=browserDetails.version<66;if(face&&("user"===face.exact||"environment"===face.exact||"user"===face.ideal||"environment"===face.ideal)&&(!navigator.mediaDevices.getSupportedConstraints||!navigator.mediaDevices.getSupportedConstraints().facingMode||getSupportedFacingModeLies)){delete constraints.video.facingMode;var matches=void 0;if("environment"===face.exact||"environment"===face.ideal?matches=["back","rear"]:"user"!==face.exact&&"user"!==face.ideal||(matches=["front"]),matches)return navigator.mediaDevices.enumerateDevices().then((function(devices){var dev=(devices=devices.filter((function(d){return"videoinput"===d.kind}))).find((function(d){return matches.some((function(match){return d.label.toLowerCase().includes(match)}))}));return!dev&&devices.length&&matches.includes("back")&&(dev=devices[devices.length-1]),dev&&(constraints.video.deviceId=face.exact?{exact:dev.deviceId}:{ideal:dev.deviceId}),constraints.video=constraintsToChrome_(constraints.video),logging("chrome: "+JSON.stringify(constraints)),func(constraints)}))}constraints.video=constraintsToChrome_(constraints.video)}return logging("chrome: "+JSON.stringify(constraints)),func(constraints)},shimError_=function(e){return browserDetails.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(navigator.getUserMedia=function(constraints,onSuccess,onError){shimConstraints_(constraints,(function(c){navigator.webkitGetUserMedia(c,onSuccess,(function(e){onError&&onError(shimError_(e))}))}))}.bind(navigator),navigator.mediaDevices.getUserMedia){var origGetUserMedia=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getUserMedia=function(cs){return shimConstraints_(cs,(function(c){return origGetUserMedia(c).then((function(stream){if(c.audio&&!stream.getAudioTracks().length||c.video&&!stream.getVideoTracks().length)throw stream.getTracks().forEach((function(track){track.stop()})),new DOMException("","NotFoundError");return stream}),(function(e){return Promise.reject(shimError_(e))}))}))}}};var logging=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils.js")).log},{"../utils.js":37}],28:[function(require,module,exports){"use strict";function _typeof2(o){return(_typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(obj){return _typeof2(obj)}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":_typeof2(obj)};exports.shimRTCIceCandidate=function(window){if(!window.RTCIceCandidate||window.RTCIceCandidate&&"foundation"in window.RTCIceCandidate.prototype)return;var NativeRTCIceCandidate=window.RTCIceCandidate;window.RTCIceCandidate=function(args){if("object"===("undefined"==typeof args?"undefined":_typeof(args))&&args.candidate&&0===args.candidate.indexOf("a=")&&((args=JSON.parse(JSON.stringify(args))).candidate=args.candidate.substr(2)),args.candidate&&args.candidate.length){var nativeCandidate=new NativeRTCIceCandidate(args),parsedCandidate=_sdp2.default.parseCandidate(args.candidate),augmentedCandidate=Object.assign(nativeCandidate,parsedCandidate);return augmentedCandidate.toJSON=function(){return{candidate:augmentedCandidate.candidate,sdpMid:augmentedCandidate.sdpMid,sdpMLineIndex:augmentedCandidate.sdpMLineIndex,usernameFragment:augmentedCandidate.usernameFragment}},augmentedCandidate}return new NativeRTCIceCandidate(args)},window.RTCIceCandidate.prototype=NativeRTCIceCandidate.prototype,utils.wrapPeerConnectionEvent(window,"icecandidate",(function(e){return e.candidate&&Object.defineProperty(e,"candidate",{value:new window.RTCIceCandidate(e.candidate),writable:"false"}),e}))},exports.shimMaxMessageSize=function(window,browserDetails){if(!window.RTCPeerConnection)return;"sctp"in window.RTCPeerConnection.prototype||Object.defineProperty(window.RTCPeerConnection.prototype,"sctp",{get:function(){return"undefined"==typeof this._sctp?null:this._sctp}});var sctpInDescription=function(description){if(!description||!description.sdp)return!1;var sections=_sdp2.default.splitSections(description.sdp);return sections.shift(),sections.some((function(mediaSection){var mLine=_sdp2.default.parseMLine(mediaSection);return mLine&&"application"===mLine.kind&&-1!==mLine.protocol.indexOf("SCTP")}))},getRemoteFirefoxVersion=function(description){var match=description.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===match||match.length<2)return-1;var version=parseInt(match[1],10);return version!=version?-1:version},getCanSendMaxMessageSize=function(remoteIsFirefox){var canSendMaxMessageSize=65536;return"firefox"===browserDetails.browser&&(canSendMaxMessageSize=browserDetails.version<57?-1===remoteIsFirefox?16384:2147483637:browserDetails.version<60?57===browserDetails.version?65535:65536:2147483637),canSendMaxMessageSize},getMaxMessageSize=function(description,remoteIsFirefox){var maxMessageSize=65536;"firefox"===browserDetails.browser&&57===browserDetails.version&&(maxMessageSize=65535);var match=_sdp2.default.matchPrefix(description.sdp,"a=max-message-size:");return match.length>0?maxMessageSize=parseInt(match[0].substr(19),10):"firefox"===browserDetails.browser&&-1!==remoteIsFirefox&&(maxMessageSize=2147483637),maxMessageSize},origSetRemoteDescription=window.RTCPeerConnection.prototype.setRemoteDescription;window.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===browserDetails.browser&&browserDetails.version>=76){var _getConfiguration=this.getConfiguration(),sdpSemantics=_getConfiguration.sdpSemantics;"plan-b"===sdpSemantics&&Object.defineProperty(this,"sctp",{get:function(){return"undefined"==typeof this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(sctpInDescription(arguments[0])){var isFirefox=getRemoteFirefoxVersion(arguments[0]),canSendMMS=getCanSendMaxMessageSize(isFirefox),remoteMMS=getMaxMessageSize(arguments[0],isFirefox),maxMessageSize=void 0;maxMessageSize=0===canSendMMS&&0===remoteMMS?Number.POSITIVE_INFINITY:0===canSendMMS||0===remoteMMS?Math.max(canSendMMS,remoteMMS):Math.min(canSendMMS,remoteMMS);var sctp={};Object.defineProperty(sctp,"maxMessageSize",{get:function(){return maxMessageSize}}),this._sctp=sctp}return origSetRemoteDescription.apply(this,arguments)}},exports.shimSendThrowTypeError=function(window){if(!window.RTCPeerConnection||!("createDataChannel"in window.RTCPeerConnection.prototype))return;function wrapDcSend(dc,pc){var origDataChannelSend=dc.send;dc.send=function(){var data=arguments[0],length=data.length||data.size||data.byteLength;if("open"===dc.readyState&&pc.sctp&&length>pc.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+pc.sctp.maxMessageSize+" bytes)");return origDataChannelSend.apply(dc,arguments)}}var origCreateDataChannel=window.RTCPeerConnection.prototype.createDataChannel;window.RTCPeerConnection.prototype.createDataChannel=function(){var dataChannel=origCreateDataChannel.apply(this,arguments);return wrapDcSend(dataChannel,this),dataChannel},utils.wrapPeerConnectionEvent(window,"datachannel",(function(e){return wrapDcSend(e.channel,e.target),e}))},exports.shimConnectionState=function(window){if(!window.RTCPeerConnection||"connectionState"in window.RTCPeerConnection.prototype)return;var proto=window.RTCPeerConnection.prototype;Object.defineProperty(proto,"connectionState",{get:function(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(proto,"onconnectionstatechange",{get:function(){return this._onconnectionstatechange||null},set:function(cb){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),cb&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=cb)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((function(method){var origMethod=proto[method];proto[method]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=function(e){var pc=e.target;if(pc._lastConnectionState!==pc.connectionState){pc._lastConnectionState=pc.connectionState;var newEvent=new Event("connectionstatechange",e);pc.dispatchEvent(newEvent)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),origMethod.apply(this,arguments)}}))},exports.removeExtmapAllowMixed=function(window,browserDetails){if(!window.RTCPeerConnection)return;if("chrome"===browserDetails.browser&&browserDetails.version>=71)return;if("safari"===browserDetails.browser&&browserDetails.version>=605)return;var nativeSRD=window.RTCPeerConnection.prototype.setRemoteDescription;window.RTCPeerConnection.prototype.setRemoteDescription=function(desc){if(desc&&desc.sdp&&-1!==desc.sdp.indexOf("\na=extmap-allow-mixed")){var sdp=desc.sdp.split("\n").filter((function(line){return"a=extmap-allow-mixed"!==line.trim()})).join("\n");window.RTCSessionDescription&&desc instanceof window.RTCSessionDescription?arguments[0]=new window.RTCSessionDescription({type:desc.type,sdp:sdp}):desc.sdp=sdp}return nativeSRD.apply(this,arguments)}},exports.shimAddIceCandidateNullOrEmpty=function(window,browserDetails){if(!window.RTCPeerConnection||!window.RTCPeerConnection.prototype)return;var nativeAddIceCandidate=window.RTCPeerConnection.prototype.addIceCandidate;if(!nativeAddIceCandidate||0===nativeAddIceCandidate.length)return;window.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===browserDetails.browser&&browserDetails.version<78||"firefox"===browserDetails.browser&&browserDetails.version<68||"safari"===browserDetails.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():nativeAddIceCandidate.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())}};var obj,_sdp=require("sdp"),_sdp2=(obj=_sdp)&&obj.__esModule?obj:{default:obj},utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("./utils"))},{"./utils":37,sdp:6}],29:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=exports.shimGetUserMedia=void 0;var _getusermedia=require("./getusermedia");Object.defineProperty(exports,"shimGetUserMedia",{enumerable:!0,get:function(){return _getusermedia.shimGetUserMedia}});var _getdisplaymedia=require("./getdisplaymedia");Object.defineProperty(exports,"shimGetDisplayMedia",{enumerable:!0,get:function(){return _getdisplaymedia.shimGetDisplayMedia}}),exports.shimPeerConnection=function(window,browserDetails){if(window.RTCIceGatherer&&(window.RTCIceCandidate||(window.RTCIceCandidate=function(args){return args}),window.RTCSessionDescription||(window.RTCSessionDescription=function(args){return args}),browserDetails.version<15025)){var origMSTEnabled=Object.getOwnPropertyDescriptor(window.MediaStreamTrack.prototype,"enabled");Object.defineProperty(window.MediaStreamTrack.prototype,"enabled",{set:function(value){origMSTEnabled.set.call(this,value);var ev=new Event("enabled");ev.enabled=value,this.dispatchEvent(ev)}})}window.RTCRtpSender&&!("dtmf"in window.RTCRtpSender.prototype)&&Object.defineProperty(window.RTCRtpSender.prototype,"dtmf",{get:function(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=new window.RTCDtmfSender(this):"video"===this.track.kind&&(this._dtmf=null)),this._dtmf}});window.RTCDtmfSender&&!window.RTCDTMFSender&&(window.RTCDTMFSender=window.RTCDtmfSender);var RTCPeerConnectionShim=(0,_rtcpeerconnectionShim2.default)(window,browserDetails.version);window.RTCPeerConnection=function(config){return config&&config.iceServers&&(config.iceServers=(0,_filtericeservers.filterIceServers)(config.iceServers,browserDetails.version),utils.log("ICE servers after filtering:",config.iceServers)),new RTCPeerConnectionShim(config)},window.RTCPeerConnection.prototype=RTCPeerConnectionShim.prototype},exports.shimReplaceTrack=function(window){window.RTCRtpSender&&!("replaceTrack"in window.RTCRtpSender.prototype)&&(window.RTCRtpSender.prototype.replaceTrack=window.RTCRtpSender.prototype.setTrack)};var obj,utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils")),_filtericeservers=require("./filtericeservers"),_rtcpeerconnectionShim=require("rtcpeerconnection-shim"),_rtcpeerconnectionShim2=(obj=_rtcpeerconnectionShim)&&obj.__esModule?obj:{default:obj}},{"../utils":37,"./filtericeservers":30,"./getdisplaymedia":31,"./getusermedia":32,"rtcpeerconnection-shim":5}],30:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.filterIceServers=function(iceServers,edgeVersion){var hasTurn=!1;return(iceServers=JSON.parse(JSON.stringify(iceServers))).filter((function(server){if(server&&(server.urls||server.url)){var urls=server.urls||server.url;server.url&&!server.urls&&utils.deprecated("RTCIceServer.url","RTCIceServer.urls");var isString="string"==typeof urls;return isString&&(urls=[urls]),urls=urls.filter((function(url){if(0===url.indexOf("stun:"))return!1;var validTurn=url.startsWith("turn")&&!url.startsWith("turn:[")&&url.includes("transport=udp");return validTurn&&!hasTurn?(hasTurn=!0,!0):validTurn&&!hasTurn})),delete server.url,server.urls=isString?urls[0]:urls,!!urls.length}}))};var utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils"))},{"../utils":37}],31:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=function(window){if(!("getDisplayMedia"in window.navigator))return;if(!window.navigator.mediaDevices)return;if(window.navigator.mediaDevices&&"getDisplayMedia"in window.navigator.mediaDevices)return;window.navigator.mediaDevices.getDisplayMedia=window.navigator.getDisplayMedia.bind(window.navigator)}},{}],32:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetUserMedia=function(window){var navigator=window&&window.navigator,origGetUserMedia=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getUserMedia=function(c){return origGetUserMedia(c).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))}))}}},{}],33:[function(require,module,exports){"use strict";function _typeof2(o){return(_typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=exports.shimGetUserMedia=void 0;var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(obj){return _typeof2(obj)}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":_typeof2(obj)},_getusermedia=require("./getusermedia");Object.defineProperty(exports,"shimGetUserMedia",{enumerable:!0,get:function(){return _getusermedia.shimGetUserMedia}});var _getdisplaymedia=require("./getdisplaymedia");Object.defineProperty(exports,"shimGetDisplayMedia",{enumerable:!0,get:function(){return _getdisplaymedia.shimGetDisplayMedia}}),exports.shimOnTrack=function(window){"object"===("undefined"==typeof window?"undefined":_typeof(window))&&window.RTCTrackEvent&&"receiver"in window.RTCTrackEvent.prototype&&!("transceiver"in window.RTCTrackEvent.prototype)&&Object.defineProperty(window.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})},exports.shimPeerConnection=function(window,browserDetails){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection&&!window.mozRTCPeerConnection)return;!window.RTCPeerConnection&&window.mozRTCPeerConnection&&(window.RTCPeerConnection=window.mozRTCPeerConnection);browserDetails.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(method){var nativeMethod=window.RTCPeerConnection.prototype[method],methodObj=function(obj,key,value){key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value;return obj}({},method,(function(){return arguments[0]=new("addIceCandidate"===method?window.RTCIceCandidate:window.RTCSessionDescription)(arguments[0]),nativeMethod.apply(this,arguments)}));window.RTCPeerConnection.prototype[method]=methodObj[method]}));var modernStatsTypes={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},nativeGetStats=window.RTCPeerConnection.prototype.getStats;window.RTCPeerConnection.prototype.getStats=function(){var _arguments=Array.prototype.slice.call(arguments),selector=_arguments[0],onSucc=_arguments[1],onErr=_arguments[2];return nativeGetStats.apply(this,[selector||null]).then((function(stats){if(browserDetails.version<53&&!onSucc)try{stats.forEach((function(stat){stat.type=modernStatsTypes[stat.type]||stat.type}))}catch(e){if("TypeError"!==e.name)throw e;stats.forEach((function(stat,i){stats.set(i,Object.assign({},stat,{type:modernStatsTypes[stat.type]||stat.type}))}))}return stats})).then(onSucc,onErr)}},exports.shimSenderGetStats=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection||!window.RTCRtpSender)return;if(window.RTCRtpSender&&"getStats"in window.RTCRtpSender.prototype)return;var origGetSenders=window.RTCPeerConnection.prototype.getSenders;origGetSenders&&(window.RTCPeerConnection.prototype.getSenders=function(){var _this=this,senders=origGetSenders.apply(this,[]);return senders.forEach((function(sender){return sender._pc=_this})),senders});var origAddTrack=window.RTCPeerConnection.prototype.addTrack;origAddTrack&&(window.RTCPeerConnection.prototype.addTrack=function(){var sender=origAddTrack.apply(this,arguments);return sender._pc=this,sender});window.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}},exports.shimReceiverGetStats=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection||!window.RTCRtpSender)return;if(window.RTCRtpSender&&"getStats"in window.RTCRtpReceiver.prototype)return;var origGetReceivers=window.RTCPeerConnection.prototype.getReceivers;origGetReceivers&&(window.RTCPeerConnection.prototype.getReceivers=function(){var _this2=this,receivers=origGetReceivers.apply(this,[]);return receivers.forEach((function(receiver){return receiver._pc=_this2})),receivers});utils.wrapPeerConnectionEvent(window,"track",(function(e){return e.receiver._pc=e.srcElement,e})),window.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}},exports.shimRemoveStream=function(window){if(!window.RTCPeerConnection||"removeStream"in window.RTCPeerConnection.prototype)return;window.RTCPeerConnection.prototype.removeStream=function(stream){var _this3=this;utils.deprecated("removeStream","removeTrack"),this.getSenders().forEach((function(sender){sender.track&&stream.getTracks().includes(sender.track)&&_this3.removeTrack(sender)}))}},exports.shimRTCDataChannel=function(window){window.DataChannel&&!window.RTCDataChannel&&(window.RTCDataChannel=window.DataChannel)},exports.shimAddTransceiver=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection)return;var origAddTransceiver=window.RTCPeerConnection.prototype.addTransceiver;origAddTransceiver&&(window.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];var initParameters=arguments[1],shouldPerformCheck=initParameters&&"sendEncodings"in initParameters;shouldPerformCheck&&initParameters.sendEncodings.forEach((function(encodingParam){if("rid"in encodingParam){if(!/^[a-z0-9]{0,16}$/i.test(encodingParam.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in encodingParam&&!(parseFloat(encodingParam.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in encodingParam&&!(parseFloat(encodingParam.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));var transceiver=origAddTransceiver.apply(this,arguments);if(shouldPerformCheck){var sender=transceiver.sender,params=sender.getParameters();(!("encodings"in params)||1===params.encodings.length&&0===Object.keys(params.encodings[0]).length)&&(params.encodings=initParameters.sendEncodings,sender.sendEncodings=initParameters.sendEncodings,this.setParametersPromises.push(sender.setParameters(params).then((function(){delete sender.sendEncodings})).catch((function(){delete sender.sendEncodings}))))}return transceiver})},exports.shimGetParameters=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCRtpSender)return;var origGetParameters=window.RTCRtpSender.prototype.getParameters;origGetParameters&&(window.RTCRtpSender.prototype.getParameters=function(){var params=origGetParameters.apply(this,arguments);return"encodings"in params||(params.encodings=[].concat(this.sendEncodings||[{}])),params})},exports.shimCreateOffer=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection)return;var origCreateOffer=window.RTCPeerConnection.prototype.createOffer;window.RTCPeerConnection.prototype.createOffer=function(){var _this4=this,_arguments2=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((function(){return origCreateOffer.apply(_this4,_arguments2)})).finally((function(){_this4.setParametersPromises=[]})):origCreateOffer.apply(this,arguments)}},exports.shimCreateAnswer=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection)return;var origCreateAnswer=window.RTCPeerConnection.prototype.createAnswer;window.RTCPeerConnection.prototype.createAnswer=function(){var _this5=this,_arguments3=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((function(){return origCreateAnswer.apply(_this5,_arguments3)})).finally((function(){_this5.setParametersPromises=[]})):origCreateAnswer.apply(this,arguments)}};var utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils"))},{"../utils":37,"./getdisplaymedia":34,"./getusermedia":35}],34:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=function(window,preferredMediaSource){if(window.navigator.mediaDevices&&"getDisplayMedia"in window.navigator.mediaDevices)return;if(!window.navigator.mediaDevices)return;window.navigator.mediaDevices.getDisplayMedia=function(constraints){if(!constraints||!constraints.video){var err=new DOMException("getDisplayMedia without video constraints is undefined");return err.name="NotFoundError",err.code=8,Promise.reject(err)}return!0===constraints.video?constraints.video={mediaSource:preferredMediaSource}:constraints.video.mediaSource=preferredMediaSource,window.navigator.mediaDevices.getUserMedia(constraints)}}},{}],35:[function(require,module,exports){"use strict";function _typeof2(o){return(_typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(obj){return _typeof2(obj)}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":_typeof2(obj)};exports.shimGetUserMedia=function(window,browserDetails){var navigator=window&&window.navigator,MediaStreamTrack=window&&window.MediaStreamTrack;if(navigator.getUserMedia=function(constraints,onSuccess,onError){utils.deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),navigator.mediaDevices.getUserMedia(constraints).then(onSuccess,onError)},!(browserDetails.version>55&&"autoGainControl"in navigator.mediaDevices.getSupportedConstraints())){var remap=function(obj,a,b){a in obj&&!(b in obj)&&(obj[b]=obj[a],delete obj[a])},nativeGetUserMedia=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);if(navigator.mediaDevices.getUserMedia=function(c){return"object"===("undefined"==typeof c?"undefined":_typeof(c))&&"object"===_typeof(c.audio)&&(c=JSON.parse(JSON.stringify(c)),remap(c.audio,"autoGainControl","mozAutoGainControl"),remap(c.audio,"noiseSuppression","mozNoiseSuppression")),nativeGetUserMedia(c)},MediaStreamTrack&&MediaStreamTrack.prototype.getSettings){var nativeGetSettings=MediaStreamTrack.prototype.getSettings;MediaStreamTrack.prototype.getSettings=function(){var obj=nativeGetSettings.apply(this,arguments);return remap(obj,"mozAutoGainControl","autoGainControl"),remap(obj,"mozNoiseSuppression","noiseSuppression"),obj}}if(MediaStreamTrack&&MediaStreamTrack.prototype.applyConstraints){var nativeApplyConstraints=MediaStreamTrack.prototype.applyConstraints;MediaStreamTrack.prototype.applyConstraints=function(c){return"audio"===this.kind&&"object"===("undefined"==typeof c?"undefined":_typeof(c))&&(c=JSON.parse(JSON.stringify(c)),remap(c,"autoGainControl","mozAutoGainControl"),remap(c,"noiseSuppression","mozNoiseSuppression")),nativeApplyConstraints.apply(this,[c])}}}};var utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils"))},{"../utils":37}],36:[function(require,module,exports){"use strict";function _typeof2(o){return(_typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(obj){return _typeof2(obj)}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":_typeof2(obj)};exports.shimLocalStreamsAPI=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection)return;"getLocalStreams"in window.RTCPeerConnection.prototype||(window.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams});if(!("addStream"in window.RTCPeerConnection.prototype)){var _addTrack=window.RTCPeerConnection.prototype.addTrack;window.RTCPeerConnection.prototype.addStream=function(stream){var _this=this;this._localStreams||(this._localStreams=[]),this._localStreams.includes(stream)||this._localStreams.push(stream),stream.getAudioTracks().forEach((function(track){return _addTrack.call(_this,track,stream)})),stream.getVideoTracks().forEach((function(track){return _addTrack.call(_this,track,stream)}))},window.RTCPeerConnection.prototype.addTrack=function(track){for(var _this2=this,_len=arguments.length,streams=Array(_len>1?_len-1:0),_key=1;_key<_len;_key++)streams[_key-1]=arguments[_key];return streams&&streams.forEach((function(stream){_this2._localStreams?_this2._localStreams.includes(stream)||_this2._localStreams.push(stream):_this2._localStreams=[stream]})),_addTrack.apply(this,arguments)}}"removeStream"in window.RTCPeerConnection.prototype||(window.RTCPeerConnection.prototype.removeStream=function(stream){var _this3=this;this._localStreams||(this._localStreams=[]);var index=this._localStreams.indexOf(stream);if(-1!==index){this._localStreams.splice(index,1);var tracks=stream.getTracks();this.getSenders().forEach((function(sender){tracks.includes(sender.track)&&_this3.removeTrack(sender)}))}})},exports.shimRemoteStreamsAPI=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection)return;"getRemoteStreams"in window.RTCPeerConnection.prototype||(window.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]});if(!("onaddstream"in window.RTCPeerConnection.prototype)){Object.defineProperty(window.RTCPeerConnection.prototype,"onaddstream",{get:function(){return this._onaddstream},set:function(f){var _this4=this;this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=f),this.addEventListener("track",this._onaddstreampoly=function(e){e.streams.forEach((function(stream){if(_this4._remoteStreams||(_this4._remoteStreams=[]),!_this4._remoteStreams.includes(stream)){_this4._remoteStreams.push(stream);var event=new Event("addstream");event.stream=stream,_this4.dispatchEvent(event)}}))})}});var origSetRemoteDescription=window.RTCPeerConnection.prototype.setRemoteDescription;window.RTCPeerConnection.prototype.setRemoteDescription=function(){var pc=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(e){e.streams.forEach((function(stream){if(pc._remoteStreams||(pc._remoteStreams=[]),!(pc._remoteStreams.indexOf(stream)>=0)){pc._remoteStreams.push(stream);var event=new Event("addstream");event.stream=stream,pc.dispatchEvent(event)}}))}),origSetRemoteDescription.apply(pc,arguments)}}},exports.shimCallbacksAPI=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection)return;var prototype=window.RTCPeerConnection.prototype,origCreateOffer=prototype.createOffer,origCreateAnswer=prototype.createAnswer,setLocalDescription=prototype.setLocalDescription,setRemoteDescription=prototype.setRemoteDescription,addIceCandidate=prototype.addIceCandidate;prototype.createOffer=function(successCallback,failureCallback){var options=arguments.length>=2?arguments[2]:arguments[0],promise=origCreateOffer.apply(this,[options]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise},prototype.createAnswer=function(successCallback,failureCallback){var options=arguments.length>=2?arguments[2]:arguments[0],promise=origCreateAnswer.apply(this,[options]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise};var withCallback=function(description,successCallback,failureCallback){var promise=setLocalDescription.apply(this,[description]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise};prototype.setLocalDescription=withCallback,withCallback=function(description,successCallback,failureCallback){var promise=setRemoteDescription.apply(this,[description]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise},prototype.setRemoteDescription=withCallback,withCallback=function(candidate,successCallback,failureCallback){var promise=addIceCandidate.apply(this,[candidate]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise},prototype.addIceCandidate=withCallback},exports.shimGetUserMedia=function(window){var navigator=window&&window.navigator;if(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia){var mediaDevices=navigator.mediaDevices,_getUserMedia=mediaDevices.getUserMedia.bind(mediaDevices);navigator.mediaDevices.getUserMedia=function(constraints){return _getUserMedia(shimConstraints(constraints))}}!navigator.getUserMedia&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&(navigator.getUserMedia=function(constraints,cb,errcb){navigator.mediaDevices.getUserMedia(constraints).then(cb,errcb)}.bind(navigator))},exports.shimConstraints=shimConstraints,exports.shimRTCIceServerUrls=function(window){if(!window.RTCPeerConnection)return;var OrigPeerConnection=window.RTCPeerConnection;window.RTCPeerConnection=function(pcConfig,pcConstraints){if(pcConfig&&pcConfig.iceServers){for(var newIceServers=[],i=0;i<pcConfig.iceServers.length;i++){var server=pcConfig.iceServers[i];!server.hasOwnProperty("urls")&&server.hasOwnProperty("url")?(utils.deprecated("RTCIceServer.url","RTCIceServer.urls"),(server=JSON.parse(JSON.stringify(server))).urls=server.url,delete server.url,newIceServers.push(server)):newIceServers.push(pcConfig.iceServers[i])}pcConfig.iceServers=newIceServers}return new OrigPeerConnection(pcConfig,pcConstraints)},window.RTCPeerConnection.prototype=OrigPeerConnection.prototype,"generateCertificate"in OrigPeerConnection&&Object.defineProperty(window.RTCPeerConnection,"generateCertificate",{get:function(){return OrigPeerConnection.generateCertificate}})},exports.shimTrackEventTransceiver=function(window){"object"===("undefined"==typeof window?"undefined":_typeof(window))&&window.RTCTrackEvent&&"receiver"in window.RTCTrackEvent.prototype&&!("transceiver"in window.RTCTrackEvent.prototype)&&Object.defineProperty(window.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})},exports.shimCreateOfferLegacy=function(window){var origCreateOffer=window.RTCPeerConnection.prototype.createOffer;window.RTCPeerConnection.prototype.createOffer=function(offerOptions){if(offerOptions){"undefined"!=typeof offerOptions.offerToReceiveAudio&&(offerOptions.offerToReceiveAudio=!!offerOptions.offerToReceiveAudio);var audioTransceiver=this.getTransceivers().find((function(transceiver){return"audio"===transceiver.receiver.track.kind}));!1===offerOptions.offerToReceiveAudio&&audioTransceiver?"sendrecv"===audioTransceiver.direction?audioTransceiver.setDirection?audioTransceiver.setDirection("sendonly"):audioTransceiver.direction="sendonly":"recvonly"===audioTransceiver.direction&&(audioTransceiver.setDirection?audioTransceiver.setDirection("inactive"):audioTransceiver.direction="inactive"):!0!==offerOptions.offerToReceiveAudio||audioTransceiver||this.addTransceiver("audio"),"undefined"!=typeof offerOptions.offerToReceiveVideo&&(offerOptions.offerToReceiveVideo=!!offerOptions.offerToReceiveVideo);var videoTransceiver=this.getTransceivers().find((function(transceiver){return"video"===transceiver.receiver.track.kind}));!1===offerOptions.offerToReceiveVideo&&videoTransceiver?"sendrecv"===videoTransceiver.direction?videoTransceiver.setDirection?videoTransceiver.setDirection("sendonly"):videoTransceiver.direction="sendonly":"recvonly"===videoTransceiver.direction&&(videoTransceiver.setDirection?videoTransceiver.setDirection("inactive"):videoTransceiver.direction="inactive"):!0!==offerOptions.offerToReceiveVideo||videoTransceiver||this.addTransceiver("video")}return origCreateOffer.apply(this,arguments)}},exports.shimAudioContext=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||window.AudioContext)return;window.AudioContext=window.webkitAudioContext};var utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils"));function shimConstraints(constraints){return constraints&&void 0!==constraints.video?Object.assign({},constraints,{video:utils.compactObject(constraints.video)}):constraints}},{"../utils":37}],37:[function(require,module,exports){"use strict";function _typeof2(o){return(_typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(obj){return _typeof2(obj)}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":_typeof2(obj)};exports.extractVersion=extractVersion,exports.wrapPeerConnectionEvent=function(window,eventNameToWrap,wrapper){if(!window.RTCPeerConnection)return;var proto=window.RTCPeerConnection.prototype,nativeAddEventListener=proto.addEventListener;proto.addEventListener=function(nativeEventName,cb){if(nativeEventName!==eventNameToWrap)return nativeAddEventListener.apply(this,arguments);var wrappedCallback=function(e){var modifiedEvent=wrapper(e);modifiedEvent&&(cb.handleEvent?cb.handleEvent(modifiedEvent):cb(modifiedEvent))};return this._eventMap=this._eventMap||{},this._eventMap[eventNameToWrap]||(this._eventMap[eventNameToWrap]=new Map),this._eventMap[eventNameToWrap].set(cb,wrappedCallback),nativeAddEventListener.apply(this,[nativeEventName,wrappedCallback])};var nativeRemoveEventListener=proto.removeEventListener;proto.removeEventListener=function(nativeEventName,cb){if(nativeEventName!==eventNameToWrap||!this._eventMap||!this._eventMap[eventNameToWrap])return nativeRemoveEventListener.apply(this,arguments);if(!this._eventMap[eventNameToWrap].has(cb))return nativeRemoveEventListener.apply(this,arguments);var unwrappedCb=this._eventMap[eventNameToWrap].get(cb);return this._eventMap[eventNameToWrap].delete(cb),0===this._eventMap[eventNameToWrap].size&&delete this._eventMap[eventNameToWrap],0===Object.keys(this._eventMap).length&&delete this._eventMap,nativeRemoveEventListener.apply(this,[nativeEventName,unwrappedCb])},Object.defineProperty(proto,"on"+eventNameToWrap,{get:function(){return this["_on"+eventNameToWrap]},set:function(cb){this["_on"+eventNameToWrap]&&(this.removeEventListener(eventNameToWrap,this["_on"+eventNameToWrap]),delete this["_on"+eventNameToWrap]),cb&&this.addEventListener(eventNameToWrap,this["_on"+eventNameToWrap]=cb)},enumerable:!0,configurable:!0})},exports.disableLog=function(bool){if("boolean"!=typeof bool)return new Error("Argument type: "+("undefined"==typeof bool?"undefined":_typeof(bool))+". Please use a boolean.");return logDisabled_=bool,bool?"adapter.js logging disabled":"adapter.js logging enabled"},exports.disableWarnings=function(bool){if("boolean"!=typeof bool)return new Error("Argument type: "+("undefined"==typeof bool?"undefined":_typeof(bool))+". Please use a boolean.");return deprecationWarnings_=!bool,"adapter.js deprecation warnings "+(bool?"disabled":"enabled")},exports.log=function(){if("object"===("undefined"==typeof window?"undefined":_typeof(window))){if(logDisabled_)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}},exports.deprecated=function(oldMethod,newMethod){if(!deprecationWarnings_)return;console.warn(oldMethod+" is deprecated, please use "+newMethod+" instead.")},exports.detectBrowser=function(window){var result={browser:null,version:null};if("undefined"==typeof window||!window.navigator)return result.browser="Not a browser.",result;var navigator=window.navigator;if(navigator.mozGetUserMedia)result.browser="firefox",result.version=extractVersion(navigator.userAgent,/Firefox\/(\d+)\./,1);else if(navigator.webkitGetUserMedia||!1===window.isSecureContext&&window.webkitRTCPeerConnection&&!window.RTCIceGatherer)result.browser="chrome",result.version=extractVersion(navigator.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(navigator.mediaDevices&&navigator.userAgent.match(/Edge\/(\d+).(\d+)$/))result.browser="edge",result.version=extractVersion(navigator.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!window.RTCPeerConnection||!navigator.userAgent.match(/AppleWebKit\/(\d+)\./))return result.browser="Not a supported browser.",result;result.browser="safari",result.version=extractVersion(navigator.userAgent,/AppleWebKit\/(\d+)\./,1),result.supportsUnifiedPlan=window.RTCRtpTransceiver&&"currentDirection"in window.RTCRtpTransceiver.prototype}return result},exports.compactObject=function compactObject(data){if(!isObject(data))return data;return Object.keys(data).reduce((function(accumulator,key){var isObj=isObject(data[key]),value=isObj?compactObject(data[key]):data[key],isEmptyObject=isObj&&!Object.keys(value).length;return void 0===value||isEmptyObject?accumulator:Object.assign(accumulator,function(obj,key,value){key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value;return obj}({},key,value))}),{})},exports.walkStats=walkStats,exports.filterStats=function(result,track,outbound){var streamStatsType=outbound?"outbound-rtp":"inbound-rtp",filteredResult=new Map;if(null===track)return filteredResult;var trackStats=[];return result.forEach((function(value){"track"===value.type&&value.trackIdentifier===track.id&&trackStats.push(value)})),trackStats.forEach((function(trackStat){result.forEach((function(stats){stats.type===streamStatsType&&stats.trackId===trackStat.id&&walkStats(result,stats,filteredResult)}))})),filteredResult};var logDisabled_=!0,deprecationWarnings_=!0;function extractVersion(uastring,expr,pos){var match=uastring.match(expr);return match&&match.length>=pos&&parseInt(match[pos],10)}function isObject(val){return"[object Object]"===Object.prototype.toString.call(val)}function walkStats(stats,base,resultSet){base&&!resultSet.has(base.id)&&(resultSet.set(base.id,base),Object.keys(base).forEach((function(name){name.endsWith("Id")?walkStats(stats,stats.get(base[name]),resultSet):name.endsWith("Ids")&&base[name].forEach((function(id){walkStats(stats,stats.get(id),resultSet)}))})))}},{}],38:[function(require,module,exports){"use strict";function _regenerator(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function i(r,n,o,i){var c=n&&n.prototype instanceof Generator?n:Generator,u=Object.create(c.prototype);return _regeneratorDefine2(u,"_invoke",function(r,n,o){var i,c,u,f=0,p=o||[],y=!1,G={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return i=t,c=0,u=e,G.n=r,a}};function d(r,n){for(c=r,u=n,t=0;!y&&f&&!o&&t<p.length;t++){var o,i=p[t],d=G.p,l=i[2];r>3?(o=l===n)&&(u=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&d<i[1])?(c=0,G.v=n,G.n=i[1]):d<l&&(o=r<3||i[0]>n||n>l)&&(i[4]=r,i[5]=n,G.n=l,c=0))}if(o||r>1)return a;throw y=!0,n}return function(o,p,l){if(f>1)throw TypeError("Generator is already running");for(y&&1===p&&d(p,l),c=p,u=l;(t=c<2?e:u)||!y;){i||(c?c<3?(c>1&&(G.n=-1),d(c,u)):G.n=u:G.v=u);try{if(f=2,i){if(c||(o="next"),t=i[o]){if(!(t=t.call(i,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);i=e}else if((t=(y=G.n<0)?u:r.call(n,G))!==a)break}catch(t){i=e,c=1,u=t}finally{f=1}}return{value:t,done:y}}}(r,o,i),!0),u}var a={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}t=Object.getPrototypeOf;var c=[][n]?t(t([][n]())):(_regeneratorDefine2(t={},n,(function(){return this})),t),u=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(c);function f(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,GeneratorFunctionPrototype):(e.__proto__=GeneratorFunctionPrototype,_regeneratorDefine2(e,o,"GeneratorFunction")),e.prototype=Object.create(u),e}return GeneratorFunction.prototype=GeneratorFunctionPrototype,_regeneratorDefine2(u,"constructor",GeneratorFunctionPrototype),_regeneratorDefine2(GeneratorFunctionPrototype,"constructor",GeneratorFunction),GeneratorFunction.displayName="GeneratorFunction",_regeneratorDefine2(GeneratorFunctionPrototype,o,"GeneratorFunction"),_regeneratorDefine2(u),_regeneratorDefine2(u,o,"Generator"),_regeneratorDefine2(u,n,(function(){return this})),_regeneratorDefine2(u,"toString",(function(){return"[object Generator]"})),(_regenerator=function(){return{w:i,m:f}})()}function _regeneratorDefine2(e,r,n,t){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}(_regeneratorDefine2=function(e,r,n,t){function o(r,n){_regeneratorDefine2(e,r,(function(e){return this._invoke(r,n,e)}))}r?i?i(e,r,{value:n,enumerable:!t,configurable:!t,writable:!t}):e[r]=n:(o("next",0),o("throw",1),o("return",2))})(e,r,n,t)}function asyncGeneratorStep(n,t,e,r,o,a,c){try{var i=n[a](c),u=i.value}catch(n){return void e(n)}i.done?t(u):Promise.resolve(u).then(r,o)}function _asyncToGenerator(n){return function(){var t=this,e=arguments;return new Promise((function(r,o){var a=n.apply(t,e);function _next(n){asyncGeneratorStep(a,r,o,_next,_throw,"next",n)}function _throw(n){asyncGeneratorStep(a,r,o,_next,_throw,"throw",n)}_next(void 0)}))}}function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}function _defineProperties(e,r){for(var t=0;t<r.length;t++){var o=r[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,_toPropertyKey(o.key),o)}}function _toPropertyKey(t){var i=function(t,r){if("object"!=_typeof(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||"default");if("object"!=_typeof(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}(t,"string");return"symbol"==_typeof(i)?i:i+""}function parseArch(arch){switch(arch){case"x86_64":case"x64":return["x86","64"];case"x86_32":case"x86":return["x86",""];case"armv6l":case"armv7l":case"armv8l":return[arch,""];case"aarch64":return["arm","64"];default:return["",""]}}function padVersion(ver){var minSegs=arguments.length>1&&void 0!==arguments[1]?arguments[1]:3,parts=ver.split("."),len=parts.length;if(len<minSegs){for(var i=0,lenToPad=minSegs-len;i<lenToPad;i+=1)parts.push("0");return parts.join(".")}return ver}var NavigatorUAData=function(){return e=function NavigatorUAData(navigator){!function(a,n){if(!(a instanceof n))throw new TypeError("Cannot call a class as a function")}(this,NavigatorUAData),this._ch=function(navigator){var mobile,uaFullVersion,m,m2,userAgent=navigator.userAgent,platform="",platformVersion="",architecture="",bitness="",fullVersionList=[],platformInfo=userAgent,found=!1,versionInfo=userAgent.replace(/\(([^)]+)\)?/g,(function($0,$1){return found||(platformInfo=$1,found=!0),""})),items=versionInfo.match(/(\S+)\/(\S+)/g),webview=!1;if(mobile=-1!==userAgent.indexOf("Mobile"),null!==(m=/Windows NT (\d+(\.\d+)*)/.exec(platformInfo))){platform="Windows";var ver={6.1:"0.1",6.2:"0.2",6.3:"0.3","10.0":"10.0","11.0":"13.0"}[m[1]];ver&&(platformVersion=padVersion(ver,3)),null!==(m2=/\b(WOW64|Win64|x64)\b/.exec(platformInfo))&&(architecture="x86",bitness="64")}else null!==(m=/Android (\d+(\.\d+)*)/.exec(platformInfo))?(platform="Android",platformVersion=padVersion(m[1]),null!==(m2=/Linux (\w+)/.exec(navigator.platform))&&m2[1]&&(architecture=(m2=parseArch(m2[1]))[0],bitness=m2[1])):null!==(m=/(iPhone|iPod touch); CPU iPhone OS (\d+(_\d+)*)/.exec(platformInfo))||null!==(m=/(iPad); CPU OS (\d+(_\d+)*)/.exec(platformInfo))?(platform="iOS",platformVersion=padVersion(m[2].replace(/_/g,"."))):null!==(m=/Macintosh; (Intel|\w+) Mac OS X (\d+([_.]\d+)*)/.exec(platformInfo))?(platform="macOS",platformVersion=padVersion(m[2].replace(/_/g,"."))):null!==(m=/Linux/.exec(platformInfo))?(platform="Linux",platformVersion=""):null!==(m=/CrOS (\w+) (\d+(\.\d+)*)/.exec(platformInfo))&&(platform="Chrome OS",platformVersion=padVersion(m[2]),architecture=(m2=parseArch(m[1]))[0],bitness=m2[1]);if(platform||(platform="Unknown"),null!==(m=/Chrome\/(\d+(\.\d+)*)/.exec(versionInfo))&&"Google Inc."===navigator.vendor){if(fullVersionList.push({brand:"Chromium",version:padVersion(m[1],4)}),null!==(m2=/(Edge?)\/(\d+(\.\d+)*)/.exec(versionInfo))){var brand={Edge:"Microsoft Edge",Edg:"Microsoft Edge"}[m[1]];fullVersionList.push({brand:brand,version:padVersion(m2[2],4)})}else fullVersionList.push({brand:"Google Chrome",version:padVersion(m[1],4)});/\bwv\b/.exec(platformInfo)&&(webview=!0)}else if(null!==(m=/AppleWebKit\/(\d+(\.\d+)*)/.exec(versionInfo))&&"Apple Computer, Inc."===navigator.vendor){if(fullVersionList.push({brand:"WebKit",version:padVersion(m[1])}),"iOS"===platform&&null!=(m2=/(CriOS|EdgiOS|FxiOS|Version)\/(\d+(\.\d+)*)/.exec(versionInfo))){var _brand={CriOS:"Google Chrome",EdgiOS:"Microsoft Edge",FxiOS:"Mozilla Firefox",Version:"Apple Safari"}[m2[1]];fullVersionList.push({brand:_brand,version:padVersion(m2[2])}),-1===items.findIndex((function(s){return s.startsWith("Safari/")}))&&(webview=!0)}}else null!==(m=/Firefox\/(\d+(\.\d+)*)/.exec(versionInfo))?fullVersionList.push({brand:"Firefox",version:padVersion(m[1])}):fullVersionList.push({brand:" Not;A Brand",version:"99.0.0.0"});return uaFullVersion=fullVersionList.length>0?fullVersionList[fullVersionList.length-1]:"",{mobile:mobile,platform:platform,brands:fullVersionList.map((function(b){var pos=b.version.indexOf("."),version=-1===pos?b.version:b.version.slice(0,pos);return{brand:b.brand,version:version}})),platformVersion:platformVersion,architecture:architecture,bitness:bitness,model:"",uaFullVersion:uaFullVersion,fullVersionList:fullVersionList,webview:webview}}(navigator),Object.defineProperties(this,{_ch:{enumerable:!1}})},(r=[{key:"mobile",get:function(){return this._ch.mobile}},{key:"platform",get:function(){return this._ch.platform}},{key:"brands",get:function(){return this._ch.brands}},{key:"getHighEntropyValues",value:function(hints){var _this=this;return new Promise((function(resolve,reject){if(!Array.isArray(hints))throw new TypeError("argument hints is not an array");var hintSet=new Set(hints),data=_this._ch,obj={mobile:data.mobile,platform:data.platform,brands:data.brands};hintSet.has("architecture")&&(obj.architecture=data.architecture),hintSet.has("bitness")&&(obj.bitness=data.bitness),hintSet.has("model")&&(obj.model=data.model),hintSet.has("platformVersion")&&(obj.platformVersion=data.platformVersion),hintSet.has("uaFullVersion")&&(obj.uaFullVersion=data.uaFullVersion),hintSet.has("fullVersionList")&&(obj.fullVersionList=data.fullVersionList),resolve(obj)}))}},{key:"toJSON",value:function(){var data=this._ch;return{mobile:data.mobile,brands:data.brands}}}])&&_defineProperties(e.prototype,r),t&&_defineProperties(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,r,t}();function _getClientInfo(){return(_getClientInfo=_asyncToGenerator(_regenerator().m((function _callee(navigator,keys){var info,customUAData;return _regenerator().w((function(_context){for(;;)switch(_context.n){case 0:if(info={},"https:"!==location.protocol){_context.n=4;break}if(keys||(keys=["brands","mobile","platform","platformVersion","architecture","bitness","model","fullVersionList"]),navigator.userAgentData){_context.n=2;break}return customUAData=new NavigatorUAData(navigator),_context.n=1,customUAData.getHighEntropyValues(keys);case 1:info=_context.v,_context.n=4;break;case 2:return _context.n=3,navigator.userAgentData.getHighEntropyValues(keys);case 3:info=_context.v;case 4:return _context.a(2,info)}}),_callee)})))).apply(this,arguments)}Object.defineProperty(NavigatorUAData.prototype,Symbol.toStringTag,{enumerable:!1,configurable:!0,writable:!1,value:"NavigatorUAData"}),module.exports={getClientInfo:function(_x,_x2){return _getClientInfo.apply(this,arguments)}}},{}],39:[function(require,module,exports){"use strict";var SESSION_STATUS=Object.freeze({CONNECTED:"CONNECTED",ESTABLISHED:"ESTABLISHED",DISCONNECTED:"DISCONNECTED",WARN:"WARN",FAILED:"FAILED",DEBUG:"DEBUG",APP_DATA:"APP_DATA",SEND_DATA_STATUS:"SEND_DATA_STATUS",PENDING:"PENDING",REGISTERED:"REGISTERED",UNREGISTERED:"UNREGISTERED",INCOMING_CALL:"INCOMING_CALL"}),STREAM_STATUS=Object.freeze({NEW:"NEW",PENDING:"PENDING",PUBLISHING:"PUBLISHING",PLAYING:"PLAYING",PAUSED:"PAUSED",UNPUBLISHED:"UNPUBLISHED",STOPPED:"STOPPED",FAILED:"FAILED",PLAYBACK_PROBLEM:"PLAYBACK_PROBLEM",RESIZE:"RESIZE",SNAPSHOT_COMPLETE:"SNAPSHOT_COMPLETE",NOT_ENOUGH_BANDWIDTH:"NOT_ENOUGH_BANDWIDTH"}),CALL_STATUS=Object.freeze({NEW:"NEW",RING:"RING",RING_MEDIA:"RING_MEDIA",HOLD:"HOLD",ESTABLISHED:"ESTABLISHED",FINISH:"FINISH",BUSY:"BUSY",SESSION_PROGRESS:"SESSION_PROGRESS",FAILED:"FAILED",PENDING:"PENDING",TRYING:"TRYING"}),STREAM_STATUS_INFO=Object.freeze({FAILED_BY_ICE_ERROR:"Failed by ICE error",FAILED_BY_ICE_TIMEOUT:"Failed by ICE timeout",FAILED_BY_KEEP_ALIVE:"Failed by ICE keep alive",FAILED_BY_DTLS_FINGERPRINT_ERROR:"Failed by DTLS fingerprint error",FAILED_BY_DTLS_ERROR:"Failed by DTLS error",FAILED_BY_HLS_WRITER_ERROR:"Failed by HLS writer error",FAILED_BY_RTMP_WRITER_ERROR:"Failed by RTMP writer error",FAILED_BY_RTP_ACTIVITY:"Failed by RTP activity",STOPPED_BY_SESSION_DISCONNECT:"Stopped by session disconnect",STOPPED_BY_REST_TERMINATE:"Stopped by rest /terminate",STOPPED_BY_PUBLISHER_STOP:"Stopped by publisher stop",STOPPED_BY_USER:"Stopped by user",FAILED_BY_ERROR:"Failed by error",FAILED_TO_ADD_STREAM_TO_PROXY:"Failed to add stream to proxy",DISTRIBUTOR_STOPPED:"Distributor stopped",PUBLISH_STREAM_IS_NOT_READY:"Publish stream is not ready",STREAM_NOT_FOUND:"Stream not found",STREAM_NAME_ALREADY_IN_USE:"Stream name is already in use",MEDIASESSION_ID_NULL:"MediaSessionId is null",MEDIASESSION_ID_ALREADY_IN_USE:"MediaSessionId is already in use",SESSION_NOT_READY:"Session not ready",SESSION_DOES_NOT_EXIST:"Session does not exist",RTSP_HAS_WRONG_FORMAT:"Rtsp has wrong format",FILE_HAS_WRONG_FORMAT:"File has wrong format",FAILED_TO_CONNECT_TO_RTSP_STREAM:"Failed to connect to rtsp stream",RTSP_STREAM_NOT_FOUND:"Rtsp stream not found",RTSPAGENT_SHUTDOWN:"RtspAgent shutdown",STREAM_FAILED:"Stream failed",NO_COMMON_CODECS:"No common codecs",BAD_URI:"Bad URI",GOT_EXCEPTION_WHILE_STREAMING_FILE:"Got exception while streaming file",REQUESTED_STREAM_SHUTDOWN:"Requested stream shutdown",FAILED_TO_READ_FILE:"Failed to read file",FILE_NOT_FOUND:"File not found",FAILED_TO_CONNECT_TO_ORIGIN_STREAM:"Failed to connect to origin stream",CDN_STREAM_NOT_FOUND:"CDN stream not found",FAILED_TO_GET_AGENT_STORAGE:"Failed to get agent storage",AGENT_SERVICING_ORIGIN_STREAM_IS_SHUTTING_DOWN:"Agent servicing origin stream is shutting down",TERMINATED_BY_KEEP_ALIVE:"Terminated by keep-alive",TRANSCODING_REQUIRED_BUT_DISABLED:"Transcoding required, but disabled",RESTRICTED_ACCESS:"Restricted access",NO_AVAILABLE_TRANSCODERS:"No available transcoders"}),CALL_STATUS_INFO=Object.freeze({NORMAL_CALL_CLEARING:"Normal call clearing",FAILED_BY_SESSION_CREATION:"Failed by session creation",FAILED_BY_ICE_ERROR:"Failed by ICE error",FAILED_BY_RTP_ACTIVITY:"Failed by RTP activity",FAILED_BY_RTMP_WRITER_ERROR:"Failed by RTMP writer error",FAILED_BY_DTLS_FINGERPRINT_ERROR:"Failed by DTLS fingerprint error",NO_COMMON_CODECS:"No common codecs",FAILED_BY_DTLS_ERROR:"Failed by DTLS error",FAILED_BY_ERROR:"Failed by error",FAILED_BY_REQUEST_TIMEOUT:"Failed by request timeout",TRANSCODING_REQUIRED_BUT_DISABLED:"Transcoding required, but disabled"}),ERROR_INFO=Object.freeze({NONE_OF_MEDIAPROVIDERS_AVAILABLE:"None of MediaProviders available",NONE_OF_PREFERRED_MEDIAPROVIDERS_AVAILABLE:"None of preferred MediaProviders available",FLASHPHONER_API_NOT_INITIALIZED:"Flashphoner API is not initialized",OPTIONS_URLSERVER_MUST_BE_PROVIDED:"options.urlServer must be provided",INVALID_SESSION_STATE:"Invalid session state",OPTIONS_MUST_BE_PROVIDED:"options must be provided",INVALID_CALL_STATE:"Invalid call state",EVENT_CANT_BE_NULL:"Event can't be null",CALLBACK_NEEDS_TO_BE_A_VALID_FUNCTION:"Callback needs to be a valid function",OPTIONS_NAME_MUST_BE_PROVIDED:"options.name must be provided",CAN_NOT_SWITCH_CAM:"Number of cams is less than 2 or camera is already used by other application",CAN_NOT_SWITCH_MIC:"Number of mics is less than 2 or microphone is already used by other application",CAN_NOT_SET_RESOLUTION:"Cannot switch a published stream resolution",CAN_NOT_GET_STATS:"Cannot get PeerConnection stats",LOCAL_ERROR:"Local error"}),MEDIA_DEVICE_KIND=Object.freeze({OUTPUT:"output",INPUT:"input",ALL:"all"}),TRANSPORT_TYPE=Object.freeze({UDP:"UDP",TCP:"TCP"}),CONNECTION_QUALITY=Object.freeze({PERFECT:"PERFECT",GOOD:"GOOD",BAD:"BAD",UNKNOWN:"UNKNOWN",UPDATE:"UPDATE"}),STREAM_EVENT_TYPE=Object.freeze({AUDIO_MUTED:"audioMuted",AUDIO_UNMUTED:"audioUnmuted",VIDEO_MUTED:"videoMuted",VIDEO_UNMUTED:"videoUnmuted",DATA:"data",SNAPSHOT_COMPLETED:"snapshotCompleted",SNAPSHOT_FAILED:"snapshotFailed",RESIZE:"resize",NOT_ENOUGH_BANDWIDTH:"notEnoughBandwidth"}),CONTENT_HINT_TYPE=Object.freeze({MOTION:"motion",DETAIL:"detail",TEXT:"text"});module.exports={SESSION_STATUS:SESSION_STATUS,STREAM_STATUS:STREAM_STATUS,CALL_STATUS:CALL_STATUS,STREAM_STATUS_INFO:STREAM_STATUS_INFO,CALL_STATUS_INFO:CALL_STATUS_INFO,ERROR_INFO:ERROR_INFO,MEDIA_DEVICE_KIND:MEDIA_DEVICE_KIND,TRANSPORT_TYPE:TRANSPORT_TYPE,CONNECTION_QUALITY:CONNECTION_QUALITY,STREAM_EVENT:"STREAM_EVENT",STREAM_EVENT_TYPE:STREAM_EVENT_TYPE,CONTENT_HINT_TYPE:CONTENT_HINT_TYPE}},{}],40:[function(require,module,exports){"use strict";function _slicedToArray(r,e){return function(r){if(Array.isArray(r))return r}(r)||function(r,l){var t=null==r?null:"undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(null!=t){var e,n,i,u,a=[],f=!0,o=!1;try{if(i=(t=t.call(r)).next,0===l){if(Object(t)!==t)return;f=!1}else for(;!(f=(e=i.call(t)).done)&&(a.push(e.value),a.length!==l);f=!0);}catch(r){o=!0,n=r}finally{try{if(!f&&null!=t.return&&(u=t.return(),Object(u)!==u))return}finally{if(o)throw n}}return a}}(r,e)||function(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}(r,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}function _regenerator(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function i(r,n,o,i){var c=n&&n.prototype instanceof Generator?n:Generator,u=Object.create(c.prototype);return _regeneratorDefine2(u,"_invoke",function(r,n,o){var i,c,u,f=0,p=o||[],y=!1,G={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return i=t,c=0,u=e,G.n=r,a}};function d(r,n){for(c=r,u=n,t=0;!y&&f&&!o&&t<p.length;t++){var o,i=p[t],d=G.p,l=i[2];r>3?(o=l===n)&&(u=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&d<i[1])?(c=0,G.v=n,G.n=i[1]):d<l&&(o=r<3||i[0]>n||n>l)&&(i[4]=r,i[5]=n,G.n=l,c=0))}if(o||r>1)return a;throw y=!0,n}return function(o,p,l){if(f>1)throw TypeError("Generator is already running");for(y&&1===p&&d(p,l),c=p,u=l;(t=c<2?e:u)||!y;){i||(c?c<3?(c>1&&(G.n=-1),d(c,u)):G.n=u:G.v=u);try{if(f=2,i){if(c||(o="next"),t=i[o]){if(!(t=t.call(i,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);i=e}else if((t=(y=G.n<0)?u:r.call(n,G))!==a)break}catch(t){i=e,c=1,u=t}finally{f=1}}return{value:t,done:y}}}(r,o,i),!0),u}var a={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}t=Object.getPrototypeOf;var c=[][n]?t(t([][n]())):(_regeneratorDefine2(t={},n,(function(){return this})),t),u=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(c);function f(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,GeneratorFunctionPrototype):(e.__proto__=GeneratorFunctionPrototype,_regeneratorDefine2(e,o,"GeneratorFunction")),e.prototype=Object.create(u),e}return GeneratorFunction.prototype=GeneratorFunctionPrototype,_regeneratorDefine2(u,"constructor",GeneratorFunctionPrototype),_regeneratorDefine2(GeneratorFunctionPrototype,"constructor",GeneratorFunction),GeneratorFunction.displayName="GeneratorFunction",_regeneratorDefine2(GeneratorFunctionPrototype,o,"GeneratorFunction"),_regeneratorDefine2(u),_regeneratorDefine2(u,o,"Generator"),_regeneratorDefine2(u,n,(function(){return this})),_regeneratorDefine2(u,"toString",(function(){return"[object Generator]"})),(_regenerator=function(){return{w:i,m:f}})()}function _regeneratorDefine2(e,r,n,t){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}(_regeneratorDefine2=function(e,r,n,t){function o(r,n){_regeneratorDefine2(e,r,(function(e){return this._invoke(r,n,e)}))}r?i?i(e,r,{value:n,enumerable:!t,configurable:!t,writable:!t}):e[r]=n:(o("next",0),o("throw",1),o("return",2))})(e,r,n,t)}function asyncGeneratorStep(n,t,e,r,o,a,c){try{var i=n[a](c),u=i.value}catch(n){return void e(n)}i.done?t(u):Promise.resolve(u).then(r,o)}function _asyncToGenerator(n){return function(){var t=this,e=arguments;return new Promise((function(r,o){var a=n.apply(t,e);function _next(n){asyncGeneratorStep(a,r,o,_next,_throw,"next",n)}function _throw(n){asyncGeneratorStep(a,r,o,_next,_throw,"throw",n)}_next(void 0)}))}}var coreLogger,clientUAData,disableConnectionQualityCalculation,uuid_v1=require("uuid").v1,constants=require("./constants"),util=require("./util"),LoggerObject=require("./util").logger,clientInfo=require("./client-info"),StatsCollector=require("./stats-collector"),_Promise=require("promise-polyfill"),KalmanFilter=require("kalmanjs"),browserDetails=require("webrtc-adapter").default.browserDetails,loggerConf={push:!1,severity:"INFO"},isUsingTemasysPlugin=!1,SESSION_STATUS=constants.SESSION_STATUS,STREAM_EVENT=constants.STREAM_EVENT,STREAM_EVENT_TYPE=constants.STREAM_EVENT_TYPE,STREAM_STATUS=constants.STREAM_STATUS,CALL_STATUS=constants.CALL_STATUS,CONNECTION_QUALITY=constants.CONNECTION_QUALITY,ERROR_INFO=constants.ERROR_INFO,MediaProvider={},sessions={},initialized=!1,init=function(){var _ref=_asyncToGenerator(_regenerator().m((function _callee(options){var waitingTemasys,audioContext,webRtcProvider,enableGainNode,webRtcConf,mediaSourceMediaProvider,mseConf,websocketProvider,wsConf,_MediaProvider,p,newMediaProvider,i,pMP;return _regenerator().w((function(_context){for(;;)switch(_context.n){case 0:if(initialized){_context.n=6;break}options||(options={}),coreLogger=createLogger(options.logger),waitingTemasys=!1;try{audioContext=new(window.AudioContext||window.webkitAudioContext)}catch(e){console.warn("Failed to create audio context")}if(disableConnectionQualityCalculation=options.disableConnectionQualityCalculation,(webRtcProvider=require("./webrtc-media-provider"))&&webRtcProvider.hasOwnProperty("available")&&webRtcProvider.available()?(MediaProvider.WebRTC=webRtcProvider,enableGainNode=!util.Browser.isSamsungBrowser()&&!util.Browser.isAndroidFirefox()&&options.createMicGainNode,webRtcConf={constraints:options.constraints||getDefaultMediaConstraints(),extensionId:options.screenSharingExtensionId,audioContext:audioContext,logger:coreLogger,createMicGainNode:enableGainNode},webRtcProvider.configure(webRtcConf)):(webRtcProvider=require("./temasys-media-provider"))&&webRtcProvider.hasOwnProperty("available")&&AdapterJS&&(waitingTemasys=!0,AdapterJS.webRTCReady((function(isUsingPlugin){if(isUsingTemasysPlugin=isUsingPlugin,isUsingPlugin||webRtcProvider.available()){MediaProvider.WebRTC=webRtcProvider;var webRtcConf={constraints:options.constraints||getDefaultMediaConstraints(),extensionId:options.screenSharingExtensionId,logger:coreLogger};webRtcProvider.configure(webRtcConf);var _MediaProvider={};for(var p in _MediaProvider.WebRTC=MediaProvider.WebRTC,MediaProvider)_MediaProvider[p]=MediaProvider[p];MediaProvider=_MediaProvider}options.mediaProvidersReadyCallback&&options.mediaProvidersReadyCallback(Object.keys(MediaProvider))}))),null,(mediaSourceMediaProvider=require("./media-source-media-provider"))&&mediaSourceMediaProvider.hasOwnProperty("available")&&mediaSourceMediaProvider.available()&&(MediaProvider.MSE=mediaSourceMediaProvider,mseConf={audioContext:audioContext,browserDetails:browserDetails.browser},mediaSourceMediaProvider.configure(mseConf)),(websocketProvider=require("./websocket-media-provider"))&&websocketProvider.hasOwnProperty("available")&&websocketProvider.available(audioContext)&&(MediaProvider.WSPlayer=websocketProvider,wsConf={receiverLocation:options.receiverLocation,decoderLocation:options.decoderLocation,audioContext:audioContext,logger:coreLogger},websocketProvider.configure(wsConf)),0!=getMediaProviders().length){_context.n=1;break}throw new Error("None of MediaProviders available");case 1:if(options.preferredMediaProvider)if(MediaProvider.hasOwnProperty(options.preferredMediaProvider)){if(getMediaProviders()[0]!=options.preferredMediaProvider){for(p in(_MediaProvider={})[options.preferredMediaProvider]=MediaProvider[options.preferredMediaProvider],MediaProvider)_MediaProvider[p]=MediaProvider[p];MediaProvider=_MediaProvider}}else corelogger.warn("core","Preferred media provider is not available.");case 2:if(!(options.preferredMediaProviders&&options.preferredMediaProviders.length>0)){_context.n=4;break}for(i in newMediaProvider={},options.preferredMediaProviders)options.preferredMediaProviders.hasOwnProperty(i)&&(pMP=options.preferredMediaProviders[i],MediaProvider.hasOwnProperty(pMP)&&(newMediaProvider[pMP]=MediaProvider[pMP]));if(!util.isEmptyObject(newMediaProvider)){_context.n=3;break}throw new Error("None of preferred MediaProviders available");case 3:MediaProvider=newMediaProvider;case 4:if(!waitingTemasys&&options.mediaProvidersReadyCallback&&options.mediaProvidersReadyCallback(Object.keys(MediaProvider)),coreLogger.info("core","Initialized"),initialized=!0,void 0!==options.collectClientInfo&&!options.collectClientInfo){_context.n=6;break}return _context.n=5,clientInfo.getClientInfo(window.navigator);case 5:clientUAData=_context.v,coreLogger.info("core","Client system data: "+JSON.stringify(clientUAData));case 6:return _context.a(2)}}),_callee)})));return function(_x){return _ref.apply(this,arguments)}}(),getMediaProviders=function(){return Object.keys(MediaProvider)},getDefaultMediaConstraints=function(){return"safari"==browserDetails.browser?{audio:!0,video:{width:{min:320,max:640},height:{min:180,max:360}}}:{audio:!0,video:{width:320,height:240}}};function getConstraintsProperty(constraints,property,defaultValue){if(!constraints||!property)return defaultValue;var res,properties=property.split(".");for(var prop in constraints)if(prop==properties[0])res=constraints[prop],properties.length>1&&(res=getConstraintsProperty(constraints[prop],properties[1],defaultValue));else if("object"===_typeof(constraints[prop]))for(var p in constraints[prop])p==property&&(res=constraints[prop][p]);return"boolean"==typeof res?res:res||defaultValue}var releaseLocalMedia=function(display,mediaProvider){if(!initialized)throw new Error("Flashphoner API is not initialized");return mediaProvider||(mediaProvider=getMediaProviders()[0]),MediaProvider[mediaProvider].releaseMedia(display)},getLoggerConf=function(loggerOptions){var conf=loggerOptions||loggerConf;return null!==loggerOptions&&(conf.enableLogs=!0),conf},createLogger=function(loggerOptions){var parentLogger=arguments.length>1&&void 0!==arguments[1]?arguments[1]:coreLogger,newLogger=parentLogger;if(void 0===newLogger||null!=loggerOptions){var loggerConf=getLoggerConf(loggerOptions);(newLogger=new LoggerObject).init(loggerConf.severity||"INFO",loggerConf.push||!1,loggerConf.customLogger,loggerConf.enableLogs)}return newLogger};module.exports={init:init,isUsingTemasys:function(){return isUsingTemasysPlugin},getMediaProviders:getMediaProviders,getMediaDevices:function(mediaProvider,labels,kind,deviceConstraints){if(!initialized)throw new Error("Flashphoner API is not initialized");return mediaProvider||(mediaProvider=getMediaProviders()[0]),MediaProvider[mediaProvider].listDevices(labels,kind,deviceConstraints)},getMobileDevices:function(mediaProvider,kind,deviceConstraints){if(!initialized)throw new Error("Flashphoner API is not initialized");return mediaProvider||(mediaProvider=getMediaProviders()[0]),MediaProvider[mediaProvider].getMobileDevices?MediaProvider[mediaProvider].getMobileDevices(kind,deviceConstraints):[]},getMediaAccess:function(constraints,display,mediaProvider,disableConstraintsNormalization){if(!initialized)throw new Error("Flashphoner API is not initialized");return mediaProvider||(mediaProvider=getMediaProviders()[0]),MediaProvider[mediaProvider].getMediaAccess(constraints,display,disableConstraintsNormalization)},releaseLocalMedia:releaseLocalMedia,getSessions:function(){return util.copyObjectToArray(sessions)},getSession:function(id){return sessions[id]},createSession:function(options){if(!initialized)throw new Error("Flashphoner API is not initialized");if(!options||!options.urlServer)throw new TypeError("options.urlServer must be provided");var connectionTimeout,cConfig,sipConfig,sessionLogger=createLogger(options.logger),logger=sessionLogger,id_=uuid_v1(),sessionStatus=SESSION_STATUS.PENDING,urlServer=options.urlServer,lbUrl=options.lbUrl,flashProto=options.flashProto||"rtmfp",flashPort=options.flashPort||1935,appKey=options.appKey||"defaultApp",mediaOptions=options.mediaOptions,keepAlive=options.keepAlive,timeout=options.timeout,sendClientInfo=void 0===options.sendClientInfo||options.sendClientInfo,wsPingSender=new function(interval){return this.interval=interval||0,this.intervalId=null,this.start=function(){this.interval>0&&(this.intervalId=setInterval((function(){send("ping",null)}),this.interval))},this.stop=function(){this.intervalId&&clearInterval(this.intervalId)},this}(options.pingInterval||0),wsPingReceiver=new function(receiveProbes,probesInterval){return this.maxPings=receiveProbes||0,this.interval=probesInterval||0,this.intervalId=null,this.pingsMissing=0,this.start=function(){if(this.maxPings>0&&this.interval>0){var receiver=this;this.intervalId=setInterval((function(){receiver.checkPingsReceived()}),this.interval)}},this.stop=function(){this.intervalId&&clearInterval(this.intervalId),this.pingsMissing=0},this.checkPingsReceived=function(){this.pingsMissing++,this.pingsMissing>=this.maxPings&&this.failure()},this.success=function(){this.pingsMissing=0},this.failure=function(){logger.info("core","Missing "+this.pingsMissing+" pings from server, connection seems to be down"),onSessionStatusChange(SESSION_STATUS.FAILED),wsConnection.close()},this}(options.receiveProbes||0,options.probesInterval||0);options.sipOptions&&(sipConfig={sipLogin:options.sipOptions.login,sipAuthenticationName:options.sipOptions.authenticationName,sipPassword:options.sipOptions.password,sipDomain:options.sipOptions.domain,sipOutboundProxy:options.sipOptions.outboundProxy,sipProxy:options.sipOptions.proxy,sipPort:options.sipOptions.port,sipRegisterRequired:options.sipOptions.registerRequired});var wsConnection,webRTCMetricsServerDescription,url,request,authToken=options.authToken,streams={},calls={},mediaConnections={},streamEventRefreshHandlers={},streamRefreshHandlers={},callRefreshHandlers={},session={},callbacks={};lbUrl?(url=lbUrl,(request=new XMLHttpRequest).open("GET",url,!0),request.timeout=5e3,request.ontimeout=function(){logger.warn("core","Timeout during geting url from balancer!"),createWS(urlServer)},request.error=function(){logger.warn("core","Error during geting url from balancer!"),createWS(urlServer)},request.onload=function(e){if(200==request.status&&4==request.readyState){var result=JSON.parse(request.responseText);urlServer=-1!==urlServer.indexOf("wss://")?"wss://"+result.server+":"+result.wss:"ws://"+result.server+":"+result.ws,flashPort=result.flash,logger.debug("core","Got url from load balancer "+result.server),createWS(urlServer)}},request.send()):createWS(urlServer);var remoteSdpCache={};function createWS(url){wsConnection=new WebSocket(url),null!=timeout&&timeout>0&&(connectionTimeout=setTimeout((function(){0==wsConnection.readyState&&(logger.warn("core","WS connection timeout"),wsConnection.close())}),timeout)),wsConnection.onerror=function(){onSessionStatusChange(SESSION_STATUS.FAILED)},wsConnection.onclose=function(){sessionStatus!==SESSION_STATUS.FAILED&&onSessionStatusChange(SESSION_STATUS.DISCONNECTED)},wsConnection.onopen=function(){onSessionStatusChange(SESSION_STATUS.CONNECTED),clearTimeout(connectionTimeout),cConfig={appKey:appKey,mediaProviders:Object.keys(MediaProvider),keepAlive:keepAlive,authToken:authToken,clientVersion:"2.0",clientOSVersion:window.navigator.appVersion,clientBrowserVersion:window.navigator.userAgent,msePacketizationVersion:2,custom:options.custom},sendClientInfo&&clientUAData&&(cConfig.clientInfo=clientUAData),sipConfig&&util.copyObjectPropsToAnotherObject(sipConfig,cConfig),send("connection",cConfig),logger.setConnection(wsConnection),wsPingSender.start(),wsPingReceiver.start()},wsConnection.onmessage=function(event){var data={};if(event.data instanceof Blob)data.message="binaryData";else var obj=(data=JSON.parse(event.data)).data[0];switch(data.message){case"ping":logger.debug("core","<<< ping"),send("pong",null),logger.debug("core",">>> pong");break;case"getUserData":authToken=obj.authToken,cConfig=obj,webRTCMetricsServerDescription=obj.webRTCMetricsServerDescription,onSessionStatusChange(SESSION_STATUS.ESTABLISHED,obj);break;case"setRemoteSDP":var mediaSessionId=data.data[0],sdp=data.data[1];streamRefreshHandlers[mediaSessionId]?streamRefreshHandlers[mediaSessionId](null,sdp):callRefreshHandlers[mediaSessionId]?callRefreshHandlers[mediaSessionId](null,sdp):(remoteSdpCache[mediaSessionId]=sdp,logger.info("core","Media not found, id "+mediaSessionId));break;case"notifyVideoFormat":case"notifyStreamStatusEvent":streamRefreshHandlers[obj.mediaSessionId]&&streamRefreshHandlers[obj.mediaSessionId](obj);break;case"notifyStreamEvent":streamEventRefreshHandlers[obj.mediaSessionId]&&streamEventRefreshHandlers[obj.mediaSessionId](obj);break;case"DataStatusEvent":restAppCommunicator.resolveData(obj);break;case"OnDataEvent":callbacks[SESSION_STATUS.APP_DATA]&&callbacks[SESSION_STATUS.APP_DATA](obj);break;case"fail":obj.apiMethod&&"StreamStatusEvent"==obj.apiMethod&&streamRefreshHandlers[obj.id]&&streamRefreshHandlers[obj.id](obj),callbacks[SESSION_STATUS.WARN]&&callbacks[SESSION_STATUS.WARN](obj);break;case"registered":onSessionStatusChange(SESSION_STATUS.REGISTERED);break;case"notifyAudioCodec":mediaSessionId=data.data[0];var codec=data.data[1];callRefreshHandlers[mediaSessionId]&&callRefreshHandlers[mediaSessionId](null,null,codec);break;case"notifyTransferEvent":callRefreshHandlers[obj.callId](null,null,null,obj);break;case"notifyTryingResponse":case"hold":case"ring":case"talk":case"finish":callRefreshHandlers[obj.callId]&&callRefreshHandlers[obj.callId](obj);break;case"notifyIncomingCall":callRefreshHandlers[obj.callId]&&logger.error("core","Call already exists, id "+obj.callId),callbacks[SESSION_STATUS.INCOMING_CALL]&&callbacks[SESSION_STATUS.INCOMING_CALL](createCall(obj));break;case"notifySessionDebugEvent":logger.info("core","Session debug status "+obj.status),callbacks[SESSION_STATUS.DEBUG]&&callbacks[SESSION_STATUS.DEBUG](obj);break;case"availableStream":var availableStream={};availableStream.mediaSessionId=obj.id,availableStream.available=obj.status,availableStream.reason=obj.info,streamRefreshHandlers[availableStream.mediaSessionId]&&streamRefreshHandlers[availableStream.mediaSessionId](availableStream);break;case"outboundVideoRate":case"inboundVideoRate":streamRefreshHandlers[obj.mediaSessionId]&&(obj.status=data.message,streamRefreshHandlers[obj.mediaSessionId](obj));break;case"webRTCMetricsDescriptionUpdate":handleWebRTCMetricsUpdate(obj,{compression:"compression",batchSize:"batchSize",sampling:"sampling",types:"types",collect:"collect"});break;case"webRTCMetricsTokenRefresh":handleWebRTCMetricsUpdate(obj,{authorization:"authorization"});break;default:logger.info("core","Unknown server message "+data.message)}logger.debug("core","Reset missing pings counter by "+data.message+" message"),wsPingReceiver.success()}}function handleWebRTCMetricsUpdate(obj){var updateFields=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(obj.ids)obj.ids.forEach((function(id){streamRefreshHandlers[id]&&streamRefreshHandlers[id](obj)}));else{Object.entries(updateFields).forEach((function(_ref2){var _ref3=_slicedToArray(_ref2,2),key=_ref3[0],value=_ref3[1];void 0!==obj[value]&&(webRTCMetricsServerDescription[key]=obj[value])}));for(var _i=0,_Object$entries=Object.entries(streamRefreshHandlers);_i<_Object$entries.length;_i++){var _Object$entries$_i=_slicedToArray(_Object$entries[_i],2),handler=(_Object$entries$_i[0],_Object$entries$_i[1]);handler(obj)}}}function send(message,data){wsConnection.readyState===WebSocket.OPEN&&wsConnection.send(JSON.stringify({message:message,data:[data]}))}function onSessionStatusChange(newStatus,obj){if((sessionStatus=newStatus)==SESSION_STATUS.DISCONNECTED||sessionStatus==SESSION_STATUS.FAILED){for(var prop in wsPingSender.stop(),wsPingReceiver.stop(),streamRefreshHandlers)streamRefreshHandlers.hasOwnProperty(prop)&&"function"==typeof streamRefreshHandlers[prop]&&streamRefreshHandlers[prop]({status:STREAM_STATUS.FAILED});delete sessions[id_]}callbacks[sessionStatus]&&callbacks[sessionStatus](session,obj)}var createCall=function(options){if(sessionStatus!==SESSION_STATUS.REGISTERED&&sessionStatus!==SESSION_STATUS.ESTABLISHED)throw new Error("Invalid session state "+sessionStatus);if(!options)throw new TypeError("options must be provided");var mediaConnection,info_,errorInfo_,audioOutputId,callLogger=createLogger(options.logger,sessionLogger),logger=callLogger,login="clickToCallApp"==appKey?"":cConfig.sipLogin,caller_=options.incoming?options.caller:login,callee_=options.callee,visibleName_=options.visibleName||login,id_=options.callId||uuid_v1(),mediaProvider=options.mediaProvider||getMediaProviders()[0],localDisplay=options.localVideoDisplay,remoteDisplay=options.remoteVideoDisplay;if(options.constraints)var constraints=options.constraints;if(options.disableConstraintsNormalization)var disableConstraintsNormalization=options.disableConstraintsNormalization;var audioProperty=getConstraintsProperty(constraints,"audio",void 0);"object"===_typeof(audioProperty)&&(audioOutputId=getConstraintsProperty(audioProperty,"outputId",0));var stripCodecs=options.stripCodecs||[],receiveAudio="undefined"==typeof options.receiveAudio||options.receiveAudio,receiveVideo="undefined"==typeof options.receiveVideo||options.receiveVideo,cacheLocalResources=options.cacheLocalResources,status_=CALL_STATUS.NEW,callbacks={},hasTransferredCall=!1,sdpHook=options.sdpHook,sipSDP=options.sipSDP,videoContentHint=(options.sipHeaders,options.videoContentHint),useControls=options.useControls,collectDeviceInfo=void 0===options.collectDeviceInfo||options.collectDeviceInfo,minBitrate=getConstraintsProperty(constraints,"video.minBitrate",0),maxBitrate=getConstraintsProperty(constraints,"video.maxBitrate",0),call={};callRefreshHandlers[id_]=function(callInfo,sdp,codec,transfer){if(transfer)return mediaConnections[id_]||(mediaConnections[id_]=mediaConnection),void("COMPLETED"==transfer.status&&delete mediaConnections[id_]);if(!mediaConnection&&0!=Object.keys(mediaConnections).length)for(var mc in mediaConnections)mediaConnection=mediaConnections[mc],hasTransferredCall=!0,delete mediaConnections[mc];if(codec)"Flash"==mediaProvider&&mediaConnection.changeAudioCodec(codec.name);else{if(sdp&&""!==sdp)return sdp=sdpHookHandler(sdp,sdpHook),sdp=util.setPublishingBitrate(sdp,mediaConnection,minBitrate,maxBitrate),void mediaConnection.setRemoteSdp(sdp,hasTransferredCall,id_).then((function(){}));var event=callInfo.status;status_=event,event!=CALL_STATUS.FAILED&&event!=CALL_STATUS.FINISH&&event!=CALL_STATUS.BUSY||(delete calls[id_],delete callRefreshHandlers[id_],0==Object.keys(calls).length&&mediaConnection&&mediaConnection.close(cacheLocalResources)),callbacks[event]&&callbacks[event](call)}};var hangup=function(){if(status_!=CALL_STATUS.NEW){if(status_==CALL_STATUS.PENDING)return cacheLocalResources||releaseLocalMedia(localDisplay,mediaProvider),callRefreshHandlers[id_]({status:CALL_STATUS.FAILED}),void(options.incoming&&send("hangup",{callId:id_}));send("hangup",{callId:id_}),mediaConnection&&mediaConnection.close(cacheLocalResources)}else callRefreshHandlers[id_]({status:CALL_STATUS.FAILED})};return call.call=function(){if(status_!==CALL_STATUS.NEW)throw new Error("Invalid call state");status_=CALL_STATUS.PENDING;MediaProvider[mediaProvider].getMediaAccess(constraints,localDisplay,disableConstraintsNormalization).then((function(){status_!=CALL_STATUS.FAILED?MediaProvider[mediaProvider].createConnection({id:id_,localDisplay:localDisplay,remoteDisplay:remoteDisplay,authToken:authToken,mainUrl:urlServer,flashProto:flashProto,flashPort:flashPort,bidirectional:!0,login:login,constraints:constraints,connectionConfig:mediaOptions,audioOutputId:audioOutputId,videoContentHint:videoContentHint,useControls:useControls,logger:logger}).then((function(newConnection){return(mediaConnection=newConnection).createOffer({sendAudio:!0,sendVideo:!0,receiveAudio:receiveAudio,receiveVideo:receiveVideo,stripCodecs:stripCodecs})})).then((function(offer){var callData={callId:id_,incoming:!1,hasVideo:offer.hasVideo,hasAudio:offer.hasAudio,status:status_,mediaProvider:mediaProvider,sdp:offer.sdp,sipSDP:sipSDP,caller:login,callee:callee_,custom:options.custom,visibleName:visibleName_};collectDeviceInfo&&(callData.localMediaInfo=collectLocalMediaInfo(MediaProvider[mediaProvider],localDisplay)),send("call",callData)})):cacheLocalResources||releaseLocalMedia(localDisplay,mediaProvider)})).catch((function(error){logger.error("core",error),status_=CALL_STATUS.FAILED,info_=ERROR_INFO.LOCAL_ERROR,errorInfo_=error.message,callRefreshHandlers[id_]({status:CALL_STATUS.FAILED}),hangup()}))},call.answer=function(answerOptions){if(status_!==CALL_STATUS.NEW&&status_!==CALL_STATUS.RING)throw new Error("Invalid call state");var sdp;localDisplay=answerOptions.localVideoDisplay,remoteDisplay=answerOptions.remoteVideoDisplay,constraints=answerOptions.constraints||getDefaultMediaConstraints(),status_=CALL_STATUS.PENDING;var sdpHook=answerOptions.sdpHook,minBitrate=getConstraintsProperty(constraints,"video.minBitrate",0),maxBitrate=getConstraintsProperty(constraints,"video.maxBitrate",0);if(sipSDP=answerOptions.sipSDP,answerOptions.sipHeaders,!remoteSdpCache[id_])throw logger.error("core","No remote sdp available"),new Error("No remote sdp available");sdp=sdpHookHandler(remoteSdpCache[id_],sdpHook),sdp=util.setPublishingBitrate(sdp,null,minBitrate,maxBitrate),delete remoteSdpCache[id_],0==util.SDP.matchPrefix(sdp,"m=video").length&&(constraints.video=!1);var stripCodecs=answerOptions.stripCodecs||[];MediaProvider[mediaProvider].getMediaAccess(constraints,localDisplay,disableConstraintsNormalization).then((function(){status_!=CALL_STATUS.FAILED?MediaProvider[mediaProvider].createConnection({id:id_,localDisplay:localDisplay,remoteDisplay:remoteDisplay,authToken:authToken,mainUrl:urlServer,flashProto:flashProto,flashPort:flashPort,bidirectional:!0,login:cConfig.sipLogin,constraints:constraints,connectionConfig:mediaOptions,audioOutputId:audioOutputId,useControls:useControls}).then((function(newConnection){return(mediaConnection=newConnection).setPublishingBitrate(minBitrate,maxBitrate),mediaConnection.setRemoteSdp(sdp)})).then((function(){return mediaConnection.createAnswer({receiveAudio:options.receiveAudio,receiveVideo:options.receiveVideo,stripCodecs:stripCodecs})})).then((function(sdp){if(status_!=CALL_STATUS.FINISH&&status_!=CALL_STATUS.FAILED){var callData={callId:id_,incoming:!0,hasVideo:!0,hasAudio:!0,status:status_,mediaProvider:mediaProvider,sdp:sdp,sipSDP:sipSDP,caller:cConfig.login,callee:callee_,custom:options.custom};collectDeviceInfo&&(callData.localMediaInfo=collectLocalMediaInfo(MediaProvider[mediaProvider],localDisplay)),send("answer",callData)}else hangup()})):cacheLocalResources||releaseLocalMedia(localDisplay,mediaProvider)})).catch((function(error){logger.error("core",error),info_=ERROR_INFO.LOCAL_ERROR,errorInfo_=error.message,status_=CALL_STATUS.FAILED,callRefreshHandlers[id_]({status:CALL_STATUS.FAILED})}))},call.hangup=hangup,call.id=function(){return id_},call.getInfo=function(){return info_},call.getErrorInfo=function(){return errorInfo_},call.status=function(){return status_},call.getStats=function(callbackFn,nativeStats){mediaConnection&&mediaConnection.getStats(callbackFn,nativeStats)},call.setAudioOutputId=function(id){if(audioOutputId=id,mediaConnection&&mediaConnection.setAudioOutputId)return mediaConnection.setAudioOutputId(id)},call.setVolume=function(volume){mediaConnection&&mediaConnection.setVolume(volume)},call.getVolume=function(){return mediaConnection?mediaConnection.getVolume():-1},call.muteAudio=function(){mediaConnection&&mediaConnection.muteAudio()},call.unmuteAudio=function(){mediaConnection&&mediaConnection.unmuteAudio()},call.isAudioMuted=function(){return!mediaConnection||mediaConnection.isAudioMuted()},call.muteVideo=function(){mediaConnection&&mediaConnection.muteVideo()},call.unmuteVideo=function(){mediaConnection&&mediaConnection.unmuteVideo()},call.isVideoMuted=function(){return!mediaConnection||mediaConnection.isVideoMuted()},call.caller=function(){return caller_},call.callee=function(){return callee_},call.visibleName=function(){return visibleName_},call.hold=function(){send("hold",{callId:id_})},call.holdForTransfer=function(){send("hold",{callId:id_,holdForTransfer:!0})},call.unhold=function(){send("unhold",{callId:id_})},call.sendDTMF=function(number,type){send("sendDtmf",{callId:id_,type:type||"RFC2833",dtmf:number})},call.transfer=function(target){send("transfer",{callId:id_,target:target})},call.on=function(event,callback){if(!event)throw new TypeError("Event can't be null");if(!callback||"function"!=typeof callback)throw new Error("Callback needs to be a valid function");return callbacks[event]=callback,call},call.switchCam=function(deviceId){if(status_!==CALL_STATUS.ESTABLISHED&&!constraints.video&&status_!==CALL_STATUS.HOLD)throw new Error("Invalid call state");return mediaConnection.switchCam(deviceId)},call.switchMic=function(deviceId){if(status_!==CALL_STATUS.ESTABLISHED&&status_!==CALL_STATUS.HOLD)throw new Error("Invalid call state");return mediaConnection.switchMic(deviceId)},call.switchToScreen=function(source,woExtension){if(status_!==CALL_STATUS.ESTABLISHED&&status_!==CALL_STATUS.HOLD)throw new Error("Invalid call state");return mediaConnection.switchToScreen(source,woExtension)},call.switchToCam=function(){if(status_!==CALL_STATUS.ESTABLISHED&&status_!==CALL_STATUS.HOLD)throw new Error("Invalid call state");mediaConnection.switchToCam()},call.getLogger=function(){return callLogger},calls[id_]=call,call},restAppCommunicator=function(){var pending={},exports={sendData:function(data){return new _Promise((function(resolve,reject){var obj={operationId:uuid_v1(),payload:data};pending[obj.operationId]={FAILED:function(info){reject(info)},ACCEPTED:function(info){resolve(info)}},send("sendData",obj)}))},resolveData:function(data){if(pending[data.operationId]){var handler=pending[data.operationId];delete pending[data.operationId],delete data.operationId,handler[data.status](data)}}};return exports}(),sdpHookHandler=function(sdp,sdpHook){if(null!=sdpHook&&"function"==typeof sdpHook){var newSdp=sdpHook({sdpString:sdp});return null!=newSdp&&""!=newSdp?newSdp:sdp}return sdp},collectLocalMediaInfo=function(mediaProvider,display){var videoCams=[],mics=[];mediaProvider.videoCams&&mediaProvider.videoCams.forEach((function(device){videoCams.push({id:device.id,label:encodeURI(device.label),type:device.type})})),mediaProvider.mics&&mediaProvider.mics.forEach((function(device){mics.push({id:device.id,label:encodeURI(device.label),type:device.type})})),videoCams.length&&logger.info("core","Video inputs available: "+JSON.stringify(videoCams)),mics.length&&logger.info("core","Audio inputs available: "+JSON.stringify(mics));var localVideo,audioTracks=[],videoTracks=[];return mediaProvider.getCacheInstance&&(localVideo=mediaProvider.getCacheInstance(display)),!localVideo&&mediaProvider.getVideoElement&&(localVideo=mediaProvider.getVideoElement(display)),localVideo&&localVideo.srcObject&&(localVideo.srcObject.getAudioTracks().forEach((function(track){var device=track.label;"MediaStreamAudioDestinationNode"===device&&mediaProvider.getAudioSourceDevice&&(device=mediaProvider.getAudioSourceDevice()),audioTracks.push({trackId:track.id,device:encodeURI(device)})})),localVideo.srcObject.getVideoTracks().forEach((function(track){videoTracks.push({trackId:track.id,device:encodeURI(track.label)})}))),videoTracks.length&&logger.info("core","Video tracks captured: "+JSON.stringify(videoTracks)),audioTracks.length&&logger.info("core","Audio tracks captured: "+JSON.stringify(audioTracks)),{devices:{video:videoCams,audio:mics},tracks:{video:videoTracks,audio:audioTracks}}};return session.id=function(){return id_},session.status=function(){return sessionStatus},session.getServerUrl=function(){return urlServer},session.createStream=function(options){var availableCallbacks=[];if(sessionStatus!==SESSION_STATUS.ESTABLISHED)throw new Error("Invalid session state "+sessionStatus);if(!options)throw new TypeError("options must be provided");if(!options.name)throw new TypeError("options.name must be provided");var mediaConnection,streamLogger=createLogger(options.logger,sessionLogger),logger=streamLogger,clientKf=new KalmanFilter,serverKf=new KalmanFilter,id_=uuid_v1(),name_=options.name,mediaProvider=options.mediaProvider||getMediaProviders()[0],display=options.display;if(options.constraints&&0!=Object.keys(options.constraints).length)var constraints=options.constraints;if(options.disableConstraintsNormalization)var disableConstraintsNormalization=options.disableConstraintsNormalization;var receiveAudio,audioOutputId,receiveVideo,mediaConnectionConstraints=options.mediaConnectionConstraints,audioProperty=getConstraintsProperty(constraints,"audio",void 0);if("boolean"==typeof audioProperty)receiveAudio=audioProperty;else if("object"===_typeof(audioProperty)){receiveAudio=!0;var _stereo=getConstraintsProperty(audioProperty,"stereo",0),_bitrate=getConstraintsProperty(audioProperty,"bitrate",0),_fec=getConstraintsProperty(audioProperty,"fec",0);audioOutputId=getConstraintsProperty(audioProperty,"outputId",0);var _codecOptions="";_bitrate&&(_codecOptions+="maxaveragebitrate="+_bitrate+";"),_stereo&&(_codecOptions+="stereo=1;sprop-stereo=1;"),_fec&&(_codecOptions+="useinbandfec=1;")}else receiveAudio="undefined"==typeof options.receiveAudio||options.receiveAudio;var videoProperty=getConstraintsProperty(constraints,"video",void 0);receiveVideo="boolean"==typeof videoProperty?videoProperty:"object"===_typeof(videoProperty)||("undefined"==typeof options.receiveVideo||options.receiveVideo);var bitrate=getConstraintsProperty(constraints,"video.bitrate",0),minBitrate=getConstraintsProperty(constraints,"video.minBitrate",0),maxBitrate=getConstraintsProperty(constraints,"video.maxBitrate",0),quality=getConstraintsProperty(constraints,"video.quality",0);quality>100&&(quality=100);var info_,errorInfo_,audioState_,videoState_,connectionQuality,playWidth="undefined"!=typeof options.playWidth?options.playWidth:getConstraintsProperty(constraints,"video.width",0),playHeight="undefined"!=typeof options.playHeight?options.playHeight:getConstraintsProperty(constraints,"video.height",0),stripCodecs=options.stripCodecs||[],resolution={},published_=!1,record_=options.record||!1,recordFileName=null,cacheLocalResources=options.cacheLocalResources,status_=STREAM_STATUS.NEW,rtmpUrl=options.rtmpUrl,remoteBitrate=-1,networkBandwidth=-1,sdpHook=options.sdpHook,transportType=options.transport,cvoExtension=options.cvoExtension,remoteVideo=options.remoteVideo,callbacks={},playoutDelay=options.playoutDelay,useCanvasMediaStream=options.useCanvasMediaStream,videoContentHint=options.videoContentHint,unmutePlayOnStart=options.unmutePlayOnStart,useControls=options.useControls,collectDeviceInfo=void 0===options.collectDeviceInfo||options.collectDeviceInfo,videoBytes=0,statsCollector=null,stream={};streamEventRefreshHandlers[id_]=function(streamEvent){if(streamEvent.type==STREAM_EVENT_TYPE.NOT_ENOUGH_BANDWIDTH){var info=streamEvent.payload.info.split("/");remoteBitrate=info[0],networkBandwidth=info[1]}else streamEvent.type==STREAM_EVENT_TYPE.RESIZE&&(resolution.width=streamEvent.payload.streamerVideoWidth,resolution.height=streamEvent.payload.streamerVideoHeight);callbacks[STREAM_EVENT]&&callbacks[STREAM_EVENT](streamEvent)},streamRefreshHandlers[id_]=function(streamInfo,sdp){if(sdp&&""!==sdp){var _sdp=sdp;return _codecOptions&&(_sdp=util.SDP.writeFmtp(sdp,_codecOptions,"opus")),_sdp=sdpHookHandler(_sdp,sdpHook),_sdp=util.setPublishingBitrate(_sdp,mediaConnection,minBitrate,maxBitrate),void mediaConnection.setRemoteSdp(_sdp).then((function(){}))}if(void 0===streamInfo.available){var event=streamInfo.status;if("inboundVideoRate"!==event&&"outboundVideoRate"!==event){if(event===STREAM_EVENT)return streamInfo.mediaSessionId||(streamInfo.mediaSessionId=id_),void streamEventRefreshHandlers[id_](streamInfo);if(event===STREAM_STATUS.RESIZE)resolution.width=streamInfo.streamerVideoWidth,resolution.height=streamInfo.streamerVideoHeight;else if(event===STREAM_STATUS.SNAPSHOT_COMPLETE);else if(event===STREAM_STATUS.NOT_ENOUGH_BANDWIDTH){var info=streamInfo.info.split("/");remoteBitrate=info[0],networkBandwidth=info[1]}else status_=event;streamInfo.audioState&&(audioState_=streamInfo.audioState),streamInfo.videoState&&(videoState_=streamInfo.videoState),streamInfo.info&&(info_=streamInfo.info),event!==STREAM_STATUS.FAILED&&event!==STREAM_STATUS.STOPPED&&event!==STREAM_STATUS.UNPUBLISHED||(delete streams[id_],delete streamRefreshHandlers[id_],delete streamEventRefreshHandlers[id_],mediaConnection&&mediaConnection.close(cacheLocalResources),statsCollector&&(statsCollector.stop(),statsCollector=null)),record_&&"undefined"!=typeof streamInfo.recordName&&(recordFileName=streamInfo.recordName),event!==STREAM_STATUS.PUBLISHING&&event!==STREAM_STATUS.PLAYING||webRTCMetricsServerDescription&&!statsCollector&&(statsCollector=StatsCollector.StreamStatsCollector(webRTCMetricsServerDescription,id_,mediaConnection,wsConnection,logger)).start(),streamInfo.authorization&&statsCollector&&statsCollector.description.ingestPoint&&(statsCollector.description.authorization=streamInfo.authorization,statsCollector.updateHttpConnection(statsCollector.description.ingestPoint,statsCollector.description.authorization)),!streamInfo.status&&void 0!==streamInfo.collect&&statsCollector&&statsCollector.update(streamInfo),callbacks[event]&&callbacks[event](stream)}else detectConnectionQuality(event,streamInfo)}else{for(var i=0;i<availableCallbacks.length;i++)info_=streamInfo.reason,"true"==streamInfo.available?availableCallbacks[i].resolve(stream):availableCallbacks[i].reject(stream);availableCallbacks=[]}};var detectConnectionQuality=function(event,streamInfo){disableConnectionQualityCalculation||mediaConnection.getStats((function(stats){var bytesSentReceived=0;if(stats)if("outboundVideoRate"==event&&stats.inboundStream&&stats.inboundStream.video&&stats.inboundStream.video.bytesReceived>0)bytesSentReceived=stats.inboundStream.video.bytesReceived;else{if(!(stats.outboundStream&&stats.outboundStream.video&&stats.outboundStream.video.bytesSent>0))return;bytesSentReceived=stats.outboundStream.video.bytesSent}if(videoBytes){var currentVideoRate=8*(bytesSentReceived-videoBytes);if(0!=currentVideoRate){var currentQuality,clientFiltered=clientKf.filter(currentVideoRate),serverFiltered=serverKf.filter(streamInfo.videoRate),videoRateDifference=100*Math.abs((serverFiltered-clientFiltered)/((serverFiltered+clientFiltered)/2));currentQuality=serverFiltered<5e4||clientFiltered<5e4?videoRateDifference>150?CONNECTION_QUALITY.BAD:CONNECTION_QUALITY.PERFECT:videoRateDifference>50?CONNECTION_QUALITY.BAD:videoRateDifference>20?CONNECTION_QUALITY.GOOD:CONNECTION_QUALITY.PERFECT,callbacks[CONNECTION_QUALITY.UPDATE]&&(connectionQuality=currentQuality,callbacks[CONNECTION_QUALITY.UPDATE](connectionQuality,clientFiltered,serverFiltered)),videoBytes=bytesSentReceived}}else videoBytes=bytesSentReceived}))},isRemoteAudioMuted=function(){return!(!mediaConnection||"Flash"==mediaProvider)&&mediaConnection.isRemoteAudioMuted()},_stop=function(){if(logger.debug("core","Stop stream "+name_),statsCollector&&(statsCollector.stop(),statsCollector=null),status_!=STREAM_STATUS.NEW)return status_==STREAM_STATUS.PENDING?(logger.warn("core","Stopping stream before server response "+id_),void setTimeout(_stop,200)):void(status_!=STREAM_STATUS.FAILED?(send(published_?"unPublishStream":"stopStream",{mediaSessionId:id_,name:name_,published:published_,hasVideo:!0,hasAudio:!0,status:status_,record:!1}),mediaConnection&&mediaConnection.close(cacheLocalResources)):logger.warn("core","Stream status FAILED"));streamRefreshHandlers[id_]({status:STREAM_STATUS.FAILED})},published=function(){return published_};function sendStreamEvent(type,payload){send("sendStreamEvent",{mediaSessionId:id_,type:type,payload:payload})}var fireUnmuteEvent=function(){isRemoteAudioMuted()&&streamRefreshHandlers[id_]&&"function"==typeof streamRefreshHandlers[id_]&&streamRefreshHandlers[id_]({status:STREAM_EVENT,type:STREAM_EVENT_TYPE.UNMUTE_REQUIRED})},setZoom=function(){var _ref4=_asyncToGenerator(_regenerator().m((function _callee2(value){return _regenerator().w((function(_context2){for(;;)switch(_context2.n){case 0:if(!published()||!mediaConnection){_context2.n=2;break}return _context2.n=1,mediaConnection.setZoom(value);case 1:return _context2.a(2,_context2.v);case 2:throw new Error("This function available for publishing stream only");case 3:return _context2.a(2)}}),_callee2)})));return function(_x2){return _ref4.apply(this,arguments)}}();return stream.play=function(){if(logger.debug("core","Play stream "+name_),status_!==STREAM_STATUS.NEW)throw new Error("Invalid stream state "+status_);status_=STREAM_STATUS.PENDING,MediaProvider[mediaProvider].createConnection({id:id_,display:display,authToken:authToken,mainUrl:urlServer,flashProto:flashProto,flashPort:flashPort,flashBufferTime:options.flashBufferTime||0,flashShowFullScreenButton:options.flashShowFullScreenButton||!1,connectionConfig:mediaOptions,connectionConstraints:mediaConnectionConstraints,audioOutputId:audioOutputId,remoteVideo:remoteVideo,playoutDelay:playoutDelay,unmutePlayOnStart:unmutePlayOnStart,useControls:useControls,logger:logger,unmuteRequiredEvent:fireUnmuteEvent},streamRefreshHandlers[id_]).then((function(newConnection){mediaConnection=newConnection;try{streamRefreshHandlers[id_]({status:status_})}catch(e){console.warn(e)}return mediaConnection.createOffer({receiveAudio:receiveAudio,receiveVideo:receiveVideo,stripCodecs:stripCodecs,stereo:_stereo})})).then((function(offer){logger.debug("core","Offer SDP:\n"+offer.sdp),send("playStream",{mediaSessionId:id_,name:name_,published:published_,hasVideo:!0,hasAudio:!0,status:status_,record:!1,width:playWidth,height:playHeight,mediaProvider:mediaProvider,sdp:offer.sdp,custom:options.custom,bitrate:bitrate,minBitrate:minBitrate,maxBitrate:maxBitrate,quality:quality,constraints:constraints,transport:transportType,cvoExtension:cvoExtension}),offer.player&&offer.player.play(id_)})).catch((function(error){throw error}))},stream.publish=function(){if(logger.debug("core","Publish stream "+name_),status_!==STREAM_STATUS.NEW)throw new Error("Invalid stream state "+status_);status_=STREAM_STATUS.PENDING,published_=!0;constraints&&constraints.video&&constraints.video.type&&constraints.video.type,MediaProvider[mediaProvider].getMediaAccess(constraints,display,disableConstraintsNormalization,useCanvasMediaStream).then((function(){status_!=STREAM_STATUS.FAILED?MediaProvider[mediaProvider].createConnection({id:id_,display:display,authToken:authToken,mainUrl:urlServer,flashProto:flashProto,flashPort:flashPort,constraints:constraints,connectionConfig:mediaOptions,connectionConstraints:mediaConnectionConstraints,customStream:!(!constraints||!constraints.customStream)&&constraints.customStream,videoContentHint:videoContentHint,useControls:useControls,logger:logger}).then((function(newConnection){return(mediaConnection=newConnection).createOffer({stripCodecs:stripCodecs})})).then((function(offer){logger.debug("core","Offer SDP:\n"+offer.sdp);var publishStreamData={mediaSessionId:id_,name:name_,published:published_,hasVideo:offer.hasVideo,hasAudio:offer.hasAudio,status:status_,record:record_,mediaProvider:mediaProvider,sdp:offer.sdp,custom:options.custom,bitrate:bitrate,minBitrate:minBitrate,maxBitrate:maxBitrate,rtmpUrl:rtmpUrl,constraints:constraints,transport:transportType,cvoExtension:cvoExtension};collectDeviceInfo&&(publishStreamData.localMediaInfo=collectLocalMediaInfo(MediaProvider[mediaProvider],display)),send("publishStream",publishStreamData)})):cacheLocalResources||releaseLocalMedia(display,mediaProvider)})).catch((function(error){logger.warn("core",error),info_=ERROR_INFO.LOCAL_ERROR,errorInfo_=error.message,status_=STREAM_STATUS.FAILED,callbacks[status_]&&callbacks[status_](stream)}))},stream.stop=_stop,stream.id=function(){return id_},stream.status=function(){return status_},stream.name=function(){return name_},stream.published=published,stream.getRecordInfo=function(){return recordFileName},stream.getInfo=function(){return info_},stream.getErrorInfo=function(){return errorInfo_},stream.videoResolution=function(){if(published_)throw new Error("This function available only on playing stream");return resolution},stream.setAudioOutputId=function(id){if(audioOutputId=id,mediaConnection&&mediaConnection.setAudioOutputId)return mediaConnection.setAudioOutputId(id)},stream.setVolume=function(volume){mediaConnection&&mediaConnection.setVolume(volume)},stream.unmuteRemoteAudio=function(){mediaConnection&&"Flash"!=mediaProvider&&mediaConnection.unmuteRemoteAudio()},stream.muteRemoteAudio=function(){mediaConnection&&"Flash"!=mediaProvider&&mediaConnection.muteRemoteAudio()},stream.isRemoteAudioMuted=isRemoteAudioMuted,stream.setMicrophoneGain=function(volume){if(status_!==STREAM_STATUS.PUBLISHING)throw new Error("Invalid stream state");mediaConnection.setMicrophoneGain(volume)},stream.getVolume=function(){return mediaConnection?mediaConnection.getVolume():-1},stream.muteAudio=function(){mediaConnection&&(mediaConnection.muteAudio(),sendStreamEvent(STREAM_EVENT_TYPE.AUDIO_MUTED))},stream.unmuteAudio=function(){mediaConnection&&(mediaConnection.unmuteAudio(),sendStreamEvent(STREAM_EVENT_TYPE.AUDIO_UNMUTED))},stream.isAudioMuted=function(){return!mediaConnection||mediaConnection.isAudioMuted()},stream.muteVideo=function(){mediaConnection&&(mediaConnection.muteVideo(),sendStreamEvent(STREAM_EVENT_TYPE.VIDEO_MUTED))},stream.unmuteVideo=function(){mediaConnection&&(mediaConnection.unmuteVideo(),sendStreamEvent(STREAM_EVENT_TYPE.VIDEO_UNMUTED))},stream.isVideoMuted=function(){return!mediaConnection||mediaConnection.isVideoMuted()},stream.getStats=function(callbackFn,nativeStats){mediaConnection&&mediaConnection.getStats(callbackFn,nativeStats)},stream.snapshot=function(){if(logger.debug("core","Request snapshot, stream "+name_),status_!==STREAM_STATUS.NEW&&status_!==STREAM_STATUS.PLAYING&&status_!==STREAM_STATUS.PUBLISHING)throw new Error("Invalid stream state");send("snapshot",{name:name_,mediaSessionId:id_})},stream.getAudioState=function(){return audioState_},stream.getVideoState=function(){return videoState_},stream.getNetworkBandwidth=function(){return networkBandwidth},stream.getRemoteBitrate=function(){return remoteBitrate},stream.fullScreen=function(){published()?logger.warn("core","Full screen is allowed only for played streams"):mediaConnection&&mediaConnection.fullScreen()},stream.on=function(event,callback){if(!event)throw new TypeError("Event can't be null");if(!callback||"function"!=typeof callback)throw new Error("Callback needs to be a valid function");return callbacks[event]=callback,stream},stream.available=function(){return new _Promise((function(resolve,reject){send("availableStream",{mediaSessionId:id_,name:name_});var promise={};promise.resolve=resolve,promise.reject=reject,availableCallbacks.push(promise)}))},stream.switchCam=function(deviceId){if(status_!==STREAM_STATUS.PUBLISHING)throw new Error("Invalid stream state");return mediaConnection.switchCam(deviceId)},stream.switchMic=function(deviceId){if(status_!==STREAM_STATUS.PUBLISHING)throw new Error("Invalid stream state");return mediaConnection.switchMic(deviceId)},stream.switchToScreen=function(source,woExtension){if(status_!==STREAM_STATUS.PUBLISHING)throw new Error("Invalid stream state");return mediaConnection.switchToScreen(source,woExtension)},stream.switchToCam=function(){if(status_!==STREAM_STATUS.PUBLISHING)throw new Error("Invalid stream state");mediaConnection.switchToCam()},stream.sendData=function(payload){if(status_!==STREAM_STATUS.PUBLISHING)throw new Error("Invalid stream state");sendStreamEvent(STREAM_EVENT_TYPE.DATA,payload)},stream.getLogger=function(){return streamLogger},stream.updateVideoSettings=function(settings){if(published()&&mediaConnection)return mediaConnection.updateVideoSettings(settings);throw new Error("This function available for publishing stream only")},stream.updateVideoResolution=function(resolution){if(published()&&mediaConnection)return mediaConnection.updateVideoResolution(resolution);throw new Error("This function available for publishing stream only")},stream.getZoomCapabilities=function(){if(published()&&mediaConnection)return mediaConnection.getZoomCapabilities();throw new Error("This function available for publishing stream only")},stream.getZoom=function(){if(published()&&mediaConnection)return mediaConnection.getZoom();throw new Error("This function available for publishing stream only")},stream.setZoom=setZoom,streams[id_]=stream,stream},session.createCall=createCall,session.getStream=function(streamId){return streams[streamId]},session.getStreams=function(){return util.copyObjectToArray(streams)},session.sendData=restAppCommunicator.sendData,session.disconnect=function(){wsConnection&&wsConnection.close()},session.submitBugReport=function(reportObject){send("submitBugReport",reportObject)},session.startDebug=function(){logger.setPushLogs(!0),logger.setLevel("DEBUG"),send("sessionDebug",{command:"start"})},session.stopDebug=function(){logger.setLevel("INFO"),send("sessionDebug",{command:"stop"})},session.on=function(event,callback){if(!event)throw new Error("Event can't be null","TypeError");if(!callback||"function"!=typeof callback)throw new Error("Callback needs to be a valid function");return callbacks[event]=callback,session},session.getLogger=function(){return sessionLogger},sessions[id_]=session,session},playFirstSound:function(noise){var mediaProvider=getMediaProviders()[0];MediaProvider[mediaProvider].playFirstSound(noise)},playFirstVideo:function(display,isLocal,src,useControls){for(var mp in MediaProvider)return MediaProvider[mp].playFirstVideo(display,isLocal,src,useControls)},getLogger:function(){if(initialized)return coreLogger;console.warn("Initialize API first.")},constants:constants,firefoxScreenSharingExtensionInstalled:!0,Browser:util.Browser}},{"./client-info":38,"./constants":39,"./media-source-media-provider":1,"./stats-collector":41,"./temasys-media-provider":1,"./util":42,"./webrtc-media-provider":43,"./websocket-media-provider":1,kalmanjs:2,"promise-polyfill":4,uuid:8,"webrtc-adapter":23}],41:[function(require,module,exports){"use strict";function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}function _slicedToArray(r,e){return function(r){if(Array.isArray(r))return r}(r)||function(r,l){var t=null==r?null:"undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(null!=t){var e,n,i,u,a=[],f=!0,o=!1;try{if(i=(t=t.call(r)).next,0===l){if(Object(t)!==t)return;f=!1}else for(;!(f=(e=i.call(t)).done)&&(a.push(e.value),a.length!==l);f=!0);}catch(r){o=!0,n=r}finally{try{if(!f&&null!=t.return&&(u=t.return(),Object(u)!==u))return}finally{if(o)throw n}}return a}}(r,e)||_unsupportedIterableToArray(r,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _createForOfIteratorHelper(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=_unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var _n=0,F=function(){};return{s:F,n:function(){return _n>=r.length?{done:!0}:{done:!1,value:r[_n++]}},e:function(r){throw r},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,u=!1;return{s:function(){t=t.call(r)},n:function(){var r=t.next();return a=r.done,r},e:function(r){u=!0,o=r},f:function(){try{a||null==t.return||t.return()}finally{if(u)throw o}}}}function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}function _regenerator(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function i(r,n,o,i){var c=n&&n.prototype instanceof Generator?n:Generator,u=Object.create(c.prototype);return _regeneratorDefine2(u,"_invoke",function(r,n,o){var i,c,u,f=0,p=o||[],y=!1,G={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return i=t,c=0,u=e,G.n=r,a}};function d(r,n){for(c=r,u=n,t=0;!y&&f&&!o&&t<p.length;t++){var o,i=p[t],d=G.p,l=i[2];r>3?(o=l===n)&&(u=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&d<i[1])?(c=0,G.v=n,G.n=i[1]):d<l&&(o=r<3||i[0]>n||n>l)&&(i[4]=r,i[5]=n,G.n=l,c=0))}if(o||r>1)return a;throw y=!0,n}return function(o,p,l){if(f>1)throw TypeError("Generator is already running");for(y&&1===p&&d(p,l),c=p,u=l;(t=c<2?e:u)||!y;){i||(c?c<3?(c>1&&(G.n=-1),d(c,u)):G.n=u:G.v=u);try{if(f=2,i){if(c||(o="next"),t=i[o]){if(!(t=t.call(i,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);i=e}else if((t=(y=G.n<0)?u:r.call(n,G))!==a)break}catch(t){i=e,c=1,u=t}finally{f=1}}return{value:t,done:y}}}(r,o,i),!0),u}var a={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}t=Object.getPrototypeOf;var c=[][n]?t(t([][n]())):(_regeneratorDefine2(t={},n,(function(){return this})),t),u=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(c);function f(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,GeneratorFunctionPrototype):(e.__proto__=GeneratorFunctionPrototype,_regeneratorDefine2(e,o,"GeneratorFunction")),e.prototype=Object.create(u),e}return GeneratorFunction.prototype=GeneratorFunctionPrototype,_regeneratorDefine2(u,"constructor",GeneratorFunctionPrototype),_regeneratorDefine2(GeneratorFunctionPrototype,"constructor",GeneratorFunction),GeneratorFunction.displayName="GeneratorFunction",_regeneratorDefine2(GeneratorFunctionPrototype,o,"GeneratorFunction"),_regeneratorDefine2(u),_regeneratorDefine2(u,o,"Generator"),_regeneratorDefine2(u,n,(function(){return this})),_regeneratorDefine2(u,"toString",(function(){return"[object Generator]"})),(_regenerator=function(){return{w:i,m:f}})()}function _regeneratorDefine2(e,r,n,t){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}(_regeneratorDefine2=function(e,r,n,t){function o(r,n){_regeneratorDefine2(e,r,(function(e){return this._invoke(r,n,e)}))}r?i?i(e,r,{value:n,enumerable:!t,configurable:!t,writable:!t}):e[r]=n:(o("next",0),o("throw",1),o("return",2))})(e,r,n,t)}function asyncGeneratorStep(n,t,e,r,o,a,c){try{var i=n[a](c),u=i.value}catch(n){return void e(n)}i.done?t(u):Promise.resolve(u).then(r,o)}function _asyncToGenerator(n){return function(){var t=this,e=arguments;return new Promise((function(r,o){var a=n.apply(t,e);function _next(n){asyncGeneratorStep(a,r,o,_next,_throw,"next",n)}function _throw(n){asyncGeneratorStep(a,r,o,_next,_throw,"throw",n)}_next(void 0)}))}}var util=require("./util"),LOG_PREFIX="stats-collector",CONNECTION_TYPE_WEBSOCKET="ws",CONNECTION_TYPE_HTTP="http",CONNECTION_STATUS_INIT=0,CONNECTION_STATUS_OK=200,CONNECTION_STATUS_BAD_REQUEST=400,CONNECTION_STATUS_INTERNAL_SERVER_ERROR=500,Connection=function(){var _send2,existingConnection=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,maxErrors=arguments.length>1&&void 0!==arguments[1]?arguments[1]:3,connection={type:"",websocket:null,http:null,maxErrors:maxErrors,errorsCount:0,status:CONNECTION_STATUS_INIT,setUp:function(url){var headers=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,existingConnection=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;url.startsWith(CONNECTION_TYPE_WEBSOCKET)?connection.type=CONNECTION_TYPE_WEBSOCKET:url.startsWith(CONNECTION_TYPE_HTTP)?(connection.type=CONNECTION_TYPE_HTTP,connection.http=HttpConnection(url,headers)):existingConnection&&(connection.type=CONNECTION_TYPE_WEBSOCKET,connection.websocket=WebsocketConnection(existingConnection)),connection.errorsCount=0,connection.status=CONNECTION_STATUS_INIT},send:(_send2=_asyncToGenerator(_regenerator().m((function _callee0(message,data){var code,_t4;return _regenerator().w((function(_context0){for(;;)switch(_context0.n){case 0:code=CONNECTION_STATUS_BAD_REQUEST,_t4=connection.type,_context0.n=_t4===CONNECTION_TYPE_WEBSOCKET?1:_t4===CONNECTION_TYPE_HTTP?2:5;break;case 1:return connection.websocket&&(code=connection.websocket.send(message,data)),_context0.a(3,5);case 2:if(!connection.http){_context0.n=4;break}return _context0.n=3,connection.http.send(message,data);case 3:code=_context0.v;case 4:return _context0.a(3,5);case 5:connection.status=code,connection.status===CONNECTION_STATUS_OK?connection.errorsCount=0:"webRTCMetricsBatch"===message&&(connection.errorsCount++,connection.errorsCount<connection.maxErrors&&(connection.status=CONNECTION_STATUS_OK));case 6:return _context0.a(2)}}),_callee0)}))),function(_x5,_x6){return _send2.apply(this,arguments)})};return connection.setUp("",null,existingConnection),connection},WebsocketConnection=function(wsConnection){var connection={websocket:wsConnection,send:function(message,data){var code=CONNECTION_STATUS_BAD_REQUEST;return connection.websocket&&(connection.websocket.readyState===WebSocket.OPEN&&connection.websocket.send(JSON.stringify({message:message,data:[data]})),code=CONNECTION_STATUS_OK),code}};return connection},HttpConnection=function(url,headers){var _send3,connection={url:addSlash(url),headers:headers,setAuthorization:function(token){this.headers.Authorization=token},send:(_send3=_asyncToGenerator(_regenerator().m((function _callee1(message,data){var code,httpHeaders,_i2,_Object$entries,_Object$entries$_i,header,value,response;return _regenerator().w((function(_context1){for(;;)switch(_context1.p=_context1.n){case 0:if(code=CONNECTION_STATUS_BAD_REQUEST,!connection.url){_context1.n=4;break}if(_context1.p=1,(httpHeaders=new Headers).append("Content-Type","application/json"),connection.headers)for(_i2=0,_Object$entries=Object.entries(connection.headers);_i2<_Object$entries.length;_i2++)_Object$entries$_i=_slicedToArray(_Object$entries[_i2],2),header=_Object$entries$_i[0],value=_Object$entries$_i[1],httpHeaders.append(header,value);return _context1.n=2,fetch(connection.url+message,{method:"POST",headers:httpHeaders,mode:"cors",body:JSON.stringify(data)});case 2:response=_context1.v,code=response.status,_context1.n=4;break;case 3:_context1.p=3,_context1.v,code=CONNECTION_STATUS_INTERNAL_SERVER_ERROR;case 4:return _context1.a(2,code)}}),_callee1,null,[[1,3]])}))),function(_x7,_x8){return _send3.apply(this,arguments)})};return connection},valueToString=function(value){var valueString="undefined";return value&&(valueString="object"===_typeof(value)?JSON.stringify(value):value.toString()),valueString},getLogger=function(logger){return logger&&void 0!==logger.info&&void 0!==logger.warn&&void 0!==logger.error&&void 0!==logger.debug?logger:{info:function(){},warn:function(){},error:function(){},debug:function(){}}},addSlash=function(value){var endpoint=value;return endpoint&&!endpoint.endsWith("/")&&(endpoint+="/"),endpoint};module.exports={StreamStatsCollector:function(description,id,mediaConnection,wsConnection,logger,maxErrors){var _sendMetrics,_collectMetrics,_send,_sendHeaders,_checkForCompression,_updateCompression,_updateHeaders,_update,_start,statCollector={description:description,id:id,mediaConnection:mediaConnection,connection:Connection(wsConnection,maxErrors),logger:getLogger(logger),headers:"",compression:"none",metricsBatch:null,timer:null,batchCount:0,timerBusy:!1,start:(_start=_asyncToGenerator(_regenerator().m((function _callee(){var error,authHeader;return _regenerator().w((function(_context){for(;;)switch(_context.n){case 0:if(error="Can't collect WebRTC stats to send: ",statCollector.description.types){_context.n=1;break}throw new Error(error+"no report types defined");case 1:if(statCollector.description.sampling){_context.n=2;break}throw new Error(error+"no sampling interval defined");case 2:if(statCollector.description.batchSize){_context.n=3;break}throw new Error(error+"no metrics batch size defined");case 3:if(statCollector.mediaConnection){_context.n=4;break}throw new Error(error+"no media connection available");case 4:return statCollector.logger.debug(LOG_PREFIX,"RTCMetricsServerDescription: "+JSON.stringify(statCollector.description)),statCollector.description.ingestPoint&&(authHeader=null,statCollector.description.authorization&&(authHeader={Authorization:statCollector.description.authorization}),statCollector.connection.setUp(statCollector.description.ingestPoint,authHeader)),_context.n=5,statCollector.updateHeaders();case 5:return _context.n=6,statCollector.updateCompression();case 6:return _context.n=7,statCollector.sendHeaders();case 7:"on"===statCollector.description.collect&&statCollector.collect(!0);case 8:return _context.a(2)}}),_callee)}))),function(){return _start.apply(this,arguments)}),collect:function(enable){enable&&statCollector.connection.status===CONNECTION_STATUS_OK?statCollector.startTimer():statCollector.stopTimer()},stop:function(){statCollector.stopTimer(),statCollector.headers=""},update:(_update=_asyncToGenerator(_regenerator().m((function _callee2(description){var _t;return _regenerator().w((function(_context2){for(;;)switch(_context2.n){case 0:if(description){_context2.n=1;break}return statCollector.logger.error(LOG_PREFIX+"-"+statCollector.id,"Can't update WebRTC metrics sending: no parameters passed"),_context2.a(2);case 1:if(statCollector.logger.debug(LOG_PREFIX,"New RTCMetricsServerDescription: "+JSON.stringify(description)),!description.types&&!description.compression){_context2.n=6;break}if(statCollector.stop(),!description.types){_context2.n=2;break}return statCollector.description.types=description.types,_context2.n=2,statCollector.updateHeaders();case 2:if(!description.compression){_context2.n=3;break}return statCollector.description.compression=description.compression,_context2.n=3,statCollector.updateCompression();case 3:return _context2.n=4,statCollector.sendHeaders();case 4:if(statCollector.connection.status===CONNECTION_STATUS_OK){_context2.n=5;break}return _context2.a(2);case 5:_context2.n=7;break;case 6:statCollector.collect(!1);case 7:description.batchSize&&(statCollector.description.batchSize=description.batchSize),description.sampling&&(statCollector.description.sampling=description.sampling),description.collect&&(statCollector.description.collect=description.collect),_t=statCollector.description.collect,_context2.n="on"===_t?8:"off"===_t?9:10;break;case 8:return statCollector.collect(!0),_context2.a(3,10);case 9:return statCollector.collect(!1),_context2.a(3,10);case 10:return _context2.a(2)}}),_callee2)}))),function(_x){return _update.apply(this,arguments)}),updateHeaders:(_updateHeaders=_asyncToGenerator(_regenerator().m((function _callee3(){var stats,currentHeaders,headersChanged,newMetrics,_args3=arguments;return _regenerator().w((function(_context3){for(;;)switch(_context3.n){case 0:if(stats=_args3.length>0&&void 0!==_args3[0]?_args3[0]:null,currentHeaders="",headersChanged=!1,null!==stats){_context3.n=2;break}return _context3.n=1,statCollector.mediaConnection.getWebRTCStats();case 1:stats=_context3.v;case 2:return Object.keys(statCollector.description.types).forEach((function(type){var typeDescriptor=statCollector.description.types[type],metricsString="",contentFilters=null;typeDescriptor.metrics&&(metricsString=typeDescriptor.metrics),typeDescriptor.contains&&(contentFilters=typeDescriptor.contains),stats[type]?stats[type].forEach((function(report){if(statCollector.logger.debug(LOG_PREFIX+"-"+statCollector.id,type+" report: "+JSON.stringify(report)),contentFilters){var filtersMatched=!0;for(var filter in contentFilters){statCollector.logger.debug(LOG_PREFIX+"-"+statCollector.id,type+" filter by "+filter+": "+JSON.stringify(contentFilters[filter]));var filterMatched=!1;if(report[filter]){var _step,_iterator=_createForOfIteratorHelper(contentFilters[filter]);try{for(_iterator.s();!(_step=_iterator.n()).done;){var value=_step.value;if(statCollector.logger.debug(LOG_PREFIX+"-"+statCollector.id,filter+": "+value+" <> "+report[filter]),report[filter]===value){filterMatched=!0;break}}}catch(err){_iterator.e(err)}finally{_iterator.f()}}if(filtersMatched=filtersMatched&&filterMatched,!filterMatched)break}filtersMatched&&(currentHeaders=statCollector.addHeaders(currentHeaders,report,metricsString))}else currentHeaders=statCollector.addHeaders(currentHeaders,report,metricsString)})):statCollector.logger.debug(LOG_PREFIX+"-"+statCollector.id,"No report type found in RTC stats: '"+type+"'")})),currentHeaders!==statCollector.headers&&(headersChanged=!0,newMetrics=[],currentHeaders.split(",").forEach((function(header){-1===statCollector.headers.indexOf(header)&&newMetrics.push(header)})),newMetrics.length&&statCollector.logger.info(LOG_PREFIX+"-"+statCollector.id,"RTC metrics to be collected: "+newMetrics.toString()),statCollector.headers=currentHeaders),_context3.a(2,headersChanged)}}),_callee3)}))),function(){return _updateHeaders.apply(this,arguments)}),addHeaders:function(currentHeaders,report,metricsString){metricsString&&metricsString.split(",").forEach((function(metric){for(var _i=0,_Object$keys=Object.keys(report);_i<_Object$keys.length;_i++){var key=_Object$keys[_i];if(metric===key&&report[key]){currentHeaders=util.addFieldToCsvString(currentHeaders,report.type+"."+report.id+"."+metric,",");break}}}));return currentHeaders},updateCompression:(_updateCompression=_asyncToGenerator(_regenerator().m((function _callee4(){return _regenerator().w((function(_context4){for(;;)switch(_context4.n){case 0:if(!statCollector.description.compression){_context4.n=3;break}if(!(statCollector.description.compression.indexOf("gzip")>=0)){_context4.n=2;break}return _context4.n=1,statCollector.checkForCompression("gzip");case 1:_context4.n=3;break;case 2:if(!(statCollector.description.compression.indexOf("deflate")>=0)){_context4.n=3;break}return _context4.n=3,statCollector.checkForCompression("deflate");case 3:return _context4.a(2)}}),_callee4)}))),function(){return _updateCompression.apply(this,arguments)}),updateHttpConnection:function(url,authorization){url.startsWith(CONNECTION_TYPE_HTTP)&&authorization&&statCollector.connection.http.setAuthorization(authorization)},checkForCompression:(_checkForCompression=_asyncToGenerator(_regenerator().m((function _callee5(compression){var _t2;return _regenerator().w((function(_context5){for(;;)switch(_context5.p=_context5.n){case 0:return _context5.p=0,_context5.n=1,util.compress(compression,"test",!1);case 1:statCollector.compression=compression,_context5.n=3;break;case 2:_context5.p=2,_t2=_context5.v,statCollector.logger.warn(LOG_PREFIX+"-"+statCollector.id,"Can't compress metrics data using "+compression+": "+_t2),statCollector.compression="none";case 3:return _context5.a(2)}}),_callee5,null,[[0,2]])}))),function(_x2){return _checkForCompression.apply(this,arguments)}),sendHeaders:(_sendHeaders=_asyncToGenerator(_regenerator().m((function _callee6(){var data;return _regenerator().w((function(_context6){for(;;)switch(_context6.n){case 0:return data={mediaSessionId:statCollector.id,compression:statCollector.compression,headers:statCollector.headers},_context6.n=1,statCollector.send("webRTCMetricsClientDescription",data);case 1:return _context6.a(2)}}),_callee6)}))),function(){return _sendHeaders.apply(this,arguments)}),send:(_send=_asyncToGenerator(_regenerator().m((function _callee7(message,data){return _regenerator().w((function(_context7){for(;;)switch(_context7.n){case 0:if(statCollector.connection.status!==CONNECTION_STATUS_INIT&&statCollector.connection.status!==CONNECTION_STATUS_OK){_context7.n=2;break}return statCollector.logger.debug(LOG_PREFIX+"-"+statCollector.id,data),_context7.n=1,statCollector.connection.send(message,data);case 1:statCollector.connection.status!==CONNECTION_STATUS_OK&&(statCollector.logger.error(LOG_PREFIX+"-"+statCollector.id,"Error "+statCollector.connection.status+" sending RTC metrics to the server, stop sending"),statCollector.stop());case 2:return _context7.a(2)}}),_callee7)}))),function(_x3,_x4){return _send.apply(this,arguments)}),startTimer:function(){statCollector.timer||(statCollector.batchCount=statCollector.description.batchSize,statCollector.timer=setInterval(statCollector.collectMetrics,statCollector.description.sampling))},stopTimer:function(){statCollector.timer&&(clearInterval(statCollector.timer),statCollector.timer=null,statCollector.metricsBatch=null)},isMetricValid:function(value){return null!=value&&""!==value&&"undefined"!==value&&"null"!==value},collectMetrics:(_collectMetrics=_asyncToGenerator(_regenerator().m((function _callee8(){var stats,metrics,lostMetrics,headersUpdated;return _regenerator().w((function(_context8){for(;;)switch(_context8.n){case 0:if(!statCollector.timer||statCollector.timerBusy){_context8.n=7;break}return statCollector.timerBusy=!0,_context8.n=1,statCollector.mediaConnection.getWebRTCStats();case 1:return stats=_context8.v,statCollector.startNewBatch(),metrics=[],lostMetrics=[],statCollector.headers?statCollector.headers.split(",").forEach((function(header){var components=header.split("."),descriptor={type:components[0],id:components[1],name:components[2]},value=null;if(stats[descriptor.type]){var _step2,_iterator2=_createForOfIteratorHelper(stats[descriptor.type]);try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){var report=_step2.value;if(report.id===descriptor.id){value=report[descriptor.name];break}}}catch(err){_iterator2.e(err)}finally{_iterator2.f()}}statCollector.isMetricValid(value)?metrics.push(value):lostMetrics.push(descriptor)})):statCollector.logger.info(LOG_PREFIX+"-"+statCollector.id,"No RTC metrics to collect, trying to update metrics available list"),_context8.n=2,statCollector.updateHeaders(stats);case 2:if(headersUpdated=_context8.v,!lostMetrics.length){_context8.n=4;break}return statCollector.logger.info(LOG_PREFIX+"-"+statCollector.id,"Missing metrics: "+JSON.stringify(lostMetrics)),_context8.n=3,statCollector.sendMetrics();case 3:statCollector.startNewBatch(metrics),_context8.n=5;break;case 4:if(!metrics.length){_context8.n=5;break}if(statCollector.metricsBatch.push(metrics),statCollector.batchCount--,0!==statCollector.batchCount&&!headersUpdated){_context8.n=5;break}return _context8.n=5,statCollector.sendMetrics();case 5:if(!headersUpdated){_context8.n=6;break}return statCollector.logger.info(LOG_PREFIX+"-"+statCollector.id,"RTC metrics list has changed, sending a new metrics description"),_context8.n=6,statCollector.sendHeaders();case 6:statCollector.timerBusy=!1;case 7:return _context8.a(2)}}),_callee8)}))),function(){return _collectMetrics.apply(this,arguments)}),sendMetrics:(_sendMetrics=_asyncToGenerator(_regenerator().m((function _callee9(){var previous,metricsToSend,metricsData,i,metricsString,j,valueString,previousString,data,_t3;return _regenerator().w((function(_context9){for(;;)switch(_context9.p=_context9.n){case 0:for(metricsToSend=[],i=0;statCollector.metricsBatch&&i<statCollector.metricsBatch.length;i++){for(metricsString="",j=0;j<statCollector.metricsBatch[i].length;j++)valueString=valueToString(statCollector.metricsBatch[i][j]),previousString="",previous&&(previousString=valueToString(previous[j])),valueString===previousString&&(valueString=""),metricsString=util.addFieldToCsvString(metricsString,valueString,";"),j>0&&""===metricsString&&(metricsString=";");previous=statCollector.metricsBatch[i],metricsToSend.push(metricsString)}if("none"===statCollector.compression){_context9.n=5;break}return _context9.p=1,_context9.n=2,util.compress(statCollector.compression,JSON.stringify(metricsToSend),!0);case 2:metricsData=_context9.v,_context9.n=4;break;case 3:_context9.p=3,_t3=_context9.v,statCollector.logger.warn(LOG_PREFIX+"-"+statCollector.id,"Can't send metrics data using"+statCollector.compression+": "+_t3),metricsData=null;case 4:_context9.n=6;break;case 5:metricsData=metricsToSend;case 6:if(!metricsData){_context9.n=7;break}return data={mediaSessionId:statCollector.id,metrics:metricsData},_context9.n=7,statCollector.send("webRTCMetricsBatch",data);case 7:statCollector.cleanBatch();case 8:return _context9.a(2)}}),_callee9,null,[[1,3]])}))),function(){return _sendMetrics.apply(this,arguments)}),startNewBatch:function(metrics){statCollector.metricsBatch||(statCollector.metricsBatch=[],metrics&&statCollector.metricsBatch.push(metrics))},cleanBatch:function(){statCollector.metricsBatch&&(statCollector.metricsBatch=null,statCollector.batchCount=statCollector.description.batchSize)}};return statCollector}}},{"./util":42}],42:[function(require,module,exports){"use strict";function _regenerator(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function i(r,n,o,i){var c=n&&n.prototype instanceof Generator?n:Generator,u=Object.create(c.prototype);return _regeneratorDefine2(u,"_invoke",function(r,n,o){var i,c,u,f=0,p=o||[],y=!1,G={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return i=t,c=0,u=e,G.n=r,a}};function d(r,n){for(c=r,u=n,t=0;!y&&f&&!o&&t<p.length;t++){var o,i=p[t],d=G.p,l=i[2];r>3?(o=l===n)&&(u=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&d<i[1])?(c=0,G.v=n,G.n=i[1]):d<l&&(o=r<3||i[0]>n||n>l)&&(i[4]=r,i[5]=n,G.n=l,c=0))}if(o||r>1)return a;throw y=!0,n}return function(o,p,l){if(f>1)throw TypeError("Generator is already running");for(y&&1===p&&d(p,l),c=p,u=l;(t=c<2?e:u)||!y;){i||(c?c<3?(c>1&&(G.n=-1),d(c,u)):G.n=u:G.v=u);try{if(f=2,i){if(c||(o="next"),t=i[o]){if(!(t=t.call(i,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);i=e}else if((t=(y=G.n<0)?u:r.call(n,G))!==a)break}catch(t){i=e,c=1,u=t}finally{f=1}}return{value:t,done:y}}}(r,o,i),!0),u}var a={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}t=Object.getPrototypeOf;var c=[][n]?t(t([][n]())):(_regeneratorDefine2(t={},n,(function(){return this})),t),u=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(c);function f(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,GeneratorFunctionPrototype):(e.__proto__=GeneratorFunctionPrototype,_regeneratorDefine2(e,o,"GeneratorFunction")),e.prototype=Object.create(u),e}return GeneratorFunction.prototype=GeneratorFunctionPrototype,_regeneratorDefine2(u,"constructor",GeneratorFunctionPrototype),_regeneratorDefine2(GeneratorFunctionPrototype,"constructor",GeneratorFunction),GeneratorFunction.displayName="GeneratorFunction",_regeneratorDefine2(GeneratorFunctionPrototype,o,"GeneratorFunction"),_regeneratorDefine2(u),_regeneratorDefine2(u,o,"Generator"),_regeneratorDefine2(u,n,(function(){return this})),_regeneratorDefine2(u,"toString",(function(){return"[object Generator]"})),(_regenerator=function(){return{w:i,m:f}})()}function _regeneratorDefine2(e,r,n,t){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}(_regeneratorDefine2=function(e,r,n,t){function o(r,n){_regeneratorDefine2(e,r,(function(e){return this._invoke(r,n,e)}))}r?i?i(e,r,{value:n,enumerable:!t,configurable:!t,writable:!t}):e[r]=n:(o("next",0),o("throw",1),o("return",2))})(e,r,n,t)}function _toConsumableArray(r){return function(r){if(Array.isArray(r))return _arrayLikeToArray(r)}(r)||function(r){if("undefined"!=typeof Symbol&&null!=r[Symbol.iterator]||null!=r["@@iterator"])return Array.from(r)}(r)||function(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}(r)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}function asyncGeneratorStep(n,t,e,r,o,a,c){try{var i=n[a](c),u=i.value}catch(n){return void e(n)}i.done?t(u):Promise.resolve(u).then(r,o)}function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}var Browser={isIE:function(){return!!document.documentMode},isFirefox:function(){return"undefined"!=typeof InstallTrigger},isChrome:function(){return!!window.chrome&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)&&!/OPR/.test(navigator.userAgent)},isEdge:function(){return!this.isIE()&&!!window.StyleMedia},isOpera:function(){return!!window.opr&&!!opr.addons||!!window.opera||navigator.userAgent.indexOf(" OPR/")>=0},isiOS:function(){return/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream},isSafari:function(){var userAgent=navigator.userAgent.toLowerCase();return/(safari|applewebkit)/i.test(userAgent)&&!userAgent.includes("chrome")&&!userAgent.includes("android")},isAndroid:function(){return navigator.userAgent.toLowerCase().indexOf("android")>-1},isSafariWebRTC:function(){return navigator.mediaDevices&&this.isSafari()},isSamsungBrowser:function(){return/SamsungBrowser/i.test(navigator.userAgent)},isAndroidFirefox:function(){return this.isAndroid()&&/Firefox/i.test(navigator.userAgent)},isChromiumEdge:function(){return/Chrome/i.test(navigator.userAgent)&&/Edg/i.test(navigator.userAgent)},version:function(){var version=navigator.userAgent.match(/version\/(\d+)/i);return version?version[1]:(this.isEdge()&&(version=/\brv[ :]+(\d+)/g.exec(navigator.userAgent)||[]),this.isOpera()&&(version=navigator.userAgent.match(/\b(OPR)\/(\d+)/)||[]),this.isChromiumEdge()&&(version=navigator.userAgent.match(/\b(Edg)\/(\d+)/)||[]),this.isSamsungBrowser()&&(version=navigator.userAgent.match(/\b(SamsungBrowser)\/(\d+)/)||[]),this.isChrome()&&(version=navigator.userAgent.match(/\b(Chrome)\/(\d+)/)||[]),this.isFirefox()&&(version=navigator.userAgent.match(/\b(Firefox)\/(\d+)/)||[]),version[2]||0)}},SDP={matchPrefix:function(sdp,prefix){return sdp.trim().split("\n").map((function(line){return line.trim()})).filter((function(line){return 0===line.indexOf(prefix)}))},writeFmtp:function(sdp,param,codec){var i,sdpArray=sdp.split("\n");for(i=0;i<sdpArray.length;i++)-1!=sdpArray[i].search(codec)&&0==sdpArray[i].indexOf("a=rtpmap")&&(sdpArray[i]+="\na=fmtp:"+sdpArray[i].match(/[0-9]+/)[0]+" "+param+"\r");var result="";for(i=0;i<sdpArray.length;i++)""!=sdpArray[i]&&(result+=sdpArray[i]+"\n");return result},setPublishingBitrate:function(sdp,minBitrate,maxBitrate){if(sdp&&(minBitrate||maxBitrate)){var i,matches,sdpArray=sdp.split("\n"),rtpmap=-1,codec="",bitrateString="";for(i=0;i<sdpArray.length;i++)sdpArray[i].startsWith("a=rtpmap")?(matches=sdpArray[i].match("a=rtpmap:(.+) (.+)/.*"))&&matches.length>2&&(rtpmap=parseInt(matches[1],10),codec=matches[2]):"H264"!==codec&&"VP8"!==codec||(sdpArray[i].startsWith("a=fmtp:"+rtpmap)?(bitrateString=this.getBitrateString(sdpArray[i],minBitrate,maxBitrate))&&(sdpArray[i]+=";"+bitrateString):(bitrateString=this.getBitrateString("",minBitrate,maxBitrate))&&(sdpArray[i]="a=fmtp:"+rtpmap+" "+bitrateString+"\r\n"+sdpArray[i]),codec="",rtpmap=-1);var newSDP="";for(i=0;i<sdpArray.length;i++)""!=sdpArray[i]&&(newSDP+=sdpArray[i]+"\n");return newSDP}return sdp},getBitrateString:function(string,minBitrate,maxBitrate){var bitrateString="";return minBitrate&&-1==string.indexOf("x-google-min-bitrate")&&(bitrateString+="x-google-min-bitrate="+minBitrate),maxBitrate&&-1==string.indexOf("x-google-max-bitrate")&&(bitrateString&&(bitrateString+=";"),bitrateString+="x-google-max-bitrate="+maxBitrate),bitrateString}},compress=function(){var n,_ref=(n=_regenerator().m((function _callee(compression,data,base64){var stream,compressedReadableStream,compressedResponse,blob,buffer,compressedBase64;return _regenerator().w((function(_context){for(;;)switch(_context.n){case 0:if("undefined"!=typeof CompressionStream){_context.n=1;break}throw new Error("Compression is not available");case 1:return stream="string"==typeof data?new Blob([data],{type:"text/plain"}).stream():data.stream(),compressedReadableStream=stream.pipeThrough(new CompressionStream(compression)),_context.n=2,new Response(compressedReadableStream);case 2:return compressedResponse=_context.v,_context.n=3,compressedResponse.blob();case 3:if(blob=_context.v,!base64){_context.n=5;break}return _context.n=4,blob.arrayBuffer();case 4:return buffer=_context.v,compressedBase64=btoa(String.fromCharCode.apply(String,_toConsumableArray(new Uint8Array(buffer)))),_context.a(2,compressedBase64);case 5:return _context.a(2,blob);case 6:return _context.a(2)}}),_callee)})),function(){var t=this,e=arguments;return new Promise((function(r,o){var a=n.apply(t,e);function _next(n){asyncGeneratorStep(a,r,o,_next,_throw,"next",n)}function _throw(n){asyncGeneratorStep(a,r,o,_next,_throw,"throw",n)}_next(void 0)}))});return function(_x,_x2,_x3){return _ref.apply(this,arguments)}}();module.exports={isEmptyObject:function(obj){for(var name in obj)return!1;return!0},copyObjectToArray:function(obj){var ret=[];for(var prop in obj)obj.hasOwnProperty(prop)&&ret.push(obj[prop]);return ret},copyObjectPropsToAnotherObject:function(src,dst){for(var prop in src)src.hasOwnProperty(prop)&&(dst[prop]=src[prop])},processRtcStatsReport:function(browser,report){var result={};if("chrome"==browser){var gotResult=!1;if(report.type&&"googCandidatePair"==report.type&&"true"==report.googActiveConnection&&(gotResult=!0),report.type&&"ssrc"==report.type&&(gotResult=!0),gotResult)for(var k in report)report.hasOwnProperty(k)&&(result[k]=report[k]);return result}if("firefox"==browser){if(report.type&&("outboundrtp"==report.type||"inboundrtp"==report.type)&&-1==report.id.indexOf("rtcp"))for(var k in result={},report)report.hasOwnProperty(k)&&(result[k]=report[k]);return result}return result},Browser:Browser,SDP:SDP,logger:function(){return{init:function(verbosity,enablePushLogs,customLogger,enableLogs){switch(verbosity.toUpperCase()){case"DEBUG":this.verbosity=3;break;case"INFO":this.verbosity=2;break;case"ERROR":this.verbosity=0;break;case"WARN":this.verbosity=1;break;case"TRACE":this.verbosity=4;break;default:this.verbosity=2}this.date=function(){return(new Date).toTimeString().split(" ")[0]},this.enablePushLogs=enablePushLogs;var delayedLogs=[];this.customLogger=customLogger,this.enableLogs=enableLogs,this.pushLogs=function(log){if(this.wsConnection&&this.enablePushLogs){if(delayedLogs.length)for(var i=0;i<delayedLogs.length;i++)this.wsConnection.send(JSON.stringify({message:"pushLogs",data:[{logs:delayedLogs[i]}]}));delayedLogs=[],this.wsConnection.send(JSON.stringify({message:"pushLogs",data:[{logs:log}]}))}else delayedLogs.push(log)}},info:function(src,text){if(this.enableLogs){var prefix=this.date()+" INFO "+src+" - ";this.pushLogs(prefix+JSON.stringify(text)+"\n"),this.verbosity>=2&&(null!=this.customLogger?this.customLogger.info(text):console.log(prefix,text))}},debug:function(src,text){if(this.enableLogs){var prefix=this.date()+" DEBUG "+src+" - ";this.pushLogs(prefix+JSON.stringify(text)+"\n"),this.verbosity>=3&&(null!=this.customLogger?this.customLogger.debug(text):console.log(prefix,text))}},trace:function(src,text){if(this.enableLogs){var prefix=this.date()+" TRACE "+src+" - ";this.pushLogs(prefix+JSON.stringify(text)+"\n"),this.verbosity>=4&&(null!=this.customLogger?this.customLogger.trace(text):console.log(prefix,text))}},warn:function(src,text){if(this.enableLogs){var prefix=this.date()+" WARN "+src+" - ";this.pushLogs(prefix+JSON.stringify(text)+"\n"),this.verbosity>=1&&(null!=this.customLogger?this.customLogger.warn(text):console.warn(prefix,text))}},error:function(src,text){if(this.enableLogs){var prefix=this.date()+" ERROR "+src+" - ";this.pushLogs(prefix+JSON.stringify(text)+"\n"),this.verbosity>=0&&(null!=this.customLogger?this.customLogger.error(text):console.error(prefix,text))}},setEnableLogs:function(enableLogs){this.enableLogs=enableLogs},setCustomLogger:function(customLogger){this.customLogger=customLogger},setConnection:function(connection){this.wsConnection=connection},setPushLogs:function(pushLogs){this.enablePushLogs=pushLogs},setLevel:function(level){switch(level.toUpperCase()){case"DEBUG":this.verbosity=3;break;case"INFO":this.verbosity=2;break;case"ERROR":this.verbosity=0;break;case"WARN":this.verbosity=1;break;case"TRACE":this.verbosity=4;break;default:this.verbosity=2}}}},stripCodecs:function(sdp,codecs){if(!codecs.length)return sdp;for(var i,sdpArray=sdp.split("\n"),codecsArray=codecs.split(","),pt=[],p=0;p<codecsArray.length;p++)for(console.log("Searching for codec "+codecsArray[p]),i=0;i<sdpArray.length;i++)-1!=sdpArray[i].search(new RegExp(codecsArray[p],"i"))&&0==sdpArray[i].indexOf("a=rtpmap")&&(console.log(codecsArray[p]+" detected"),pt.push(sdpArray[i].match(/[0-9]+/)[0]),sdpArray[i]="");if(pt.length){for(p=0;p<pt.length;p++)for(i=0;i<sdpArray.length;i++)-1==sdpArray[i].search("a=fmtp:"+pt[p])&&-1==sdpArray[i].search("a=rtcp-fb:"+pt[p])||(sdpArray[i]="");for(i=0;i<sdpArray.length;i++)if(-1!=sdpArray[i].search("m=audio")||-1!=sdpArray[i].search("m=video")){for(var mLineSplitted=sdpArray[i].split(" "),newMLine="",m=0;m<mLineSplitted.length;m++)(-1==pt.indexOf(mLineSplitted[m].trim())||m<=2)&&(newMLine+=mLineSplitted[m],m<mLineSplitted.length-1&&(newMLine+=" "));sdpArray[i]=newMLine}}var result="";for(i=0;i<sdpArray.length;i++)""!=sdpArray[i]&&(result+=sdpArray[i]+"\n");return result},getCurrentCodecAndSampleRate:function(sdp,mediaType){for(var codecPt,rows=sdp.split("\n"),ret={},i=0;i<rows.length;i++){if(codecPt&&-1!=rows[i].indexOf("a=rtpmap:"+codecPt))return ret.name=rows[i].split(" ")[1].split("/")[0],ret.sampleRate=rows[i].split(" ")[1].split("/")[1],ret;-1!=rows[i].indexOf("m="+mediaType)&&(codecPt=rows[i].split(" ")[3].trim())}return ret.name="undefined",ret.sampleRate="undefined",ret},isPromise:function(object){return null!==object&&"object"===_typeof(object)&&"function"==typeof object.then&&"function"==typeof object.catch},setPublishingBitrate:function(sdp,mediaConnection,minBitrate,maxBitrate){return(minBitrate||maxBitrate)&&(sdp&&Browser.isChrome()||Browser.isSafariWebRTC()?sdp=SDP.setPublishingBitrate(sdp,minBitrate,maxBitrate):mediaConnection&&mediaConnection.setPublishingBitrate(minBitrate,maxBitrate)),sdp},addFieldToCsvString:function(csvString,field,delimiter){return""!==field&&field.indexOf(delimiter)>=0&&(field='"'+field+'"'),csvString=""===csvString?field:csvString+delimiter+field},compress:compress}},{}],43:[function(require,module,exports){function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}function _slicedToArray(r,e){return function(r){if(Array.isArray(r))return r}(r)||function(r,l){var t=null==r?null:"undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(null!=t){var e,n,i,u,a=[],f=!0,o=!1;try{if(i=(t=t.call(r)).next,0===l){if(Object(t)!==t)return;f=!1}else for(;!(f=(e=i.call(t)).done)&&(a.push(e.value),a.length!==l);f=!0);}catch(r){o=!0,n=r}finally{try{if(!f&&null!=t.return&&(u=t.return(),Object(u)!==u))return}finally{if(o)throw n}}return a}}(r,e)||_unsupportedIterableToArray(r,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}function _regenerator(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function i(r,n,o,i){var c=n&&n.prototype instanceof Generator?n:Generator,u=Object.create(c.prototype);return _regeneratorDefine2(u,"_invoke",function(r,n,o){var i,c,u,f=0,p=o||[],y=!1,G={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return i=t,c=0,u=e,G.n=r,a}};function d(r,n){for(c=r,u=n,t=0;!y&&f&&!o&&t<p.length;t++){var o,i=p[t],d=G.p,l=i[2];r>3?(o=l===n)&&(u=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&d<i[1])?(c=0,G.v=n,G.n=i[1]):d<l&&(o=r<3||i[0]>n||n>l)&&(i[4]=r,i[5]=n,G.n=l,c=0))}if(o||r>1)return a;throw y=!0,n}return function(o,p,l){if(f>1)throw TypeError("Generator is already running");for(y&&1===p&&d(p,l),c=p,u=l;(t=c<2?e:u)||!y;){i||(c?c<3?(c>1&&(G.n=-1),d(c,u)):G.n=u:G.v=u);try{if(f=2,i){if(c||(o="next"),t=i[o]){if(!(t=t.call(i,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);i=e}else if((t=(y=G.n<0)?u:r.call(n,G))!==a)break}catch(t){i=e,c=1,u=t}finally{f=1}}return{value:t,done:y}}}(r,o,i),!0),u}var a={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}t=Object.getPrototypeOf;var c=[][n]?t(t([][n]())):(_regeneratorDefine2(t={},n,(function(){return this})),t),u=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(c);function f(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,GeneratorFunctionPrototype):(e.__proto__=GeneratorFunctionPrototype,_regeneratorDefine2(e,o,"GeneratorFunction")),e.prototype=Object.create(u),e}return GeneratorFunction.prototype=GeneratorFunctionPrototype,_regeneratorDefine2(u,"constructor",GeneratorFunctionPrototype),_regeneratorDefine2(GeneratorFunctionPrototype,"constructor",GeneratorFunction),GeneratorFunction.displayName="GeneratorFunction",_regeneratorDefine2(GeneratorFunctionPrototype,o,"GeneratorFunction"),_regeneratorDefine2(u),_regeneratorDefine2(u,o,"Generator"),_regeneratorDefine2(u,n,(function(){return this})),_regeneratorDefine2(u,"toString",(function(){return"[object Generator]"})),(_regenerator=function(){return{w:i,m:f}})()}function _regeneratorDefine2(e,r,n,t){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}(_regeneratorDefine2=function(e,r,n,t){function o(r,n){_regeneratorDefine2(e,r,(function(e){return this._invoke(r,n,e)}))}r?i?i(e,r,{value:n,enumerable:!t,configurable:!t,writable:!t}):e[r]=n:(o("next",0),o("throw",1),o("return",2))})(e,r,n,t)}function asyncGeneratorStep(n,t,e,r,o,a,c){try{var i=n[a](c),u=i.value}catch(n){return void e(n)}i.done?t(u):Promise.resolve(u).then(r,o)}function _asyncToGenerator(n){return function(){var t=this,e=arguments;return new Promise((function(r,o){var a=n.apply(t,e);function _next(n){asyncGeneratorStep(a,r,o,_next,_throw,"next",n)}function _throw(n){asyncGeneratorStep(a,r,o,_next,_throw,"throw",n)}_next(void 0)}))}}var extensionId,defaultConstraints,logger,audioContext,createMicGainNode,microphoneGain,browserDetails=require("webrtc-adapter").default.browserDetails,uuid_v1=require("uuid").v1,util=require("./util"),connections={},constants=require("./constants"),validBrowsers=["firefox","chrome","safari"],videoCams=[],mics=[],audioSourceDevice="",mixAudioTracks=function(stream1,stream2){var stream1Sound=audioContext.createMediaStreamSource(stream1),stream2Sound=audioContext.createMediaStreamSource(stream2),destination=audioContext.createMediaStreamDestination(),newStream=destination.stream;return stream1Sound.connect(destination),stream2Sound.connect(destination),newStream.getAudioTracks()[0]},loadCanvasVideo=function(display,stream,video){var vEl=video;if(vEl){if("CANVAS"!==vEl.tagName){var canvas=document.createElement("canvas");display.replaceChild(canvas,vEl),canvas.appendChild(vEl),vEl=canvas}}else!function(parent){var canvas=document.createElement("canvas");parent.appendChild(canvas)}(display),function(parent){var video=document.createElement("video");parent.appendChild(video)}(display.children[0]),vEl=display.children[0];vEl.id||(vEl.id=uuid_v1()+"-LOCAL_CACHED_VIDEO");var child=vEl.children[0];return child.srcObject=stream,child.muted=!0,child.onloadedmetadata=function(e){child.play(),vEl.width=child.videoWidth,vEl.height=child.videoHeight,function(canvas,videoWidth,videoHeight){if(!canvas.parentNode)return;var newSize,display=vEl.parentNode,parentSize={w:display.parentNode.clientWidth,h:display.parentNode.clientHeight};newSize=videoWidth&&videoHeight?downScaleToFitSize(videoWidth,videoHeight,parentSize.w,parentSize.h):downScaleToFitSize(canvas.videoWidth,canvas.videoHeight,parentSize.w,parentSize.h);display.style.width=newSize.w+"px",display.style.height=newSize.h+"px";var margin=0;parentSize.h-newSize.h>1&&(margin=Math.floor((parentSize.h-newSize.h)/2));function downScaleToFitSize(videoWidth,videoHeight,dstWidth,dstHeight){var newWidth,newHeight,videoRatio=videoWidth/videoHeight;return dstWidth/dstHeight>videoRatio?(newHeight=dstHeight,newWidth=Math.floor(videoRatio*dstHeight)):(newWidth=dstWidth,newHeight=Math.floor(dstWidth/videoRatio)),{w:newWidth,h:newHeight}}display.style.margin=margin+"px auto"}(vEl,child.videoWidth,child.videoHeight)},util.Browser.isFirefox()&&vEl.getContext("2d"),vEl.srcObject=vEl.captureStream(30),stream.getAudioTracks().length>0&&vEl.srcObject.addTrack(stream.getAudioTracks()[0]),vEl},loadVideo=function(display,stream,screenShare,requestAudioConstraints,resolve,constraints,useCanvas){var video;function resolveCallback(){requestAudioConstraints&&"chrome"==browserDetails.browser?(logger.info("webrtc","Request for audio stream"),navigator.getUserMedia({audio:requestAudioConstraints},(function(stream){if(logger.info("webrtc","Got audio stream, add it to video stream"),video.srcObject.getAudioTracks()[0]){var mixedTrack=mixAudioTracks(stream,video.srcObject),originalTrack=video.srcObject.getAudioTracks()[0];video.srcObject.removeTrack(originalTrack),video.srcObject.addTrack(mixedTrack)}else video.srcObject.addTrack(stream.getAudioTracks()[0]);resolve(display)}))):resolve(display)}video=useCanvas?loadCanvasVideo(display,stream,getCacheInstance(display)):function(display,stream,screenShare,constraints,video){var vEl=video;return vEl||(vEl=createVideoElement(),display.appendChild(vEl)),vEl.id||(vEl.id=uuid_v1()+"-LOCAL_CACHED_VIDEO"),vEl.srcObject=stream,vEl.onloadedmetadata=function(e){screenShare&&!screenCaptureSupportedBrowsers()&&setScreenResolution(vEl,stream,constraints),vEl.play()},vEl}(display,stream,screenShare,constraints,getCacheInstance(display)),createMicGainNode&&stream.getAudioTracks().length>0&&"chrome"==browserDetails.browser&&(audioContext.resume(),microphoneGain=createGainNode(stream)),constraints.systemSound&&"chrome"==browserDetails.browser?chrome.runtime.sendMessage(extensionId,{type:"isInstalled"},(function(response){response?chrome.runtime.sendMessage(extensionId,{type:"getSourceId"},(function(response){if(response.error)resolveCallback(),logger.error("webrtc",response.error);else if(response.systemSoundAccess){var constraints={audio:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:response.sourceId,echoCancellation:!0},optional:[]},video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:response.sourceId},optional:[]}};navigator.getUserMedia(constraints,(function(audioStream){if(stream.getAudioTracks().length>0){var originalAudioTrack=stream.getAudioTracks()[0],mixedTrack=mixAudioTracks(stream,audioStream);stream.addTrack(mixedTrack),stream.removeTrack(originalAudioTrack)}else stream.addTrack(audioStream.getAudioTracks()[0]);resolveCallback()}),(function(reason){resolveCallback(),logger.error("webrtc",reason)}))}else resolveCallback(),logger.error("webrtc","System sound: access is denied by the user")})):resolveCallback()})):resolveCallback()},createGainNode=function(stream){var audioCtx=audioContext,source=audioCtx.createMediaStreamSource(stream),gainNode=audioCtx.createGain(),destination=audioCtx.createMediaStreamDestination(),outputStream=destination.stream;source.connect(gainNode),gainNode.connect(destination);var sourceAudioTrack=stream.getAudioTracks()[0];return audioSourceDevice=sourceAudioTrack.label,gainNode.sourceAudioTrack=sourceAudioTrack,gainNode.release=function(){this.sourceAudioTrack.stop(),this.disconnect()},stream.addTrack(outputStream.getAudioTracks()[0]),stream.removeTrack(sourceAudioTrack),gainNode},setScreenResolution=function(video,stream,constraints){var newHeight,newWidth,videoRatio;video.videoWidth>video.videoHeight?(videoRatio=video.videoWidth/video.videoHeight,newHeight=constraints.video.videoWidth/videoRatio,newWidth=constraints.video.videoWidth):(videoRatio=video.videoHeight/video.videoWidth,newWidth=constraints.video.videoHeight/videoRatio,newHeight=constraints.video.videoHeight),console.log("videoRatio === "+videoRatio),stream.getVideoTracks()[0].applyConstraints({height:newHeight,width:newWidth})},getScreenDeviceIdWoExtension=function(constraints){return new Promise((function(resolve,reject){var video={};constraints.video.frameRate.ideal&&(video.frameRate=constraints.video.frameRate.ideal),constraints.video.width&&(video.width=constraints.video.width),constraints.video.height&&(video.height=constraints.video.height),0===Object.keys(video).length&&(video=!0),resolve({video:video,audio:!0})}))},getScreenDeviceId=function(constraints){return new Promise((function(resolve,reject){var o={};window.chrome?chrome.runtime.sendMessage(extensionId,{type:"isInstalled"},(function(response){response?(o.maxWidth=constraints&&constraints.video&&constraints.video.width?constraints.video.width:320,o.maxHeight=constraints&&constraints.video&&constraints.video.height?constraints.video.height:240,o.maxFrameRate=constraints&&constraints.video&&constraints.video.frameRate&&constraints.video.frameRate.ideal?constraints.video.frameRate.ideal:30,o.chromeMediaSource="desktop",chrome.runtime.sendMessage(extensionId,{type:"getSourceId"},(function(response){if(response.error)reject(new Error("Screen access denied"));else{o.chromeMediaSourceId=response.sourceId;var result={mandatory:o,sourceId:response.sourceId};response.systemSoundAccess&&(result.audioMandatory={chromeMediaSource:"desktop",chromeMediaSourceId:response.sourceId,echoCancellation:!0}),resolve(result)}}))):reject(new Error("Screen sharing extension is not available"))})):(o.mediaSource=constraints.video.mediaSource,o.width={},o.height={},o.frameRate={min:constraints.video.frameRate.max,max:constraints.video.frameRate.max},o.videoWidth=constraints.video.width,o.videoHeight=constraints.video.height,resolve(o))}))},releaseMedia=function(display){var video=getCacheInstance(display);return!!video&&(removeVideoElement(video),!0)};function getCacheInstance(display){var i;if(display)for(i=0;i<display.children.length;i++)if(display.children[i]&&(-1!=display.children[i].id.indexOf("-LOCAL_CACHED_VIDEO")||-1!=display.children[i].id.indexOf("-REMOTE_CACHED_VIDEO")))return logger.info("webrtc","FOUND WEBRTC CACHED INSTANCE, id "+display.children[i].id),display.children[i]}function createVideoElement(){var useControls=arguments.length>0&&void 0!==arguments[0]&&arguments[0],video=document.createElement("video");return video.muted=!0,util.Browser.isSafariWebRTC()&&(video.setAttribute("playsinline",""),video.setAttribute("webkit-playsinline","")),useControls&&enableVideoControls(video),video}function removeVideoElement(video){if(video.srcObject){video.pause();for(var tracks=video.srcObject.getTracks(),i=0;i<tracks.length;i++)tracks[i].stop(),-1!=video.id.indexOf("-LOCAL_CACHED_VIDEO")&&"audio"==tracks[i].kind&µphoneGain&µphoneGain.release();if(video.srcObject=null,"CANVAS"===video.tagName)for(var _i=0;_i<video.children.length;_i++)removeVideoElement(video.children[_i])}}function enableVideoControls(video){video&&!video.controls&&video.setAttribute("controls","controls")}var getList=function(devices,kind){for(var videoFilter=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,list={audio:[],video:[]},micCount=0,outputCount=0,camCount=0,i=0;i<devices.length;i++){var device=devices[i],ret={id:device.deviceId,label:device.label};0===device.kind.indexOf("audio"+kind)&&"communications"!==device.deviceId?(ret.type="audioinput"===device.kind?"mic":"speaker","mic"===ret.type&&""===ret.label&&(ret.label="microphone"+ ++micCount),"speaker"===ret.type&&""===ret.label&&(ret.label="speaker"+ ++outputCount),list.audio.push(ret)):0===device.kind.indexOf("video"+kind)?!videoFilter||videoFilter.find((function(id){return id===device.deviceId}))?(""===ret.label&&(ret.label="camera"+ ++camCount),ret.type="camera",list.video.push(ret)):logger.debug("webrtc","Video device "+device.deviceId+"does not conform the filter "+JSON.stringify(videoFilter)):logger.debug("webrtc","unknown device "+device.kind+" id "+device.deviceId)}return list},listDevices=function(labels,kind,deviceConstraints){deviceConstraints||(deviceConstraints={audio:!0,video:!0}),kind?kind===constants.MEDIA_DEVICE_KIND.ALL&&(kind=""):kind=constants.MEDIA_DEVICE_KIND.INPUT;return new Promise((function(resolve,reject){navigator.mediaDevices.enumerateDevices().then((function(devices){if(labels){var constraints=function(devices){for(var constraints={},i=0;i<devices.length;i++){var device=devices[i];0===device.kind.indexOf("audio"+kind)&&deviceConstraints.audio?constraints.audio=deviceConstraints.audio:0===device.kind.indexOf("video"+kind)&&deviceConstraints.video?constraints.video=deviceConstraints.video:logger.debug("webrtc","unknown device "+device.kind+" id "+device.deviceId)}return constraints}(devices);if(0===Object.keys(constraints).length)return void reject(new Error(kind+" media devices not found"));navigator.getUserMedia(constraints,(function(stream){navigator.mediaDevices.enumerateDevices().then((function(devicesWithLabels){resolve(getList(devicesWithLabels,kind)),stream.getTracks().forEach((function(track){track.stop()}))}),reject)}),reject)}else resolve(getList(devices,kind))}),reject)}))},getMobileDevices=function(){var _ref3=_asyncToGenerator(_regenerator().m((function _callee4(kind){var deviceConstraints,constraints,videoFilter,list,getCamera,front,back,_stream,mediaDevices,_t2,_args4=arguments;return _regenerator().w((function(_context4){for(;;)switch(_context4.p=_context4.n){case 0:return deviceConstraints=_args4.length>1&&void 0!==_args4[1]?_args4[1]:null,constraints={},videoFilter=[],list=null,kind?kind===constants.MEDIA_DEVICE_KIND.ALL&&(kind=""):kind=constants.MEDIA_DEVICE_KIND.INPUT,deviceConstraints&&deviceConstraints.audio?constraints.audio=deviceConstraints.audio:constraints.audio=!0,deviceConstraints&&deviceConstraints.video&&"object"===_typeof(deviceConstraints.video)?constraints.video=deviceConstraints.video:constraints.video={},getCamera=function(){var _ref4=_asyncToGenerator(_regenerator().m((function _callee3(constraints,facingMode){var deviceId,mediaConstraints,_t;return _regenerator().w((function(_context3){for(;;)switch(_context3.p=_context3.n){case 0:return deviceId=null,(mediaConstraints={audio:!1,video:constraints.video}).video.facingMode=facingMode,_context3.p=1,_context3.n=2,navigator.mediaDevices.getUserMedia(mediaConstraints);case 2:stream=_context3.v,stream&&(stream.getVideoTracks().length>0&&(deviceId=stream.getVideoTracks()[0].getSettings().deviceId),stream.getTracks().forEach((function(track){track.stop()}))),_context3.n=4;break;case 3:_context3.p=3,_t=_context3.v,logger.error("webrtc","Can't get device access with video constraints "+JSON.stringify(constraints.video)+", error "+_t);case 4:return _context3.a(2,deviceId)}}),_callee3,null,[[1,3]])})));return function(_x5,_x6){return _ref4.apply(this,arguments)}}(),_context4.n=1,getCamera(constraints,{ideal:"user"});case 1:return(front=_context4.v)&&""!==front&&(logger.debug("webrtc","Front camera id: "+front),videoFilter.push(front)),_context4.n=2,getCamera(constraints,{ideal:"environment"});case 2:return(back=_context4.v)&&""!==back&&(logger.debug("webrtc","Back camera id: "+back),videoFilter.push(back)),_context4.p=3,_context4.n=4,navigator.mediaDevices.getUserMedia(constraints);case 4:if(!(_stream=_context4.v)){_context4.n=6;break}return _context4.n=5,navigator.mediaDevices.enumerateDevices();case 5:(mediaDevices=_context4.v)&&(logger.debug("webrtc","mediaDevices: "+JSON.stringify(mediaDevices)),list=getList(mediaDevices,kind,videoFilter)),_stream.getTracks().forEach((function(track){track.stop()}));case 6:_context4.n=8;break;case 7:_context4.p=7,_t2=_context4.v,logger.error("webrtc","Can't get device access with constraints "+JSON.stringify(constraints)+", error "+_t2);case 8:return _context4.a(2,list)}}),_callee4,null,[[3,7]])})));return function(_x4){return _ref3.apply(this,arguments)}}();var screenCaptureSupportedBrowsers=function(){return util.Browser.isChrome()||util.Browser.isSafari()};module.exports={createConnection:function(options){return new Promise((function(resolve,reject){options.logger&&(logger=options.logger);var id=options.id,connectionConfig=options.connectionConfig||{iceServers:[]},connectionConstraints=options.connectionConstraints||{};connectionConstraints.hasOwnProperty("optional")||(connectionConstraints.optional=[{DtlsSrtpKeyAgreement:!0}]),connectionConfig.bundlePolicy="max-compat";var localVideo,currentAudioTrack,currentVideoTrack,systemSoundTrack,connection=new RTCPeerConnection(connectionConfig,connectionConstraints),display=options.display,localDisplay=options.localDisplay,remoteDisplay=options.remoteDisplay,bidirectional=options.bidirectional,remoteVideo=options.remoteVideo,switchCamIndex=0,switchMicCount=0,customStream=options.customStream,constraints=options.constraints?options.constraints:{},screenShare=!1,playoutDelay=options.playoutDelay,videoContentHint=options.videoContentHint?options.videoContentHint:"motion",unmutePlayOnStart=void 0===options.unmutePlayOnStart||options.unmutePlayOnStart,useControls=options.useControls||!1,unmuteRequiredEvent=options.unmuteRequiredEvent?options.unmuteRequiredEvent:null,zoom=null;if(bidirectional)(localVideo=getCacheInstance(localDisplay))&&(localVideo.srcObject?(localVideo.id=id+"-local",setContentHint(localVideo.srcObject,videoContentHint),addStreamTracks(connection,localVideo.srcObject)):localVideo=null),(remoteVideo=getCacheInstance(remoteDisplay))||(remoteVideo=createVideoElement(useControls),remoteDisplay.appendChild(remoteVideo)),remoteVideo.id=id+"-remote",options.audioOutputId&&"undefined"!=typeof remoteVideo.setSinkId&&remoteVideo.setSinkId(options.audioOutputId),remoteVideo.style="border-radius: 1px";else if(remoteVideo)remoteVideo.id&&(id=remoteVideo.id);else{var cachedVideo=getCacheInstance(display);cachedVideo&&-1===cachedVideo.id.indexOf("-REMOTE_CACHED_VIDEO")&&cachedVideo.srcObject?((localVideo=cachedVideo).id=id,setContentHint(localVideo.srcObject,videoContentHint),addStreamTracks(connection,localVideo.srcObject)):(cachedVideo?remoteVideo=cachedVideo:(remoteVideo=createVideoElement(useControls),display.appendChild(remoteVideo)),remoteVideo.id=id,options.audioOutputId&&"undefined"!=typeof remoteVideo.setSinkId&&remoteVideo.setSinkId(options.audioOutputId),remoteVideo.style="border-radius: 1px")}if(localVideo){useControls&&enableVideoControls(localVideo);var videoTrack=localVideo.srcObject.getVideoTracks()[0];videoTrack&&videoCams.forEach((function(cam,index){videoTrack.label===cam.label&&(switchCamIndex=index)}));var audioTrack=localVideo.srcObject.getAudioTracks()[0];audioTrack&&mics.forEach((function(mic,index){audioTrack.label===mic.label&&(switchMicCount=index)}))}function setContentHint(stream,hint){stream.getVideoTracks().forEach((function(track){void 0===track.contentHint?logger.warn("webrtc","Track contentHint unsupported"):(logger.info("webrtc","Set video track contentHint to "+hint),track.contentHint=hint)}))}function addStreamTracks(pc,stream){stream.getTracks().forEach((function(track){pc.addTrack(track,stream)}))}remoteVideo&&useControls&&enableVideoControls(remoteVideo),connection.ontrack=function(event){remoteVideo&&(remoteVideo.srcObject=event.streams[0],remoteVideo.onloadedmetadata=function(e){remoteVideo&&remoteVideo.play().then((function(){unmutePlayOnStart?remoteVideo.muted=!1:fireUnmuteEvent()})).catch((function(e){validBrowsers.includes(browserDetails.browser)?(logger.info("webrtc","Autoplay detected! Trying to play a video with a muted sound..."),remoteVideo.muted=!0,remoteVideo.play(),fireUnmuteEvent()):logger.error("webrtc",e)}))}),void 0!==playoutDelay&&connection.getReceivers().forEach((function(track){void 0===track.playoutDelayHint&&logger.warn("webrtc","Playout delay unsupported"),track.playoutDelayHint=playoutDelay}))},connection.onremovestream=function(event){remoteVideo&&remoteVideo.pause()},connection.onsignalingstatechange=function(event){},connection.oniceconnectionstatechange=function(event){},connection.onicecandidate=function(event){null!=event.candidate&&logger.debug("webrtc","Added icecandidate: "+event.candidate.candidate)};var unmuteAudio=function(){localVideo&&localVideo.srcObject&&localVideo.srcObject.getAudioTracks().length>0&&(localVideo.srcObject.getAudioTracks()[0].enabled=!0)},unmuteVideo=function(){localVideo&&localVideo.srcObject&&localVideo.srcObject.getVideoTracks().length>0&&(localVideo.srcObject.getVideoTracks()[0].enabled=!0)},getStat=function(){var _ref=_asyncToGenerator(_regenerator().m((function _callee(callbackFn,nativeStats){var result,rawStat;return _regenerator().w((function(_context){for(;;)switch(_context.n){case 0:return result={outboundStream:{},inboundStream:{},otherStats:[]},_context.n=1,getWebRTCStats();case 1:rawStat=_context.v,nativeStats?callbackFn(rawStat):(rawStat["candidate-pair"]&&rawStat["candidate-pair"].forEach((function(report){"succeeded"===report.state&&report.nominated&&(report.availableIncomingBitrate?result.otherStats.availableIncomingBitrate=report.availableIncomingBitrate:localVideo&&report.availableOutgoingBitrate&&(result.otherStats.availableOutgoingBitrate=report.availableOutgoingBitrate))})),rawStat["outbound-rtp"]&&rawStat["outbound-rtp"].forEach((function(report){fillStatObject(result.outboundStream,report,report.kind),"video"===report.kind&&getVideoSize(result.outboundStream[report.kind],report.type,report)})),rawStat["inbound-rtp"]&&rawStat["inbound-rtp"].forEach((function(report){fillStatObject(result.inboundStream,report,report.kind),"video"===report.kind&&getVideoSize(result.inboundStream.video,report.type,report)})),callbackFn(result));case 2:return _context.a(2)}}),_callee)})));return function(_x,_x2){return _ref.apply(this,arguments)}}(),getVideoSize=function(obj,type,report){var videoSize={};"outbound-rtp"===type?void 0!==localVideo&&null!=localVideo&&(videoSize=localVideo.srcObject.getVideoTracks()[0].getSettings()):"inbound-rtp"===type&&void 0!==remoteVideo&&null!=remoteVideo&&(videoSize.width=remoteVideo.videoWidth,videoSize.height=remoteVideo.videoHeight),void 0!==report.frameWidth?obj.width=report.frameWidth:void 0!==videoSize.width&&(obj.width=videoSize.width),void 0!==report.frameHeight?obj.height=report.frameHeight:void 0!==videoSize.height&&(obj.height=videoSize.height)},fillStatObject=function(obj,report,mediaType){obj[mediaType]={};var description=null!=connection.currentRemoteDescription?connection.currentRemoteDescription:connection.remoteDescription,sdp="";description&&description.sdp?sdp=description.sdp:logger.debug("webrtc","Can't parse current SDP to detect codec and sampleRate");var qualityLimitationDurations,codec=util.getCurrentCodecAndSampleRate(sdp,mediaType);obj[mediaType].codec=codec.name,obj[mediaType].codecRate=codec.sampleRate,Object.keys(report).forEach((function(key){(key.startsWith("bytes")||key.startsWith("packets")||-1!=key.indexOf("Count")||-1!=key.indexOf("audioLevel")||"framesPerSecond"===key||"qualityLimitationReason"===key)&&(obj[mediaType][key]=report[key]),"qualityLimitationDurations"===key&&(qualityLimitationDurations=report[key])})),qualityLimitationDurations&&(obj[mediaType].qualityLimitationDurations=qualityLimitationDurations[obj[mediaType].qualityLimitationReason])},processScreenStream=function(stream,resolve){connection.getSenders().forEach((function(sender){if("audio"!==sender.track.kind){currentAudioTrack=localVideo.srcObject.getAudioTracks()[0],currentVideoTrack=localVideo.srcObject.getVideoTracks()[0];var newVideoTrack=stream.getVideoTracks()[0];newVideoTrack.enabled=currentVideoTrack.enabled,sender.replaceTrack(newVideoTrack),localVideo.srcObject=stream,stream.getAudioTracks()[0]?(systemSoundTrack=stream.getAudioTracks()[0],connection.getSenders().forEach((function(sender){if("video"!==sender.track.kind){var mixedTrack=mixAudioTracks(stream,new MediaStream([sender.track]));mixedTrack.enabled=currentAudioTrack.enabled,sender.replaceTrack(mixedTrack),localVideo.srcObject.removeTrack(stream.getAudioTracks()[0]),localVideo.srcObject.addTrack(mixedTrack),currentAudioTrack.enabled=!0}}))):localVideo.srcObject.addTrack(currentAudioTrack)}})),logger.info("webrtc","Switch to screen"),screenShare=!0,resolve()},updateVideoSettings=function(settings){return new Promise((function(resolve,reject){connection&&settings&&connection.getSenders().forEach((function(sender){if("video"==sender.track.kind){for(var parameters=sender.getParameters(),i=0;i<parameters.encodings.length;i++)settings.maxBitrate?parameters.encodings[i].maxBitrate=1e3*settings.maxBitrate:parameters.encodings[i].maxBitrate&&delete parameters.encodings[i].maxBitrate,settings.frameRate&&(parameters.encodings[i].maxFramerate=settings.frameRate),settings.scaleResolutionDownBy&&(parameters.encodings[i].scaleResolutionDownBy=settings.scaleResolutionDownBy);sender.setParameters(parameters).then((function(){logger.info("webrtc","Set video encoder parameters to "+JSON.stringify(parameters.encodings)),resolve(parameters.encodings)})).catch((function(reason){logger.error("webrtc",reason),reject(reason)}))}}))}))},fireUnmuteEvent=function(){unmuteRequiredEvent&&"function"==typeof unmuteRequiredEvent&&unmuteRequiredEvent()},setZoom=function(){var _ref2=_asyncToGenerator(_regenerator().m((function _callee2(value){var _localVideo$srcObject3,_localVideo$srcObject4,track;return _regenerator().w((function(_context2){for(;;)switch(_context2.n){case 0:if(!zoom){_context2.n=6;break}if(!(value>=zoom.min&&value<=zoom.max)){_context2.n=4;break}if(!localVideo||!localVideo.srcObject){_context2.n=2;break}return _localVideo$srcObject3=localVideo.srcObject.getVideoTracks(),_localVideo$srcObject4=_slicedToArray(_localVideo$srcObject3,1),track=_localVideo$srcObject4[0],_context2.n=1,track.applyConstraints({advanced:[{zoom:value}]});case 1:zoom.value=value,_context2.n=3;break;case 2:logger.warn("webrtc","Can't set zoom value: no local video");case 3:_context2.n=5;break;case 4:logger.info("webrtc","Zoom value "+value+"is out of range: "+zoom.min+"-"+zoom.max);case 5:_context2.n=7;break;case 6:logger.info("webrtc","Zoom is not supported or zoom capabilities unknown yet");case 7:return _context2.a(2)}}),_callee2)})));return function(_x3){return _ref2.apply(this,arguments)}}(),getWebRTCStats=function(){return new Promise((function(resolve,reject){var browser=browserDetails.browser;connection&&validBrowsers.includes(browser)?connection.getStats(null).then((function(stats){var statObject={};stats&&stats.forEach((function(report){report&&(void 0===statObject[report.type]&&(statObject[report.type]=[]),statObject[report.type].push(report))})),resolve(statObject)})).catch((function(reason){logger.error("webrtc",reason),reject(reason)})):reject(constants.ERROR_INFO.CAN_NOT_GET_STATS)}))},exports={state:function(){return connection.signalingState},createOffer:function(options){return new Promise((function(resolve,reject){var hasAudio=!0,hasVideo=!0;localVideo?(localVideo.srcObject.getAudioTracks()[0]||(hasAudio=!1),localVideo.srcObject.getVideoTracks()[0]||(hasVideo=!1,options.receiveVideo=!1)):"safari"!=browserDetails.browser||connection.getTransceivers().length||(options.receiveAudio&&connection.addTransceiver("audio",{direction:"recvonly"}),options.receiveVideo&&connection.addTransceiver("video",{direction:"recvonly"}));var constraints={offerToReceiveAudio:options.receiveAudio?1:0,offerToReceiveVideo:options.receiveVideo?1:0};connection.createOffer(constraints).then((function(offer){options.stereo&&(offer.sdp=offer.sdp.replace("minptime=10","minptime=10;stereo=1;sprop-stereo=1")),connection.setLocalDescription(offer).then((function(){var o={};o.sdp=util.stripCodecs(offer.sdp,options.stripCodecs),o.hasAudio=hasAudio,o.hasVideo=hasVideo,resolve(o)}))}))}))},createAnswer:function(options){return new Promise((function(resolve,reject){connection.createAnswer().then((function(answer){connection.setLocalDescription(answer).then((function(){resolve(util.stripCodecs(answer.sdp,options.stripCodecs))}))}))}))},setRemoteSdp:function(sdp){return logger.debug("webrtc","setRemoteSDP:"),logger.debug("webrtc",sdp),new Promise((function(resolve,reject){var sdpType;sdpType="have-local-offer"==connection.signalingState?"answer":"offer";var rtcSdp=new RTCSessionDescription({type:sdpType,sdp:sdp});connection.setRemoteDescription(rtcSdp).then((function(){browserDetails.browser,resolve()})).catch((function(error){reject(error)}))}))},changeAudioCodec:function(codec){return!1},close:function(cacheCamera){remoteVideo&&(removeVideoElement(remoteVideo),options.remoteVideo||(remoteVideo.id=remoteVideo.id+"-REMOTE_CACHED_VIDEO"),remoteVideo=null),localVideo&&!getCacheInstance(localDisplay||display)&&cacheCamera?(localVideo.id=localVideo.id+"-LOCAL_CACHED_VIDEO",unmuteAudio(),unmuteVideo(),localVideo=null):localVideo&&(localVideo.id=localVideo.id+"-LOCAL_CACHED_VIDEO",removeVideoElement(localVideo),localVideo=null),"closed"!==connection.signalingState&&connection.close(),delete connections[id]},setAudioOutputId:function(id){if(remoteVideo){if("edge"==browserDetails.browser){var srcObject=remoteVideo.srcObject;remoteVideo.srcObject=null;var res=remoteVideo.setSinkId(id);return remoteVideo.srcObject=srcObject,res}return remoteVideo.setSinkId(id)}},setVolume:function(volume){remoteVideo&&remoteVideo.srcObject&&remoteVideo.srcObject.getAudioTracks().length>0&&(remoteVideo.volume=volume/100)},unmuteRemoteAudio:function(){remoteVideo&&remoteVideo.srcObject&&remoteVideo.srcObject.getAudioTracks().length>0&&(remoteVideo.muted=!1)},muteRemoteAudio:function(){remoteVideo&&remoteVideo.srcObject&&remoteVideo.srcObject.getAudioTracks().length>0&&(remoteVideo.muted=!0)},isRemoteAudioMuted:function(){return!(remoteVideo&&remoteVideo.srcObject&&remoteVideo.srcObject.getAudioTracks().length>0)||remoteVideo.muted},setMicrophoneGain:function(volume){microphoneGain&&(microphoneGain.gain.value=volume/100)},getVolume:function(){return remoteVideo&&remoteVideo.srcObject&&remoteVideo.srcObject.getAudioTracks().length>0?100*remoteVideo.volume:-1},muteAudio:function(){localVideo&&localVideo.srcObject&&localVideo.srcObject.getAudioTracks().length>0&&(localVideo.srcObject.getAudioTracks()[0].enabled=!1)}};exports.unmuteAudio=unmuteAudio,exports.isAudioMuted=function(){return!(localVideo&&localVideo.srcObject&&localVideo.srcObject.getAudioTracks().length>0)||!localVideo.srcObject.getAudioTracks()[0].enabled},exports.muteVideo=function(){localVideo&&localVideo.srcObject&&localVideo.srcObject.getVideoTracks().length>0&&(localVideo.srcObject.getVideoTracks()[0].enabled=!1)},exports.unmuteVideo=unmuteVideo,exports.isVideoMuted=function(){return!(localVideo&&localVideo.srcObject&&localVideo.srcObject.getVideoTracks().length>0)||!localVideo.srcObject.getVideoTracks()[0].enabled},exports.getStats=getStat,exports.fullScreen=function(){var video=document.getElementById(id);if(video)if(document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.msFullscreenElement)document.exitFullscreen?document.exitFullscreen():document.msExitFullscreen?document.msExitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitExitFullscreen&&document.webkitExitFullscreen();else if(video.requestFullscreen){var result=video.requestFullscreen();util.isPromise(result)&&result.catch((function(e){logger.debug("webrtc",e)}))}else if(video.msRequestFullscreen)video.msRequestFullscreen();else if(video.mozRequestFullScreen)video.mozRequestFullScreen();else if(video.webkitRequestFullscreen)video.webkitRequestFullscreen();else if(video.webkitEnterFullscreen){video.webkitEnterFullscreen();var needRestart=!1;video.addEventListener("pause",(function(){needRestart&&(video.play(),needRestart=!1)})),video.addEventListener("webkitendfullscreen",(function(){video.play(),needRestart=!0}))}},exports.switchCam=function(deviceId){return new Promise((function(resolve,reject){localVideo&&localVideo.srcObject&&videoCams.length>1&&!customStream&&!screenShare?connection.getSenders().forEach((function(sender){if("audio"!==sender.track.kind){var cameraId;sender.track.stop(),"undefined"!=typeof deviceId?(videoCams.forEach((function(cam,index){deviceId===cam.id&&(switchCamIndex=index)})),cameraId=deviceId):(switchCamIndex=(switchCamIndex+1)%videoCams.length,cameraId=videoCams[switchCamIndex].id),cameraId||(logger.error("webrtc","Can't detect camera to switch to"),reject(constants.ERROR_INFO.CAN_NOT_SWITCH_CAM));var clonedConstraints=Object.assign({},constraints);clonedConstraints.video.deviceId={exact:cameraId},clonedConstraints.audio=!1,navigator.mediaDevices.getUserMedia(clonedConstraints).then((function(newStream){var newVideoTrack=newStream.getVideoTracks()[0];newVideoTrack.enabled=localVideo.srcObject.getVideoTracks()[0].enabled;var audioTrack=localVideo.srcObject.getAudioTracks()[0];sender.replaceTrack(newVideoTrack),localVideo.srcObject=newStream,0==localVideo.srcObject.getAudioTracks().length&&audioTrack&&localVideo.srcObject.addTrack(audioTrack),logger.info("webrtc","Switch camera to "+cameraId),resolve(cameraId)})).catch((function(reason){logger.error("webrtc",reason),reject(reason)}))}})):reject(constants.ERROR_INFO.CAN_NOT_SWITCH_CAM)}))},exports.switchMic=function(deviceId){return new Promise((function(resolve,reject){localVideo&&localVideo.srcObject&&mics.length>1&&!customStream?connection.getSenders().forEach((function(sender){if("video"!==sender.track.kind){switchMicCount=(switchMicCount+1)%mics.length,sender.track.stop(),microphoneGain&µphoneGain.release();var mic="undefined"!=typeof deviceId?deviceId:mics[switchMicCount].id,clonedConstraints=Object.assign({},constraints);clonedConstraints.audio.deviceId={exact:mic},clonedConstraints.video=!1,navigator.mediaDevices.getUserMedia(clonedConstraints).then((function(newStream){if(microphoneGain){var currentGain=microphoneGain.gain.value;(microphoneGain=createGainNode(newStream)).gain.value=currentGain}var newAudioTrack=newStream.getAudioTracks()[0];newAudioTrack.enabled=localVideo.srcObject.getAudioTracks()[0].enabled,currentAudioTrack=newAudioTrack;var videoTrack=localVideo.srcObject.getVideoTracks()[0];if(systemSoundTrack){var mixedTrack=mixAudioTracks(new MediaStream([newAudioTrack]),new MediaStream([systemSoundTrack]));mixedTrack.enabled=newAudioTrack.enabled,sender.replaceTrack(mixedTrack),localVideo.srcObject=new MediaStream([mixedTrack])}else sender.replaceTrack(newAudioTrack),localVideo.srcObject=newStream;videoTrack&&localVideo.srcObject.addTrack(videoTrack),logger.info("webrtc","Switch mic to "+mic),resolve(mic)})).catch((function(reason){logger.error("webrtc",reason),reject(reason)}))}})):reject(constants.ERROR_INFO.CAN_NOT_SWITCH_MIC)}))},exports.switchToScreen=function(source,woExtension){return new Promise((function(resolve,reject){if(!screenShare){var clonedConstraints={video:Object.assign({},constraints.video),audio:Object.assign({},constraints.audio)};if("firefox"===browserDetails.browser&&(clonedConstraints.video.mediaSource=source),woExtension)return void getScreenDeviceIdWoExtension(clonedConstraints).then((function(screenSharingConstraints){navigator.mediaDevices.getDisplayMedia(screenSharingConstraints).then((function(stream){processScreenStream(stream,resolve)})).catch(reject)}));getScreenDeviceId(clonedConstraints).then((function(screenSharingConstraints){clonedConstraints.sourceId=screenSharingConstraints.sourceId,screenSharingConstraints.audioMandatory?clonedConstraints.audio={mandatory:screenSharingConstraints.audioMandatory,optional:[]}:delete clonedConstraints.audio,"firefox"==browserDetails.browser?clonedConstraints.video=screenSharingConstraints:"chrome"==browserDetails.browser&&(delete clonedConstraints.video,clonedConstraints.video={mandatory:screenSharingConstraints.mandatory}),navigator.mediaDevices.getUserMedia(clonedConstraints).then((function(stream){processScreenStream(stream,resolve)})).catch((function(reason){logger.error(reason),reject(reason)}))})).catch((function(reason){logger.error(reason),reject(reason)}))}}))},exports.switchToCam=function(){screenShare&&connection.getSenders().forEach((function(sender){"audio"!==sender.track.kind&&(currentVideoTrack.enabled=sender.track.enabled,sender.track.stop(),localVideo.srcObject=new MediaStream([currentVideoTrack]),sender.replaceTrack(currentVideoTrack),currentAudioTrack&&connection.getSenders().forEach((function(sender){"video"!==sender.track.kind&&(systemSoundTrack&&(currentAudioTrack.enabled=sender.track.enabled,sender.track.stop(),systemSoundTrack.stop(),systemSoundTrack=null,sender.replaceTrack(currentAudioTrack)),localVideo.srcObject.addTrack(currentAudioTrack))})))})),logger.info("webrtc","Switch to cam"),screenShare=!1},exports.setPublishingBitrate=function(minBitrate,maxBitrate){updateVideoSettings({maxBitrate:maxBitrate})},exports.updateVideoSettings=updateVideoSettings,exports.updateVideoResolution=function(resolution){return new Promise((function(resolve,reject){connection&&localVideo&&localVideo.srcObject&&!customStream&&resolution?connection.getSenders().forEach((function(sender){if("audio"!==sender.track.kind){sender.track.stop();var clonedConstraints=Object.assign({},constraints);resolution.width&&(clonedConstraints.video.width={ideal:resolution.width}),resolution.height&&(clonedConstraints.video.height={ideal:resolution.height}),clonedConstraints.audio=!1,navigator.mediaDevices.getUserMedia(clonedConstraints).then((function(newStream){var newVideoTrack=newStream.getVideoTracks()[0];newVideoTrack.enabled=localVideo.srcObject.getVideoTracks()[0].enabled;var audioTrack=localVideo.srcObject.getAudioTracks()[0];sender.replaceTrack(newVideoTrack),localVideo.srcObject=newStream,0==localVideo.srcObject.getAudioTracks().length&&audioTrack&&localVideo.srcObject.addTrack(audioTrack),logger.info("webrtc","Set video constraints to "+JSON.stringify(clonedConstraints.video)),resolve(clonedConstraints.video)})).catch((function(reason){logger.error("webrtc",reason),reject(reason)}))}})):reject(constants.ERROR_INFO.CAN_NOT_SET_RESOLUTION)}))},exports.getZoomCapabilities=function(){if(localVideo&&localVideo.srcObject)if(constraints.video&&constraints.video.zoom){var track=_slicedToArray(localVideo.srcObject.getVideoTracks(),1)[0],capabilities=track.getCapabilities(),settings=track.getSettings();"zoom"in settings?zoom={min:capabilities.zoom.min,max:capabilities.zoom.max,step:capabilities.zoom.step,value:settings.zoom}:(logger.info("webrtc","Zoom is not supported by "+track.label),zoom=null)}else zoom=null;return zoom},exports.setZoom=setZoom,exports.getZoom=function(){return zoom?zoom.value:-1},exports.getWebRTCStats=getWebRTCStats,connections[id]=exports,resolve(exports)}))},getMediaAccess:function(constraints,display,disableConstraintsNormalization,useCanvas){return new Promise((function(resolve,reject){constraints||(constraints=defaultConstraints),disableConstraintsNormalization||(constraints=function(constraints){var customStream=constraints.customStream;if((constraints=JSON.parse(JSON.stringify(constraints))).customStream=customStream,constraints.video&&(!0===constraints.video&&(constraints.video={}),"object"===_typeof(constraints.video))){var width=constraints.video.width,height=constraints.video.height;if("safari"==browserDetails.browser?width&&height?"object"===_typeof(width)&&"object"===_typeof(height)||(constraints.video.width={min:width,max:width},constraints.video.height={min:height,max:height}):(constraints.video.width={min:320,max:640},constraints.video.height={min:180,max:360}):(isNaN(width)||0===width||isNaN(height)||0===height)&&(constraints.video.width=320,constraints.video.height=240),"chrome"===browserDetails.browser&&browserDetails.version>=134);else{var frameRate=constraints.video.frameRate&&0!=constraints.video.frameRate?constraints.video.frameRate:30;constraints.video.frameRate={ideal:frameRate}}}constraints.audio&&constraints.audio.stereo&&(constraints.audio.echoCancellation=!1,constraints.audio.googEchoCancellation=!1);return constraints}(constraints));var cacheInstance=getCacheInstance(display);if(cacheInstance&&cacheInstance.srcObject&&JSON.stringify(display.mediaTrackConstraints)==JSON.stringify(constraints)&&!constraints.customStream)resolve(display);else if(display.mediaTrackConstraints=constraints,releaseMedia(display),constraints.video||constraints.audio||constraints.customStream)if(constraints.video&&constraints.video.type&&"screen"==constraints.video.type){if(delete constraints.video.type,screenCaptureSupportedBrowsers()&&constraints.video.withoutExtension)return void getScreenDeviceIdWoExtension(constraints).then((function(screenSharingConstraints){!function(constraints,requestAudioConstraints){navigator.mediaDevices.getDisplayMedia(constraints).then((function(stream){loadVideo(display,stream,!0,requestAudioConstraints,resolve,constraints)})).catch(reject)}(screenSharingConstraints,constraints.audio)}));var requestAudioConstraints=null;getScreenDeviceId(constraints).then((function(screenSharingConstraints){for(var prop in constraints.sourceId=screenSharingConstraints.sourceId,requestAudioConstraints=constraints.audio,screenSharingConstraints.audioMandatory?constraints.audio={mandatory:screenSharingConstraints.audioMandatory,optional:[]}:window.chrome&&(constraints.audio=!1),delete screenSharingConstraints.audioMandatory,delete screenSharingConstraints.sourceId,screenSharingConstraints)screenSharingConstraints.hasOwnProperty(prop)&&(constraints.video[prop]=screenSharingConstraints[prop]);"chrome"==browserDetails.browser&&(delete constraints.video.frameRate,delete constraints.video.height,delete constraints.video.width,delete constraints.systemSound),getAccess(constraints,!0,requestAudioConstraints)}),reject)}else getAccess(constraints);else resolve(display);function getAccess(constraints,screenShare,requestAudioConstraints){if(logger.info("webrtc",constraints),constraints.customStream)if(constraints.audio||constraints.video){var normalizedConstraints={audio:!!constraints.audio&&constraints.audio,video:!!constraints.video&&constraints.video};navigator.getUserMedia(normalizedConstraints,(function(stream){stream.getTracks().forEach((function(track){constraints.customStream.addTrack(track)})),loadVideo(display,constraints.customStream,screenShare,requestAudioConstraints,resolve,constraints)}),reject)}else loadVideo(display,constraints.customStream,screenShare,requestAudioConstraints,resolve,constraints);else listDevices(!1).then((function(devices){devices.video.forEach((function(device){videoCams.find((function(cam){return device.id===cam.id}))||videoCams.push(device)})),devices.audio.forEach((function(device){mics.find((function(mic){return device.id===mic.id}))||mics.push(device)})),navigator.getUserMedia(constraints,(function(stream){loadVideo(display,stream,screenShare,requestAudioConstraints,resolve,constraints,useCanvas)}),reject)}),reject)}}))},releaseMedia:releaseMedia,listDevices:listDevices,getMobileDevices:getMobileDevices,playFirstSound:function(){if(audioContext){for(var buffer=audioContext.createBuffer(1,441,44100),output=buffer.getChannelData(0),i=0;i<output.length;i++)output[i]=0;var source=audioContext.createBufferSource();return source.buffer=buffer,source.connect(audioContext.destination),source.start?source.start(0):source.play?source.play(0):source.noteOn&&source.noteOn(0),!0}return!1},playFirstVideo:function(display,isLocal,src){var useControls=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return new Promise((function(resolve,reject){if(!getCacheInstance(display)){var video=createVideoElement(useControls);if(video.muted=!0,video.id=uuid_v1()+(isLocal?"-LOCAL_CACHED_VIDEO":"-REMOTE_CACHED_VIDEO"),src)return video.src=src,void video.play().then((function(){display.appendChild(video),video.removeAttribute("src"),resolve()})).catch((function(){logger.info("webrtc","Autoplay detected! Trying to play a video with a muted sound..."),video.muted=!0,video.play().then((function(){display.appendChild(video),video.removeAttribute("src"),resolve()})),video.onsuspend=function(event){reject()}}))}resolve()}))},available:function(){return"getUserMedia"in navigator&&"RTCPeerConnection"in window},configure:function(configuration){extensionId=configuration.extensionId,defaultConstraints=configuration.constraints,audioContext=configuration.audioContext,logger=configuration.logger,createMicGainNode="undefined"==typeof configuration.createMicGainNode||configuration.createMicGainNode,logger.info("webrtc","Initialized")},videoCams:videoCams,mics:mics,getAudioSourceDevice:function(){return audioSourceDevice},getCacheInstance:getCacheInstance,getVideoElement:function getVideoElement(display){if(display){var _step,_iterator=function(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=_unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var _n=0,F=function(){};return{s:F,n:function(){return _n>=r.length?{done:!0}:{done:!1,value:r[_n++]}},e:function(r){throw r},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,u=!1;return{s:function(){t=t.call(r)},n:function(){var r=t.next();return a=r.done,r},e:function(r){u=!0,o=r},f:function(){try{a||null==t.return||t.return()}finally{if(u)throw o}}}}(display.children);try{for(_iterator.s();!(_step=_iterator.n()).done;){var child=_step.value;if("video"===child.tagName.toLowerCase())return child;var grandchild=getVideoElement(child);if(grandchild)return grandchild}}catch(err){_iterator.e(err)}finally{_iterator.f()}}return null}}},{"./constants":39,"./util":42,uuid:8,"webrtc-adapter":23}]},{},[40])(40)}));
|
|
12
|
+
var KalmanFilter=function(){function KalmanFilter(){var _ref=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},_ref$R=_ref.R,R=void 0===_ref$R?1:_ref$R,_ref$Q=_ref.Q,Q=void 0===_ref$Q?1:_ref$Q,_ref$A=_ref.A,A=void 0===_ref$A?1:_ref$A,_ref$B=_ref.B,B=void 0===_ref$B?0:_ref$B,_ref$C=_ref.C,C=void 0===_ref$C?1:_ref$C;_classCallCheck(this,KalmanFilter),this.R=R,this.Q=Q,this.A=A,this.C=C,this.B=B,this.cov=NaN,this.x=NaN}var Constructor,protoProps,staticProps;return Constructor=KalmanFilter,(protoProps=[{key:"filter",value:function(z){var u=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(isNaN(this.x))this.x=1/this.C*z,this.cov=1/this.C*this.Q*(1/this.C);else{var predX=this.predict(u),predCov=this.uncertainty(),K=predCov*this.C*(1/(this.C*predCov*this.C+this.Q));this.x=predX+K*(z-this.C*predX),this.cov=predCov-K*this.C*predCov}return this.x}},{key:"predict",value:function(){var u=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return this.A*this.x+this.B*u}},{key:"uncertainty",value:function(){return this.A*this.cov*this.A+this.R}},{key:"lastMeasurement",value:function(){return this.x}},{key:"setMeasurementNoise",value:function(noise){this.Q=noise}},{key:"setProcessNoise",value:function(noise){this.R=noise}}])&&_defineProperties(Constructor.prototype,protoProps),staticProps&&_defineProperties(Constructor,staticProps),KalmanFilter}();module.exports=KalmanFilter},{}],19:[function(require,module,exports){"use strict";var _require=require("./lib/deflate"),Deflate=_require.Deflate,deflate=_require.deflate,deflateRaw=_require.deflateRaw,gzip=_require.gzip,_require2=require("./lib/inflate"),Inflate=_require2.Inflate,inflate=_require2.inflate,inflateRaw=_require2.inflateRaw,ungzip=_require2.ungzip,constants=require("./lib/zlib/constants");module.exports.Deflate=Deflate,module.exports.deflate=deflate,module.exports.deflateRaw=deflateRaw,module.exports.gzip=gzip,module.exports.Inflate=Inflate,module.exports.inflate=inflate,module.exports.inflateRaw=inflateRaw,module.exports.ungzip=ungzip,module.exports.constants=constants},{"./lib/deflate":20,"./lib/inflate":21,"./lib/zlib/constants":25}],20:[function(require,module,exports){"use strict";var zlib_deflate=require("./zlib/deflate"),utils=require("./utils/common"),strings=require("./utils/strings"),msg=require("./zlib/messages"),ZStream=require("./zlib/zstream"),toString=Object.prototype.toString,_require=require("./zlib/constants"),Z_NO_FLUSH=_require.Z_NO_FLUSH,Z_SYNC_FLUSH=_require.Z_SYNC_FLUSH,Z_FULL_FLUSH=_require.Z_FULL_FLUSH,Z_FINISH=_require.Z_FINISH,Z_OK=_require.Z_OK,Z_STREAM_END=_require.Z_STREAM_END,Z_DEFAULT_COMPRESSION=_require.Z_DEFAULT_COMPRESSION,Z_DEFAULT_STRATEGY=_require.Z_DEFAULT_STRATEGY,Z_DEFLATED=_require.Z_DEFLATED;function Deflate(options){this.options=utils.assign({level:Z_DEFAULT_COMPRESSION,method:Z_DEFLATED,chunkSize:16384,windowBits:15,memLevel:8,strategy:Z_DEFAULT_STRATEGY},options||{});var opt=this.options;opt.raw&&opt.windowBits>0?opt.windowBits=-opt.windowBits:opt.gzip&&opt.windowBits>0&&opt.windowBits<16&&(opt.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new ZStream,this.strm.avail_out=0;var status=zlib_deflate.deflateInit2(this.strm,opt.level,opt.method,opt.windowBits,opt.memLevel,opt.strategy);if(status!==Z_OK)throw new Error(msg[status]);if(opt.header&&zlib_deflate.deflateSetHeader(this.strm,opt.header),opt.dictionary){var dict;if(dict="string"==typeof opt.dictionary?strings.string2buf(opt.dictionary):"[object ArrayBuffer]"===toString.call(opt.dictionary)?new Uint8Array(opt.dictionary):opt.dictionary,(status=zlib_deflate.deflateSetDictionary(this.strm,dict))!==Z_OK)throw new Error(msg[status]);this._dict_set=!0}}function deflate(input,options){var deflator=new Deflate(options);if(deflator.push(input,!0),deflator.err)throw deflator.msg||msg[deflator.err];return deflator.result}Deflate.prototype.push=function(data,flush_mode){var status,_flush_mode,strm=this.strm,chunkSize=this.options.chunkSize;if(this.ended)return!1;for(_flush_mode=flush_mode===~~flush_mode?flush_mode:!0===flush_mode?Z_FINISH:Z_NO_FLUSH,"string"==typeof data?strm.input=strings.string2buf(data):"[object ArrayBuffer]"===toString.call(data)?strm.input=new Uint8Array(data):strm.input=data,strm.next_in=0,strm.avail_in=strm.input.length;;)if(0===strm.avail_out&&(strm.output=new Uint8Array(chunkSize),strm.next_out=0,strm.avail_out=chunkSize),(_flush_mode===Z_SYNC_FLUSH||_flush_mode===Z_FULL_FLUSH)&&strm.avail_out<=6)this.onData(strm.output.subarray(0,strm.next_out)),strm.avail_out=0;else{if((status=zlib_deflate.deflate(strm,_flush_mode))===Z_STREAM_END)return strm.next_out>0&&this.onData(strm.output.subarray(0,strm.next_out)),status=zlib_deflate.deflateEnd(this.strm),this.onEnd(status),this.ended=!0,status===Z_OK;if(0!==strm.avail_out){if(_flush_mode>0&&strm.next_out>0)this.onData(strm.output.subarray(0,strm.next_out)),strm.avail_out=0;else if(0===strm.avail_in)break}else this.onData(strm.output)}return!0},Deflate.prototype.onData=function(chunk){this.chunks.push(chunk)},Deflate.prototype.onEnd=function(status){status===Z_OK&&(this.result=utils.flattenChunks(this.chunks)),this.chunks=[],this.err=status,this.msg=this.strm.msg},module.exports.Deflate=Deflate,module.exports.deflate=deflate,module.exports.deflateRaw=function(input,options){return(options=options||{}).raw=!0,deflate(input,options)},module.exports.gzip=function(input,options){return(options=options||{}).gzip=!0,deflate(input,options)},module.exports.constants=require("./zlib/constants")},{"./utils/common":22,"./utils/strings":23,"./zlib/constants":25,"./zlib/deflate":27,"./zlib/messages":32,"./zlib/zstream":34}],21:[function(require,module,exports){"use strict";var zlib_inflate=require("./zlib/inflate"),utils=require("./utils/common"),strings=require("./utils/strings"),msg=require("./zlib/messages"),ZStream=require("./zlib/zstream"),GZheader=require("./zlib/gzheader"),toString=Object.prototype.toString,_require=require("./zlib/constants"),Z_NO_FLUSH=_require.Z_NO_FLUSH,Z_FINISH=_require.Z_FINISH,Z_OK=_require.Z_OK,Z_STREAM_END=_require.Z_STREAM_END,Z_NEED_DICT=_require.Z_NEED_DICT,Z_STREAM_ERROR=_require.Z_STREAM_ERROR,Z_DATA_ERROR=_require.Z_DATA_ERROR,Z_MEM_ERROR=_require.Z_MEM_ERROR;function Inflate(options){this.options=utils.assign({chunkSize:65536,windowBits:15,to:""},options||{});var opt=this.options;opt.raw&&opt.windowBits>=0&&opt.windowBits<16&&(opt.windowBits=-opt.windowBits,0===opt.windowBits&&(opt.windowBits=-15)),!(opt.windowBits>=0&&opt.windowBits<16)||options&&options.windowBits||(opt.windowBits+=32),opt.windowBits>15&&opt.windowBits<48&&0==(15&opt.windowBits)&&(opt.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new ZStream,this.strm.avail_out=0;var status=zlib_inflate.inflateInit2(this.strm,opt.windowBits);if(status!==Z_OK)throw new Error(msg[status]);if(this.header=new GZheader,zlib_inflate.inflateGetHeader(this.strm,this.header),opt.dictionary&&("string"==typeof opt.dictionary?opt.dictionary=strings.string2buf(opt.dictionary):"[object ArrayBuffer]"===toString.call(opt.dictionary)&&(opt.dictionary=new Uint8Array(opt.dictionary)),opt.raw&&(status=zlib_inflate.inflateSetDictionary(this.strm,opt.dictionary))!==Z_OK))throw new Error(msg[status])}function inflate(input,options){var inflator=new Inflate(options);if(inflator.push(input),inflator.err)throw inflator.msg||msg[inflator.err];return inflator.result}Inflate.prototype.push=function(data,flush_mode){var status,_flush_mode,last_avail_out,strm=this.strm,chunkSize=this.options.chunkSize,dictionary=this.options.dictionary;if(this.ended)return!1;for(_flush_mode=flush_mode===~~flush_mode?flush_mode:!0===flush_mode?Z_FINISH:Z_NO_FLUSH,"[object ArrayBuffer]"===toString.call(data)?strm.input=new Uint8Array(data):strm.input=data,strm.next_in=0,strm.avail_in=strm.input.length;;){for(0===strm.avail_out&&(strm.output=new Uint8Array(chunkSize),strm.next_out=0,strm.avail_out=chunkSize),(status=zlib_inflate.inflate(strm,_flush_mode))===Z_NEED_DICT&&dictionary&&((status=zlib_inflate.inflateSetDictionary(strm,dictionary))===Z_OK?status=zlib_inflate.inflate(strm,_flush_mode):status===Z_DATA_ERROR&&(status=Z_NEED_DICT));strm.avail_in>0&&status===Z_STREAM_END&&strm.state.wrap>0&&0!==data[strm.next_in];)zlib_inflate.inflateReset(strm),status=zlib_inflate.inflate(strm,_flush_mode);switch(status){case Z_STREAM_ERROR:case Z_DATA_ERROR:case Z_NEED_DICT:case Z_MEM_ERROR:return this.onEnd(status),this.ended=!0,!1}if(last_avail_out=strm.avail_out,strm.next_out&&(0===strm.avail_out||status===Z_STREAM_END))if("string"===this.options.to){var next_out_utf8=strings.utf8border(strm.output,strm.next_out),tail=strm.next_out-next_out_utf8,utf8str=strings.buf2string(strm.output,next_out_utf8);strm.next_out=tail,strm.avail_out=chunkSize-tail,tail&&strm.output.set(strm.output.subarray(next_out_utf8,next_out_utf8+tail),0),this.onData(utf8str)}else this.onData(strm.output.length===strm.next_out?strm.output:strm.output.subarray(0,strm.next_out));if(status!==Z_OK||0!==last_avail_out){if(status===Z_STREAM_END)return status=zlib_inflate.inflateEnd(this.strm),this.onEnd(status),this.ended=!0,!0;if(0===strm.avail_in)break}}return!0},Inflate.prototype.onData=function(chunk){this.chunks.push(chunk)},Inflate.prototype.onEnd=function(status){status===Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=utils.flattenChunks(this.chunks)),this.chunks=[],this.err=status,this.msg=this.strm.msg},module.exports.Inflate=Inflate,module.exports.inflate=inflate,module.exports.inflateRaw=function(input,options){return(options=options||{}).raw=!0,inflate(input,options)},module.exports.ungzip=inflate,module.exports.constants=require("./zlib/constants")},{"./utils/common":22,"./utils/strings":23,"./zlib/constants":25,"./zlib/gzheader":28,"./zlib/inflate":30,"./zlib/messages":32,"./zlib/zstream":34}],22:[function(require,module,exports){"use strict";function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}var _has=function(obj,key){return Object.prototype.hasOwnProperty.call(obj,key)};module.exports.assign=function(obj){for(var sources=Array.prototype.slice.call(arguments,1);sources.length;){var source=sources.shift();if(source){if("object"!==_typeof(source))throw new TypeError(source+"must be non-object");for(var p in source)_has(source,p)&&(obj[p]=source[p])}}return obj},module.exports.flattenChunks=function(chunks){for(var len=0,i=0,l=chunks.length;i<l;i++)len+=chunks[i].length;for(var result=new Uint8Array(len),_i=0,pos=0,_l=chunks.length;_i<_l;_i++){var chunk=chunks[_i];result.set(chunk,pos),pos+=chunk.length}return result}},{}],23:[function(require,module,exports){"use strict";var STR_APPLY_UIA_OK=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(__){STR_APPLY_UIA_OK=!1}for(var _utf8len=new Uint8Array(256),q=0;q<256;q++)_utf8len[q]=q>=252?6:q>=248?5:q>=240?4:q>=224?3:q>=192?2:1;_utf8len[254]=_utf8len[254]=1,module.exports.string2buf=function(str){if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(str);var buf,c,c2,m_pos,i,str_len=str.length,buf_len=0;for(m_pos=0;m_pos<str_len;m_pos++)55296==(64512&(c=str.charCodeAt(m_pos)))&&m_pos+1<str_len&&56320==(64512&(c2=str.charCodeAt(m_pos+1)))&&(c=65536+(c-55296<<10)+(c2-56320),m_pos++),buf_len+=c<128?1:c<2048?2:c<65536?3:4;for(buf=new Uint8Array(buf_len),i=0,m_pos=0;i<buf_len;m_pos++)55296==(64512&(c=str.charCodeAt(m_pos)))&&m_pos+1<str_len&&56320==(64512&(c2=str.charCodeAt(m_pos+1)))&&(c=65536+(c-55296<<10)+(c2-56320),m_pos++),c<128?buf[i++]=c:c<2048?(buf[i++]=192|c>>>6,buf[i++]=128|63&c):c<65536?(buf[i++]=224|c>>>12,buf[i++]=128|c>>>6&63,buf[i++]=128|63&c):(buf[i++]=240|c>>>18,buf[i++]=128|c>>>12&63,buf[i++]=128|c>>>6&63,buf[i++]=128|63&c);return buf};module.exports.buf2string=function(buf,max){var i,out,len=max||buf.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(buf.subarray(0,max));var utf16buf=new Array(2*len);for(out=0,i=0;i<len;){var c=buf[i++];if(c<128)utf16buf[out++]=c;else{var c_len=_utf8len[c];if(c_len>4)utf16buf[out++]=65533,i+=c_len-1;else{for(c&=2===c_len?31:3===c_len?15:7;c_len>1&&i<len;)c=c<<6|63&buf[i++],c_len--;c_len>1?utf16buf[out++]=65533:c<65536?utf16buf[out++]=c:(c-=65536,utf16buf[out++]=55296|c>>10&1023,utf16buf[out++]=56320|1023&c)}}}return function(buf,len){if(len<65534&&buf.subarray&&STR_APPLY_UIA_OK)return String.fromCharCode.apply(null,buf.length===len?buf:buf.subarray(0,len));for(var result="",i=0;i<len;i++)result+=String.fromCharCode(buf[i]);return result}(utf16buf,out)},module.exports.utf8border=function(buf,max){(max=max||buf.length)>buf.length&&(max=buf.length);for(var pos=max-1;pos>=0&&128==(192&buf[pos]);)pos--;return pos<0||0===pos?max:pos+_utf8len[buf[pos]]>max?pos:max}},{}],24:[function(require,module,exports){"use strict";module.exports=function(adler,buf,len,pos){for(var s1=65535&adler|0,s2=adler>>>16&65535|0,n=0;0!==len;){len-=n=len>2e3?2e3:len;do{s2=s2+(s1=s1+buf[pos++]|0)|0}while(--n);s1%=65521,s2%=65521}return s1|s2<<16|0}},{}],25:[function(require,module,exports){"use strict";module.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],26:[function(require,module,exports){"use strict";var crcTable=new Uint32Array(function(){for(var c,table=[],n=0;n<256;n++){c=n;for(var k=0;k<8;k++)c=1&c?3988292384^c>>>1:c>>>1;table[n]=c}return table}());module.exports=function(crc,buf,len,pos){var t=crcTable,end=pos+len;crc^=-1;for(var i=pos;i<end;i++)crc=crc>>>8^t[255&(crc^buf[i])];return-1^crc}},{}],27:[function(require,module,exports){"use strict";var _require=require("./trees"),_tr_init=_require._tr_init,_tr_stored_block=_require._tr_stored_block,_tr_flush_block=_require._tr_flush_block,_tr_tally=_require._tr_tally,_tr_align=_require._tr_align,adler32=require("./adler32"),crc32=require("./crc32"),msg=require("./messages"),_require2=require("./constants"),Z_NO_FLUSH=_require2.Z_NO_FLUSH,Z_PARTIAL_FLUSH=_require2.Z_PARTIAL_FLUSH,Z_FULL_FLUSH=_require2.Z_FULL_FLUSH,Z_FINISH=_require2.Z_FINISH,Z_BLOCK=_require2.Z_BLOCK,Z_OK=_require2.Z_OK,Z_STREAM_END=_require2.Z_STREAM_END,Z_STREAM_ERROR=_require2.Z_STREAM_ERROR,Z_DATA_ERROR=_require2.Z_DATA_ERROR,Z_BUF_ERROR=_require2.Z_BUF_ERROR,Z_DEFAULT_COMPRESSION=_require2.Z_DEFAULT_COMPRESSION,Z_FILTERED=_require2.Z_FILTERED,Z_HUFFMAN_ONLY=_require2.Z_HUFFMAN_ONLY,Z_RLE=_require2.Z_RLE,Z_FIXED=_require2.Z_FIXED,Z_DEFAULT_STRATEGY=_require2.Z_DEFAULT_STRATEGY,Z_UNKNOWN=_require2.Z_UNKNOWN,Z_DEFLATED=_require2.Z_DEFLATED,err=function(strm,errorCode){return strm.msg=msg[errorCode],errorCode},rank=function(f){return 2*f-(f>4?9:0)},zero=function(buf){for(var len=buf.length;--len>=0;)buf[len]=0},slide_hash=function(s){var n,m,p,wsize=s.w_size;p=n=s.hash_size;do{m=s.head[--p],s.head[p]=m>=wsize?m-wsize:0}while(--n);p=n=wsize;do{m=s.prev[--p],s.prev[p]=m>=wsize?m-wsize:0}while(--n)},HASH=function(s,prev,data){return(prev<<s.hash_shift^data)&s.hash_mask},flush_pending=function(strm){var s=strm.state,len=s.pending;len>strm.avail_out&&(len=strm.avail_out),0!==len&&(strm.output.set(s.pending_buf.subarray(s.pending_out,s.pending_out+len),strm.next_out),strm.next_out+=len,s.pending_out+=len,strm.total_out+=len,strm.avail_out-=len,s.pending-=len,0===s.pending&&(s.pending_out=0))},flush_block_only=function(s,last){_tr_flush_block(s,s.block_start>=0?s.block_start:-1,s.strstart-s.block_start,last),s.block_start=s.strstart,flush_pending(s.strm)},put_byte=function(s,b){s.pending_buf[s.pending++]=b},putShortMSB=function(s,b){s.pending_buf[s.pending++]=b>>>8&255,s.pending_buf[s.pending++]=255&b},read_buf=function(strm,buf,start,size){var len=strm.avail_in;return len>size&&(len=size),0===len?0:(strm.avail_in-=len,buf.set(strm.input.subarray(strm.next_in,strm.next_in+len),start),1===strm.state.wrap?strm.adler=adler32(strm.adler,buf,len,start):2===strm.state.wrap&&(strm.adler=crc32(strm.adler,buf,len,start)),strm.next_in+=len,strm.total_in+=len,len)},longest_match=function(s,cur_match){var match,len,chain_length=s.max_chain_length,scan=s.strstart,best_len=s.prev_length,nice_match=s.nice_match,limit=s.strstart>s.w_size-262?s.strstart-(s.w_size-262):0,_win=s.window,wmask=s.w_mask,prev=s.prev,strend=s.strstart+258,scan_end1=_win[scan+best_len-1],scan_end=_win[scan+best_len];s.prev_length>=s.good_match&&(chain_length>>=2),nice_match>s.lookahead&&(nice_match=s.lookahead);do{if(_win[(match=cur_match)+best_len]===scan_end&&_win[match+best_len-1]===scan_end1&&_win[match]===_win[scan]&&_win[++match]===_win[scan+1]){scan+=2,match++;do{}while(_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&scan<strend);if(len=258-(strend-scan),scan=strend-258,len>best_len){if(s.match_start=cur_match,best_len=len,len>=nice_match)break;scan_end1=_win[scan+best_len-1],scan_end=_win[scan+best_len]}}}while((cur_match=prev[cur_match&wmask])>limit&&0!=--chain_length);return best_len<=s.lookahead?best_len:s.lookahead},fill_window=function(s){var n,more,str,_w_size=s.w_size;do{if(more=s.window_size-s.lookahead-s.strstart,s.strstart>=_w_size+(_w_size-262)&&(s.window.set(s.window.subarray(_w_size,_w_size+_w_size-more),0),s.match_start-=_w_size,s.strstart-=_w_size,s.block_start-=_w_size,s.insert>s.strstart&&(s.insert=s.strstart),slide_hash(s),more+=_w_size),0===s.strm.avail_in)break;if(n=read_buf(s.strm,s.window,s.strstart+s.lookahead,more),s.lookahead+=n,s.lookahead+s.insert>=3)for(str=s.strstart-s.insert,s.ins_h=s.window[str],s.ins_h=HASH(s,s.ins_h,s.window[str+1]);s.insert&&(s.ins_h=HASH(s,s.ins_h,s.window[str+3-1]),s.prev[str&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=str,str++,s.insert--,!(s.lookahead+s.insert<3)););}while(s.lookahead<262&&0!==s.strm.avail_in)},deflate_stored=function(s,flush){var len,left,have,min_block=s.pending_buf_size-5>s.w_size?s.w_size:s.pending_buf_size-5,last=0,used=s.strm.avail_in;do{if(len=65535,have=s.bi_valid+42>>3,s.strm.avail_out<have)break;if(have=s.strm.avail_out-have,len>(left=s.strstart-s.block_start)+s.strm.avail_in&&(len=left+s.strm.avail_in),len>have&&(len=have),len<min_block&&(0===len&&flush!==Z_FINISH||flush===Z_NO_FLUSH||len!==left+s.strm.avail_in))break;last=flush===Z_FINISH&&len===left+s.strm.avail_in?1:0,_tr_stored_block(s,0,0,last),s.pending_buf[s.pending-4]=len,s.pending_buf[s.pending-3]=len>>8,s.pending_buf[s.pending-2]=~len,s.pending_buf[s.pending-1]=~len>>8,flush_pending(s.strm),left&&(left>len&&(left=len),s.strm.output.set(s.window.subarray(s.block_start,s.block_start+left),s.strm.next_out),s.strm.next_out+=left,s.strm.avail_out-=left,s.strm.total_out+=left,s.block_start+=left,len-=left),len&&(read_buf(s.strm,s.strm.output,s.strm.next_out,len),s.strm.next_out+=len,s.strm.avail_out-=len,s.strm.total_out+=len)}while(0===last);return(used-=s.strm.avail_in)&&(used>=s.w_size?(s.matches=2,s.window.set(s.strm.input.subarray(s.strm.next_in-s.w_size,s.strm.next_in),0),s.strstart=s.w_size,s.insert=s.strstart):(s.window_size-s.strstart<=used&&(s.strstart-=s.w_size,s.window.set(s.window.subarray(s.w_size,s.w_size+s.strstart),0),s.matches<2&&s.matches++,s.insert>s.strstart&&(s.insert=s.strstart)),s.window.set(s.strm.input.subarray(s.strm.next_in-used,s.strm.next_in),s.strstart),s.strstart+=used,s.insert+=used>s.w_size-s.insert?s.w_size-s.insert:used),s.block_start=s.strstart),s.high_water<s.strstart&&(s.high_water=s.strstart),last?4:flush!==Z_NO_FLUSH&&flush!==Z_FINISH&&0===s.strm.avail_in&&s.strstart===s.block_start?2:(have=s.window_size-s.strstart,s.strm.avail_in>have&&s.block_start>=s.w_size&&(s.block_start-=s.w_size,s.strstart-=s.w_size,s.window.set(s.window.subarray(s.w_size,s.w_size+s.strstart),0),s.matches<2&&s.matches++,have+=s.w_size,s.insert>s.strstart&&(s.insert=s.strstart)),have>s.strm.avail_in&&(have=s.strm.avail_in),have&&(read_buf(s.strm,s.window,s.strstart,have),s.strstart+=have,s.insert+=have>s.w_size-s.insert?s.w_size-s.insert:have),s.high_water<s.strstart&&(s.high_water=s.strstart),have=s.bi_valid+42>>3,min_block=(have=s.pending_buf_size-have>65535?65535:s.pending_buf_size-have)>s.w_size?s.w_size:have,((left=s.strstart-s.block_start)>=min_block||(left||flush===Z_FINISH)&&flush!==Z_NO_FLUSH&&0===s.strm.avail_in&&left<=have)&&(len=left>have?have:left,last=flush===Z_FINISH&&0===s.strm.avail_in&&len===left?1:0,_tr_stored_block(s,s.block_start,len,last),s.block_start+=len,flush_pending(s.strm)),last?3:1)},deflate_fast=function(s,flush){for(var hash_head,bflush;;){if(s.lookahead<262){if(fill_window(s),s.lookahead<262&&flush===Z_NO_FLUSH)return 1;if(0===s.lookahead)break}if(hash_head=0,s.lookahead>=3&&(s.ins_h=HASH(s,s.ins_h,s.window[s.strstart+3-1]),hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=s.strstart),0!==hash_head&&s.strstart-hash_head<=s.w_size-262&&(s.match_length=longest_match(s,hash_head)),s.match_length>=3)if(bflush=_tr_tally(s,s.strstart-s.match_start,s.match_length-3),s.lookahead-=s.match_length,s.match_length<=s.max_lazy_match&&s.lookahead>=3){s.match_length--;do{s.strstart++,s.ins_h=HASH(s,s.ins_h,s.window[s.strstart+3-1]),hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=s.strstart}while(0!=--s.match_length);s.strstart++}else s.strstart+=s.match_length,s.match_length=0,s.ins_h=s.window[s.strstart],s.ins_h=HASH(s,s.ins_h,s.window[s.strstart+1]);else bflush=_tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++;if(bflush&&(flush_block_only(s,!1),0===s.strm.avail_out))return 1}return s.insert=s.strstart<2?s.strstart:2,flush===Z_FINISH?(flush_block_only(s,!0),0===s.strm.avail_out?3:4):s.sym_next&&(flush_block_only(s,!1),0===s.strm.avail_out)?1:2},deflate_slow=function(s,flush){for(var hash_head,bflush,max_insert;;){if(s.lookahead<262){if(fill_window(s),s.lookahead<262&&flush===Z_NO_FLUSH)return 1;if(0===s.lookahead)break}if(hash_head=0,s.lookahead>=3&&(s.ins_h=HASH(s,s.ins_h,s.window[s.strstart+3-1]),hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=s.strstart),s.prev_length=s.match_length,s.prev_match=s.match_start,s.match_length=2,0!==hash_head&&s.prev_length<s.max_lazy_match&&s.strstart-hash_head<=s.w_size-262&&(s.match_length=longest_match(s,hash_head),s.match_length<=5&&(s.strategy===Z_FILTERED||3===s.match_length&&s.strstart-s.match_start>4096)&&(s.match_length=2)),s.prev_length>=3&&s.match_length<=s.prev_length){max_insert=s.strstart+s.lookahead-3,bflush=_tr_tally(s,s.strstart-1-s.prev_match,s.prev_length-3),s.lookahead-=s.prev_length-1,s.prev_length-=2;do{++s.strstart<=max_insert&&(s.ins_h=HASH(s,s.ins_h,s.window[s.strstart+3-1]),hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=s.strstart)}while(0!=--s.prev_length);if(s.match_available=0,s.match_length=2,s.strstart++,bflush&&(flush_block_only(s,!1),0===s.strm.avail_out))return 1}else if(s.match_available){if((bflush=_tr_tally(s,0,s.window[s.strstart-1]))&&flush_block_only(s,!1),s.strstart++,s.lookahead--,0===s.strm.avail_out)return 1}else s.match_available=1,s.strstart++,s.lookahead--}return s.match_available&&(bflush=_tr_tally(s,0,s.window[s.strstart-1]),s.match_available=0),s.insert=s.strstart<2?s.strstart:2,flush===Z_FINISH?(flush_block_only(s,!0),0===s.strm.avail_out?3:4):s.sym_next&&(flush_block_only(s,!1),0===s.strm.avail_out)?1:2};function Config(good_length,max_lazy,nice_length,max_chain,func){this.good_length=good_length,this.max_lazy=max_lazy,this.nice_length=nice_length,this.max_chain=max_chain,this.func=func}var configuration_table=[new Config(0,0,0,0,deflate_stored),new Config(4,4,8,4,deflate_fast),new Config(4,5,16,8,deflate_fast),new Config(4,6,32,32,deflate_fast),new Config(4,4,16,16,deflate_slow),new Config(8,16,32,32,deflate_slow),new Config(8,16,128,128,deflate_slow),new Config(8,32,128,256,deflate_slow),new Config(32,128,258,1024,deflate_slow),new Config(32,258,258,4096,deflate_slow)];function DeflateState(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Z_DEFLATED,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),zero(this.dyn_ltree),zero(this.dyn_dtree),zero(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),zero(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),zero(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}var deflateStateCheck=function(strm){if(!strm)return 1;var s=strm.state;return!s||s.strm!==strm||42!==s.status&&57!==s.status&&69!==s.status&&73!==s.status&&91!==s.status&&103!==s.status&&113!==s.status&&666!==s.status?1:0},deflateResetKeep=function(strm){if(deflateStateCheck(strm))return err(strm,Z_STREAM_ERROR);strm.total_in=strm.total_out=0,strm.data_type=Z_UNKNOWN;var s=strm.state;return s.pending=0,s.pending_out=0,s.wrap<0&&(s.wrap=-s.wrap),s.status=2===s.wrap?57:s.wrap?42:113,strm.adler=2===s.wrap?0:1,s.last_flush=-2,_tr_init(s),Z_OK},deflateReset=function(strm){var s,ret=deflateResetKeep(strm);return ret===Z_OK&&((s=strm.state).window_size=2*s.w_size,zero(s.head),s.max_lazy_match=configuration_table[s.level].max_lazy,s.good_match=configuration_table[s.level].good_length,s.nice_match=configuration_table[s.level].nice_length,s.max_chain_length=configuration_table[s.level].max_chain,s.strstart=0,s.block_start=0,s.lookahead=0,s.insert=0,s.match_length=s.prev_length=2,s.match_available=0,s.ins_h=0),ret},deflateInit2=function(strm,level,method,windowBits,memLevel,strategy){if(!strm)return Z_STREAM_ERROR;var wrap=1;if(level===Z_DEFAULT_COMPRESSION&&(level=6),windowBits<0?(wrap=0,windowBits=-windowBits):windowBits>15&&(wrap=2,windowBits-=16),memLevel<1||memLevel>9||method!==Z_DEFLATED||windowBits<8||windowBits>15||level<0||level>9||strategy<0||strategy>Z_FIXED||8===windowBits&&1!==wrap)return err(strm,Z_STREAM_ERROR);8===windowBits&&(windowBits=9);var s=new DeflateState;return strm.state=s,s.strm=strm,s.status=42,s.wrap=wrap,s.gzhead=null,s.w_bits=windowBits,s.w_size=1<<s.w_bits,s.w_mask=s.w_size-1,s.hash_bits=memLevel+7,s.hash_size=1<<s.hash_bits,s.hash_mask=s.hash_size-1,s.hash_shift=~~((s.hash_bits+3-1)/3),s.window=new Uint8Array(2*s.w_size),s.head=new Uint16Array(s.hash_size),s.prev=new Uint16Array(s.w_size),s.lit_bufsize=1<<memLevel+6,s.pending_buf_size=4*s.lit_bufsize,s.pending_buf=new Uint8Array(s.pending_buf_size),s.sym_buf=s.lit_bufsize,s.sym_end=3*(s.lit_bufsize-1),s.level=level,s.strategy=strategy,s.method=method,deflateReset(strm)};module.exports.deflateInit=function(strm,level){return deflateInit2(strm,level,Z_DEFLATED,15,8,Z_DEFAULT_STRATEGY)},module.exports.deflateInit2=deflateInit2,module.exports.deflateReset=deflateReset,module.exports.deflateResetKeep=deflateResetKeep,module.exports.deflateSetHeader=function(strm,head){return deflateStateCheck(strm)||2!==strm.state.wrap?Z_STREAM_ERROR:(strm.state.gzhead=head,Z_OK)},module.exports.deflate=function(strm,flush){if(deflateStateCheck(strm)||flush>Z_BLOCK||flush<0)return strm?err(strm,Z_STREAM_ERROR):Z_STREAM_ERROR;var s=strm.state;if(!strm.output||0!==strm.avail_in&&!strm.input||666===s.status&&flush!==Z_FINISH)return err(strm,0===strm.avail_out?Z_BUF_ERROR:Z_STREAM_ERROR);var old_flush=s.last_flush;if(s.last_flush=flush,0!==s.pending){if(flush_pending(strm),0===strm.avail_out)return s.last_flush=-1,Z_OK}else if(0===strm.avail_in&&rank(flush)<=rank(old_flush)&&flush!==Z_FINISH)return err(strm,Z_BUF_ERROR);if(666===s.status&&0!==strm.avail_in)return err(strm,Z_BUF_ERROR);if(42===s.status&&0===s.wrap&&(s.status=113),42===s.status){var header=Z_DEFLATED+(s.w_bits-8<<4)<<8;if(header|=(s.strategy>=Z_HUFFMAN_ONLY||s.level<2?0:s.level<6?1:6===s.level?2:3)<<6,0!==s.strstart&&(header|=32),putShortMSB(s,header+=31-header%31),0!==s.strstart&&(putShortMSB(s,strm.adler>>>16),putShortMSB(s,65535&strm.adler)),strm.adler=1,s.status=113,flush_pending(strm),0!==s.pending)return s.last_flush=-1,Z_OK}if(57===s.status)if(strm.adler=0,put_byte(s,31),put_byte(s,139),put_byte(s,8),s.gzhead)put_byte(s,(s.gzhead.text?1:0)+(s.gzhead.hcrc?2:0)+(s.gzhead.extra?4:0)+(s.gzhead.name?8:0)+(s.gzhead.comment?16:0)),put_byte(s,255&s.gzhead.time),put_byte(s,s.gzhead.time>>8&255),put_byte(s,s.gzhead.time>>16&255),put_byte(s,s.gzhead.time>>24&255),put_byte(s,9===s.level?2:s.strategy>=Z_HUFFMAN_ONLY||s.level<2?4:0),put_byte(s,255&s.gzhead.os),s.gzhead.extra&&s.gzhead.extra.length&&(put_byte(s,255&s.gzhead.extra.length),put_byte(s,s.gzhead.extra.length>>8&255)),s.gzhead.hcrc&&(strm.adler=crc32(strm.adler,s.pending_buf,s.pending,0)),s.gzindex=0,s.status=69;else if(put_byte(s,0),put_byte(s,0),put_byte(s,0),put_byte(s,0),put_byte(s,0),put_byte(s,9===s.level?2:s.strategy>=Z_HUFFMAN_ONLY||s.level<2?4:0),put_byte(s,3),s.status=113,flush_pending(strm),0!==s.pending)return s.last_flush=-1,Z_OK;if(69===s.status){if(s.gzhead.extra){for(var beg=s.pending,left=(65535&s.gzhead.extra.length)-s.gzindex;s.pending+left>s.pending_buf_size;){var copy=s.pending_buf_size-s.pending;if(s.pending_buf.set(s.gzhead.extra.subarray(s.gzindex,s.gzindex+copy),s.pending),s.pending=s.pending_buf_size,s.gzhead.hcrc&&s.pending>beg&&(strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)),s.gzindex+=copy,flush_pending(strm),0!==s.pending)return s.last_flush=-1,Z_OK;beg=0,left-=copy}var gzhead_extra=new Uint8Array(s.gzhead.extra);s.pending_buf.set(gzhead_extra.subarray(s.gzindex,s.gzindex+left),s.pending),s.pending+=left,s.gzhead.hcrc&&s.pending>beg&&(strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)),s.gzindex=0}s.status=73}if(73===s.status){if(s.gzhead.name){var val,_beg=s.pending;do{if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>_beg&&(strm.adler=crc32(strm.adler,s.pending_buf,s.pending-_beg,_beg)),flush_pending(strm),0!==s.pending)return s.last_flush=-1,Z_OK;_beg=0}val=s.gzindex<s.gzhead.name.length?255&s.gzhead.name.charCodeAt(s.gzindex++):0,put_byte(s,val)}while(0!==val);s.gzhead.hcrc&&s.pending>_beg&&(strm.adler=crc32(strm.adler,s.pending_buf,s.pending-_beg,_beg)),s.gzindex=0}s.status=91}if(91===s.status){if(s.gzhead.comment){var _val,_beg2=s.pending;do{if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>_beg2&&(strm.adler=crc32(strm.adler,s.pending_buf,s.pending-_beg2,_beg2)),flush_pending(strm),0!==s.pending)return s.last_flush=-1,Z_OK;_beg2=0}_val=s.gzindex<s.gzhead.comment.length?255&s.gzhead.comment.charCodeAt(s.gzindex++):0,put_byte(s,_val)}while(0!==_val);s.gzhead.hcrc&&s.pending>_beg2&&(strm.adler=crc32(strm.adler,s.pending_buf,s.pending-_beg2,_beg2))}s.status=103}if(103===s.status){if(s.gzhead.hcrc){if(s.pending+2>s.pending_buf_size&&(flush_pending(strm),0!==s.pending))return s.last_flush=-1,Z_OK;put_byte(s,255&strm.adler),put_byte(s,strm.adler>>8&255),strm.adler=0}if(s.status=113,flush_pending(strm),0!==s.pending)return s.last_flush=-1,Z_OK}if(0!==strm.avail_in||0!==s.lookahead||flush!==Z_NO_FLUSH&&666!==s.status){var bstate=0===s.level?deflate_stored(s,flush):s.strategy===Z_HUFFMAN_ONLY?function(s,flush){for(var bflush;;){if(0===s.lookahead&&(fill_window(s),0===s.lookahead)){if(flush===Z_NO_FLUSH)return 1;break}if(s.match_length=0,bflush=_tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++,bflush&&(flush_block_only(s,!1),0===s.strm.avail_out))return 1}return s.insert=0,flush===Z_FINISH?(flush_block_only(s,!0),0===s.strm.avail_out?3:4):s.sym_next&&(flush_block_only(s,!1),0===s.strm.avail_out)?1:2}(s,flush):s.strategy===Z_RLE?function(s,flush){for(var bflush,prev,scan,strend,_win=s.window;;){if(s.lookahead<=258){if(fill_window(s),s.lookahead<=258&&flush===Z_NO_FLUSH)return 1;if(0===s.lookahead)break}if(s.match_length=0,s.lookahead>=3&&s.strstart>0&&(prev=_win[scan=s.strstart-1])===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]){strend=s.strstart+258;do{}while(prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&scan<strend);s.match_length=258-(strend-scan),s.match_length>s.lookahead&&(s.match_length=s.lookahead)}if(s.match_length>=3?(bflush=_tr_tally(s,1,s.match_length-3),s.lookahead-=s.match_length,s.strstart+=s.match_length,s.match_length=0):(bflush=_tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++),bflush&&(flush_block_only(s,!1),0===s.strm.avail_out))return 1}return s.insert=0,flush===Z_FINISH?(flush_block_only(s,!0),0===s.strm.avail_out?3:4):s.sym_next&&(flush_block_only(s,!1),0===s.strm.avail_out)?1:2}(s,flush):configuration_table[s.level].func(s,flush);if(3!==bstate&&4!==bstate||(s.status=666),1===bstate||3===bstate)return 0===strm.avail_out&&(s.last_flush=-1),Z_OK;if(2===bstate&&(flush===Z_PARTIAL_FLUSH?_tr_align(s):flush!==Z_BLOCK&&(_tr_stored_block(s,0,0,!1),flush===Z_FULL_FLUSH&&(zero(s.head),0===s.lookahead&&(s.strstart=0,s.block_start=0,s.insert=0))),flush_pending(strm),0===strm.avail_out))return s.last_flush=-1,Z_OK}return flush!==Z_FINISH?Z_OK:s.wrap<=0?Z_STREAM_END:(2===s.wrap?(put_byte(s,255&strm.adler),put_byte(s,strm.adler>>8&255),put_byte(s,strm.adler>>16&255),put_byte(s,strm.adler>>24&255),put_byte(s,255&strm.total_in),put_byte(s,strm.total_in>>8&255),put_byte(s,strm.total_in>>16&255),put_byte(s,strm.total_in>>24&255)):(putShortMSB(s,strm.adler>>>16),putShortMSB(s,65535&strm.adler)),flush_pending(strm),s.wrap>0&&(s.wrap=-s.wrap),0!==s.pending?Z_OK:Z_STREAM_END)},module.exports.deflateEnd=function(strm){if(deflateStateCheck(strm))return Z_STREAM_ERROR;var status=strm.state.status;return strm.state=null,113===status?err(strm,Z_DATA_ERROR):Z_OK},module.exports.deflateSetDictionary=function(strm,dictionary){var dictLength=dictionary.length;if(deflateStateCheck(strm))return Z_STREAM_ERROR;var s=strm.state,wrap=s.wrap;if(2===wrap||1===wrap&&42!==s.status||s.lookahead)return Z_STREAM_ERROR;if(1===wrap&&(strm.adler=adler32(strm.adler,dictionary,dictLength,0)),s.wrap=0,dictLength>=s.w_size){0===wrap&&(zero(s.head),s.strstart=0,s.block_start=0,s.insert=0);var tmpDict=new Uint8Array(s.w_size);tmpDict.set(dictionary.subarray(dictLength-s.w_size,dictLength),0),dictionary=tmpDict,dictLength=s.w_size}var avail=strm.avail_in,next=strm.next_in,input=strm.input;for(strm.avail_in=dictLength,strm.next_in=0,strm.input=dictionary,fill_window(s);s.lookahead>=3;){var str=s.strstart,n=s.lookahead-2;do{s.ins_h=HASH(s,s.ins_h,s.window[str+3-1]),s.prev[str&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=str,str++}while(--n);s.strstart=str,s.lookahead=2,fill_window(s)}return s.strstart+=s.lookahead,s.block_start=s.strstart,s.insert=s.lookahead,s.lookahead=0,s.match_length=s.prev_length=2,s.match_available=0,strm.next_in=next,strm.input=input,strm.avail_in=avail,s.wrap=wrap,Z_OK},module.exports.deflateInfo="pako deflate (from Nodeca project)"},{"./adler32":24,"./constants":25,"./crc32":26,"./messages":32,"./trees":33}],28:[function(require,module,exports){"use strict";module.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],29:[function(require,module,exports){"use strict";module.exports=function(strm,start){var _in,last,_out,beg,end,dmax,wsize,whave,wnext,s_window,hold,bits,lcode,dcode,lmask,dmask,here,op,len,dist,from,from_source,input,output,state=strm.state;_in=strm.next_in,input=strm.input,last=_in+(strm.avail_in-5),_out=strm.next_out,output=strm.output,beg=_out-(start-strm.avail_out),end=_out+(strm.avail_out-257),dmax=state.dmax,wsize=state.wsize,whave=state.whave,wnext=state.wnext,s_window=state.window,hold=state.hold,bits=state.bits,lcode=state.lencode,dcode=state.distcode,lmask=(1<<state.lenbits)-1,dmask=(1<<state.distbits)-1;top:do{bits<15&&(hold+=input[_in++]<<bits,bits+=8,hold+=input[_in++]<<bits,bits+=8),here=lcode[hold&lmask];dolen:for(;;){if(hold>>>=op=here>>>24,bits-=op,0===(op=here>>>16&255))output[_out++]=65535&here;else{if(!(16&op)){if(0==(64&op)){here=lcode[(65535&here)+(hold&(1<<op)-1)];continue dolen}if(32&op){state.mode=16191;break top}strm.msg="invalid literal/length code",state.mode=16209;break top}len=65535&here,(op&=15)&&(bits<op&&(hold+=input[_in++]<<bits,bits+=8),len+=hold&(1<<op)-1,hold>>>=op,bits-=op),bits<15&&(hold+=input[_in++]<<bits,bits+=8,hold+=input[_in++]<<bits,bits+=8),here=dcode[hold&dmask];dodist:for(;;){if(hold>>>=op=here>>>24,bits-=op,!(16&(op=here>>>16&255))){if(0==(64&op)){here=dcode[(65535&here)+(hold&(1<<op)-1)];continue dodist}strm.msg="invalid distance code",state.mode=16209;break top}if(dist=65535&here,bits<(op&=15)&&(hold+=input[_in++]<<bits,(bits+=8)<op&&(hold+=input[_in++]<<bits,bits+=8)),(dist+=hold&(1<<op)-1)>dmax){strm.msg="invalid distance too far back",state.mode=16209;break top}if(hold>>>=op,bits-=op,dist>(op=_out-beg)){if((op=dist-op)>whave&&state.sane){strm.msg="invalid distance too far back",state.mode=16209;break top}if(from=0,from_source=s_window,0===wnext){if(from+=wsize-op,op<len){len-=op;do{output[_out++]=s_window[from++]}while(--op);from=_out-dist,from_source=output}}else if(wnext<op){if(from+=wsize+wnext-op,(op-=wnext)<len){len-=op;do{output[_out++]=s_window[from++]}while(--op);if(from=0,wnext<len){len-=op=wnext;do{output[_out++]=s_window[from++]}while(--op);from=_out-dist,from_source=output}}}else if(from+=wnext-op,op<len){len-=op;do{output[_out++]=s_window[from++]}while(--op);from=_out-dist,from_source=output}for(;len>2;)output[_out++]=from_source[from++],output[_out++]=from_source[from++],output[_out++]=from_source[from++],len-=3;len&&(output[_out++]=from_source[from++],len>1&&(output[_out++]=from_source[from++]))}else{from=_out-dist;do{output[_out++]=output[from++],output[_out++]=output[from++],output[_out++]=output[from++],len-=3}while(len>2);len&&(output[_out++]=output[from++],len>1&&(output[_out++]=output[from++]))}break}}break}}while(_in<last&&_out<end);_in-=len=bits>>3,hold&=(1<<(bits-=len<<3))-1,strm.next_in=_in,strm.next_out=_out,strm.avail_in=_in<last?last-_in+5:5-(_in-last),strm.avail_out=_out<end?end-_out+257:257-(_out-end),state.hold=hold,state.bits=bits}},{}],30:[function(require,module,exports){"use strict";var adler32=require("./adler32"),crc32=require("./crc32"),inflate_fast=require("./inffast"),inflate_table=require("./inftrees"),_require=require("./constants"),Z_FINISH=_require.Z_FINISH,Z_BLOCK=_require.Z_BLOCK,Z_TREES=_require.Z_TREES,Z_OK=_require.Z_OK,Z_STREAM_END=_require.Z_STREAM_END,Z_NEED_DICT=_require.Z_NEED_DICT,Z_STREAM_ERROR=_require.Z_STREAM_ERROR,Z_DATA_ERROR=_require.Z_DATA_ERROR,Z_MEM_ERROR=_require.Z_MEM_ERROR,Z_BUF_ERROR=_require.Z_BUF_ERROR,Z_DEFLATED=_require.Z_DEFLATED,BAD=16209,zswap32=function(q){return(q>>>24&255)+(q>>>8&65280)+((65280&q)<<8)+((255&q)<<24)};function InflateState(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}var lenfix,distfix,inflateStateCheck=function(strm){if(!strm)return 1;var state=strm.state;return!state||state.strm!==strm||state.mode<16180||state.mode>16211?1:0},inflateResetKeep=function(strm){if(inflateStateCheck(strm))return Z_STREAM_ERROR;var state=strm.state;return strm.total_in=strm.total_out=state.total=0,strm.msg="",state.wrap&&(strm.adler=1&state.wrap),state.mode=16180,state.last=0,state.havedict=0,state.flags=-1,state.dmax=32768,state.head=null,state.hold=0,state.bits=0,state.lencode=state.lendyn=new Int32Array(852),state.distcode=state.distdyn=new Int32Array(592),state.sane=1,state.back=-1,Z_OK},inflateReset=function(strm){if(inflateStateCheck(strm))return Z_STREAM_ERROR;var state=strm.state;return state.wsize=0,state.whave=0,state.wnext=0,inflateResetKeep(strm)},inflateReset2=function(strm,windowBits){var wrap;if(inflateStateCheck(strm))return Z_STREAM_ERROR;var state=strm.state;return windowBits<0?(wrap=0,windowBits=-windowBits):(wrap=5+(windowBits>>4),windowBits<48&&(windowBits&=15)),windowBits&&(windowBits<8||windowBits>15)?Z_STREAM_ERROR:(null!==state.window&&state.wbits!==windowBits&&(state.window=null),state.wrap=wrap,state.wbits=windowBits,inflateReset(strm))},inflateInit2=function(strm,windowBits){if(!strm)return Z_STREAM_ERROR;var state=new InflateState;strm.state=state,state.strm=strm,state.window=null,state.mode=16180;var ret=inflateReset2(strm,windowBits);return ret!==Z_OK&&(strm.state=null),ret},virgin=!0,fixedtables=function(state){if(virgin){lenfix=new Int32Array(512),distfix=new Int32Array(32);for(var sym=0;sym<144;)state.lens[sym++]=8;for(;sym<256;)state.lens[sym++]=9;for(;sym<280;)state.lens[sym++]=7;for(;sym<288;)state.lens[sym++]=8;for(inflate_table(1,state.lens,0,288,lenfix,0,state.work,{bits:9}),sym=0;sym<32;)state.lens[sym++]=5;inflate_table(2,state.lens,0,32,distfix,0,state.work,{bits:5}),virgin=!1}state.lencode=lenfix,state.lenbits=9,state.distcode=distfix,state.distbits=5},updatewindow=function(strm,src,end,copy){var dist,state=strm.state;return null===state.window&&(state.wsize=1<<state.wbits,state.wnext=0,state.whave=0,state.window=new Uint8Array(state.wsize)),copy>=state.wsize?(state.window.set(src.subarray(end-state.wsize,end),0),state.wnext=0,state.whave=state.wsize):((dist=state.wsize-state.wnext)>copy&&(dist=copy),state.window.set(src.subarray(end-copy,end-copy+dist),state.wnext),(copy-=dist)?(state.window.set(src.subarray(end-copy,end),0),state.wnext=copy,state.whave=state.wsize):(state.wnext+=dist,state.wnext===state.wsize&&(state.wnext=0),state.whave<state.wsize&&(state.whave+=dist))),0};module.exports.inflateReset=inflateReset,module.exports.inflateReset2=inflateReset2,module.exports.inflateResetKeep=inflateResetKeep,module.exports.inflateInit=function(strm){return inflateInit2(strm,15)},module.exports.inflateInit2=inflateInit2,module.exports.inflate=function(strm,flush){var state,input,output,next,put,have,left,hold,bits,_in,_out,copy,from,from_source,here_bits,here_op,here_val,last_bits,last_op,last_val,len,ret,opts,n,here=0,hbuf=new Uint8Array(4),order=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(inflateStateCheck(strm)||!strm.output||!strm.input&&0!==strm.avail_in)return Z_STREAM_ERROR;16191===(state=strm.state).mode&&(state.mode=16192),put=strm.next_out,output=strm.output,left=strm.avail_out,next=strm.next_in,input=strm.input,have=strm.avail_in,hold=state.hold,bits=state.bits,_in=have,_out=left,ret=Z_OK;inf_leave:for(;;)switch(state.mode){case 16180:if(0===state.wrap){state.mode=16192;break}for(;bits<16;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(2&state.wrap&&35615===hold){0===state.wbits&&(state.wbits=15),state.check=0,hbuf[0]=255&hold,hbuf[1]=hold>>>8&255,state.check=crc32(state.check,hbuf,2,0),hold=0,bits=0,state.mode=16181;break}if(state.head&&(state.head.done=!1),!(1&state.wrap)||(((255&hold)<<8)+(hold>>8))%31){strm.msg="incorrect header check",state.mode=BAD;break}if((15&hold)!==Z_DEFLATED){strm.msg="unknown compression method",state.mode=BAD;break}if(bits-=4,len=8+(15&(hold>>>=4)),0===state.wbits&&(state.wbits=len),len>15||len>state.wbits){strm.msg="invalid window size",state.mode=BAD;break}state.dmax=1<<state.wbits,state.flags=0,strm.adler=state.check=1,state.mode=512&hold?16189:16191,hold=0,bits=0;break;case 16181:for(;bits<16;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(state.flags=hold,(255&state.flags)!==Z_DEFLATED){strm.msg="unknown compression method",state.mode=BAD;break}if(57344&state.flags){strm.msg="unknown header flags set",state.mode=BAD;break}state.head&&(state.head.text=hold>>8&1),512&state.flags&&4&state.wrap&&(hbuf[0]=255&hold,hbuf[1]=hold>>>8&255,state.check=crc32(state.check,hbuf,2,0)),hold=0,bits=0,state.mode=16182;case 16182:for(;bits<32;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}state.head&&(state.head.time=hold),512&state.flags&&4&state.wrap&&(hbuf[0]=255&hold,hbuf[1]=hold>>>8&255,hbuf[2]=hold>>>16&255,hbuf[3]=hold>>>24&255,state.check=crc32(state.check,hbuf,4,0)),hold=0,bits=0,state.mode=16183;case 16183:for(;bits<16;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}state.head&&(state.head.xflags=255&hold,state.head.os=hold>>8),512&state.flags&&4&state.wrap&&(hbuf[0]=255&hold,hbuf[1]=hold>>>8&255,state.check=crc32(state.check,hbuf,2,0)),hold=0,bits=0,state.mode=16184;case 16184:if(1024&state.flags){for(;bits<16;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}state.length=hold,state.head&&(state.head.extra_len=hold),512&state.flags&&4&state.wrap&&(hbuf[0]=255&hold,hbuf[1]=hold>>>8&255,state.check=crc32(state.check,hbuf,2,0)),hold=0,bits=0}else state.head&&(state.head.extra=null);state.mode=16185;case 16185:if(1024&state.flags&&((copy=state.length)>have&&(copy=have),copy&&(state.head&&(len=state.head.extra_len-state.length,state.head.extra||(state.head.extra=new Uint8Array(state.head.extra_len)),state.head.extra.set(input.subarray(next,next+copy),len)),512&state.flags&&4&state.wrap&&(state.check=crc32(state.check,input,copy,next)),have-=copy,next+=copy,state.length-=copy),state.length))break inf_leave;state.length=0,state.mode=16186;case 16186:if(2048&state.flags){if(0===have)break inf_leave;copy=0;do{len=input[next+copy++],state.head&&len&&state.length<65536&&(state.head.name+=String.fromCharCode(len))}while(len&©<have);if(512&state.flags&&4&state.wrap&&(state.check=crc32(state.check,input,copy,next)),have-=copy,next+=copy,len)break inf_leave}else state.head&&(state.head.name=null);state.length=0,state.mode=16187;case 16187:if(4096&state.flags){if(0===have)break inf_leave;copy=0;do{len=input[next+copy++],state.head&&len&&state.length<65536&&(state.head.comment+=String.fromCharCode(len))}while(len&©<have);if(512&state.flags&&4&state.wrap&&(state.check=crc32(state.check,input,copy,next)),have-=copy,next+=copy,len)break inf_leave}else state.head&&(state.head.comment=null);state.mode=16188;case 16188:if(512&state.flags){for(;bits<16;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(4&state.wrap&&hold!==(65535&state.check)){strm.msg="header crc mismatch",state.mode=BAD;break}hold=0,bits=0}state.head&&(state.head.hcrc=state.flags>>9&1,state.head.done=!0),strm.adler=state.check=0,state.mode=16191;break;case 16189:for(;bits<32;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}strm.adler=state.check=zswap32(hold),hold=0,bits=0,state.mode=16190;case 16190:if(0===state.havedict)return strm.next_out=put,strm.avail_out=left,strm.next_in=next,strm.avail_in=have,state.hold=hold,state.bits=bits,Z_NEED_DICT;strm.adler=state.check=1,state.mode=16191;case 16191:if(flush===Z_BLOCK||flush===Z_TREES)break inf_leave;case 16192:if(state.last){hold>>>=7&bits,bits-=7&bits,state.mode=16206;break}for(;bits<3;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}switch(state.last=1&hold,bits-=1,3&(hold>>>=1)){case 0:state.mode=16193;break;case 1:if(fixedtables(state),state.mode=16199,flush===Z_TREES){hold>>>=2,bits-=2;break inf_leave}break;case 2:state.mode=16196;break;case 3:strm.msg="invalid block type",state.mode=BAD}hold>>>=2,bits-=2;break;case 16193:for(hold>>>=7&bits,bits-=7&bits;bits<32;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if((65535&hold)!=(hold>>>16^65535)){strm.msg="invalid stored block lengths",state.mode=BAD;break}if(state.length=65535&hold,hold=0,bits=0,state.mode=16194,flush===Z_TREES)break inf_leave;case 16194:state.mode=16195;case 16195:if(copy=state.length){if(copy>have&&(copy=have),copy>left&&(copy=left),0===copy)break inf_leave;output.set(input.subarray(next,next+copy),put),have-=copy,next+=copy,left-=copy,put+=copy,state.length-=copy;break}state.mode=16191;break;case 16196:for(;bits<14;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(state.nlen=257+(31&hold),hold>>>=5,bits-=5,state.ndist=1+(31&hold),hold>>>=5,bits-=5,state.ncode=4+(15&hold),hold>>>=4,bits-=4,state.nlen>286||state.ndist>30){strm.msg="too many length or distance symbols",state.mode=BAD;break}state.have=0,state.mode=16197;case 16197:for(;state.have<state.ncode;){for(;bits<3;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}state.lens[order[state.have++]]=7&hold,hold>>>=3,bits-=3}for(;state.have<19;)state.lens[order[state.have++]]=0;if(state.lencode=state.lendyn,state.lenbits=7,opts={bits:state.lenbits},ret=inflate_table(0,state.lens,0,19,state.lencode,0,state.work,opts),state.lenbits=opts.bits,ret){strm.msg="invalid code lengths set",state.mode=BAD;break}state.have=0,state.mode=16198;case 16198:for(;state.have<state.nlen+state.ndist;){for(;here_op=(here=state.lencode[hold&(1<<state.lenbits)-1])>>>16&255,here_val=65535&here,!((here_bits=here>>>24)<=bits);){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(here_val<16)hold>>>=here_bits,bits-=here_bits,state.lens[state.have++]=here_val;else{if(16===here_val){for(n=here_bits+2;bits<n;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(hold>>>=here_bits,bits-=here_bits,0===state.have){strm.msg="invalid bit length repeat",state.mode=BAD;break}len=state.lens[state.have-1],copy=3+(3&hold),hold>>>=2,bits-=2}else if(17===here_val){for(n=here_bits+3;bits<n;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}bits-=here_bits,len=0,copy=3+(7&(hold>>>=here_bits)),hold>>>=3,bits-=3}else{for(n=here_bits+7;bits<n;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}bits-=here_bits,len=0,copy=11+(127&(hold>>>=here_bits)),hold>>>=7,bits-=7}if(state.have+copy>state.nlen+state.ndist){strm.msg="invalid bit length repeat",state.mode=BAD;break}for(;copy--;)state.lens[state.have++]=len}}if(state.mode===BAD)break;if(0===state.lens[256]){strm.msg="invalid code -- missing end-of-block",state.mode=BAD;break}if(state.lenbits=9,opts={bits:state.lenbits},ret=inflate_table(1,state.lens,0,state.nlen,state.lencode,0,state.work,opts),state.lenbits=opts.bits,ret){strm.msg="invalid literal/lengths set",state.mode=BAD;break}if(state.distbits=6,state.distcode=state.distdyn,opts={bits:state.distbits},ret=inflate_table(2,state.lens,state.nlen,state.ndist,state.distcode,0,state.work,opts),state.distbits=opts.bits,ret){strm.msg="invalid distances set",state.mode=BAD;break}if(state.mode=16199,flush===Z_TREES)break inf_leave;case 16199:state.mode=16200;case 16200:if(have>=6&&left>=258){strm.next_out=put,strm.avail_out=left,strm.next_in=next,strm.avail_in=have,state.hold=hold,state.bits=bits,inflate_fast(strm,_out),put=strm.next_out,output=strm.output,left=strm.avail_out,next=strm.next_in,input=strm.input,have=strm.avail_in,hold=state.hold,bits=state.bits,16191===state.mode&&(state.back=-1);break}for(state.back=0;here_op=(here=state.lencode[hold&(1<<state.lenbits)-1])>>>16&255,here_val=65535&here,!((here_bits=here>>>24)<=bits);){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(here_op&&0==(240&here_op)){for(last_bits=here_bits,last_op=here_op,last_val=here_val;here_op=(here=state.lencode[last_val+((hold&(1<<last_bits+last_op)-1)>>last_bits)])>>>16&255,here_val=65535&here,!(last_bits+(here_bits=here>>>24)<=bits);){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}hold>>>=last_bits,bits-=last_bits,state.back+=last_bits}if(hold>>>=here_bits,bits-=here_bits,state.back+=here_bits,state.length=here_val,0===here_op){state.mode=16205;break}if(32&here_op){state.back=-1,state.mode=16191;break}if(64&here_op){strm.msg="invalid literal/length code",state.mode=BAD;break}state.extra=15&here_op,state.mode=16201;case 16201:if(state.extra){for(n=state.extra;bits<n;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}state.length+=hold&(1<<state.extra)-1,hold>>>=state.extra,bits-=state.extra,state.back+=state.extra}state.was=state.length,state.mode=16202;case 16202:for(;here_op=(here=state.distcode[hold&(1<<state.distbits)-1])>>>16&255,here_val=65535&here,!((here_bits=here>>>24)<=bits);){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(0==(240&here_op)){for(last_bits=here_bits,last_op=here_op,last_val=here_val;here_op=(here=state.distcode[last_val+((hold&(1<<last_bits+last_op)-1)>>last_bits)])>>>16&255,here_val=65535&here,!(last_bits+(here_bits=here>>>24)<=bits);){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}hold>>>=last_bits,bits-=last_bits,state.back+=last_bits}if(hold>>>=here_bits,bits-=here_bits,state.back+=here_bits,64&here_op){strm.msg="invalid distance code",state.mode=BAD;break}state.offset=here_val,state.extra=15&here_op,state.mode=16203;case 16203:if(state.extra){for(n=state.extra;bits<n;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}state.offset+=hold&(1<<state.extra)-1,hold>>>=state.extra,bits-=state.extra,state.back+=state.extra}if(state.offset>state.dmax){strm.msg="invalid distance too far back",state.mode=BAD;break}state.mode=16204;case 16204:if(0===left)break inf_leave;if(copy=_out-left,state.offset>copy){if((copy=state.offset-copy)>state.whave&&state.sane){strm.msg="invalid distance too far back",state.mode=BAD;break}copy>state.wnext?(copy-=state.wnext,from=state.wsize-copy):from=state.wnext-copy,copy>state.length&&(copy=state.length),from_source=state.window}else from_source=output,from=put-state.offset,copy=state.length;copy>left&&(copy=left),left-=copy,state.length-=copy;do{output[put++]=from_source[from++]}while(--copy);0===state.length&&(state.mode=16200);break;case 16205:if(0===left)break inf_leave;output[put++]=state.length,left--,state.mode=16200;break;case 16206:if(state.wrap){for(;bits<32;){if(0===have)break inf_leave;have--,hold|=input[next++]<<bits,bits+=8}if(_out-=left,strm.total_out+=_out,state.total+=_out,4&state.wrap&&_out&&(strm.adler=state.check=state.flags?crc32(state.check,output,_out,put-_out):adler32(state.check,output,_out,put-_out)),_out=left,4&state.wrap&&(state.flags?hold:zswap32(hold))!==state.check){strm.msg="incorrect data check",state.mode=BAD;break}hold=0,bits=0}state.mode=16207;case 16207:if(state.wrap&&state.flags){for(;bits<32;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(4&state.wrap&&hold!==(4294967295&state.total)){strm.msg="incorrect length check",state.mode=BAD;break}hold=0,bits=0}state.mode=16208;case 16208:ret=Z_STREAM_END;break inf_leave;case BAD:ret=Z_DATA_ERROR;break inf_leave;case 16210:return Z_MEM_ERROR;case 16211:default:return Z_STREAM_ERROR}return strm.next_out=put,strm.avail_out=left,strm.next_in=next,strm.avail_in=have,state.hold=hold,state.bits=bits,(state.wsize||_out!==strm.avail_out&&state.mode<BAD&&(state.mode<16206||flush!==Z_FINISH))&&updatewindow(strm,strm.output,strm.next_out,_out-strm.avail_out)?(state.mode=16210,Z_MEM_ERROR):(_in-=strm.avail_in,_out-=strm.avail_out,strm.total_in+=_in,strm.total_out+=_out,state.total+=_out,4&state.wrap&&_out&&(strm.adler=state.check=state.flags?crc32(state.check,output,_out,strm.next_out-_out):adler32(state.check,output,_out,strm.next_out-_out)),strm.data_type=state.bits+(state.last?64:0)+(16191===state.mode?128:0)+(16199===state.mode||16194===state.mode?256:0),(0===_in&&0===_out||flush===Z_FINISH)&&ret===Z_OK&&(ret=Z_BUF_ERROR),ret)},module.exports.inflateEnd=function(strm){if(inflateStateCheck(strm))return Z_STREAM_ERROR;var state=strm.state;return state.window&&(state.window=null),strm.state=null,Z_OK},module.exports.inflateGetHeader=function(strm,head){if(inflateStateCheck(strm))return Z_STREAM_ERROR;var state=strm.state;return 0==(2&state.wrap)?Z_STREAM_ERROR:(state.head=head,head.done=!1,Z_OK)},module.exports.inflateSetDictionary=function(strm,dictionary){var state,dictLength=dictionary.length;return inflateStateCheck(strm)||0!==(state=strm.state).wrap&&16190!==state.mode?Z_STREAM_ERROR:16190===state.mode&&adler32(1,dictionary,dictLength,0)!==state.check?Z_DATA_ERROR:updatewindow(strm,dictionary,dictLength,dictLength)?(state.mode=16210,Z_MEM_ERROR):(state.havedict=1,Z_OK)},module.exports.inflateInfo="pako inflate (from Nodeca project)"},{"./adler32":24,"./constants":25,"./crc32":26,"./inffast":29,"./inftrees":31}],31:[function(require,module,exports){"use strict";var lbase=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),lext=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),dbase=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),dext=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]);module.exports=function(type,lens,lens_index,codes,table,table_index,work,opts){var incr,fill,low,mask,next,match,here_bits,here_op,here_val,bits=opts.bits,len=0,sym=0,min=0,max=0,root=0,curr=0,drop=0,left=0,used=0,huff=0,base=null,count=new Uint16Array(16),offs=new Uint16Array(16),extra=null;for(len=0;len<=15;len++)count[len]=0;for(sym=0;sym<codes;sym++)count[lens[lens_index+sym]]++;for(root=bits,max=15;max>=1&&0===count[max];max--);if(root>max&&(root=max),0===max)return table[table_index++]=20971520,table[table_index++]=20971520,opts.bits=1,0;for(min=1;min<max&&0===count[min];min++);for(root<min&&(root=min),left=1,len=1;len<=15;len++)if(left<<=1,(left-=count[len])<0)return-1;if(left>0&&(0===type||1!==max))return-1;for(offs[1]=0,len=1;len<15;len++)offs[len+1]=offs[len]+count[len];for(sym=0;sym<codes;sym++)0!==lens[lens_index+sym]&&(work[offs[lens[lens_index+sym]]++]=sym);if(0===type?(base=extra=work,match=20):1===type?(base=lbase,extra=lext,match=257):(base=dbase,extra=dext,match=0),huff=0,sym=0,len=min,next=table_index,curr=root,drop=0,low=-1,mask=(used=1<<root)-1,1===type&&used>852||2===type&&used>592)return 1;for(;;){here_bits=len-drop,work[sym]+1<match?(here_op=0,here_val=work[sym]):work[sym]>=match?(here_op=extra[work[sym]-match],here_val=base[work[sym]-match]):(here_op=96,here_val=0),incr=1<<len-drop,min=fill=1<<curr;do{table[next+(huff>>drop)+(fill-=incr)]=here_bits<<24|here_op<<16|here_val|0}while(0!==fill);for(incr=1<<len-1;huff&incr;)incr>>=1;if(0!==incr?(huff&=incr-1,huff+=incr):huff=0,sym++,0==--count[len]){if(len===max)break;len=lens[lens_index+work[sym]]}if(len>root&&(huff&mask)!==low){for(0===drop&&(drop=root),next+=min,left=1<<(curr=len-drop);curr+drop<max&&!((left-=count[curr+drop])<=0);)curr++,left<<=1;if(used+=1<<curr,1===type&&used>852||2===type&&used>592)return 1;table[low=huff&mask]=root<<24|curr<<16|next-table_index|0}}return 0!==huff&&(table[next+huff]=len-drop<<24|64<<16|0),opts.bits=root,0}},{}],32:[function(require,module,exports){"use strict";module.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],33:[function(require,module,exports){"use strict";function zero(buf){for(var len=buf.length;--len>=0;)buf[len]=0}var extra_lbits=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),extra_dbits=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),extra_blbits=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),bl_order=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),static_ltree=new Array(576);zero(static_ltree);var static_dtree=new Array(60);zero(static_dtree);var _dist_code=new Array(512);zero(_dist_code);var _length_code=new Array(256);zero(_length_code);var base_length=new Array(29);zero(base_length);var static_l_desc,static_d_desc,static_bl_desc,base_dist=new Array(30);function StaticTreeDesc(static_tree,extra_bits,extra_base,elems,max_length){this.static_tree=static_tree,this.extra_bits=extra_bits,this.extra_base=extra_base,this.elems=elems,this.max_length=max_length,this.has_stree=static_tree&&static_tree.length}function TreeDesc(dyn_tree,stat_desc){this.dyn_tree=dyn_tree,this.max_code=0,this.stat_desc=stat_desc}zero(base_dist);var d_code=function(dist){return dist<256?_dist_code[dist]:_dist_code[256+(dist>>>7)]},put_short=function(s,w){s.pending_buf[s.pending++]=255&w,s.pending_buf[s.pending++]=w>>>8&255},send_bits=function(s,value,length){s.bi_valid>16-length?(s.bi_buf|=value<<s.bi_valid&65535,put_short(s,s.bi_buf),s.bi_buf=value>>16-s.bi_valid,s.bi_valid+=length-16):(s.bi_buf|=value<<s.bi_valid&65535,s.bi_valid+=length)},send_code=function(s,c,tree){send_bits(s,tree[2*c],tree[2*c+1])},bi_reverse=function(code,len){var res=0;do{res|=1&code,code>>>=1,res<<=1}while(--len>0);return res>>>1},gen_codes=function(tree,max_code,bl_count){var bits,n,next_code=new Array(16),code=0;for(bits=1;bits<=15;bits++)code=code+bl_count[bits-1]<<1,next_code[bits]=code;for(n=0;n<=max_code;n++){var len=tree[2*n+1];0!==len&&(tree[2*n]=bi_reverse(next_code[len]++,len))}},init_block=function(s){var n;for(n=0;n<286;n++)s.dyn_ltree[2*n]=0;for(n=0;n<30;n++)s.dyn_dtree[2*n]=0;for(n=0;n<19;n++)s.bl_tree[2*n]=0;s.dyn_ltree[512]=1,s.opt_len=s.static_len=0,s.sym_next=s.matches=0},bi_windup=function(s){s.bi_valid>8?put_short(s,s.bi_buf):s.bi_valid>0&&(s.pending_buf[s.pending++]=s.bi_buf),s.bi_buf=0,s.bi_valid=0},smaller=function(tree,n,m,depth){var _n2=2*n,_m2=2*m;return tree[_n2]<tree[_m2]||tree[_n2]===tree[_m2]&&depth[n]<=depth[m]},pqdownheap=function(s,tree,k){for(var v=s.heap[k],j=k<<1;j<=s.heap_len&&(j<s.heap_len&&smaller(tree,s.heap[j+1],s.heap[j],s.depth)&&j++,!smaller(tree,v,s.heap[j],s.depth));)s.heap[k]=s.heap[j],k=j,j<<=1;s.heap[k]=v},compress_block=function(s,ltree,dtree){var dist,lc,code,extra,sx=0;if(0!==s.sym_next)do{dist=255&s.pending_buf[s.sym_buf+sx++],dist+=(255&s.pending_buf[s.sym_buf+sx++])<<8,lc=s.pending_buf[s.sym_buf+sx++],0===dist?send_code(s,lc,ltree):(code=_length_code[lc],send_code(s,code+256+1,ltree),0!==(extra=extra_lbits[code])&&(lc-=base_length[code],send_bits(s,lc,extra)),dist--,code=d_code(dist),send_code(s,code,dtree),0!==(extra=extra_dbits[code])&&(dist-=base_dist[code],send_bits(s,dist,extra)))}while(sx<s.sym_next);send_code(s,256,ltree)},build_tree=function(s,desc){var n,m,node,tree=desc.dyn_tree,stree=desc.stat_desc.static_tree,has_stree=desc.stat_desc.has_stree,elems=desc.stat_desc.elems,max_code=-1;for(s.heap_len=0,s.heap_max=573,n=0;n<elems;n++)0!==tree[2*n]?(s.heap[++s.heap_len]=max_code=n,s.depth[n]=0):tree[2*n+1]=0;for(;s.heap_len<2;)tree[2*(node=s.heap[++s.heap_len]=max_code<2?++max_code:0)]=1,s.depth[node]=0,s.opt_len--,has_stree&&(s.static_len-=stree[2*node+1]);for(desc.max_code=max_code,n=s.heap_len>>1;n>=1;n--)pqdownheap(s,tree,n);node=elems;do{n=s.heap[1],s.heap[1]=s.heap[s.heap_len--],pqdownheap(s,tree,1),m=s.heap[1],s.heap[--s.heap_max]=n,s.heap[--s.heap_max]=m,tree[2*node]=tree[2*n]+tree[2*m],s.depth[node]=(s.depth[n]>=s.depth[m]?s.depth[n]:s.depth[m])+1,tree[2*n+1]=tree[2*m+1]=node,s.heap[1]=node++,pqdownheap(s,tree,1)}while(s.heap_len>=2);s.heap[--s.heap_max]=s.heap[1],function(s,desc){var h,n,m,bits,xbits,f,tree=desc.dyn_tree,max_code=desc.max_code,stree=desc.stat_desc.static_tree,has_stree=desc.stat_desc.has_stree,extra=desc.stat_desc.extra_bits,base=desc.stat_desc.extra_base,max_length=desc.stat_desc.max_length,overflow=0;for(bits=0;bits<=15;bits++)s.bl_count[bits]=0;for(tree[2*s.heap[s.heap_max]+1]=0,h=s.heap_max+1;h<573;h++)(bits=tree[2*tree[2*(n=s.heap[h])+1]+1]+1)>max_length&&(bits=max_length,overflow++),tree[2*n+1]=bits,n>max_code||(s.bl_count[bits]++,xbits=0,n>=base&&(xbits=extra[n-base]),f=tree[2*n],s.opt_len+=f*(bits+xbits),has_stree&&(s.static_len+=f*(stree[2*n+1]+xbits)));if(0!==overflow){do{for(bits=max_length-1;0===s.bl_count[bits];)bits--;s.bl_count[bits]--,s.bl_count[bits+1]+=2,s.bl_count[max_length]--,overflow-=2}while(overflow>0);for(bits=max_length;0!==bits;bits--)for(n=s.bl_count[bits];0!==n;)(m=s.heap[--h])>max_code||(tree[2*m+1]!==bits&&(s.opt_len+=(bits-tree[2*m+1])*tree[2*m],tree[2*m+1]=bits),n--)}}(s,desc),gen_codes(tree,max_code,s.bl_count)},scan_tree=function(s,tree,max_code){var n,curlen,prevlen=-1,nextlen=tree[1],count=0,max_count=7,min_count=4;for(0===nextlen&&(max_count=138,min_count=3),tree[2*(max_code+1)+1]=65535,n=0;n<=max_code;n++)curlen=nextlen,nextlen=tree[2*(n+1)+1],++count<max_count&&curlen===nextlen||(count<min_count?s.bl_tree[2*curlen]+=count:0!==curlen?(curlen!==prevlen&&s.bl_tree[2*curlen]++,s.bl_tree[32]++):count<=10?s.bl_tree[34]++:s.bl_tree[36]++,count=0,prevlen=curlen,0===nextlen?(max_count=138,min_count=3):curlen===nextlen?(max_count=6,min_count=3):(max_count=7,min_count=4))},send_tree=function(s,tree,max_code){var n,curlen,prevlen=-1,nextlen=tree[1],count=0,max_count=7,min_count=4;for(0===nextlen&&(max_count=138,min_count=3),n=0;n<=max_code;n++)if(curlen=nextlen,nextlen=tree[2*(n+1)+1],!(++count<max_count&&curlen===nextlen)){if(count<min_count)do{send_code(s,curlen,s.bl_tree)}while(0!=--count);else 0!==curlen?(curlen!==prevlen&&(send_code(s,curlen,s.bl_tree),count--),send_code(s,16,s.bl_tree),send_bits(s,count-3,2)):count<=10?(send_code(s,17,s.bl_tree),send_bits(s,count-3,3)):(send_code(s,18,s.bl_tree),send_bits(s,count-11,7));count=0,prevlen=curlen,0===nextlen?(max_count=138,min_count=3):curlen===nextlen?(max_count=6,min_count=3):(max_count=7,min_count=4)}},static_init_done=!1,_tr_stored_block=function(s,buf,stored_len,last){send_bits(s,0+(last?1:0),3),bi_windup(s),put_short(s,stored_len),put_short(s,~stored_len),stored_len&&s.pending_buf.set(s.window.subarray(buf,buf+stored_len),s.pending),s.pending+=stored_len};module.exports._tr_init=function(s){static_init_done||(!function(){var n,bits,length,code,dist,bl_count=new Array(16);for(length=0,code=0;code<28;code++)for(base_length[code]=length,n=0;n<1<<extra_lbits[code];n++)_length_code[length++]=code;for(_length_code[length-1]=code,dist=0,code=0;code<16;code++)for(base_dist[code]=dist,n=0;n<1<<extra_dbits[code];n++)_dist_code[dist++]=code;for(dist>>=7;code<30;code++)for(base_dist[code]=dist<<7,n=0;n<1<<extra_dbits[code]-7;n++)_dist_code[256+dist++]=code;for(bits=0;bits<=15;bits++)bl_count[bits]=0;for(n=0;n<=143;)static_ltree[2*n+1]=8,n++,bl_count[8]++;for(;n<=255;)static_ltree[2*n+1]=9,n++,bl_count[9]++;for(;n<=279;)static_ltree[2*n+1]=7,n++,bl_count[7]++;for(;n<=287;)static_ltree[2*n+1]=8,n++,bl_count[8]++;for(gen_codes(static_ltree,287,bl_count),n=0;n<30;n++)static_dtree[2*n+1]=5,static_dtree[2*n]=bi_reverse(n,5);static_l_desc=new StaticTreeDesc(static_ltree,extra_lbits,257,286,15),static_d_desc=new StaticTreeDesc(static_dtree,extra_dbits,0,30,15),static_bl_desc=new StaticTreeDesc(new Array(0),extra_blbits,0,19,7)}(),static_init_done=!0),s.l_desc=new TreeDesc(s.dyn_ltree,static_l_desc),s.d_desc=new TreeDesc(s.dyn_dtree,static_d_desc),s.bl_desc=new TreeDesc(s.bl_tree,static_bl_desc),s.bi_buf=0,s.bi_valid=0,init_block(s)},module.exports._tr_stored_block=_tr_stored_block,module.exports._tr_flush_block=function(s,buf,stored_len,last){var opt_lenb,static_lenb,max_blindex=0;s.level>0?(2===s.strm.data_type&&(s.strm.data_type=function(s){var n,block_mask=4093624447;for(n=0;n<=31;n++,block_mask>>>=1)if(1&block_mask&&0!==s.dyn_ltree[2*n])return 0;if(0!==s.dyn_ltree[18]||0!==s.dyn_ltree[20]||0!==s.dyn_ltree[26])return 1;for(n=32;n<256;n++)if(0!==s.dyn_ltree[2*n])return 1;return 0}(s)),build_tree(s,s.l_desc),build_tree(s,s.d_desc),max_blindex=function(s){var max_blindex;for(scan_tree(s,s.dyn_ltree,s.l_desc.max_code),scan_tree(s,s.dyn_dtree,s.d_desc.max_code),build_tree(s,s.bl_desc),max_blindex=18;max_blindex>=3&&0===s.bl_tree[2*bl_order[max_blindex]+1];max_blindex--);return s.opt_len+=3*(max_blindex+1)+5+5+4,max_blindex}(s),opt_lenb=s.opt_len+3+7>>>3,(static_lenb=s.static_len+3+7>>>3)<=opt_lenb&&(opt_lenb=static_lenb)):opt_lenb=static_lenb=stored_len+5,stored_len+4<=opt_lenb&&-1!==buf?_tr_stored_block(s,buf,stored_len,last):4===s.strategy||static_lenb===opt_lenb?(send_bits(s,2+(last?1:0),3),compress_block(s,static_ltree,static_dtree)):(send_bits(s,4+(last?1:0),3),function(s,lcodes,dcodes,blcodes){var rank;for(send_bits(s,lcodes-257,5),send_bits(s,dcodes-1,5),send_bits(s,blcodes-4,4),rank=0;rank<blcodes;rank++)send_bits(s,s.bl_tree[2*bl_order[rank]+1],3);send_tree(s,s.dyn_ltree,lcodes-1),send_tree(s,s.dyn_dtree,dcodes-1)}(s,s.l_desc.max_code+1,s.d_desc.max_code+1,max_blindex+1),compress_block(s,s.dyn_ltree,s.dyn_dtree)),init_block(s),last&&bi_windup(s)},module.exports._tr_tally=function(s,dist,lc){return s.pending_buf[s.sym_buf+s.sym_next++]=dist,s.pending_buf[s.sym_buf+s.sym_next++]=dist>>8,s.pending_buf[s.sym_buf+s.sym_next++]=lc,0===dist?s.dyn_ltree[2*lc]++:(s.matches++,dist--,s.dyn_ltree[2*(_length_code[lc]+256+1)]++,s.dyn_dtree[2*d_code(dist)]++),s.sym_next===s.sym_end},module.exports._tr_align=function(s){send_bits(s,2,3),send_code(s,256,static_ltree),function(s){16===s.bi_valid?(put_short(s,s.bi_buf),s.bi_buf=0,s.bi_valid=0):s.bi_valid>=8&&(s.pending_buf[s.pending++]=255&s.bi_buf,s.bi_buf>>=8,s.bi_valid-=8)}(s)}},{}],34:[function(require,module,exports){"use strict";module.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],35:[function(require,module,exports){var cachedSetTimeout,cachedClearTimeout,process=module.exports={};function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}function runTimeout(fun){if(cachedSetTimeout===setTimeout)return setTimeout(fun,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(fun,0);try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}!function(){try{cachedSetTimeout="function"==typeof setTimeout?setTimeout:defaultSetTimout}catch(e){cachedSetTimeout=defaultSetTimout}try{cachedClearTimeout="function"==typeof clearTimeout?clearTimeout:defaultClearTimeout}catch(e){cachedClearTimeout=defaultClearTimeout}}();var currentQueue,queue=[],draining=!1,queueIndex=-1;function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var timeout=runTimeout(cleanUpNextTick);draining=!0;for(var len=queue.length;len;){for(currentQueue=queue,queue=[];++queueIndex<len;)currentQueue&¤tQueue[queueIndex].run();queueIndex=-1,len=queue.length}currentQueue=null,draining=!1,function(marker){if(cachedClearTimeout===clearTimeout)return clearTimeout(marker);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(marker);try{cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}(timeout)}}function Item(fun,array){this.fun=fun,this.array=array}function noop(){}process.nextTick=function(fun){var args=new Array(arguments.length-1);if(arguments.length>1)for(var i=1;i<arguments.length;i++)args[i-1]=arguments[i];queue.push(new Item(fun,args)),1!==queue.length||draining||runTimeout(drainQueue)},Item.prototype.run=function(){this.fun.apply(null,this.array)},process.title="browser",process.browser=!0,process.env={},process.argv=[],process.version="",process.versions={},process.on=noop,process.addListener=noop,process.once=noop,process.off=noop,process.removeListener=noop,process.removeAllListeners=noop,process.emit=noop,process.prependListener=noop,process.prependOnceListener=noop,process.listeners=function(name){return[]},process.binding=function(name){throw new Error("process.binding is not supported")},process.cwd=function(){return"/"},process.chdir=function(dir){throw new Error("process.chdir is not supported")},process.umask=function(){return 0}},{}],36:[function(require,module,exports){(function(setImmediate){(function(){function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}!function(root){var setTimeoutFunc=setTimeout;function noop(){}function Promise(fn){if(!(this instanceof Promise))throw new TypeError("Promises must be constructed via new");if("function"!=typeof fn)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=void 0,this._deferreds=[],doResolve(fn,this)}function handle(self,deferred){for(;3===self._state;)self=self._value;0!==self._state?(self._handled=!0,Promise._immediateFn((function(){var cb=1===self._state?deferred.onFulfilled:deferred.onRejected;if(null!==cb){var ret;try{ret=cb(self._value)}catch(e){return void reject(deferred.promise,e)}resolve(deferred.promise,ret)}else(1===self._state?resolve:reject)(deferred.promise,self._value)}))):self._deferreds.push(deferred)}function resolve(self,newValue){try{if(newValue===self)throw new TypeError("A promise cannot be resolved with itself.");if(newValue&&("object"===_typeof(newValue)||"function"==typeof newValue)){var then=newValue.then;if(newValue instanceof Promise)return self._state=3,self._value=newValue,void finale(self);if("function"==typeof then)return void doResolve((fn=then,thisArg=newValue,function(){fn.apply(thisArg,arguments)}),self)}self._state=1,self._value=newValue,finale(self)}catch(e){reject(self,e)}var fn,thisArg}function reject(self,newValue){self._state=2,self._value=newValue,finale(self)}function finale(self){2===self._state&&0===self._deferreds.length&&Promise._immediateFn((function(){self._handled||Promise._unhandledRejectionFn(self._value)}));for(var i=0,len=self._deferreds.length;i<len;i++)handle(self,self._deferreds[i]);self._deferreds=null}function Handler(onFulfilled,onRejected,promise){this.onFulfilled="function"==typeof onFulfilled?onFulfilled:null,this.onRejected="function"==typeof onRejected?onRejected:null,this.promise=promise}function doResolve(fn,self){var done=!1;try{fn((function(value){done||(done=!0,resolve(self,value))}),(function(reason){done||(done=!0,reject(self,reason))}))}catch(ex){if(done)return;done=!0,reject(self,ex)}}Promise.prototype.catch=function(onRejected){return this.then(null,onRejected)},Promise.prototype.then=function(onFulfilled,onRejected){var prom=new this.constructor(noop);return handle(this,new Handler(onFulfilled,onRejected,prom)),prom},Promise.all=function(arr){return new Promise((function(resolve,reject){if(!arr||"undefined"==typeof arr.length)throw new TypeError("Promise.all accepts an array");var args=Array.prototype.slice.call(arr);if(0===args.length)return resolve([]);var remaining=args.length;function res(i,val){try{if(val&&("object"===_typeof(val)||"function"==typeof val)){var then=val.then;if("function"==typeof then)return void then.call(val,(function(val){res(i,val)}),reject)}args[i]=val,0==--remaining&&resolve(args)}catch(ex){reject(ex)}}for(var i=0;i<args.length;i++)res(i,args[i])}))},Promise.resolve=function(value){return value&&"object"===_typeof(value)&&value.constructor===Promise?value:new Promise((function(resolve){resolve(value)}))},Promise.reject=function(value){return new Promise((function(resolve,reject){reject(value)}))},Promise.race=function(values){return new Promise((function(resolve,reject){for(var i=0,len=values.length;i<len;i++)values[i].then(resolve,reject)}))},Promise._immediateFn="function"==typeof setImmediate&&function(fn){setImmediate(fn)}||function(fn){setTimeoutFunc(fn,0)},Promise._unhandledRejectionFn=function(err){"undefined"!=typeof console&&console&&console.warn("Possible Unhandled Promise Rejection:",err)},Promise._setImmediateFn=function(fn){Promise._immediateFn=fn},Promise._setUnhandledRejectionFn=function(fn){Promise._unhandledRejectionFn=fn},"undefined"!=typeof module&&module.exports?module.exports=Promise:root.Promise||(root.Promise=Promise)}(this)}).call(this)}).call(this,require("timers").setImmediate)},{timers:39}],37:[function(require,module,exports){"use strict";var SDPUtils=require("sdp");function writeMediaSection(transceiver,caps,type,stream,dtlsRole){var sdp=SDPUtils.writeRtpDescription(transceiver.kind,caps);if(sdp+=SDPUtils.writeIceParameters(transceiver.iceGatherer.getLocalParameters()),sdp+=SDPUtils.writeDtlsParameters(transceiver.dtlsTransport.getLocalParameters(),"offer"===type?"actpass":dtlsRole||"active"),sdp+="a=mid:"+transceiver.mid+"\r\n",transceiver.rtpSender&&transceiver.rtpReceiver?sdp+="a=sendrecv\r\n":transceiver.rtpSender?sdp+="a=sendonly\r\n":transceiver.rtpReceiver?sdp+="a=recvonly\r\n":sdp+="a=inactive\r\n",transceiver.rtpSender){var trackId=transceiver.rtpSender._initialTrackId||transceiver.rtpSender.track.id;transceiver.rtpSender._initialTrackId=trackId;var msid="msid:"+(stream?stream.id:"-")+" "+trackId+"\r\n";sdp+="a="+msid,sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].ssrc+" "+msid,transceiver.sendEncodingParameters[0].rtx&&(sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].rtx.ssrc+" "+msid,sdp+="a=ssrc-group:FID "+transceiver.sendEncodingParameters[0].ssrc+" "+transceiver.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].ssrc+" cname:"+SDPUtils.localCName+"\r\n",transceiver.rtpSender&&transceiver.sendEncodingParameters[0].rtx&&(sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].rtx.ssrc+" cname:"+SDPUtils.localCName+"\r\n"),sdp}function getCommonCapabilities(localCapabilities,remoteCapabilities){var commonCapabilities={codecs:[],headerExtensions:[],fecMechanisms:[]},findCodecByPayloadType=function(pt,codecs){pt=parseInt(pt,10);for(var i=0;i<codecs.length;i++)if(codecs[i].payloadType===pt||codecs[i].preferredPayloadType===pt)return codecs[i]},rtxCapabilityMatches=function(lRtx,rRtx,lCodecs,rCodecs){var lCodec=findCodecByPayloadType(lRtx.parameters.apt,lCodecs),rCodec=findCodecByPayloadType(rRtx.parameters.apt,rCodecs);return lCodec&&rCodec&&lCodec.name.toLowerCase()===rCodec.name.toLowerCase()};return localCapabilities.codecs.forEach((function(lCodec){for(var i=0;i<remoteCapabilities.codecs.length;i++){var rCodec=remoteCapabilities.codecs[i];if(lCodec.name.toLowerCase()===rCodec.name.toLowerCase()&&lCodec.clockRate===rCodec.clockRate){if("rtx"===lCodec.name.toLowerCase()&&lCodec.parameters&&rCodec.parameters.apt&&!rtxCapabilityMatches(lCodec,rCodec,localCapabilities.codecs,remoteCapabilities.codecs))continue;(rCodec=JSON.parse(JSON.stringify(rCodec))).numChannels=Math.min(lCodec.numChannels,rCodec.numChannels),commonCapabilities.codecs.push(rCodec),rCodec.rtcpFeedback=rCodec.rtcpFeedback.filter((function(fb){for(var j=0;j<lCodec.rtcpFeedback.length;j++)if(lCodec.rtcpFeedback[j].type===fb.type&&lCodec.rtcpFeedback[j].parameter===fb.parameter)return!0;return!1}));break}}})),localCapabilities.headerExtensions.forEach((function(lHeaderExtension){for(var i=0;i<remoteCapabilities.headerExtensions.length;i++){var rHeaderExtension=remoteCapabilities.headerExtensions[i];if(lHeaderExtension.uri===rHeaderExtension.uri){commonCapabilities.headerExtensions.push(rHeaderExtension);break}}})),commonCapabilities}function isActionAllowedInSignalingState(action,type,signalingState){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"]}}[type][action].indexOf(signalingState)}function maybeAddCandidate(iceTransport,candidate){var alreadyAdded=iceTransport.getRemoteCandidates().find((function(remoteCandidate){return candidate.foundation===remoteCandidate.foundation&&candidate.ip===remoteCandidate.ip&&candidate.port===remoteCandidate.port&&candidate.priority===remoteCandidate.priority&&candidate.protocol===remoteCandidate.protocol&&candidate.type===remoteCandidate.type}));return alreadyAdded||iceTransport.addRemoteCandidate(candidate),!alreadyAdded}function makeError(name,description){var e=new Error(description);return e.name=name,e.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[name],e}module.exports=function(window,edgeVersion){function addTrackToStreamAndFireEvent(track,stream){stream.addTrack(track),stream.dispatchEvent(new window.MediaStreamTrackEvent("addtrack",{track:track}))}function fireAddTrack(pc,track,receiver,streams){var trackEvent=new Event("track");trackEvent.track=track,trackEvent.receiver=receiver,trackEvent.transceiver={receiver:receiver},trackEvent.streams=streams,window.setTimeout((function(){pc._dispatchEvent("track",trackEvent)}))}var RTCPeerConnection=function(config){var pc=this,_eventTarget=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach((function(method){pc[method]=_eventTarget[method].bind(_eventTarget)})),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",config=JSON.parse(JSON.stringify(config||{})),this.usingBundle="max-bundle"===config.bundlePolicy,"negotiate"===config.rtcpMuxPolicy)throw makeError("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(config.rtcpMuxPolicy||(config.rtcpMuxPolicy="require"),config.iceTransportPolicy){case"all":case"relay":break;default:config.iceTransportPolicy="all"}switch(config.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:config.bundlePolicy="balanced"}if(config.iceServers=function(iceServers,edgeVersion){var hasTurn=!1;return(iceServers=JSON.parse(JSON.stringify(iceServers))).filter((function(server){if(server&&(server.urls||server.url)){var urls=server.urls||server.url;server.url&&!server.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var isString="string"==typeof urls;return isString&&(urls=[urls]),urls=urls.filter((function(url){return 0===url.indexOf("turn:")&&-1!==url.indexOf("transport=udp")&&-1===url.indexOf("turn:[")&&!hasTurn?(hasTurn=!0,!0):0===url.indexOf("stun:")&&edgeVersion>=14393&&-1===url.indexOf("?transport=udp")})),delete server.url,server.urls=isString?urls[0]:urls,!!urls.length}}))}(config.iceServers||[],edgeVersion),this._iceGatherers=[],config.iceCandidatePoolSize)for(var i=config.iceCandidatePoolSize;i>0;i--)this._iceGatherers.push(new window.RTCIceGatherer({iceServers:config.iceServers,gatherPolicy:config.iceTransportPolicy}));else config.iceCandidatePoolSize=0;this._config=config,this.transceivers=[],this._sdpSessionId=SDPUtils.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(RTCPeerConnection.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(RTCPeerConnection.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),RTCPeerConnection.prototype.onicecandidate=null,RTCPeerConnection.prototype.onaddstream=null,RTCPeerConnection.prototype.ontrack=null,RTCPeerConnection.prototype.onremovestream=null,RTCPeerConnection.prototype.onsignalingstatechange=null,RTCPeerConnection.prototype.oniceconnectionstatechange=null,RTCPeerConnection.prototype.onconnectionstatechange=null,RTCPeerConnection.prototype.onicegatheringstatechange=null,RTCPeerConnection.prototype.onnegotiationneeded=null,RTCPeerConnection.prototype.ondatachannel=null,RTCPeerConnection.prototype._dispatchEvent=function(name,event){this._isClosed||(this.dispatchEvent(event),"function"==typeof this["on"+name]&&this["on"+name](event))},RTCPeerConnection.prototype._emitGatheringStateChange=function(){var event=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",event)},RTCPeerConnection.prototype.getConfiguration=function(){return this._config},RTCPeerConnection.prototype.getLocalStreams=function(){return this.localStreams},RTCPeerConnection.prototype.getRemoteStreams=function(){return this.remoteStreams},RTCPeerConnection.prototype._createTransceiver=function(kind,doNotAdd){var hasBundleTransport=this.transceivers.length>0,transceiver={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:kind,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&hasBundleTransport)transceiver.iceTransport=this.transceivers[0].iceTransport,transceiver.dtlsTransport=this.transceivers[0].dtlsTransport;else{var transports=this._createIceAndDtlsTransports();transceiver.iceTransport=transports.iceTransport,transceiver.dtlsTransport=transports.dtlsTransport}return doNotAdd||this.transceivers.push(transceiver),transceiver},RTCPeerConnection.prototype.addTrack=function(track,stream){if(this._isClosed)throw makeError("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var transceiver;if(this.transceivers.find((function(s){return s.track===track})))throw makeError("InvalidAccessError","Track already exists.");for(var i=0;i<this.transceivers.length;i++)this.transceivers[i].track||this.transceivers[i].kind!==track.kind||(transceiver=this.transceivers[i]);return transceiver||(transceiver=this._createTransceiver(track.kind)),this._maybeFireNegotiationNeeded(),-1===this.localStreams.indexOf(stream)&&this.localStreams.push(stream),transceiver.track=track,transceiver.stream=stream,transceiver.rtpSender=new window.RTCRtpSender(track,transceiver.dtlsTransport),transceiver.rtpSender},RTCPeerConnection.prototype.addStream=function(stream){var pc=this;if(edgeVersion>=15025)stream.getTracks().forEach((function(track){pc.addTrack(track,stream)}));else{var clonedStream=stream.clone();stream.getTracks().forEach((function(track,idx){var clonedTrack=clonedStream.getTracks()[idx];track.addEventListener("enabled",(function(event){clonedTrack.enabled=event.enabled}))})),clonedStream.getTracks().forEach((function(track){pc.addTrack(track,clonedStream)}))}},RTCPeerConnection.prototype.removeTrack=function(sender){if(this._isClosed)throw makeError("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(sender instanceof window.RTCRtpSender))throw new TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var transceiver=this.transceivers.find((function(t){return t.rtpSender===sender}));if(!transceiver)throw makeError("InvalidAccessError","Sender was not created by this connection.");var stream=transceiver.stream;transceiver.rtpSender.stop(),transceiver.rtpSender=null,transceiver.track=null,transceiver.stream=null,-1===this.transceivers.map((function(t){return t.stream})).indexOf(stream)&&this.localStreams.indexOf(stream)>-1&&this.localStreams.splice(this.localStreams.indexOf(stream),1),this._maybeFireNegotiationNeeded()},RTCPeerConnection.prototype.removeStream=function(stream){var pc=this;stream.getTracks().forEach((function(track){var sender=pc.getSenders().find((function(s){return s.track===track}));sender&&pc.removeTrack(sender)}))},RTCPeerConnection.prototype.getSenders=function(){return this.transceivers.filter((function(transceiver){return!!transceiver.rtpSender})).map((function(transceiver){return transceiver.rtpSender}))},RTCPeerConnection.prototype.getReceivers=function(){return this.transceivers.filter((function(transceiver){return!!transceiver.rtpReceiver})).map((function(transceiver){return transceiver.rtpReceiver}))},RTCPeerConnection.prototype._createIceGatherer=function(sdpMLineIndex,usingBundle){var pc=this;if(usingBundle&&sdpMLineIndex>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var iceGatherer=new window.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(iceGatherer,"state",{value:"new",writable:!0}),this.transceivers[sdpMLineIndex].bufferedCandidateEvents=[],this.transceivers[sdpMLineIndex].bufferCandidates=function(event){var end=!event.candidate||0===Object.keys(event.candidate).length;iceGatherer.state=end?"completed":"gathering",null!==pc.transceivers[sdpMLineIndex].bufferedCandidateEvents&&pc.transceivers[sdpMLineIndex].bufferedCandidateEvents.push(event)},iceGatherer.addEventListener("localcandidate",this.transceivers[sdpMLineIndex].bufferCandidates),iceGatherer},RTCPeerConnection.prototype._gather=function(mid,sdpMLineIndex){var pc=this,iceGatherer=this.transceivers[sdpMLineIndex].iceGatherer;if(!iceGatherer.onlocalcandidate){var bufferedCandidateEvents=this.transceivers[sdpMLineIndex].bufferedCandidateEvents;this.transceivers[sdpMLineIndex].bufferedCandidateEvents=null,iceGatherer.removeEventListener("localcandidate",this.transceivers[sdpMLineIndex].bufferCandidates),iceGatherer.onlocalcandidate=function(evt){if(!(pc.usingBundle&&sdpMLineIndex>0)){var event=new Event("icecandidate");event.candidate={sdpMid:mid,sdpMLineIndex:sdpMLineIndex};var cand=evt.candidate,end=!cand||0===Object.keys(cand).length;if(end)"new"!==iceGatherer.state&&"gathering"!==iceGatherer.state||(iceGatherer.state="completed");else{"new"===iceGatherer.state&&(iceGatherer.state="gathering"),cand.component=1,cand.ufrag=iceGatherer.getLocalParameters().usernameFragment;var serializedCandidate=SDPUtils.writeCandidate(cand);event.candidate=Object.assign(event.candidate,SDPUtils.parseCandidate(serializedCandidate)),event.candidate.candidate=serializedCandidate,event.candidate.toJSON=function(){return{candidate:event.candidate.candidate,sdpMid:event.candidate.sdpMid,sdpMLineIndex:event.candidate.sdpMLineIndex,usernameFragment:event.candidate.usernameFragment}}}var sections=SDPUtils.getMediaSections(pc._localDescription.sdp);sections[event.candidate.sdpMLineIndex]+=end?"a=end-of-candidates\r\n":"a="+event.candidate.candidate+"\r\n",pc._localDescription.sdp=SDPUtils.getDescription(pc._localDescription.sdp)+sections.join("");var complete=pc.transceivers.every((function(transceiver){return transceiver.iceGatherer&&"completed"===transceiver.iceGatherer.state}));"gathering"!==pc.iceGatheringState&&(pc.iceGatheringState="gathering",pc._emitGatheringStateChange()),end||pc._dispatchEvent("icecandidate",event),complete&&(pc._dispatchEvent("icecandidate",new Event("icecandidate")),pc.iceGatheringState="complete",pc._emitGatheringStateChange())}},window.setTimeout((function(){bufferedCandidateEvents.forEach((function(e){iceGatherer.onlocalcandidate(e)}))}),0)}},RTCPeerConnection.prototype._createIceAndDtlsTransports=function(){var pc=this,iceTransport=new window.RTCIceTransport(null);iceTransport.onicestatechange=function(){pc._updateIceConnectionState(),pc._updateConnectionState()};var dtlsTransport=new window.RTCDtlsTransport(iceTransport);return dtlsTransport.ondtlsstatechange=function(){pc._updateConnectionState()},dtlsTransport.onerror=function(){Object.defineProperty(dtlsTransport,"state",{value:"failed",writable:!0}),pc._updateConnectionState()},{iceTransport:iceTransport,dtlsTransport:dtlsTransport}},RTCPeerConnection.prototype._disposeIceAndDtlsTransports=function(sdpMLineIndex){var iceGatherer=this.transceivers[sdpMLineIndex].iceGatherer;iceGatherer&&(delete iceGatherer.onlocalcandidate,delete this.transceivers[sdpMLineIndex].iceGatherer);var iceTransport=this.transceivers[sdpMLineIndex].iceTransport;iceTransport&&(delete iceTransport.onicestatechange,delete this.transceivers[sdpMLineIndex].iceTransport);var dtlsTransport=this.transceivers[sdpMLineIndex].dtlsTransport;dtlsTransport&&(delete dtlsTransport.ondtlsstatechange,delete dtlsTransport.onerror,delete this.transceivers[sdpMLineIndex].dtlsTransport)},RTCPeerConnection.prototype._transceive=function(transceiver,send,recv){var params=getCommonCapabilities(transceiver.localCapabilities,transceiver.remoteCapabilities);send&&transceiver.rtpSender&&(params.encodings=transceiver.sendEncodingParameters,params.rtcp={cname:SDPUtils.localCName,compound:transceiver.rtcpParameters.compound},transceiver.recvEncodingParameters.length&&(params.rtcp.ssrc=transceiver.recvEncodingParameters[0].ssrc),transceiver.rtpSender.send(params)),recv&&transceiver.rtpReceiver&¶ms.codecs.length>0&&("video"===transceiver.kind&&transceiver.recvEncodingParameters&&edgeVersion<15019&&transceiver.recvEncodingParameters.forEach((function(p){delete p.rtx})),transceiver.recvEncodingParameters.length?params.encodings=transceiver.recvEncodingParameters:params.encodings=[{}],params.rtcp={compound:transceiver.rtcpParameters.compound},transceiver.rtcpParameters.cname&&(params.rtcp.cname=transceiver.rtcpParameters.cname),transceiver.sendEncodingParameters.length&&(params.rtcp.ssrc=transceiver.sendEncodingParameters[0].ssrc),transceiver.rtpReceiver.receive(params))},RTCPeerConnection.prototype.setLocalDescription=function(description){var sections,sessionpart,pc=this;if(-1===["offer","answer"].indexOf(description.type))return Promise.reject(makeError("TypeError",'Unsupported type "'+description.type+'"'));if(!isActionAllowedInSignalingState("setLocalDescription",description.type,pc.signalingState)||pc._isClosed)return Promise.reject(makeError("InvalidStateError","Can not set local "+description.type+" in state "+pc.signalingState));if("offer"===description.type)sections=SDPUtils.splitSections(description.sdp),sessionpart=sections.shift(),sections.forEach((function(mediaSection,sdpMLineIndex){var caps=SDPUtils.parseRtpParameters(mediaSection);pc.transceivers[sdpMLineIndex].localCapabilities=caps})),pc.transceivers.forEach((function(transceiver,sdpMLineIndex){pc._gather(transceiver.mid,sdpMLineIndex)}));else if("answer"===description.type){sections=SDPUtils.splitSections(pc._remoteDescription.sdp),sessionpart=sections.shift();var isIceLite=SDPUtils.matchPrefix(sessionpart,"a=ice-lite").length>0;sections.forEach((function(mediaSection,sdpMLineIndex){var transceiver=pc.transceivers[sdpMLineIndex],iceGatherer=transceiver.iceGatherer,iceTransport=transceiver.iceTransport,dtlsTransport=transceiver.dtlsTransport,localCapabilities=transceiver.localCapabilities,remoteCapabilities=transceiver.remoteCapabilities;if(!(SDPUtils.isRejected(mediaSection)&&0===SDPUtils.matchPrefix(mediaSection,"a=bundle-only").length)&&!transceiver.rejected){var remoteIceParameters=SDPUtils.getIceParameters(mediaSection,sessionpart),remoteDtlsParameters=SDPUtils.getDtlsParameters(mediaSection,sessionpart);isIceLite&&(remoteDtlsParameters.role="server"),pc.usingBundle&&0!==sdpMLineIndex||(pc._gather(transceiver.mid,sdpMLineIndex),"new"===iceTransport.state&&iceTransport.start(iceGatherer,remoteIceParameters,isIceLite?"controlling":"controlled"),"new"===dtlsTransport.state&&dtlsTransport.start(remoteDtlsParameters));var params=getCommonCapabilities(localCapabilities,remoteCapabilities);pc._transceive(transceiver,params.codecs.length>0,!1)}}))}return pc._localDescription={type:description.type,sdp:description.sdp},"offer"===description.type?pc._updateSignalingState("have-local-offer"):pc._updateSignalingState("stable"),Promise.resolve()},RTCPeerConnection.prototype.setRemoteDescription=function(description){var pc=this;if(-1===["offer","answer"].indexOf(description.type))return Promise.reject(makeError("TypeError",'Unsupported type "'+description.type+'"'));if(!isActionAllowedInSignalingState("setRemoteDescription",description.type,pc.signalingState)||pc._isClosed)return Promise.reject(makeError("InvalidStateError","Can not set remote "+description.type+" in state "+pc.signalingState));var streams={};pc.remoteStreams.forEach((function(stream){streams[stream.id]=stream}));var receiverList=[],sections=SDPUtils.splitSections(description.sdp),sessionpart=sections.shift(),isIceLite=SDPUtils.matchPrefix(sessionpart,"a=ice-lite").length>0,usingBundle=SDPUtils.matchPrefix(sessionpart,"a=group:BUNDLE ").length>0;pc.usingBundle=usingBundle;var iceOptions=SDPUtils.matchPrefix(sessionpart,"a=ice-options:")[0];return pc.canTrickleIceCandidates=!!iceOptions&&iceOptions.substr(14).split(" ").indexOf("trickle")>=0,sections.forEach((function(mediaSection,sdpMLineIndex){var lines=SDPUtils.splitLines(mediaSection),kind=SDPUtils.getKind(mediaSection),rejected=SDPUtils.isRejected(mediaSection)&&0===SDPUtils.matchPrefix(mediaSection,"a=bundle-only").length,protocol=lines[0].substr(2).split(" ")[2],direction=SDPUtils.getDirection(mediaSection,sessionpart),remoteMsid=SDPUtils.parseMsid(mediaSection),mid=SDPUtils.getMid(mediaSection)||SDPUtils.generateIdentifier();if(rejected||"application"===kind&&("DTLS/SCTP"===protocol||"UDP/DTLS/SCTP"===protocol))pc.transceivers[sdpMLineIndex]={mid:mid,kind:kind,protocol:protocol,rejected:!0};else{var transceiver,iceGatherer,iceTransport,dtlsTransport,rtpReceiver,sendEncodingParameters,recvEncodingParameters,localCapabilities,track;!rejected&&pc.transceivers[sdpMLineIndex]&&pc.transceivers[sdpMLineIndex].rejected&&(pc.transceivers[sdpMLineIndex]=pc._createTransceiver(kind,!0));var remoteIceParameters,remoteDtlsParameters,remoteCapabilities=SDPUtils.parseRtpParameters(mediaSection);rejected||(remoteIceParameters=SDPUtils.getIceParameters(mediaSection,sessionpart),(remoteDtlsParameters=SDPUtils.getDtlsParameters(mediaSection,sessionpart)).role="client"),recvEncodingParameters=SDPUtils.parseRtpEncodingParameters(mediaSection);var rtcpParameters=SDPUtils.parseRtcpParameters(mediaSection),isComplete=SDPUtils.matchPrefix(mediaSection,"a=end-of-candidates",sessionpart).length>0,cands=SDPUtils.matchPrefix(mediaSection,"a=candidate:").map((function(cand){return SDPUtils.parseCandidate(cand)})).filter((function(cand){return 1===cand.component}));if(("offer"===description.type||"answer"===description.type)&&!rejected&&usingBundle&&sdpMLineIndex>0&&pc.transceivers[sdpMLineIndex]&&(pc._disposeIceAndDtlsTransports(sdpMLineIndex),pc.transceivers[sdpMLineIndex].iceGatherer=pc.transceivers[0].iceGatherer,pc.transceivers[sdpMLineIndex].iceTransport=pc.transceivers[0].iceTransport,pc.transceivers[sdpMLineIndex].dtlsTransport=pc.transceivers[0].dtlsTransport,pc.transceivers[sdpMLineIndex].rtpSender&&pc.transceivers[sdpMLineIndex].rtpSender.setTransport(pc.transceivers[0].dtlsTransport),pc.transceivers[sdpMLineIndex].rtpReceiver&&pc.transceivers[sdpMLineIndex].rtpReceiver.setTransport(pc.transceivers[0].dtlsTransport)),"offer"!==description.type||rejected){if("answer"===description.type&&!rejected){iceGatherer=(transceiver=pc.transceivers[sdpMLineIndex]).iceGatherer,iceTransport=transceiver.iceTransport,dtlsTransport=transceiver.dtlsTransport,rtpReceiver=transceiver.rtpReceiver,sendEncodingParameters=transceiver.sendEncodingParameters,localCapabilities=transceiver.localCapabilities,pc.transceivers[sdpMLineIndex].recvEncodingParameters=recvEncodingParameters,pc.transceivers[sdpMLineIndex].remoteCapabilities=remoteCapabilities,pc.transceivers[sdpMLineIndex].rtcpParameters=rtcpParameters,cands.length&&"new"===iceTransport.state&&(!isIceLite&&!isComplete||usingBundle&&0!==sdpMLineIndex?cands.forEach((function(candidate){maybeAddCandidate(transceiver.iceTransport,candidate)})):iceTransport.setRemoteCandidates(cands)),usingBundle&&0!==sdpMLineIndex||("new"===iceTransport.state&&iceTransport.start(iceGatherer,remoteIceParameters,"controlling"),"new"===dtlsTransport.state&&dtlsTransport.start(remoteDtlsParameters)),!getCommonCapabilities(transceiver.localCapabilities,transceiver.remoteCapabilities).codecs.filter((function(c){return"rtx"===c.name.toLowerCase()})).length&&transceiver.sendEncodingParameters[0].rtx&&delete transceiver.sendEncodingParameters[0].rtx,pc._transceive(transceiver,"sendrecv"===direction||"recvonly"===direction,"sendrecv"===direction||"sendonly"===direction),!rtpReceiver||"sendrecv"!==direction&&"sendonly"!==direction?delete transceiver.rtpReceiver:(track=rtpReceiver.track,remoteMsid?(streams[remoteMsid.stream]||(streams[remoteMsid.stream]=new window.MediaStream),addTrackToStreamAndFireEvent(track,streams[remoteMsid.stream]),receiverList.push([track,rtpReceiver,streams[remoteMsid.stream]])):(streams.default||(streams.default=new window.MediaStream),addTrackToStreamAndFireEvent(track,streams.default),receiverList.push([track,rtpReceiver,streams.default])))}}else{(transceiver=pc.transceivers[sdpMLineIndex]||pc._createTransceiver(kind)).mid=mid,transceiver.iceGatherer||(transceiver.iceGatherer=pc._createIceGatherer(sdpMLineIndex,usingBundle)),cands.length&&"new"===transceiver.iceTransport.state&&(!isComplete||usingBundle&&0!==sdpMLineIndex?cands.forEach((function(candidate){maybeAddCandidate(transceiver.iceTransport,candidate)})):transceiver.iceTransport.setRemoteCandidates(cands)),localCapabilities=window.RTCRtpReceiver.getCapabilities(kind),edgeVersion<15019&&(localCapabilities.codecs=localCapabilities.codecs.filter((function(codec){return"rtx"!==codec.name}))),sendEncodingParameters=transceiver.sendEncodingParameters||[{ssrc:1001*(2*sdpMLineIndex+2)}];var stream,isNewTrack=!1;if("sendrecv"===direction||"sendonly"===direction){if(isNewTrack=!transceiver.rtpReceiver,rtpReceiver=transceiver.rtpReceiver||new window.RTCRtpReceiver(transceiver.dtlsTransport,kind),isNewTrack)track=rtpReceiver.track,remoteMsid&&"-"===remoteMsid.stream||(remoteMsid?(streams[remoteMsid.stream]||(streams[remoteMsid.stream]=new window.MediaStream,Object.defineProperty(streams[remoteMsid.stream],"id",{get:function(){return remoteMsid.stream}})),Object.defineProperty(track,"id",{get:function(){return remoteMsid.track}}),stream=streams[remoteMsid.stream]):(streams.default||(streams.default=new window.MediaStream),stream=streams.default)),stream&&(addTrackToStreamAndFireEvent(track,stream),transceiver.associatedRemoteMediaStreams.push(stream)),receiverList.push([track,rtpReceiver,stream])}else transceiver.rtpReceiver&&transceiver.rtpReceiver.track&&(transceiver.associatedRemoteMediaStreams.forEach((function(s){var nativeTrack=s.getTracks().find((function(t){return t.id===transceiver.rtpReceiver.track.id}));nativeTrack&&function(track,stream){stream.removeTrack(track),stream.dispatchEvent(new window.MediaStreamTrackEvent("removetrack",{track:track}))}(nativeTrack,s)})),transceiver.associatedRemoteMediaStreams=[]);transceiver.localCapabilities=localCapabilities,transceiver.remoteCapabilities=remoteCapabilities,transceiver.rtpReceiver=rtpReceiver,transceiver.rtcpParameters=rtcpParameters,transceiver.sendEncodingParameters=sendEncodingParameters,transceiver.recvEncodingParameters=recvEncodingParameters,pc._transceive(pc.transceivers[sdpMLineIndex],!1,isNewTrack)}}})),void 0===pc._dtlsRole&&(pc._dtlsRole="offer"===description.type?"active":"passive"),pc._remoteDescription={type:description.type,sdp:description.sdp},"offer"===description.type?pc._updateSignalingState("have-remote-offer"):pc._updateSignalingState("stable"),Object.keys(streams).forEach((function(sid){var stream=streams[sid];if(stream.getTracks().length){if(-1===pc.remoteStreams.indexOf(stream)){pc.remoteStreams.push(stream);var event=new Event("addstream");event.stream=stream,window.setTimeout((function(){pc._dispatchEvent("addstream",event)}))}receiverList.forEach((function(item){var track=item[0],receiver=item[1];stream.id===item[2].id&&fireAddTrack(pc,track,receiver,[stream])}))}})),receiverList.forEach((function(item){item[2]||fireAddTrack(pc,item[0],item[1],[])})),window.setTimeout((function(){pc&&pc.transceivers&&pc.transceivers.forEach((function(transceiver){transceiver.iceTransport&&"new"===transceiver.iceTransport.state&&transceiver.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),transceiver.iceTransport.addRemoteCandidate({}))}))}),4e3),Promise.resolve()},RTCPeerConnection.prototype.close=function(){this.transceivers.forEach((function(transceiver){transceiver.iceTransport&&transceiver.iceTransport.stop(),transceiver.dtlsTransport&&transceiver.dtlsTransport.stop(),transceiver.rtpSender&&transceiver.rtpSender.stop(),transceiver.rtpReceiver&&transceiver.rtpReceiver.stop()})),this._isClosed=!0,this._updateSignalingState("closed")},RTCPeerConnection.prototype._updateSignalingState=function(newState){this.signalingState=newState;var event=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",event)},RTCPeerConnection.prototype._maybeFireNegotiationNeeded=function(){var pc=this;"stable"===this.signalingState&&!0!==this.needNegotiation&&(this.needNegotiation=!0,window.setTimeout((function(){if(pc.needNegotiation){pc.needNegotiation=!1;var event=new Event("negotiationneeded");pc._dispatchEvent("negotiationneeded",event)}}),0))},RTCPeerConnection.prototype._updateIceConnectionState=function(){var newState,states={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(transceiver){transceiver.iceTransport&&!transceiver.rejected&&states[transceiver.iceTransport.state]++})),newState="new",states.failed>0?newState="failed":states.checking>0?newState="checking":states.disconnected>0?newState="disconnected":states.new>0?newState="new":states.connected>0?newState="connected":states.completed>0&&(newState="completed"),newState!==this.iceConnectionState){this.iceConnectionState=newState;var event=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",event)}},RTCPeerConnection.prototype._updateConnectionState=function(){var newState,states={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(transceiver){transceiver.iceTransport&&transceiver.dtlsTransport&&!transceiver.rejected&&(states[transceiver.iceTransport.state]++,states[transceiver.dtlsTransport.state]++)})),states.connected+=states.completed,newState="new",states.failed>0?newState="failed":states.connecting>0?newState="connecting":states.disconnected>0?newState="disconnected":states.new>0?newState="new":states.connected>0&&(newState="connected"),newState!==this.connectionState){this.connectionState=newState;var event=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",event)}},RTCPeerConnection.prototype.createOffer=function(){var pc=this;if(pc._isClosed)return Promise.reject(makeError("InvalidStateError","Can not call createOffer after close"));var numAudioTracks=pc.transceivers.filter((function(t){return"audio"===t.kind})).length,numVideoTracks=pc.transceivers.filter((function(t){return"video"===t.kind})).length,offerOptions=arguments[0];if(offerOptions){if(offerOptions.mandatory||offerOptions.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");void 0!==offerOptions.offerToReceiveAudio&&(numAudioTracks=!0===offerOptions.offerToReceiveAudio?1:!1===offerOptions.offerToReceiveAudio?0:offerOptions.offerToReceiveAudio),void 0!==offerOptions.offerToReceiveVideo&&(numVideoTracks=!0===offerOptions.offerToReceiveVideo?1:!1===offerOptions.offerToReceiveVideo?0:offerOptions.offerToReceiveVideo)}for(pc.transceivers.forEach((function(transceiver){"audio"===transceiver.kind?--numAudioTracks<0&&(transceiver.wantReceive=!1):"video"===transceiver.kind&&--numVideoTracks<0&&(transceiver.wantReceive=!1)}));numAudioTracks>0||numVideoTracks>0;)numAudioTracks>0&&(pc._createTransceiver("audio"),numAudioTracks--),numVideoTracks>0&&(pc._createTransceiver("video"),numVideoTracks--);var sdp=SDPUtils.writeSessionBoilerplate(pc._sdpSessionId,pc._sdpSessionVersion++);pc.transceivers.forEach((function(transceiver,sdpMLineIndex){var track=transceiver.track,kind=transceiver.kind,mid=transceiver.mid||SDPUtils.generateIdentifier();transceiver.mid=mid,transceiver.iceGatherer||(transceiver.iceGatherer=pc._createIceGatherer(sdpMLineIndex,pc.usingBundle));var localCapabilities=window.RTCRtpSender.getCapabilities(kind);edgeVersion<15019&&(localCapabilities.codecs=localCapabilities.codecs.filter((function(codec){return"rtx"!==codec.name}))),localCapabilities.codecs.forEach((function(codec){"H264"===codec.name&&void 0===codec.parameters["level-asymmetry-allowed"]&&(codec.parameters["level-asymmetry-allowed"]="1"),transceiver.remoteCapabilities&&transceiver.remoteCapabilities.codecs&&transceiver.remoteCapabilities.codecs.forEach((function(remoteCodec){codec.name.toLowerCase()===remoteCodec.name.toLowerCase()&&codec.clockRate===remoteCodec.clockRate&&(codec.preferredPayloadType=remoteCodec.payloadType)}))})),localCapabilities.headerExtensions.forEach((function(hdrExt){(transceiver.remoteCapabilities&&transceiver.remoteCapabilities.headerExtensions||[]).forEach((function(rHdrExt){hdrExt.uri===rHdrExt.uri&&(hdrExt.id=rHdrExt.id)}))}));var sendEncodingParameters=transceiver.sendEncodingParameters||[{ssrc:1001*(2*sdpMLineIndex+1)}];track&&edgeVersion>=15019&&"video"===kind&&!sendEncodingParameters[0].rtx&&(sendEncodingParameters[0].rtx={ssrc:sendEncodingParameters[0].ssrc+1}),transceiver.wantReceive&&(transceiver.rtpReceiver=new window.RTCRtpReceiver(transceiver.dtlsTransport,kind)),transceiver.localCapabilities=localCapabilities,transceiver.sendEncodingParameters=sendEncodingParameters})),"max-compat"!==pc._config.bundlePolicy&&(sdp+="a=group:BUNDLE "+pc.transceivers.map((function(t){return t.mid})).join(" ")+"\r\n"),sdp+="a=ice-options:trickle\r\n",pc.transceivers.forEach((function(transceiver,sdpMLineIndex){sdp+=writeMediaSection(transceiver,transceiver.localCapabilities,"offer",transceiver.stream,pc._dtlsRole),sdp+="a=rtcp-rsize\r\n",!transceiver.iceGatherer||"new"===pc.iceGatheringState||0!==sdpMLineIndex&&pc.usingBundle||(transceiver.iceGatherer.getLocalCandidates().forEach((function(cand){cand.component=1,sdp+="a="+SDPUtils.writeCandidate(cand)+"\r\n"})),"completed"===transceiver.iceGatherer.state&&(sdp+="a=end-of-candidates\r\n"))}));var desc=new window.RTCSessionDescription({type:"offer",sdp:sdp});return Promise.resolve(desc)},RTCPeerConnection.prototype.createAnswer=function(){var pc=this;if(pc._isClosed)return Promise.reject(makeError("InvalidStateError","Can not call createAnswer after close"));if("have-remote-offer"!==pc.signalingState&&"have-local-pranswer"!==pc.signalingState)return Promise.reject(makeError("InvalidStateError","Can not call createAnswer in signalingState "+pc.signalingState));var sdp=SDPUtils.writeSessionBoilerplate(pc._sdpSessionId,pc._sdpSessionVersion++);pc.usingBundle&&(sdp+="a=group:BUNDLE "+pc.transceivers.map((function(t){return t.mid})).join(" ")+"\r\n"),sdp+="a=ice-options:trickle\r\n";var mediaSectionsInOffer=SDPUtils.getMediaSections(pc._remoteDescription.sdp).length;pc.transceivers.forEach((function(transceiver,sdpMLineIndex){if(!(sdpMLineIndex+1>mediaSectionsInOffer)){if(transceiver.rejected)return"application"===transceiver.kind?"DTLS/SCTP"===transceiver.protocol?sdp+="m=application 0 DTLS/SCTP 5000\r\n":sdp+="m=application 0 "+transceiver.protocol+" webrtc-datachannel\r\n":"audio"===transceiver.kind?sdp+="m=audio 0 UDP/TLS/RTP/SAVPF 0\r\na=rtpmap:0 PCMU/8000\r\n":"video"===transceiver.kind&&(sdp+="m=video 0 UDP/TLS/RTP/SAVPF 120\r\na=rtpmap:120 VP8/90000\r\n"),void(sdp+="c=IN IP4 0.0.0.0\r\na=inactive\r\na=mid:"+transceiver.mid+"\r\n");var localTrack;if(transceiver.stream)"audio"===transceiver.kind?localTrack=transceiver.stream.getAudioTracks()[0]:"video"===transceiver.kind&&(localTrack=transceiver.stream.getVideoTracks()[0]),localTrack&&edgeVersion>=15019&&"video"===transceiver.kind&&!transceiver.sendEncodingParameters[0].rtx&&(transceiver.sendEncodingParameters[0].rtx={ssrc:transceiver.sendEncodingParameters[0].ssrc+1});var commonCapabilities=getCommonCapabilities(transceiver.localCapabilities,transceiver.remoteCapabilities);!commonCapabilities.codecs.filter((function(c){return"rtx"===c.name.toLowerCase()})).length&&transceiver.sendEncodingParameters[0].rtx&&delete transceiver.sendEncodingParameters[0].rtx,sdp+=writeMediaSection(transceiver,commonCapabilities,"answer",transceiver.stream,pc._dtlsRole),transceiver.rtcpParameters&&transceiver.rtcpParameters.reducedSize&&(sdp+="a=rtcp-rsize\r\n")}}));var desc=new window.RTCSessionDescription({type:"answer",sdp:sdp});return Promise.resolve(desc)},RTCPeerConnection.prototype.addIceCandidate=function(candidate){var sections,pc=this;return candidate&&void 0===candidate.sdpMLineIndex&&!candidate.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise((function(resolve,reject){if(!pc._remoteDescription)return reject(makeError("InvalidStateError","Can not add ICE candidate without a remote description"));if(candidate&&""!==candidate.candidate){var sdpMLineIndex=candidate.sdpMLineIndex;if(candidate.sdpMid)for(var i=0;i<pc.transceivers.length;i++)if(pc.transceivers[i].mid===candidate.sdpMid){sdpMLineIndex=i;break}var transceiver=pc.transceivers[sdpMLineIndex];if(!transceiver)return reject(makeError("OperationError","Can not add ICE candidate"));if(transceiver.rejected)return resolve();var cand=Object.keys(candidate.candidate).length>0?SDPUtils.parseCandidate(candidate.candidate):{};if("tcp"===cand.protocol&&(0===cand.port||9===cand.port))return resolve();if(cand.component&&1!==cand.component)return resolve();if((0===sdpMLineIndex||sdpMLineIndex>0&&transceiver.iceTransport!==pc.transceivers[0].iceTransport)&&!maybeAddCandidate(transceiver.iceTransport,cand))return reject(makeError("OperationError","Can not add ICE candidate"));var candidateString=candidate.candidate.trim();0===candidateString.indexOf("a=")&&(candidateString=candidateString.substr(2)),(sections=SDPUtils.getMediaSections(pc._remoteDescription.sdp))[sdpMLineIndex]+="a="+(cand.type?candidateString:"end-of-candidates")+"\r\n",pc._remoteDescription.sdp=SDPUtils.getDescription(pc._remoteDescription.sdp)+sections.join("")}else for(var j=0;j<pc.transceivers.length&&(pc.transceivers[j].rejected||(pc.transceivers[j].iceTransport.addRemoteCandidate({}),(sections=SDPUtils.getMediaSections(pc._remoteDescription.sdp))[j]+="a=end-of-candidates\r\n",pc._remoteDescription.sdp=SDPUtils.getDescription(pc._remoteDescription.sdp)+sections.join(""),!pc.usingBundle));j++);resolve()}))},RTCPeerConnection.prototype.getStats=function(selector){if(selector&&selector instanceof window.MediaStreamTrack){var senderOrReceiver=null;if(this.transceivers.forEach((function(transceiver){transceiver.rtpSender&&transceiver.rtpSender.track===selector?senderOrReceiver=transceiver.rtpSender:transceiver.rtpReceiver&&transceiver.rtpReceiver.track===selector&&(senderOrReceiver=transceiver.rtpReceiver)})),!senderOrReceiver)throw makeError("InvalidAccessError","Invalid selector.");return senderOrReceiver.getStats()}var promises=[];return this.transceivers.forEach((function(transceiver){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach((function(method){transceiver[method]&&promises.push(transceiver[method].getStats())}))})),Promise.all(promises).then((function(allStats){var results=new Map;return allStats.forEach((function(stats){stats.forEach((function(stat){results.set(stat.id,stat)}))})),results}))};["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach((function(ortcObjectName){var obj=window[ortcObjectName];if(obj&&obj.prototype&&obj.prototype.getStats){var nativeGetstats=obj.prototype.getStats;obj.prototype.getStats=function(){return nativeGetstats.apply(this).then((function(nativeStats){var mapStats=new Map;return Object.keys(nativeStats).forEach((function(id){var stat;nativeStats[id].type={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[(stat=nativeStats[id]).type]||stat.type,mapStats.set(id,nativeStats[id])})),mapStats}))}}}));var methods=["createOffer","createAnswer"];return methods.forEach((function(method){var nativeMethod=RTCPeerConnection.prototype[method];RTCPeerConnection.prototype[method]=function(){var args=arguments;return"function"==typeof args[0]||"function"==typeof args[1]?nativeMethod.apply(this,[arguments[2]]).then((function(description){"function"==typeof args[0]&&args[0].apply(null,[description])}),(function(error){"function"==typeof args[1]&&args[1].apply(null,[error])})):nativeMethod.apply(this,arguments)}})),(methods=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach((function(method){var nativeMethod=RTCPeerConnection.prototype[method];RTCPeerConnection.prototype[method]=function(){var args=arguments;return"function"==typeof args[1]||"function"==typeof args[2]?nativeMethod.apply(this,arguments).then((function(){"function"==typeof args[1]&&args[1].apply(null)}),(function(error){"function"==typeof args[2]&&args[2].apply(null,[error])})):nativeMethod.apply(this,arguments)}})),["getStats"].forEach((function(method){var nativeMethod=RTCPeerConnection.prototype[method];RTCPeerConnection.prototype[method]=function(){var args=arguments;return"function"==typeof args[1]?nativeMethod.apply(this,arguments).then((function(){"function"==typeof args[1]&&args[1].apply(null)})):nativeMethod.apply(this,arguments)}})),RTCPeerConnection}},{sdp:38}],38:[function(require,module,exports){"use strict";function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}var SDPUtils={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};SDPUtils.localCName=SDPUtils.generateIdentifier(),SDPUtils.splitLines=function(blob){return blob.trim().split("\n").map((function(line){return line.trim()}))},SDPUtils.splitSections=function(blob){return blob.split("\nm=").map((function(part,index){return(index>0?"m="+part:part).trim()+"\r\n"}))},SDPUtils.getDescription=function(blob){var sections=SDPUtils.splitSections(blob);return sections&§ions[0]},SDPUtils.getMediaSections=function(blob){var sections=SDPUtils.splitSections(blob);return sections.shift(),sections},SDPUtils.matchPrefix=function(blob,prefix){return SDPUtils.splitLines(blob).filter((function(line){return 0===line.indexOf(prefix)}))},SDPUtils.parseCandidate=function(line){for(var parts,candidate={foundation:(parts=0===line.indexOf("a=candidate:")?line.substring(12).split(" "):line.substring(10).split(" "))[0],component:parseInt(parts[1],10),protocol:parts[2].toLowerCase(),priority:parseInt(parts[3],10),ip:parts[4],address:parts[4],port:parseInt(parts[5],10),type:parts[7]},i=8;i<parts.length;i+=2)switch(parts[i]){case"raddr":candidate.relatedAddress=parts[i+1];break;case"rport":candidate.relatedPort=parseInt(parts[i+1],10);break;case"tcptype":candidate.tcpType=parts[i+1];break;case"ufrag":candidate.ufrag=parts[i+1],candidate.usernameFragment=parts[i+1];break;default:candidate[parts[i]]=parts[i+1]}return candidate},SDPUtils.writeCandidate=function(candidate){var sdp=[];sdp.push(candidate.foundation),sdp.push(candidate.component),sdp.push(candidate.protocol.toUpperCase()),sdp.push(candidate.priority),sdp.push(candidate.address||candidate.ip),sdp.push(candidate.port);var type=candidate.type;return sdp.push("typ"),sdp.push(type),"host"!==type&&candidate.relatedAddress&&candidate.relatedPort&&(sdp.push("raddr"),sdp.push(candidate.relatedAddress),sdp.push("rport"),sdp.push(candidate.relatedPort)),candidate.tcpType&&"tcp"===candidate.protocol.toLowerCase()&&(sdp.push("tcptype"),sdp.push(candidate.tcpType)),(candidate.usernameFragment||candidate.ufrag)&&(sdp.push("ufrag"),sdp.push(candidate.usernameFragment||candidate.ufrag)),"candidate:"+sdp.join(" ")},SDPUtils.parseIceOptions=function(line){return line.substr(14).split(" ")},SDPUtils.parseRtpMap=function(line){var parts=line.substr(9).split(" "),parsed={payloadType:parseInt(parts.shift(),10)};return parts=parts[0].split("/"),parsed.name=parts[0],parsed.clockRate=parseInt(parts[1],10),parsed.channels=3===parts.length?parseInt(parts[2],10):1,parsed.numChannels=parsed.channels,parsed},SDPUtils.writeRtpMap=function(codec){var pt=codec.payloadType;void 0!==codec.preferredPayloadType&&(pt=codec.preferredPayloadType);var channels=codec.channels||codec.numChannels||1;return"a=rtpmap:"+pt+" "+codec.name+"/"+codec.clockRate+(1!==channels?"/"+channels:"")+"\r\n"},SDPUtils.parseExtmap=function(line){var parts=line.substr(9).split(" ");return{id:parseInt(parts[0],10),direction:parts[0].indexOf("/")>0?parts[0].split("/")[1]:"sendrecv",uri:parts[1]}},SDPUtils.writeExtmap=function(headerExtension){return"a=extmap:"+(headerExtension.id||headerExtension.preferredId)+(headerExtension.direction&&"sendrecv"!==headerExtension.direction?"/"+headerExtension.direction:"")+" "+headerExtension.uri+"\r\n"},SDPUtils.parseFmtp=function(line){for(var kv,parsed={},parts=line.substr(line.indexOf(" ")+1).split(";"),j=0;j<parts.length;j++)parsed[(kv=parts[j].trim().split("="))[0].trim()]=kv[1];return parsed},SDPUtils.writeFmtp=function(codec){var line="",pt=codec.payloadType;if(void 0!==codec.preferredPayloadType&&(pt=codec.preferredPayloadType),codec.parameters&&Object.keys(codec.parameters).length){var params=[];Object.keys(codec.parameters).forEach((function(param){codec.parameters[param]?params.push(param+"="+codec.parameters[param]):params.push(param)})),line+="a=fmtp:"+pt+" "+params.join(";")+"\r\n"}return line},SDPUtils.parseRtcpFb=function(line){var parts=line.substr(line.indexOf(" ")+1).split(" ");return{type:parts.shift(),parameter:parts.join(" ")}},SDPUtils.writeRtcpFb=function(codec){var lines="",pt=codec.payloadType;return void 0!==codec.preferredPayloadType&&(pt=codec.preferredPayloadType),codec.rtcpFeedback&&codec.rtcpFeedback.length&&codec.rtcpFeedback.forEach((function(fb){lines+="a=rtcp-fb:"+pt+" "+fb.type+(fb.parameter&&fb.parameter.length?" "+fb.parameter:"")+"\r\n"})),lines},SDPUtils.parseSsrcMedia=function(line){var sp=line.indexOf(" "),parts={ssrc:parseInt(line.substr(7,sp-7),10)},colon=line.indexOf(":",sp);return colon>-1?(parts.attribute=line.substr(sp+1,colon-sp-1),parts.value=line.substr(colon+1)):parts.attribute=line.substr(sp+1),parts},SDPUtils.parseSsrcGroup=function(line){var parts=line.substr(13).split(" ");return{semantics:parts.shift(),ssrcs:parts.map((function(ssrc){return parseInt(ssrc,10)}))}},SDPUtils.getMid=function(mediaSection){var mid=SDPUtils.matchPrefix(mediaSection,"a=mid:")[0];if(mid)return mid.substr(6)},SDPUtils.parseFingerprint=function(line){var parts=line.substr(14).split(" ");return{algorithm:parts[0].toLowerCase(),value:parts[1]}},SDPUtils.getDtlsParameters=function(mediaSection,sessionpart){return{role:"auto",fingerprints:SDPUtils.matchPrefix(mediaSection+sessionpart,"a=fingerprint:").map(SDPUtils.parseFingerprint)}},SDPUtils.writeDtlsParameters=function(params,setupType){var sdp="a=setup:"+setupType+"\r\n";return params.fingerprints.forEach((function(fp){sdp+="a=fingerprint:"+fp.algorithm+" "+fp.value+"\r\n"})),sdp},SDPUtils.parseCryptoLine=function(line){var parts=line.substr(9).split(" ");return{tag:parseInt(parts[0],10),cryptoSuite:parts[1],keyParams:parts[2],sessionParams:parts.slice(3)}},SDPUtils.writeCryptoLine=function(parameters){return"a=crypto:"+parameters.tag+" "+parameters.cryptoSuite+" "+("object"===_typeof(parameters.keyParams)?SDPUtils.writeCryptoKeyParams(parameters.keyParams):parameters.keyParams)+(parameters.sessionParams?" "+parameters.sessionParams.join(" "):"")+"\r\n"},SDPUtils.parseCryptoKeyParams=function(keyParams){if(0!==keyParams.indexOf("inline:"))return null;var parts=keyParams.substr(7).split("|");return{keyMethod:"inline",keySalt:parts[0],lifeTime:parts[1],mkiValue:parts[2]?parts[2].split(":")[0]:void 0,mkiLength:parts[2]?parts[2].split(":")[1]:void 0}},SDPUtils.writeCryptoKeyParams=function(keyParams){return keyParams.keyMethod+":"+keyParams.keySalt+(keyParams.lifeTime?"|"+keyParams.lifeTime:"")+(keyParams.mkiValue&&keyParams.mkiLength?"|"+keyParams.mkiValue+":"+keyParams.mkiLength:"")},SDPUtils.getCryptoParameters=function(mediaSection,sessionpart){return SDPUtils.matchPrefix(mediaSection+sessionpart,"a=crypto:").map(SDPUtils.parseCryptoLine)},SDPUtils.getIceParameters=function(mediaSection,sessionpart){var ufrag=SDPUtils.matchPrefix(mediaSection+sessionpart,"a=ice-ufrag:")[0],pwd=SDPUtils.matchPrefix(mediaSection+sessionpart,"a=ice-pwd:")[0];return ufrag&&pwd?{usernameFragment:ufrag.substr(12),password:pwd.substr(10)}:null},SDPUtils.writeIceParameters=function(params){return"a=ice-ufrag:"+params.usernameFragment+"\r\na=ice-pwd:"+params.password+"\r\n"},SDPUtils.parseRtpParameters=function(mediaSection){for(var description={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},mline=SDPUtils.splitLines(mediaSection)[0].split(" "),i=3;i<mline.length;i++){var pt=mline[i],rtpmapline=SDPUtils.matchPrefix(mediaSection,"a=rtpmap:"+pt+" ")[0];if(rtpmapline){var codec=SDPUtils.parseRtpMap(rtpmapline),fmtps=SDPUtils.matchPrefix(mediaSection,"a=fmtp:"+pt+" ");switch(codec.parameters=fmtps.length?SDPUtils.parseFmtp(fmtps[0]):{},codec.rtcpFeedback=SDPUtils.matchPrefix(mediaSection,"a=rtcp-fb:"+pt+" ").map(SDPUtils.parseRtcpFb),description.codecs.push(codec),codec.name.toUpperCase()){case"RED":case"ULPFEC":description.fecMechanisms.push(codec.name.toUpperCase())}}}return SDPUtils.matchPrefix(mediaSection,"a=extmap:").forEach((function(line){description.headerExtensions.push(SDPUtils.parseExtmap(line))})),description},SDPUtils.writeRtpDescription=function(kind,caps){var sdp="";sdp+="m="+kind+" ",sdp+=caps.codecs.length>0?"9":"0",sdp+=" UDP/TLS/RTP/SAVPF ",sdp+=caps.codecs.map((function(codec){return void 0!==codec.preferredPayloadType?codec.preferredPayloadType:codec.payloadType})).join(" ")+"\r\n",sdp+="c=IN IP4 0.0.0.0\r\n",sdp+="a=rtcp:9 IN IP4 0.0.0.0\r\n",caps.codecs.forEach((function(codec){sdp+=SDPUtils.writeRtpMap(codec),sdp+=SDPUtils.writeFmtp(codec),sdp+=SDPUtils.writeRtcpFb(codec)}));var maxptime=0;return caps.codecs.forEach((function(codec){codec.maxptime>maxptime&&(maxptime=codec.maxptime)})),maxptime>0&&(sdp+="a=maxptime:"+maxptime+"\r\n"),sdp+="a=rtcp-mux\r\n",caps.headerExtensions&&caps.headerExtensions.forEach((function(extension){sdp+=SDPUtils.writeExtmap(extension)})),sdp},SDPUtils.parseRtpEncodingParameters=function(mediaSection){var secondarySsrc,encodingParameters=[],description=SDPUtils.parseRtpParameters(mediaSection),hasRed=-1!==description.fecMechanisms.indexOf("RED"),hasUlpfec=-1!==description.fecMechanisms.indexOf("ULPFEC"),ssrcs=SDPUtils.matchPrefix(mediaSection,"a=ssrc:").map((function(line){return SDPUtils.parseSsrcMedia(line)})).filter((function(parts){return"cname"===parts.attribute})),primarySsrc=ssrcs.length>0&&ssrcs[0].ssrc,flows=SDPUtils.matchPrefix(mediaSection,"a=ssrc-group:FID").map((function(line){return line.substr(17).split(" ").map((function(part){return parseInt(part,10)}))}));flows.length>0&&flows[0].length>1&&flows[0][0]===primarySsrc&&(secondarySsrc=flows[0][1]),description.codecs.forEach((function(codec){if("RTX"===codec.name.toUpperCase()&&codec.parameters.apt){var encParam={ssrc:primarySsrc,codecPayloadType:parseInt(codec.parameters.apt,10)};primarySsrc&&secondarySsrc&&(encParam.rtx={ssrc:secondarySsrc}),encodingParameters.push(encParam),hasRed&&((encParam=JSON.parse(JSON.stringify(encParam))).fec={ssrc:primarySsrc,mechanism:hasUlpfec?"red+ulpfec":"red"},encodingParameters.push(encParam))}})),0===encodingParameters.length&&primarySsrc&&encodingParameters.push({ssrc:primarySsrc});var bandwidth=SDPUtils.matchPrefix(mediaSection,"b=");return bandwidth.length&&(bandwidth=0===bandwidth[0].indexOf("b=TIAS:")?parseInt(bandwidth[0].substr(7),10):0===bandwidth[0].indexOf("b=AS:")?1e3*parseInt(bandwidth[0].substr(5),10)*.95-16e3:void 0,encodingParameters.forEach((function(params){params.maxBitrate=bandwidth}))),encodingParameters},SDPUtils.parseRtcpParameters=function(mediaSection){var rtcpParameters={},remoteSsrc=SDPUtils.matchPrefix(mediaSection,"a=ssrc:").map((function(line){return SDPUtils.parseSsrcMedia(line)})).filter((function(obj){return"cname"===obj.attribute}))[0];remoteSsrc&&(rtcpParameters.cname=remoteSsrc.value,rtcpParameters.ssrc=remoteSsrc.ssrc);var rsize=SDPUtils.matchPrefix(mediaSection,"a=rtcp-rsize");rtcpParameters.reducedSize=rsize.length>0,rtcpParameters.compound=0===rsize.length;var mux=SDPUtils.matchPrefix(mediaSection,"a=rtcp-mux");return rtcpParameters.mux=mux.length>0,rtcpParameters},SDPUtils.parseMsid=function(mediaSection){var parts,spec=SDPUtils.matchPrefix(mediaSection,"a=msid:");if(1===spec.length)return{stream:(parts=spec[0].substr(7).split(" "))[0],track:parts[1]};var planB=SDPUtils.matchPrefix(mediaSection,"a=ssrc:").map((function(line){return SDPUtils.parseSsrcMedia(line)})).filter((function(msidParts){return"msid"===msidParts.attribute}));return planB.length>0?{stream:(parts=planB[0].value.split(" "))[0],track:parts[1]}:void 0},SDPUtils.parseSctpDescription=function(mediaSection){var maxMessageSize,mline=SDPUtils.parseMLine(mediaSection),maxSizeLine=SDPUtils.matchPrefix(mediaSection,"a=max-message-size:");maxSizeLine.length>0&&(maxMessageSize=parseInt(maxSizeLine[0].substr(19),10)),isNaN(maxMessageSize)&&(maxMessageSize=65536);var sctpPort=SDPUtils.matchPrefix(mediaSection,"a=sctp-port:");if(sctpPort.length>0)return{port:parseInt(sctpPort[0].substr(12),10),protocol:mline.fmt,maxMessageSize:maxMessageSize};if(SDPUtils.matchPrefix(mediaSection,"a=sctpmap:").length>0){var parts=SDPUtils.matchPrefix(mediaSection,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(parts[0],10),protocol:parts[1],maxMessageSize:maxMessageSize}}},SDPUtils.writeSctpDescription=function(media,sctp){var output=[];return output="DTLS/SCTP"!==media.protocol?["m="+media.kind+" 9 "+media.protocol+" "+sctp.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+sctp.port+"\r\n"]:["m="+media.kind+" 9 "+media.protocol+" "+sctp.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+sctp.port+" "+sctp.protocol+" 65535\r\n"],void 0!==sctp.maxMessageSize&&output.push("a=max-message-size:"+sctp.maxMessageSize+"\r\n"),output.join("")},SDPUtils.generateSessionId=function(){return Math.random().toString().substr(2,21)},SDPUtils.writeSessionBoilerplate=function(sessId,sessVer,sessUser){var version=void 0!==sessVer?sessVer:2;return"v=0\r\no="+(sessUser||"thisisadapterortc")+" "+(sessId||SDPUtils.generateSessionId())+" "+version+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},SDPUtils.writeMediaSection=function(transceiver,caps,type,stream){var sdp=SDPUtils.writeRtpDescription(transceiver.kind,caps);if(sdp+=SDPUtils.writeIceParameters(transceiver.iceGatherer.getLocalParameters()),sdp+=SDPUtils.writeDtlsParameters(transceiver.dtlsTransport.getLocalParameters(),"offer"===type?"actpass":"active"),sdp+="a=mid:"+transceiver.mid+"\r\n",transceiver.direction?sdp+="a="+transceiver.direction+"\r\n":transceiver.rtpSender&&transceiver.rtpReceiver?sdp+="a=sendrecv\r\n":transceiver.rtpSender?sdp+="a=sendonly\r\n":transceiver.rtpReceiver?sdp+="a=recvonly\r\n":sdp+="a=inactive\r\n",transceiver.rtpSender){var msid="msid:"+stream.id+" "+transceiver.rtpSender.track.id+"\r\n";sdp+="a="+msid,sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].ssrc+" "+msid,transceiver.sendEncodingParameters[0].rtx&&(sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].rtx.ssrc+" "+msid,sdp+="a=ssrc-group:FID "+transceiver.sendEncodingParameters[0].ssrc+" "+transceiver.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].ssrc+" cname:"+SDPUtils.localCName+"\r\n",transceiver.rtpSender&&transceiver.sendEncodingParameters[0].rtx&&(sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].rtx.ssrc+" cname:"+SDPUtils.localCName+"\r\n"),sdp},SDPUtils.getDirection=function(mediaSection,sessionpart){for(var lines=SDPUtils.splitLines(mediaSection),i=0;i<lines.length;i++)switch(lines[i]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return lines[i].substr(2)}return sessionpart?SDPUtils.getDirection(sessionpart):"sendrecv"},SDPUtils.getKind=function(mediaSection){return SDPUtils.splitLines(mediaSection)[0].split(" ")[0].substr(2)},SDPUtils.isRejected=function(mediaSection){return"0"===mediaSection.split(" ",2)[1]},SDPUtils.parseMLine=function(mediaSection){var parts=SDPUtils.splitLines(mediaSection)[0].substr(2).split(" ");return{kind:parts[0],port:parseInt(parts[1],10),protocol:parts[2],fmt:parts.slice(3).join(" ")}},SDPUtils.parseOLine=function(mediaSection){var parts=SDPUtils.matchPrefix(mediaSection,"o=")[0].substr(2).split(" ");return{username:parts[0],sessionId:parts[1],sessionVersion:parseInt(parts[2],10),netType:parts[3],addressType:parts[4],address:parts[5]}},SDPUtils.isValidSDP=function(blob){if("string"!=typeof blob||0===blob.length)return!1;for(var lines=SDPUtils.splitLines(blob),i=0;i<lines.length;i++)if(lines[i].length<2||"="!==lines[i].charAt(1))return!1;return!0},"object"===("undefined"==typeof module?"undefined":_typeof(module))&&(module.exports=SDPUtils)},{}],39:[function(require,module,exports){(function(setImmediate,clearImmediate){(function(){var nextTick=require("process/browser.js").nextTick,apply=Function.prototype.apply,slice=Array.prototype.slice,immediateIds={},nextImmediateId=0;function Timeout(id,clearFn){this._id=id,this._clearFn=clearFn}exports.setTimeout=function(){return new Timeout(apply.call(setTimeout,window,arguments),clearTimeout)},exports.setInterval=function(){return new Timeout(apply.call(setInterval,window,arguments),clearInterval)},exports.clearTimeout=exports.clearInterval=function(timeout){timeout.close()},Timeout.prototype.unref=Timeout.prototype.ref=function(){},Timeout.prototype.close=function(){this._clearFn.call(window,this._id)},exports.enroll=function(item,msecs){clearTimeout(item._idleTimeoutId),item._idleTimeout=msecs},exports.unenroll=function(item){clearTimeout(item._idleTimeoutId),item._idleTimeout=-1},exports._unrefActive=exports.active=function(item){clearTimeout(item._idleTimeoutId);var msecs=item._idleTimeout;msecs>=0&&(item._idleTimeoutId=setTimeout((function(){item._onTimeout&&item._onTimeout()}),msecs))},exports.setImmediate="function"==typeof setImmediate?setImmediate:function(fn){var id=nextImmediateId++,args=!(arguments.length<2)&&slice.call(arguments,1);return immediateIds[id]=!0,nextTick((function(){immediateIds[id]&&(args?fn.apply(null,args):fn.call(null),exports.clearImmediate(id))})),id},exports.clearImmediate="function"==typeof clearImmediate?clearImmediate:function(id){delete immediateIds[id]}}).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate)},{"process/browser.js":35,timers:39}],40:[function(require,module,exports){(function(global){(function(){function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}var __extends,__assign,__rest,__decorate,__param,__esDecorate,__runInitializers,__propKey,__setFunctionName,__metadata,__awaiter,__generator,__exportStar,__values,__read,__spread,__spreadArrays,__spreadArray,_await,__asyncGenerator,__asyncDelegator,__asyncValues,__makeTemplateObject,__importStar,__importDefault,__classPrivateFieldGet,__classPrivateFieldSet,__classPrivateFieldIn,__createBinding,__addDisposableResource,__disposeResources,__rewriteRelativeImportExtension;!function(factory){var root="object"===("undefined"==typeof global?"undefined":_typeof(global))?global:"object"===("undefined"==typeof self?"undefined":_typeof(self))?self:"object"===_typeof(this)?this:{};function createExporter(exports,previous){return exports!==root&&("function"==typeof Object.create?Object.defineProperty(exports,"__esModule",{value:!0}):exports.__esModule=!0),function(id,v){return exports[id]=previous?previous(id,v):v}}"object"===("undefined"==typeof module?"undefined":_typeof(module))&&"object"===_typeof(module.exports)?factory(createExporter(root,createExporter(module.exports))):factory(createExporter(root))}((function(exporter){var extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)Object.prototype.hasOwnProperty.call(b,p)&&(d[p]=b[p])};__extends=function(d,b){if("function"!=typeof b&&null!==b)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");function __(){this.constructor=d}extendStatics(d,b),d.prototype=null===b?Object.create(b):(__.prototype=b.prototype,new __)},__assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++)for(var p in s=arguments[i])Object.prototype.hasOwnProperty.call(s,p)&&(t[p]=s[p]);return t},__rest=function(s,e){var t={};for(var p in s)Object.prototype.hasOwnProperty.call(s,p)&&e.indexOf(p)<0&&(t[p]=s[p]);if(null!=s&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(p=Object.getOwnPropertySymbols(s);i<p.length;i++)e.indexOf(p[i])<0&&Object.prototype.propertyIsEnumerable.call(s,p[i])&&(t[p[i]]=s[p[i]])}return t},__decorate=function(decorators,target,key,desc){var d,c=arguments.length,r=c<3?target:null===desc?desc=Object.getOwnPropertyDescriptor(target,key):desc;if("object"===("undefined"==typeof Reflect?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r},__param=function(paramIndex,decorator){return function(target,key){decorator(target,key,paramIndex)}},__esDecorate=function(ctor,descriptorIn,decorators,contextIn,initializers,extraInitializers){function accept(f){if(void 0!==f&&"function"!=typeof f)throw new TypeError("Function expected");return f}for(var _,kind=contextIn.kind,key="getter"===kind?"get":"setter"===kind?"set":"value",target=!descriptorIn&&ctor?contextIn.static?ctor:ctor.prototype:null,descriptor=descriptorIn||(target?Object.getOwnPropertyDescriptor(target,contextIn.name):{}),done=!1,i=decorators.length-1;i>=0;i--){var context={};for(var p in contextIn)context[p]="access"===p?{}:contextIn[p];for(var p in contextIn.access)context.access[p]=contextIn.access[p];context.addInitializer=function(f){if(done)throw new TypeError("Cannot add initializers after decoration has completed");extraInitializers.push(accept(f||null))};var result=(0,decorators[i])("accessor"===kind?{get:descriptor.get,set:descriptor.set}:descriptor[key],context);if("accessor"===kind){if(void 0===result)continue;if(null===result||"object"!==_typeof(result))throw new TypeError("Object expected");(_=accept(result.get))&&(descriptor.get=_),(_=accept(result.set))&&(descriptor.set=_),(_=accept(result.init))&&initializers.unshift(_)}else(_=accept(result))&&("field"===kind?initializers.unshift(_):descriptor[key]=_)}target&&Object.defineProperty(target,contextIn.name,descriptor),done=!0},__runInitializers=function(thisArg,initializers,value){for(var useValue=arguments.length>2,i=0;i<initializers.length;i++)value=useValue?initializers[i].call(thisArg,value):initializers[i].call(thisArg);return useValue?value:void 0},__propKey=function(x){return"symbol"===_typeof(x)?x:"".concat(x)},__setFunctionName=function(f,name,prefix){return"symbol"===_typeof(name)&&(name=name.description?"[".concat(name.description,"]"):""),Object.defineProperty(f,"name",{configurable:!0,value:prefix?"".concat(prefix," ",name):name})},__metadata=function(metadataKey,metadataValue){if("object"===("undefined"==typeof Reflect?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.metadata)return Reflect.metadata(metadataKey,metadataValue)},__awaiter=function(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){var value;result.done?resolve(result.value):(value=result.value,value instanceof P?value:new P((function(resolve){resolve(value)}))).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))},__generator=function(thisArg,body){var f,y,t,_={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]},g=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return g.next=verb(0),g.throw=verb(1),g.return=verb(2),"function"==typeof Symbol&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return function(op){if(f)throw new TypeError("Generator is already executing.");for(;g&&(g=0,op[0]&&(_=0)),_;)try{if(f=1,y&&(t=2&op[0]?y.return:op[0]?y.throw||((t=y.return)&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;switch(y=0,t&&(op=[2&op[0],t.value]),op[0]){case 0:case 1:t=op;break;case 4:return _.label++,{value:op[1],done:!1};case 5:_.label++,y=op[1],op=[0];continue;case 7:op=_.ops.pop(),_.trys.pop();continue;default:if(!(t=_.trys,(t=t.length>0&&t[t.length-1])||6!==op[0]&&2!==op[0])){_=0;continue}if(3===op[0]&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(6===op[0]&&_.label<t[1]){_.label=t[1],t=op;break}if(t&&_.label<t[2]){_.label=t[2],_.ops.push(op);break}t[2]&&_.ops.pop(),_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e],y=0}finally{f=t=0}if(5&op[0])throw op[1];return{value:op[0]?op[1]:void 0,done:!0}}([n,v])}}},__exportStar=function(m,o){for(var p in m)"default"===p||Object.prototype.hasOwnProperty.call(o,p)||__createBinding(o,m,p)},__createBinding=Object.create?function(o,m,k,k2){void 0===k2&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);desc&&!("get"in desc?!m.__esModule:desc.writable||desc.configurable)||(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){void 0===k2&&(k2=k),o[k2]=m[k]},__values=function(o){var s="function"==typeof Symbol&&Symbol.iterator,m=s&&o[s],i=0;if(m)return m.call(o);if(o&&"number"==typeof o.length)return{next:function(){return o&&i>=o.length&&(o=void 0),{value:o&&o[i++],done:!o}}};throw new TypeError(s?"Object is not iterable.":"Symbol.iterator is not defined.")},__read=function(o,n){var m="function"==typeof Symbol&&o[Symbol.iterator];if(!m)return o;var r,e,i=m.call(o),ar=[];try{for(;(void 0===n||n-- >0)&&!(r=i.next()).done;)ar.push(r.value)}catch(error){e={error:error}}finally{try{r&&!r.done&&(m=i.return)&&m.call(i)}finally{if(e)throw e.error}}return ar},__spread=function(){for(var ar=[],i=0;i<arguments.length;i++)ar=ar.concat(__read(arguments[i]));return ar},__spreadArrays=function(){for(var s=0,i=0,il=arguments.length;i<il;i++)s+=arguments[i].length;var r=Array(s),k=0;for(i=0;i<il;i++)for(var a=arguments[i],j=0,jl=a.length;j<jl;j++,k++)r[k]=a[j];return r},__spreadArray=function(to,from,pack){if(pack||2===arguments.length)for(var ar,i=0,l=from.length;i<l;i++)!ar&&i in from||(ar||(ar=Array.prototype.slice.call(from,0,i)),ar[i]=from[i]);return to.concat(ar||Array.prototype.slice.call(from))},_await=function(v){return this instanceof _await?(this.v=v,this):new _await(v)},__asyncGenerator=function(thisArg,_arguments,generator){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,g=generator.apply(thisArg,_arguments||[]),q=[];return i=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),verb("next"),verb("throw"),verb("return",(function(f){return function(v){return Promise.resolve(v).then(f,reject)}})),i[Symbol.asyncIterator]=function(){return this},i;function verb(n,f){g[n]&&(i[n]=function(v){return new Promise((function(a,b){q.push([n,v,a,b])>1||resume(n,v)}))},f&&(i[n]=f(i[n])))}function resume(n,v){try{(r=g[n](v)).value instanceof _await?Promise.resolve(r.value.v).then(fulfill,reject):settle(q[0][2],r)}catch(e){settle(q[0][3],e)}var r}function fulfill(value){resume("next",value)}function reject(value){resume("throw",value)}function settle(f,v){f(v),q.shift(),q.length&&resume(q[0][0],q[0][1])}},__asyncDelegator=function(o){var i,p;return i={},verb("next"),verb("throw",(function(e){throw e})),verb("return"),i[Symbol.iterator]=function(){return this},i;function verb(n,f){i[n]=o[n]?function(v){return(p=!p)?{value:_await(o[n](v)),done:!1}:f?f(v):v}:f}},__asyncValues=function(o){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,m=o[Symbol.asyncIterator];return m?m.call(o):(o="function"==typeof __values?__values(o):o[Symbol.iterator](),i={},verb("next"),verb("throw"),verb("return"),i[Symbol.asyncIterator]=function(){return this},i);function verb(n){i[n]=o[n]&&function(v){return new Promise((function(resolve,reject){(function(resolve,reject,d,v){Promise.resolve(v).then((function(v){resolve({value:v,done:d})}),reject)})(resolve,reject,(v=o[n](v)).done,v.value)}))}}},__makeTemplateObject=function(cooked,raw){return Object.defineProperty?Object.defineProperty(cooked,"raw",{value:raw}):cooked.raw=raw,cooked};var __setModuleDefault=Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}:function(o,v){o.default=v},_ownKeys=function(o){return(_ownKeys=Object.getOwnPropertyNames||function(o){var ar=[];for(var k in o)Object.prototype.hasOwnProperty.call(o,k)&&(ar[ar.length]=k);return ar})(o)};__importStar=function(mod){if(mod&&mod.__esModule)return mod;var result={};if(null!=mod)for(var k=_ownKeys(mod),i=0;i<k.length;i++)"default"!==k[i]&&__createBinding(result,mod,k[i]);return __setModuleDefault(result,mod),result},__importDefault=function(mod){return mod&&mod.__esModule?mod:{default:mod}},__classPrivateFieldGet=function(receiver,state,kind,f){if("a"===kind&&!f)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof state?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===kind?f:"a"===kind?f.call(receiver):f?f.value:state.get(receiver)},__classPrivateFieldSet=function(receiver,state,value,kind,f){if("m"===kind)throw new TypeError("Private method is not writable");if("a"===kind&&!f)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof state?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===kind?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value},__classPrivateFieldIn=function(state,receiver){if(null===receiver||"object"!==_typeof(receiver)&&"function"!=typeof receiver)throw new TypeError("Cannot use 'in' operator on non-object");return"function"==typeof state?receiver===state:state.has(receiver)},__addDisposableResource=function(env,value,async){if(null!=value){if("object"!==_typeof(value)&&"function"!=typeof value)throw new TypeError("Object expected.");var dispose,inner;if(async){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");dispose=value[Symbol.asyncDispose]}if(void 0===dispose){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");dispose=value[Symbol.dispose],async&&(inner=dispose)}if("function"!=typeof dispose)throw new TypeError("Object not disposable.");inner&&(dispose=function(){try{inner.call(this)}catch(e){return Promise.reject(e)}}),env.stack.push({value:value,dispose:dispose,async:async})}else async&&env.stack.push({async:!0});return value};var _SuppressedError="function"==typeof SuppressedError?SuppressedError:function(error,suppressed,message){var e=new Error(message);return e.name="SuppressedError",e.error=error,e.suppressed=suppressed,e};__disposeResources=function(env){function fail(e){env.error=env.hasError?new _SuppressedError(e,env.error,"An error was suppressed during disposal."):e,env.hasError=!0}var r,s=0;return function next(){for(;r=env.stack.pop();)try{if(!r.async&&1===s)return s=0,env.stack.push(r),Promise.resolve().then(next);if(r.dispose){var result=r.dispose.call(r.value);if(r.async)return s|=2,Promise.resolve(result).then(next,(function(e){return fail(e),next()}))}else s|=1}catch(e){fail(e)}if(1===s)return env.hasError?Promise.reject(env.error):Promise.resolve();if(env.hasError)throw env.error}()},__rewriteRelativeImportExtension=function(path,preserveJsx){return"string"==typeof path&&/^\.\.?\//.test(path)?path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,(function(m,tsx,d,ext,cm){return tsx?preserveJsx?".jsx":".js":!d||ext&&cm?d+ext+"."+cm.toLowerCase()+"js":m})):path},exporter("__extends",__extends),exporter("__assign",__assign),exporter("__rest",__rest),exporter("__decorate",__decorate),exporter("__param",__param),exporter("__esDecorate",__esDecorate),exporter("__runInitializers",__runInitializers),exporter("__propKey",__propKey),exporter("__setFunctionName",__setFunctionName),exporter("__metadata",__metadata),exporter("__awaiter",__awaiter),exporter("__generator",__generator),exporter("__exportStar",__exportStar),exporter("__createBinding",__createBinding),exporter("__values",__values),exporter("__read",__read),exporter("__spread",__spread),exporter("__spreadArrays",__spreadArrays),exporter("__spreadArray",__spreadArray),exporter("__await",_await),exporter("__asyncGenerator",__asyncGenerator),exporter("__asyncDelegator",__asyncDelegator),exporter("__asyncValues",__asyncValues),exporter("__makeTemplateObject",__makeTemplateObject),exporter("__importStar",__importStar),exporter("__importDefault",__importDefault),exporter("__classPrivateFieldGet",__classPrivateFieldGet),exporter("__classPrivateFieldSet",__classPrivateFieldSet),exporter("__classPrivateFieldIn",__classPrivateFieldIn),exporter("__addDisposableResource",__addDisposableResource),exporter("__disposeResources",__disposeResources),exporter("__rewriteRelativeImportExtension",__rewriteRelativeImportExtension)}))}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],41:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"v1",{enumerable:!0,get:function(){return _v.default}}),Object.defineProperty(exports,"v3",{enumerable:!0,get:function(){return _v2.default}}),Object.defineProperty(exports,"v4",{enumerable:!0,get:function(){return _v3.default}}),Object.defineProperty(exports,"v5",{enumerable:!0,get:function(){return _v4.default}}),Object.defineProperty(exports,"NIL",{enumerable:!0,get:function(){return _nil.default}}),Object.defineProperty(exports,"version",{enumerable:!0,get:function(){return _version.default}}),Object.defineProperty(exports,"validate",{enumerable:!0,get:function(){return _validate.default}}),Object.defineProperty(exports,"stringify",{enumerable:!0,get:function(){return _stringify.default}}),Object.defineProperty(exports,"parse",{enumerable:!0,get:function(){return _parse.default}});var _v=_interopRequireDefault(require("./v1.js")),_v2=_interopRequireDefault(require("./v3.js")),_v3=_interopRequireDefault(require("./v4.js")),_v4=_interopRequireDefault(require("./v5.js")),_nil=_interopRequireDefault(require("./nil.js")),_version=_interopRequireDefault(require("./version.js")),_validate=_interopRequireDefault(require("./validate.js")),_stringify=_interopRequireDefault(require("./stringify.js")),_parse=_interopRequireDefault(require("./parse.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}},{"./nil.js":43,"./parse.js":44,"./stringify.js":48,"./v1.js":49,"./v3.js":50,"./v4.js":52,"./v5.js":53,"./validate.js":54,"./version.js":55}],42:[function(require,module,exports){"use strict";function getOutputLength(inputLength8){return 14+(inputLength8+64>>>9<<4)+1}function safeAdd(x,y){var lsw=(65535&x)+(65535&y);return(x>>16)+(y>>16)+(lsw>>16)<<16|65535&lsw}function md5cmn(q,a,b,x,s,t){return safeAdd((num=safeAdd(safeAdd(a,q),safeAdd(x,t)))<<(cnt=s)|num>>>32-cnt,b);var num,cnt}function md5ff(a,b,c,d,x,s,t){return md5cmn(b&c|~b&d,a,b,x,s,t)}function md5gg(a,b,c,d,x,s,t){return md5cmn(b&d|c&~d,a,b,x,s,t)}function md5hh(a,b,c,d,x,s,t){return md5cmn(b^c^d,a,b,x,s,t)}function md5ii(a,b,c,d,x,s,t){return md5cmn(c^(b|~d),a,b,x,s,t)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _default=function(bytes){if("string"==typeof bytes){var msg=unescape(encodeURIComponent(bytes));bytes=new Uint8Array(msg.length);for(var i=0;i<msg.length;++i)bytes[i]=msg.charCodeAt(i)}return function(input){for(var output=[],length32=32*input.length,i=0;i<length32;i+=8){var x=input[i>>5]>>>i%32&255,hex=parseInt("0123456789abcdef".charAt(x>>>4&15)+"0123456789abcdef".charAt(15&x),16);output.push(hex)}return output}(function(x,len){x[len>>5]|=128<<len%32,x[getOutputLength(len)-1]=len;for(var a=1732584193,b=-271733879,c=-1732584194,d=271733878,i=0;i<x.length;i+=16){var olda=a,oldb=b,oldc=c,oldd=d;a=md5ff(a,b,c,d,x[i],7,-680876936),d=md5ff(d,a,b,c,x[i+1],12,-389564586),c=md5ff(c,d,a,b,x[i+2],17,606105819),b=md5ff(b,c,d,a,x[i+3],22,-1044525330),a=md5ff(a,b,c,d,x[i+4],7,-176418897),d=md5ff(d,a,b,c,x[i+5],12,1200080426),c=md5ff(c,d,a,b,x[i+6],17,-1473231341),b=md5ff(b,c,d,a,x[i+7],22,-45705983),a=md5ff(a,b,c,d,x[i+8],7,1770035416),d=md5ff(d,a,b,c,x[i+9],12,-1958414417),c=md5ff(c,d,a,b,x[i+10],17,-42063),b=md5ff(b,c,d,a,x[i+11],22,-1990404162),a=md5ff(a,b,c,d,x[i+12],7,1804603682),d=md5ff(d,a,b,c,x[i+13],12,-40341101),c=md5ff(c,d,a,b,x[i+14],17,-1502002290),b=md5ff(b,c,d,a,x[i+15],22,1236535329),a=md5gg(a,b,c,d,x[i+1],5,-165796510),d=md5gg(d,a,b,c,x[i+6],9,-1069501632),c=md5gg(c,d,a,b,x[i+11],14,643717713),b=md5gg(b,c,d,a,x[i],20,-373897302),a=md5gg(a,b,c,d,x[i+5],5,-701558691),d=md5gg(d,a,b,c,x[i+10],9,38016083),c=md5gg(c,d,a,b,x[i+15],14,-660478335),b=md5gg(b,c,d,a,x[i+4],20,-405537848),a=md5gg(a,b,c,d,x[i+9],5,568446438),d=md5gg(d,a,b,c,x[i+14],9,-1019803690),c=md5gg(c,d,a,b,x[i+3],14,-187363961),b=md5gg(b,c,d,a,x[i+8],20,1163531501),a=md5gg(a,b,c,d,x[i+13],5,-1444681467),d=md5gg(d,a,b,c,x[i+2],9,-51403784),c=md5gg(c,d,a,b,x[i+7],14,1735328473),b=md5gg(b,c,d,a,x[i+12],20,-1926607734),a=md5hh(a,b,c,d,x[i+5],4,-378558),d=md5hh(d,a,b,c,x[i+8],11,-2022574463),c=md5hh(c,d,a,b,x[i+11],16,1839030562),b=md5hh(b,c,d,a,x[i+14],23,-35309556),a=md5hh(a,b,c,d,x[i+1],4,-1530992060),d=md5hh(d,a,b,c,x[i+4],11,1272893353),c=md5hh(c,d,a,b,x[i+7],16,-155497632),b=md5hh(b,c,d,a,x[i+10],23,-1094730640),a=md5hh(a,b,c,d,x[i+13],4,681279174),d=md5hh(d,a,b,c,x[i],11,-358537222),c=md5hh(c,d,a,b,x[i+3],16,-722521979),b=md5hh(b,c,d,a,x[i+6],23,76029189),a=md5hh(a,b,c,d,x[i+9],4,-640364487),d=md5hh(d,a,b,c,x[i+12],11,-421815835),c=md5hh(c,d,a,b,x[i+15],16,530742520),b=md5hh(b,c,d,a,x[i+2],23,-995338651),a=md5ii(a,b,c,d,x[i],6,-198630844),d=md5ii(d,a,b,c,x[i+7],10,1126891415),c=md5ii(c,d,a,b,x[i+14],15,-1416354905),b=md5ii(b,c,d,a,x[i+5],21,-57434055),a=md5ii(a,b,c,d,x[i+12],6,1700485571),d=md5ii(d,a,b,c,x[i+3],10,-1894986606),c=md5ii(c,d,a,b,x[i+10],15,-1051523),b=md5ii(b,c,d,a,x[i+1],21,-2054922799),a=md5ii(a,b,c,d,x[i+8],6,1873313359),d=md5ii(d,a,b,c,x[i+15],10,-30611744),c=md5ii(c,d,a,b,x[i+6],15,-1560198380),b=md5ii(b,c,d,a,x[i+13],21,1309151649),a=md5ii(a,b,c,d,x[i+4],6,-145523070),d=md5ii(d,a,b,c,x[i+11],10,-1120210379),c=md5ii(c,d,a,b,x[i+2],15,718787259),b=md5ii(b,c,d,a,x[i+9],21,-343485551),a=safeAdd(a,olda),b=safeAdd(b,oldb),c=safeAdd(c,oldc),d=safeAdd(d,oldd)}return[a,b,c,d]}(function(input){if(0===input.length)return[];for(var length8=8*input.length,output=new Uint32Array(getOutputLength(length8)),i=0;i<length8;i+=8)output[i>>5]|=(255&input[i/8])<<i%32;return output}(bytes),8*bytes.length))};exports.default=_default},{}],43:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;exports.default="00000000-0000-0000-0000-000000000000"},{}],44:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var obj,_validate=(obj=require("./validate.js"))&&obj.__esModule?obj:{default:obj};var _default=function(uuid){if(!(0,_validate.default)(uuid))throw TypeError("Invalid UUID");var v,arr=new Uint8Array(16);return arr[0]=(v=parseInt(uuid.slice(0,8),16))>>>24,arr[1]=v>>>16&255,arr[2]=v>>>8&255,arr[3]=255&v,arr[4]=(v=parseInt(uuid.slice(9,13),16))>>>8,arr[5]=255&v,arr[6]=(v=parseInt(uuid.slice(14,18),16))>>>8,arr[7]=255&v,arr[8]=(v=parseInt(uuid.slice(19,23),16))>>>8,arr[9]=255&v,arr[10]=(v=parseInt(uuid.slice(24,36),16))/1099511627776&255,arr[11]=v/4294967296&255,arr[12]=v>>>24&255,arr[13]=v>>>16&255,arr[14]=v>>>8&255,arr[15]=255&v,arr};exports.default=_default},{"./validate.js":54}],45:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;exports.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i},{}],46:[function(require,module,exports){"use strict";var getRandomValues;Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(){if(!getRandomValues&&!(getRandomValues="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return getRandomValues(rnds8)};var rnds8=new Uint8Array(16)},{}],47:[function(require,module,exports){"use strict";function f(s,x,y,z){switch(s){case 0:return x&y^~x&z;case 1:return x^y^z;case 2:return x&y^x&z^y&z;case 3:return x^y^z}}function ROTL(x,n){return x<<n|x>>>32-n}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _default=function(bytes){var K=[1518500249,1859775393,2400959708,3395469782],H=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof bytes){var msg=unescape(encodeURIComponent(bytes));bytes=[];for(var i=0;i<msg.length;++i)bytes.push(msg.charCodeAt(i))}else Array.isArray(bytes)||(bytes=Array.prototype.slice.call(bytes));bytes.push(128);for(var l=bytes.length/4+2,N=Math.ceil(l/16),M=new Array(N),_i=0;_i<N;++_i){for(var arr=new Uint32Array(16),j=0;j<16;++j)arr[j]=bytes[64*_i+4*j]<<24|bytes[64*_i+4*j+1]<<16|bytes[64*_i+4*j+2]<<8|bytes[64*_i+4*j+3];M[_i]=arr}M[N-1][14]=8*(bytes.length-1)/Math.pow(2,32),M[N-1][14]=Math.floor(M[N-1][14]),M[N-1][15]=8*(bytes.length-1)&4294967295;for(var _i2=0;_i2<N;++_i2){for(var W=new Uint32Array(80),t=0;t<16;++t)W[t]=M[_i2][t];for(var _t=16;_t<80;++_t)W[_t]=ROTL(W[_t-3]^W[_t-8]^W[_t-14]^W[_t-16],1);for(var a=H[0],b=H[1],c=H[2],d=H[3],e=H[4],_t2=0;_t2<80;++_t2){var s=Math.floor(_t2/20),T=ROTL(a,5)+f(s,b,c,d)+e+K[s]+W[_t2]>>>0;e=d,d=c,c=ROTL(b,30)>>>0,b=a,a=T}H[0]=H[0]+a>>>0,H[1]=H[1]+b>>>0,H[2]=H[2]+c>>>0,H[3]=H[3]+d>>>0,H[4]=H[4]+e>>>0}return[H[0]>>24&255,H[0]>>16&255,H[0]>>8&255,255&H[0],H[1]>>24&255,H[1]>>16&255,H[1]>>8&255,255&H[1],H[2]>>24&255,H[2]>>16&255,H[2]>>8&255,255&H[2],H[3]>>24&255,H[3]>>16&255,H[3]>>8&255,255&H[3],H[4]>>24&255,H[4]>>16&255,H[4]>>8&255,255&H[4]]};exports.default=_default},{}],48:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var obj,_validate=(obj=require("./validate.js"))&&obj.__esModule?obj:{default:obj};for(var byteToHex=[],i=0;i<256;++i)byteToHex.push((i+256).toString(16).substr(1));var _default=function(arr){var offset=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,uuid=(byteToHex[arr[offset+0]]+byteToHex[arr[offset+1]]+byteToHex[arr[offset+2]]+byteToHex[arr[offset+3]]+"-"+byteToHex[arr[offset+4]]+byteToHex[arr[offset+5]]+"-"+byteToHex[arr[offset+6]]+byteToHex[arr[offset+7]]+"-"+byteToHex[arr[offset+8]]+byteToHex[arr[offset+9]]+"-"+byteToHex[arr[offset+10]]+byteToHex[arr[offset+11]]+byteToHex[arr[offset+12]]+byteToHex[arr[offset+13]]+byteToHex[arr[offset+14]]+byteToHex[arr[offset+15]]).toLowerCase();if(!(0,_validate.default)(uuid))throw TypeError("Stringified UUID is invalid");return uuid};exports.default=_default},{"./validate.js":54}],49:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _nodeId,_clockseq,_rng=_interopRequireDefault(require("./rng.js")),_stringify=_interopRequireDefault(require("./stringify.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _lastMSecs=0,_lastNSecs=0;var _default=function(options,buf,offset){var i=buf&&offset||0,b=buf||new Array(16),node=(options=options||{}).node||_nodeId,clockseq=void 0!==options.clockseq?options.clockseq:_clockseq;if(null==node||null==clockseq){var seedBytes=options.random||(options.rng||_rng.default)();null==node&&(node=_nodeId=[1|seedBytes[0],seedBytes[1],seedBytes[2],seedBytes[3],seedBytes[4],seedBytes[5]]),null==clockseq&&(clockseq=_clockseq=16383&(seedBytes[6]<<8|seedBytes[7]))}var msecs=void 0!==options.msecs?options.msecs:Date.now(),nsecs=void 0!==options.nsecs?options.nsecs:_lastNSecs+1,dt=msecs-_lastMSecs+(nsecs-_lastNSecs)/1e4;if(dt<0&&void 0===options.clockseq&&(clockseq=clockseq+1&16383),(dt<0||msecs>_lastMSecs)&&void 0===options.nsecs&&(nsecs=0),nsecs>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");_lastMSecs=msecs,_lastNSecs=nsecs,_clockseq=clockseq;var tl=(1e4*(268435455&(msecs+=122192928e5))+nsecs)%4294967296;b[i++]=tl>>>24&255,b[i++]=tl>>>16&255,b[i++]=tl>>>8&255,b[i++]=255&tl;var tmh=msecs/4294967296*1e4&268435455;b[i++]=tmh>>>8&255,b[i++]=255&tmh,b[i++]=tmh>>>24&15|16,b[i++]=tmh>>>16&255,b[i++]=clockseq>>>8|128,b[i++]=255&clockseq;for(var n=0;n<6;++n)b[i+n]=node[n];return buf||(0,_stringify.default)(b)};exports.default=_default},{"./rng.js":46,"./stringify.js":48}],50:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _v=_interopRequireDefault(require("./v35.js")),_md=_interopRequireDefault(require("./md5.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _default=(0,_v.default)("v3",48,_md.default);exports.default=_default},{"./md5.js":42,"./v35.js":51}],51:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(name,version,hashfunc){function generateUUID(value,namespace,buf,offset){if("string"==typeof value&&(value=function(str){str=unescape(encodeURIComponent(str));for(var bytes=[],i=0;i<str.length;++i)bytes.push(str.charCodeAt(i));return bytes}(value)),"string"==typeof namespace&&(namespace=(0,_parse.default)(namespace)),16!==namespace.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var bytes=new Uint8Array(16+value.length);if(bytes.set(namespace),bytes.set(value,namespace.length),(bytes=hashfunc(bytes))[6]=15&bytes[6]|version,bytes[8]=63&bytes[8]|128,buf){offset=offset||0;for(var i=0;i<16;++i)buf[offset+i]=bytes[i];return buf}return(0,_stringify.default)(bytes)}try{generateUUID.name=name}catch(err){}return generateUUID.DNS=DNS,generateUUID.URL=URL,generateUUID},exports.URL=exports.DNS=void 0;var _stringify=_interopRequireDefault(require("./stringify.js")),_parse=_interopRequireDefault(require("./parse.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8";exports.DNS=DNS;var URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8";exports.URL=URL},{"./parse.js":44,"./stringify.js":48}],52:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _rng=_interopRequireDefault(require("./rng.js")),_stringify=_interopRequireDefault(require("./stringify.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _default=function(options,buf,offset){var rnds=(options=options||{}).random||(options.rng||_rng.default)();if(rnds[6]=15&rnds[6]|64,rnds[8]=63&rnds[8]|128,buf){offset=offset||0;for(var i=0;i<16;++i)buf[offset+i]=rnds[i];return buf}return(0,_stringify.default)(rnds)};exports.default=_default},{"./rng.js":46,"./stringify.js":48}],53:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _v=_interopRequireDefault(require("./v35.js")),_sha=_interopRequireDefault(require("./sha1.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _default=(0,_v.default)("v5",80,_sha.default);exports.default=_default},{"./sha1.js":47,"./v35.js":51}],54:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var obj,_regex=(obj=require("./regex.js"))&&obj.__esModule?obj:{default:obj};var _default=function(uuid){return"string"==typeof uuid&&_regex.default.test(uuid)};exports.default=_default},{"./regex.js":45}],55:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var obj,_validate=(obj=require("./validate.js"))&&obj.__esModule?obj:{default:obj};var _default=function(uuid){if(!(0,_validate.default)(uuid))throw TypeError("Invalid UUID");return parseInt(uuid.substr(14,1),16)};exports.default=_default},{"./validate.js":54}],56:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var adapter=(0,require("./adapter_factory.js").adapterFactory)({window:"undefined"==typeof window?void 0:window});exports.default=adapter},{"./adapter_factory.js":57}],57:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.adapterFactory=function(){var _ref=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},window=_ref.window,options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0},logging=utils.log,browserDetails=utils.detectBrowser(window),adapter={browserDetails:browserDetails,commonShim:commonShim,extractVersion:utils.extractVersion,disableLog:utils.disableLog,disableWarnings:utils.disableWarnings};switch(browserDetails.browser){case"chrome":if(!chromeShim||!chromeShim.shimPeerConnection||!options.shimChrome)return logging("Chrome shim is not included in this adapter release."),adapter;if(null===browserDetails.version)return logging("Chrome shim can not determine version, not shimming."),adapter;logging("adapter.js shimming chrome."),adapter.browserShim=chromeShim,commonShim.shimAddIceCandidateNullOrEmpty(window,browserDetails),chromeShim.shimGetUserMedia(window,browserDetails),chromeShim.shimMediaStream(window,browserDetails),chromeShim.shimPeerConnection(window,browserDetails),chromeShim.shimOnTrack(window,browserDetails),chromeShim.shimAddTrackRemoveTrack(window,browserDetails),chromeShim.shimGetSendersWithDtmf(window,browserDetails),chromeShim.shimGetStats(window,browserDetails),chromeShim.shimSenderReceiverGetStats(window,browserDetails),chromeShim.fixNegotiationNeeded(window,browserDetails),commonShim.shimRTCIceCandidate(window,browserDetails),commonShim.shimConnectionState(window,browserDetails),commonShim.shimMaxMessageSize(window,browserDetails),commonShim.shimSendThrowTypeError(window,browserDetails),commonShim.removeExtmapAllowMixed(window,browserDetails);break;case"firefox":if(!firefoxShim||!firefoxShim.shimPeerConnection||!options.shimFirefox)return logging("Firefox shim is not included in this adapter release."),adapter;logging("adapter.js shimming firefox."),adapter.browserShim=firefoxShim,commonShim.shimAddIceCandidateNullOrEmpty(window,browserDetails),firefoxShim.shimGetUserMedia(window,browserDetails),firefoxShim.shimPeerConnection(window,browserDetails),firefoxShim.shimOnTrack(window,browserDetails),firefoxShim.shimRemoveStream(window,browserDetails),firefoxShim.shimSenderGetStats(window,browserDetails),firefoxShim.shimReceiverGetStats(window,browserDetails),firefoxShim.shimRTCDataChannel(window,browserDetails),firefoxShim.shimAddTransceiver(window,browserDetails),firefoxShim.shimGetParameters(window,browserDetails),firefoxShim.shimCreateOffer(window,browserDetails),firefoxShim.shimCreateAnswer(window,browserDetails),commonShim.shimRTCIceCandidate(window,browserDetails),commonShim.shimConnectionState(window,browserDetails),commonShim.shimMaxMessageSize(window,browserDetails),commonShim.shimSendThrowTypeError(window,browserDetails);break;case"edge":if(!edgeShim||!edgeShim.shimPeerConnection||!options.shimEdge)return logging("MS edge shim is not included in this adapter release."),adapter;logging("adapter.js shimming edge."),adapter.browserShim=edgeShim,edgeShim.shimGetUserMedia(window,browserDetails),edgeShim.shimGetDisplayMedia(window,browserDetails),edgeShim.shimPeerConnection(window,browserDetails),edgeShim.shimReplaceTrack(window,browserDetails),commonShim.shimMaxMessageSize(window,browserDetails),commonShim.shimSendThrowTypeError(window,browserDetails);break;case"safari":if(!safariShim||!options.shimSafari)return logging("Safari shim is not included in this adapter release."),adapter;logging("adapter.js shimming safari."),adapter.browserShim=safariShim,commonShim.shimAddIceCandidateNullOrEmpty(window,browserDetails),safariShim.shimRTCIceServerUrls(window,browserDetails),safariShim.shimCreateOfferLegacy(window,browserDetails),safariShim.shimCallbacksAPI(window,browserDetails),safariShim.shimLocalStreamsAPI(window,browserDetails),safariShim.shimRemoteStreamsAPI(window,browserDetails),safariShim.shimTrackEventTransceiver(window,browserDetails),safariShim.shimGetUserMedia(window,browserDetails),safariShim.shimAudioContext(window,browserDetails),commonShim.shimRTCIceCandidate(window,browserDetails),commonShim.shimMaxMessageSize(window,browserDetails),commonShim.shimSendThrowTypeError(window,browserDetails),commonShim.removeExtmapAllowMixed(window,browserDetails);break;default:logging("Unsupported browser!")}return adapter};var utils=_interopRequireWildcard(require("./utils")),chromeShim=_interopRequireWildcard(require("./chrome/chrome_shim")),edgeShim=_interopRequireWildcard(require("./edge/edge_shim")),firefoxShim=_interopRequireWildcard(require("./firefox/firefox_shim")),safariShim=_interopRequireWildcard(require("./safari/safari_shim")),commonShim=_interopRequireWildcard(require("./common_shim"));function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}},{"./chrome/chrome_shim":58,"./common_shim":61,"./edge/edge_shim":62,"./firefox/firefox_shim":66,"./safari/safari_shim":69,"./utils":70}],58:[function(require,module,exports){"use strict";function _typeof2(o){return(_typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=exports.shimGetUserMedia=void 0;var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(obj){return _typeof2(obj)}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":_typeof2(obj)},_getusermedia=require("./getusermedia");Object.defineProperty(exports,"shimGetUserMedia",{enumerable:!0,get:function(){return _getusermedia.shimGetUserMedia}});var _getdisplaymedia=require("./getdisplaymedia");Object.defineProperty(exports,"shimGetDisplayMedia",{enumerable:!0,get:function(){return _getdisplaymedia.shimGetDisplayMedia}}),exports.shimMediaStream=function(window){window.MediaStream=window.MediaStream||window.webkitMediaStream},exports.shimOnTrack=function(window){if("object"===("undefined"==typeof window?"undefined":_typeof(window))&&window.RTCPeerConnection&&!("ontrack"in window.RTCPeerConnection.prototype)){Object.defineProperty(window.RTCPeerConnection.prototype,"ontrack",{get:function(){return this._ontrack},set:function(f){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=f)},enumerable:!0,configurable:!0});var origSetRemoteDescription=window.RTCPeerConnection.prototype.setRemoteDescription;window.RTCPeerConnection.prototype.setRemoteDescription=function(){var _this=this;return this._ontrackpoly||(this._ontrackpoly=function(e){e.stream.addEventListener("addtrack",(function(te){var receiver=void 0;receiver=window.RTCPeerConnection.prototype.getReceivers?_this.getReceivers().find((function(r){return r.track&&r.track.id===te.track.id})):{track:te.track};var event=new Event("track");event.track=te.track,event.receiver=receiver,event.transceiver={receiver:receiver},event.streams=[e.stream],_this.dispatchEvent(event)})),e.stream.getTracks().forEach((function(track){var receiver=void 0;receiver=window.RTCPeerConnection.prototype.getReceivers?_this.getReceivers().find((function(r){return r.track&&r.track.id===track.id})):{track:track};var event=new Event("track");event.track=track,event.receiver=receiver,event.transceiver={receiver:receiver},event.streams=[e.stream],_this.dispatchEvent(event)}))},this.addEventListener("addstream",this._ontrackpoly)),origSetRemoteDescription.apply(this,arguments)}}else utils.wrapPeerConnectionEvent(window,"track",(function(e){return e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e}))},exports.shimGetSendersWithDtmf=function(window){if("object"===("undefined"==typeof window?"undefined":_typeof(window))&&window.RTCPeerConnection&&!("getSenders"in window.RTCPeerConnection.prototype)&&"createDTMFSender"in window.RTCPeerConnection.prototype){var shimSenderWithDtmf=function(pc,track){return{track:track,get dtmf(){return void 0===this._dtmf&&("audio"===track.kind?this._dtmf=pc.createDTMFSender(track):this._dtmf=null),this._dtmf},_pc:pc}};if(!window.RTCPeerConnection.prototype.getSenders){window.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};var origAddTrack=window.RTCPeerConnection.prototype.addTrack;window.RTCPeerConnection.prototype.addTrack=function(track,stream){var sender=origAddTrack.apply(this,arguments);return sender||(sender=shimSenderWithDtmf(this,track),this._senders.push(sender)),sender};var origRemoveTrack=window.RTCPeerConnection.prototype.removeTrack;window.RTCPeerConnection.prototype.removeTrack=function(sender){origRemoveTrack.apply(this,arguments);var idx=this._senders.indexOf(sender);-1!==idx&&this._senders.splice(idx,1)}}var origAddStream=window.RTCPeerConnection.prototype.addStream;window.RTCPeerConnection.prototype.addStream=function(stream){var _this2=this;this._senders=this._senders||[],origAddStream.apply(this,[stream]),stream.getTracks().forEach((function(track){_this2._senders.push(shimSenderWithDtmf(_this2,track))}))};var origRemoveStream=window.RTCPeerConnection.prototype.removeStream;window.RTCPeerConnection.prototype.removeStream=function(stream){var _this3=this;this._senders=this._senders||[],origRemoveStream.apply(this,[stream]),stream.getTracks().forEach((function(track){var sender=_this3._senders.find((function(s){return s.track===track}));sender&&_this3._senders.splice(_this3._senders.indexOf(sender),1)}))}}else if("object"===("undefined"==typeof window?"undefined":_typeof(window))&&window.RTCPeerConnection&&"getSenders"in window.RTCPeerConnection.prototype&&"createDTMFSender"in window.RTCPeerConnection.prototype&&window.RTCRtpSender&&!("dtmf"in window.RTCRtpSender.prototype)){var origGetSenders=window.RTCPeerConnection.prototype.getSenders;window.RTCPeerConnection.prototype.getSenders=function(){var _this4=this,senders=origGetSenders.apply(this,[]);return senders.forEach((function(sender){return sender._pc=_this4})),senders},Object.defineProperty(window.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}})}},exports.shimGetStats=function(window){if(!window.RTCPeerConnection)return;var origGetStats=window.RTCPeerConnection.prototype.getStats;window.RTCPeerConnection.prototype.getStats=function(){var _this5=this,_arguments=Array.prototype.slice.call(arguments),selector=_arguments[0],onSucc=_arguments[1],onErr=_arguments[2];if(arguments.length>0&&"function"==typeof selector)return origGetStats.apply(this,arguments);if(0===origGetStats.length&&(0===arguments.length||"function"!=typeof selector))return origGetStats.apply(this,[]);var fixChromeStats_=function(response){var standardReport={};return response.result().forEach((function(report){var standardStats={id:report.id,timestamp:report.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[report.type]||report.type};report.names().forEach((function(name){standardStats[name]=report.stat(name)})),standardReport[standardStats.id]=standardStats})),standardReport},makeMapStats=function(stats){return new Map(Object.keys(stats).map((function(key){return[key,stats[key]]})))};if(arguments.length>=2){var successCallbackWrapper_=function(response){onSucc(makeMapStats(fixChromeStats_(response)))};return origGetStats.apply(this,[successCallbackWrapper_,selector])}return new Promise((function(resolve,reject){origGetStats.apply(_this5,[function(response){resolve(makeMapStats(fixChromeStats_(response)))},reject])})).then(onSucc,onErr)}},exports.shimSenderReceiverGetStats=function(window){if(!("object"===("undefined"==typeof window?"undefined":_typeof(window))&&window.RTCPeerConnection&&window.RTCRtpSender&&window.RTCRtpReceiver))return;if(!("getStats"in window.RTCRtpSender.prototype)){var origGetSenders=window.RTCPeerConnection.prototype.getSenders;origGetSenders&&(window.RTCPeerConnection.prototype.getSenders=function(){var _this6=this,senders=origGetSenders.apply(this,[]);return senders.forEach((function(sender){return sender._pc=_this6})),senders});var origAddTrack=window.RTCPeerConnection.prototype.addTrack;origAddTrack&&(window.RTCPeerConnection.prototype.addTrack=function(){var sender=origAddTrack.apply(this,arguments);return sender._pc=this,sender}),window.RTCRtpSender.prototype.getStats=function(){var sender=this;return this._pc.getStats().then((function(result){return utils.filterStats(result,sender.track,!0)}))}}if(!("getStats"in window.RTCRtpReceiver.prototype)){var origGetReceivers=window.RTCPeerConnection.prototype.getReceivers;origGetReceivers&&(window.RTCPeerConnection.prototype.getReceivers=function(){var _this7=this,receivers=origGetReceivers.apply(this,[]);return receivers.forEach((function(receiver){return receiver._pc=_this7})),receivers}),utils.wrapPeerConnectionEvent(window,"track",(function(e){return e.receiver._pc=e.srcElement,e})),window.RTCRtpReceiver.prototype.getStats=function(){var receiver=this;return this._pc.getStats().then((function(result){return utils.filterStats(result,receiver.track,!1)}))}}if(!("getStats"in window.RTCRtpSender.prototype)||!("getStats"in window.RTCRtpReceiver.prototype))return;var origGetStats=window.RTCPeerConnection.prototype.getStats;window.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof window.MediaStreamTrack){var track=arguments[0],sender=void 0,receiver=void 0,err=void 0;return this.getSenders().forEach((function(s){s.track===track&&(sender?err=!0:sender=s)})),this.getReceivers().forEach((function(r){return r.track===track&&(receiver?err=!0:receiver=r),r.track===track})),err||sender&&receiver?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):sender?sender.getStats():receiver?receiver.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return origGetStats.apply(this,arguments)}},exports.shimAddTrackRemoveTrackWithNative=shimAddTrackRemoveTrackWithNative,exports.shimAddTrackRemoveTrack=function(window,browserDetails){if(!window.RTCPeerConnection)return;if(window.RTCPeerConnection.prototype.addTrack&&browserDetails.version>=65)return shimAddTrackRemoveTrackWithNative(window);var origGetLocalStreams=window.RTCPeerConnection.prototype.getLocalStreams;window.RTCPeerConnection.prototype.getLocalStreams=function(){var _this11=this,nativeStreams=origGetLocalStreams.apply(this);return this._reverseStreams=this._reverseStreams||{},nativeStreams.map((function(stream){return _this11._reverseStreams[stream.id]}))};var origAddStream=window.RTCPeerConnection.prototype.addStream;window.RTCPeerConnection.prototype.addStream=function(stream){var _this12=this;if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},stream.getTracks().forEach((function(track){if(_this12.getSenders().find((function(s){return s.track===track})))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[stream.id]){var newStream=new window.MediaStream(stream.getTracks());this._streams[stream.id]=newStream,this._reverseStreams[newStream.id]=stream,stream=newStream}origAddStream.apply(this,[stream])};var origRemoveStream=window.RTCPeerConnection.prototype.removeStream;function replaceInternalStreamId(pc,description){var sdp=description.sdp;return Object.keys(pc._reverseStreams||[]).forEach((function(internalId){var externalStream=pc._reverseStreams[internalId],internalStream=pc._streams[externalStream.id];sdp=sdp.replace(new RegExp(internalStream.id,"g"),externalStream.id)})),new RTCSessionDescription({type:description.type,sdp:sdp})}function replaceExternalStreamId(pc,description){var sdp=description.sdp;return Object.keys(pc._reverseStreams||[]).forEach((function(internalId){var externalStream=pc._reverseStreams[internalId],internalStream=pc._streams[externalStream.id];sdp=sdp.replace(new RegExp(externalStream.id,"g"),internalStream.id)})),new RTCSessionDescription({type:description.type,sdp:sdp})}window.RTCPeerConnection.prototype.removeStream=function(stream){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},origRemoveStream.apply(this,[this._streams[stream.id]||stream]),delete this._reverseStreams[this._streams[stream.id]?this._streams[stream.id].id:stream.id],delete this._streams[stream.id]},window.RTCPeerConnection.prototype.addTrack=function(track,stream){var _this13=this;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");var streams=[].slice.call(arguments,1);if(1!==streams.length||!streams[0].getTracks().find((function(t){return t===track})))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");var alreadyExists=this.getSenders().find((function(s){return s.track===track}));if(alreadyExists)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};var oldStream=this._streams[stream.id];if(oldStream)oldStream.addTrack(track),Promise.resolve().then((function(){_this13.dispatchEvent(new Event("negotiationneeded"))}));else{var newStream=new window.MediaStream([track]);this._streams[stream.id]=newStream,this._reverseStreams[newStream.id]=stream,this.addStream(newStream)}return this.getSenders().find((function(s){return s.track===track}))},["createOffer","createAnswer"].forEach((function(method){var nativeMethod=window.RTCPeerConnection.prototype[method],methodObj=_defineProperty({},method,(function(){var _this14=this,args=arguments,isLegacyCall=arguments.length&&"function"==typeof arguments[0];return isLegacyCall?nativeMethod.apply(this,[function(description){var desc=replaceInternalStreamId(_this14,description);args[0].apply(null,[desc])},function(err){args[1]&&args[1].apply(null,err)},arguments[2]]):nativeMethod.apply(this,arguments).then((function(description){return replaceInternalStreamId(_this14,description)}))}));window.RTCPeerConnection.prototype[method]=methodObj[method]}));var origSetLocalDescription=window.RTCPeerConnection.prototype.setLocalDescription;window.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=replaceExternalStreamId(this,arguments[0]),origSetLocalDescription.apply(this,arguments)):origSetLocalDescription.apply(this,arguments)};var origLocalDescription=Object.getOwnPropertyDescriptor(window.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(window.RTCPeerConnection.prototype,"localDescription",{get:function(){var description=origLocalDescription.get.apply(this);return""===description.type?description:replaceInternalStreamId(this,description)}}),window.RTCPeerConnection.prototype.removeTrack=function(sender){var _this15=this;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!sender._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(sender._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};var stream=void 0;Object.keys(this._streams).forEach((function(streamid){_this15._streams[streamid].getTracks().find((function(track){return sender.track===track}))&&(stream=_this15._streams[streamid])})),stream&&(1===stream.getTracks().length?this.removeStream(this._reverseStreams[stream.id]):stream.removeTrack(sender.track),this.dispatchEvent(new Event("negotiationneeded")))}},exports.shimPeerConnection=function(window,browserDetails){!window.RTCPeerConnection&&window.webkitRTCPeerConnection&&(window.RTCPeerConnection=window.webkitRTCPeerConnection);if(!window.RTCPeerConnection)return;browserDetails.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(method){var nativeMethod=window.RTCPeerConnection.prototype[method],methodObj=_defineProperty({},method,(function(){return arguments[0]=new("addIceCandidate"===method?window.RTCIceCandidate:window.RTCSessionDescription)(arguments[0]),nativeMethod.apply(this,arguments)}));window.RTCPeerConnection.prototype[method]=methodObj[method]}))},exports.fixNegotiationNeeded=function(window,browserDetails){utils.wrapPeerConnectionEvent(window,"negotiationneeded",(function(e){var pc=e.target;if(!(browserDetails.version<72||pc.getConfiguration&&"plan-b"===pc.getConfiguration().sdpSemantics)||"stable"===pc.signalingState)return e}))};var utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils.js"));function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function shimAddTrackRemoveTrackWithNative(window){window.RTCPeerConnection.prototype.getLocalStreams=function(){var _this8=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((function(streamId){return _this8._shimmedLocalStreams[streamId][0]}))};var origAddTrack=window.RTCPeerConnection.prototype.addTrack;window.RTCPeerConnection.prototype.addTrack=function(track,stream){if(!stream)return origAddTrack.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var sender=origAddTrack.apply(this,arguments);return this._shimmedLocalStreams[stream.id]?-1===this._shimmedLocalStreams[stream.id].indexOf(sender)&&this._shimmedLocalStreams[stream.id].push(sender):this._shimmedLocalStreams[stream.id]=[stream,sender],sender};var origAddStream=window.RTCPeerConnection.prototype.addStream;window.RTCPeerConnection.prototype.addStream=function(stream){var _this9=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},stream.getTracks().forEach((function(track){if(_this9.getSenders().find((function(s){return s.track===track})))throw new DOMException("Track already exists.","InvalidAccessError")}));var existingSenders=this.getSenders();origAddStream.apply(this,arguments);var newSenders=this.getSenders().filter((function(newSender){return-1===existingSenders.indexOf(newSender)}));this._shimmedLocalStreams[stream.id]=[stream].concat(newSenders)};var origRemoveStream=window.RTCPeerConnection.prototype.removeStream;window.RTCPeerConnection.prototype.removeStream=function(stream){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[stream.id],origRemoveStream.apply(this,arguments)};var origRemoveTrack=window.RTCPeerConnection.prototype.removeTrack;window.RTCPeerConnection.prototype.removeTrack=function(sender){var _this10=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},sender&&Object.keys(this._shimmedLocalStreams).forEach((function(streamId){var idx=_this10._shimmedLocalStreams[streamId].indexOf(sender);-1!==idx&&_this10._shimmedLocalStreams[streamId].splice(idx,1),1===_this10._shimmedLocalStreams[streamId].length&&delete _this10._shimmedLocalStreams[streamId]})),origRemoveTrack.apply(this,arguments)}}},{"../utils.js":70,"./getdisplaymedia":59,"./getusermedia":60}],59:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=function(window,getSourceId){if(window.navigator.mediaDevices&&"getDisplayMedia"in window.navigator.mediaDevices)return;if(!window.navigator.mediaDevices)return;if("function"!=typeof getSourceId)return void console.error("shimGetDisplayMedia: getSourceId argument is not a function");window.navigator.mediaDevices.getDisplayMedia=function(constraints){return getSourceId(constraints).then((function(sourceId){var widthSpecified=constraints.video&&constraints.video.width,heightSpecified=constraints.video&&constraints.video.height,frameRateSpecified=constraints.video&&constraints.video.frameRate;return constraints.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:sourceId,maxFrameRate:frameRateSpecified||3}},widthSpecified&&(constraints.video.mandatory.maxWidth=widthSpecified),heightSpecified&&(constraints.video.mandatory.maxHeight=heightSpecified),window.navigator.mediaDevices.getUserMedia(constraints)}))}}},{}],60:[function(require,module,exports){"use strict";function _typeof2(o){return(_typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(obj){return _typeof2(obj)}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":_typeof2(obj)};exports.shimGetUserMedia=function(window,browserDetails){var navigator=window&&window.navigator;if(!navigator.mediaDevices)return;var constraintsToChrome_=function(c){if("object"!==("undefined"==typeof c?"undefined":_typeof(c))||c.mandatory||c.optional)return c;var cc={};return Object.keys(c).forEach((function(key){if("require"!==key&&"advanced"!==key&&"mediaSource"!==key){var r="object"===_typeof(c[key])?c[key]:{ideal:c[key]};void 0!==r.exact&&"number"==typeof r.exact&&(r.min=r.max=r.exact);var oldname_=function(prefix,name){return prefix?prefix+name.charAt(0).toUpperCase()+name.slice(1):"deviceId"===name?"sourceId":name};if(void 0!==r.ideal){cc.optional=cc.optional||[];var oc={};"number"==typeof r.ideal?(oc[oldname_("min",key)]=r.ideal,cc.optional.push(oc),(oc={})[oldname_("max",key)]=r.ideal,cc.optional.push(oc)):(oc[oldname_("",key)]=r.ideal,cc.optional.push(oc))}void 0!==r.exact&&"number"!=typeof r.exact?(cc.mandatory=cc.mandatory||{},cc.mandatory[oldname_("",key)]=r.exact):["min","max"].forEach((function(mix){void 0!==r[mix]&&(cc.mandatory=cc.mandatory||{},cc.mandatory[oldname_(mix,key)]=r[mix])}))}})),c.advanced&&(cc.optional=(cc.optional||[]).concat(c.advanced)),cc},shimConstraints_=function(constraints,func){if(browserDetails.version>=61)return func(constraints);if((constraints=JSON.parse(JSON.stringify(constraints)))&&"object"===_typeof(constraints.audio)){var remap=function(obj,a,b){a in obj&&!(b in obj)&&(obj[b]=obj[a],delete obj[a])};remap((constraints=JSON.parse(JSON.stringify(constraints))).audio,"autoGainControl","googAutoGainControl"),remap(constraints.audio,"noiseSuppression","googNoiseSuppression"),constraints.audio=constraintsToChrome_(constraints.audio)}if(constraints&&"object"===_typeof(constraints.video)){var face=constraints.video.facingMode;face=face&&("object"===("undefined"==typeof face?"undefined":_typeof(face))?face:{ideal:face});var getSupportedFacingModeLies=browserDetails.version<66;if(face&&("user"===face.exact||"environment"===face.exact||"user"===face.ideal||"environment"===face.ideal)&&(!navigator.mediaDevices.getSupportedConstraints||!navigator.mediaDevices.getSupportedConstraints().facingMode||getSupportedFacingModeLies)){delete constraints.video.facingMode;var matches=void 0;if("environment"===face.exact||"environment"===face.ideal?matches=["back","rear"]:"user"!==face.exact&&"user"!==face.ideal||(matches=["front"]),matches)return navigator.mediaDevices.enumerateDevices().then((function(devices){var dev=(devices=devices.filter((function(d){return"videoinput"===d.kind}))).find((function(d){return matches.some((function(match){return d.label.toLowerCase().includes(match)}))}));return!dev&&devices.length&&matches.includes("back")&&(dev=devices[devices.length-1]),dev&&(constraints.video.deviceId=face.exact?{exact:dev.deviceId}:{ideal:dev.deviceId}),constraints.video=constraintsToChrome_(constraints.video),logging("chrome: "+JSON.stringify(constraints)),func(constraints)}))}constraints.video=constraintsToChrome_(constraints.video)}return logging("chrome: "+JSON.stringify(constraints)),func(constraints)},shimError_=function(e){return browserDetails.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(navigator.getUserMedia=function(constraints,onSuccess,onError){shimConstraints_(constraints,(function(c){navigator.webkitGetUserMedia(c,onSuccess,(function(e){onError&&onError(shimError_(e))}))}))}.bind(navigator),navigator.mediaDevices.getUserMedia){var origGetUserMedia=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getUserMedia=function(cs){return shimConstraints_(cs,(function(c){return origGetUserMedia(c).then((function(stream){if(c.audio&&!stream.getAudioTracks().length||c.video&&!stream.getVideoTracks().length)throw stream.getTracks().forEach((function(track){track.stop()})),new DOMException("","NotFoundError");return stream}),(function(e){return Promise.reject(shimError_(e))}))}))}}};var logging=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils.js")).log},{"../utils.js":70}],61:[function(require,module,exports){"use strict";function _typeof2(o){return(_typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(obj){return _typeof2(obj)}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":_typeof2(obj)};exports.shimRTCIceCandidate=function(window){if(!window.RTCIceCandidate||window.RTCIceCandidate&&"foundation"in window.RTCIceCandidate.prototype)return;var NativeRTCIceCandidate=window.RTCIceCandidate;window.RTCIceCandidate=function(args){if("object"===("undefined"==typeof args?"undefined":_typeof(args))&&args.candidate&&0===args.candidate.indexOf("a=")&&((args=JSON.parse(JSON.stringify(args))).candidate=args.candidate.substr(2)),args.candidate&&args.candidate.length){var nativeCandidate=new NativeRTCIceCandidate(args),parsedCandidate=_sdp2.default.parseCandidate(args.candidate),augmentedCandidate=Object.assign(nativeCandidate,parsedCandidate);return augmentedCandidate.toJSON=function(){return{candidate:augmentedCandidate.candidate,sdpMid:augmentedCandidate.sdpMid,sdpMLineIndex:augmentedCandidate.sdpMLineIndex,usernameFragment:augmentedCandidate.usernameFragment}},augmentedCandidate}return new NativeRTCIceCandidate(args)},window.RTCIceCandidate.prototype=NativeRTCIceCandidate.prototype,utils.wrapPeerConnectionEvent(window,"icecandidate",(function(e){return e.candidate&&Object.defineProperty(e,"candidate",{value:new window.RTCIceCandidate(e.candidate),writable:"false"}),e}))},exports.shimMaxMessageSize=function(window,browserDetails){if(!window.RTCPeerConnection)return;"sctp"in window.RTCPeerConnection.prototype||Object.defineProperty(window.RTCPeerConnection.prototype,"sctp",{get:function(){return"undefined"==typeof this._sctp?null:this._sctp}});var sctpInDescription=function(description){if(!description||!description.sdp)return!1;var sections=_sdp2.default.splitSections(description.sdp);return sections.shift(),sections.some((function(mediaSection){var mLine=_sdp2.default.parseMLine(mediaSection);return mLine&&"application"===mLine.kind&&-1!==mLine.protocol.indexOf("SCTP")}))},getRemoteFirefoxVersion=function(description){var match=description.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===match||match.length<2)return-1;var version=parseInt(match[1],10);return version!=version?-1:version},getCanSendMaxMessageSize=function(remoteIsFirefox){var canSendMaxMessageSize=65536;return"firefox"===browserDetails.browser&&(canSendMaxMessageSize=browserDetails.version<57?-1===remoteIsFirefox?16384:2147483637:browserDetails.version<60?57===browserDetails.version?65535:65536:2147483637),canSendMaxMessageSize},getMaxMessageSize=function(description,remoteIsFirefox){var maxMessageSize=65536;"firefox"===browserDetails.browser&&57===browserDetails.version&&(maxMessageSize=65535);var match=_sdp2.default.matchPrefix(description.sdp,"a=max-message-size:");return match.length>0?maxMessageSize=parseInt(match[0].substr(19),10):"firefox"===browserDetails.browser&&-1!==remoteIsFirefox&&(maxMessageSize=2147483637),maxMessageSize},origSetRemoteDescription=window.RTCPeerConnection.prototype.setRemoteDescription;window.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===browserDetails.browser&&browserDetails.version>=76){var _getConfiguration=this.getConfiguration(),sdpSemantics=_getConfiguration.sdpSemantics;"plan-b"===sdpSemantics&&Object.defineProperty(this,"sctp",{get:function(){return"undefined"==typeof this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(sctpInDescription(arguments[0])){var isFirefox=getRemoteFirefoxVersion(arguments[0]),canSendMMS=getCanSendMaxMessageSize(isFirefox),remoteMMS=getMaxMessageSize(arguments[0],isFirefox),maxMessageSize=void 0;maxMessageSize=0===canSendMMS&&0===remoteMMS?Number.POSITIVE_INFINITY:0===canSendMMS||0===remoteMMS?Math.max(canSendMMS,remoteMMS):Math.min(canSendMMS,remoteMMS);var sctp={};Object.defineProperty(sctp,"maxMessageSize",{get:function(){return maxMessageSize}}),this._sctp=sctp}return origSetRemoteDescription.apply(this,arguments)}},exports.shimSendThrowTypeError=function(window){if(!window.RTCPeerConnection||!("createDataChannel"in window.RTCPeerConnection.prototype))return;function wrapDcSend(dc,pc){var origDataChannelSend=dc.send;dc.send=function(){var data=arguments[0],length=data.length||data.size||data.byteLength;if("open"===dc.readyState&&pc.sctp&&length>pc.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+pc.sctp.maxMessageSize+" bytes)");return origDataChannelSend.apply(dc,arguments)}}var origCreateDataChannel=window.RTCPeerConnection.prototype.createDataChannel;window.RTCPeerConnection.prototype.createDataChannel=function(){var dataChannel=origCreateDataChannel.apply(this,arguments);return wrapDcSend(dataChannel,this),dataChannel},utils.wrapPeerConnectionEvent(window,"datachannel",(function(e){return wrapDcSend(e.channel,e.target),e}))},exports.shimConnectionState=function(window){if(!window.RTCPeerConnection||"connectionState"in window.RTCPeerConnection.prototype)return;var proto=window.RTCPeerConnection.prototype;Object.defineProperty(proto,"connectionState",{get:function(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(proto,"onconnectionstatechange",{get:function(){return this._onconnectionstatechange||null},set:function(cb){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),cb&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=cb)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((function(method){var origMethod=proto[method];proto[method]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=function(e){var pc=e.target;if(pc._lastConnectionState!==pc.connectionState){pc._lastConnectionState=pc.connectionState;var newEvent=new Event("connectionstatechange",e);pc.dispatchEvent(newEvent)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),origMethod.apply(this,arguments)}}))},exports.removeExtmapAllowMixed=function(window,browserDetails){if(!window.RTCPeerConnection)return;if("chrome"===browserDetails.browser&&browserDetails.version>=71)return;if("safari"===browserDetails.browser&&browserDetails.version>=605)return;var nativeSRD=window.RTCPeerConnection.prototype.setRemoteDescription;window.RTCPeerConnection.prototype.setRemoteDescription=function(desc){if(desc&&desc.sdp&&-1!==desc.sdp.indexOf("\na=extmap-allow-mixed")){var sdp=desc.sdp.split("\n").filter((function(line){return"a=extmap-allow-mixed"!==line.trim()})).join("\n");window.RTCSessionDescription&&desc instanceof window.RTCSessionDescription?arguments[0]=new window.RTCSessionDescription({type:desc.type,sdp:sdp}):desc.sdp=sdp}return nativeSRD.apply(this,arguments)}},exports.shimAddIceCandidateNullOrEmpty=function(window,browserDetails){if(!window.RTCPeerConnection||!window.RTCPeerConnection.prototype)return;var nativeAddIceCandidate=window.RTCPeerConnection.prototype.addIceCandidate;if(!nativeAddIceCandidate||0===nativeAddIceCandidate.length)return;window.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===browserDetails.browser&&browserDetails.version<78||"firefox"===browserDetails.browser&&browserDetails.version<68||"safari"===browserDetails.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():nativeAddIceCandidate.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())}};var obj,_sdp=require("sdp"),_sdp2=(obj=_sdp)&&obj.__esModule?obj:{default:obj},utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("./utils"))},{"./utils":70,sdp:38}],62:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=exports.shimGetUserMedia=void 0;var _getusermedia=require("./getusermedia");Object.defineProperty(exports,"shimGetUserMedia",{enumerable:!0,get:function(){return _getusermedia.shimGetUserMedia}});var _getdisplaymedia=require("./getdisplaymedia");Object.defineProperty(exports,"shimGetDisplayMedia",{enumerable:!0,get:function(){return _getdisplaymedia.shimGetDisplayMedia}}),exports.shimPeerConnection=function(window,browserDetails){if(window.RTCIceGatherer&&(window.RTCIceCandidate||(window.RTCIceCandidate=function(args){return args}),window.RTCSessionDescription||(window.RTCSessionDescription=function(args){return args}),browserDetails.version<15025)){var origMSTEnabled=Object.getOwnPropertyDescriptor(window.MediaStreamTrack.prototype,"enabled");Object.defineProperty(window.MediaStreamTrack.prototype,"enabled",{set:function(value){origMSTEnabled.set.call(this,value);var ev=new Event("enabled");ev.enabled=value,this.dispatchEvent(ev)}})}window.RTCRtpSender&&!("dtmf"in window.RTCRtpSender.prototype)&&Object.defineProperty(window.RTCRtpSender.prototype,"dtmf",{get:function(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=new window.RTCDtmfSender(this):"video"===this.track.kind&&(this._dtmf=null)),this._dtmf}});window.RTCDtmfSender&&!window.RTCDTMFSender&&(window.RTCDTMFSender=window.RTCDtmfSender);var RTCPeerConnectionShim=(0,_rtcpeerconnectionShim2.default)(window,browserDetails.version);window.RTCPeerConnection=function(config){return config&&config.iceServers&&(config.iceServers=(0,_filtericeservers.filterIceServers)(config.iceServers,browserDetails.version),utils.log("ICE servers after filtering:",config.iceServers)),new RTCPeerConnectionShim(config)},window.RTCPeerConnection.prototype=RTCPeerConnectionShim.prototype},exports.shimReplaceTrack=function(window){window.RTCRtpSender&&!("replaceTrack"in window.RTCRtpSender.prototype)&&(window.RTCRtpSender.prototype.replaceTrack=window.RTCRtpSender.prototype.setTrack)};var obj,utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils")),_filtericeservers=require("./filtericeservers"),_rtcpeerconnectionShim=require("rtcpeerconnection-shim"),_rtcpeerconnectionShim2=(obj=_rtcpeerconnectionShim)&&obj.__esModule?obj:{default:obj}},{"../utils":70,"./filtericeservers":63,"./getdisplaymedia":64,"./getusermedia":65,"rtcpeerconnection-shim":37}],63:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.filterIceServers=function(iceServers,edgeVersion){var hasTurn=!1;return(iceServers=JSON.parse(JSON.stringify(iceServers))).filter((function(server){if(server&&(server.urls||server.url)){var urls=server.urls||server.url;server.url&&!server.urls&&utils.deprecated("RTCIceServer.url","RTCIceServer.urls");var isString="string"==typeof urls;return isString&&(urls=[urls]),urls=urls.filter((function(url){if(0===url.indexOf("stun:"))return!1;var validTurn=url.startsWith("turn")&&!url.startsWith("turn:[")&&url.includes("transport=udp");return validTurn&&!hasTurn?(hasTurn=!0,!0):validTurn&&!hasTurn})),delete server.url,server.urls=isString?urls[0]:urls,!!urls.length}}))};var utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils"))},{"../utils":70}],64:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=function(window){if(!("getDisplayMedia"in window.navigator))return;if(!window.navigator.mediaDevices)return;if(window.navigator.mediaDevices&&"getDisplayMedia"in window.navigator.mediaDevices)return;window.navigator.mediaDevices.getDisplayMedia=window.navigator.getDisplayMedia.bind(window.navigator)}},{}],65:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetUserMedia=function(window){var navigator=window&&window.navigator,origGetUserMedia=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getUserMedia=function(c){return origGetUserMedia(c).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))}))}}},{}],66:[function(require,module,exports){"use strict";function _typeof2(o){return(_typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=exports.shimGetUserMedia=void 0;var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(obj){return _typeof2(obj)}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":_typeof2(obj)},_getusermedia=require("./getusermedia");Object.defineProperty(exports,"shimGetUserMedia",{enumerable:!0,get:function(){return _getusermedia.shimGetUserMedia}});var _getdisplaymedia=require("./getdisplaymedia");Object.defineProperty(exports,"shimGetDisplayMedia",{enumerable:!0,get:function(){return _getdisplaymedia.shimGetDisplayMedia}}),exports.shimOnTrack=function(window){"object"===("undefined"==typeof window?"undefined":_typeof(window))&&window.RTCTrackEvent&&"receiver"in window.RTCTrackEvent.prototype&&!("transceiver"in window.RTCTrackEvent.prototype)&&Object.defineProperty(window.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})},exports.shimPeerConnection=function(window,browserDetails){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection&&!window.mozRTCPeerConnection)return;!window.RTCPeerConnection&&window.mozRTCPeerConnection&&(window.RTCPeerConnection=window.mozRTCPeerConnection);browserDetails.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(method){var nativeMethod=window.RTCPeerConnection.prototype[method],methodObj=function(obj,key,value){key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value;return obj}({},method,(function(){return arguments[0]=new("addIceCandidate"===method?window.RTCIceCandidate:window.RTCSessionDescription)(arguments[0]),nativeMethod.apply(this,arguments)}));window.RTCPeerConnection.prototype[method]=methodObj[method]}));var modernStatsTypes={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},nativeGetStats=window.RTCPeerConnection.prototype.getStats;window.RTCPeerConnection.prototype.getStats=function(){var _arguments=Array.prototype.slice.call(arguments),selector=_arguments[0],onSucc=_arguments[1],onErr=_arguments[2];return nativeGetStats.apply(this,[selector||null]).then((function(stats){if(browserDetails.version<53&&!onSucc)try{stats.forEach((function(stat){stat.type=modernStatsTypes[stat.type]||stat.type}))}catch(e){if("TypeError"!==e.name)throw e;stats.forEach((function(stat,i){stats.set(i,Object.assign({},stat,{type:modernStatsTypes[stat.type]||stat.type}))}))}return stats})).then(onSucc,onErr)}},exports.shimSenderGetStats=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection||!window.RTCRtpSender)return;if(window.RTCRtpSender&&"getStats"in window.RTCRtpSender.prototype)return;var origGetSenders=window.RTCPeerConnection.prototype.getSenders;origGetSenders&&(window.RTCPeerConnection.prototype.getSenders=function(){var _this=this,senders=origGetSenders.apply(this,[]);return senders.forEach((function(sender){return sender._pc=_this})),senders});var origAddTrack=window.RTCPeerConnection.prototype.addTrack;origAddTrack&&(window.RTCPeerConnection.prototype.addTrack=function(){var sender=origAddTrack.apply(this,arguments);return sender._pc=this,sender});window.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}},exports.shimReceiverGetStats=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection||!window.RTCRtpSender)return;if(window.RTCRtpSender&&"getStats"in window.RTCRtpReceiver.prototype)return;var origGetReceivers=window.RTCPeerConnection.prototype.getReceivers;origGetReceivers&&(window.RTCPeerConnection.prototype.getReceivers=function(){var _this2=this,receivers=origGetReceivers.apply(this,[]);return receivers.forEach((function(receiver){return receiver._pc=_this2})),receivers});utils.wrapPeerConnectionEvent(window,"track",(function(e){return e.receiver._pc=e.srcElement,e})),window.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}},exports.shimRemoveStream=function(window){if(!window.RTCPeerConnection||"removeStream"in window.RTCPeerConnection.prototype)return;window.RTCPeerConnection.prototype.removeStream=function(stream){var _this3=this;utils.deprecated("removeStream","removeTrack"),this.getSenders().forEach((function(sender){sender.track&&stream.getTracks().includes(sender.track)&&_this3.removeTrack(sender)}))}},exports.shimRTCDataChannel=function(window){window.DataChannel&&!window.RTCDataChannel&&(window.RTCDataChannel=window.DataChannel)},exports.shimAddTransceiver=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection)return;var origAddTransceiver=window.RTCPeerConnection.prototype.addTransceiver;origAddTransceiver&&(window.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];var initParameters=arguments[1],shouldPerformCheck=initParameters&&"sendEncodings"in initParameters;shouldPerformCheck&&initParameters.sendEncodings.forEach((function(encodingParam){if("rid"in encodingParam){if(!/^[a-z0-9]{0,16}$/i.test(encodingParam.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in encodingParam&&!(parseFloat(encodingParam.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in encodingParam&&!(parseFloat(encodingParam.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));var transceiver=origAddTransceiver.apply(this,arguments);if(shouldPerformCheck){var sender=transceiver.sender,params=sender.getParameters();(!("encodings"in params)||1===params.encodings.length&&0===Object.keys(params.encodings[0]).length)&&(params.encodings=initParameters.sendEncodings,sender.sendEncodings=initParameters.sendEncodings,this.setParametersPromises.push(sender.setParameters(params).then((function(){delete sender.sendEncodings})).catch((function(){delete sender.sendEncodings}))))}return transceiver})},exports.shimGetParameters=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCRtpSender)return;var origGetParameters=window.RTCRtpSender.prototype.getParameters;origGetParameters&&(window.RTCRtpSender.prototype.getParameters=function(){var params=origGetParameters.apply(this,arguments);return"encodings"in params||(params.encodings=[].concat(this.sendEncodings||[{}])),params})},exports.shimCreateOffer=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection)return;var origCreateOffer=window.RTCPeerConnection.prototype.createOffer;window.RTCPeerConnection.prototype.createOffer=function(){var _this4=this,_arguments2=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((function(){return origCreateOffer.apply(_this4,_arguments2)})).finally((function(){_this4.setParametersPromises=[]})):origCreateOffer.apply(this,arguments)}},exports.shimCreateAnswer=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection)return;var origCreateAnswer=window.RTCPeerConnection.prototype.createAnswer;window.RTCPeerConnection.prototype.createAnswer=function(){var _this5=this,_arguments3=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((function(){return origCreateAnswer.apply(_this5,_arguments3)})).finally((function(){_this5.setParametersPromises=[]})):origCreateAnswer.apply(this,arguments)}};var utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils"))},{"../utils":70,"./getdisplaymedia":67,"./getusermedia":68}],67:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=function(window,preferredMediaSource){if(window.navigator.mediaDevices&&"getDisplayMedia"in window.navigator.mediaDevices)return;if(!window.navigator.mediaDevices)return;window.navigator.mediaDevices.getDisplayMedia=function(constraints){if(!constraints||!constraints.video){var err=new DOMException("getDisplayMedia without video constraints is undefined");return err.name="NotFoundError",err.code=8,Promise.reject(err)}return!0===constraints.video?constraints.video={mediaSource:preferredMediaSource}:constraints.video.mediaSource=preferredMediaSource,window.navigator.mediaDevices.getUserMedia(constraints)}}},{}],68:[function(require,module,exports){"use strict";function _typeof2(o){return(_typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(obj){return _typeof2(obj)}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":_typeof2(obj)};exports.shimGetUserMedia=function(window,browserDetails){var navigator=window&&window.navigator,MediaStreamTrack=window&&window.MediaStreamTrack;if(navigator.getUserMedia=function(constraints,onSuccess,onError){utils.deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),navigator.mediaDevices.getUserMedia(constraints).then(onSuccess,onError)},!(browserDetails.version>55&&"autoGainControl"in navigator.mediaDevices.getSupportedConstraints())){var remap=function(obj,a,b){a in obj&&!(b in obj)&&(obj[b]=obj[a],delete obj[a])},nativeGetUserMedia=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);if(navigator.mediaDevices.getUserMedia=function(c){return"object"===("undefined"==typeof c?"undefined":_typeof(c))&&"object"===_typeof(c.audio)&&(c=JSON.parse(JSON.stringify(c)),remap(c.audio,"autoGainControl","mozAutoGainControl"),remap(c.audio,"noiseSuppression","mozNoiseSuppression")),nativeGetUserMedia(c)},MediaStreamTrack&&MediaStreamTrack.prototype.getSettings){var nativeGetSettings=MediaStreamTrack.prototype.getSettings;MediaStreamTrack.prototype.getSettings=function(){var obj=nativeGetSettings.apply(this,arguments);return remap(obj,"mozAutoGainControl","autoGainControl"),remap(obj,"mozNoiseSuppression","noiseSuppression"),obj}}if(MediaStreamTrack&&MediaStreamTrack.prototype.applyConstraints){var nativeApplyConstraints=MediaStreamTrack.prototype.applyConstraints;MediaStreamTrack.prototype.applyConstraints=function(c){return"audio"===this.kind&&"object"===("undefined"==typeof c?"undefined":_typeof(c))&&(c=JSON.parse(JSON.stringify(c)),remap(c,"autoGainControl","mozAutoGainControl"),remap(c,"noiseSuppression","mozNoiseSuppression")),nativeApplyConstraints.apply(this,[c])}}}};var utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils"))},{"../utils":70}],69:[function(require,module,exports){"use strict";function _typeof2(o){return(_typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(obj){return _typeof2(obj)}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":_typeof2(obj)};exports.shimLocalStreamsAPI=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection)return;"getLocalStreams"in window.RTCPeerConnection.prototype||(window.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams});if(!("addStream"in window.RTCPeerConnection.prototype)){var _addTrack=window.RTCPeerConnection.prototype.addTrack;window.RTCPeerConnection.prototype.addStream=function(stream){var _this=this;this._localStreams||(this._localStreams=[]),this._localStreams.includes(stream)||this._localStreams.push(stream),stream.getAudioTracks().forEach((function(track){return _addTrack.call(_this,track,stream)})),stream.getVideoTracks().forEach((function(track){return _addTrack.call(_this,track,stream)}))},window.RTCPeerConnection.prototype.addTrack=function(track){for(var _this2=this,_len=arguments.length,streams=Array(_len>1?_len-1:0),_key=1;_key<_len;_key++)streams[_key-1]=arguments[_key];return streams&&streams.forEach((function(stream){_this2._localStreams?_this2._localStreams.includes(stream)||_this2._localStreams.push(stream):_this2._localStreams=[stream]})),_addTrack.apply(this,arguments)}}"removeStream"in window.RTCPeerConnection.prototype||(window.RTCPeerConnection.prototype.removeStream=function(stream){var _this3=this;this._localStreams||(this._localStreams=[]);var index=this._localStreams.indexOf(stream);if(-1!==index){this._localStreams.splice(index,1);var tracks=stream.getTracks();this.getSenders().forEach((function(sender){tracks.includes(sender.track)&&_this3.removeTrack(sender)}))}})},exports.shimRemoteStreamsAPI=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection)return;"getRemoteStreams"in window.RTCPeerConnection.prototype||(window.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]});if(!("onaddstream"in window.RTCPeerConnection.prototype)){Object.defineProperty(window.RTCPeerConnection.prototype,"onaddstream",{get:function(){return this._onaddstream},set:function(f){var _this4=this;this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=f),this.addEventListener("track",this._onaddstreampoly=function(e){e.streams.forEach((function(stream){if(_this4._remoteStreams||(_this4._remoteStreams=[]),!_this4._remoteStreams.includes(stream)){_this4._remoteStreams.push(stream);var event=new Event("addstream");event.stream=stream,_this4.dispatchEvent(event)}}))})}});var origSetRemoteDescription=window.RTCPeerConnection.prototype.setRemoteDescription;window.RTCPeerConnection.prototype.setRemoteDescription=function(){var pc=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(e){e.streams.forEach((function(stream){if(pc._remoteStreams||(pc._remoteStreams=[]),!(pc._remoteStreams.indexOf(stream)>=0)){pc._remoteStreams.push(stream);var event=new Event("addstream");event.stream=stream,pc.dispatchEvent(event)}}))}),origSetRemoteDescription.apply(pc,arguments)}}},exports.shimCallbacksAPI=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||!window.RTCPeerConnection)return;var prototype=window.RTCPeerConnection.prototype,origCreateOffer=prototype.createOffer,origCreateAnswer=prototype.createAnswer,setLocalDescription=prototype.setLocalDescription,setRemoteDescription=prototype.setRemoteDescription,addIceCandidate=prototype.addIceCandidate;prototype.createOffer=function(successCallback,failureCallback){var options=arguments.length>=2?arguments[2]:arguments[0],promise=origCreateOffer.apply(this,[options]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise},prototype.createAnswer=function(successCallback,failureCallback){var options=arguments.length>=2?arguments[2]:arguments[0],promise=origCreateAnswer.apply(this,[options]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise};var withCallback=function(description,successCallback,failureCallback){var promise=setLocalDescription.apply(this,[description]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise};prototype.setLocalDescription=withCallback,withCallback=function(description,successCallback,failureCallback){var promise=setRemoteDescription.apply(this,[description]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise},prototype.setRemoteDescription=withCallback,withCallback=function(candidate,successCallback,failureCallback){var promise=addIceCandidate.apply(this,[candidate]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise},prototype.addIceCandidate=withCallback},exports.shimGetUserMedia=function(window){var navigator=window&&window.navigator;if(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia){var mediaDevices=navigator.mediaDevices,_getUserMedia=mediaDevices.getUserMedia.bind(mediaDevices);navigator.mediaDevices.getUserMedia=function(constraints){return _getUserMedia(shimConstraints(constraints))}}!navigator.getUserMedia&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&(navigator.getUserMedia=function(constraints,cb,errcb){navigator.mediaDevices.getUserMedia(constraints).then(cb,errcb)}.bind(navigator))},exports.shimConstraints=shimConstraints,exports.shimRTCIceServerUrls=function(window){if(!window.RTCPeerConnection)return;var OrigPeerConnection=window.RTCPeerConnection;window.RTCPeerConnection=function(pcConfig,pcConstraints){if(pcConfig&&pcConfig.iceServers){for(var newIceServers=[],i=0;i<pcConfig.iceServers.length;i++){var server=pcConfig.iceServers[i];!server.hasOwnProperty("urls")&&server.hasOwnProperty("url")?(utils.deprecated("RTCIceServer.url","RTCIceServer.urls"),(server=JSON.parse(JSON.stringify(server))).urls=server.url,delete server.url,newIceServers.push(server)):newIceServers.push(pcConfig.iceServers[i])}pcConfig.iceServers=newIceServers}return new OrigPeerConnection(pcConfig,pcConstraints)},window.RTCPeerConnection.prototype=OrigPeerConnection.prototype,"generateCertificate"in OrigPeerConnection&&Object.defineProperty(window.RTCPeerConnection,"generateCertificate",{get:function(){return OrigPeerConnection.generateCertificate}})},exports.shimTrackEventTransceiver=function(window){"object"===("undefined"==typeof window?"undefined":_typeof(window))&&window.RTCTrackEvent&&"receiver"in window.RTCTrackEvent.prototype&&!("transceiver"in window.RTCTrackEvent.prototype)&&Object.defineProperty(window.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})},exports.shimCreateOfferLegacy=function(window){var origCreateOffer=window.RTCPeerConnection.prototype.createOffer;window.RTCPeerConnection.prototype.createOffer=function(offerOptions){if(offerOptions){"undefined"!=typeof offerOptions.offerToReceiveAudio&&(offerOptions.offerToReceiveAudio=!!offerOptions.offerToReceiveAudio);var audioTransceiver=this.getTransceivers().find((function(transceiver){return"audio"===transceiver.receiver.track.kind}));!1===offerOptions.offerToReceiveAudio&&audioTransceiver?"sendrecv"===audioTransceiver.direction?audioTransceiver.setDirection?audioTransceiver.setDirection("sendonly"):audioTransceiver.direction="sendonly":"recvonly"===audioTransceiver.direction&&(audioTransceiver.setDirection?audioTransceiver.setDirection("inactive"):audioTransceiver.direction="inactive"):!0!==offerOptions.offerToReceiveAudio||audioTransceiver||this.addTransceiver("audio"),"undefined"!=typeof offerOptions.offerToReceiveVideo&&(offerOptions.offerToReceiveVideo=!!offerOptions.offerToReceiveVideo);var videoTransceiver=this.getTransceivers().find((function(transceiver){return"video"===transceiver.receiver.track.kind}));!1===offerOptions.offerToReceiveVideo&&videoTransceiver?"sendrecv"===videoTransceiver.direction?videoTransceiver.setDirection?videoTransceiver.setDirection("sendonly"):videoTransceiver.direction="sendonly":"recvonly"===videoTransceiver.direction&&(videoTransceiver.setDirection?videoTransceiver.setDirection("inactive"):videoTransceiver.direction="inactive"):!0!==offerOptions.offerToReceiveVideo||videoTransceiver||this.addTransceiver("video")}return origCreateOffer.apply(this,arguments)}},exports.shimAudioContext=function(window){if("object"!==("undefined"==typeof window?"undefined":_typeof(window))||window.AudioContext)return;window.AudioContext=window.webkitAudioContext};var utils=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../utils"));function shimConstraints(constraints){return constraints&&void 0!==constraints.video?Object.assign({},constraints,{video:utils.compactObject(constraints.video)}):constraints}},{"../utils":70}],70:[function(require,module,exports){"use strict";function _typeof2(o){return(_typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(obj){return _typeof2(obj)}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":_typeof2(obj)};exports.extractVersion=extractVersion,exports.wrapPeerConnectionEvent=function(window,eventNameToWrap,wrapper){if(!window.RTCPeerConnection)return;var proto=window.RTCPeerConnection.prototype,nativeAddEventListener=proto.addEventListener;proto.addEventListener=function(nativeEventName,cb){if(nativeEventName!==eventNameToWrap)return nativeAddEventListener.apply(this,arguments);var wrappedCallback=function(e){var modifiedEvent=wrapper(e);modifiedEvent&&(cb.handleEvent?cb.handleEvent(modifiedEvent):cb(modifiedEvent))};return this._eventMap=this._eventMap||{},this._eventMap[eventNameToWrap]||(this._eventMap[eventNameToWrap]=new Map),this._eventMap[eventNameToWrap].set(cb,wrappedCallback),nativeAddEventListener.apply(this,[nativeEventName,wrappedCallback])};var nativeRemoveEventListener=proto.removeEventListener;proto.removeEventListener=function(nativeEventName,cb){if(nativeEventName!==eventNameToWrap||!this._eventMap||!this._eventMap[eventNameToWrap])return nativeRemoveEventListener.apply(this,arguments);if(!this._eventMap[eventNameToWrap].has(cb))return nativeRemoveEventListener.apply(this,arguments);var unwrappedCb=this._eventMap[eventNameToWrap].get(cb);return this._eventMap[eventNameToWrap].delete(cb),0===this._eventMap[eventNameToWrap].size&&delete this._eventMap[eventNameToWrap],0===Object.keys(this._eventMap).length&&delete this._eventMap,nativeRemoveEventListener.apply(this,[nativeEventName,unwrappedCb])},Object.defineProperty(proto,"on"+eventNameToWrap,{get:function(){return this["_on"+eventNameToWrap]},set:function(cb){this["_on"+eventNameToWrap]&&(this.removeEventListener(eventNameToWrap,this["_on"+eventNameToWrap]),delete this["_on"+eventNameToWrap]),cb&&this.addEventListener(eventNameToWrap,this["_on"+eventNameToWrap]=cb)},enumerable:!0,configurable:!0})},exports.disableLog=function(bool){if("boolean"!=typeof bool)return new Error("Argument type: "+("undefined"==typeof bool?"undefined":_typeof(bool))+". Please use a boolean.");return logDisabled_=bool,bool?"adapter.js logging disabled":"adapter.js logging enabled"},exports.disableWarnings=function(bool){if("boolean"!=typeof bool)return new Error("Argument type: "+("undefined"==typeof bool?"undefined":_typeof(bool))+". Please use a boolean.");return deprecationWarnings_=!bool,"adapter.js deprecation warnings "+(bool?"disabled":"enabled")},exports.log=function(){if("object"===("undefined"==typeof window?"undefined":_typeof(window))){if(logDisabled_)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}},exports.deprecated=function(oldMethod,newMethod){if(!deprecationWarnings_)return;console.warn(oldMethod+" is deprecated, please use "+newMethod+" instead.")},exports.detectBrowser=function(window){var result={browser:null,version:null};if("undefined"==typeof window||!window.navigator)return result.browser="Not a browser.",result;var navigator=window.navigator;if(navigator.mozGetUserMedia)result.browser="firefox",result.version=extractVersion(navigator.userAgent,/Firefox\/(\d+)\./,1);else if(navigator.webkitGetUserMedia||!1===window.isSecureContext&&window.webkitRTCPeerConnection&&!window.RTCIceGatherer)result.browser="chrome",result.version=extractVersion(navigator.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(navigator.mediaDevices&&navigator.userAgent.match(/Edge\/(\d+).(\d+)$/))result.browser="edge",result.version=extractVersion(navigator.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!window.RTCPeerConnection||!navigator.userAgent.match(/AppleWebKit\/(\d+)\./))return result.browser="Not a supported browser.",result;result.browser="safari",result.version=extractVersion(navigator.userAgent,/AppleWebKit\/(\d+)\./,1),result.supportsUnifiedPlan=window.RTCRtpTransceiver&&"currentDirection"in window.RTCRtpTransceiver.prototype}return result},exports.compactObject=function compactObject(data){if(!isObject(data))return data;return Object.keys(data).reduce((function(accumulator,key){var isObj=isObject(data[key]),value=isObj?compactObject(data[key]):data[key],isEmptyObject=isObj&&!Object.keys(value).length;return void 0===value||isEmptyObject?accumulator:Object.assign(accumulator,function(obj,key,value){key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value;return obj}({},key,value))}),{})},exports.walkStats=walkStats,exports.filterStats=function(result,track,outbound){var streamStatsType=outbound?"outbound-rtp":"inbound-rtp",filteredResult=new Map;if(null===track)return filteredResult;var trackStats=[];return result.forEach((function(value){"track"===value.type&&value.trackIdentifier===track.id&&trackStats.push(value)})),trackStats.forEach((function(trackStat){result.forEach((function(stats){stats.type===streamStatsType&&stats.trackId===trackStat.id&&walkStats(result,stats,filteredResult)}))})),filteredResult};var logDisabled_=!0,deprecationWarnings_=!0;function extractVersion(uastring,expr,pos){var match=uastring.match(expr);return match&&match.length>=pos&&parseInt(match[pos],10)}function isObject(val){return"[object Object]"===Object.prototype.toString.call(val)}function walkStats(stats,base,resultSet){base&&!resultSet.has(base.id)&&(resultSet.set(base.id,base),Object.keys(base).forEach((function(name){name.endsWith("Id")?walkStats(stats,stats.get(base[name]),resultSet):name.endsWith("Ids")&&base[name].forEach((function(id){walkStats(stats,stats.get(id),resultSet)}))})))}},{}],71:[function(require,module,exports){"use strict";function _regenerator(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function i(r,n,o,i){var c=n&&n.prototype instanceof Generator?n:Generator,u=Object.create(c.prototype);return _regeneratorDefine2(u,"_invoke",function(r,n,o){var i,c,u,f=0,p=o||[],y=!1,G={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return i=t,c=0,u=e,G.n=r,a}};function d(r,n){for(c=r,u=n,t=0;!y&&f&&!o&&t<p.length;t++){var o,i=p[t],d=G.p,l=i[2];r>3?(o=l===n)&&(u=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&d<i[1])?(c=0,G.v=n,G.n=i[1]):d<l&&(o=r<3||i[0]>n||n>l)&&(i[4]=r,i[5]=n,G.n=l,c=0))}if(o||r>1)return a;throw y=!0,n}return function(o,p,l){if(f>1)throw TypeError("Generator is already running");for(y&&1===p&&d(p,l),c=p,u=l;(t=c<2?e:u)||!y;){i||(c?c<3?(c>1&&(G.n=-1),d(c,u)):G.n=u:G.v=u);try{if(f=2,i){if(c||(o="next"),t=i[o]){if(!(t=t.call(i,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);i=e}else if((t=(y=G.n<0)?u:r.call(n,G))!==a)break}catch(t){i=e,c=1,u=t}finally{f=1}}return{value:t,done:y}}}(r,o,i),!0),u}var a={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}t=Object.getPrototypeOf;var c=[][n]?t(t([][n]())):(_regeneratorDefine2(t={},n,(function(){return this})),t),u=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(c);function f(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,GeneratorFunctionPrototype):(e.__proto__=GeneratorFunctionPrototype,_regeneratorDefine2(e,o,"GeneratorFunction")),e.prototype=Object.create(u),e}return GeneratorFunction.prototype=GeneratorFunctionPrototype,_regeneratorDefine2(u,"constructor",GeneratorFunctionPrototype),_regeneratorDefine2(GeneratorFunctionPrototype,"constructor",GeneratorFunction),GeneratorFunction.displayName="GeneratorFunction",_regeneratorDefine2(GeneratorFunctionPrototype,o,"GeneratorFunction"),_regeneratorDefine2(u),_regeneratorDefine2(u,o,"Generator"),_regeneratorDefine2(u,n,(function(){return this})),_regeneratorDefine2(u,"toString",(function(){return"[object Generator]"})),(_regenerator=function(){return{w:i,m:f}})()}function _regeneratorDefine2(e,r,n,t){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}(_regeneratorDefine2=function(e,r,n,t){function o(r,n){_regeneratorDefine2(e,r,(function(e){return this._invoke(r,n,e)}))}r?i?i(e,r,{value:n,enumerable:!t,configurable:!t,writable:!t}):e[r]=n:(o("next",0),o("throw",1),o("return",2))})(e,r,n,t)}function asyncGeneratorStep(n,t,e,r,o,a,c){try{var i=n[a](c),u=i.value}catch(n){return void e(n)}i.done?t(u):Promise.resolve(u).then(r,o)}function _asyncToGenerator(n){return function(){var t=this,e=arguments;return new Promise((function(r,o){var a=n.apply(t,e);function _next(n){asyncGeneratorStep(a,r,o,_next,_throw,"next",n)}function _throw(n){asyncGeneratorStep(a,r,o,_next,_throw,"throw",n)}_next(void 0)}))}}function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}function _defineProperties(e,r){for(var t=0;t<r.length;t++){var o=r[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,_toPropertyKey(o.key),o)}}function _toPropertyKey(t){var i=function(t,r){if("object"!=_typeof(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||"default");if("object"!=_typeof(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}(t,"string");return"symbol"==_typeof(i)?i:i+""}function parseArch(arch){switch(arch){case"x86_64":case"x64":return["x86","64"];case"x86_32":case"x86":return["x86",""];case"armv6l":case"armv7l":case"armv8l":return[arch,""];case"aarch64":return["arm","64"];default:return["",""]}}function padVersion(ver){var minSegs=arguments.length>1&&void 0!==arguments[1]?arguments[1]:3,parts=ver.split("."),len=parts.length;if(len<minSegs){for(var i=0,lenToPad=minSegs-len;i<lenToPad;i+=1)parts.push("0");return parts.join(".")}return ver}var NavigatorUAData=function(){return e=function NavigatorUAData(navigator){!function(a,n){if(!(a instanceof n))throw new TypeError("Cannot call a class as a function")}(this,NavigatorUAData),this._ch=function(navigator){var mobile,uaFullVersion,m,m2,userAgent=navigator.userAgent,platform="",platformVersion="",architecture="",bitness="",fullVersionList=[],platformInfo=userAgent,found=!1,versionInfo=userAgent.replace(/\(([^)]+)\)?/g,(function($0,$1){return found||(platformInfo=$1,found=!0),""})),items=versionInfo.match(/(\S+)\/(\S+)/g),webview=!1;if(mobile=-1!==userAgent.indexOf("Mobile"),null!==(m=/Windows NT (\d+(\.\d+)*)/.exec(platformInfo))){platform="Windows";var ver={6.1:"0.1",6.2:"0.2",6.3:"0.3","10.0":"10.0","11.0":"13.0"}[m[1]];ver&&(platformVersion=padVersion(ver,3)),null!==(m2=/\b(WOW64|Win64|x64)\b/.exec(platformInfo))&&(architecture="x86",bitness="64")}else null!==(m=/Android (\d+(\.\d+)*)/.exec(platformInfo))?(platform="Android",platformVersion=padVersion(m[1]),null!==(m2=/Linux (\w+)/.exec(navigator.platform))&&m2[1]&&(architecture=(m2=parseArch(m2[1]))[0],bitness=m2[1])):null!==(m=/(iPhone|iPod touch); CPU iPhone OS (\d+(_\d+)*)/.exec(platformInfo))||null!==(m=/(iPad); CPU OS (\d+(_\d+)*)/.exec(platformInfo))?(platform="iOS",platformVersion=padVersion(m[2].replace(/_/g,"."))):null!==(m=/Macintosh; (Intel|\w+) Mac OS X (\d+([_.]\d+)*)/.exec(platformInfo))?(platform="macOS",platformVersion=padVersion(m[2].replace(/_/g,"."))):null!==(m=/Linux/.exec(platformInfo))?(platform="Linux",platformVersion=""):null!==(m=/CrOS (\w+) (\d+(\.\d+)*)/.exec(platformInfo))&&(platform="Chrome OS",platformVersion=padVersion(m[2]),architecture=(m2=parseArch(m[1]))[0],bitness=m2[1]);if(platform||(platform="Unknown"),null!==(m=/Chrome\/(\d+(\.\d+)*)/.exec(versionInfo))&&"Google Inc."===navigator.vendor){if(fullVersionList.push({brand:"Chromium",version:padVersion(m[1],4)}),null!==(m2=/(Edge?)\/(\d+(\.\d+)*)/.exec(versionInfo))){var brand={Edge:"Microsoft Edge",Edg:"Microsoft Edge"}[m[1]];fullVersionList.push({brand:brand,version:padVersion(m2[2],4)})}else fullVersionList.push({brand:"Google Chrome",version:padVersion(m[1],4)});/\bwv\b/.exec(platformInfo)&&(webview=!0)}else if(null!==(m=/AppleWebKit\/(\d+(\.\d+)*)/.exec(versionInfo))&&"Apple Computer, Inc."===navigator.vendor){if(fullVersionList.push({brand:"WebKit",version:padVersion(m[1])}),"iOS"===platform&&null!=(m2=/(CriOS|EdgiOS|FxiOS|Version)\/(\d+(\.\d+)*)/.exec(versionInfo))){var _brand={CriOS:"Google Chrome",EdgiOS:"Microsoft Edge",FxiOS:"Mozilla Firefox",Version:"Apple Safari"}[m2[1]];fullVersionList.push({brand:_brand,version:padVersion(m2[2])}),-1===items.findIndex((function(s){return s.startsWith("Safari/")}))&&(webview=!0)}}else null!==(m=/Firefox\/(\d+(\.\d+)*)/.exec(versionInfo))?fullVersionList.push({brand:"Firefox",version:padVersion(m[1])}):fullVersionList.push({brand:" Not;A Brand",version:"99.0.0.0"});return uaFullVersion=fullVersionList.length>0?fullVersionList[fullVersionList.length-1]:"",{mobile:mobile,platform:platform,brands:fullVersionList.map((function(b){var pos=b.version.indexOf("."),version=-1===pos?b.version:b.version.slice(0,pos);return{brand:b.brand,version:version}})),platformVersion:platformVersion,architecture:architecture,bitness:bitness,model:"",uaFullVersion:uaFullVersion,fullVersionList:fullVersionList,webview:webview}}(navigator),Object.defineProperties(this,{_ch:{enumerable:!1}})},(r=[{key:"mobile",get:function(){return this._ch.mobile}},{key:"platform",get:function(){return this._ch.platform}},{key:"brands",get:function(){return this._ch.brands}},{key:"getHighEntropyValues",value:function(hints){var _this=this;return new Promise((function(resolve,reject){if(!Array.isArray(hints))throw new TypeError("argument hints is not an array");var hintSet=new Set(hints),data=_this._ch,obj={mobile:data.mobile,platform:data.platform,brands:data.brands};hintSet.has("architecture")&&(obj.architecture=data.architecture),hintSet.has("bitness")&&(obj.bitness=data.bitness),hintSet.has("model")&&(obj.model=data.model),hintSet.has("platformVersion")&&(obj.platformVersion=data.platformVersion),hintSet.has("uaFullVersion")&&(obj.uaFullVersion=data.uaFullVersion),hintSet.has("fullVersionList")&&(obj.fullVersionList=data.fullVersionList),resolve(obj)}))}},{key:"toJSON",value:function(){var data=this._ch;return{mobile:data.mobile,brands:data.brands}}}])&&_defineProperties(e.prototype,r),t&&_defineProperties(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,r,t}();function _getClientInfo(){return(_getClientInfo=_asyncToGenerator(_regenerator().m((function _callee(navigator,keys){var info,customUAData;return _regenerator().w((function(_context){for(;;)switch(_context.n){case 0:if(info={},"https:"!==location.protocol){_context.n=4;break}if(keys||(keys=["brands","mobile","platform","platformVersion","architecture","bitness","model","fullVersionList"]),navigator.userAgentData){_context.n=2;break}return customUAData=new NavigatorUAData(navigator),_context.n=1,customUAData.getHighEntropyValues(keys);case 1:info=_context.v,_context.n=4;break;case 2:return _context.n=3,navigator.userAgentData.getHighEntropyValues(keys);case 3:info=_context.v;case 4:return _context.a(2,info)}}),_callee)})))).apply(this,arguments)}Object.defineProperty(NavigatorUAData.prototype,Symbol.toStringTag,{enumerable:!1,configurable:!0,writable:!1,value:"NavigatorUAData"}),module.exports={getClientInfo:function(_x,_x2){return _getClientInfo.apply(this,arguments)}}},{}],72:[function(require,module,exports){"use strict";var SESSION_STATUS=Object.freeze({CONNECTED:"CONNECTED",ESTABLISHED:"ESTABLISHED",DISCONNECTED:"DISCONNECTED",WARN:"WARN",FAILED:"FAILED",DEBUG:"DEBUG",APP_DATA:"APP_DATA",SEND_DATA_STATUS:"SEND_DATA_STATUS",PENDING:"PENDING",REGISTERED:"REGISTERED",UNREGISTERED:"UNREGISTERED",INCOMING_CALL:"INCOMING_CALL"}),STREAM_STATUS=Object.freeze({NEW:"NEW",PENDING:"PENDING",PUBLISHING:"PUBLISHING",PLAYING:"PLAYING",PAUSED:"PAUSED",UNPUBLISHED:"UNPUBLISHED",STOPPED:"STOPPED",FAILED:"FAILED",PLAYBACK_PROBLEM:"PLAYBACK_PROBLEM",RESIZE:"RESIZE",SNAPSHOT_COMPLETE:"SNAPSHOT_COMPLETE",NOT_ENOUGH_BANDWIDTH:"NOT_ENOUGH_BANDWIDTH"}),CALL_STATUS=Object.freeze({NEW:"NEW",RING:"RING",RING_MEDIA:"RING_MEDIA",HOLD:"HOLD",ESTABLISHED:"ESTABLISHED",FINISH:"FINISH",BUSY:"BUSY",SESSION_PROGRESS:"SESSION_PROGRESS",FAILED:"FAILED",PENDING:"PENDING",TRYING:"TRYING"}),STREAM_STATUS_INFO=Object.freeze({FAILED_BY_ICE_ERROR:"Failed by ICE error",FAILED_BY_ICE_TIMEOUT:"Failed by ICE timeout",FAILED_BY_KEEP_ALIVE:"Failed by ICE keep alive",FAILED_BY_DTLS_FINGERPRINT_ERROR:"Failed by DTLS fingerprint error",FAILED_BY_DTLS_ERROR:"Failed by DTLS error",FAILED_BY_HLS_WRITER_ERROR:"Failed by HLS writer error",FAILED_BY_RTMP_WRITER_ERROR:"Failed by RTMP writer error",FAILED_BY_RTP_ACTIVITY:"Failed by RTP activity",STOPPED_BY_SESSION_DISCONNECT:"Stopped by session disconnect",STOPPED_BY_REST_TERMINATE:"Stopped by rest /terminate",STOPPED_BY_PUBLISHER_STOP:"Stopped by publisher stop",STOPPED_BY_USER:"Stopped by user",FAILED_BY_ERROR:"Failed by error",FAILED_TO_ADD_STREAM_TO_PROXY:"Failed to add stream to proxy",DISTRIBUTOR_STOPPED:"Distributor stopped",PUBLISH_STREAM_IS_NOT_READY:"Publish stream is not ready",STREAM_NOT_FOUND:"Stream not found",STREAM_NAME_ALREADY_IN_USE:"Stream name is already in use",MEDIASESSION_ID_NULL:"MediaSessionId is null",MEDIASESSION_ID_ALREADY_IN_USE:"MediaSessionId is already in use",SESSION_NOT_READY:"Session not ready",SESSION_DOES_NOT_EXIST:"Session does not exist",RTSP_HAS_WRONG_FORMAT:"Rtsp has wrong format",FILE_HAS_WRONG_FORMAT:"File has wrong format",FAILED_TO_CONNECT_TO_RTSP_STREAM:"Failed to connect to rtsp stream",RTSP_STREAM_NOT_FOUND:"Rtsp stream not found",RTSPAGENT_SHUTDOWN:"RtspAgent shutdown",STREAM_FAILED:"Stream failed",NO_COMMON_CODECS:"No common codecs",BAD_URI:"Bad URI",GOT_EXCEPTION_WHILE_STREAMING_FILE:"Got exception while streaming file",REQUESTED_STREAM_SHUTDOWN:"Requested stream shutdown",FAILED_TO_READ_FILE:"Failed to read file",FILE_NOT_FOUND:"File not found",FAILED_TO_CONNECT_TO_ORIGIN_STREAM:"Failed to connect to origin stream",CDN_STREAM_NOT_FOUND:"CDN stream not found",FAILED_TO_GET_AGENT_STORAGE:"Failed to get agent storage",AGENT_SERVICING_ORIGIN_STREAM_IS_SHUTTING_DOWN:"Agent servicing origin stream is shutting down",TERMINATED_BY_KEEP_ALIVE:"Terminated by keep-alive",TRANSCODING_REQUIRED_BUT_DISABLED:"Transcoding required, but disabled",RESTRICTED_ACCESS:"Restricted access",NO_AVAILABLE_TRANSCODERS:"No available transcoders"}),CALL_STATUS_INFO=Object.freeze({NORMAL_CALL_CLEARING:"Normal call clearing",FAILED_BY_SESSION_CREATION:"Failed by session creation",FAILED_BY_ICE_ERROR:"Failed by ICE error",FAILED_BY_RTP_ACTIVITY:"Failed by RTP activity",FAILED_BY_RTMP_WRITER_ERROR:"Failed by RTMP writer error",FAILED_BY_DTLS_FINGERPRINT_ERROR:"Failed by DTLS fingerprint error",NO_COMMON_CODECS:"No common codecs",FAILED_BY_DTLS_ERROR:"Failed by DTLS error",FAILED_BY_ERROR:"Failed by error",FAILED_BY_REQUEST_TIMEOUT:"Failed by request timeout",TRANSCODING_REQUIRED_BUT_DISABLED:"Transcoding required, but disabled"}),ERROR_INFO=Object.freeze({NONE_OF_MEDIAPROVIDERS_AVAILABLE:"None of MediaProviders available",NONE_OF_PREFERRED_MEDIAPROVIDERS_AVAILABLE:"None of preferred MediaProviders available",FLASHPHONER_API_NOT_INITIALIZED:"Flashphoner API is not initialized",OPTIONS_URLSERVER_MUST_BE_PROVIDED:"options.urlServer must be provided",INVALID_SESSION_STATE:"Invalid session state",OPTIONS_MUST_BE_PROVIDED:"options must be provided",INVALID_CALL_STATE:"Invalid call state",EVENT_CANT_BE_NULL:"Event can't be null",CALLBACK_NEEDS_TO_BE_A_VALID_FUNCTION:"Callback needs to be a valid function",OPTIONS_NAME_MUST_BE_PROVIDED:"options.name must be provided",CAN_NOT_SWITCH_CAM:"Number of cams is less than 2 or camera is already used by other application",CAN_NOT_SWITCH_MIC:"Number of mics is less than 2 or microphone is already used by other application",CAN_NOT_SET_RESOLUTION:"Cannot switch a published stream resolution",CAN_NOT_GET_STATS:"Cannot get PeerConnection stats",LOCAL_ERROR:"Local error"}),MEDIA_DEVICE_KIND=Object.freeze({OUTPUT:"output",INPUT:"input",ALL:"all"}),TRANSPORT_TYPE=Object.freeze({UDP:"UDP",TCP:"TCP"}),CONNECTION_QUALITY=Object.freeze({PERFECT:"PERFECT",GOOD:"GOOD",BAD:"BAD",UNKNOWN:"UNKNOWN",UPDATE:"UPDATE"}),STREAM_EVENT_TYPE=Object.freeze({AUDIO_MUTED:"audioMuted",AUDIO_UNMUTED:"audioUnmuted",VIDEO_MUTED:"videoMuted",VIDEO_UNMUTED:"videoUnmuted",DATA:"data",SNAPSHOT_COMPLETED:"snapshotCompleted",SNAPSHOT_FAILED:"snapshotFailed",RESIZE:"resize",NOT_ENOUGH_BANDWIDTH:"notEnoughBandwidth"}),CONTENT_HINT_TYPE=Object.freeze({MOTION:"motion",DETAIL:"detail",TEXT:"text"});module.exports={SESSION_STATUS:SESSION_STATUS,STREAM_STATUS:STREAM_STATUS,CALL_STATUS:CALL_STATUS,STREAM_STATUS_INFO:STREAM_STATUS_INFO,CALL_STATUS_INFO:CALL_STATUS_INFO,ERROR_INFO:ERROR_INFO,MEDIA_DEVICE_KIND:MEDIA_DEVICE_KIND,TRANSPORT_TYPE:TRANSPORT_TYPE,CONNECTION_QUALITY:CONNECTION_QUALITY,STREAM_EVENT:"STREAM_EVENT",STREAM_EVENT_TYPE:STREAM_EVENT_TYPE,CONTENT_HINT_TYPE:CONTENT_HINT_TYPE}},{}],73:[function(require,module,exports){"use strict";function ownKeys(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);r&&(o=o.filter((function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),t.push.apply(t,o)}return t}function _objectSpread(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?ownKeys(Object(t),!0).forEach((function(r){_defineProperty(e,r,t[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):ownKeys(Object(t)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))}))}return e}function _defineProperty(e,r,t){return(r=function(t){var i=function(t,r){if("object"!=_typeof(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||"default");if("object"!=_typeof(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}(t,"string");return"symbol"==_typeof(i)?i:i+""}(r))in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}function _slicedToArray(r,e){return function(r){if(Array.isArray(r))return r}(r)||function(r,l){var t=null==r?null:"undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(null!=t){var e,n,i,u,a=[],f=!0,o=!1;try{if(i=(t=t.call(r)).next,0===l){if(Object(t)!==t)return;f=!1}else for(;!(f=(e=i.call(t)).done)&&(a.push(e.value),a.length!==l);f=!0);}catch(r){o=!0,n=r}finally{try{if(!f&&null!=t.return&&(u=t.return(),Object(u)!==u))return}finally{if(o)throw n}}return a}}(r,e)||function(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}(r,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}function _regenerator(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function i(r,n,o,i){var c=n&&n.prototype instanceof Generator?n:Generator,u=Object.create(c.prototype);return _regeneratorDefine2(u,"_invoke",function(r,n,o){var i,c,u,f=0,p=o||[],y=!1,G={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return i=t,c=0,u=e,G.n=r,a}};function d(r,n){for(c=r,u=n,t=0;!y&&f&&!o&&t<p.length;t++){var o,i=p[t],d=G.p,l=i[2];r>3?(o=l===n)&&(u=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&d<i[1])?(c=0,G.v=n,G.n=i[1]):d<l&&(o=r<3||i[0]>n||n>l)&&(i[4]=r,i[5]=n,G.n=l,c=0))}if(o||r>1)return a;throw y=!0,n}return function(o,p,l){if(f>1)throw TypeError("Generator is already running");for(y&&1===p&&d(p,l),c=p,u=l;(t=c<2?e:u)||!y;){i||(c?c<3?(c>1&&(G.n=-1),d(c,u)):G.n=u:G.v=u);try{if(f=2,i){if(c||(o="next"),t=i[o]){if(!(t=t.call(i,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);i=e}else if((t=(y=G.n<0)?u:r.call(n,G))!==a)break}catch(t){i=e,c=1,u=t}finally{f=1}}return{value:t,done:y}}}(r,o,i),!0),u}var a={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}t=Object.getPrototypeOf;var c=[][n]?t(t([][n]())):(_regeneratorDefine2(t={},n,(function(){return this})),t),u=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(c);function f(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,GeneratorFunctionPrototype):(e.__proto__=GeneratorFunctionPrototype,_regeneratorDefine2(e,o,"GeneratorFunction")),e.prototype=Object.create(u),e}return GeneratorFunction.prototype=GeneratorFunctionPrototype,_regeneratorDefine2(u,"constructor",GeneratorFunctionPrototype),_regeneratorDefine2(GeneratorFunctionPrototype,"constructor",GeneratorFunction),GeneratorFunction.displayName="GeneratorFunction",_regeneratorDefine2(GeneratorFunctionPrototype,o,"GeneratorFunction"),_regeneratorDefine2(u),_regeneratorDefine2(u,o,"Generator"),_regeneratorDefine2(u,n,(function(){return this})),_regeneratorDefine2(u,"toString",(function(){return"[object Generator]"})),(_regenerator=function(){return{w:i,m:f}})()}function _regeneratorDefine2(e,r,n,t){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}(_regeneratorDefine2=function(e,r,n,t){function o(r,n){_regeneratorDefine2(e,r,(function(e){return this._invoke(r,n,e)}))}r?i?i(e,r,{value:n,enumerable:!t,configurable:!t,writable:!t}):e[r]=n:(o("next",0),o("throw",1),o("return",2))})(e,r,n,t)}function asyncGeneratorStep(n,t,e,r,o,a,c){try{var i=n[a](c),u=i.value}catch(n){return void e(n)}i.done?t(u):Promise.resolve(u).then(r,o)}function _asyncToGenerator(n){return function(){var t=this,e=arguments;return new Promise((function(r,o){var a=n.apply(t,e);function _next(n){asyncGeneratorStep(a,r,o,_next,_throw,"next",n)}function _throw(n){asyncGeneratorStep(a,r,o,_next,_throw,"throw",n)}_next(void 0)}))}}var coreLogger,clientUAData,disableConnectionQualityCalculation,_require=require("@flashphoner/web-sdk-metrics"),RTCMetricsCollectorBuilder=_require.RTCMetricsCollectorBuilder,RTCMetricsCollectType=_require.RTCMetricsCollectType,RTCMetricsHttpSender=_require.RTCMetricsHttpSender,uuid_v1=require("uuid").v1,constants=require("./constants"),util=require("./util"),LoggerObject=require("./util").logger,clientInfo=require("./client-info"),_Promise=require("promise-polyfill"),KalmanFilter=require("kalmanjs"),browserDetails=require("webrtc-adapter").default.browserDetails,loggerConf={push:!1,severity:"INFO"},isUsingTemasysPlugin=!1,SESSION_STATUS=constants.SESSION_STATUS,STREAM_EVENT=constants.STREAM_EVENT,STREAM_EVENT_TYPE=constants.STREAM_EVENT_TYPE,STREAM_STATUS=constants.STREAM_STATUS,CALL_STATUS=constants.CALL_STATUS,CONNECTION_QUALITY=constants.CONNECTION_QUALITY,ERROR_INFO=constants.ERROR_INFO,MediaProvider={},sessions={},initialized=!1,init=function(){var _ref=_asyncToGenerator(_regenerator().m((function _callee(options){var waitingTemasys,audioContext,webRtcProvider,enableGainNode,webRtcConf,mediaSourceMediaProvider,mseConf,websocketProvider,wsConf,_MediaProvider,p,newMediaProvider,i,pMP;return _regenerator().w((function(_context){for(;;)switch(_context.n){case 0:if(initialized){_context.n=6;break}options||(options={}),coreLogger=createLogger(options.logger),waitingTemasys=!1;try{audioContext=new(window.AudioContext||window.webkitAudioContext)}catch(e){console.warn("Failed to create audio context")}if(disableConnectionQualityCalculation=options.disableConnectionQualityCalculation,(webRtcProvider=require("./webrtc-media-provider"))&&webRtcProvider.hasOwnProperty("available")&&webRtcProvider.available()?(MediaProvider.WebRTC=webRtcProvider,enableGainNode=!util.Browser.isSamsungBrowser()&&!util.Browser.isAndroidFirefox()&&options.createMicGainNode,webRtcConf={constraints:options.constraints||getDefaultMediaConstraints(),extensionId:options.screenSharingExtensionId,audioContext:audioContext,logger:coreLogger,createMicGainNode:enableGainNode},webRtcProvider.configure(webRtcConf)):(webRtcProvider=require("./temasys-media-provider"))&&webRtcProvider.hasOwnProperty("available")&&AdapterJS&&(waitingTemasys=!0,AdapterJS.webRTCReady((function(isUsingPlugin){if(isUsingTemasysPlugin=isUsingPlugin,isUsingPlugin||webRtcProvider.available()){MediaProvider.WebRTC=webRtcProvider;var webRtcConf={constraints:options.constraints||getDefaultMediaConstraints(),extensionId:options.screenSharingExtensionId,logger:coreLogger};webRtcProvider.configure(webRtcConf);var _MediaProvider={};for(var p in _MediaProvider.WebRTC=MediaProvider.WebRTC,MediaProvider)_MediaProvider[p]=MediaProvider[p];MediaProvider=_MediaProvider}options.mediaProvidersReadyCallback&&options.mediaProvidersReadyCallback(Object.keys(MediaProvider))}))),null,(mediaSourceMediaProvider=require("./media-source-media-provider"))&&mediaSourceMediaProvider.hasOwnProperty("available")&&mediaSourceMediaProvider.available()&&(MediaProvider.MSE=mediaSourceMediaProvider,mseConf={audioContext:audioContext,browserDetails:browserDetails.browser},mediaSourceMediaProvider.configure(mseConf)),(websocketProvider=require("./websocket-media-provider"))&&websocketProvider.hasOwnProperty("available")&&websocketProvider.available(audioContext)&&(MediaProvider.WSPlayer=websocketProvider,wsConf={receiverLocation:options.receiverLocation,decoderLocation:options.decoderLocation,audioContext:audioContext,logger:coreLogger},websocketProvider.configure(wsConf)),0!=getMediaProviders().length){_context.n=1;break}throw new Error("None of MediaProviders available");case 1:if(options.preferredMediaProvider)if(MediaProvider.hasOwnProperty(options.preferredMediaProvider)){if(getMediaProviders()[0]!=options.preferredMediaProvider){for(p in(_MediaProvider={})[options.preferredMediaProvider]=MediaProvider[options.preferredMediaProvider],MediaProvider)_MediaProvider[p]=MediaProvider[p];MediaProvider=_MediaProvider}}else corelogger.warn("core","Preferred media provider is not available.");case 2:if(!(options.preferredMediaProviders&&options.preferredMediaProviders.length>0)){_context.n=4;break}for(i in newMediaProvider={},options.preferredMediaProviders)options.preferredMediaProviders.hasOwnProperty(i)&&(pMP=options.preferredMediaProviders[i],MediaProvider.hasOwnProperty(pMP)&&(newMediaProvider[pMP]=MediaProvider[pMP]));if(!util.isEmptyObject(newMediaProvider)){_context.n=3;break}throw new Error("None of preferred MediaProviders available");case 3:MediaProvider=newMediaProvider;case 4:if(!waitingTemasys&&options.mediaProvidersReadyCallback&&options.mediaProvidersReadyCallback(Object.keys(MediaProvider)),coreLogger.info("core","Initialized"),initialized=!0,void 0!==options.collectClientInfo&&!options.collectClientInfo){_context.n=6;break}return _context.n=5,clientInfo.getClientInfo(window.navigator);case 5:clientUAData=_context.v,coreLogger.info("core","Client system data: "+JSON.stringify(clientUAData));case 6:return _context.a(2)}}),_callee)})));return function(_x){return _ref.apply(this,arguments)}}(),getMediaProviders=function(){return Object.keys(MediaProvider)},getDefaultMediaConstraints=function(){return"safari"==browserDetails.browser?{audio:!0,video:{width:{min:320,max:640},height:{min:180,max:360}}}:{audio:!0,video:{width:320,height:240}}};function getConstraintsProperty(constraints,property,defaultValue){if(!constraints||!property)return defaultValue;var res,properties=property.split(".");for(var prop in constraints)if(prop==properties[0])res=constraints[prop],properties.length>1&&(res=getConstraintsProperty(constraints[prop],properties[1],defaultValue));else if("object"===_typeof(constraints[prop]))for(var p in constraints[prop])p==property&&(res=constraints[prop][p]);return"boolean"==typeof res?res:res||defaultValue}var releaseLocalMedia=function(display,mediaProvider){if(!initialized)throw new Error("Flashphoner API is not initialized");return mediaProvider||(mediaProvider=getMediaProviders()[0]),MediaProvider[mediaProvider].releaseMedia(display)},getLoggerConf=function(loggerOptions){var conf=loggerOptions||loggerConf;return null!==loggerOptions&&(conf.enableLogs=!0),conf},createLogger=function(loggerOptions){var parentLogger=arguments.length>1&&void 0!==arguments[1]?arguments[1]:coreLogger,newLogger=parentLogger;if(void 0===newLogger||null!=loggerOptions){var loggerConf=getLoggerConf(loggerOptions);(newLogger=new LoggerObject).init(loggerConf.severity||"INFO",loggerConf.push||!1,loggerConf.customLogger,loggerConf.enableLogs)}return newLogger};module.exports={init:init,isUsingTemasys:function(){return isUsingTemasysPlugin},getMediaProviders:getMediaProviders,getMediaDevices:function(mediaProvider,labels,kind,deviceConstraints){if(!initialized)throw new Error("Flashphoner API is not initialized");return mediaProvider||(mediaProvider=getMediaProviders()[0]),MediaProvider[mediaProvider].listDevices(labels,kind,deviceConstraints)},getMobileDevices:function(mediaProvider,kind,deviceConstraints){if(!initialized)throw new Error("Flashphoner API is not initialized");return mediaProvider||(mediaProvider=getMediaProviders()[0]),MediaProvider[mediaProvider].getMobileDevices?MediaProvider[mediaProvider].getMobileDevices(kind,deviceConstraints):[]},getMediaAccess:function(constraints,display,mediaProvider,disableConstraintsNormalization){if(!initialized)throw new Error("Flashphoner API is not initialized");return mediaProvider||(mediaProvider=getMediaProviders()[0]),MediaProvider[mediaProvider].getMediaAccess(constraints,display,disableConstraintsNormalization)},releaseLocalMedia:releaseLocalMedia,getSessions:function(){return util.copyObjectToArray(sessions)},getSession:function(id){return sessions[id]},createSession:function(options){if(!initialized)throw new Error("Flashphoner API is not initialized");if(!options||!options.urlServer)throw new TypeError("options.urlServer must be provided");var connectionTimeout,cConfig,sipConfig,sessionLogger=createLogger(options.logger),logger=sessionLogger,id_=uuid_v1(),sessionStatus=SESSION_STATUS.PENDING,urlServer=options.urlServer,lbUrl=options.lbUrl,flashProto=options.flashProto||"rtmfp",flashPort=options.flashPort||1935,appKey=options.appKey||"defaultApp",mediaOptions=options.mediaOptions,keepAlive=options.keepAlive,timeout=options.timeout,sendClientInfo=void 0===options.sendClientInfo||options.sendClientInfo,wsPingSender=new function(interval){return this.interval=interval||0,this.intervalId=null,this.start=function(){this.interval>0&&(this.intervalId=setInterval((function(){send("ping",null)}),this.interval))},this.stop=function(){this.intervalId&&clearInterval(this.intervalId)},this}(options.pingInterval||0),wsPingReceiver=new function(receiveProbes,probesInterval){return this.maxPings=receiveProbes||0,this.interval=probesInterval||0,this.intervalId=null,this.pingsMissing=0,this.start=function(){if(this.maxPings>0&&this.interval>0){var receiver=this;this.intervalId=setInterval((function(){receiver.checkPingsReceived()}),this.interval)}},this.stop=function(){this.intervalId&&clearInterval(this.intervalId),this.pingsMissing=0},this.checkPingsReceived=function(){this.pingsMissing++,this.pingsMissing>=this.maxPings&&this.failure()},this.success=function(){this.pingsMissing=0},this.failure=function(){logger.info("core","Missing "+this.pingsMissing+" pings from server, connection seems to be down"),onSessionStatusChange(SESSION_STATUS.FAILED),wsConnection.close()},this}(options.receiveProbes||0,options.probesInterval||0);options.sipOptions&&(sipConfig={sipLogin:options.sipOptions.login,sipAuthenticationName:options.sipOptions.authenticationName,sipPassword:options.sipOptions.password,sipDomain:options.sipOptions.domain,sipOutboundProxy:options.sipOptions.outboundProxy,sipProxy:options.sipOptions.proxy,sipPort:options.sipOptions.port,sipRegisterRequired:options.sipOptions.registerRequired});var wsConnection,webRTCMetricsServerDescription,url,request,authToken=options.authToken,streams={},calls={},mediaConnections={},streamEventRefreshHandlers={},streamRefreshHandlers={},callRefreshHandlers={},session={},callbacks={};lbUrl?(url=lbUrl,(request=new XMLHttpRequest).open("GET",url,!0),request.timeout=5e3,request.ontimeout=function(){logger.warn("core","Timeout during geting url from balancer!"),createWS(urlServer)},request.error=function(){logger.warn("core","Error during geting url from balancer!"),createWS(urlServer)},request.onload=function(e){if(200==request.status&&4==request.readyState){var result=JSON.parse(request.responseText);urlServer=-1!==urlServer.indexOf("wss://")?"wss://"+result.server+":"+result.wss:"ws://"+result.server+":"+result.ws,flashPort=result.flash,logger.debug("core","Got url from load balancer "+result.server),createWS(urlServer)}},request.send()):createWS(urlServer);var remoteSdpCache={};function createWS(url){wsConnection=new WebSocket(url),null!=timeout&&timeout>0&&(connectionTimeout=setTimeout((function(){0==wsConnection.readyState&&(logger.warn("core","WS connection timeout"),wsConnection.close())}),timeout)),wsConnection.onerror=function(){onSessionStatusChange(SESSION_STATUS.FAILED)},wsConnection.onclose=function(){sessionStatus!==SESSION_STATUS.FAILED&&onSessionStatusChange(SESSION_STATUS.DISCONNECTED)},wsConnection.onopen=function(){onSessionStatusChange(SESSION_STATUS.CONNECTED),clearTimeout(connectionTimeout),cConfig={appKey:appKey,mediaProviders:Object.keys(MediaProvider),keepAlive:keepAlive,authToken:authToken,clientVersion:"2.0",clientOSVersion:window.navigator.appVersion,clientBrowserVersion:window.navigator.userAgent,msePacketizationVersion:2,custom:options.custom},sendClientInfo&&clientUAData&&(cConfig.clientInfo=clientUAData),sipConfig&&util.copyObjectPropsToAnotherObject(sipConfig,cConfig),send("connection",cConfig),logger.setConnection(wsConnection),wsPingSender.start(),wsPingReceiver.start()},wsConnection.onmessage=function(event){var data={};if(event.data instanceof Blob)data.message="binaryData";else var obj=(data=JSON.parse(event.data)).data[0];switch(data.message){case"ping":logger.debug("core","<<< ping"),send("pong",null),logger.debug("core",">>> pong");break;case"getUserData":authToken=obj.authToken,cConfig=obj,webRTCMetricsServerDescription=obj.webRTCMetricsServerDescription,onSessionStatusChange(SESSION_STATUS.ESTABLISHED,obj);break;case"setRemoteSDP":var mediaSessionId=data.data[0],sdp=data.data[1];streamRefreshHandlers[mediaSessionId]?streamRefreshHandlers[mediaSessionId](null,sdp):callRefreshHandlers[mediaSessionId]?callRefreshHandlers[mediaSessionId](null,sdp):(remoteSdpCache[mediaSessionId]=sdp,logger.info("core","Media not found, id "+mediaSessionId));break;case"notifyVideoFormat":case"notifyStreamStatusEvent":streamRefreshHandlers[obj.mediaSessionId]&&streamRefreshHandlers[obj.mediaSessionId](obj);break;case"notifyStreamEvent":streamEventRefreshHandlers[obj.mediaSessionId]&&streamEventRefreshHandlers[obj.mediaSessionId](obj);break;case"DataStatusEvent":restAppCommunicator.resolveData(obj);break;case"OnDataEvent":callbacks[SESSION_STATUS.APP_DATA]&&callbacks[SESSION_STATUS.APP_DATA](obj);break;case"fail":obj.apiMethod&&"StreamStatusEvent"==obj.apiMethod&&streamRefreshHandlers[obj.id]&&streamRefreshHandlers[obj.id](obj),callbacks[SESSION_STATUS.WARN]&&callbacks[SESSION_STATUS.WARN](obj);break;case"registered":onSessionStatusChange(SESSION_STATUS.REGISTERED);break;case"notifyAudioCodec":mediaSessionId=data.data[0];var codec=data.data[1];callRefreshHandlers[mediaSessionId]&&callRefreshHandlers[mediaSessionId](null,null,codec);break;case"notifyTransferEvent":callRefreshHandlers[obj.callId](null,null,null,obj);break;case"notifyTryingResponse":case"hold":case"ring":case"talk":case"finish":callRefreshHandlers[obj.callId]&&callRefreshHandlers[obj.callId](obj);break;case"notifyIncomingCall":callRefreshHandlers[obj.callId]&&logger.error("core","Call already exists, id "+obj.callId),callbacks[SESSION_STATUS.INCOMING_CALL]&&callbacks[SESSION_STATUS.INCOMING_CALL](createCall(obj));break;case"notifySessionDebugEvent":logger.info("core","Session debug status "+obj.status),callbacks[SESSION_STATUS.DEBUG]&&callbacks[SESSION_STATUS.DEBUG](obj);break;case"availableStream":var availableStream={};availableStream.mediaSessionId=obj.id,availableStream.available=obj.status,availableStream.reason=obj.info,streamRefreshHandlers[availableStream.mediaSessionId]&&streamRefreshHandlers[availableStream.mediaSessionId](availableStream);break;case"outboundVideoRate":case"inboundVideoRate":streamRefreshHandlers[obj.mediaSessionId]&&(obj.status=data.message,streamRefreshHandlers[obj.mediaSessionId](obj));break;case"webRTCMetricsTokenRefresh":for(var _i=0,_Object$entries=Object.entries(streamRefreshHandlers);_i<_Object$entries.length;_i++){var _Object$entries$_i=_slicedToArray(_Object$entries[_i],2);_Object$entries$_i[0];(0,_Object$entries$_i[1])(obj)}break;case"webRTCMetricsDescriptionUpdate":if(obj.ids)obj.ids.forEach((function(id){streamRefreshHandlers[id]&&streamRefreshHandlers[id](obj)}));else{obj.compression&&(webRTCMetricsServerDescription.compression=obj.compression),obj.batchSize&&(webRTCMetricsServerDescription.batchSize=obj.batchSize),obj.sampling&&(webRTCMetricsServerDescription.sampling=obj.sampling),obj.types&&(webRTCMetricsServerDescription.types=obj.types),obj.collect&&(webRTCMetricsServerDescription.collect=obj.collect);for(var _i2=0,_Object$entries2=Object.entries(streamRefreshHandlers);_i2<_Object$entries2.length;_i2++){var _Object$entries2$_i=_slicedToArray(_Object$entries2[_i2],2);_Object$entries2$_i[0];(0,_Object$entries2$_i[1])(obj)}}break;default:logger.info("core","Unknown server message "+data.message)}logger.debug("core","Reset missing pings counter by "+data.message+" message"),wsPingReceiver.success()}}function send(message,data){wsConnection.readyState===WebSocket.OPEN&&wsConnection.send(JSON.stringify({message:message,data:[data]}))}function onSessionStatusChange(newStatus,obj){if((sessionStatus=newStatus)==SESSION_STATUS.DISCONNECTED||sessionStatus==SESSION_STATUS.FAILED){for(var prop in wsPingSender.stop(),wsPingReceiver.stop(),streamRefreshHandlers)streamRefreshHandlers.hasOwnProperty(prop)&&"function"==typeof streamRefreshHandlers[prop]&&streamRefreshHandlers[prop]({status:STREAM_STATUS.FAILED});delete sessions[id_]}callbacks[sessionStatus]&&callbacks[sessionStatus](session,obj)}var createCall=function(options){if(sessionStatus!==SESSION_STATUS.REGISTERED&&sessionStatus!==SESSION_STATUS.ESTABLISHED)throw new Error("Invalid session state "+sessionStatus);if(!options)throw new TypeError("options must be provided");var mediaConnection,info_,errorInfo_,audioOutputId,callLogger=createLogger(options.logger,sessionLogger),logger=callLogger,login="clickToCallApp"==appKey?"":cConfig.sipLogin,caller_=options.incoming?options.caller:login,callee_=options.callee,visibleName_=options.visibleName||login,id_=options.callId||uuid_v1(),mediaProvider=options.mediaProvider||getMediaProviders()[0],localDisplay=options.localVideoDisplay,remoteDisplay=options.remoteVideoDisplay;if(options.constraints)var constraints=options.constraints;if(options.disableConstraintsNormalization)var disableConstraintsNormalization=options.disableConstraintsNormalization;var audioProperty=getConstraintsProperty(constraints,"audio",void 0);"object"===_typeof(audioProperty)&&(audioOutputId=getConstraintsProperty(audioProperty,"outputId",0));var stripCodecs=options.stripCodecs||[],receiveAudio="undefined"==typeof options.receiveAudio||options.receiveAudio,receiveVideo="undefined"==typeof options.receiveVideo||options.receiveVideo,cacheLocalResources=options.cacheLocalResources,status_=CALL_STATUS.NEW,callbacks={},hasTransferredCall=!1,sdpHook=options.sdpHook,sipSDP=options.sipSDP,videoContentHint=(options.sipHeaders,options.videoContentHint),useControls=options.useControls,collectDeviceInfo=void 0===options.collectDeviceInfo||options.collectDeviceInfo,minBitrate=getConstraintsProperty(constraints,"video.minBitrate",0),maxBitrate=getConstraintsProperty(constraints,"video.maxBitrate",0),call={};callRefreshHandlers[id_]=function(callInfo,sdp,codec,transfer){if(transfer)return mediaConnections[id_]||(mediaConnections[id_]=mediaConnection),void("COMPLETED"==transfer.status&&delete mediaConnections[id_]);if(!mediaConnection&&0!=Object.keys(mediaConnections).length)for(var mc in mediaConnections)mediaConnection=mediaConnections[mc],hasTransferredCall=!0,delete mediaConnections[mc];if(codec)"Flash"==mediaProvider&&mediaConnection.changeAudioCodec(codec.name);else{if(sdp&&""!==sdp)return sdp=sdpHookHandler(sdp,sdpHook),sdp=util.setPublishingBitrate(sdp,mediaConnection,minBitrate,maxBitrate),void mediaConnection.setRemoteSdp(sdp,hasTransferredCall,id_).then((function(){}));var event=callInfo.status;status_=event,event!=CALL_STATUS.FAILED&&event!=CALL_STATUS.FINISH&&event!=CALL_STATUS.BUSY||(delete calls[id_],delete callRefreshHandlers[id_],0==Object.keys(calls).length&&mediaConnection&&mediaConnection.close(cacheLocalResources)),callbacks[event]&&callbacks[event](call)}};var hangup=function(){if(status_!=CALL_STATUS.NEW){if(status_==CALL_STATUS.PENDING)return cacheLocalResources||releaseLocalMedia(localDisplay,mediaProvider),callRefreshHandlers[id_]({status:CALL_STATUS.FAILED}),void(options.incoming&&send("hangup",{callId:id_}));send("hangup",{callId:id_}),mediaConnection&&mediaConnection.close(cacheLocalResources)}else callRefreshHandlers[id_]({status:CALL_STATUS.FAILED})};return call.call=function(){if(status_!==CALL_STATUS.NEW)throw new Error("Invalid call state");status_=CALL_STATUS.PENDING;MediaProvider[mediaProvider].getMediaAccess(constraints,localDisplay,disableConstraintsNormalization).then((function(){status_!=CALL_STATUS.FAILED?MediaProvider[mediaProvider].createConnection({id:id_,localDisplay:localDisplay,remoteDisplay:remoteDisplay,authToken:authToken,mainUrl:urlServer,flashProto:flashProto,flashPort:flashPort,bidirectional:!0,login:login,constraints:constraints,connectionConfig:mediaOptions,audioOutputId:audioOutputId,videoContentHint:videoContentHint,useControls:useControls,logger:logger}).then((function(newConnection){return(mediaConnection=newConnection).createOffer({sendAudio:!0,sendVideo:!0,receiveAudio:receiveAudio,receiveVideo:receiveVideo,stripCodecs:stripCodecs})})).then((function(offer){var callData={callId:id_,incoming:!1,hasVideo:offer.hasVideo,hasAudio:offer.hasAudio,status:status_,mediaProvider:mediaProvider,sdp:offer.sdp,sipSDP:sipSDP,caller:login,callee:callee_,custom:options.custom,visibleName:visibleName_};collectDeviceInfo&&(callData.localMediaInfo=collectLocalMediaInfo(MediaProvider[mediaProvider],localDisplay)),send("call",callData)})):cacheLocalResources||releaseLocalMedia(localDisplay,mediaProvider)})).catch((function(error){logger.error("core",error),status_=CALL_STATUS.FAILED,info_=ERROR_INFO.LOCAL_ERROR,errorInfo_=error.message,callRefreshHandlers[id_]({status:CALL_STATUS.FAILED}),hangup()}))},call.answer=function(answerOptions){if(status_!==CALL_STATUS.NEW&&status_!==CALL_STATUS.RING)throw new Error("Invalid call state");var sdp;localDisplay=answerOptions.localVideoDisplay,remoteDisplay=answerOptions.remoteVideoDisplay,constraints=answerOptions.constraints||getDefaultMediaConstraints(),status_=CALL_STATUS.PENDING;var sdpHook=answerOptions.sdpHook,minBitrate=getConstraintsProperty(constraints,"video.minBitrate",0),maxBitrate=getConstraintsProperty(constraints,"video.maxBitrate",0);if(sipSDP=answerOptions.sipSDP,answerOptions.sipHeaders,!remoteSdpCache[id_])throw logger.error("core","No remote sdp available"),new Error("No remote sdp available");sdp=sdpHookHandler(remoteSdpCache[id_],sdpHook),sdp=util.setPublishingBitrate(sdp,null,minBitrate,maxBitrate),delete remoteSdpCache[id_],0==util.SDP.matchPrefix(sdp,"m=video").length&&(constraints.video=!1);var stripCodecs=answerOptions.stripCodecs||[];MediaProvider[mediaProvider].getMediaAccess(constraints,localDisplay,disableConstraintsNormalization).then((function(){status_!=CALL_STATUS.FAILED?MediaProvider[mediaProvider].createConnection({id:id_,localDisplay:localDisplay,remoteDisplay:remoteDisplay,authToken:authToken,mainUrl:urlServer,flashProto:flashProto,flashPort:flashPort,bidirectional:!0,login:cConfig.sipLogin,constraints:constraints,connectionConfig:mediaOptions,audioOutputId:audioOutputId,useControls:useControls}).then((function(newConnection){return(mediaConnection=newConnection).setPublishingBitrate(minBitrate,maxBitrate),mediaConnection.setRemoteSdp(sdp)})).then((function(){return mediaConnection.createAnswer({receiveAudio:options.receiveAudio,receiveVideo:options.receiveVideo,stripCodecs:stripCodecs})})).then((function(sdp){if(status_!=CALL_STATUS.FINISH&&status_!=CALL_STATUS.FAILED){var callData={callId:id_,incoming:!0,hasVideo:!0,hasAudio:!0,status:status_,mediaProvider:mediaProvider,sdp:sdp,sipSDP:sipSDP,caller:cConfig.login,callee:callee_,custom:options.custom};collectDeviceInfo&&(callData.localMediaInfo=collectLocalMediaInfo(MediaProvider[mediaProvider],localDisplay)),send("answer",callData)}else hangup()})):cacheLocalResources||releaseLocalMedia(localDisplay,mediaProvider)})).catch((function(error){logger.error("core",error),info_=ERROR_INFO.LOCAL_ERROR,errorInfo_=error.message,status_=CALL_STATUS.FAILED,callRefreshHandlers[id_]({status:CALL_STATUS.FAILED})}))},call.hangup=hangup,call.id=function(){return id_},call.getInfo=function(){return info_},call.getErrorInfo=function(){return errorInfo_},call.status=function(){return status_},call.getStats=function(callbackFn,nativeStats){mediaConnection&&mediaConnection.getStats(callbackFn,nativeStats)},call.setAudioOutputId=function(id){if(audioOutputId=id,mediaConnection&&mediaConnection.setAudioOutputId)return mediaConnection.setAudioOutputId(id)},call.setVolume=function(volume){mediaConnection&&mediaConnection.setVolume(volume)},call.getVolume=function(){return mediaConnection?mediaConnection.getVolume():-1},call.muteAudio=function(){mediaConnection&&mediaConnection.muteAudio()},call.unmuteAudio=function(){mediaConnection&&mediaConnection.unmuteAudio()},call.isAudioMuted=function(){return!mediaConnection||mediaConnection.isAudioMuted()},call.muteVideo=function(){mediaConnection&&mediaConnection.muteVideo()},call.unmuteVideo=function(){mediaConnection&&mediaConnection.unmuteVideo()},call.isVideoMuted=function(){return!mediaConnection||mediaConnection.isVideoMuted()},call.caller=function(){return caller_},call.callee=function(){return callee_},call.visibleName=function(){return visibleName_},call.hold=function(){send("hold",{callId:id_})},call.holdForTransfer=function(){send("hold",{callId:id_,holdForTransfer:!0})},call.unhold=function(){send("unhold",{callId:id_})},call.sendDTMF=function(number,type){send("sendDtmf",{callId:id_,type:type||"RFC2833",dtmf:number})},call.transfer=function(target){send("transfer",{callId:id_,target:target})},call.on=function(event,callback){if(!event)throw new TypeError("Event can't be null");if(!callback||"function"!=typeof callback)throw new Error("Callback needs to be a valid function");return callbacks[event]=callback,call},call.switchCam=function(deviceId){if(status_!==CALL_STATUS.ESTABLISHED&&!constraints.video&&status_!==CALL_STATUS.HOLD)throw new Error("Invalid call state");return mediaConnection.switchCam(deviceId)},call.switchMic=function(deviceId){if(status_!==CALL_STATUS.ESTABLISHED&&status_!==CALL_STATUS.HOLD)throw new Error("Invalid call state");return mediaConnection.switchMic(deviceId)},call.switchToScreen=function(source,woExtension){if(status_!==CALL_STATUS.ESTABLISHED&&status_!==CALL_STATUS.HOLD)throw new Error("Invalid call state");return mediaConnection.switchToScreen(source,woExtension)},call.switchToCam=function(){if(status_!==CALL_STATUS.ESTABLISHED&&status_!==CALL_STATUS.HOLD)throw new Error("Invalid call state");mediaConnection.switchToCam()},call.getLogger=function(){return callLogger},calls[id_]=call,call},restAppCommunicator=function(){var pending={},exports={sendData:function(data){return new _Promise((function(resolve,reject){var obj={operationId:uuid_v1(),payload:data};pending[obj.operationId]={FAILED:function(info){reject(info)},ACCEPTED:function(info){resolve(info)}},send("sendData",obj)}))},resolveData:function(data){if(pending[data.operationId]){var handler=pending[data.operationId];delete pending[data.operationId],delete data.operationId,handler[data.status](data)}}};return exports}(),sdpHookHandler=function(sdp,sdpHook){if(null!=sdpHook&&"function"==typeof sdpHook){var newSdp=sdpHook({sdpString:sdp});return null!=newSdp&&""!=newSdp?newSdp:sdp}return sdp},collectLocalMediaInfo=function(mediaProvider,display){var videoCams=[],mics=[];mediaProvider.videoCams&&mediaProvider.videoCams.forEach((function(device){videoCams.push({id:device.id,label:encodeURI(device.label),type:device.type})})),mediaProvider.mics&&mediaProvider.mics.forEach((function(device){mics.push({id:device.id,label:encodeURI(device.label),type:device.type})})),videoCams.length&&logger.info("core","Video inputs available: "+JSON.stringify(videoCams)),mics.length&&logger.info("core","Audio inputs available: "+JSON.stringify(mics));var localVideo,audioTracks=[],videoTracks=[];return mediaProvider.getCacheInstance&&(localVideo=mediaProvider.getCacheInstance(display)),!localVideo&&mediaProvider.getVideoElement&&(localVideo=mediaProvider.getVideoElement(display)),localVideo&&localVideo.srcObject&&(localVideo.srcObject.getAudioTracks().forEach((function(track){var device=track.label;"MediaStreamAudioDestinationNode"===device&&mediaProvider.getAudioSourceDevice&&(device=mediaProvider.getAudioSourceDevice()),audioTracks.push({trackId:track.id,device:encodeURI(device)})})),localVideo.srcObject.getVideoTracks().forEach((function(track){videoTracks.push({trackId:track.id,device:encodeURI(track.label)})}))),videoTracks.length&&logger.info("core","Video tracks captured: "+JSON.stringify(videoTracks)),audioTracks.length&&logger.info("core","Audio tracks captured: "+JSON.stringify(audioTracks)),{devices:{video:videoCams,audio:mics},tracks:{video:videoTracks,audio:audioTracks}}};return session.id=function(){return id_},session.status=function(){return sessionStatus},session.getServerUrl=function(){return urlServer},session.createStream=function(options){var availableCallbacks=[];if(sessionStatus!==SESSION_STATUS.ESTABLISHED)throw new Error("Invalid session state "+sessionStatus);if(!options)throw new TypeError("options must be provided");if(!options.name)throw new TypeError("options.name must be provided");var mediaConnection,streamLogger=createLogger(options.logger,sessionLogger),logger=streamLogger,clientKf=new KalmanFilter,serverKf=new KalmanFilter,id_=uuid_v1(),name_=options.name,mediaProvider=options.mediaProvider||getMediaProviders()[0],display=options.display;if(options.constraints&&0!=Object.keys(options.constraints).length)var constraints=options.constraints;if(options.disableConstraintsNormalization)var disableConstraintsNormalization=options.disableConstraintsNormalization;var receiveAudio,audioOutputId,receiveVideo,mediaConnectionConstraints=options.mediaConnectionConstraints,audioProperty=getConstraintsProperty(constraints,"audio",void 0);if("boolean"==typeof audioProperty)receiveAudio=audioProperty;else if("object"===_typeof(audioProperty)){receiveAudio=!0;var _stereo=getConstraintsProperty(audioProperty,"stereo",0),_bitrate=getConstraintsProperty(audioProperty,"bitrate",0),_fec=getConstraintsProperty(audioProperty,"fec",0);audioOutputId=getConstraintsProperty(audioProperty,"outputId",0);var _codecOptions="";_bitrate&&(_codecOptions+="maxaveragebitrate="+_bitrate+";"),_stereo&&(_codecOptions+="stereo=1;sprop-stereo=1;"),_fec&&(_codecOptions+="useinbandfec=1;")}else receiveAudio="undefined"==typeof options.receiveAudio||options.receiveAudio;var videoProperty=getConstraintsProperty(constraints,"video",void 0);receiveVideo="boolean"==typeof videoProperty?videoProperty:"object"===_typeof(videoProperty)||("undefined"==typeof options.receiveVideo||options.receiveVideo);var bitrate=getConstraintsProperty(constraints,"video.bitrate",0),minBitrate=getConstraintsProperty(constraints,"video.minBitrate",0),maxBitrate=getConstraintsProperty(constraints,"video.maxBitrate",0),quality=getConstraintsProperty(constraints,"video.quality",0);quality>100&&(quality=100);var info_,errorInfo_,audioState_,videoState_,connectionQuality,playWidth="undefined"!=typeof options.playWidth?options.playWidth:getConstraintsProperty(constraints,"video.width",0),playHeight="undefined"!=typeof options.playHeight?options.playHeight:getConstraintsProperty(constraints,"video.height",0),stripCodecs=options.stripCodecs||[],resolution={},published_=!1,record_=options.record||!1,recordFileName=null,cacheLocalResources=options.cacheLocalResources,status_=STREAM_STATUS.NEW,rtmpUrl=options.rtmpUrl,remoteBitrate=-1,networkBandwidth=-1,sdpHook=options.sdpHook,transportType=options.transport,cvoExtension=options.cvoExtension,remoteVideo=options.remoteVideo,callbacks={},playoutDelay=options.playoutDelay,useCanvasMediaStream=options.useCanvasMediaStream,videoContentHint=options.videoContentHint,unmutePlayOnStart=options.unmutePlayOnStart,useControls=options.useControls,collectDeviceInfo=void 0===options.collectDeviceInfo||options.collectDeviceInfo,videoBytes=0,statsCollector=null,httpStatsSender=null,stream={};streamEventRefreshHandlers[id_]=function(streamEvent){if(streamEvent.type==STREAM_EVENT_TYPE.NOT_ENOUGH_BANDWIDTH){var info=streamEvent.payload.info.split("/");remoteBitrate=info[0],networkBandwidth=info[1]}else streamEvent.type==STREAM_EVENT_TYPE.RESIZE&&(resolution.width=streamEvent.payload.streamerVideoWidth,resolution.height=streamEvent.payload.streamerVideoHeight);callbacks[STREAM_EVENT]&&callbacks[STREAM_EVENT](streamEvent)},streamRefreshHandlers[id_]=function(streamInfo,sdp){if(sdp&&""!==sdp){var _sdp=sdp;return _codecOptions&&(_sdp=util.SDP.writeFmtp(sdp,_codecOptions,"opus")),_sdp=sdpHookHandler(_sdp,sdpHook),_sdp=util.setPublishingBitrate(_sdp,mediaConnection,minBitrate,maxBitrate),void mediaConnection.setRemoteSdp(_sdp).then((function(){}))}if(void 0===streamInfo.available){var event=streamInfo.status;if("inboundVideoRate"!==event&&"outboundVideoRate"!==event){if(event===STREAM_EVENT)return streamInfo.mediaSessionId||(streamInfo.mediaSessionId=id_),void streamEventRefreshHandlers[id_](streamInfo);if(event===STREAM_STATUS.RESIZE)resolution.width=streamInfo.streamerVideoWidth,resolution.height=streamInfo.streamerVideoHeight;else if(event===STREAM_STATUS.SNAPSHOT_COMPLETE);else if(event===STREAM_STATUS.NOT_ENOUGH_BANDWIDTH){var info=streamInfo.info.split("/");remoteBitrate=info[0],networkBandwidth=info[1]}else status_=event;if(streamInfo.audioState&&(audioState_=streamInfo.audioState),streamInfo.videoState&&(videoState_=streamInfo.videoState),streamInfo.info&&(info_=streamInfo.info),event!==STREAM_STATUS.FAILED&&event!==STREAM_STATUS.STOPPED&&event!==STREAM_STATUS.UNPUBLISHED||(delete streams[id_],delete streamRefreshHandlers[id_],delete streamEventRefreshHandlers[id_],mediaConnection&&mediaConnection.close(cacheLocalResources),statsCollector&&(statsCollector.stop(),statsCollector=null)),record_&&"undefined"!=typeof streamInfo.recordName&&(recordFileName=streamInfo.recordName),(event===STREAM_STATUS.PUBLISHING||event===STREAM_STATUS.PLAYING)&&webRTCMetricsServerDescription&&!statsCollector){var builder=(new RTCMetricsCollectorBuilder).id(id_).description(webRTCMetricsServerDescription).peerConnection(mediaConnection.getRTCPeerConnection()).logger(logger).websocket(wsConnection);null!=webRTCMetricsServerDescription.ingestPoint&&webRTCMetricsServerDescription.ingestPoint.startsWith("http")&&(httpStatsSender=new RTCMetricsHttpSender(webRTCMetricsServerDescription.ingestPoint,{Authorization:webRTCMetricsServerDescription.authorization}),builder.httpSender(httpStatsSender)),(statsCollector=builder.build()).start()}!streamInfo.status&&null!=streamInfo.authorization&&httpStatsSender&&(httpStatsSender.headers=_objectSpread(_objectSpread({},httpStatsSender.headers),{},{Authorization:streamInfo.authorization})),!streamInfo.status&&void 0!==streamInfo.collect&&statsCollector&&(streamInfo.collect===RTCMetricsCollectType.on?statsCollector.collect(!0):statsCollector.collect(!1)),callbacks[event]&&callbacks[event](stream)}else detectConnectionQuality(event,streamInfo)}else{for(var i=0;i<availableCallbacks.length;i++)info_=streamInfo.reason,"true"==streamInfo.available?availableCallbacks[i].resolve(stream):availableCallbacks[i].reject(stream);availableCallbacks=[]}};var detectConnectionQuality=function(event,streamInfo){disableConnectionQualityCalculation||mediaConnection.getStats((function(stats){var bytesSentReceived=0;if(stats)if("outboundVideoRate"==event&&stats.inboundStream&&stats.inboundStream.video&&stats.inboundStream.video.bytesReceived>0)bytesSentReceived=stats.inboundStream.video.bytesReceived;else{if(!(stats.outboundStream&&stats.outboundStream.video&&stats.outboundStream.video.bytesSent>0))return;bytesSentReceived=stats.outboundStream.video.bytesSent}if(videoBytes){var currentVideoRate=8*(bytesSentReceived-videoBytes);if(0!=currentVideoRate){var currentQuality,clientFiltered=clientKf.filter(currentVideoRate),serverFiltered=serverKf.filter(streamInfo.videoRate),videoRateDifference=100*Math.abs((serverFiltered-clientFiltered)/((serverFiltered+clientFiltered)/2));currentQuality=serverFiltered<5e4||clientFiltered<5e4?videoRateDifference>150?CONNECTION_QUALITY.BAD:CONNECTION_QUALITY.PERFECT:videoRateDifference>50?CONNECTION_QUALITY.BAD:videoRateDifference>20?CONNECTION_QUALITY.GOOD:CONNECTION_QUALITY.PERFECT,callbacks[CONNECTION_QUALITY.UPDATE]&&(connectionQuality=currentQuality,callbacks[CONNECTION_QUALITY.UPDATE](connectionQuality,clientFiltered,serverFiltered)),videoBytes=bytesSentReceived}}else videoBytes=bytesSentReceived}))},isRemoteAudioMuted=function(){return!(!mediaConnection||"Flash"==mediaProvider)&&mediaConnection.isRemoteAudioMuted()},_stop=function(){if(logger.debug("core","Stop stream "+name_),statsCollector&&(statsCollector.stop(),statsCollector=null),status_!=STREAM_STATUS.NEW)return status_==STREAM_STATUS.PENDING?(logger.warn("core","Stopping stream before server response "+id_),void setTimeout(_stop,200)):void(status_!=STREAM_STATUS.FAILED?(send(published_?"unPublishStream":"stopStream",{mediaSessionId:id_,name:name_,published:published_,hasVideo:!0,hasAudio:!0,status:status_,record:!1}),mediaConnection&&mediaConnection.close(cacheLocalResources)):logger.warn("core","Stream status FAILED"));streamRefreshHandlers[id_]({status:STREAM_STATUS.FAILED})},published=function(){return published_};function sendStreamEvent(type,payload){send("sendStreamEvent",{mediaSessionId:id_,type:type,payload:payload})}var fireUnmuteEvent=function(){isRemoteAudioMuted()&&streamRefreshHandlers[id_]&&"function"==typeof streamRefreshHandlers[id_]&&streamRefreshHandlers[id_]({status:STREAM_EVENT,type:STREAM_EVENT_TYPE.UNMUTE_REQUIRED})},setZoom=function(){var _ref2=_asyncToGenerator(_regenerator().m((function _callee2(value){return _regenerator().w((function(_context2){for(;;)switch(_context2.n){case 0:if(!published()||!mediaConnection){_context2.n=2;break}return _context2.n=1,mediaConnection.setZoom(value);case 1:return _context2.a(2,_context2.v);case 2:throw new Error("This function available for publishing stream only");case 3:return _context2.a(2)}}),_callee2)})));return function(_x2){return _ref2.apply(this,arguments)}}();return stream.play=function(){if(logger.debug("core","Play stream "+name_),status_!==STREAM_STATUS.NEW)throw new Error("Invalid stream state "+status_);status_=STREAM_STATUS.PENDING,MediaProvider[mediaProvider].createConnection({id:id_,display:display,authToken:authToken,mainUrl:urlServer,flashProto:flashProto,flashPort:flashPort,flashBufferTime:options.flashBufferTime||0,flashShowFullScreenButton:options.flashShowFullScreenButton||!1,connectionConfig:mediaOptions,connectionConstraints:mediaConnectionConstraints,audioOutputId:audioOutputId,remoteVideo:remoteVideo,playoutDelay:playoutDelay,unmutePlayOnStart:unmutePlayOnStart,useControls:useControls,logger:logger,unmuteRequiredEvent:fireUnmuteEvent},streamRefreshHandlers[id_]).then((function(newConnection){mediaConnection=newConnection;try{streamRefreshHandlers[id_]({status:status_})}catch(e){console.warn(e)}return mediaConnection.createOffer({receiveAudio:receiveAudio,receiveVideo:receiveVideo,stripCodecs:stripCodecs,stereo:_stereo})})).then((function(offer){logger.debug("core","Offer SDP:\n"+offer.sdp),send("playStream",{mediaSessionId:id_,name:name_,published:published_,hasVideo:!0,hasAudio:!0,status:status_,record:!1,width:playWidth,height:playHeight,mediaProvider:mediaProvider,sdp:offer.sdp,custom:options.custom,bitrate:bitrate,minBitrate:minBitrate,maxBitrate:maxBitrate,quality:quality,constraints:constraints,transport:transportType,cvoExtension:cvoExtension}),offer.player&&offer.player.play(id_)})).catch((function(error){throw error}))},stream.publish=function(){if(logger.debug("core","Publish stream "+name_),status_!==STREAM_STATUS.NEW)throw new Error("Invalid stream state "+status_);status_=STREAM_STATUS.PENDING,published_=!0;constraints&&constraints.video&&constraints.video.type&&constraints.video.type,MediaProvider[mediaProvider].getMediaAccess(constraints,display,disableConstraintsNormalization,useCanvasMediaStream).then((function(){status_!=STREAM_STATUS.FAILED?MediaProvider[mediaProvider].createConnection({id:id_,display:display,authToken:authToken,mainUrl:urlServer,flashProto:flashProto,flashPort:flashPort,constraints:constraints,connectionConfig:mediaOptions,connectionConstraints:mediaConnectionConstraints,customStream:!(!constraints||!constraints.customStream)&&constraints.customStream,videoContentHint:videoContentHint,useControls:useControls,logger:logger}).then((function(newConnection){return(mediaConnection=newConnection).createOffer({stripCodecs:stripCodecs})})).then((function(offer){logger.debug("core","Offer SDP:\n"+offer.sdp);var publishStreamData={mediaSessionId:id_,name:name_,published:published_,hasVideo:offer.hasVideo,hasAudio:offer.hasAudio,status:status_,record:record_,mediaProvider:mediaProvider,sdp:offer.sdp,custom:options.custom,bitrate:bitrate,minBitrate:minBitrate,maxBitrate:maxBitrate,rtmpUrl:rtmpUrl,constraints:constraints,transport:transportType,cvoExtension:cvoExtension};collectDeviceInfo&&(publishStreamData.localMediaInfo=collectLocalMediaInfo(MediaProvider[mediaProvider],display)),send("publishStream",publishStreamData)})):cacheLocalResources||releaseLocalMedia(display,mediaProvider)})).catch((function(error){logger.warn("core",error),info_=ERROR_INFO.LOCAL_ERROR,errorInfo_=error.message,status_=STREAM_STATUS.FAILED,callbacks[status_]&&callbacks[status_](stream)}))},stream.stop=_stop,stream.id=function(){return id_},stream.status=function(){return status_},stream.name=function(){return name_},stream.published=published,stream.getRecordInfo=function(){return recordFileName},stream.getInfo=function(){return info_},stream.getErrorInfo=function(){return errorInfo_},stream.videoResolution=function(){if(published_)throw new Error("This function available only on playing stream");return resolution},stream.setAudioOutputId=function(id){if(audioOutputId=id,mediaConnection&&mediaConnection.setAudioOutputId)return mediaConnection.setAudioOutputId(id)},stream.setVolume=function(volume){mediaConnection&&mediaConnection.setVolume(volume)},stream.unmuteRemoteAudio=function(){mediaConnection&&"Flash"!=mediaProvider&&mediaConnection.unmuteRemoteAudio()},stream.muteRemoteAudio=function(){mediaConnection&&"Flash"!=mediaProvider&&mediaConnection.muteRemoteAudio()},stream.isRemoteAudioMuted=isRemoteAudioMuted,stream.setMicrophoneGain=function(volume){if(status_!==STREAM_STATUS.PUBLISHING)throw new Error("Invalid stream state");mediaConnection.setMicrophoneGain(volume)},stream.getVolume=function(){return mediaConnection?mediaConnection.getVolume():-1},stream.muteAudio=function(){mediaConnection&&(mediaConnection.muteAudio(),sendStreamEvent(STREAM_EVENT_TYPE.AUDIO_MUTED))},stream.unmuteAudio=function(){mediaConnection&&(mediaConnection.unmuteAudio(),sendStreamEvent(STREAM_EVENT_TYPE.AUDIO_UNMUTED))},stream.isAudioMuted=function(){return!mediaConnection||mediaConnection.isAudioMuted()},stream.muteVideo=function(){mediaConnection&&(mediaConnection.muteVideo(),sendStreamEvent(STREAM_EVENT_TYPE.VIDEO_MUTED))},stream.unmuteVideo=function(){mediaConnection&&(mediaConnection.unmuteVideo(),sendStreamEvent(STREAM_EVENT_TYPE.VIDEO_UNMUTED))},stream.isVideoMuted=function(){return!mediaConnection||mediaConnection.isVideoMuted()},stream.getStats=function(callbackFn,nativeStats){mediaConnection&&mediaConnection.getStats(callbackFn,nativeStats)},stream.snapshot=function(){if(logger.debug("core","Request snapshot, stream "+name_),status_!==STREAM_STATUS.NEW&&status_!==STREAM_STATUS.PLAYING&&status_!==STREAM_STATUS.PUBLISHING)throw new Error("Invalid stream state");send("snapshot",{name:name_,mediaSessionId:id_})},stream.getAudioState=function(){return audioState_},stream.getVideoState=function(){return videoState_},stream.getNetworkBandwidth=function(){return networkBandwidth},stream.getRemoteBitrate=function(){return remoteBitrate},stream.fullScreen=function(){published()?logger.warn("core","Full screen is allowed only for played streams"):mediaConnection&&mediaConnection.fullScreen()},stream.on=function(event,callback){if(!event)throw new TypeError("Event can't be null");if(!callback||"function"!=typeof callback)throw new Error("Callback needs to be a valid function");return callbacks[event]=callback,stream},stream.available=function(){return new _Promise((function(resolve,reject){send("availableStream",{mediaSessionId:id_,name:name_});var promise={};promise.resolve=resolve,promise.reject=reject,availableCallbacks.push(promise)}))},stream.switchCam=function(deviceId){if(status_!==STREAM_STATUS.PUBLISHING)throw new Error("Invalid stream state");return mediaConnection.switchCam(deviceId)},stream.switchMic=function(deviceId){if(status_!==STREAM_STATUS.PUBLISHING)throw new Error("Invalid stream state");return mediaConnection.switchMic(deviceId)},stream.switchToScreen=function(source,woExtension){if(status_!==STREAM_STATUS.PUBLISHING)throw new Error("Invalid stream state");return mediaConnection.switchToScreen(source,woExtension)},stream.switchToCam=function(){if(status_!==STREAM_STATUS.PUBLISHING)throw new Error("Invalid stream state");mediaConnection.switchToCam()},stream.sendData=function(payload){if(status_!==STREAM_STATUS.PUBLISHING)throw new Error("Invalid stream state");sendStreamEvent(STREAM_EVENT_TYPE.DATA,payload)},stream.getLogger=function(){return streamLogger},stream.updateVideoSettings=function(settings){if(published()&&mediaConnection)return mediaConnection.updateVideoSettings(settings);throw new Error("This function available for publishing stream only")},stream.updateVideoResolution=function(resolution){if(published()&&mediaConnection)return mediaConnection.updateVideoResolution(resolution);throw new Error("This function available for publishing stream only")},stream.getZoomCapabilities=function(){if(published()&&mediaConnection)return mediaConnection.getZoomCapabilities();throw new Error("This function available for publishing stream only")},stream.getZoom=function(){if(published()&&mediaConnection)return mediaConnection.getZoom();throw new Error("This function available for publishing stream only")},stream.setZoom=setZoom,streams[id_]=stream,stream},session.createCall=createCall,session.getStream=function(streamId){return streams[streamId]},session.getStreams=function(){return util.copyObjectToArray(streams)},session.sendData=restAppCommunicator.sendData,session.disconnect=function(){wsConnection&&wsConnection.close()},session.submitBugReport=function(reportObject){send("submitBugReport",reportObject)},session.startDebug=function(){logger.setPushLogs(!0),logger.setLevel("DEBUG"),send("sessionDebug",{command:"start"})},session.stopDebug=function(){logger.setLevel("INFO"),send("sessionDebug",{command:"stop"})},session.on=function(event,callback){if(!event)throw new Error("Event can't be null","TypeError");if(!callback||"function"!=typeof callback)throw new Error("Callback needs to be a valid function");return callbacks[event]=callback,session},session.getLogger=function(){return sessionLogger},sessions[id_]=session,session},playFirstSound:function(noise){var mediaProvider=getMediaProviders()[0];MediaProvider[mediaProvider].playFirstSound(noise)},playFirstVideo:function(display,isLocal,src,useControls){for(var mp in MediaProvider)return MediaProvider[mp].playFirstVideo(display,isLocal,src,useControls)},getLogger:function(){if(initialized)return coreLogger;console.warn("Initialize API first.")},constants:constants,firefoxScreenSharingExtensionInstalled:!0,Browser:util.Browser}},{"./client-info":71,"./constants":72,"./media-source-media-provider":17,"./temasys-media-provider":17,"./util":74,"./webrtc-media-provider":75,"./websocket-media-provider":17,"@flashphoner/web-sdk-metrics":1,kalmanjs:18,"promise-polyfill":36,uuid:41,"webrtc-adapter":56}],74:[function(require,module,exports){"use strict";function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}var Browser={isIE:function(){return!!document.documentMode},isFirefox:function(){return"undefined"!=typeof InstallTrigger},isChrome:function(){return!!window.chrome&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)&&!/OPR/.test(navigator.userAgent)},isEdge:function(){return!this.isIE()&&!!window.StyleMedia},isOpera:function(){return!!window.opr&&!!opr.addons||!!window.opera||navigator.userAgent.indexOf(" OPR/")>=0},isiOS:function(){return/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream},isSafari:function(){var userAgent=navigator.userAgent.toLowerCase();return/(safari|applewebkit)/i.test(userAgent)&&!userAgent.includes("chrome")&&!userAgent.includes("android")},isAndroid:function(){return navigator.userAgent.toLowerCase().indexOf("android")>-1},isSafariWebRTC:function(){return navigator.mediaDevices&&this.isSafari()},isSamsungBrowser:function(){return/SamsungBrowser/i.test(navigator.userAgent)},isAndroidFirefox:function(){return this.isAndroid()&&/Firefox/i.test(navigator.userAgent)},isChromiumEdge:function(){return/Chrome/i.test(navigator.userAgent)&&/Edg/i.test(navigator.userAgent)},version:function(){var version=navigator.userAgent.match(/version\/(\d+)/i);return version?version[1]:(this.isEdge()&&(version=/\brv[ :]+(\d+)/g.exec(navigator.userAgent)||[]),this.isOpera()&&(version=navigator.userAgent.match(/\b(OPR)\/(\d+)/)||[]),this.isChromiumEdge()&&(version=navigator.userAgent.match(/\b(Edg)\/(\d+)/)||[]),this.isSamsungBrowser()&&(version=navigator.userAgent.match(/\b(SamsungBrowser)\/(\d+)/)||[]),this.isChrome()&&(version=navigator.userAgent.match(/\b(Chrome)\/(\d+)/)||[]),this.isFirefox()&&(version=navigator.userAgent.match(/\b(Firefox)\/(\d+)/)||[]),version[2]||0)}},SDP={matchPrefix:function(sdp,prefix){return sdp.trim().split("\n").map((function(line){return line.trim()})).filter((function(line){return 0===line.indexOf(prefix)}))},writeFmtp:function(sdp,param,codec){var i,sdpArray=sdp.split("\n");for(i=0;i<sdpArray.length;i++)-1!=sdpArray[i].search(codec)&&0==sdpArray[i].indexOf("a=rtpmap")&&(sdpArray[i]+="\na=fmtp:"+sdpArray[i].match(/[0-9]+/)[0]+" "+param+"\r");var result="";for(i=0;i<sdpArray.length;i++)""!=sdpArray[i]&&(result+=sdpArray[i]+"\n");return result},setPublishingBitrate:function(sdp,minBitrate,maxBitrate){if(sdp&&(minBitrate||maxBitrate)){var i,matches,sdpArray=sdp.split("\n"),rtpmap=-1,codec="",bitrateString="";for(i=0;i<sdpArray.length;i++)sdpArray[i].startsWith("a=rtpmap")?(matches=sdpArray[i].match("a=rtpmap:(.+) (.+)/.*"))&&matches.length>2&&(rtpmap=parseInt(matches[1],10),codec=matches[2]):"H264"!==codec&&"VP8"!==codec||(sdpArray[i].startsWith("a=fmtp:"+rtpmap)?(bitrateString=this.getBitrateString(sdpArray[i],minBitrate,maxBitrate))&&(sdpArray[i]+=";"+bitrateString):(bitrateString=this.getBitrateString("",minBitrate,maxBitrate))&&(sdpArray[i]="a=fmtp:"+rtpmap+" "+bitrateString+"\r\n"+sdpArray[i]),codec="",rtpmap=-1);var newSDP="";for(i=0;i<sdpArray.length;i++)""!=sdpArray[i]&&(newSDP+=sdpArray[i]+"\n");return newSDP}return sdp},getBitrateString:function(string,minBitrate,maxBitrate){var bitrateString="";return minBitrate&&-1==string.indexOf("x-google-min-bitrate")&&(bitrateString+="x-google-min-bitrate="+minBitrate),maxBitrate&&-1==string.indexOf("x-google-max-bitrate")&&(bitrateString&&(bitrateString+=";"),bitrateString+="x-google-max-bitrate="+maxBitrate),bitrateString}};module.exports={isEmptyObject:function(obj){for(var name in obj)return!1;return!0},copyObjectToArray:function(obj){var ret=[];for(var prop in obj)obj.hasOwnProperty(prop)&&ret.push(obj[prop]);return ret},copyObjectPropsToAnotherObject:function(src,dst){for(var prop in src)src.hasOwnProperty(prop)&&(dst[prop]=src[prop])},processRtcStatsReport:function(browser,report){var result={};if("chrome"==browser){var gotResult=!1;if(report.type&&"googCandidatePair"==report.type&&"true"==report.googActiveConnection&&(gotResult=!0),report.type&&"ssrc"==report.type&&(gotResult=!0),gotResult)for(var k in report)report.hasOwnProperty(k)&&(result[k]=report[k]);return result}if("firefox"==browser){if(report.type&&("outboundrtp"==report.type||"inboundrtp"==report.type)&&-1==report.id.indexOf("rtcp"))for(var k in result={},report)report.hasOwnProperty(k)&&(result[k]=report[k]);return result}return result},Browser:Browser,SDP:SDP,logger:function(){return{init:function(verbosity,enablePushLogs,customLogger,enableLogs){switch(verbosity.toUpperCase()){case"DEBUG":this.verbosity=3;break;case"INFO":this.verbosity=2;break;case"ERROR":this.verbosity=0;break;case"WARN":this.verbosity=1;break;case"TRACE":this.verbosity=4;break;default:this.verbosity=2}this.date=function(){return(new Date).toTimeString().split(" ")[0]},this.enablePushLogs=enablePushLogs;var delayedLogs=[];this.customLogger=customLogger,this.enableLogs=enableLogs,this.pushLogs=function(log){if(this.wsConnection&&this.enablePushLogs){if(delayedLogs.length)for(var i=0;i<delayedLogs.length;i++)this.wsConnection.send(JSON.stringify({message:"pushLogs",data:[{logs:delayedLogs[i]}]}));delayedLogs=[],this.wsConnection.send(JSON.stringify({message:"pushLogs",data:[{logs:log}]}))}else delayedLogs.push(log)}},info:function(src,text){if(this.enableLogs){var prefix=this.date()+" INFO "+src+" - ";this.pushLogs(prefix+JSON.stringify(text)+"\n"),this.verbosity>=2&&(null!=this.customLogger?this.customLogger.info(text):console.log(prefix,text))}},debug:function(src,text){if(this.enableLogs){var prefix=this.date()+" DEBUG "+src+" - ";this.pushLogs(prefix+JSON.stringify(text)+"\n"),this.verbosity>=3&&(null!=this.customLogger?this.customLogger.debug(text):console.log(prefix,text))}},trace:function(src,text){if(this.enableLogs){var prefix=this.date()+" TRACE "+src+" - ";this.pushLogs(prefix+JSON.stringify(text)+"\n"),this.verbosity>=4&&(null!=this.customLogger?this.customLogger.trace(text):console.log(prefix,text))}},warn:function(src,text){if(this.enableLogs){var prefix=this.date()+" WARN "+src+" - ";this.pushLogs(prefix+JSON.stringify(text)+"\n"),this.verbosity>=1&&(null!=this.customLogger?this.customLogger.warn(text):console.warn(prefix,text))}},error:function(src,text){if(this.enableLogs){var prefix=this.date()+" ERROR "+src+" - ";this.pushLogs(prefix+JSON.stringify(text)+"\n"),this.verbosity>=0&&(null!=this.customLogger?this.customLogger.error(text):console.error(prefix,text))}},setEnableLogs:function(enableLogs){this.enableLogs=enableLogs},setCustomLogger:function(customLogger){this.customLogger=customLogger},setConnection:function(connection){this.wsConnection=connection},setPushLogs:function(pushLogs){this.enablePushLogs=pushLogs},setLevel:function(level){switch(level.toUpperCase()){case"DEBUG":this.verbosity=3;break;case"INFO":this.verbosity=2;break;case"ERROR":this.verbosity=0;break;case"WARN":this.verbosity=1;break;case"TRACE":this.verbosity=4;break;default:this.verbosity=2}}}},stripCodecs:function(sdp,codecs){if(!codecs.length)return sdp;for(var i,sdpArray=sdp.split("\n"),codecsArray=codecs.split(","),pt=[],p=0;p<codecsArray.length;p++)for(console.log("Searching for codec "+codecsArray[p]),i=0;i<sdpArray.length;i++)-1!=sdpArray[i].search(new RegExp(codecsArray[p],"i"))&&0==sdpArray[i].indexOf("a=rtpmap")&&(console.log(codecsArray[p]+" detected"),pt.push(sdpArray[i].match(/[0-9]+/)[0]),sdpArray[i]="");if(pt.length){for(p=0;p<pt.length;p++)for(i=0;i<sdpArray.length;i++)-1==sdpArray[i].search("a=fmtp:"+pt[p])&&-1==sdpArray[i].search("a=rtcp-fb:"+pt[p])||(sdpArray[i]="");for(i=0;i<sdpArray.length;i++)if(-1!=sdpArray[i].search("m=audio")||-1!=sdpArray[i].search("m=video")){for(var mLineSplitted=sdpArray[i].split(" "),newMLine="",m=0;m<mLineSplitted.length;m++)(-1==pt.indexOf(mLineSplitted[m].trim())||m<=2)&&(newMLine+=mLineSplitted[m],m<mLineSplitted.length-1&&(newMLine+=" "));sdpArray[i]=newMLine}}var result="";for(i=0;i<sdpArray.length;i++)""!=sdpArray[i]&&(result+=sdpArray[i]+"\n");return result},getCurrentCodecAndSampleRate:function(sdp,mediaType){for(var codecPt,rows=sdp.split("\n"),ret={},i=0;i<rows.length;i++){if(codecPt&&-1!=rows[i].indexOf("a=rtpmap:"+codecPt))return ret.name=rows[i].split(" ")[1].split("/")[0],ret.sampleRate=rows[i].split(" ")[1].split("/")[1],ret;-1!=rows[i].indexOf("m="+mediaType)&&(codecPt=rows[i].split(" ")[3].trim())}return ret.name="undefined",ret.sampleRate="undefined",ret},isPromise:function(object){return null!==object&&"object"===_typeof(object)&&"function"==typeof object.then&&"function"==typeof object.catch},setPublishingBitrate:function(sdp,mediaConnection,minBitrate,maxBitrate){return(minBitrate||maxBitrate)&&(sdp&&Browser.isChrome()||Browser.isSafariWebRTC()?sdp=SDP.setPublishingBitrate(sdp,minBitrate,maxBitrate):mediaConnection&&mediaConnection.setPublishingBitrate(minBitrate,maxBitrate)),sdp},addFieldToCsvString:function(csvString,field,delimiter){return""!==field&&field.indexOf(delimiter)>=0&&(field='"'+field+'"'),csvString=""===csvString?field:csvString+delimiter+field}}},{}],75:[function(require,module,exports){function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}function _slicedToArray(r,e){return function(r){if(Array.isArray(r))return r}(r)||function(r,l){var t=null==r?null:"undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(null!=t){var e,n,i,u,a=[],f=!0,o=!1;try{if(i=(t=t.call(r)).next,0===l){if(Object(t)!==t)return;f=!1}else for(;!(f=(e=i.call(t)).done)&&(a.push(e.value),a.length!==l);f=!0);}catch(r){o=!0,n=r}finally{try{if(!f&&null!=t.return&&(u=t.return(),Object(u)!==u))return}finally{if(o)throw n}}return a}}(r,e)||_unsupportedIterableToArray(r,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}function _regenerator(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function i(r,n,o,i){var c=n&&n.prototype instanceof Generator?n:Generator,u=Object.create(c.prototype);return _regeneratorDefine2(u,"_invoke",function(r,n,o){var i,c,u,f=0,p=o||[],y=!1,G={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return i=t,c=0,u=e,G.n=r,a}};function d(r,n){for(c=r,u=n,t=0;!y&&f&&!o&&t<p.length;t++){var o,i=p[t],d=G.p,l=i[2];r>3?(o=l===n)&&(u=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&d<i[1])?(c=0,G.v=n,G.n=i[1]):d<l&&(o=r<3||i[0]>n||n>l)&&(i[4]=r,i[5]=n,G.n=l,c=0))}if(o||r>1)return a;throw y=!0,n}return function(o,p,l){if(f>1)throw TypeError("Generator is already running");for(y&&1===p&&d(p,l),c=p,u=l;(t=c<2?e:u)||!y;){i||(c?c<3?(c>1&&(G.n=-1),d(c,u)):G.n=u:G.v=u);try{if(f=2,i){if(c||(o="next"),t=i[o]){if(!(t=t.call(i,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);i=e}else if((t=(y=G.n<0)?u:r.call(n,G))!==a)break}catch(t){i=e,c=1,u=t}finally{f=1}}return{value:t,done:y}}}(r,o,i),!0),u}var a={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}t=Object.getPrototypeOf;var c=[][n]?t(t([][n]())):(_regeneratorDefine2(t={},n,(function(){return this})),t),u=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(c);function f(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,GeneratorFunctionPrototype):(e.__proto__=GeneratorFunctionPrototype,_regeneratorDefine2(e,o,"GeneratorFunction")),e.prototype=Object.create(u),e}return GeneratorFunction.prototype=GeneratorFunctionPrototype,_regeneratorDefine2(u,"constructor",GeneratorFunctionPrototype),_regeneratorDefine2(GeneratorFunctionPrototype,"constructor",GeneratorFunction),GeneratorFunction.displayName="GeneratorFunction",_regeneratorDefine2(GeneratorFunctionPrototype,o,"GeneratorFunction"),_regeneratorDefine2(u),_regeneratorDefine2(u,o,"Generator"),_regeneratorDefine2(u,n,(function(){return this})),_regeneratorDefine2(u,"toString",(function(){return"[object Generator]"})),(_regenerator=function(){return{w:i,m:f}})()}function _regeneratorDefine2(e,r,n,t){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}(_regeneratorDefine2=function(e,r,n,t){function o(r,n){_regeneratorDefine2(e,r,(function(e){return this._invoke(r,n,e)}))}r?i?i(e,r,{value:n,enumerable:!t,configurable:!t,writable:!t}):e[r]=n:(o("next",0),o("throw",1),o("return",2))})(e,r,n,t)}function asyncGeneratorStep(n,t,e,r,o,a,c){try{var i=n[a](c),u=i.value}catch(n){return void e(n)}i.done?t(u):Promise.resolve(u).then(r,o)}function _asyncToGenerator(n){return function(){var t=this,e=arguments;return new Promise((function(r,o){var a=n.apply(t,e);function _next(n){asyncGeneratorStep(a,r,o,_next,_throw,"next",n)}function _throw(n){asyncGeneratorStep(a,r,o,_next,_throw,"throw",n)}_next(void 0)}))}}var extensionId,defaultConstraints,logger,audioContext,createMicGainNode,microphoneGain,browserDetails=require("webrtc-adapter").default.browserDetails,uuid_v1=require("uuid").v1,util=require("./util"),connections={},constants=require("./constants"),validBrowsers=["firefox","chrome","safari"],videoCams=[],mics=[],audioSourceDevice="",mixAudioTracks=function(stream1,stream2){var stream1Sound=audioContext.createMediaStreamSource(stream1),stream2Sound=audioContext.createMediaStreamSource(stream2),destination=audioContext.createMediaStreamDestination(),newStream=destination.stream;return stream1Sound.connect(destination),stream2Sound.connect(destination),newStream.getAudioTracks()[0]},loadCanvasVideo=function(display,stream,video){var vEl=video;if(vEl){if("CANVAS"!==vEl.tagName){var canvas=document.createElement("canvas");display.replaceChild(canvas,vEl),canvas.appendChild(vEl),vEl=canvas}}else!function(parent){var canvas=document.createElement("canvas");parent.appendChild(canvas)}(display),function(parent){var video=document.createElement("video");parent.appendChild(video)}(display.children[0]),vEl=display.children[0];vEl.id||(vEl.id=uuid_v1()+"-LOCAL_CACHED_VIDEO");var child=vEl.children[0];return child.srcObject=stream,child.muted=!0,child.onloadedmetadata=function(e){child.play(),vEl.width=child.videoWidth,vEl.height=child.videoHeight,function(canvas,videoWidth,videoHeight){if(!canvas.parentNode)return;var newSize,display=vEl.parentNode,parentSize={w:display.parentNode.clientWidth,h:display.parentNode.clientHeight};newSize=videoWidth&&videoHeight?downScaleToFitSize(videoWidth,videoHeight,parentSize.w,parentSize.h):downScaleToFitSize(canvas.videoWidth,canvas.videoHeight,parentSize.w,parentSize.h);display.style.width=newSize.w+"px",display.style.height=newSize.h+"px";var margin=0;parentSize.h-newSize.h>1&&(margin=Math.floor((parentSize.h-newSize.h)/2));function downScaleToFitSize(videoWidth,videoHeight,dstWidth,dstHeight){var newWidth,newHeight,videoRatio=videoWidth/videoHeight;return dstWidth/dstHeight>videoRatio?(newHeight=dstHeight,newWidth=Math.floor(videoRatio*dstHeight)):(newWidth=dstWidth,newHeight=Math.floor(dstWidth/videoRatio)),{w:newWidth,h:newHeight}}display.style.margin=margin+"px auto"}(vEl,child.videoWidth,child.videoHeight)},util.Browser.isFirefox()&&vEl.getContext("2d"),vEl.srcObject=vEl.captureStream(30),stream.getAudioTracks().length>0&&vEl.srcObject.addTrack(stream.getAudioTracks()[0]),vEl},loadVideo=function(display,stream,screenShare,requestAudioConstraints,resolve,constraints,useCanvas){var video;function resolveCallback(){requestAudioConstraints&&"chrome"==browserDetails.browser?(logger.info("webrtc","Request for audio stream"),navigator.getUserMedia({audio:requestAudioConstraints},(function(stream){if(logger.info("webrtc","Got audio stream, add it to video stream"),video.srcObject.getAudioTracks()[0]){var mixedTrack=mixAudioTracks(stream,video.srcObject),originalTrack=video.srcObject.getAudioTracks()[0];video.srcObject.removeTrack(originalTrack),video.srcObject.addTrack(mixedTrack)}else video.srcObject.addTrack(stream.getAudioTracks()[0]);resolve(display)}))):resolve(display)}video=useCanvas?loadCanvasVideo(display,stream,getCacheInstance(display)):function(display,stream,screenShare,constraints,video){var vEl=video;return vEl||(vEl=createVideoElement(),display.appendChild(vEl)),vEl.id||(vEl.id=uuid_v1()+"-LOCAL_CACHED_VIDEO"),vEl.srcObject=stream,vEl.onloadedmetadata=function(e){screenShare&&!screenCaptureSupportedBrowsers()&&setScreenResolution(vEl,stream,constraints),vEl.play()},vEl}(display,stream,screenShare,constraints,getCacheInstance(display)),createMicGainNode&&stream.getAudioTracks().length>0&&"chrome"==browserDetails.browser&&(audioContext.resume(),microphoneGain=createGainNode(stream)),constraints.systemSound&&"chrome"==browserDetails.browser?chrome.runtime.sendMessage(extensionId,{type:"isInstalled"},(function(response){response?chrome.runtime.sendMessage(extensionId,{type:"getSourceId"},(function(response){if(response.error)resolveCallback(),logger.error("webrtc",response.error);else if(response.systemSoundAccess){var constraints={audio:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:response.sourceId,echoCancellation:!0},optional:[]},video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:response.sourceId},optional:[]}};navigator.getUserMedia(constraints,(function(audioStream){if(stream.getAudioTracks().length>0){var originalAudioTrack=stream.getAudioTracks()[0],mixedTrack=mixAudioTracks(stream,audioStream);stream.addTrack(mixedTrack),stream.removeTrack(originalAudioTrack)}else stream.addTrack(audioStream.getAudioTracks()[0]);resolveCallback()}),(function(reason){resolveCallback(),logger.error("webrtc",reason)}))}else resolveCallback(),logger.error("webrtc","System sound: access is denied by the user")})):resolveCallback()})):resolveCallback()},createGainNode=function(stream){var audioCtx=audioContext,source=audioCtx.createMediaStreamSource(stream),gainNode=audioCtx.createGain(),destination=audioCtx.createMediaStreamDestination(),outputStream=destination.stream;source.connect(gainNode),gainNode.connect(destination);var sourceAudioTrack=stream.getAudioTracks()[0];return audioSourceDevice=sourceAudioTrack.label,gainNode.sourceAudioTrack=sourceAudioTrack,gainNode.release=function(){this.sourceAudioTrack.stop(),this.disconnect()},stream.addTrack(outputStream.getAudioTracks()[0]),stream.removeTrack(sourceAudioTrack),gainNode},setScreenResolution=function(video,stream,constraints){var newHeight,newWidth,videoRatio;video.videoWidth>video.videoHeight?(videoRatio=video.videoWidth/video.videoHeight,newHeight=constraints.video.videoWidth/videoRatio,newWidth=constraints.video.videoWidth):(videoRatio=video.videoHeight/video.videoWidth,newWidth=constraints.video.videoHeight/videoRatio,newHeight=constraints.video.videoHeight),console.log("videoRatio === "+videoRatio),stream.getVideoTracks()[0].applyConstraints({height:newHeight,width:newWidth})},getScreenDeviceIdWoExtension=function(constraints){return new Promise((function(resolve,reject){var video={};constraints.video.frameRate.ideal&&(video.frameRate=constraints.video.frameRate.ideal),constraints.video.width&&(video.width=constraints.video.width),constraints.video.height&&(video.height=constraints.video.height),0===Object.keys(video).length&&(video=!0),resolve({video:video,audio:!0})}))},getScreenDeviceId=function(constraints){return new Promise((function(resolve,reject){var o={};window.chrome?chrome.runtime.sendMessage(extensionId,{type:"isInstalled"},(function(response){response?(o.maxWidth=constraints&&constraints.video&&constraints.video.width?constraints.video.width:320,o.maxHeight=constraints&&constraints.video&&constraints.video.height?constraints.video.height:240,o.maxFrameRate=constraints&&constraints.video&&constraints.video.frameRate&&constraints.video.frameRate.ideal?constraints.video.frameRate.ideal:30,o.chromeMediaSource="desktop",chrome.runtime.sendMessage(extensionId,{type:"getSourceId"},(function(response){if(response.error)reject(new Error("Screen access denied"));else{o.chromeMediaSourceId=response.sourceId;var result={mandatory:o,sourceId:response.sourceId};response.systemSoundAccess&&(result.audioMandatory={chromeMediaSource:"desktop",chromeMediaSourceId:response.sourceId,echoCancellation:!0}),resolve(result)}}))):reject(new Error("Screen sharing extension is not available"))})):(o.mediaSource=constraints.video.mediaSource,o.width={},o.height={},o.frameRate={min:constraints.video.frameRate.max,max:constraints.video.frameRate.max},o.videoWidth=constraints.video.width,o.videoHeight=constraints.video.height,resolve(o))}))},releaseMedia=function(display){var video=getCacheInstance(display);return!!video&&(removeVideoElement(video),!0)};function getCacheInstance(display){var i;if(display)for(i=0;i<display.children.length;i++)if(display.children[i]&&(-1!=display.children[i].id.indexOf("-LOCAL_CACHED_VIDEO")||-1!=display.children[i].id.indexOf("-REMOTE_CACHED_VIDEO")))return logger.info("webrtc","FOUND WEBRTC CACHED INSTANCE, id "+display.children[i].id),display.children[i]}function createVideoElement(){var useControls=arguments.length>0&&void 0!==arguments[0]&&arguments[0],video=document.createElement("video");return video.muted=!0,util.Browser.isSafariWebRTC()&&(video.setAttribute("playsinline",""),video.setAttribute("webkit-playsinline","")),useControls&&enableVideoControls(video),video}function removeVideoElement(video){if(video.srcObject){video.pause();for(var tracks=video.srcObject.getTracks(),i=0;i<tracks.length;i++)tracks[i].stop(),-1!=video.id.indexOf("-LOCAL_CACHED_VIDEO")&&"audio"==tracks[i].kind&µphoneGain&µphoneGain.release();if(video.srcObject=null,"CANVAS"===video.tagName)for(var _i=0;_i<video.children.length;_i++)removeVideoElement(video.children[_i])}}function enableVideoControls(video){video&&!video.controls&&video.setAttribute("controls","controls")}var getList=function(devices,kind){for(var videoFilter=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,list={audio:[],video:[]},micCount=0,outputCount=0,camCount=0,i=0;i<devices.length;i++){var device=devices[i],ret={id:device.deviceId,label:device.label};0===device.kind.indexOf("audio"+kind)&&"communications"!==device.deviceId?(ret.type="audioinput"===device.kind?"mic":"speaker","mic"===ret.type&&""===ret.label&&(ret.label="microphone"+ ++micCount),"speaker"===ret.type&&""===ret.label&&(ret.label="speaker"+ ++outputCount),list.audio.push(ret)):0===device.kind.indexOf("video"+kind)?!videoFilter||videoFilter.find((function(id){return id===device.deviceId}))?(""===ret.label&&(ret.label="camera"+ ++camCount),ret.type="camera",list.video.push(ret)):logger.debug("webrtc","Video device "+device.deviceId+"does not conform the filter "+JSON.stringify(videoFilter)):logger.debug("webrtc","unknown device "+device.kind+" id "+device.deviceId)}return list},listDevices=function(labels,kind,deviceConstraints){deviceConstraints||(deviceConstraints={audio:!0,video:!0}),kind?kind===constants.MEDIA_DEVICE_KIND.ALL&&(kind=""):kind=constants.MEDIA_DEVICE_KIND.INPUT;return new Promise((function(resolve,reject){navigator.mediaDevices.enumerateDevices().then((function(devices){if(labels){var constraints=function(devices){for(var constraints={},i=0;i<devices.length;i++){var device=devices[i];0===device.kind.indexOf("audio"+kind)&&deviceConstraints.audio?constraints.audio=deviceConstraints.audio:0===device.kind.indexOf("video"+kind)&&deviceConstraints.video?constraints.video=deviceConstraints.video:logger.debug("webrtc","unknown device "+device.kind+" id "+device.deviceId)}return constraints}(devices);if(0===Object.keys(constraints).length)return void reject(new Error(kind+" media devices not found"));navigator.getUserMedia(constraints,(function(stream){navigator.mediaDevices.enumerateDevices().then((function(devicesWithLabels){resolve(getList(devicesWithLabels,kind)),stream.getTracks().forEach((function(track){track.stop()}))}),reject)}),reject)}else resolve(getList(devices,kind))}),reject)}))},getMobileDevices=function(){var _ref3=_asyncToGenerator(_regenerator().m((function _callee4(kind){var deviceConstraints,constraints,videoFilter,list,getCamera,front,back,_stream,mediaDevices,_t2,_args4=arguments;return _regenerator().w((function(_context4){for(;;)switch(_context4.p=_context4.n){case 0:return deviceConstraints=_args4.length>1&&void 0!==_args4[1]?_args4[1]:null,constraints={},videoFilter=[],list=null,kind?kind===constants.MEDIA_DEVICE_KIND.ALL&&(kind=""):kind=constants.MEDIA_DEVICE_KIND.INPUT,deviceConstraints&&deviceConstraints.audio?constraints.audio=deviceConstraints.audio:constraints.audio=!0,deviceConstraints&&deviceConstraints.video&&"object"===_typeof(deviceConstraints.video)?constraints.video=deviceConstraints.video:constraints.video={},getCamera=function(){var _ref4=_asyncToGenerator(_regenerator().m((function _callee3(constraints,facingMode){var deviceId,mediaConstraints,_t;return _regenerator().w((function(_context3){for(;;)switch(_context3.p=_context3.n){case 0:return deviceId=null,(mediaConstraints={audio:!1,video:constraints.video}).video.facingMode=facingMode,_context3.p=1,_context3.n=2,navigator.mediaDevices.getUserMedia(mediaConstraints);case 2:stream=_context3.v,stream&&(stream.getVideoTracks().length>0&&(deviceId=stream.getVideoTracks()[0].getSettings().deviceId),stream.getTracks().forEach((function(track){track.stop()}))),_context3.n=4;break;case 3:_context3.p=3,_t=_context3.v,logger.error("webrtc","Can't get device access with video constraints "+JSON.stringify(constraints.video)+", error "+_t);case 4:return _context3.a(2,deviceId)}}),_callee3,null,[[1,3]])})));return function(_x5,_x6){return _ref4.apply(this,arguments)}}(),_context4.n=1,getCamera(constraints,{ideal:"user"});case 1:return(front=_context4.v)&&""!==front&&(logger.debug("webrtc","Front camera id: "+front),videoFilter.push(front)),_context4.n=2,getCamera(constraints,{ideal:"environment"});case 2:return(back=_context4.v)&&""!==back&&(logger.debug("webrtc","Back camera id: "+back),videoFilter.push(back)),_context4.p=3,_context4.n=4,navigator.mediaDevices.getUserMedia(constraints);case 4:if(!(_stream=_context4.v)){_context4.n=6;break}return _context4.n=5,navigator.mediaDevices.enumerateDevices();case 5:(mediaDevices=_context4.v)&&(logger.debug("webrtc","mediaDevices: "+JSON.stringify(mediaDevices)),list=getList(mediaDevices,kind,videoFilter)),_stream.getTracks().forEach((function(track){track.stop()}));case 6:_context4.n=8;break;case 7:_context4.p=7,_t2=_context4.v,logger.error("webrtc","Can't get device access with constraints "+JSON.stringify(constraints)+", error "+_t2);case 8:return _context4.a(2,list)}}),_callee4,null,[[3,7]])})));return function(_x4){return _ref3.apply(this,arguments)}}();var screenCaptureSupportedBrowsers=function(){return util.Browser.isChrome()||util.Browser.isSafari()};module.exports={createConnection:function(options){return new Promise((function(resolve,reject){options.logger&&(logger=options.logger);var id=options.id,connectionConfig=options.connectionConfig||{iceServers:[]},connectionConstraints=options.connectionConstraints||{};connectionConstraints.hasOwnProperty("optional")||(connectionConstraints.optional=[{DtlsSrtpKeyAgreement:!0}]),connectionConfig.bundlePolicy="max-compat";var localVideo,currentAudioTrack,currentVideoTrack,systemSoundTrack,connection=new RTCPeerConnection(connectionConfig,connectionConstraints),display=options.display,localDisplay=options.localDisplay,remoteDisplay=options.remoteDisplay,bidirectional=options.bidirectional,remoteVideo=options.remoteVideo,switchCamIndex=0,switchMicCount=0,customStream=options.customStream,constraints=options.constraints?options.constraints:{},screenShare=!1,playoutDelay=options.playoutDelay,videoContentHint=options.videoContentHint?options.videoContentHint:"motion",unmutePlayOnStart=void 0===options.unmutePlayOnStart||options.unmutePlayOnStart,useControls=options.useControls||!1,unmuteRequiredEvent=options.unmuteRequiredEvent?options.unmuteRequiredEvent:null,zoom=null;if(bidirectional)(localVideo=getCacheInstance(localDisplay))&&(localVideo.srcObject?(localVideo.id=id+"-local",setContentHint(localVideo.srcObject,videoContentHint),addStreamTracks(connection,localVideo.srcObject)):localVideo=null),(remoteVideo=getCacheInstance(remoteDisplay))||(remoteVideo=createVideoElement(useControls),remoteDisplay.appendChild(remoteVideo)),remoteVideo.id=id+"-remote",options.audioOutputId&&"undefined"!=typeof remoteVideo.setSinkId&&remoteVideo.setSinkId(options.audioOutputId),remoteVideo.style="border-radius: 1px";else if(remoteVideo)remoteVideo.id&&(id=remoteVideo.id);else{var cachedVideo=getCacheInstance(display);cachedVideo&&-1===cachedVideo.id.indexOf("-REMOTE_CACHED_VIDEO")&&cachedVideo.srcObject?((localVideo=cachedVideo).id=id,setContentHint(localVideo.srcObject,videoContentHint),addStreamTracks(connection,localVideo.srcObject)):(cachedVideo?remoteVideo=cachedVideo:(remoteVideo=createVideoElement(useControls),display.appendChild(remoteVideo)),remoteVideo.id=id,options.audioOutputId&&"undefined"!=typeof remoteVideo.setSinkId&&remoteVideo.setSinkId(options.audioOutputId),remoteVideo.style="border-radius: 1px")}if(localVideo){useControls&&enableVideoControls(localVideo);var videoTrack=localVideo.srcObject.getVideoTracks()[0];videoTrack&&videoCams.forEach((function(cam,index){videoTrack.label===cam.label&&(switchCamIndex=index)}));var audioTrack=localVideo.srcObject.getAudioTracks()[0];audioTrack&&mics.forEach((function(mic,index){audioTrack.label===mic.label&&(switchMicCount=index)}))}function setContentHint(stream,hint){stream.getVideoTracks().forEach((function(track){void 0===track.contentHint?logger.warn("webrtc","Track contentHint unsupported"):(logger.info("webrtc","Set video track contentHint to "+hint),track.contentHint=hint)}))}function addStreamTracks(pc,stream){stream.getTracks().forEach((function(track){pc.addTrack(track,stream)}))}remoteVideo&&useControls&&enableVideoControls(remoteVideo),connection.ontrack=function(event){remoteVideo&&(remoteVideo.srcObject=event.streams[0],remoteVideo.onloadedmetadata=function(e){remoteVideo&&remoteVideo.play().then((function(){unmutePlayOnStart?remoteVideo.muted=!1:fireUnmuteEvent()})).catch((function(e){validBrowsers.includes(browserDetails.browser)?(logger.info("webrtc","Autoplay detected! Trying to play a video with a muted sound..."),remoteVideo.muted=!0,remoteVideo.play(),fireUnmuteEvent()):logger.error("webrtc",e)}))}),void 0!==playoutDelay&&connection.getReceivers().forEach((function(track){void 0===track.playoutDelayHint&&logger.warn("webrtc","Playout delay unsupported"),track.playoutDelayHint=playoutDelay}))},connection.onremovestream=function(event){remoteVideo&&remoteVideo.pause()},connection.onsignalingstatechange=function(event){},connection.oniceconnectionstatechange=function(event){},connection.onicecandidate=function(event){null!=event.candidate&&logger.debug("webrtc","Added icecandidate: "+event.candidate.candidate)};var unmuteAudio=function(){localVideo&&localVideo.srcObject&&localVideo.srcObject.getAudioTracks().length>0&&(localVideo.srcObject.getAudioTracks()[0].enabled=!0)},unmuteVideo=function(){localVideo&&localVideo.srcObject&&localVideo.srcObject.getVideoTracks().length>0&&(localVideo.srcObject.getVideoTracks()[0].enabled=!0)},getStat=function(){var _ref=_asyncToGenerator(_regenerator().m((function _callee(callbackFn,nativeStats){var result,rawStat;return _regenerator().w((function(_context){for(;;)switch(_context.n){case 0:return result={outboundStream:{},inboundStream:{},otherStats:[]},_context.n=1,getWebRTCStats();case 1:rawStat=_context.v,nativeStats?callbackFn(rawStat):(rawStat["candidate-pair"]&&rawStat["candidate-pair"].forEach((function(report){"succeeded"===report.state&&report.nominated&&(report.availableIncomingBitrate?result.otherStats.availableIncomingBitrate=report.availableIncomingBitrate:localVideo&&report.availableOutgoingBitrate&&(result.otherStats.availableOutgoingBitrate=report.availableOutgoingBitrate))})),rawStat["outbound-rtp"]&&rawStat["outbound-rtp"].forEach((function(report){fillStatObject(result.outboundStream,report,report.kind),"video"===report.kind&&getVideoSize(result.outboundStream[report.kind],report.type,report)})),rawStat["inbound-rtp"]&&rawStat["inbound-rtp"].forEach((function(report){fillStatObject(result.inboundStream,report,report.kind),"video"===report.kind&&getVideoSize(result.inboundStream.video,report.type,report)})),callbackFn(result));case 2:return _context.a(2)}}),_callee)})));return function(_x,_x2){return _ref.apply(this,arguments)}}(),getVideoSize=function(obj,type,report){var videoSize={};"outbound-rtp"===type?void 0!==localVideo&&null!=localVideo&&(videoSize=localVideo.srcObject.getVideoTracks()[0].getSettings()):"inbound-rtp"===type&&void 0!==remoteVideo&&null!=remoteVideo&&(videoSize.width=remoteVideo.videoWidth,videoSize.height=remoteVideo.videoHeight),void 0!==report.frameWidth?obj.width=report.frameWidth:void 0!==videoSize.width&&(obj.width=videoSize.width),void 0!==report.frameHeight?obj.height=report.frameHeight:void 0!==videoSize.height&&(obj.height=videoSize.height)},fillStatObject=function(obj,report,mediaType){obj[mediaType]={};var description=null!=connection.currentRemoteDescription?connection.currentRemoteDescription:connection.remoteDescription,sdp="";description&&description.sdp?sdp=description.sdp:logger.debug("webrtc","Can't parse current SDP to detect codec and sampleRate");var qualityLimitationDurations,codec=util.getCurrentCodecAndSampleRate(sdp,mediaType);obj[mediaType].codec=codec.name,obj[mediaType].codecRate=codec.sampleRate,Object.keys(report).forEach((function(key){(key.startsWith("bytes")||key.startsWith("packets")||-1!=key.indexOf("Count")||-1!=key.indexOf("audioLevel")||"framesPerSecond"===key||"qualityLimitationReason"===key)&&(obj[mediaType][key]=report[key]),"qualityLimitationDurations"===key&&(qualityLimitationDurations=report[key])})),qualityLimitationDurations&&(obj[mediaType].qualityLimitationDurations=qualityLimitationDurations[obj[mediaType].qualityLimitationReason])},processScreenStream=function(stream,resolve){connection.getSenders().forEach((function(sender){if("audio"!==sender.track.kind){currentAudioTrack=localVideo.srcObject.getAudioTracks()[0],currentVideoTrack=localVideo.srcObject.getVideoTracks()[0];var newVideoTrack=stream.getVideoTracks()[0];newVideoTrack.enabled=currentVideoTrack.enabled,sender.replaceTrack(newVideoTrack),localVideo.srcObject=stream,stream.getAudioTracks()[0]?(systemSoundTrack=stream.getAudioTracks()[0],connection.getSenders().forEach((function(sender){if("video"!==sender.track.kind){var mixedTrack=mixAudioTracks(stream,new MediaStream([sender.track]));mixedTrack.enabled=currentAudioTrack.enabled,sender.replaceTrack(mixedTrack),localVideo.srcObject.removeTrack(stream.getAudioTracks()[0]),localVideo.srcObject.addTrack(mixedTrack),currentAudioTrack.enabled=!0}}))):localVideo.srcObject.addTrack(currentAudioTrack)}})),logger.info("webrtc","Switch to screen"),screenShare=!0,resolve()},updateVideoSettings=function(settings){return new Promise((function(resolve,reject){connection&&settings&&connection.getSenders().forEach((function(sender){if("video"==sender.track.kind){for(var parameters=sender.getParameters(),i=0;i<parameters.encodings.length;i++)settings.maxBitrate?parameters.encodings[i].maxBitrate=1e3*settings.maxBitrate:parameters.encodings[i].maxBitrate&&delete parameters.encodings[i].maxBitrate,settings.frameRate&&(parameters.encodings[i].maxFramerate=settings.frameRate),settings.scaleResolutionDownBy&&(parameters.encodings[i].scaleResolutionDownBy=settings.scaleResolutionDownBy);sender.setParameters(parameters).then((function(){logger.info("webrtc","Set video encoder parameters to "+JSON.stringify(parameters.encodings)),resolve(parameters.encodings)})).catch((function(reason){logger.error("webrtc",reason),reject(reason)}))}}))}))},fireUnmuteEvent=function(){unmuteRequiredEvent&&"function"==typeof unmuteRequiredEvent&&unmuteRequiredEvent()},setZoom=function(){var _ref2=_asyncToGenerator(_regenerator().m((function _callee2(value){var _localVideo$srcObject3,_localVideo$srcObject4,track;return _regenerator().w((function(_context2){for(;;)switch(_context2.n){case 0:if(!zoom){_context2.n=6;break}if(!(value>=zoom.min&&value<=zoom.max)){_context2.n=4;break}if(!localVideo||!localVideo.srcObject){_context2.n=2;break}return _localVideo$srcObject3=localVideo.srcObject.getVideoTracks(),_localVideo$srcObject4=_slicedToArray(_localVideo$srcObject3,1),track=_localVideo$srcObject4[0],_context2.n=1,track.applyConstraints({advanced:[{zoom:value}]});case 1:zoom.value=value,_context2.n=3;break;case 2:logger.warn("webrtc","Can't set zoom value: no local video");case 3:_context2.n=5;break;case 4:logger.info("webrtc","Zoom value "+value+"is out of range: "+zoom.min+"-"+zoom.max);case 5:_context2.n=7;break;case 6:logger.info("webrtc","Zoom is not supported or zoom capabilities unknown yet");case 7:return _context2.a(2)}}),_callee2)})));return function(_x3){return _ref2.apply(this,arguments)}}(),getWebRTCStats=function(){return new Promise((function(resolve,reject){var browser=browserDetails.browser;connection&&validBrowsers.includes(browser)?connection.getStats(null).then((function(stats){var statObject={};stats&&stats.forEach((function(report){report&&(void 0===statObject[report.type]&&(statObject[report.type]=[]),statObject[report.type].push(report))})),resolve(statObject)})).catch((function(reason){logger.error("webrtc",reason),reject(reason)})):reject(constants.ERROR_INFO.CAN_NOT_GET_STATS)}))},exports={state:function(){return connection.signalingState},createOffer:function(options){return new Promise((function(resolve,reject){var hasAudio=!0,hasVideo=!0;localVideo?(localVideo.srcObject.getAudioTracks()[0]||(hasAudio=!1),localVideo.srcObject.getVideoTracks()[0]||(hasVideo=!1,options.receiveVideo=!1)):"safari"!=browserDetails.browser||connection.getTransceivers().length||(options.receiveAudio&&connection.addTransceiver("audio",{direction:"recvonly"}),options.receiveVideo&&connection.addTransceiver("video",{direction:"recvonly"}));var constraints={offerToReceiveAudio:options.receiveAudio?1:0,offerToReceiveVideo:options.receiveVideo?1:0};connection.createOffer(constraints).then((function(offer){options.stereo&&(offer.sdp=offer.sdp.replace("minptime=10","minptime=10;stereo=1;sprop-stereo=1")),connection.setLocalDescription(offer).then((function(){var o={};o.sdp=util.stripCodecs(offer.sdp,options.stripCodecs),o.hasAudio=hasAudio,o.hasVideo=hasVideo,resolve(o)}))}))}))},createAnswer:function(options){return new Promise((function(resolve,reject){connection.createAnswer().then((function(answer){connection.setLocalDescription(answer).then((function(){resolve(util.stripCodecs(answer.sdp,options.stripCodecs))}))}))}))},setRemoteSdp:function(sdp){return logger.debug("webrtc","setRemoteSDP:"),logger.debug("webrtc",sdp),new Promise((function(resolve,reject){var sdpType;sdpType="have-local-offer"==connection.signalingState?"answer":"offer";var rtcSdp=new RTCSessionDescription({type:sdpType,sdp:sdp});connection.setRemoteDescription(rtcSdp).then((function(){browserDetails.browser,resolve()})).catch((function(error){reject(error)}))}))},changeAudioCodec:function(codec){return!1},close:function(cacheCamera){remoteVideo&&(removeVideoElement(remoteVideo),options.remoteVideo||(remoteVideo.id=remoteVideo.id+"-REMOTE_CACHED_VIDEO"),remoteVideo=null),localVideo&&!getCacheInstance(localDisplay||display)&&cacheCamera?(localVideo.id=localVideo.id+"-LOCAL_CACHED_VIDEO",unmuteAudio(),unmuteVideo(),localVideo=null):localVideo&&(localVideo.id=localVideo.id+"-LOCAL_CACHED_VIDEO",removeVideoElement(localVideo),localVideo=null),"closed"!==connection.signalingState&&connection.close(),delete connections[id]},setAudioOutputId:function(id){if(remoteVideo){if("edge"==browserDetails.browser){var srcObject=remoteVideo.srcObject;remoteVideo.srcObject=null;var res=remoteVideo.setSinkId(id);return remoteVideo.srcObject=srcObject,res}return remoteVideo.setSinkId(id)}},setVolume:function(volume){remoteVideo&&remoteVideo.srcObject&&remoteVideo.srcObject.getAudioTracks().length>0&&(remoteVideo.volume=volume/100)},unmuteRemoteAudio:function(){remoteVideo&&remoteVideo.srcObject&&remoteVideo.srcObject.getAudioTracks().length>0&&(remoteVideo.muted=!1)},muteRemoteAudio:function(){remoteVideo&&remoteVideo.srcObject&&remoteVideo.srcObject.getAudioTracks().length>0&&(remoteVideo.muted=!0)},isRemoteAudioMuted:function(){return!(remoteVideo&&remoteVideo.srcObject&&remoteVideo.srcObject.getAudioTracks().length>0)||remoteVideo.muted},setMicrophoneGain:function(volume){microphoneGain&&(microphoneGain.gain.value=volume/100)},getVolume:function(){return remoteVideo&&remoteVideo.srcObject&&remoteVideo.srcObject.getAudioTracks().length>0?100*remoteVideo.volume:-1},muteAudio:function(){localVideo&&localVideo.srcObject&&localVideo.srcObject.getAudioTracks().length>0&&(localVideo.srcObject.getAudioTracks()[0].enabled=!1)}};exports.unmuteAudio=unmuteAudio,exports.isAudioMuted=function(){return!(localVideo&&localVideo.srcObject&&localVideo.srcObject.getAudioTracks().length>0)||!localVideo.srcObject.getAudioTracks()[0].enabled},exports.muteVideo=function(){localVideo&&localVideo.srcObject&&localVideo.srcObject.getVideoTracks().length>0&&(localVideo.srcObject.getVideoTracks()[0].enabled=!1)},exports.unmuteVideo=unmuteVideo,exports.isVideoMuted=function(){return!(localVideo&&localVideo.srcObject&&localVideo.srcObject.getVideoTracks().length>0)||!localVideo.srcObject.getVideoTracks()[0].enabled},exports.getStats=getStat,exports.fullScreen=function(){var video=document.getElementById(id);if(video)if(document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.msFullscreenElement)document.exitFullscreen?document.exitFullscreen():document.msExitFullscreen?document.msExitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitExitFullscreen&&document.webkitExitFullscreen();else if(video.requestFullscreen){var result=video.requestFullscreen();util.isPromise(result)&&result.catch((function(e){logger.debug("webrtc",e)}))}else if(video.msRequestFullscreen)video.msRequestFullscreen();else if(video.mozRequestFullScreen)video.mozRequestFullScreen();else if(video.webkitRequestFullscreen)video.webkitRequestFullscreen();else if(video.webkitEnterFullscreen){video.webkitEnterFullscreen();var needRestart=!1;video.addEventListener("pause",(function(){needRestart&&(video.play(),needRestart=!1)})),video.addEventListener("webkitendfullscreen",(function(){video.play(),needRestart=!0}))}},exports.switchCam=function(deviceId){return new Promise((function(resolve,reject){localVideo&&localVideo.srcObject&&videoCams.length>1&&!customStream&&!screenShare?connection.getSenders().forEach((function(sender){if("audio"!==sender.track.kind){var cameraId;sender.track.stop(),"undefined"!=typeof deviceId?(videoCams.forEach((function(cam,index){deviceId===cam.id&&(switchCamIndex=index)})),cameraId=deviceId):(switchCamIndex=(switchCamIndex+1)%videoCams.length,cameraId=videoCams[switchCamIndex].id),cameraId||(logger.error("webrtc","Can't detect camera to switch to"),reject(constants.ERROR_INFO.CAN_NOT_SWITCH_CAM));var clonedConstraints=Object.assign({},constraints);clonedConstraints.video.deviceId={exact:cameraId},clonedConstraints.audio=!1,navigator.mediaDevices.getUserMedia(clonedConstraints).then((function(newStream){var newVideoTrack=newStream.getVideoTracks()[0];newVideoTrack.enabled=localVideo.srcObject.getVideoTracks()[0].enabled;var audioTrack=localVideo.srcObject.getAudioTracks()[0];sender.replaceTrack(newVideoTrack),localVideo.srcObject=newStream,0==localVideo.srcObject.getAudioTracks().length&&audioTrack&&localVideo.srcObject.addTrack(audioTrack),logger.info("webrtc","Switch camera to "+cameraId),resolve(cameraId)})).catch((function(reason){logger.error("webrtc",reason),reject(reason)}))}})):reject(constants.ERROR_INFO.CAN_NOT_SWITCH_CAM)}))},exports.switchMic=function(deviceId){return new Promise((function(resolve,reject){localVideo&&localVideo.srcObject&&mics.length>1&&!customStream?connection.getSenders().forEach((function(sender){if("video"!==sender.track.kind){switchMicCount=(switchMicCount+1)%mics.length,sender.track.stop(),microphoneGain&µphoneGain.release();var mic="undefined"!=typeof deviceId?deviceId:mics[switchMicCount].id,clonedConstraints=Object.assign({},constraints);clonedConstraints.audio.deviceId={exact:mic},clonedConstraints.video=!1,navigator.mediaDevices.getUserMedia(clonedConstraints).then((function(newStream){if(microphoneGain){var currentGain=microphoneGain.gain.value;(microphoneGain=createGainNode(newStream)).gain.value=currentGain}var newAudioTrack=newStream.getAudioTracks()[0];newAudioTrack.enabled=localVideo.srcObject.getAudioTracks()[0].enabled,currentAudioTrack=newAudioTrack;var videoTrack=localVideo.srcObject.getVideoTracks()[0];if(systemSoundTrack){var mixedTrack=mixAudioTracks(new MediaStream([newAudioTrack]),new MediaStream([systemSoundTrack]));mixedTrack.enabled=newAudioTrack.enabled,sender.replaceTrack(mixedTrack),localVideo.srcObject=new MediaStream([mixedTrack])}else sender.replaceTrack(newAudioTrack),localVideo.srcObject=newStream;videoTrack&&localVideo.srcObject.addTrack(videoTrack),logger.info("webrtc","Switch mic to "+mic),resolve(mic)})).catch((function(reason){logger.error("webrtc",reason),reject(reason)}))}})):reject(constants.ERROR_INFO.CAN_NOT_SWITCH_MIC)}))},exports.switchToScreen=function(source,woExtension){return new Promise((function(resolve,reject){if(!screenShare){var clonedConstraints={video:Object.assign({},constraints.video),audio:Object.assign({},constraints.audio)};if("firefox"===browserDetails.browser&&(clonedConstraints.video.mediaSource=source),woExtension)return void getScreenDeviceIdWoExtension(clonedConstraints).then((function(screenSharingConstraints){navigator.mediaDevices.getDisplayMedia(screenSharingConstraints).then((function(stream){processScreenStream(stream,resolve)})).catch(reject)}));getScreenDeviceId(clonedConstraints).then((function(screenSharingConstraints){clonedConstraints.sourceId=screenSharingConstraints.sourceId,screenSharingConstraints.audioMandatory?clonedConstraints.audio={mandatory:screenSharingConstraints.audioMandatory,optional:[]}:delete clonedConstraints.audio,"firefox"==browserDetails.browser?clonedConstraints.video=screenSharingConstraints:"chrome"==browserDetails.browser&&(delete clonedConstraints.video,clonedConstraints.video={mandatory:screenSharingConstraints.mandatory}),navigator.mediaDevices.getUserMedia(clonedConstraints).then((function(stream){processScreenStream(stream,resolve)})).catch((function(reason){logger.error(reason),reject(reason)}))})).catch((function(reason){logger.error(reason),reject(reason)}))}}))},exports.switchToCam=function(){screenShare&&connection.getSenders().forEach((function(sender){"audio"!==sender.track.kind&&(currentVideoTrack.enabled=sender.track.enabled,sender.track.stop(),localVideo.srcObject=new MediaStream([currentVideoTrack]),sender.replaceTrack(currentVideoTrack),currentAudioTrack&&connection.getSenders().forEach((function(sender){"video"!==sender.track.kind&&(systemSoundTrack&&(currentAudioTrack.enabled=sender.track.enabled,sender.track.stop(),systemSoundTrack.stop(),systemSoundTrack=null,sender.replaceTrack(currentAudioTrack)),localVideo.srcObject.addTrack(currentAudioTrack))})))})),logger.info("webrtc","Switch to cam"),screenShare=!1},exports.setPublishingBitrate=function(minBitrate,maxBitrate){updateVideoSettings({maxBitrate:maxBitrate})},exports.updateVideoSettings=updateVideoSettings,exports.updateVideoResolution=function(resolution){return new Promise((function(resolve,reject){connection&&localVideo&&localVideo.srcObject&&!customStream&&resolution?connection.getSenders().forEach((function(sender){if("audio"!==sender.track.kind){sender.track.stop();var clonedConstraints=Object.assign({},constraints);resolution.width&&(clonedConstraints.video.width={ideal:resolution.width}),resolution.height&&(clonedConstraints.video.height={ideal:resolution.height}),clonedConstraints.audio=!1,navigator.mediaDevices.getUserMedia(clonedConstraints).then((function(newStream){var newVideoTrack=newStream.getVideoTracks()[0];newVideoTrack.enabled=localVideo.srcObject.getVideoTracks()[0].enabled;var audioTrack=localVideo.srcObject.getAudioTracks()[0];sender.replaceTrack(newVideoTrack),localVideo.srcObject=newStream,0==localVideo.srcObject.getAudioTracks().length&&audioTrack&&localVideo.srcObject.addTrack(audioTrack),logger.info("webrtc","Set video constraints to "+JSON.stringify(clonedConstraints.video)),resolve(clonedConstraints.video)})).catch((function(reason){logger.error("webrtc",reason),reject(reason)}))}})):reject(constants.ERROR_INFO.CAN_NOT_SET_RESOLUTION)}))},exports.getZoomCapabilities=function(){if(localVideo&&localVideo.srcObject)if(constraints.video&&constraints.video.zoom){var track=_slicedToArray(localVideo.srcObject.getVideoTracks(),1)[0],capabilities=track.getCapabilities(),settings=track.getSettings();"zoom"in settings?zoom={min:capabilities.zoom.min,max:capabilities.zoom.max,step:capabilities.zoom.step,value:settings.zoom}:(logger.info("webrtc","Zoom is not supported by "+track.label),zoom=null)}else zoom=null;return zoom},exports.setZoom=setZoom,exports.getZoom=function(){return zoom?zoom.value:-1},exports.getWebRTCStats=getWebRTCStats,exports.getRTCPeerConnection=function(){return connection},connections[id]=exports,resolve(exports)}))},getMediaAccess:function(constraints,display,disableConstraintsNormalization,useCanvas){return new Promise((function(resolve,reject){constraints||(constraints=defaultConstraints),disableConstraintsNormalization||(constraints=function(constraints){var customStream=constraints.customStream;if((constraints=JSON.parse(JSON.stringify(constraints))).customStream=customStream,constraints.video&&(!0===constraints.video&&(constraints.video={}),"object"===_typeof(constraints.video))){var width=constraints.video.width,height=constraints.video.height;if("safari"==browserDetails.browser?width&&height?"object"===_typeof(width)&&"object"===_typeof(height)||(constraints.video.width={min:width,max:width},constraints.video.height={min:height,max:height}):(constraints.video.width={min:320,max:640},constraints.video.height={min:180,max:360}):(isNaN(width)||0===width||isNaN(height)||0===height)&&(constraints.video.width=320,constraints.video.height=240),"chrome"===browserDetails.browser&&browserDetails.version>=134);else{var frameRate=constraints.video.frameRate&&0!=constraints.video.frameRate?constraints.video.frameRate:30;constraints.video.frameRate={ideal:frameRate}}}constraints.audio&&constraints.audio.stereo&&(constraints.audio.echoCancellation=!1,constraints.audio.googEchoCancellation=!1);return constraints}(constraints));var cacheInstance=getCacheInstance(display);if(cacheInstance&&cacheInstance.srcObject&&JSON.stringify(display.mediaTrackConstraints)==JSON.stringify(constraints)&&!constraints.customStream)resolve(display);else if(display.mediaTrackConstraints=constraints,releaseMedia(display),constraints.video||constraints.audio||constraints.customStream)if(constraints.video&&constraints.video.type&&"screen"==constraints.video.type){if(delete constraints.video.type,screenCaptureSupportedBrowsers()&&constraints.video.withoutExtension)return void getScreenDeviceIdWoExtension(constraints).then((function(screenSharingConstraints){!function(constraints,requestAudioConstraints){navigator.mediaDevices.getDisplayMedia(constraints).then((function(stream){loadVideo(display,stream,!0,requestAudioConstraints,resolve,constraints)})).catch(reject)}(screenSharingConstraints,constraints.audio)}));var requestAudioConstraints=null;getScreenDeviceId(constraints).then((function(screenSharingConstraints){for(var prop in constraints.sourceId=screenSharingConstraints.sourceId,requestAudioConstraints=constraints.audio,screenSharingConstraints.audioMandatory?constraints.audio={mandatory:screenSharingConstraints.audioMandatory,optional:[]}:window.chrome&&(constraints.audio=!1),delete screenSharingConstraints.audioMandatory,delete screenSharingConstraints.sourceId,screenSharingConstraints)screenSharingConstraints.hasOwnProperty(prop)&&(constraints.video[prop]=screenSharingConstraints[prop]);"chrome"==browserDetails.browser&&(delete constraints.video.frameRate,delete constraints.video.height,delete constraints.video.width,delete constraints.systemSound),getAccess(constraints,!0,requestAudioConstraints)}),reject)}else getAccess(constraints);else resolve(display);function getAccess(constraints,screenShare,requestAudioConstraints){if(logger.info("webrtc",constraints),constraints.customStream)if(constraints.audio||constraints.video){var normalizedConstraints={audio:!!constraints.audio&&constraints.audio,video:!!constraints.video&&constraints.video};navigator.getUserMedia(normalizedConstraints,(function(stream){stream.getTracks().forEach((function(track){constraints.customStream.addTrack(track)})),loadVideo(display,constraints.customStream,screenShare,requestAudioConstraints,resolve,constraints)}),reject)}else loadVideo(display,constraints.customStream,screenShare,requestAudioConstraints,resolve,constraints);else listDevices(!1).then((function(devices){devices.video.forEach((function(device){videoCams.find((function(cam){return device.id===cam.id}))||videoCams.push(device)})),devices.audio.forEach((function(device){mics.find((function(mic){return device.id===mic.id}))||mics.push(device)})),navigator.getUserMedia(constraints,(function(stream){loadVideo(display,stream,screenShare,requestAudioConstraints,resolve,constraints,useCanvas)}),reject)}),reject)}}))},releaseMedia:releaseMedia,listDevices:listDevices,getMobileDevices:getMobileDevices,playFirstSound:function(){if(audioContext){for(var buffer=audioContext.createBuffer(1,441,44100),output=buffer.getChannelData(0),i=0;i<output.length;i++)output[i]=0;var source=audioContext.createBufferSource();return source.buffer=buffer,source.connect(audioContext.destination),source.start?source.start(0):source.play?source.play(0):source.noteOn&&source.noteOn(0),!0}return!1},playFirstVideo:function(display,isLocal,src){var useControls=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return new Promise((function(resolve,reject){if(!getCacheInstance(display)){var video=createVideoElement(useControls);if(video.muted=!0,video.id=uuid_v1()+(isLocal?"-LOCAL_CACHED_VIDEO":"-REMOTE_CACHED_VIDEO"),src)return video.src=src,void video.play().then((function(){display.appendChild(video),video.removeAttribute("src"),resolve()})).catch((function(){logger.info("webrtc","Autoplay detected! Trying to play a video with a muted sound..."),video.muted=!0,video.play().then((function(){display.appendChild(video),video.removeAttribute("src"),resolve()})),video.onsuspend=function(event){reject()}}))}resolve()}))},available:function(){return"getUserMedia"in navigator&&"RTCPeerConnection"in window},configure:function(configuration){extensionId=configuration.extensionId,defaultConstraints=configuration.constraints,audioContext=configuration.audioContext,logger=configuration.logger,createMicGainNode="undefined"==typeof configuration.createMicGainNode||configuration.createMicGainNode,logger.info("webrtc","Initialized")},videoCams:videoCams,mics:mics,getAudioSourceDevice:function(){return audioSourceDevice},getCacheInstance:getCacheInstance,getVideoElement:function getVideoElement(display){if(display){var _step,_iterator=function(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=_unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var _n=0,F=function(){};return{s:F,n:function(){return _n>=r.length?{done:!0}:{done:!1,value:r[_n++]}},e:function(r){throw r},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,u=!1;return{s:function(){t=t.call(r)},n:function(){var r=t.next();return a=r.done,r},e:function(r){u=!0,o=r},f:function(){try{a||null==t.return||t.return()}finally{if(u)throw o}}}}(display.children);try{for(_iterator.s();!(_step=_iterator.n()).done;){var child=_step.value;if("video"===child.tagName.toLowerCase())return child;var grandchild=getVideoElement(child);if(grandchild)return grandchild}}catch(err){_iterator.e(err)}finally{_iterator.f()}}return null}}},{"./constants":72,"./util":74,uuid:41,"webrtc-adapter":56}]},{},[73])(73)}));
|