@hzkj/voicenine 1.4.6 → 1.4.8

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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # HANZI VOICENINE
2
2
 
3
- ## VERSION 1.4.2
3
+ ## VERSION 1.4.8
4
4
 
5
5
  ## 引入
6
6
 
package/lib/main.js CHANGED
@@ -1 +1 @@
1
- const e={LOGIN:"LOGIN",LOGOUT:"LOGOUT",READY:"READY",NOT_READY:"NOT_READY",WORK_NOT_READY:"WORK_NOT_READY",AFTER:"AFTER",OUT_CALL:"OUT_CALL",OUT_CALLER_RING:"OUT_CALLER_RING",OUT_CALLED_RING:"OUT_CALLED_RING",PLAY_AGENT_ID:"PLAY_AGENT_ID",TALKING:"TALKING",MUTE_TALKING:"MUTE_TALKING",HOLD_TALKING:"HOLD_TALKING",INNER_CALL_RING:"INNER_CALL_RING",INNER_CALL_TALKING:"INNER_CALL_TALKING",INBOUND_RING:"INBOUND_RING",TRANSFER:"TRANSFER",TRANSFERED_RING:"TRANSFERED_RING",TRANSFER_OUT_RING:"TRANSFER_OUT_RING",TRANSFERED_TALKING:"TRANSFERED_TALKING",CONSULT:"CONSULT",CONSULT_RING:"CONSULT_RING",CONSULT_OUT_RING:"CONSULT_OUT_RING",CONSULT_IVR:"CONSULT_IVR",CONSULT_TALKING:"CONSULT_TALKING",CONSULTED_TALKING:"CONSULTED_TALKING",CONFERENCE_TALKING:"CONFERENCE_TALKING"},t={ready:"READY",busy:"NOT_READY",busy_work:"WORK_NOT_READY",login:"LOGIN",logout:"LOGOUT",call:"MAKE_CALL",hangup:"HANGUP_CALL",answer:"ANSWER",hold:"HOLD",hold_cancel:"HOLD_CANCEL",mute:"MUTE",mute_cancel:"MUTE_CANCEL",transfer:"TRANSFER",transfer_cancel:"TRANSFER_CANCEL",consult:"CONSULT",consult_party:"CONSULT_PARTY",consult_transfer:"CONSULT_TRANSFER",consult_cancel:"CONSULT_CANCEL",consult_stop:"CONSULT_STOP",conference_remove:"CONFERENCE_REMOVE",followdata:"FOLLOWDATA"},n={[e.LOGIN]:"已登录",[e.LOGOUT]:"已退出",[e.READY]:"空闲",[e.NOT_READY]:"忙碌",[e.WORK_NOT_READY]:"自定义忙碌",[e.AFTER]:"话后",[e.OUT_CALL]:"外呼中",[e.OUT_CALLER_RING]:"外呼主叫振铃",[e.OUT_CALLED_RING]:"外呼被叫振铃",[e.PLAY_AGENT_ID]:"播放坐席工号",[e.TALKING]:"通话中",[e.MUTE_TALKING]:"静音中",[e.HOLD_TALKING]:"保持中",[e.INNER_CALL_RING]:"内呼来电振铃",[e.INNER_CALL_TALKING]:"内呼通话中",[e.INBOUND_RING]:"来电振铃",[e.TRANSFER]:"转接中",[e.TRANSFERED_RING]:"转接来电振铃",[e.TRANSFER_OUT_RING]:"转接外呼振铃",[e.TRANSFERED_TALKING]:"转接来电通话中",[e.CONSULT]:"咨询中",[e.CONSULT_RING]:"咨询来电振铃",[e.CONSULT_OUT_RING]:"咨询外呼振铃",[e.CONSULT_IVR]:"咨询IVR",[e.CONSULT_TALKING]:"咨询通话中",[e.CONSULTED_TALKING]:"来电咨询中",[e.CONFERENCE_TALKING]:"多方通话"},r={[e.LOGIN]:[t.call],[e.LOGOUT]:[],[e.READY]:[t.call],[e.NOT_READY]:[t.call],[e.WORK_NOT_READY]:[t.call],[e.AFTER]:[t.call],[e.OUT_CALL]:[t.hangup],[e.OUT_CALLER_RING]:[t.answer,t.hangup],[e.OUT_CALLED_RING]:[t.hangup],[e.PLAY_AGENT_ID]:[t.hangup],[e.TALKING]:[t.hangup,t.hold,t.mute,t.transfer,t.consult],[e.MUTE_TALKING]:[t.mute_cancel],[e.HOLD_TALKING]:[t.hold_cancel],[e.INNER_CALL_RING]:[t.hangup,t.answer],[e.INNER_CALL_TALKING]:[t.hangup,t.mute],[e.INBOUND_RING]:[t.hangup,t.answer],[e.TRANSFER]:[t.transfer_cancel],[e.TRANSFERED_RING]:[t.hangup,t.answer],[e.TRANSFER_OUT_RING]:[t.transfer_cancel],[e.TRANSFERED_TALKING]:[t.hangup,t.mute,t.transfer,t.consult],[e.CONSULT]:[t.consult_cancel],[e.CONSULT_RING]:[t.hangup,t.answer],[e.CONSULT_OUT_RING]:[t.consult_cancel],[e.CONSULT_IVR]:[t.hangup,t.consult_cancel],[e.CONSULT_TALKING]:[t.hangup,t.mute,t.consult_party,t.consult_transfer],[e.CONSULTED_TALKING]:[t.hangup,t.mute],[e.CONFERENCE_TALKING]:[t.hangup,t.mute,t.consult]};!function(e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).adapter=e()}(function(){return function e(t,n,r){function o(a,s){if(!n[a]){if(!t[a]){var c="function"==typeof require&&require;if(!s&&c)return c(a,!0);if(i)return i(a,!0);throw(c=new Error("Cannot find module '"+a+"'")).code="MODULE_NOT_FOUND",c}c=n[a]={exports:{}},t[a][0].call(c.exports,function(e){return o(t[a][1][e]||e)},c,c.exports,e,t,n,r)}return n[a].exports}for(var i="function"==typeof require&&require,a=0;a<r.length;a++)o(r[a]);return o}({1:[function(e,t,n){e=(0,e("./adapter_factory.js").adapterFactory)({window:"undefined"==typeof window?void 0:window}),t.exports=e},{"./adapter_factory.js":2}],2:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0}),n.adapterFactory=function(){var e=(0<arguments.length&&void 0!==arguments[0]?arguments[0]:{}).window,t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0},n=r.log,d=r.detectBrowser(e),l={browserDetails:d,commonShim:s,extractVersion:r.extractVersion,disableLog:r.disableLog,disableWarnings:r.disableWarnings,sdp:c};switch(d.browser){case"chrome":if(!o||!o.shimPeerConnection||!t.shimChrome)return n("Chrome shim is not included in this adapter release."),l;if(null===d.version)return n("Chrome shim can not determine version, not shimming."),l;n("adapter.js shimming chrome."),l.browserShim=o,s.shimAddIceCandidateNullOrEmpty(e,d),s.shimParameterlessSetLocalDescription(e,d),o.shimGetUserMedia(e,d),o.shimMediaStream(e,d),o.shimPeerConnection(e,d),o.shimOnTrack(e,d),o.shimAddTrackRemoveTrack(e,d),o.shimGetSendersWithDtmf(e,d),o.shimGetStats(e,d),o.shimSenderReceiverGetStats(e,d),o.fixNegotiationNeeded(e,d),s.shimRTCIceCandidate(e,d),s.shimConnectionState(e,d),s.shimMaxMessageSize(e,d),s.shimSendThrowTypeError(e,d),s.removeExtmapAllowMixed(e,d);break;case"firefox":if(!i||!i.shimPeerConnection||!t.shimFirefox)return n("Firefox shim is not included in this adapter release."),l;n("adapter.js shimming firefox."),l.browserShim=i,s.shimAddIceCandidateNullOrEmpty(e,d),s.shimParameterlessSetLocalDescription(e,d),i.shimGetUserMedia(e,d),i.shimPeerConnection(e,d),i.shimOnTrack(e,d),i.shimRemoveStream(e,d),i.shimSenderGetStats(e,d),i.shimReceiverGetStats(e,d),i.shimRTCDataChannel(e,d),i.shimAddTransceiver(e,d),i.shimGetParameters(e,d),i.shimCreateOffer(e,d),i.shimCreateAnswer(e,d),s.shimRTCIceCandidate(e,d),s.shimConnectionState(e,d),s.shimMaxMessageSize(e,d),s.shimSendThrowTypeError(e,d);break;case"safari":if(!a||!t.shimSafari)return n("Safari shim is not included in this adapter release."),l;n("adapter.js shimming safari."),l.browserShim=a,s.shimAddIceCandidateNullOrEmpty(e,d),s.shimParameterlessSetLocalDescription(e,d),a.shimRTCIceServerUrls(e,d),a.shimCreateOfferLegacy(e,d),a.shimCallbacksAPI(e,d),a.shimLocalStreamsAPI(e,d),a.shimRemoteStreamsAPI(e,d),a.shimTrackEventTransceiver(e,d),a.shimGetUserMedia(e,d),a.shimAudioContext(e,d),s.shimRTCIceCandidate(e,d),s.shimMaxMessageSize(e,d),s.shimSendThrowTypeError(e,d),s.removeExtmapAllowMixed(e,d);break;default:n("Unsupported browser!")}return l};var r=d(e("./utils")),o=d(e("./chrome/chrome_shim")),i=d(e("./firefox/firefox_shim")),a=d(e("./safari/safari_shim")),s=d(e("./common_shim")),c=d(e("sdp"));function d(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}},{"./chrome/chrome_shim":3,"./common_shim":6,"./firefox/firefox_shim":7,"./safari/safari_shim":10,"./utils":11,sdp:12}],3:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0}),n.shimGetDisplayMedia=n.shimGetUserMedia=void 0;var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},o=e("./getusermedia");Object.defineProperty(n,"shimGetUserMedia",{enumerable:!0,get:function(){return o.shimGetUserMedia}});var i=e("./getdisplaymedia");Object.defineProperty(n,"shimGetDisplayMedia",{enumerable:!0,get:function(){return i.shimGetDisplayMedia}}),n.shimMediaStream=function(e){e.MediaStream=e.MediaStream||e.webkitMediaStream},n.shimOnTrack=function(e){var t;"object"!==(void 0===e?"undefined":r(e))||!e.RTCPeerConnection||"ontrack"in e.RTCPeerConnection.prototype?a.wrapPeerConnectionEvent(e,"track",function(e){return e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e}):(Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get:function(){return this._ontrack},set:function(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0}),t=e.RTCPeerConnection.prototype.setRemoteDescription,e.RTCPeerConnection.prototype.setRemoteDescription=function(){var n=this;return this._ontrackpoly||(this._ontrackpoly=function(t){t.stream.addEventListener("addtrack",function(r){var o=e.RTCPeerConnection.prototype.getReceivers?n.getReceivers().find(function(e){return e.track&&e.track.id===r.track.id}):{track:r.track},i=new Event("track");i.track=r.track,i.receiver=o,i.transceiver={receiver:o},i.streams=[t.stream],n.dispatchEvent(i)}),t.stream.getTracks().forEach(function(r){var o=e.RTCPeerConnection.prototype.getReceivers?n.getReceivers().find(function(e){return e.track&&e.track.id===r.id}):{track:r},i=new Event("track");i.track=r,i.receiver=o,i.transceiver={receiver:o},i.streams=[t.stream],n.dispatchEvent(i)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)})},n.shimGetSendersWithDtmf=function(e){var t,n,o,i,a,s;"object"===(void 0===e?"undefined":r(e))&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype?(t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}},e.RTCPeerConnection.prototype.getSenders||(e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()},n=e.RTCPeerConnection.prototype.addTrack,e.RTCPeerConnection.prototype.addTrack=function(e,r){var o=n.apply(this,arguments);return o||(o=t(this,e),this._senders.push(o)),o},o=e.RTCPeerConnection.prototype.removeTrack,e.RTCPeerConnection.prototype.removeTrack=function(e){o.apply(this,arguments),-1!==(e=this._senders.indexOf(e))&&this._senders.splice(e,1)}),i=e.RTCPeerConnection.prototype.addStream,e.RTCPeerConnection.prototype.addStream=function(e){var n=this;this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach(function(e){n._senders.push(t(n,e))})},a=e.RTCPeerConnection.prototype.removeStream,e.RTCPeerConnection.prototype.removeStream=function(e){var t=this;this._senders=this._senders||[],a.apply(this,[e]),e.getTracks().forEach(function(e){var n=t._senders.find(function(t){return t.track===e});n&&t._senders.splice(t._senders.indexOf(n),1)})}):"object"===(void 0===e?"undefined":r(e))&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)&&(s=e.RTCPeerConnection.prototype.getSenders,e.RTCPeerConnection.prototype.getSenders=function(){var e=this,t=s.apply(this,[]);return t.forEach(function(t){return t._pc=e}),t},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get:function(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}}))},n.shimGetStats=function(e){var t;e.RTCPeerConnection&&(t=e.RTCPeerConnection.prototype.getStats,e.RTCPeerConnection.prototype.getStats=function(){var e=this,n=(o=Array.prototype.slice.call(arguments))[0],r=o[1],o=o[2];if(0<arguments.length&&"function"==typeof n)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof n))return t.apply(this,[]);var i=function(e){var t={};return e.result().forEach(function(e){var n={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach(function(t){n[t]=e.stat(t)}),t[n.id]=n}),t},a=function(e){return new Map(Object.keys(e).map(function(t){return[t,e[t]]}))};return 2<=arguments.length?t.apply(this,[function(e){r(a(i(e)))},n]):new Promise(function(n,r){t.apply(e,[function(e){n(a(i(e)))},r])}).then(r,o)})},n.shimSenderReceiverGetStats=function(e){var t,n,o,i;"object"===(void 0===e?"undefined":r(e))&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver&&("getStats"in e.RTCRtpSender.prototype||((t=e.RTCPeerConnection.prototype.getSenders)&&(e.RTCPeerConnection.prototype.getSenders=function(){var e=this,n=t.apply(this,[]);return n.forEach(function(t){return t._pc=e}),n}),(n=e.RTCPeerConnection.prototype.addTrack)&&(e.RTCPeerConnection.prototype.addTrack=function(){var e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){var e=this;return this._pc.getStats().then(function(t){return a.filterStats(t,e.track,!0)})}),"getStats"in e.RTCRtpReceiver.prototype||((o=e.RTCPeerConnection.prototype.getReceivers)&&(e.RTCPeerConnection.prototype.getReceivers=function(){var e=this,t=o.apply(this,[]);return t.forEach(function(t){return t._pc=e}),t}),a.wrapPeerConnectionEvent(e,"track",function(e){return e.receiver._pc=e.srcElement,e}),e.RTCRtpReceiver.prototype.getStats=function(){var e=this;return this._pc.getStats().then(function(t){return a.filterStats(t,e.track,!1)})}),"getStats"in e.RTCRtpSender.prototype&&"getStats"in e.RTCRtpReceiver.prototype&&(i=e.RTCPeerConnection.prototype.getStats,e.RTCPeerConnection.prototype.getStats=function(){if(0<arguments.length&&arguments[0]instanceof e.MediaStreamTrack){var t=arguments[0],n=void 0,r=void 0,o=void 0;return this.getSenders().forEach(function(e){e.track===t&&(n?o=!0:n=e)}),this.getReceivers().forEach(function(e){return e.track===t&&(r?o=!0:r=e),e.track===t}),o||n&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):n?n.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return i.apply(this,arguments)}))},n.shimAddTrackRemoveTrackWithNative=c,n.shimAddTrackRemoveTrack=function(e,t){if(e.RTCPeerConnection){if(e.RTCPeerConnection.prototype.addTrack&&65<=t.version)return c(e);var n=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){var e=this,t=n.apply(this);return this._reverseStreams=this._reverseStreams||{},t.map(function(t){return e._reverseStreams[t.id]})};var r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){var n,o=this;this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(function(e){if(o.getSenders().find(function(t){return t.track===e}))throw new DOMException("Track already exists.","InvalidAccessError")}),this._reverseStreams[t.id]||(n=new e.MediaStream(t.getTracks()),this._streams[t.id]=n,this._reverseStreams[n.id]=t,t=n),r.apply(this,[t])};var o=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},o.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[(this._streams[e.id]||e).id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,n){var r=this;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");var o=[].slice.call(arguments,1);if(1!==o.length||!o[0].getTracks().find(function(e){return e===t}))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(function(e){return e.track===t}))throw new DOMException("Track already exists.","InvalidAccessError");return this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},(o=this._streams[n.id])?(o.addTrack(t),Promise.resolve().then(function(){r.dispatchEvent(new Event("negotiationneeded"))})):(o=new e.MediaStream([t]),this._streams[n.id]=o,this._reverseStreams[o.id]=n,this.addStream(o)),this.getSenders().find(function(e){return e.track===t})},["createOffer","createAnswer"].forEach(function(t){var n=e.RTCPeerConnection.prototype[t],r=s({},t,function(){var e=this,t=arguments;return arguments.length&&"function"==typeof arguments[0]?n.apply(this,[function(n){n=d(e,n),t[0].apply(null,[n])},function(e){t[1]&&t[1].apply(null,e)},arguments[2]]):n.apply(this,arguments).then(function(t){return d(e,t)})});e.RTCPeerConnection.prototype[t]=r[t]});var i=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type&&(arguments[0]=(e=this,n=(t=arguments[0]).sdp,Object.keys(e._reverseStreams||[]).forEach(function(t){var r=e._reverseStreams[t];t=e._streams[r.id];n=n.replace(new RegExp(r.id,"g"),t.id)}),new RTCSessionDescription({type:t.type,sdp:n}))),i.apply(this,arguments);var e,t,n};var a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get:function(){var e=a.get.apply(this);return""===e.type?e:d(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){var t=this;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(e._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};var n=void 0;Object.keys(this._streams).forEach(function(r){t._streams[r].getTracks().find(function(t){return e.track===t})&&(n=t._streams[r])}),n&&(1===n.getTracks().length?this.removeStream(this._reverseStreams[n.id]):n.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function d(e,t){var n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(function(t){var r=e._reverseStreams[t];t=e._streams[r.id];n=n.replace(new RegExp(t.id,"g"),r.id)}),new RTCSessionDescription({type:t.type,sdp:n})}},n.shimPeerConnection=function(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){var n=e.RTCPeerConnection.prototype[t],r=s({},t,function(){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)});e.RTCPeerConnection.prototype[t]=r[t]})},n.fixNegotiationNeeded=function(e,t){a.wrapPeerConnectionEvent(e,"negotiationneeded",function(e){var n=e.target;if(!(t.version<72||n.getConfiguration&&"plan-b"===n.getConfiguration().sdpSemantics)||"stable"===n.signalingState)return e})};var a=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}(e("../utils.js"));function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function c(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){var e=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(function(t){return e._shimmedLocalStreams[t][0]})};var t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){if(!n)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var r=t.apply(this,arguments);return this._shimmedLocalStreams[n.id]?-1===this._shimmedLocalStreams[n.id].indexOf(r)&&this._shimmedLocalStreams[n.id].push(r):this._shimmedLocalStreams[n.id]=[n,r],r};var n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){var t=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(function(e){if(t.getSenders().find(function(t){return t.track===e}))throw new DOMException("Track already exists.","InvalidAccessError")});var r=this.getSenders();n.apply(this,arguments);var o=this.getSenders().filter(function(e){return-1===r.indexOf(e)});this._shimmedLocalStreams[e.id]=[e].concat(o)};var r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],r.apply(this,arguments)};var o=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){var t=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(function(n){var r=t._shimmedLocalStreams[n].indexOf(e);-1!==r&&t._shimmedLocalStreams[n].splice(r,1),1===t._shimmedLocalStreams[n].length&&delete t._shimmedLocalStreams[n]}),o.apply(this,arguments)}}},{"../utils.js":11,"./getdisplaymedia":4,"./getusermedia":5}],4:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0}),n.shimGetDisplayMedia=function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(n){return t(n).then(function(t){var r=n.video&&n.video.width,o=n.video&&n.video.height,i=n.video&&n.video.frameRate;return n.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:i||3}},r&&(n.video.mandatory.maxWidth=r),o&&(n.video.mandatory.maxHeight=o),e.navigator.mediaDevices.getUserMedia(n)})}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}},{}],5:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};n.shimGetUserMedia=function(e,t){var n,i,a,s,c=e&&e.navigator;c.mediaDevices&&(n=function(e){if("object"!==(void 0===e?"undefined":r(e))||e.mandatory||e.optional)return e;var t={};return Object.keys(e).forEach(function(n){var o,i,a;"require"!==n&&"advanced"!==n&&"mediaSource"!==n&&(void 0!==(o="object"===r(e[n])?e[n]:{ideal:e[n]}).exact&&"number"==typeof o.exact&&(o.min=o.max=o.exact),i=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t},void 0!==o.ideal&&(t.optional=t.optional||[],a={},"number"==typeof o.ideal?(a[i("min",n)]=o.ideal,t.optional.push(a),(a={})[i("max",n)]=o.ideal):a[i("",n)]=o.ideal,t.optional.push(a)),void 0!==o.exact&&"number"!=typeof o.exact?(t.mandatory=t.mandatory||{},t.mandatory[i("",n)]=o.exact):["min","max"].forEach(function(e){void 0!==o[e]&&(t.mandatory=t.mandatory||{},t.mandatory[i(e,n)]=o[e])}))}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},i=function(e,i){if(61<=t.version)return i(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"===r(e.audio)&&((s=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])})((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),s(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)),e&&"object"===r(e.video)){var a=(a=e.video.facingMode)&&("object"===(void 0===a?"undefined":r(a))?a:{ideal:a}),s=t.version<66;if(a&&("user"===a.exact||"environment"===a.exact||"user"===a.ideal||"environment"===a.ideal)&&(!c.mediaDevices.getSupportedConstraints||!c.mediaDevices.getSupportedConstraints().facingMode||s)){delete e.video.facingMode;var d=void 0;if("environment"===a.exact||"environment"===a.ideal?d=["back","rear"]:"user"!==a.exact&&"user"!==a.ideal||(d=["front"]),d)return c.mediaDevices.enumerateDevices().then(function(t){var r=(t=t.filter(function(e){return"videoinput"===e.kind})).find(function(e){return d.some(function(t){return e.label.toLowerCase().includes(t)})});return(r=!r&&t.length&&d.includes("back")?t[t.length-1]:r)&&(e.video.deviceId=a.exact?{exact:r.deviceId}:{ideal:r.deviceId}),e.video=n(e.video),o("chrome: "+JSON.stringify(e)),i(e)})}e.video=n(e.video)}return o("chrome: "+JSON.stringify(e)),i(e)},a=function(e){return 64<=t.version?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}}},c.getUserMedia=function(e,t,n){i(e,function(e){c.webkitGetUserMedia(e,t,function(e){n&&n(a(e))})})}.bind(c),c.mediaDevices.getUserMedia&&(s=c.mediaDevices.getUserMedia.bind(c.mediaDevices),c.mediaDevices.getUserMedia=function(e){return i(e,function(e){return s(e).then(function(t){if(e.audio&&!t.getAudioTracks().length||e.video&&!t.getVideoTracks().length)throw t.getTracks().forEach(function(e){e.stop()}),new DOMException("","NotFoundError");return t},function(e){return Promise.reject(a(e))})})}))};var o=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}(e("../utils.js")).log},{"../utils.js":11}],6:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};n.shimRTCIceCandidate=function(e){var t;!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype||(t=e.RTCIceCandidate,e.RTCIceCandidate=function(e){if("object"===(void 0===e?"undefined":r(e))&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substr(2)),e.candidate&&e.candidate.length){var n=new t(e),o=i.default.parseCandidate(e.candidate),a=Object.assign(n,o);return a.toJSON=function(){return{candidate:a.candidate,sdpMid:a.sdpMid,sdpMLineIndex:a.sdpMLineIndex,usernameFragment:a.usernameFragment}},a}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,a.wrapPeerConnectionEvent(e,"icecandidate",function(t){return t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t}))},n.shimMaxMessageSize=function(e,t){var n;e.RTCPeerConnection&&("sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get:function(){return void 0===this._sctp?null:this._sctp}}),n=e.RTCPeerConnection.prototype.setRemoteDescription,e.RTCPeerConnection.prototype.setRemoteDescription=function(){var e,r,o,a;return this._sctp=null,"chrome"===t.browser&&76<=t.version&&"plan-b"===this.getConfiguration().sdpSemantics&&Object.defineProperty(this,"sctp",{get:function(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0}),function(e){return!(!e||!e.sdp)&&((e=i.default.splitSections(e.sdp)).shift(),e.some(function(e){return(e=i.default.parseMLine(e))&&"application"===e.kind&&-1!==e.protocol.indexOf("SCTP")}))}(arguments[0])&&(r=function(e){return null===(e=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/))||e.length<2||(e=parseInt(e[1],10))!=e?-1:e}(arguments[0]),o=r,a=65536,a=a="firefox"===t.browser?t.version<57?-1===o?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637:a,r=function(e,n){var r=65536;return"firefox"===t.browser&&57===t.version&&(r=65535),0<(e=i.default.matchPrefix(e.sdp,"a=max-message-size:")).length?r=parseInt(e[0].substr(19),10):"firefox"===t.browser&&-1!==n&&(r=2147483637),r}(arguments[0],r),void 0,e=0===a&&0===r?Number.POSITIVE_INFINITY:0===a||0===r?Math.max(a,r):Math.min(a,r),r={},Object.defineProperty(r,"maxMessageSize",{get:function(){return e}}),this._sctp=r),n.apply(this,arguments)})},n.shimSendThrowTypeError=function(e){var t;function n(e,t){var n=e.send;e.send=function(){var r=(r=arguments[0]).length||r.size||r.byteLength;if("open"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return n.apply(e,arguments)}}e.RTCPeerConnection&&"createDataChannel"in e.RTCPeerConnection.prototype&&(t=e.RTCPeerConnection.prototype.createDataChannel,e.RTCPeerConnection.prototype.createDataChannel=function(){var e=t.apply(this,arguments);return n(e,this),e},a.wrapPeerConnectionEvent(e,"datachannel",function(e){return n(e.channel,e.target),e}))},n.shimConnectionState=function(e){var t;!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype||(t=e.RTCPeerConnection.prototype,Object.defineProperty(t,"connectionState",{get:function(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get:function(){return this._onconnectionstatechange||null},set:function(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(function(e){var n=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=function(e){var t,n=e.target;return n._lastConnectionState!==n.connectionState&&(n._lastConnectionState=n.connectionState,t=new Event("connectionstatechange",e),n.dispatchEvent(t)),e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}}))},n.removeExtmapAllowMixed=function(e,t){var n;e.RTCPeerConnection&&("chrome"===t.browser&&71<=t.version||"safari"===t.browser&&605<=t.version||(n=e.RTCPeerConnection.prototype.setRemoteDescription,e.RTCPeerConnection.prototype.setRemoteDescription=function(t){var r;return t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")&&(r=t.sdp.split("\n").filter(function(e){return"a=extmap-allow-mixed"!==e.trim()}).join("\n"),e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:r}):t.sdp=r),n.apply(this,arguments)}))},n.shimAddIceCandidateNullOrEmpty=function(e,t){var n;e.RTCPeerConnection&&e.RTCPeerConnection.prototype&&(n=e.RTCPeerConnection.prototype.addIceCandidate)&&0!==n.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})},n.shimParameterlessSetLocalDescription=function(e,t){var n;e.RTCPeerConnection&&e.RTCPeerConnection.prototype&&(n=e.RTCPeerConnection.prototype.setLocalDescription)&&0!==n.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){var e=this,t=arguments[0]||{};if("object"!==(void 0===t?"undefined":r(t))||t.type&&t.sdp)return n.apply(this,arguments);if(!(t={type:t.type,sdp:t.sdp}).type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":t.type="offer";break;default:t.type="answer"}return t.sdp||"offer"!==t.type&&"answer"!==t.type?n.apply(this,[t]):("offer"===t.type?this.createOffer:this.createAnswer).apply(this).then(function(t){return n.apply(e,[t])})})};var o,i=(o=e("sdp"))&&o.__esModule?o:{default:o},a=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}(e("./utils"))},{"./utils":11,sdp:12}],7:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0}),n.shimGetDisplayMedia=n.shimGetUserMedia=void 0;var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},o=e("./getusermedia");Object.defineProperty(n,"shimGetUserMedia",{enumerable:!0,get:function(){return o.shimGetUserMedia}});var i=e("./getdisplaymedia");Object.defineProperty(n,"shimGetDisplayMedia",{enumerable:!0,get:function(){return i.shimGetDisplayMedia}}),n.shimOnTrack=function(e){"object"===(void 0===e?"undefined":r(e))&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})},n.shimPeerConnection=function(e,t){var n,o;"object"===(void 0===e?"undefined":r(e))&&(e.RTCPeerConnection||e.mozRTCPeerConnection)&&(!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){var n=e.RTCPeerConnection.prototype[t],r=function(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}({},t,function(){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)});e.RTCPeerConnection.prototype[t]=r[t]}),n={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},o=e.RTCPeerConnection.prototype.getStats,e.RTCPeerConnection.prototype.getStats=function(){var e=(i=Array.prototype.slice.call(arguments))[0],r=i[1],i=i[2];return o.apply(this,[e||null]).then(function(e){if(t.version<53&&!r)try{e.forEach(function(e){e.type=n[e.type]||e.type})}catch(t){if("TypeError"!==t.name)throw t;e.forEach(function(t,r){e.set(r,Object.assign({},t,{type:n[t.type]||t.type}))})}return e}).then(r,i)})},n.shimSenderGetStats=function(e){var t,n;"object"===(void 0===e?"undefined":r(e))&&e.RTCPeerConnection&&e.RTCRtpSender&&(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype||((t=e.RTCPeerConnection.prototype.getSenders)&&(e.RTCPeerConnection.prototype.getSenders=function(){var e=this,n=t.apply(this,[]);return n.forEach(function(t){return t._pc=e}),n}),(n=e.RTCPeerConnection.prototype.addTrack)&&(e.RTCPeerConnection.prototype.addTrack=function(){var e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}))},n.shimReceiverGetStats=function(e){var t;"object"===(void 0===e?"undefined":r(e))&&e.RTCPeerConnection&&e.RTCRtpSender&&(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype||((t=e.RTCPeerConnection.prototype.getReceivers)&&(e.RTCPeerConnection.prototype.getReceivers=function(){var e=this,n=t.apply(this,[]);return n.forEach(function(t){return t._pc=e}),n}),a.wrapPeerConnectionEvent(e,"track",function(e){return e.receiver._pc=e.srcElement,e}),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}))},n.shimRemoveStream=function(e){!e.RTCPeerConnection||"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){var t=this;a.deprecated("removeStream","removeTrack"),this.getSenders().forEach(function(n){n.track&&e.getTracks().includes(n.track)&&t.removeTrack(n)})})},n.shimRTCDataChannel=function(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)},n.shimAddTransceiver=function(e){var t;"object"!==(void 0===e?"undefined":r(e))||!e.RTCPeerConnection||(t=e.RTCPeerConnection.prototype.addTransceiver)&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];var e=arguments[1],n=e&&"sendEncodings"in e;n&&e.sendEncodings.forEach(function(e){if("rid"in e&&!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in e&&!(1<=parseFloat(e.scaleResolutionDownBy)))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(0<=parseFloat(e.maxFramerate)))throw new RangeError("max_framerate must be >= 0.0")});var r,o=t.apply(this,arguments);return n&&("encodings"in(n=(r=o.sender).getParameters())&&(1!==n.encodings.length||0!==Object.keys(n.encodings[0]).length)||(n.encodings=e.sendEncodings,r.sendEncodings=e.sendEncodings,this.setParametersPromises.push(r.setParameters(n).then(function(){delete r.sendEncodings}).catch(function(){delete r.sendEncodings})))),o})},n.shimGetParameters=function(e){var t;"object"!==(void 0===e?"undefined":r(e))||!e.RTCRtpSender||(t=e.RTCRtpSender.prototype.getParameters)&&(e.RTCRtpSender.prototype.getParameters=function(){var e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})},n.shimCreateOffer=function(e){var t;"object"===(void 0===e?"undefined":r(e))&&e.RTCPeerConnection&&(t=e.RTCPeerConnection.prototype.createOffer,e.RTCPeerConnection.prototype.createOffer=function(){var e=this,n=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return t.apply(e,n)}).finally(function(){e.setParametersPromises=[]}):t.apply(this,arguments)})},n.shimCreateAnswer=function(e){var t;"object"===(void 0===e?"undefined":r(e))&&e.RTCPeerConnection&&(t=e.RTCPeerConnection.prototype.createAnswer,e.RTCPeerConnection.prototype.createAnswer=function(){var e=this,n=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return t.apply(e,n)}).finally(function(){e.setParametersPromises=[]}):t.apply(this,arguments)})};var a=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}(e("../utils"))},{"../utils":11,"./getdisplaymedia":8,"./getusermedia":9}],8:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0}),n.shimGetDisplayMedia=function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(n){return n&&n.video?(!0===n.video?n.video={mediaSource:t}:n.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(n)):((n=new DOMException("getDisplayMedia without video constraints is undefined")).name="NotFoundError",n.code=8,Promise.reject(n))})}},{}],9:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};n.shimGetUserMedia=function(e,t){var n,i,a,s,c=e&&e.navigator;e=e&&e.MediaStreamTrack;c.getUserMedia=function(e,t,n){o.deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),c.mediaDevices.getUserMedia(e).then(t,n)},55<t.version&&"autoGainControl"in c.mediaDevices.getSupportedConstraints()||(n=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])},i=c.mediaDevices.getUserMedia.bind(c.mediaDevices),c.mediaDevices.getUserMedia=function(e){return"object"===(void 0===e?"undefined":r(e))&&"object"===r(e.audio)&&(e=JSON.parse(JSON.stringify(e)),n(e.audio,"autoGainControl","mozAutoGainControl"),n(e.audio,"noiseSuppression","mozNoiseSuppression")),i(e)},e&&e.prototype.getSettings&&(a=e.prototype.getSettings,e.prototype.getSettings=function(){var e=a.apply(this,arguments);return n(e,"mozAutoGainControl","autoGainControl"),n(e,"mozNoiseSuppression","noiseSuppression"),e}),e&&e.prototype.applyConstraints&&(s=e.prototype.applyConstraints,e.prototype.applyConstraints=function(e){return"audio"===this.kind&&"object"===(void 0===e?"undefined":r(e))&&(e=JSON.parse(JSON.stringify(e)),n(e,"autoGainControl","mozAutoGainControl"),n(e,"noiseSuppression","mozNoiseSuppression")),s.apply(this,[e])}))};var o=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}(e("../utils"))},{"../utils":11}],10:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};n.shimLocalStreamsAPI=function(e){var t;"object"===(void 0===e?"undefined":r(e))&&e.RTCPeerConnection&&("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),"addStream"in e.RTCPeerConnection.prototype||(t=e.RTCPeerConnection.prototype.addTrack,e.RTCPeerConnection.prototype.addStream=function(e){var n=this;this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(function(r){return t.call(n,r,e)}),e.getVideoTracks().forEach(function(r){return t.call(n,r,e)})},e.RTCPeerConnection.prototype.addTrack=function(e){for(var n=this,r=arguments.length,o=Array(1<r?r-1:0),i=1;i<r;i++)o[i-1]=arguments[i];return o&&o.forEach(function(e){n._localStreams?n._localStreams.includes(e)||n._localStreams.push(e):n._localStreams=[e]}),t.apply(this,arguments)}),"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){var t=this;this._localStreams||(this._localStreams=[]);var n,r=this._localStreams.indexOf(e);-1!==r&&(this._localStreams.splice(r,1),n=e.getTracks(),this.getSenders().forEach(function(e){n.includes(e.track)&&t.removeTrack(e)}))}))},n.shimRemoteStreamsAPI=function(e){var t;"object"===(void 0===e?"undefined":r(e))&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams||[]}),"onaddstream"in e.RTCPeerConnection.prototype||(Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get:function(){return this._onaddstream},set:function(e){var t=this;this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=function(e){e.streams.forEach(function(e){var n;t._remoteStreams||(t._remoteStreams=[]),t._remoteStreams.includes(e)||(t._remoteStreams.push(e),(n=new Event("addstream")).stream=e,t.dispatchEvent(n))})})}}),t=e.RTCPeerConnection.prototype.setRemoteDescription,e.RTCPeerConnection.prototype.setRemoteDescription=function(){var e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach(function(t){var n;e._remoteStreams||(e._remoteStreams=[]),0<=e._remoteStreams.indexOf(t)||(e._remoteStreams.push(t),(n=new Event("addstream")).stream=t,e.dispatchEvent(n))})}),t.apply(e,arguments)}))},n.shimCallbacksAPI=function(e){var t,n,o,i,a,s;"object"===(void 0===e?"undefined":r(e))&&e.RTCPeerConnection&&(t=e.RTCPeerConnection.prototype,n=t.createOffer,o=t.createAnswer,i=t.setLocalDescription,a=t.setRemoteDescription,s=t.addIceCandidate,t.createOffer=function(e,t){var r=n.apply(this,[2<=arguments.length?arguments[2]:e]);return t?(r.then(e,t),Promise.resolve()):r},t.createAnswer=function(e,t){var n=o.apply(this,[2<=arguments.length?arguments[2]:e]);return t?(n.then(e,t),Promise.resolve()):n},e=function(e,t,n){return e=i.apply(this,[e]),n?(e.then(t,n),Promise.resolve()):e},t.setLocalDescription=e,e=function(e,t,n){return e=a.apply(this,[e]),n?(e.then(t,n),Promise.resolve()):e},t.setRemoteDescription=e,e=function(e,t,n){return e=s.apply(this,[e]),n?(e.then(t,n),Promise.resolve()):e},t.addIceCandidate=e)},n.shimGetUserMedia=function(e){var t,n=e&&e.navigator;n.mediaDevices&&n.mediaDevices.getUserMedia&&(e=n.mediaDevices,t=e.getUserMedia.bind(e),n.mediaDevices.getUserMedia=function(e){return t(i(e))}),!n.getUserMedia&&n.mediaDevices&&n.mediaDevices.getUserMedia&&(n.getUserMedia=function(e,t,r){n.mediaDevices.getUserMedia(e).then(t,r)}.bind(n))},n.shimConstraints=i,n.shimRTCIceServerUrls=function(e){var t;e.RTCPeerConnection&&(t=e.RTCPeerConnection,e.RTCPeerConnection=function(e,n){if(e&&e.iceServers){for(var r=[],i=0;i<e.iceServers.length;i++){var a=e.iceServers[i];!a.hasOwnProperty("urls")&&a.hasOwnProperty("url")?(o.deprecated("RTCIceServer.url","RTCIceServer.urls"),(a=JSON.parse(JSON.stringify(a))).urls=a.url,delete a.url,r.push(a)):r.push(e.iceServers[i])}e.iceServers=r}return new t(e,n)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:function(){return t.generateCertificate}}))},n.shimTrackEventTransceiver=function(e){"object"===(void 0===e?"undefined":r(e))&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})},n.shimCreateOfferLegacy=function(e){var t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){var n;return e&&(void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio),n=this.getTransceivers().find(function(e){return"audio"===e.receiver.track.kind}),!1===e.offerToReceiveAudio&&n?"sendrecv"===n.direction?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":"recvonly"===n.direction&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):!0!==e.offerToReceiveAudio||n||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo),n=this.getTransceivers().find(function(e){return"video"===e.receiver.track.kind}),!1===e.offerToReceiveVideo&&n?"sendrecv"===n.direction?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":"recvonly"===n.direction&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):!0!==e.offerToReceiveVideo||n||this.addTransceiver("video",{direction:"recvonly"})),t.apply(this,arguments)}},n.shimAudioContext=function(e){"object"!==(void 0===e?"undefined":r(e))||e.AudioContext||(e.AudioContext=e.webkitAudioContext)};var o=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}(e("../utils"));function i(e){return e&&void 0!==e.video?Object.assign({},e,{video:o.compactObject(e.video)}):e}},{"../utils":11}],11:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};n.extractVersion=a,n.wrapPeerConnectionEvent=function(e,t,n){var r,o;e.RTCPeerConnection&&(e=e.RTCPeerConnection.prototype,r=e.addEventListener,e.addEventListener=function(e,o){if(e!==t)return r.apply(this,arguments);function i(e){(e=n(e))&&(o.handleEvent?o.handleEvent(e):o(e))}return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(o,i),r.apply(this,[e,i])},o=e.removeEventListener,e.removeEventListener=function(e,n){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(n))return o.apply(this,arguments);var r=this._eventMap[t].get(n);return this._eventMap[t].delete(n),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,o.apply(this,[e,r])},Object.defineProperty(e,"on"+t,{get:function(){return this["_on"+t]},set:function(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0}))},n.disableLog=function(e){return"boolean"==typeof e?(o=e)?"adapter.js logging disabled":"adapter.js logging enabled":new Error("Argument type: "+(void 0===e?"undefined":r(e))+". Please use a boolean.")},n.disableWarnings=function(e){return"boolean"==typeof e?(i=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled")):new Error("Argument type: "+(void 0===e?"undefined":r(e))+". Please use a boolean.")},n.log=function(){"object"===("undefined"==typeof window?"undefined":r(window))&&(o||"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments))},n.deprecated=function(e,t){i&&console.warn(e+" is deprecated, please use "+t+" instead.")},n.detectBrowser=function(e){var t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;var n=e.navigator;if(n.mozGetUserMedia)t.browser="firefox",t.version=a(n.userAgent,/Firefox\/(\d+)\./,1);else if(n.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection&&!e.RTCIceGatherer)t.browser="chrome",t.version=a(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!n.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=a(n.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t},n.compactObject=function e(t){return s(t)?Object.keys(t).reduce(function(n,r){var o=(i=s(t[r]))?e(t[r]):t[r],i=i&&!Object.keys(o).length;return void 0===o||i?n:Object.assign(n,function(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}({},r,o))},{}):t},n.walkStats=c,n.filterStats=function(e,t,n){var r=n?"outbound-rtp":"inbound-rtp",o=new Map;if(null===t)return o;var i=[];return e.forEach(function(e){"track"===e.type&&e.trackIdentifier===t.id&&i.push(e)}),i.forEach(function(t){e.forEach(function(n){n.type===r&&n.trackId===t.id&&c(e,n,o)})}),o};var o=!0,i=!0;function a(e,t,n){return(t=e.match(t))&&t.length>=n&&parseInt(t[n],10)}function s(e){return"[object Object]"===Object.prototype.toString.call(e)}function c(e,t,n){t&&!n.has(t.id)&&(n.set(t.id,t),Object.keys(t).forEach(function(r){r.endsWith("Id")?c(e,e.get(t[r]),n):r.endsWith("Ids")&&t[r].forEach(function(t){c(e,e.get(t),n)})}))}},{}],12:[function(e,t,n){var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},o={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};o.localCName=o.generateIdentifier(),o.splitLines=function(e){return e.trim().split("\n").map(function(e){return e.trim()})},o.splitSections=function(e){return e.split("\nm=").map(function(e,t){return(0<t?"m="+e:e).trim()+"\r\n"})},o.getDescription=function(e){return(e=o.splitSections(e))&&e[0]},o.getMediaSections=function(e){return(e=o.splitSections(e)).shift(),e},o.matchPrefix=function(e,t){return o.splitLines(e).filter(function(e){return 0===e.indexOf(t)})},o.parseCandidate=function(e){for(var t=void 0,n={foundation:(t=(0===e.indexOf("a=candidate:")?e.substring(12):e.substring(10)).split(" "))[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]},r=8;r<t.length;r+=2)switch(t[r]){case"raddr":n.relatedAddress=t[r+1];break;case"rport":n.relatedPort=parseInt(t[r+1],10);break;case"tcptype":n.tcpType=t[r+1];break;case"ufrag":n.ufrag=t[r+1],n.usernameFragment=t[r+1];break;default:void 0===n[t[r]]&&(n[t[r]]=t[r+1])}return n},o.writeCandidate=function(e){var t=[];t.push(e.foundation);var n=e.component;return"rtp"===n?t.push(1):"rtcp"===n?t.push(2):t.push(n),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port),n=e.type,t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},o.parseIceOptions=function(e){return e.substr(14).split(" ")},o.parseRtpMap=function(e){var t=e.substr(9).split(" ");e={payloadType:parseInt(t.shift(),10)},t=t[0].split("/");return e.name=t[0],e.clockRate=parseInt(t[1],10),e.channels=3===t.length?parseInt(t[2],10):1,e.numChannels=e.channels,e},o.writeRtpMap=function(e){var t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);var n=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==n?"/"+n:"")+"\r\n"},o.parseExtmap=function(e){return e=e.substr(9).split(" "),{id:parseInt(e[0],10),direction:0<e[0].indexOf("/")?e[0].split("/")[1]:"sendrecv",uri:e[1]}},o.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+"\r\n"},o.parseFmtp=function(e){for(var t={},n=void 0,r=e.substr(e.indexOf(" ")+1).split(";"),o=0;o<r.length;o++)t[(n=r[o].trim().split("="))[0].trim()]=n[1];return t},o.writeFmtp=function(e){var t,n="",r=e.payloadType;return void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length&&(t=[],Object.keys(e.parameters).forEach(function(n){void 0!==e.parameters[n]?t.push(n+"="+e.parameters[n]):t.push(n)}),n+="a=fmtp:"+r+" "+t.join(";")+"\r\n"),n},o.parseRtcpFb=function(e){return{type:(e=e.substr(e.indexOf(" ")+1).split(" ")).shift(),parameter:e.join(" ")}},o.writeRtcpFb=function(e){var t="",n=e.payloadType;return void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(function(e){t+="a=rtcp-fb:"+n+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"}),t},o.parseSsrcMedia=function(e){var t=e.indexOf(" "),n={ssrc:parseInt(e.substr(7,t-7),10)},r=e.indexOf(":",t);return-1<r?(n.attribute=e.substr(t+1,r-t-1),n.value=e.substr(r+1)):n.attribute=e.substr(t+1),n},o.parseSsrcGroup=function(e){return{semantics:(e=e.substr(13).split(" ")).shift(),ssrcs:e.map(function(e){return parseInt(e,10)})}},o.getMid=function(e){if(e=o.matchPrefix(e,"a=mid:")[0])return e.substr(6)},o.parseFingerprint=function(e){return{algorithm:(e=e.substr(14).split(" "))[0].toLowerCase(),value:e[1].toUpperCase()}},o.getDtlsParameters=function(e,t){return{role:"auto",fingerprints:o.matchPrefix(e+t,"a=fingerprint:").map(o.parseFingerprint)}},o.writeDtlsParameters=function(e,t){var n="a=setup:"+t+"\r\n";return e.fingerprints.forEach(function(e){n+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"}),n},o.parseCryptoLine=function(e){return e=e.substr(9).split(" "),{tag:parseInt(e[0],10),cryptoSuite:e[1],keyParams:e[2],sessionParams:e.slice(3)}},o.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"===r(e.keyParams)?o.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},o.parseCryptoKeyParams=function(e){return 0!==e.indexOf("inline:")?null:{keyMethod:"inline",keySalt:(e=e.substr(7).split("|"))[0],lifeTime:e[1],mkiValue:e[2]?e[2].split(":")[0]:void 0,mkiLength:e[2]?e[2].split(":")[1]:void 0}},o.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},o.getCryptoParameters=function(e,t){return o.matchPrefix(e+t,"a=crypto:").map(o.parseCryptoLine)},o.getIceParameters=function(e,t){var n=o.matchPrefix(e+t,"a=ice-ufrag:")[0];t=o.matchPrefix(e+t,"a=ice-pwd:")[0];return n&&t?{usernameFragment:n.substr(12),password:t.substr(10)}:null},o.writeIceParameters=function(e){var t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},o.parseRtpParameters=function(e){for(var t={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=o.splitLines(e)[0].split(" "),r=3;r<n.length;r++){var i=n[r];if(s=o.matchPrefix(e,"a=rtpmap:"+i+" ")[0]){var a=o.parseRtpMap(s),s=o.matchPrefix(e,"a=fmtp:"+i+" ");switch(a.parameters=s.length?o.parseFmtp(s[0]):{},a.rtcpFeedback=o.matchPrefix(e,"a=rtcp-fb:"+i+" ").map(o.parseRtcpFb),t.codecs.push(a),a.name.toUpperCase()){case"RED":case"ULPFEC":t.fecMechanisms.push(a.name.toUpperCase())}}}return o.matchPrefix(e,"a=extmap:").forEach(function(e){t.headerExtensions.push(o.parseExtmap(e))}),t},o.writeRtpDescription=function(e,t){var n="";n+="m="+e+" ",n+=0<t.codecs.length?"9":"0",n+=" UDP/TLS/RTP/SAVPF ",n+=t.codecs.map(function(e){return void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType}).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",t.codecs.forEach(function(e){n+=o.writeRtpMap(e),n+=o.writeFmtp(e),n+=o.writeRtcpFb(e)});var r=0;return t.codecs.forEach(function(e){e.maxptime>r&&(r=e.maxptime)}),0<r&&(n+="a=maxptime:"+r+"\r\n"),t.headerExtensions&&t.headerExtensions.forEach(function(e){n+=o.writeExtmap(e)}),n},o.parseRtpEncodingParameters=function(e){var t=[],n=o.parseRtpParameters(e),r=-1!==n.fecMechanisms.indexOf("RED"),i=-1!==n.fecMechanisms.indexOf("ULPFEC"),a=0<(c=o.matchPrefix(e,"a=ssrc:").map(function(e){return o.parseSsrcMedia(e)}).filter(function(e){return"cname"===e.attribute})).length&&c[0].ssrc,s=void 0,c=o.matchPrefix(e,"a=ssrc-group:FID").map(function(e){return e.substr(17).split(" ").map(function(e){return parseInt(e,10)})});0<c.length&&1<c[0].length&&c[0][0]===a&&(s=c[0][1]),n.codecs.forEach(function(e){"RTX"===e.name.toUpperCase()&&e.parameters.apt&&(e={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)},a&&s&&(e.rtx={ssrc:s}),t.push(e),r&&((e=JSON.parse(JSON.stringify(e))).fec={ssrc:a,mechanism:i?"red+ulpfec":"red"},t.push(e)))}),0===t.length&&a&&t.push({ssrc:a});var d=o.matchPrefix(e,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substr(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substr(5),10)*.95-16e3:void 0,t.forEach(function(e){e.maxBitrate=d})),t},o.parseRtcpParameters=function(e){var t={},n=o.matchPrefix(e,"a=ssrc:").map(function(e){return o.parseSsrcMedia(e)}).filter(function(e){return"cname"===e.attribute})[0];return n&&(t.cname=n.value,t.ssrc=n.ssrc),n=o.matchPrefix(e,"a=rtcp-rsize"),t.reducedSize=0<n.length,t.compound=0===n.length,e=o.matchPrefix(e,"a=rtcp-mux"),t.mux=0<e.length,t},o.writeRtcpParameters=function(e){var t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},o.parseMsid=function(e){var t=void 0,n=o.matchPrefix(e,"a=msid:");return 1===n.length?{stream:(t=n[0].substr(7).split(" "))[0],track:t[1]}:0<(e=o.matchPrefix(e,"a=ssrc:").map(function(e){return o.parseSsrcMedia(e)}).filter(function(e){return"msid"===e.attribute})).length?{stream:(t=e[0].value.split(" "))[0],track:t[1]}:void 0},o.parseSctpDescription=function(e){var t=o.parseMLine(e),n=o.matchPrefix(e,"a=max-message-size:"),r=void 0;return 0<n.length&&(r=parseInt(n[0].substr(19),10)),isNaN(r)&&(r=65536),0<(n=o.matchPrefix(e,"a=sctp-port:")).length?{port:parseInt(n[0].substr(12),10),protocol:t.fmt,maxMessageSize:r}:0<(e=o.matchPrefix(e,"a=sctpmap:")).length?(e=e[0].substr(10).split(" "),{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:r}):void 0},o.writeSctpDescription=function(e,t){var n=[];n="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"];return void 0!==t.maxMessageSize&&n.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),n.join("")},o.generateSessionId=function(){return Math.random().toString().substr(2,21)},o.writeSessionBoilerplate=function(e,t,n){return t=void 0!==t?t:2,"v=0\r\no="+(n||"thisisadapterortc")+" "+(e||o.generateSessionId())+" "+t+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},o.getDirection=function(e,t){for(var n=o.splitLines(e),r=0;r<n.length;r++)switch(n[r]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[r].substr(2)}return t?o.getDirection(t):"sendrecv"},o.getKind=function(e){return o.splitLines(e)[0].split(" ")[0].substr(2)},o.isRejected=function(e){return"0"===e.split(" ",2)[1]},o.parseMLine=function(e){return{kind:(e=o.splitLines(e)[0].substr(2).split(" "))[0],port:parseInt(e[1],10),protocol:e[2],fmt:e.slice(3).join(" ")}},o.parseOLine=function(e){return{username:(e=o.matchPrefix(e,"o=")[0].substr(2).split(" "))[0],sessionId:e[1],sessionVersion:parseInt(e[2],10),netType:e[3],addressType:e[4],address:e[5]}},o.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;for(var t=o.splitLines(e),n=0;n<t.length;n++)if(t[n].length<2||"="!==t[n].charAt(1))return!1;return!0},"object"===(void 0===t?"undefined":r(t))&&(t.exports=o)},{}]},{},[1])(1)}),i.sessions=new Map,i.isExtensionEnabled=function(){if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)return!0;if(window.navigator.userAgent.match("Chrome")){let e=parseInt(window.navigator.userAgent.match(/Chrome\/(.*) /)[1],10),t=33;return window.navigator.userAgent.match("Linux")&&(t=35),e>=26&&e<=t||i.extension.isInstalled()}return!0};var o={extensionId:"hapfgfdkleiggjjpfpenajgdnfckjpaj",isInstalled:function(){return null!==document.querySelector("#janus-extension-installed")},getScreen:function(e){let t=window.setTimeout(function(){let t=new Error("NavigatorUserMediaError");return t.name='The required Chrome extension is not installed: click <a href="#">here</a> to install it. (NOTE: this will need you to refresh the page)',e(t)},1e3);this.cache[t]=e,window.postMessage({type:"janusGetScreen",id:t},"*")},init:function(){let e={};this.cache=e,window.addEventListener("message",function(t){if(t.origin==window.location.origin)if("janusGotScreen"==t.data.type&&e[t.data.id]){let n=e[t.data.id];if(delete e[t.data.id],""===t.data.sourceId){let e=new Error("NavigatorUserMediaError");e.name="You cancelled the request for permission, giving up...",n(e)}else n(null,t.data.sourceId)}else"janusGetScreenPending"==t.data.type&&(console.log("clearing ",t.data.id),window.clearTimeout(t.data.id))})}};function i(e){if((e=e||{}).success="function"==typeof e.success?e.success:i.noop,e.error="function"==typeof e.error?e.error:i.noop,e.destroyed="function"==typeof e.destroyed?e.destroyed:i.noop,!i.initDone)return e.error("Library not initialized"),{};if(!i.isWebrtcSupported())return e.error("WebRTC not supported by this browser"),{};if(i.log("Library initialized: "+i.initDone),!e.server)return e.error("Invalid server url"),{};let t=!1,n=null,r={},o=!1,a=null,s=0,c=e.server;i.isArray(c)?(i.log("Multiple servers provided ("+c.length+"), will use the first that works"),c=null,a=e.server,i.debug(a)):0===c.indexOf("ws")?(t=!0,i.log("Using WebSockets to contact Janus: "+c)):(t=!1,i.log("Using REST API to contact Janus: "+c));let d=e.iceServers||[{urls:"stun:stun.l.google.com:19302"}],l=e.iceTransportPolicy,u=e.bundlePolicy,p=!1;void 0!==e.withCredentials&&null!==e.withCredentials&&(p=!0===e.withCredentials);let f=10;void 0!==e.max_poll_events&&null!==e.max_poll_events&&(f=e.max_poll_events),f<1&&(f=1);let m=null;void 0!==e.token&&null!==e.token&&(m=e.token);let h=null;void 0!==e.apisecret&&null!==e.apisecret&&(h=e.apisecret),this.destroyOnUnload=!0,void 0!==e.destroyOnUnload&&null!==e.destroyOnUnload&&(this.destroyOnUnload=!0===e.destroyOnUnload);let g=6e4;function v(e){let t={high:9e5,medium:3e5,low:1e5};return null!=e&&(e.high&&(t.high=e.high),e.medium&&(t.medium=e.medium),e.low&&(t.low=e.low)),t}void 0!==e.longPollTimeout&&null!==e.longPollTimeout&&(g=e.longPollTimeout),isNaN(g)&&(g=6e4);let y=!1,S=null,b=new Map,C=this,T=0,w=new Map;function R(){if(null==S)return;if(i.debug("Long poll..."),!y)return void i.warn("Is the server down? (connected=false)");let t=c+"/"+S+"?rid="+(new Date).getTime();f&&(t=t+"&maxev="+f),m&&(t=t+"&token="+encodeURIComponent(m)),h&&(t=t+"&apisecret="+encodeURIComponent(h)),i.httpAPICall(t,{verb:"GET",withCredentials:p,success:k,timeout:g,error:function(t,n){if(i.error(t+":",n),T++,T>3)return y=!1,void e.error("Lost connection to the server (is it down?)");R()}})}function k(e,r){if(T=0,t||null==S||!0===r||R(),t||!i.isArray(e))if("keepalive"!==e.janus){if("server_info"===e.janus){i.debug("Got info on the Janus instance"),i.debug(e);const t=e.transaction;if(t){const n=w.get(t);n&&n(e),w.delete(t)}return}if("ack"===e.janus){i.debug("Got an ack on session "+S),i.debug(e);const t=e.transaction;if(t){const n=w.get(t);n&&n(e),w.delete(t)}return}if("success"===e.janus){i.debug("Got a success on session "+S),i.debug(e);const t=e.transaction;if(t){const n=w.get(t);n&&n(e),w.delete(t)}return}if("trickle"===e.janus){const t=e.sender;if(!t)return void i.warn("Missing sender...");const n=b.get(t);if(!n)return void i.debug("This handle is not attached to this session");let r=e.candidate;i.debug("Got a trickled candidate on session "+S),i.debug(r);let o=n.webrtcStuff;o.pc&&o.remoteSdp?(i.debug("Adding remote candidate:",r),r&&!0!==r.completed?o.pc.addIceCandidate(r):o.pc.addIceCandidate(i.endOfCandidates)):(i.debug("We didn't do setRemoteDescription (trickle got here before the offer?), caching candidate"),o.candidates||(o.candidates=[]),o.candidates.push(r),i.debug(o.candidates))}else{if("webrtcup"===e.janus){i.debug("Got a webrtcup event on session "+S),i.debug(e);const t=e.sender;if(!t)return void i.warn("Missing sender...");const n=b.get(t);return n?void n.webrtcState(!0):void i.debug("This handle is not attached to this session")}if("hangup"===e.janus){i.debug("Got a hangup event on session "+S),i.debug(e);const t=e.sender;if(!t)return void i.warn("Missing sender...");const n=b.get(t);if(!n)return void i.debug("This handle is not attached to this session");n.webrtcState(!1,e.reason),n.hangup()}else if("detached"===e.janus){i.debug("Got a detached event on session "+S),i.debug(e);const t=e.sender;if(!t)return void i.warn("Missing sender...");const n=b.get(t);if(!n)return;n.ondetached(),n.detach()}else if("media"===e.janus){i.debug("Got a media event on session "+S),i.debug(e);const t=e.sender;if(!t)return void i.warn("Missing sender...");const n=b.get(t);if(!n)return void i.debug("This handle is not attached to this session");n.mediaState(e.type,e.receiving,e.mid)}else if("slowlink"===e.janus){i.debug("Got a slowlink event on session "+S),i.debug(e);const t=e.sender;if(!t)return void i.warn("Missing sender...");const n=b.get(t);if(!n)return void i.debug("This handle is not attached to this session");n.slowLink(e.uplink,e.lost,e.mid)}else{if("error"===e.janus){i.error("Ooops: "+e.error.code+" "+e.error.reason),i.debug(e);let t=e.transaction;if(t){let n=w.get(t);n&&n(e),w.delete(t)}return}if("event"===e.janus){i.debug("Got a plugin event on session "+S),i.debug(e);const t=e.sender;if(!t)return void i.warn("Missing sender...");let n=e.plugindata;if(!n)return void i.warn("Missing plugindata...");i.debug(" -- Event is coming from "+t+" ("+n.plugin+")");let r=n.data;i.debug(r);const o=b.get(t);if(!o)return void i.warn("This handle is not attached to this session");let a=e.jsep;a&&(i.debug("Handling SDP as well..."),i.debug(a));let s=o.onmessage;s?(i.debug("Notifying application..."),s(r,a)):i.debug("No provided notification callback")}else{if("timeout"===e.janus)return i.error("Timeout on session "+S),i.debug(e),void(t&&n.close(3504,"Gateway timeout"));i.warn("Unknown message/event '"+e.janus+"' on session "+S),i.debug(e)}}}}else i.vdebug("Got a keepalive on session "+S);else for(let t=0;t<e.length;t++)k(e[t],!0)}function _(d){let l=i.randomString(12),u={janus:"create",transaction:l};if(d.reconnect&&(y=!1,u.janus="claim",u.session_id=S,n&&(n.onopen=null,n.onerror=null,n.onclose=null,o&&(o=!1))),m&&(u.token=m),h&&(u.apisecret=h),!c&&i.isArray(a)&&(c=a[s],0===c.indexOf("ws")?(t=!0,i.log("Server #"+(s+1)+": trying WebSockets to contact Janus ("+c+")")):(t=!1,i.log("Server #"+(s+1)+": trying REST API to contact Janus ("+c+")"))),t){n=i.newWebSocket(c,"janus-protocol"),r={error:function(){if(i.error("Error connecting to the Janus WebSockets server... "+c),i.isArray(a)&&!d.reconnect)return s++,s===a.length?void d.error("Error connecting to any of the provided Janus servers: Is the server down?"):(c=null,void setTimeout(function(){_(d)},200));d.error("Error connecting to the Janus WebSockets server: Is the server down?")},open:function(){w.set(l,function(e){if(i.debug(e),"success"!==e.janus)return i.error("Ooops: "+e.error.code+" "+e.error.reason),void d.error(e.error.reason);o=!0,y=!0,S=e.session_id?e.session_id:e.data.id,d.reconnect?i.log("Claimed session: "+S):i.log("Created session: "+S),i.sessions.set(S,C),d.success()}),n.send(JSON.stringify(u))},message:function(e){k(JSON.parse(e.data))},close:function(){c&&y&&(y=!1,e.error("Lost connection to the server (is it down?)"))}};for(let e in r)n.addEventListener(e,r[e])}else i.httpAPICall(c,{verb:"POST",withCredentials:p,body:u,success:function(e){if(i.debug(e),"success"!==e.janus)return i.error("Ooops: "+e.error.code+" "+e.error.reason),void d.error(e.error.reason);y=!0,S=e.session_id?e.session_id:e.data.id,d.reconnect?i.log("Claimed session: "+S):i.log("Created session: "+S),i.sessions.set(S,C),R(),d.success()},error:function(e,t){if(i.error(e+":",t),i.isArray(a)&&!d.reconnect)return s++,s===a.length?void d.error("Error connecting to any of the provided Janus servers: Is the server down?"):(c=null,void setTimeout(function(){_(d)},200));""===t?d.error(e+": Is the server down?"):t&&t.error?d.error(e+": "+t.error.message):d.error(e+": "+t)}})}function P(e,r){if((r=r||{}).success="function"==typeof r.success?r.success:i.noop,r.error="function"==typeof r.error?r.error:i.noop,!y)return i.warn("Is the server down? (connected=false)"),void r.error("Is the server down? (connected=false)");let o=b.get(e);if(!o||!o.webrtcStuff)return i.warn("Invalid handle"),void r.error("Invalid handle");let a=r.message,s=r.jsep,d=i.randomString(12),l={janus:"message",body:a,transaction:d};if(o.token&&(l.token=o.token),h&&(l.apisecret=h),s){l.jsep={type:s.type,sdp:s.sdp},s.e2ee&&(l.jsep.e2ee=!0),"hml"!==s.rid_order&&"lmh"!==s.rid_order||(l.jsep.rid_order=s.rid_order),s.force_relay&&(l.jsep.force_relay=!0);let e=null,t=o.webrtcStuff;if(t.pc){let n=t.pc.getTransceivers();if(n&&n.length>0)for(let t in n){let r=n[t];if(r&&r.sender&&r.sender.track&&"video"===r.sender.track.kind){let n=r.sender.getParameters();n&&n.encodings&&1===n.encodings.length&&n.encodings[0]&&n.encodings[0].scalabilityMode&&(e||(e=[]),e.push({mindex:parseInt(t),mid:r.mid,svc:n.encodings[0].scalabilityMode}))}}}e&&(l.jsep.svc=e)}if(i.debug("Sending message to plugin (handle="+e+"):"),i.debug(l),t)return l.session_id=S,l.handle_id=e,w.set(d,function(e){if(i.debug("Message sent!"),i.debug(e),"success"===e.janus){let t=e.plugindata;if(!t)return i.warn("Request succeeded, but missing plugindata..."),void r.success();i.log("Synchronous transaction successful ("+t.plugin+")");let n=t.data;return i.debug(n),void r.success(n)}"ack"===e.janus?r.success():e.error?(i.error("Ooops: "+e.error.code+" "+e.error.reason),r.error(e.error.code+" "+e.error.reason)):(i.error("Unknown error"),r.error("Unknown error"))}),void n.send(JSON.stringify(l));i.httpAPICall(c+"/"+S+"/"+e,{verb:"POST",withCredentials:p,body:l,success:function(e){if(i.debug("Message sent!"),i.debug(e),"success"===e.janus){let t=e.plugindata;if(!t)return i.warn("Request succeeded, but missing plugindata..."),void r.success();i.log("Synchronous transaction successful ("+t.plugin+")");let n=t.data;return i.debug(n),void r.success(n)}"ack"===e.janus?r.success():e.error?(i.error("Ooops: "+e.error.code+" "+e.error.reason),r.error(e.error.code+" "+e.error.reason)):(i.error("Unknown error"),r.error("Unknown error"))},error:function(e,t){i.error(e+":",t),r.error(e+": "+t)}})}function I(e,r){if(!y)return void i.warn("Is the server down? (connected=false)");let o=b.get(e);if(!o||!o.webrtcStuff)return void i.warn("Invalid handle");let a={janus:"trickle",candidate:r,transaction:i.randomString(12)};if(o.token&&(a.token=o.token),h&&(a.apisecret=h),i.vdebug("Sending trickle candidate (handle="+e+"):"),i.vdebug(a),t)return a.session_id=S,a.handle_id=e,void n.send(JSON.stringify(a));i.httpAPICall(c+"/"+S+"/"+e,{verb:"POST",withCredentials:p,body:a,success:function(e){i.vdebug("Candidate sent!"),i.vdebug(e),"ack"===e.janus||i.error("Ooops: "+e.error.code+" "+e.error.reason)},error:function(e,t){i.error(e+":",t)}})}function E(e,t,n,r,o){let a=b.get(e);if(!a||!a.webrtcStuff)return void i.warn("Invalid handle");let s=a.webrtcStuff;if(!s.pc)return void i.warn("Invalid PeerConnection");let c=function(e){i.log("Received state change on data channel:",e);let t=e.target.label,n=e.target.protocol,r=s.dataChannel[t]?s.dataChannel[t].readyState:"null";if(i.log("State change on <"+t+"> data channel: "+r),"open"===r){if(s.dataChannel[t].pending&&s.dataChannel[t].pending.length>0){i.log("Sending pending messages on <"+t+">:",s.dataChannel[t].pending.length);for(let e of s.dataChannel[t].pending)i.log("Sending data on data channel <"+t+">"),i.debug(e),s.dataChannel[t].send(e);s.dataChannel[t].pending=[]}a.ondataopen(t,n)}};if(r)s.dataChannel[t]=r;else{let e=s.dataChannelOptions;n&&(e.protocol=n),s.dataChannel[t]=s.pc.createDataChannel(t,e)}s.dataChannel[t].onmessage=function(e){i.log("Received message on data channel:",e);let t=e.target.label;a.ondata(e.data,t)},s.dataChannel[t].onopen=c,s.dataChannel[t].onclose=c,s.dataChannel[t].onerror=function(e){i.error("Got error on data channel:",e)},s.dataChannel[t].pending=[],o&&s.dataChannel[t].pending.push(o)}function A(e,t){(t=t||{}).success="function"==typeof t.success?t.success:i.noop,t.error="function"==typeof t.error?t.error:i.noop;let n=b.get(e);if(!n||!n.webrtcStuff)return i.warn("Invalid handle"),void t.error("Invalid handle");let r=n.webrtcStuff,o=t.text||t.data;if(!o)return i.warn("Invalid data"),void t.error("Invalid data");let a=t.label?t.label:i.dataChanDefaultLabel;return r.dataChannel[a]?"open"!==r.dataChannel[a].readyState?(r.dataChannel[a].pending.push(o),void t.success()):(i.log("Sending data on data channel <"+a+">"),i.debug(o),r.dataChannel[a].send(o),void t.success()):(E(e,a,t.protocol,!1,o,t.protocol),void t.success())}function O(e,t){(t=t||{}).success="function"==typeof t.success?t.success:i.noop,t.error="function"==typeof t.error?t.error:i.noop;let n=b.get(e);if(!n||!n.webrtcStuff)return i.warn("Invalid handle"),void t.error("Invalid handle");let r=n.webrtcStuff;if(!r.dtmfSender){if(r.pc){let e=r.pc.getSenders().find(function(e){return e.track&&"audio"===e.track.kind});if(!e)return i.warn("Invalid DTMF configuration (no audio track)"),void t.error("Invalid DTMF configuration (no audio track)");r.dtmfSender=e.dtmf,r.dtmfSender&&(i.log("Created DTMF Sender"),r.dtmfSender.ontonechange=function(e){i.debug("Sent DTMF tone: "+e.tone)})}if(!r.dtmfSender)return i.warn("Invalid DTMF configuration"),void t.error("Invalid DTMF configuration")}let o=t.dtmf;if(!o)return i.warn("Invalid DTMF parameters"),void t.error("Invalid DTMF parameters");let a=o.tones;if(!a)return i.warn("Invalid DTMF string"),void t.error("Invalid DTMF string");let s="number"==typeof o.duration?o.duration:500,c="number"==typeof o.gap?o.gap:50;i.debug("Sending DTMF string "+a+" (duration "+s+"ms, gap "+c+"ms)"),r.dtmfSender.insertDTMF(a,s,c),t.success()}function D(e,r){(r=r||{}).success="function"==typeof r.success?r.success:i.noop,r.error="function"==typeof r.error?r.error:i.noop;let o=!0===r.noRequest;i.log("Destroying handle "+e+" (only-locally="+o+")"),$(e);let a=b.get(e);if(!a||a.detached)return b.delete(e),void r.success();if(a.detached=!0,o)return b.delete(e),void r.success();if(!y)return i.warn("Is the server down? (connected=false)"),void r.error("Is the server down? (connected=false)");let s={janus:"detach",transaction:i.randomString(12)};if(a.token&&(s.token=a.token),h&&(s.apisecret=h),t)return s.session_id=S,s.handle_id=e,n.send(JSON.stringify(s)),b.delete(e),void r.success();i.httpAPICall(c+"/"+S+"/"+e,{verb:"POST",withCredentials:p,body:s,success:function(t){i.log("Destroyed handle:"),i.debug(t),"success"!==t.janus&&i.error("Ooops: "+t.error.code+" "+t.error.reason),b.delete(e),r.success()},error:function(t,n){i.error(t+":",n),b.delete(e),r.success()}})}function N(e,t){let n=b.get(e);if(!n||!n.webrtcStuff)throw i.warn("Invalid handle"),"Invalid handle";let r=n.webrtcStuff;if(r.pc)return;let o={iceServers:d,iceTransportPolicy:l,bundlePolicy:u,sdpSemantics:"unified-plan"},a=!1;if(t.tracks)for(let e of t.tracks)if(e.transforms&&(e.transforms.sender||e.transforms.receiver)){a=!0;break}t.externalEncryption&&(a=!0,r.externalEncryption=!0),RTCRtpSender&&(RTCRtpSender.prototype.createEncodedStreams||RTCRtpSender.prototype.createEncodedAudioStreams&&RTCRtpSender.prototype.createEncodedVideoStreams)&&a&&(r.insertableStreams=!0,o.forceEncodedAudioInsertableStreams=!0,o.forceEncodedVideoInsertableStreams=!0,o.encodedInsertableStreams=!0),i.log("Creating PeerConnection"),r.pc=new RTCPeerConnection(o),i.debug(r.pc),r.pc.getStats&&(r.volume={},r.bitrate.value="0 kbits/sec"),i.log("Preparing local SDP and gathering candidates (trickle="+r.trickle+")"),r.pc.onconnectionstatechange=function(){r.pc&&n.connectionState(r.pc.connectionState)},r.pc.oniceconnectionstatechange=function(){r.pc&&n.iceState(r.pc.iceConnectionState)},r.pc.onicecandidate=function(n){if(!n.candidate||n.candidate.candidate&&n.candidate.candidate.indexOf("endOfCandidates")>0)i.log("End of candidates."),r.iceDone=!0,!0===r.trickle?I(e,{completed:!0}):function(e,t){t=t||{},t.success="function"==typeof t.success?t.success:i.noop,t.error="function"==typeof t.error?t.error:i.noop;let n=b.get(e);if(!n||!n.webrtcStuff)return void i.warn("Invalid handle, not sending anything");let r=n.webrtcStuff;if(i.log("Sending offer/answer SDP..."),!r.mySdp)return void i.warn("Local SDP instance is invalid, not sending anything...");r.mySdp={type:r.pc.localDescription.type,sdp:r.pc.localDescription.sdp},!1===r.trickle&&(r.mySdp.trickle=!1);i.debug(t),r.sdpSent=!0,t.success(r.mySdp)}(e,t);else{let t={candidate:n.candidate.candidate,sdpMid:n.candidate.sdpMid,sdpMLineIndex:n.candidate.sdpMLineIndex};!0===r.trickle&&I(e,t)}},r.pc.ontrack=function(e){if(i.log("Handling Remote Track",e),!e.streams)return;if(!e.track)return;let t=e.transceiver?e.transceiver.mid:e.track.id;try{e.transceiver&&e.transceiver.mid&&e.track.id&&(n.mids||(n.mids={}),n.mids[e.track.id]=e.transceiver.mid),n.onremotetrack(e.track,t,!0,{reason:"created"})}catch(e){i.error("Error calling onremotetrack",e)}if(e.track.onended)return;let o=null;i.log("Adding onended callback to track:",e.track),e.track.onended=function(t){i.log("Remote track removed:",t),clearTimeout(o);let a=r.pc?r.pc.getTransceivers():null,s=a?a.find(e=>e.receiver.track===t.target):null,c=s?s.mid:t.target.id;c===t.target.id&&n.mids&&n.mids[e.track.id]&&(c=n.mids[e.track.id]);try{n.onremotetrack(t.target,c,!1,{reason:"ended"})}catch(e){i.error("Error calling onremotetrack on removal",e)}delete n.mids[e.track.id]},e.track.onmute=function(t){i.log("Remote track muted:",t),o||(o=setTimeout(function(){i.log("Removing remote track");let a=r.pc?r.pc.getTransceivers():null,s=a?a.find(e=>e.receiver.track===t.target):null,c=s?s.mid:t.target.id;c===t.target.id&&n.mids&&n.mids[e.track.id]&&(c=n.mids[e.track.id]);try{n.onremotetrack(t.target,c,!1,{reason:"mute"})}catch(e){i.error("Error calling onremotetrack on mute",e)}o=null},2520))},e.track.onunmute=function(e){if(i.log("Remote track flowing again:",e),null!=o)clearTimeout(o),o=null;else try{let t=r.pc?r.pc.getTransceivers():null,o=t?t.find(t=>t.receiver.track===e.target):null,i=o?o.mid:e.target.id;n.onremotetrack(e.target,i,!0,{reason:"unmute"})}catch(e){i.error("Error calling onremotetrack on unmute",e)}}}}async function L(e,t,n){(n=n||{}).success="function"==typeof n.success?n.success:i.noop,n.error="function"==typeof n.error?n.error:z;let r=n.jsep;if(t&&r)return i.error("Provided a JSEP to a createOffer"),void n.error("Provided a JSEP to a createOffer");if(!(t||r&&r.type&&r.sdp))return i.error("A valid JSEP is required for createAnswer"),void n.error("A valid JSEP is required for createAnswer");if(n.media&&!n.tracks){if(n.tracks=i.mediaToTracks(n.media),!0===n.simulcast||!0===n.simulcast2||n.svc)for(let e of n.tracks)if("video"===e.type){!0===n.simulcast||!0===n.simulcast2?e.simulcast=!0:n.svc&&(e.svc=n.svc);break}i.warn("Deprecated media object passed, use tracks instead. Automatically translated to:",n.tracks)}if(n.tracks&&!Array.isArray(n.tracks))return i.error("Tracks must be an array"),void n.error("Tracks must be an array");let o=b.get(e);if(!o||!o.webrtcStuff)return i.warn("Invalid handle"),void n.error("Invalid handle");let a=o.webrtcStuff;var s;a.trickle=(s=n.trickle,i.debug("isTrickleEnabled:",s),!1!==s);try{if(N(e,n),t&&await j(e,n),r){if(await a.pc.setRemoteDescription(r),i.log("Remote description accepted!"),a.remoteSdp=r.sdp,a.candidates&&a.candidates.length>0){for(let e=0;e<a.candidates.length;e++){let t=a.candidates[e];i.debug("Adding remote candidate:",t),t&&!0!==t.completed?a.pc.addIceCandidate(t):a.pc.addIceCandidate(i.endOfCandidates)}a.candidates=[]}await j(e,n);let t=await async function(e,t){t=t||{},t.customizeSdp="function"==typeof t.customizeSdp?t.customizeSdp:i.noop;let n=b.get(e);if(!n||!n.webrtcStuff)throw i.warn("Invalid handle"),"Invalid handle";let r=n.webrtcStuff;i.log("Creating answer (iceDone="+r.iceDone+")");let o=await r.pc.createAnswer();i.debug(o);let a={type:"answer",sdp:o.sdp};if(t.customizeSdp(a),o.sdp=a.sdp,i.log("Setting local description"),r.mySdp={type:"answer",sdp:o.sdp},await r.pc.setLocalDescription(o),!r.iceDone&&!r.trickle)return i.log("Waiting for all candidates..."),null;(r.insertableStreams||r.externalEncryption)&&(o.e2ee=!0);return o}(e,n);n.success(t)}else{let t=await async function(e,t){t=t||{},t.customizeSdp="function"==typeof t.customizeSdp?t.customizeSdp:i.noop;let n=b.get(e);if(!n||!n.webrtcStuff)throw i.warn("Invalid handle"),"Invalid handle";let r=n.webrtcStuff;i.log("Creating offer (iceDone="+r.iceDone+")");let o={},a=!0===t.iceRestart;a&&(o.iceRestart=!0);i.debug(o);let s=await r.pc.createOffer(o);i.debug(s);let c={type:"offer",sdp:s.sdp};if(t.customizeSdp(c),s.sdp=c.sdp,i.log("Setting local description"),r.mySdp={type:"offer",sdp:s.sdp},await r.pc.setLocalDescription(s),r.mediaConstraints=o,!r.iceDone&&!r.trickle)return i.log("Waiting for all candidates..."),null;(r.insertableStreams||r.externalEncryption)&&(s.e2ee=!0);return s}(e,n);n.success(t)}}catch(e){i.error(e),n.error(e)}}function M(e,t){(t=t||{}).success="function"==typeof t.success?t.success:i.noop,t.error="function"==typeof t.error?t.error:z,t.customizeSdp="function"==typeof t.customizeSdp?t.customizeSdp:i.noop;let n=t.jsep,r=b.get(e);if(!r||!r.webrtcStuff)return i.warn("Invalid handle"),void t.error("Invalid handle");let o=r.webrtcStuff;if(n){if(!o.pc)return i.warn("Wait, no PeerConnection?? if this is an answer, use createAnswer and not handleRemoteJsep"),void t.error("No PeerConnection: if this is an answer, use createAnswer and not handleRemoteJsep");t.customizeSdp(n),o.pc.setRemoteDescription(n).then(function(){if(i.log("Remote description accepted!"),o.remoteSdp=n.sdp,o.candidates&&o.candidates.length>0){for(let e=0;e<o.candidates.length;e++){let t=o.candidates[e];i.debug("Adding remote candidate:",t),t&&!0!==t.completed?o.pc.addIceCandidate(t):o.pc.addIceCandidate(i.endOfCandidates)}o.candidates=[]}t.success()},t.error)}else t.error("Invalid JSEP")}async function x(e,t){if((t=t||{}).success="function"==typeof t.success?t.success:i.noop,t.error="function"==typeof t.error?t.error:i.noop,t.tracks&&!Array.isArray(t.tracks))return i.error("Tracks must be an array"),void t.error("Tracks must be an array");for(let e of t.tracks)(e.add||!e.replace&&!e.remove)&&(e.replace=!0);try{await j(e,t),t.success()}catch(e){i.error(e),t.error(e)}}async function j(e,t){let n=b.get(e);if(!n||!n.webrtcStuff)throw i.warn("Invalid handle, not sending anything"),"Invalid handle";let r=n.webrtcStuff;if(!r.pc)throw i.warn("Invalid PeerConnection"),"Invalid PeerConnection";let o=t.tracks;if(!o||!Array.isArray(o)||0===o.length)return;let a=!1,s={};for(let e of o){if(delete e.gumGroup,!e.type||!["audio","video"].includes(e.type))continue;if(!e.capture||e.capture instanceof MediaStreamTrack)continue;let t=e.group?e.group:"default";s[t]||(s[t]={}),s[t][e.type]||(e.gumGroup=t,s[t][e.type]=e)}let c=Object.keys(s);for(let e of c){let t=s[e];t.audio&&t.video||(t.audio&&delete t.audio.gumGroup,t.video&&delete t.video.gumGroup,delete s[e])}let d=!!t.jsep;for(let t of o){if(!t.type){i.warn("Missing track type:",t);continue}if("data"===t.type){if(r.pc.ondatachannel){i.warn("Data channel exists already, not creating another one");continue}i.log("Creating default data channel"),E(e,i.dataChanDefaultLabel,null,!1),r.pc.ondatachannel=function(t){i.log("Data channel created by Janus:",t),E(e,t.channel.label,t.channel.protocol,t.channel)};continue}if(void 0!==t.add&&null!==t.add||void 0!==t.remove&&null!==t.remove||void 0!==t.replace&&null!==t.replace||(t.add=!0),t.add&&t.remove||t.add&&t.remove&&t.replace){i.warn("Conflicting actions for track, ignoring:",t);continue}t.add&&t.replace?(i.warn("Both add and replace provided, falling back to replace:",t),delete t.add):t.remove&&t.replace&&(i.warn("Both remove and replace provided, falling back to remove:",t),delete t.replace);let o=t.type;"screen"===t.type&&(o="video");let c=null,l=null;if(t.mid?c=r.pc.getTransceivers().find(e=>e.mid===t.mid&&e.receiver.track.kind===o):t.add||(c=r.pc.getTransceivers().find(e=>e.receiver.track.kind===o)),t.replace||t.remove){if(!c){i.warn("Couldn't find a transceiver for track:",t);continue}if(!c.sender){i.warn("No sender in the transceiver for track:",t);continue}l=c.sender}if(d&&!c&&(c=r.pc.getTransceivers().find(e=>e.receiver.track.kind===o),!c)){i.warn("Couldn't find a transceiver for track:",t);continue}let u=null,p=null;if((t.remove||t.replace)&&(i.log("Removing track from PeerConnection",t),p=l.track?l.track.id:null,await l.replaceTrack(null),p&&r.myStream)){let e=null;if("audio"===o&&r.myStream.getAudioTracks()&&r.myStream.getAudioTracks().length)for(let t of r.myStream.getAudioTracks())t.id===p&&(e=t,i.log("Removing audio track:",e));else if("video"===o&&r.myStream.getVideoTracks()&&r.myStream.getVideoTracks().length)for(let t of r.myStream.getVideoTracks())t.id===p&&(e=t,i.log("Removing video track:",e));if(e){try{r.myStream.removeTrack(e),n.onlocaltrack(e,!1)}catch(e){i.error("Error calling onlocaltrack on removal for renegotiation",e)}if(!0!==e.dontStop)try{e.stop()}catch(e){}}}if(t.capture){if(t.gumGroup&&s[t.gumGroup]&&s[t.gumGroup].stream){let e=s[t.gumGroup].stream;u="audio"===t.type?e.getAudioTracks()[0]:e.getVideoTracks()[0],delete s[t.gumGroup].stream,delete s[t.gumGroup],delete t.gumGroup}else if(t.capture instanceof MediaStreamTrack)u=t.capture;else{a||(a=!0,n.consentDialog(!0));let e=i.trackConstraints(t),r=null;if("audio"===t.type||"video"===t.type){if(t.gumGroup){let n="audio"===t.type?"video":"audio";if(s[t.gumGroup]&&s[t.gumGroup][n]){let r=s[t.gumGroup][n],o=i.trackConstraints(r);e[n]=o[n]}}r=await navigator.mediaDevices.getUserMedia(e),t.gumGroup&&e.audio&&e.video&&(s[t.gumGroup].stream=r,delete t.gumGroup)}else r=await navigator.mediaDevices.getDisplayMedia(e);u="audio"===t.type?r.getAudioTracks()[0]:r.getVideoTracks()[0]}if(t.replace){await l.replaceTrack(u);let e="sendrecv";!1!==t.recv&&"inactive"!==c.direction&&"sendonly"!==c.direction||(e="sendonly"),c.setDirection?c.setDirection(e):c.direction=e}else{if(r.myStream||(r.myStream=new MediaStream),"audio"===o||!t.simulcast&&!t.svc)l=r.pc.addTrack(u,r.myStream),c=r.pc.getTransceivers().find(e=>e.sender===l);else if(t.simulcast){i.log("Enabling rid-based simulcasting:",u);let e=v(t.simulcastMaxBitrates);c=r.pc.addTransceiver(u,{direction:"sendrecv",streams:[r.myStream],sendEncodings:t.sendEncodings||[{rid:"h",active:!0,scalabilityMode:"L1T2",maxBitrate:e.high},{rid:"m",active:!0,scalabilityMode:"L1T2",maxBitrate:e.medium,scaleResolutionDownBy:2},{rid:"l",active:!0,scalabilityMode:"L1T2",maxBitrate:e.low,scaleResolutionDownBy:4}]})}else i.log("Enabling SVC ("+t.svc+"):",u),c=r.pc.addTransceiver(u,{direction:"sendrecv",streams:[r.myStream],sendEncodings:[{scalabilityMode:t.svc}]});if(l||(l=c?c.sender:null),t.codec)if("firefox"===i.webRTCAdapter.browserDetails.browser)i.warn("setCodecPreferences not supported in Firefox, ignoring codec for track:",t);else if("string"!=typeof t.codec)i.warn("Invalid codec value, ignoring for track:",t);else{let e=o+"/"+t.codec.toLowerCase(),n=RTCRtpReceiver.getCapabilities(o).codecs.filter(function(t){return t.mimeType.toLowerCase()===e});if(n&&0!==n.length){if(c)try{c.setCodecPreferences(n)}catch(e){i.warn("Failed enforcing codec for this "+o+" track:",e)}}else i.warn("Codec not supported in this browser for this track, ignoring:",t)}if(t.bitrate)if(t.simulcast||t.svc)i.warn("Ignoring bitrate for simulcast/SVC track, use sendEncodings for that");else if(isNaN(t.bitrate)||t.bitrate<0)i.warn("Ignoring invalid bitrate for track:",t);else if(l){let e=l.getParameters();e&&e.encodings&&0!==e.encodings.length?(e.encodings[0].maxBitrate=t.bitrate,await l.setParameters(e)):i.warn("No encodings in the sender parameters, ignoring bitrate for track:",t)}if("video"===o&&t.framerate)if(t.simulcast||t.svc)i.warn("Ignoring framerate for simulcast/SVC track, use sendEncodings for that");else if(isNaN(t.framerate)||t.framerate<0)i.warn("Ignoring invalid framerate for track:",t);else if(l){let e=l.getParameters();e&&e.encodings&&0!==e.encodings.length?(e.encodings[0].maxFramerate=t.framerate,await l.setParameters(e)):i.warn("No encodings in the sender parameters, ignoring framerate for track:",t)}if(t.transforms){if(l&&t.transforms.sender){let e=null;RTCRtpSender.prototype.createEncodedStreams?e=l.createEncodedStreams():(RTCRtpSender.prototype.createAudioEncodedStreams||RTCRtpSender.prototype.createEncodedVideoStreams)&&("audio"===o?e=l.createEncodedAudioStreams():"video"===o&&(e=l.createEncodedVideoStreams())),e&&(console.log("Insertable Streams sender transform:",e),e.readableStream&&e.writableStream?e.readableStream.pipeThrough(t.transforms.sender).pipeTo(e.writableStream):e.readable&&e.writable&&e.readable.pipeThrough(t.transforms.sender).pipeTo(e.writable))}if(c&&c.receiver&&t.transforms.receiver){let e=null;RTCRtpReceiver.prototype.createEncodedStreams?e=c.receiver.createEncodedStreams():(RTCRtpReceiver.prototype.createAudioEncodedStreams||RTCRtpReceiver.prototype.createEncodedVideoStreams)&&("audio"===o?e=c.receiver.createEncodedAudioStreams():"video"===o&&(e=c.receiver.createEncodedVideoStreams())),e&&(console.log("Insertable Streams receiver transform:",e),e.readableStream&&e.writableStream?e.readableStream.pipeThrough(t.transforms.receiver).pipeTo(e.writableStream):e.readable&&e.writable&&e.readable.pipeThrough(t.transforms.receiver).pipeTo(e.writable))}}}u&&!0===t.dontStop&&(u.dontStop=!0)}else if(t.recv&&(c||(c=r.pc.addTransceiver(o)),c)){if(t.codec)if("firefox"===i.webRTCAdapter.browserDetails.browser)i.warn("setCodecPreferences not supported in Firefox, ignoring codec for track:",t);else if("string"!=typeof t.codec)i.warn("Invalid codec value, ignoring for track:",t);else{let e=o+"/"+t.codec.toLowerCase(),n=RTCRtpReceiver.getCapabilities(o).codecs.filter(function(t){return t.mimeType.toLowerCase()===e});if(n&&0!==n.length)try{c.setCodecPreferences(n)}catch(e){i.warn("Failed enforcing codec for this "+o+" track:",e)}else i.warn("Codec not supported in this browser for this track, ignoring:",t)}if(c.receiver&&t.transforms&&t.transforms.receiver){let e=null;RTCRtpReceiver.prototype.createEncodedStreams?e=c.receiver.createEncodedStreams():(RTCRtpReceiver.prototype.createAudioEncodedStreams||RTCRtpReceiver.prototype.createEncodedVideoStreams)&&("audio"===o?e=c.receiver.createEncodedAudioStreams():"video"===o&&(e=c.receiver.createEncodedVideoStreams())),e&&(console.log("Insertable Streams receiver transform:",e),e.readableStream&&e.writableStream?e.readableStream.pipeThrough(t.transforms.receiver).pipeTo(e.writableStream):e.readable&&e.writable&&e.readable.pipeThrough(t.transforms.receiver).pipeTo(e.writable))}}if(u){r.myStream.addTrack(u),u.onended=function(e){i.log("Local track removed:",e);try{n.onlocaltrack(e.target,!1)}catch(e){i.error("Error calling onlocaltrack following end",e)}};try{n.onlocaltrack(u,!0)}catch(e){i.error("Error calling onlocaltrack for track add",e)}}if(c){let e=c.direction,n=null,r=u&&c.sender.track,o=!1!==t.recv&&c.receiver.track;r&&o?n="sendrecv":r&&!o?n="sendonly":!r&&o?n="recvonly":r||o||(n="inactive"),n&&n!==e&&(i.warn("Changing direction of transceiver to "+n+" (was "+e+")",t),c.setDirection?c.setDirection(n):c.direction=n)}}a&&n.consentDialog(!1)}function G(e){let t=b.get(e);if(!t||!t.webrtcStuff)return i.warn("Invalid handle"),null;let n=t.webrtcStuff;if(!n.pc)return i.warn("Invalid PeerConnection"),null;let r=[],o=n.pc.getTransceivers();for(let e of o){let t=null;e.sender&&e.sender.track&&(t={mid:e.mid},t.type=e.sender.track.kind,t.id=e.sender.track.id,t.label=e.sender.track.label),t&&r.push(t)}return r}function U(e){let t=b.get(e);if(!t||!t.webrtcStuff)return i.warn("Invalid handle"),null;let n=t.webrtcStuff;if(!n.pc)return i.warn("Invalid PeerConnection"),null;let r=[],o=n.pc.getTransceivers();for(let e of o){let t=null;e.receiver&&e.receiver.track&&(t={mid:e.mid},t.type=e.receiver.track.kind,t.id=e.receiver.track.id,t.label=e.receiver.track.label),t&&r.push(t)}return r}function F(e,t,n,r){r="function"==typeof r?r:i.noop;let o=b.get(e);if(!o||!o.webrtcStuff)return i.warn("Invalid handle"),void r(0);let a=n?"remote":"local",s=o.webrtcStuff;if(s.volume[a]||(s.volume[a]={value:0}),s.pc&&s.pc.getStats&&("chrome"===i.webRTCAdapter.browserDetails.browser||"safari"===i.webRTCAdapter.browserDetails.browser)){let e=s.pc;if(t){let o=s.pc.getTransceivers().find(e=>e.mid===t&&"audio"===e.receiver.track.kind);if(!o)return i.warn("No audio transceiver with mid "+t),void r(0);if(n&&!o.receiver)return i.warn("Remote transceiver track unavailable"),void r(0);if(!n&&!o.sender)return i.warn("Local transceiver track unavailable"),void r(0);e=n?o.receiver:o.sender}return e.getStats().then(function(e){e.forEach(function(e){e&&"audio"===e.kind&&(n&&!e.remoteSource||!n&&"media-source"!==e.type||r(e.audioLevel?e.audioLevel:0))})}),s.volume[a].value}return i.warn("Getting the "+a+" volume unsupported by browser"),void r(0)}function V(e,t,n){let r=b.get(e);if(!r||!r.webrtcStuff)return i.warn("Invalid handle"),!0;let o=r.webrtcStuff;if(!o.pc)return i.warn("Invalid PeerConnection"),!0;if(!o.myStream)return i.warn("Invalid local MediaStream"),!0;if(n){if(!o.myStream.getVideoTracks()||0===o.myStream.getVideoTracks().length)return i.warn("No video track"),!0;if(t){let e=o.pc.getTransceivers().find(e=>e.mid===t&&"video"===e.receiver.track.kind);return e?e.sender&&e.sender.track?!e.sender.track.enabled:(i.warn("No video sender with mid "+t),!0):(i.warn("No video transceiver with mid "+t),!0)}return!o.myStream.getVideoTracks()[0].enabled}if(!o.myStream.getAudioTracks()||0===o.myStream.getAudioTracks().length)return i.warn("No audio track"),!0;if(t){let e=o.pc.getTransceivers().find(e=>e.mid===t&&"audio"===e.receiver.track.kind);return e?e.sender&&e.sender.track?!e.sender.track.enabled:(i.warn("No audio sender with mid "+t),!0):(i.warn("No audio transceiver with mid "+t),!0)}return!o.myStream.getAudioTracks()[0].enabled}function J(e,t,n,r){let o=b.get(e);if(!o||!o.webrtcStuff)return i.warn("Invalid handle"),!1;let a=o.webrtcStuff;if(!a.pc)return i.warn("Invalid PeerConnection"),!1;if(!a.myStream)return i.warn("Invalid local MediaStream"),!1;if(n){if(!a.myStream.getVideoTracks()||0===a.myStream.getVideoTracks().length)return i.warn("No video track"),!1;if(t){let e=a.pc.getTransceivers().find(e=>e.mid===t&&"video"===e.receiver.track.kind);if(!e)return i.warn("No video transceiver with mid "+t),!1;if(!e.sender||!e.sender.track)return i.warn("No video sender with mid "+t),!1;e.sender.track.enabled=!r}else for(const e of a.myStream.getVideoTracks())e.enabled=!r}else{if(!a.myStream.getAudioTracks()||0===a.myStream.getAudioTracks().length)return i.warn("No audio track"),!1;if(t){let e=a.pc.getTransceivers().find(e=>e.mid===t&&"audio"===e.receiver.track.kind);if(!e)return i.warn("No audio transceiver with mid "+t),!1;if(!e.sender||!e.sender.track)return i.warn("No audio sender with mid "+t),!1;e.sender.track.enabled=!r}else for(const e of a.myStream.getAudioTracks())e.enabled=!r}return!0}function W(e,t){let n=b.get(e);if(!n||!n.webrtcStuff)return i.warn("Invalid handle"),"Invalid handle";let r=n.webrtcStuff;if(!r.pc)return"Invalid PeerConnection";if(r.pc.getStats){let e=r.pc,n=t||"default";if(t){let n=r.pc.getTransceivers().find(e=>e.mid===t&&"video"===e.receiver.track.kind);if(!n)return i.warn("No video transceiver with mid "+t),"No video transceiver with mid "+t;if(!n.receiver)return i.warn("No video receiver with mid "+t),"No video receiver with mid "+t;e=n.receiver}return r.bitrate[n]||(r.bitrate[n]={timer:null,bsnow:null,bsbefore:null,tsnow:null,tsbefore:null,value:"0 kbits/sec"}),r.bitrate[n].timer?r.bitrate[n].value:(i.log("Starting bitrate timer"+(t?" for mid "+t:"")+" (via getStats)"),r.bitrate[n].timer=setInterval(function(){e.getStats().then(function(e){e.forEach(function(e){if(!e)return;let t=!1;if(("video"===e.mediaType||"video"===e.kind||e.id.toLowerCase().indexOf("video")>-1)&&"inbound-rtp"===e.type&&e.id.indexOf("rtcp")<0?t=!0:"ssrc"!=e.type||!e.bytesReceived||"VP8"!==e.googCodecName&&""!==e.googCodecName||(t=!0),t)if(r.bitrate[n].bsnow=e.bytesReceived,r.bitrate[n].tsnow=e.timestamp,null===r.bitrate[n].bsbefore||null===r.bitrate[n].tsbefore)r.bitrate[n].bsbefore=r.bitrate[n].bsnow,r.bitrate[n].tsbefore=r.bitrate[n].tsnow;else{let e=r.bitrate[n].tsnow-r.bitrate[n].tsbefore;"safari"===i.webRTCAdapter.browserDetails.browser&&(e/=1e3);let t=Math.round(8*(r.bitrate[n].bsnow-r.bitrate[n].bsbefore)/e);"safari"===i.webRTCAdapter.browserDetails.browser&&(t=parseInt(t/1e3)),r.bitrate[n].value=t+" kbits/sec",r.bitrate[n].bsbefore=r.bitrate[n].bsnow,r.bitrate[n].tsbefore=r.bitrate[n].tsnow}})})},1e3),"0 kbits/sec")}return i.warn("Getting the video bitrate unsupported by browser"),"Feature unsupported by browser"}function K(e,t,n){let r=b.get(e);if(!r||!r.webrtcStuff)return void i.warn("Invalid handle");let o=r.webrtcStuff;if(!o.pc)return void i.warn("Invalid PeerConnection");let a=o.pc.getTransceivers().find(e=>e.mid===t);if(!a)return void i.warn("No transceiver with mid",t);if(!a.sender)return void i.warn("No sender for transceiver with mid",t);let s=a.sender.getParameters();s&&s.encodings&&0!==s.encodings.length?s.encodings.length>1?i.warn("Ignoring bitrate for simulcast track, use sendEncodings for that"):isNaN(n)||n<0?i.warn("Invalid bitrate (must be a positive integer)"):(s.encodings[0].maxBitrate=n,a.sender.setParameters(s)):i.warn("No parameters encodings")}function z(e){i.error("WebRTC error:",e)}function $(e,r){i.log("Cleaning WebRTC stuff");let o=b.get(e);if(!o)return;let a=o.webrtcStuff;if(a){if(!0===r){let r={janus:"hangup",transaction:i.randomString(12)};o.token&&(r.token=o.token),h&&(r.apisecret=h),i.debug("Sending hangup request (handle="+e+"):"),i.debug(r),t?(r.session_id=S,r.handle_id=e,n.send(JSON.stringify(r))):i.httpAPICall(c+"/"+S+"/"+e,{verb:"POST",withCredentials:p,body:r})}a.volume&&(a.volume.local&&a.volume.local.timer&&clearInterval(a.volume.local.timer),a.volume.remote&&a.volume.remote.timer&&clearInterval(a.volume.remote.timer));for(let e in a.bitrate)a.bitrate[e].timer&&clearInterval(a.bitrate[e].timer);a.bitrate={},!a.streamExternal&&a.myStream&&(i.log("Stopping local stream tracks"),i.stopAllTracks(a.myStream)),a.streamExternal=!1,a.myStream=null;try{a.pc.close()}catch(e){}a.pc=null,a.candidates=null,a.mySdp=null,a.remoteSdp=null,a.iceDone=!1,a.dataChannel={},a.dtmfSender=null,a.insertableStreams=!1,a.externalEncryption=!1}o.oncleanup()}_(e),this.getServer=function(){return c},this.isConnected=function(){return y},this.reconnect=function(e){(e=e||{}).success="function"==typeof e.success?e.success:i.noop,e.error="function"==typeof e.error?e.error:i.noop,e.reconnect=!0,_(e)},this.getSessionId=function(){return S},this.getInfo=function(e){!function(e){if(e=e||{},e.success="function"==typeof e.success?e.success:i.noop,e.error="function"==typeof e.error?e.error:i.noop,i.log("Getting info on Janus instance"),!y)return i.warn("Is the server down? (connected=false)"),void e.error("Is the server down? (connected=false)");let r=i.randomString(12),o={janus:"info",transaction:r};m&&(o.token=m);h&&(o.apisecret=h);if(t)return w.set(r,function(t){i.log("Server info:"),i.debug(t),"server_info"!==t.janus&&i.error("Ooops: "+t.error.code+" "+t.error.reason),e.success(t)}),void n.send(JSON.stringify(o));i.httpAPICall(c,{verb:"POST",withCredentials:p,body:o,success:function(t){i.log("Server info:"),i.debug(t),"server_info"!==t.janus&&i.error("Ooops: "+t.error.code+" "+t.error.reason),e.success(t)},error:function(t,n){i.error(t+":",n),""===n?e.error(t+": Is the server down?"):e.error(t+": "+n)}})}(e)},this.destroy=function(a){!function(a){a=a||{},a.success="function"==typeof a.success?a.success:i.noop,a.error="function"==typeof a.error?a.error:i.noop;let s=!0===a.unload,d=!0;void 0!==a.notifyDestroyed&&null!==a.notifyDestroyed&&(d=!0===a.notifyDestroyed);let l=!0===a.cleanupHandles;if(i.log("Destroying session "+S+" (unload="+s+")"),!S)return i.warn("No session to destroy"),a.success(),void(d&&e.destroyed());if(l)for(const e of b.keys())D(e,{noRequest:!0});if(!y)return i.warn("Is the server down? (connected=false)"),S=null,void a.success();let u={janus:"destroy",transaction:i.randomString(12)};m&&(u.token=m);h&&(u.apisecret=h);if(s)return t?(n.onclose=null,n.close(),n=null):navigator.sendBeacon(c+"/"+S,JSON.stringify(u)),i.log("Destroyed session:"),S=null,y=!1,a.success(),void(d&&e.destroyed());if(t){u.session_id=S;let t=function(){for(let e in r)n.removeEventListener(e,r[e]);n.removeEventListener("message",i),n.removeEventListener("error",s),o&&clearTimeout(o),n.close()},i=function(n){let r=JSON.parse(n.data);r.session_id==u.session_id&&r.transaction==u.transaction&&(t(),a.success(),d&&e.destroyed())},s=function(){t(),a.error("Failed to destroy the server: Is the server down?"),d&&e.destroyed()};return n.addEventListener("message",i),n.addEventListener("error",s),void(1===n.readyState?n.send(JSON.stringify(u)):s())}i.httpAPICall(c+"/"+S,{verb:"POST",withCredentials:p,body:u,success:function(t){i.log("Destroyed session:"),i.debug(t),S=null,y=!1,"success"!==t.janus&&i.error("Ooops: "+t.error.code+" "+t.error.reason),a.success(),d&&e.destroyed()},error:function(t,n){i.error(t+":",n),S=null,y=!1,a.success(),d&&e.destroyed()}})}(a)},this.attach=function(e){!function(e){if(e=e||{},e.success="function"==typeof e.success?e.success:i.noop,e.error="function"==typeof e.error?e.error:i.noop,e.dataChannelOptions=e.dataChannelOptions||{ordered:!0},e.consentDialog="function"==typeof e.consentDialog?e.consentDialog:i.noop,e.connectionState="function"==typeof e.connectionState?e.connectionState:i.noop,e.iceState="function"==typeof e.iceState?e.iceState:i.noop,e.mediaState="function"==typeof e.mediaState?e.mediaState:i.noop,e.webrtcState="function"==typeof e.webrtcState?e.webrtcState:i.noop,e.slowLink="function"==typeof e.slowLink?e.slowLink:i.noop,e.onmessage="function"==typeof e.onmessage?e.onmessage:i.noop,e.onlocaltrack="function"==typeof e.onlocaltrack?e.onlocaltrack:i.noop,e.onremotetrack="function"==typeof e.onremotetrack?e.onremotetrack:i.noop,e.ondata="function"==typeof e.ondata?e.ondata:i.noop,e.ondataopen="function"==typeof e.ondataopen?e.ondataopen:i.noop,e.oncleanup="function"==typeof e.oncleanup?e.oncleanup:i.noop,e.ondetached="function"==typeof e.ondetached?e.ondetached:i.noop,!y)return i.warn("Is the server down? (connected=false)"),void e.error("Is the server down? (connected=false)");let r=e.plugin;if(!r)return i.error("Invalid plugin"),void e.error("Invalid plugin");let o=e.opaqueId,a=e.loopIndex,s=e.token?e.token:m,d=i.randomString(12),l={janus:"attach",plugin:r,opaque_id:o,loop_index:a,transaction:d};s&&(l.token=s);h&&(l.apisecret=h);if(t)return w.set(d,function(t){if(i.debug(t),"success"!==t.janus)return i.error("Ooops: "+t.error.code+" "+t.error.reason),void e.error("Ooops: "+t.error.code+" "+t.error.reason);let n=t.data.id;i.log("Created handle: "+n);let o={session:C,plugin:r,id:n,token:s,detached:!1,webrtcStuff:{started:!1,myStream:null,streamExternal:!1,mySdp:null,mediaConstraints:null,pc:null,dataChannelOptions:e.dataChannelOptions,dataChannel:{},dtmfSender:null,trickle:!0,iceDone:!1,bitrate:{}},getId:function(){return n},getPlugin:function(){return r},getVolume:function(e,t){return F(n,e,!0,t)},getRemoteVolume:function(e,t){return F(n,e,!0,t)},getLocalVolume:function(e,t){return F(n,e,!1,t)},isAudioMuted:function(e){return V(n,e,!1)},muteAudio:function(e){return J(n,e,!1,!0)},unmuteAudio:function(e){return J(n,e,!1,!1)},isVideoMuted:function(e){return V(n,e,!0)},muteVideo:function(e){return J(n,e,!0,!0)},unmuteVideo:function(e){return J(n,e,!0,!1)},getBitrate:function(e){return W(n,e)},setMaxBitrate:function(e,t){return K(n,e,t)},send:function(e){P(n,e)},data:function(e){A(n,e)},dtmf:function(e){O(n,e)},consentDialog:e.consentDialog,connectionState:e.connectionState,iceState:e.iceState,mediaState:e.mediaState,webrtcState:e.webrtcState,slowLink:e.slowLink,onmessage:e.onmessage,createOffer:function(e){L(n,!0,e)},createAnswer:function(e){L(n,!1,e)},handleRemoteJsep:function(e){M(n,e)},replaceTracks:function(e){x(n,e)},getLocalTracks:function(){return G(n)},getRemoteTracks:function(){return U(n)},onlocaltrack:e.onlocaltrack,onremotetrack:e.onremotetrack,ondata:e.ondata,ondataopen:e.ondataopen,oncleanup:e.oncleanup,ondetached:e.ondetached,hangup:function(e){$(n,!0===e)},detach:function(e){D(n,e)}};b.set(n,o),e.success(o)}),l.session_id=S,void n.send(JSON.stringify(l));i.httpAPICall(c+"/"+S,{verb:"POST",withCredentials:p,body:l,success:function(t){if(i.debug(t),"success"!==t.janus)return i.error("Ooops: "+t.error.code+" "+t.error.reason),void e.error("Ooops: "+t.error.code+" "+t.error.reason);let n=t.data.id;i.log("Created handle: "+n);let o={session:C,plugin:r,id:n,token:s,detached:!1,webrtcStuff:{started:!1,myStream:null,streamExternal:!1,mySdp:null,mediaConstraints:null,pc:null,dataChannelOptions:e.dataChannelOptions,dataChannel:{},dtmfSender:null,trickle:!0,iceDone:!1,bitrate:{}},getId:function(){return n},getPlugin:function(){return r},getVolume:function(e,t){return F(n,e,!0,t)},getRemoteVolume:function(e,t){return F(n,e,!0,t)},getLocalVolume:function(e,t){return F(n,e,!1,t)},isAudioMuted:function(e){return V(n,e,!1)},muteAudio:function(e){return J(n,e,!1,!0)},unmuteAudio:function(e){return J(n,e,!1,!1)},isVideoMuted:function(e){return V(n,e,!0)},muteVideo:function(e){return J(n,e,!0,!0)},unmuteVideo:function(e){return J(n,e,!0,!1)},getBitrate:function(e){return W(n,e)},setMaxBitrate:function(e,t){return K(n,e,t)},send:function(e){P(n,e)},data:function(e){A(n,e)},dtmf:function(e){O(n,e)},consentDialog:e.consentDialog,connectionState:e.connectionState,iceState:e.iceState,mediaState:e.mediaState,webrtcState:e.webrtcState,slowLink:e.slowLink,onmessage:e.onmessage,createOffer:function(e){L(n,!0,e)},createAnswer:function(e){L(n,!1,e)},handleRemoteJsep:function(e){M(n,e)},replaceTracks:function(e){x(n,e)},getLocalTracks:function(){return G(n)},getRemoteTracks:function(){return U(n)},onlocaltrack:e.onlocaltrack,onremotetrack:e.onremotetrack,ondata:e.ondata,ondataopen:e.ondataopen,oncleanup:e.oncleanup,ondetached:e.ondetached,hangup:function(e){$(n,!0===e)},detach:function(e){D(n,e)}};b.set(n,o),e.success(o)},error:function(t,n){i.error(t+":",n),""===n?e.error(t+": Is the server down?"):e.error(t+": "+n)}})}(e)},this.keepalive=()=>function(){if(!o)return;if(!c||!t||!y)return void console.log("server:",c,",","websockets:",t,",","connected:",y);let e={janus:"keepalive",session_id:S,transaction:i.randomString(12)};m&&(e.token=m);h&&(e.apisecret=h);n.send(JSON.stringify(e))}()}i.useDefaultDependencies=function(e){let t=e&&e.fetch||fetch,n=e&&e.Promise||Promise,r=e&&e.WebSocket||WebSocket;return{newWebSocket:function(e,t){return new r(e,t)},extension:e&&e.extension||o,isArray:function(e){return Array.isArray(e)},webRTCAdapter:e&&e.adapter||adapter,httpAPICall:function(e,r){let o={method:r.verb,headers:{Accept:"application/json, text/plain, */*"},cache:"no-cache"};"POST"===r.verb&&(o.headers["Content-Type"]="application/json"),void 0!==r.withCredentials&&(o.credentials=!0===r.withCredentials?"include":r.withCredentials?r.withCredentials:"omit"),r.body&&(o.body=JSON.stringify(r.body));let a=t(e,o).catch(function(e){return n.reject({message:"Probably a network error, is the server down?",error:e})});if(r.timeout){let e=new n(function(e,t){let n=setTimeout(function(){return clearTimeout(n),t({message:"Request timed out",timeout:r.timeout})},r.timeout)});a=n.race([a,e])}return a.then(function(e){return e.ok?typeof r.success==typeof i.noop?e.json().then(function(e){try{r.success(e)}catch(e){i.error("Unhandled httpAPICall success callback error",e)}},function(t){return n.reject({message:"Failed to parse response body",error:t,response:e})}):void 0:n.reject({message:"API call failed",response:e})}).catch(function(e){typeof r.error==typeof i.noop&&r.error(e.message||"<< internal error >>",e)}),a}}},i.useOldDependencies=function(e){let t=e&&e.jQuery||jQuery,n=e&&e.WebSocket||WebSocket;return{newWebSocket:function(e,t){return new n(e,t)},isArray:function(e){return t.isArray(e)},extension:e&&e.extension||o,webRTCAdapter:e&&e.adapter||adapter,httpAPICall:function(e,n){let r=void 0!==n.body?{contentType:"application/json",data:JSON.stringify(n.body)}:{},o=void 0!==n.withCredentials?{xhrFields:{withCredentials:n.withCredentials}}:{};return t.ajax(t.extend(r,o,{url:e,type:n.verb,cache:!1,dataType:"json",async:n.async,timeout:n.timeout,success:function(e){typeof n.success==typeof i.noop&&n.success(e)},error:function(e,t,r){typeof n.error==typeof i.noop&&n.error(t,r)}}))}}},i.mediaToTracks=function(e){let t=[];if(e){if(!e.keepAudio&&!1!==e.audio&&(void 0===e.audio||e.audio||e.audioSend||e.audioRecv||e.addAudio||e.replaceAudio||e.removeAudio)){let n={type:"audio"};e.removeAudio?n.remove=!0:(e.addAudio?n.add=!0:e.replaceAudio&&(n.replace=!0),!1!==e.audioSend&&(n.capture=e.audio||!0),!1!==e.audioRecv&&(n.recv=!0)),(n.remove||n.capture||n.recv)&&t.push(n)}if(!e.keepVideo&&!1!==e.video&&(void 0===e.video||e.video||e.videoSend||e.videoRecv||e.addVideo||e.replaceVideo||e.removeVideo)){let n={type:"video"};e.removeVideo?n.remove=!0:(e.addVideo?n.add=!0:e.replaceVideo&&(n.replace=!0),!1!==e.videoSend&&(n.capture=e.video||!0,["screen","window","desktop"].includes(n.capture)&&(n.type="screen",n.capture={video:{}},e.screenshareFrameRate&&(n.capture.frameRate=e.screenshareFrameRate),e.screenshareHeight&&(n.capture.height=e.screenshareHeight),e.screenshareWidth&&(n.capture.width=e.screenshareWidth))),!1!==e.videoRecv&&(n.recv=!0)),(n.remove||n.capture||n.recv)&&t.push(n)}e.data&&t.push({type:"data"})}else t.push({type:"audio",capture:!0,recv:!0}),t.push({type:"video",capture:!0,recv:!0});return t},i.trackConstraints=function(e){let t={};if(!e||!e.capture)return t;if("audio"===e.type)t.audio=e.capture;else if("video"===e.type)if((e.simulcast||e.svc)&&!0===e.capture&&(e.capture="hires"),!0===e.capture||"object"==typeof e.capture)t.video=e.capture;else{let n=0,r=0;"lowres"===e.capture?(n=320,r=240):"lowres-16:9"===e.capture?(n=320,r=180):"hires"===e.capture||"hires-16:9"===e.capture||"hdres"===e.capture?(n=1280,r=720):"fhdres"===e.capture?(n=1920,r=1080):"4kres"===e.capture?(n=3840,r=2160):"stdres"===e.capture?(n=640,r=480):"stdres-16:9"===e.capture?(n=640,r=360):(i.log("Default video setting is stdres 4:3"),n=640,r=480),t.video={width:{ideal:n},height:{ideal:r}}}else"screen"===e.type&&(t.video=e.capture);return t},i.noop=function(){},i.dataChanDefaultLabel="JanusDataChannel",i.endOfCandidates=null,i.stopAllTracks=function(e){try{let t=e.getTracks();for(let e of t)i.log(e),e&&!0!==e.dontStop&&e.stop()}catch(e){}},i.init=function(e){if((e=e||{}).callback="function"==typeof e.callback?e.callback:i.noop,i.initDone)e.callback();else{if(void 0===console.log&&(console.log=function(){}),i.trace=i.noop,i.debug=i.noop,i.vdebug=i.noop,i.log=i.noop,i.warn=i.noop,i.error=i.noop,!0===e.debug||"all"===e.debug)i.trace=console.trace.bind(console),i.debug=console.debug.bind(console),i.vdebug=console.debug.bind(console),i.log=console.log.bind(console),i.warn=console.warn.bind(console),i.error=console.error.bind(console);else if(Array.isArray(e.debug))for(let t of e.debug)switch(t){case"trace":i.trace=console.trace.bind(console);break;case"debug":i.debug=console.debug.bind(console);break;case"vdebug":i.vdebug=console.debug.bind(console);break;case"log":i.log=console.log.bind(console);break;case"warn":i.warn=console.warn.bind(console);break;case"error":i.error=console.error.bind(console);break;default:console.error("Unknown debugging option '"+t+"' (supported: 'trace', 'debug', 'vdebug', 'log', warn', 'error')")}i.log("Initializing library");let t=e.dependencies||i.useDefaultDependencies();i.isArray=t.isArray,i.webRTCAdapter=t.webRTCAdapter,i.httpAPICall=t.httpAPICall,i.newWebSocket=t.newWebSocket,i.extension=t.extension,i.extension.init(),i.listDevices=function(e,t){e="function"==typeof e?e:i.noop,t||(t={audio:!0,video:!0}),i.isGetUserMediaAvailable()?navigator.mediaDevices.getUserMedia(t).then(function(t){navigator.mediaDevices.enumerateDevices().then(function(n){i.debug(n),e(n),i.stopAllTracks(t)})}).catch(function(t){i.error(t),e([])}):(i.warn("navigator.mediaDevices unavailable"),e([]))},i.attachMediaStream=function(e,t){try{e.srcObject=t}catch(n){try{e.src=URL.createObjectURL(t)}catch(e){i.error("Error attaching stream to element",e)}}},i.reattachMediaStream=function(e,t){try{e.srcObject=t.srcObject}catch(n){try{e.src=t.src}catch(e){i.error("Error reattaching stream to element",e)}}};let n=["iPad","iPhone","iPod"].indexOf(navigator.platform)>=0?"pagehide":"beforeunload",r=window["on"+n];if(window.addEventListener(n,function(){i.log("Closing window");for(const[e,t]of i.sessions)t&&t.destroyOnUnload&&(i.log("Destroying session "+e),t.destroy({unload:!0,notifyDestroyed:!1}));r&&"function"==typeof r&&r()}),i.safariVp8=!1,i.safariVp9=!1,"safari"===i.webRTCAdapter.browserDetails.browser&&i.webRTCAdapter.browserDetails.version>=605)if(RTCRtpSender&&RTCRtpSender.getCapabilities&&RTCRtpSender.getCapabilities("video")&&RTCRtpSender.getCapabilities("video").codecs&&RTCRtpSender.getCapabilities("video").codecs.length){for(let e of RTCRtpSender.getCapabilities("video").codecs)e&&e.mimeType&&"video/vp8"===e.mimeType.toLowerCase()?i.safariVp8=!0:e&&e.mimeType&&"video/vp9"===e.mimeType.toLowerCase()&&(i.safariVp9=!0);i.safariVp8?i.log("This version of Safari supports VP8"):i.warn("This version of Safari does NOT support VP8: if you're using a Technology Preview, try enabling the 'WebRTC VP8 codec' setting in the 'Experimental Features' Develop menu")}else{let e=new RTCPeerConnection({});e.createOffer({offerToReceiveVideo:!0}).then(function(t){i.safariVp8=-1!==t.sdp.indexOf("VP8"),i.safariVp9=-1!==t.sdp.indexOf("VP9"),i.safariVp8?i.log("This version of Safari supports VP8"):i.warn("This version of Safari does NOT support VP8: if you're using a Technology Preview, try enabling the 'WebRTC VP8 codec' setting in the 'Experimental Features' Develop menu"),e.close(),e=null})}i.initDone=!0,e.callback()}},i.isWebrtcSupported=function(){return!!window.RTCPeerConnection},i.isGetUserMediaAvailable=function(){return navigator.mediaDevices&&navigator.mediaDevices.getUserMedia},i.randomString=function(e){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n="";for(let r=0;r<e;r++){let e=Math.floor(62*Math.random());n+=t.charAt(e)}return n};function a(e,t=1e4){const n=new Worker(((e=1e4)=>URL.createObjectURL(new Blob([`\n self.onmessage = (e) => {\n if (e.data === 'START') {\n // 每10秒发送一次心跳(避免过度耗电)\n setInterval(() => {\n self.postMessage('heartbeat');\n }, ${e});\n }\n };\n `])))(t));return n.postMessage("START"),n.onmessage=t=>{"heartbeat"===t.data&&(console.log("Worker active at:",new Date),e())},window.addEventListener("unload",()=>{n.terminate()}),n}const s={url:null,queue:[],timer:null,batchSize:20,flushInterval:5e3,push(e,t,n){const r=`[${(new Date).toLocaleString("zh-CN",{hour12:!1})}] [VoiceNine] [${t}]`;"warn"===e?console.warn(r,n):"error"===e?console.error(r,n):console.log(r,n)}};function c(e,t){s.push("info",e,t)}function d(e,t){s.push("warn",e,t)}function l(e,t,n){s.push("error",e,n?`${t} ${n}`:t)}const u={agentId:"",agentKey:"",companyId:"",agentType:"",token:"",wsServer:"",webrtcServer:"",sipServer:"",agentCode:"",sipPwd:"",groupId:"",groupIds:[]};const p=new class{instance=null;socket=null;connected=!1;janus=null;sipcall=null;stream=null;events={};seat={};callId=null;conference=null;conferenceList=[];status=e.LOGIN;lastStatus=e.LOGIN;reconnectState=null;autoAcceptTimer=null;code=0;msg=null;jsep=null;isHangup=!1;_userLogout=!1;constructor(){if(this.instance)return this.instance;this.instance=this,a(()=>{this._keepalive(),this.janus&&!this._userLogout&&this.janus?.keepalive()})}_init(e){this.seat={...u,...e},this.reconnectState=null,this._userLogout=!1,this._initMedia();const t=`${this.seat.wsServer}?token=${this.seat.token}`;this.connectWs(t)}_initMedia(){const e=document.getElementById("mediaContainer");e&&(e.parentNode.removeChild(e),c("_initMedia","清理旧的媒体容器"));const t=document.createElement("div");t.id="mediaContainer",t.style.width="0px",t.style.height="0px",t.style.position="absolute",t.style.top="0px",t.style.left="0px",t.style.zIndex="-1",t.style.visibility="hidden",t.style.overflow="hidden",document.body.appendChild(t);const n=document.createElement("audio");n.id="incomingcallAudio",n.loop=!0,n.src="https://r.hanfatong.com/voicenine/beep.mp3",t.appendChild(n);const r=document.createElement("audio");r.id="callEndAudio",r.loop=!1,r.src="https://r.hanfatong.com/voicenine/hangup.mp3",t.appendChild(r);const o=document.createElement("video");o.id="peerVideo",o.autoplay=!0,t.appendChild(o);const i=document.createElement("video");i.id="remoteVideo",i.autoplay=!0,t.appendChild(i)}_initJanus(){const{webrtcServer:t,sipServer:n}=this.seat;if(!t||!n)return void l("_initJanus","WebRTC server or SIP server is not configured.");let r={},o={},a=!1;i.init({debug:"all",callback:()=>{c("_initJanus","Janus initialized.");if(!i.isWebrtcSupported())return void d("_initJanus","No WebRTC support or not HTTPS.");this.trigger("connstate",{type:"janus",state:"connecting"});const n=new i({server:t,success:()=>{this.trigger("connstate",{type:"janus",state:"connected"}),n.attach({plugin:"janus.plugin.sip",opaqueId:"voicenine_"+i.randomString(16),success:e=>{c("_initJanus","SIP plugin attached."),this.sipcall=e;const t={request:"register",username:this.seat.agentCode,authuser:this.seat.agentCode,display_name:this.seat.agentCode,secret:this.seat.sipPwd};e.send({message:t}),this.sipcall=e,this.trigger("sipstate",{registered:null,username:this.seat.agentCode})},onmessage:(t,n)=>{i.debug(" ::: Got a message :::",t);const{call_id:r,result:o}=t;if(o?.event){const s=o.event;if(this.msg=null,this.jsep=null,"registration_failed"===s)d("_initJanus","SIP registration failed: "+o.code+" "+o.reason),this.trigger("sipstate",{registered:!1,code:o.code,reason:o.reason});else if("registered"===s)c("_initJanus","SIP registered: "+o.username),a||(a=!0,o.master_id),this.trigger("sipstate",{registered:!0,username:o.username});else if("calling"===s)c("_initJanus","calling...");else if("incomingcall"===s){c("_initJanus","incomingcall"),this.sipcall.callId=r,this.toggleRing(!0),this.msg=t,this.jsep=n;const o=(r=0)=>{2==this.seat.workType||this.status===e.OUT_CALL||this.status===e.OUT_CALLER_RING?(this.autoAcceptTimer&&clearTimeout(this.autoAcceptTimer),this.accept(t,n)):r<60&&(this.status===e.READY||this.status===e.NOT_READY||this.status===e.WORK_NOT_READY||this.status===e.AFTER||this.status===e.LOGIN)?(this.autoAcceptTimer&&clearTimeout(this.autoAcceptTimer),this.autoAcceptTimer=setTimeout(()=>o(r+1),50)):(d("mayAutoAccept",`状态 ${this.status} retries=${r},decline incoming call`),this.sipcall.send({message:{request:"decline",code:603}}))};2==this.seat.loginType&&o()}else if("accepting"===s);else if("progress"===s)c("_initJanus","progress"),n&&this.sipcall.handleRemoteJsep({jsep:n});else if("accepted"===s)c("_initJanus","accepted"),this.toggleRing(!1),n&&this.sipcall.handleRemoteJsep({jsep:n}),this.sipcall.callId=r;else if("updatingcall"===s){c("_initJanus","updatingcall");const e=n.sdp.indexOf("m=audio ")>-1,t=n.sdp.indexOf("m=video ")>-1,r=[];e&&!this.sipcall.doAudio&&(this.sipcall.doAudio=!0,r.push({type:"audio",capture:!0,recv:!0})),t&&!this.sipcall.doVideo&&(this.sipcall.doVideo=!0,r.push({type:"video",capture:!0,recv:!0})),this.sipcall.createAnswer({jsep:n,tracks:r,success:n=>{i.debug("Got SDP "+n.type+"! audio="+e+", video="+t+":",n);this.sipcall.send({message:{request:"update"},jsep:n})},error:e=>{this.trigger("error",e),l("createAnswer","WebRTC error",e)}})}else if("message"===s);else if("info"===s);else if("notify"===s);else if("transfer"===s);else if("hangup"===s){c("_initJanus",`hangup: ${o.code} ${o.reason}`);const e=o.reason||"",t=this.status&&this.status.includes("TALKING");if(e.includes("DTLS")&&this._dtlsRebuildNeeded&&this.connected&&t)return void this._onDtlsAlert();this._dtlsRebuildNeeded=!1,setTimeout(()=>{this.toggleRing(!1)},0),setTimeout(()=>{this.sipcall&&this.sipcall.hangup()},150)}}},onlocaltrack:(e,t)=>{c("onlocaltrack",`${t?"added":"removed"} kind=${e.kind}`);const n=e.id.replace(/[{}]/g,"");if(!t){if(this.stream=r[n],this.stream)try{const e=this.stream.getTracks(),t=e.some(e=>"audio"===e.kind&&e.getSettings().deviceId&&e.label.toLowerCase().includes("bluetooth"));setTimeout(()=>{e.forEach(e=>{e&&"ended"!==e.readyState&&("audio"===e.kind?(e.enabled=!1,setTimeout(()=>e.stop(),50)):e.stop())})},t?300:100)}catch(e){l("onlocaltrack","停止本地轨道失败",e)}return e.kind,void delete r[n]}if(this.stream=r[n],!this.stream){if("audio"===e.kind);else{this.stream=new MediaStream([e]),r[n]=this.stream;let t=document.getElementById("remoteVideo");i.attachMediaStream(t,this.stream)}"completed"!==this.sipcall.webrtcStuff.pc.iceConnectionState&&this.sipcall.webrtcStuff.pc.iceConnectionState}},onremotetrack:function(e,t,n){if(n&&"audio"===e.kind){this.stream=new MediaStream([e]),o[t]=this.stream;let n=document.getElementById("peerVideo");i.attachMediaStream(n,this.stream)}},oncleanup:()=>{c("oncleanup","cleanup notification"),setTimeout(()=>{this.sipcall&&(delete this.sipcall.callId,delete this.sipcall.doAudio)},50),setTimeout(()=>{Object.values(r).forEach(e=>{if(e){e.getTracks().forEach(e=>{"ended"!==e.readyState&&e.stop()})}})},100),setTimeout(()=>{r={},o={},this.stream=null,this._iceRestarting=!1,this._dtlsRebuildNeeded=!1,this._iceRestartCooldown=null},200)},error:e=>{l("_initJanus","attach plugin error",e)},consentDialog:function(e){},webrtcTimeout:function(e){c("webrtcTimeout",e)},iceState:e=>{c("iceState",e),"disconnected"===e||"failed"===e?this._iceRestart(e):"connected"!==e&&"completed"!==e||this._onIceRestartSuccess()},mediaState:(e,t,n)=>{c("mediaState",`${e} ${t?"started":"stopped"} mid=${n}`),"audio"===e&&t&&this._iceRestarting&&this._onIceRestartSuccess()},webrtcState:e=>{c("webrtcState",e?"up":"down")},slowLink:function(e,t,n){d("slowLink",`${e?"sending":"receiving"} lost=${t} mid=${n}`)}})},error:e=>{l("_initJanus","janus session error",e),this.trigger("connstate",{type:"janus",state:"failed",reason:e}),this.connected&&!this._userLogout&&(d("_initJanus","Janus session 断开,WS 在线,5s 后重建 Janus"),setTimeout(()=>{this.connected&&this._initJanus()},5e3))},destroyed:()=>{c("_initJanus","destroyed")}});this.janus=n,window.Janus=i}})}_keepalive(){if(!this.socket||!this.connected||this.socket.readyState!==WebSocket.OPEN)return;let e={cmd:"ping",agentKey:this.seat.agentKey,sequence:(new Date).getTime()};this.echo(JSON.stringify(e))}accept(e,t){(0,this.sipcall.createAnswer)({jsep:t,media:{audio:!0,video:!1},success:e=>{this.sipcall.send({message:{request:"accept"},jsep:e})},error:e=>{this.trigger("error",e),l("accept","WebRTC error",e);this.sipcall.send({message:{request:"decline",code:480}})}}),this.autoAcceptTimer&&clearTimeout(this.autoAcceptTimer)}echo(e){if(this.socket&&this.socket.readyState===WebSocket.OPEN){try{const t=JSON.parse(e);"ping"!==t.cmd&&c("echo",`cmd=${t.cmd} agentKey=${t.agentKey||""}`)}catch{c("echo","发送消息")}this.socket.send(e)}else d("echo","WebSocket 未连接,消息丢弃")}toggleRing(e){const t=document.getElementById("incomingcallAudio");e?t.play():t.pause()}playEndRing(){document.getElementById("callEndAudio").play()}connectWs(t){if(c("connectWs","连接WebSocket: "+t.split("?")[0]),!window.WebSocket)return void alert("您的浏览器不支持WebSocket协议!");this.trigger("connstate",{type:"ws",state:"connecting"});const n=new WebSocket(t);this.socket=n,n.onmessage=t=>{const n=JSON.parse(t.data);"PONG"!==n.type&&c("onmessage",`type=${n.type} code=${n.code} agentKey=${n.agentKey||""}`),this.onmessage(n);let r=n.type;e[r]&&(0===n.code&&(this.lastStatus=this.status,this.status=r,c("onmessage",`状态变更: ${this.lastStatus} -> ${this.status}`)),this.code=n.code,this.handleStatusChange(n))},n.onopen=()=>{c("connectWs","WebSocket connection opened."),this.clearReconectStatus(),this.sendAction(e.LOGIN),this.connected=!0,this.trigger("connstate",{type:"ws",state:"connected"})},n.onclose=e=>{c("connectWs",`WebSocket connection closed, Code: ${e.code}${e.reason?", Reason: "+e.reason:""}`),this.reconectInterval&&clearInterval(this.reconectInterval),this.connected=!1;this.trigger("logout",this.code),this.trigger("connstate",{type:"ws",state:"closed",code:e.code,reason:e.reason}),2===this.seat.loginType&&this.janus?.destroy(),[1111,1403,1105,1417].includes(this.code)?c("connectWs","不自动重连, code: "+this.code):this._userLogout||1e3===e.code&&"Bye"===e.reason?c("connectWs","主动登出,不自动重连"):this.reconectInterval=setInterval(()=>{2===this.seat.loginType&&this.janus?.destroy();const e=`${this.seat.wsServer}?token=${this.seat.token}`;this.connectWs(e)},5e3)}}changeStatus(e){this.echo(`{"cmd":"${e}", "agentKey": "${this.seat.agentKey}", "sequence": ${(new Date).getTime()} }`),this.afterPhoneInterval&&window.clearInterval(this.afterPhoneInterval)}handleStatusChange(t){const{type:n,message:r,code:o,data:i}=t;if(i&&i.callId&&(this.callId=i.callId),i&&i.conference&&(this.conference=i.conference),i&&i.conferenceList?this.conferenceList=i.conferenceList:this.conferenceList=[],n===e.LOGIN)2===this.seat.loginType&&0===o&&this._initJanus(),null==this.reconnectState?this.sendAction(i.loginState):this.sendAction(this.reconnectState);else if(n===e.AFTER){this.lastStatus.includes("TALKING")&&(this.isHangup?this.isHangup=!1:this.playEndRing()),2===i.loginType&&0===i.answerTime&&("404"!==i.sipStatus&&"483"!==i.sipStatus||this._initJanus());const t=i.afterInterval||3;this.afterPhoneInterval=setTimeout(()=>{this.status===e.AFTER&&(c("handleStatusChange","话后自动空闲"),this.sendAction(e.READY))},1e3*t)}else n===e.OUT_CALL||(n===e.READY||n===e.NOT_READY||n===e.WORK_NOT_READY)&&(this.reconnectState=n);this.trigger("state",t),this.trigger(n,t)}sendAction(e,n){let r={cmd:e,agentKey:this.seat.agentKey,sequence:(new Date).getTime()};if(e===t.login)r={...r,loginType:this.seat.loginType,workType:this.seat.workType},this.status&&this.status.includes("TALKING")&&(r.callId=this.callId);else if(e===t.call){this.afterPhoneInterval&&window.clearInterval(this.afterPhoneInterval);const{telNum:e,display:t="",followData:o}=n||{};r={...r,called:e,display:t,callType:1,followData:o||{}}}else if(e===t.transfer){let{transferValue:e,transferType:t="4"}=n||{};e.includes("@")&&(t="3"),r={...r,transferType:t,transferValue:e}}else if(e===t.consult){const{consultValue:e}=n||{};let t="2";e.includes("@")&&(t="4"),r={...r,callId:this.callId,transferType:t,consultValue:e}}else if(e===t.consult_cancel);else if(e===t.consult_party)r.callId=this.callId;else if(e===t.consult_transfer)r.callId=this.callId;else if(e===t.busy_work){const{busyDesc:e}=n||{};r={...r,busyDesc:e,callId:this.callId}}else if(e===t.ready)this.afterPhoneInterval&&window.clearInterval(this.afterPhoneInterval);else if(e===t.busy)this.afterPhoneInterval&&window.clearInterval(this.afterPhoneInterval);else if(e===t.conference_remove){const{deviceId:t,memberId:o,username:i}=n||{};r={cmd:e,callId:this.callId,deviceId:t,conference:this.conference,memberId:o,username:i}}else{if(e===t.logout){this._userLogout=!0;const e=JSON.stringify(r);return this.echo(e),void(2===this.seat.loginType&&this.janus?.destroy())}e===t.followdata?r={...r,callId:this.callId,followData:n.followData||{}}:e===t.hangup&&(this.isHangup=!0,this.callId&&(r={...r,callId:this.callId}))}const o=JSON.stringify(r);this.echo(o)}clearReconectStatus(){this.reconectInterval&&clearInterval(this.reconectInterval)}_iceRestart(e){if(!(this.status&&this.status.includes("TALKING"))||!this.connected)return;const t=Date.now();this._iceRestartCooldown&&t<this._iceRestartCooldown?d("_iceRestart",`ICE ${e},冷却期内跳过(剩余 ${this._iceRestartCooldown-t}ms)`):(d("_iceRestart",`ICE ${e},尝试 ICE restart 恢复通话`),this.trigger("icestate",{state:"disconnected"}),this.sipcall.createOffer({iceRestart:!0,tracks:[{type:"audio",capture:!0,recv:!0}],success:e=>{c("_iceRestart","offer 创建成功,发送 update"),this._iceRestarting=!0,this._dtlsRebuildNeeded=!0,this._iceRestartCooldown=Date.now()+15e3,this.trigger("icestate",{state:"reconnecting"}),this.sipcall.send({message:{request:"update"},jsep:e})},error:e=>{l("_iceRestart","ICE restart 失败",e),this.trigger("icestate",{state:"failed"})}}))}_onIceRestartSuccess(){this._iceRestarting&&(this._iceRestarting=!1,c("_onIceRestartSuccess","ICE 重连成功"),this.trigger("icestate",{state:"reconnected"}))}_onDtlsAlert(){this._dtlsRebuildNeeded=!1,this._iceRestarting=!1,d("_onDtlsAlert","DTLS alert,重建 Janus"),this.trigger("icestate",{state:"failed",reason:"dtls_alert"}),setTimeout(()=>{this.connected&&this._initJanus()},500)}on(e,t){this.events[e]||(c("on","订阅事件: "+e),this.events[e]=[]),this.events[e].push(t)}trigger(e,t){this.events[e]&&(c("trigger","触发事件: "+e),this.events[e].forEach(e=>e(t)))}onmessage(e){this.trigger("message",e)}datelog(){var e=new Date,t=e.getFullYear(),n=e.getMonth()+1,r=e.getDate(),o=e.getHours(),i=e.getMinutes(),a=e.getSeconds(),s=e.getMilliseconds();return n<10&&(n="0"+n),r<10&&(r="0"+r),o<10&&(o="0"+o),i<10&&(i="0"+i),a<10&&(a="0"+a),s<10?s+="00":s<100&&(s+="0"),t+"-"+n+"-"+r+" "+o+":"+i+":"+a+"."+s}};class f{static _instance=null;static _version_="1.4.6";static _enum_={state:e,btn:t,label:n};constructor(){if(f._instance)return f._instance;f._instance=this,console.log("[VoiceNine] version:",f._version_),this.on("state",e=>this._stateHandler(e))}get version(){return f._version_}get status(){return p.status}get enum(){return f._enum_}init(e){console.log("["+p.datelog()+"] voice9 init",e),p._init(e)}logout(){p.sendAction(t.logout)}setBusy(){p.sendAction(t.busy)}setReady(){p.sendAction(t.ready)}setWorkNotReady(e){p.sendAction(t.busy_work,{busyDesc:e})}call(n,r={}){const o=[e.LOGIN,e.READY,e.NOT_READY,e.WORK_NOT_READY,e.AFTER];if(!p.connected)return{success:!1,reason:"ws_disconnected",message:"WebSocket 未连接"};if(!o.includes(p.status))return{success:!1,reason:"invalid_state",message:`当前状态不允许外呼: ${p.status}`};if(2===p.seat.loginType){if(!p.sipcall)return{success:!1,reason:"webrtc_not_ready",message:"WebRTC 未初始化"};const e=p.sipcall.webrtcStuff?.pc?.iceConnectionState;if(e&&"connected"!==e&&"completed"!==e&&"new"!==e)return{success:!1,reason:"ice_disconnected",message:`ICE 连接异常: ${e}`}}return p.sendAction(t.call,{telNum:n,...r}),{success:!0}}answer(){p.accept(p.msg,p.jsep)}sendDtmf(e){const t={cmd:"dtmf",dtmf:e,callId:p.callId,agentKey:p.seat.agentKey,sequence:(new Date).getTime()};p.echo(JSON.stringify(t))}hangup(){p.sendAction(t.hangup)}transfer(e,n={}){p.sendAction(t.transfer,{transferValue:e,...n})}consult(e,n={}){p.sendAction(t.consult,{telNum:e,...n})}cancelConsult(){p.sendAction(t.consult_cancel)}stopConsult(){p.sendAction(t.consult_stop)}consultTransfer(e,n={}){p.sendAction(t.consult_transfer,{transferValue:e,...n})}consultParty(){p.sendAction(t.consult_party)}mute(){p.sendAction(t.mute)}muteCancel(){p.sendAction(t.mute_cancel)}hold(){p.sendAction(t.hold)}holdCancel(){p.sendAction(t.hold_cancel)}monitor(e,t){const n={cmd:"MONITOR_CALL",callId:t,agentKey:p.seat.agentKey,monitorAgent:e,sequence:(new Date).getTime()};p.echo(JSON.stringify(n))}intercept(){p.sendAction("INTERCEPT_CALL")}barge(e,t){const n={cmd:"BARGE_CALL",callId:t,agentKey:p.seat.agentKey,monitorAgent:e,sequence:(new Date).getTime()};p.echo(JSON.stringify(n))}coach(e,t){const n={cmd:"COACH_CALL",callId:t,agentKey:p.seat.agentKey,monitorAgent:e,sequence:(new Date).getTime()};p.echo(JSON.stringify(n))}updateFollowData(e){const t={cmd:"UPDATE_FOLLOWDATA",followData:e,callId:p.callId,agentKey:p.seat.agentKey,sequence:(new Date).getTime()};p.echo(JSON.stringify(t))}action(e,t){p.sendAction(e,t)}message(e){p.echo(JSON.stringify(e))}on(e,t){p.on(e,t)}off(e,t){if(!p.events[e])return;if(!t)return void(p.events[e]=[]);const n=p.events[e].indexOf(t);n>-1&&p.events[e].splice(n,1)}emit(e,t){p.trigger(e,t)}_stateHandler(t){const{type:n,code:o}=t;if(p.events.btnstate){const e=r[n]||[];p.events.btnstate.forEach(t=>t(e))}if(p.events.agentstate){let t=n;t===e.LOGIN&&0!==Number(o)&&(t=""),p.events.agentstate.forEach(e=>e(t))}}}export{f as VoiceNine};
1
+ const e={LOGIN:"LOGIN",LOGOUT:"LOGOUT",READY:"READY",NOT_READY:"NOT_READY",WORK_NOT_READY:"WORK_NOT_READY",AFTER:"AFTER",OUT_CALL:"OUT_CALL",OUT_CALLER_RING:"OUT_CALLER_RING",OUT_CALLED_RING:"OUT_CALLED_RING",PLAY_AGENT_ID:"PLAY_AGENT_ID",TALKING:"TALKING",MUTE_TALKING:"MUTE_TALKING",HOLD_TALKING:"HOLD_TALKING",INNER_CALL_RING:"INNER_CALL_RING",INNER_CALL_TALKING:"INNER_CALL_TALKING",INBOUND_RING:"INBOUND_RING",TRANSFER:"TRANSFER",TRANSFERED_RING:"TRANSFERED_RING",TRANSFER_OUT_RING:"TRANSFER_OUT_RING",TRANSFERED_TALKING:"TRANSFERED_TALKING",CONSULT:"CONSULT",CONSULT_RING:"CONSULT_RING",CONSULT_OUT_RING:"CONSULT_OUT_RING",CONSULT_IVR:"CONSULT_IVR",CONSULT_TALKING:"CONSULT_TALKING",CONSULTED_TALKING:"CONSULTED_TALKING",CONFERENCE_TALKING:"CONFERENCE_TALKING"},t={ready:"READY",busy:"NOT_READY",busy_work:"WORK_NOT_READY",login:"LOGIN",logout:"LOGOUT",call:"MAKE_CALL",hangup:"HANGUP_CALL",answer:"ANSWER",hold:"HOLD",hold_cancel:"HOLD_CANCEL",mute:"MUTE",mute_cancel:"MUTE_CANCEL",transfer:"TRANSFER",transfer_cancel:"TRANSFER_CANCEL",consult:"CONSULT",consult_party:"CONSULT_PARTY",consult_transfer:"CONSULT_TRANSFER",consult_cancel:"CONSULT_CANCEL",consult_stop:"CONSULT_STOP",conference_remove:"CONFERENCE_REMOVE",followdata:"FOLLOWDATA"},n={[e.LOGIN]:"已登录",[e.LOGOUT]:"已退出",[e.READY]:"空闲",[e.NOT_READY]:"忙碌",[e.WORK_NOT_READY]:"自定义忙碌",[e.AFTER]:"话后",[e.OUT_CALL]:"外呼中",[e.OUT_CALLER_RING]:"外呼主叫振铃",[e.OUT_CALLED_RING]:"外呼被叫振铃",[e.PLAY_AGENT_ID]:"播放坐席工号",[e.TALKING]:"通话中",[e.MUTE_TALKING]:"静音中",[e.HOLD_TALKING]:"保持中",[e.INNER_CALL_RING]:"内呼来电振铃",[e.INNER_CALL_TALKING]:"内呼通话中",[e.INBOUND_RING]:"来电振铃",[e.TRANSFER]:"转接中",[e.TRANSFERED_RING]:"转接来电振铃",[e.TRANSFER_OUT_RING]:"转接外呼振铃",[e.TRANSFERED_TALKING]:"转接来电通话中",[e.CONSULT]:"咨询中",[e.CONSULT_RING]:"咨询来电振铃",[e.CONSULT_OUT_RING]:"咨询外呼振铃",[e.CONSULT_IVR]:"咨询IVR",[e.CONSULT_TALKING]:"咨询通话中",[e.CONSULTED_TALKING]:"来电咨询中",[e.CONFERENCE_TALKING]:"多方通话"},r={[e.LOGIN]:[t.call],[e.LOGOUT]:[],[e.READY]:[t.call],[e.NOT_READY]:[t.call],[e.WORK_NOT_READY]:[t.call],[e.AFTER]:[t.call],[e.OUT_CALL]:[t.hangup],[e.OUT_CALLER_RING]:[t.answer,t.hangup],[e.OUT_CALLED_RING]:[t.hangup],[e.PLAY_AGENT_ID]:[t.hangup],[e.TALKING]:[t.hangup,t.hold,t.mute,t.transfer,t.consult],[e.MUTE_TALKING]:[t.mute_cancel],[e.HOLD_TALKING]:[t.hold_cancel],[e.INNER_CALL_RING]:[t.hangup,t.answer],[e.INNER_CALL_TALKING]:[t.hangup,t.mute],[e.INBOUND_RING]:[t.hangup,t.answer],[e.TRANSFER]:[t.transfer_cancel],[e.TRANSFERED_RING]:[t.hangup,t.answer],[e.TRANSFER_OUT_RING]:[t.transfer_cancel],[e.TRANSFERED_TALKING]:[t.hangup,t.mute,t.transfer,t.consult],[e.CONSULT]:[t.consult_cancel],[e.CONSULT_RING]:[t.hangup,t.answer],[e.CONSULT_OUT_RING]:[t.consult_cancel],[e.CONSULT_IVR]:[t.hangup,t.consult_cancel],[e.CONSULT_TALKING]:[t.hangup,t.mute,t.consult_party,t.consult_transfer],[e.CONSULTED_TALKING]:[t.hangup,t.mute],[e.CONFERENCE_TALKING]:[t.hangup,t.mute,t.consult]};!function(e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).adapter=e()}(function(){return function e(t,n,r){function i(s,a){if(!n[s]){if(!t[s]){var c="function"==typeof require&&require;if(!a&&c)return c(s,!0);if(o)return o(s,!0);throw(c=new Error("Cannot find module '"+s+"'")).code="MODULE_NOT_FOUND",c}c=n[s]={exports:{}},t[s][0].call(c.exports,function(e){return i(t[s][1][e]||e)},c,c.exports,e,t,n,r)}return n[s].exports}for(var o="function"==typeof require&&require,s=0;s<r.length;s++)i(r[s]);return i}({1:[function(e,t,n){e=(0,e("./adapter_factory.js").adapterFactory)({window:"undefined"==typeof window?void 0:window}),t.exports=e},{"./adapter_factory.js":2}],2:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0}),n.adapterFactory=function(){var e=(0<arguments.length&&void 0!==arguments[0]?arguments[0]:{}).window,t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0},n=r.log,d=r.detectBrowser(e),u={browserDetails:d,commonShim:a,extractVersion:r.extractVersion,disableLog:r.disableLog,disableWarnings:r.disableWarnings,sdp:c};switch(d.browser){case"chrome":if(!i||!i.shimPeerConnection||!t.shimChrome)return n("Chrome shim is not included in this adapter release."),u;if(null===d.version)return n("Chrome shim can not determine version, not shimming."),u;n("adapter.js shimming chrome."),u.browserShim=i,a.shimAddIceCandidateNullOrEmpty(e,d),a.shimParameterlessSetLocalDescription(e,d),i.shimGetUserMedia(e,d),i.shimMediaStream(e,d),i.shimPeerConnection(e,d),i.shimOnTrack(e,d),i.shimAddTrackRemoveTrack(e,d),i.shimGetSendersWithDtmf(e,d),i.shimGetStats(e,d),i.shimSenderReceiverGetStats(e,d),i.fixNegotiationNeeded(e,d),a.shimRTCIceCandidate(e,d),a.shimConnectionState(e,d),a.shimMaxMessageSize(e,d),a.shimSendThrowTypeError(e,d),a.removeExtmapAllowMixed(e,d);break;case"firefox":if(!o||!o.shimPeerConnection||!t.shimFirefox)return n("Firefox shim is not included in this adapter release."),u;n("adapter.js shimming firefox."),u.browserShim=o,a.shimAddIceCandidateNullOrEmpty(e,d),a.shimParameterlessSetLocalDescription(e,d),o.shimGetUserMedia(e,d),o.shimPeerConnection(e,d),o.shimOnTrack(e,d),o.shimRemoveStream(e,d),o.shimSenderGetStats(e,d),o.shimReceiverGetStats(e,d),o.shimRTCDataChannel(e,d),o.shimAddTransceiver(e,d),o.shimGetParameters(e,d),o.shimCreateOffer(e,d),o.shimCreateAnswer(e,d),a.shimRTCIceCandidate(e,d),a.shimConnectionState(e,d),a.shimMaxMessageSize(e,d),a.shimSendThrowTypeError(e,d);break;case"safari":if(!s||!t.shimSafari)return n("Safari shim is not included in this adapter release."),u;n("adapter.js shimming safari."),u.browserShim=s,a.shimAddIceCandidateNullOrEmpty(e,d),a.shimParameterlessSetLocalDescription(e,d),s.shimRTCIceServerUrls(e,d),s.shimCreateOfferLegacy(e,d),s.shimCallbacksAPI(e,d),s.shimLocalStreamsAPI(e,d),s.shimRemoteStreamsAPI(e,d),s.shimTrackEventTransceiver(e,d),s.shimGetUserMedia(e,d),s.shimAudioContext(e,d),a.shimRTCIceCandidate(e,d),a.shimMaxMessageSize(e,d),a.shimSendThrowTypeError(e,d),a.removeExtmapAllowMixed(e,d);break;default:n("Unsupported browser!")}return u};var r=d(e("./utils")),i=d(e("./chrome/chrome_shim")),o=d(e("./firefox/firefox_shim")),s=d(e("./safari/safari_shim")),a=d(e("./common_shim")),c=d(e("sdp"));function d(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}},{"./chrome/chrome_shim":3,"./common_shim":6,"./firefox/firefox_shim":7,"./safari/safari_shim":10,"./utils":11,sdp:12}],3:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0}),n.shimGetDisplayMedia=n.shimGetUserMedia=void 0;var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i=e("./getusermedia");Object.defineProperty(n,"shimGetUserMedia",{enumerable:!0,get:function(){return i.shimGetUserMedia}});var o=e("./getdisplaymedia");Object.defineProperty(n,"shimGetDisplayMedia",{enumerable:!0,get:function(){return o.shimGetDisplayMedia}}),n.shimMediaStream=function(e){e.MediaStream=e.MediaStream||e.webkitMediaStream},n.shimOnTrack=function(e){var t;"object"!==(void 0===e?"undefined":r(e))||!e.RTCPeerConnection||"ontrack"in e.RTCPeerConnection.prototype?s.wrapPeerConnectionEvent(e,"track",function(e){return e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e}):(Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get:function(){return this._ontrack},set:function(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0}),t=e.RTCPeerConnection.prototype.setRemoteDescription,e.RTCPeerConnection.prototype.setRemoteDescription=function(){var n=this;return this._ontrackpoly||(this._ontrackpoly=function(t){t.stream.addEventListener("addtrack",function(r){var i=e.RTCPeerConnection.prototype.getReceivers?n.getReceivers().find(function(e){return e.track&&e.track.id===r.track.id}):{track:r.track},o=new Event("track");o.track=r.track,o.receiver=i,o.transceiver={receiver:i},o.streams=[t.stream],n.dispatchEvent(o)}),t.stream.getTracks().forEach(function(r){var i=e.RTCPeerConnection.prototype.getReceivers?n.getReceivers().find(function(e){return e.track&&e.track.id===r.id}):{track:r},o=new Event("track");o.track=r,o.receiver=i,o.transceiver={receiver:i},o.streams=[t.stream],n.dispatchEvent(o)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)})},n.shimGetSendersWithDtmf=function(e){var t,n,i,o,s,a;"object"===(void 0===e?"undefined":r(e))&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype?(t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}},e.RTCPeerConnection.prototype.getSenders||(e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()},n=e.RTCPeerConnection.prototype.addTrack,e.RTCPeerConnection.prototype.addTrack=function(e,r){var i=n.apply(this,arguments);return i||(i=t(this,e),this._senders.push(i)),i},i=e.RTCPeerConnection.prototype.removeTrack,e.RTCPeerConnection.prototype.removeTrack=function(e){i.apply(this,arguments),-1!==(e=this._senders.indexOf(e))&&this._senders.splice(e,1)}),o=e.RTCPeerConnection.prototype.addStream,e.RTCPeerConnection.prototype.addStream=function(e){var n=this;this._senders=this._senders||[],o.apply(this,[e]),e.getTracks().forEach(function(e){n._senders.push(t(n,e))})},s=e.RTCPeerConnection.prototype.removeStream,e.RTCPeerConnection.prototype.removeStream=function(e){var t=this;this._senders=this._senders||[],s.apply(this,[e]),e.getTracks().forEach(function(e){var n=t._senders.find(function(t){return t.track===e});n&&t._senders.splice(t._senders.indexOf(n),1)})}):"object"===(void 0===e?"undefined":r(e))&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)&&(a=e.RTCPeerConnection.prototype.getSenders,e.RTCPeerConnection.prototype.getSenders=function(){var e=this,t=a.apply(this,[]);return t.forEach(function(t){return t._pc=e}),t},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get:function(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}}))},n.shimGetStats=function(e){var t;e.RTCPeerConnection&&(t=e.RTCPeerConnection.prototype.getStats,e.RTCPeerConnection.prototype.getStats=function(){var e=this,n=(i=Array.prototype.slice.call(arguments))[0],r=i[1],i=i[2];if(0<arguments.length&&"function"==typeof n)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof n))return t.apply(this,[]);var o=function(e){var t={};return e.result().forEach(function(e){var n={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach(function(t){n[t]=e.stat(t)}),t[n.id]=n}),t},s=function(e){return new Map(Object.keys(e).map(function(t){return[t,e[t]]}))};return 2<=arguments.length?t.apply(this,[function(e){r(s(o(e)))},n]):new Promise(function(n,r){t.apply(e,[function(e){n(s(o(e)))},r])}).then(r,i)})},n.shimSenderReceiverGetStats=function(e){var t,n,i,o;"object"===(void 0===e?"undefined":r(e))&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver&&("getStats"in e.RTCRtpSender.prototype||((t=e.RTCPeerConnection.prototype.getSenders)&&(e.RTCPeerConnection.prototype.getSenders=function(){var e=this,n=t.apply(this,[]);return n.forEach(function(t){return t._pc=e}),n}),(n=e.RTCPeerConnection.prototype.addTrack)&&(e.RTCPeerConnection.prototype.addTrack=function(){var e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){var e=this;return this._pc.getStats().then(function(t){return s.filterStats(t,e.track,!0)})}),"getStats"in e.RTCRtpReceiver.prototype||((i=e.RTCPeerConnection.prototype.getReceivers)&&(e.RTCPeerConnection.prototype.getReceivers=function(){var e=this,t=i.apply(this,[]);return t.forEach(function(t){return t._pc=e}),t}),s.wrapPeerConnectionEvent(e,"track",function(e){return e.receiver._pc=e.srcElement,e}),e.RTCRtpReceiver.prototype.getStats=function(){var e=this;return this._pc.getStats().then(function(t){return s.filterStats(t,e.track,!1)})}),"getStats"in e.RTCRtpSender.prototype&&"getStats"in e.RTCRtpReceiver.prototype&&(o=e.RTCPeerConnection.prototype.getStats,e.RTCPeerConnection.prototype.getStats=function(){if(0<arguments.length&&arguments[0]instanceof e.MediaStreamTrack){var t=arguments[0],n=void 0,r=void 0,i=void 0;return this.getSenders().forEach(function(e){e.track===t&&(n?i=!0:n=e)}),this.getReceivers().forEach(function(e){return e.track===t&&(r?i=!0:r=e),e.track===t}),i||n&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):n?n.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return o.apply(this,arguments)}))},n.shimAddTrackRemoveTrackWithNative=c,n.shimAddTrackRemoveTrack=function(e,t){if(e.RTCPeerConnection){if(e.RTCPeerConnection.prototype.addTrack&&65<=t.version)return c(e);var n=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){var e=this,t=n.apply(this);return this._reverseStreams=this._reverseStreams||{},t.map(function(t){return e._reverseStreams[t.id]})};var r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){var n,i=this;this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(function(e){if(i.getSenders().find(function(t){return t.track===e}))throw new DOMException("Track already exists.","InvalidAccessError")}),this._reverseStreams[t.id]||(n=new e.MediaStream(t.getTracks()),this._streams[t.id]=n,this._reverseStreams[n.id]=t,t=n),r.apply(this,[t])};var i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[(this._streams[e.id]||e).id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,n){var r=this;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");var i=[].slice.call(arguments,1);if(1!==i.length||!i[0].getTracks().find(function(e){return e===t}))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(function(e){return e.track===t}))throw new DOMException("Track already exists.","InvalidAccessError");return this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},(i=this._streams[n.id])?(i.addTrack(t),Promise.resolve().then(function(){r.dispatchEvent(new Event("negotiationneeded"))})):(i=new e.MediaStream([t]),this._streams[n.id]=i,this._reverseStreams[i.id]=n,this.addStream(i)),this.getSenders().find(function(e){return e.track===t})},["createOffer","createAnswer"].forEach(function(t){var n=e.RTCPeerConnection.prototype[t],r=a({},t,function(){var e=this,t=arguments;return arguments.length&&"function"==typeof arguments[0]?n.apply(this,[function(n){n=d(e,n),t[0].apply(null,[n])},function(e){t[1]&&t[1].apply(null,e)},arguments[2]]):n.apply(this,arguments).then(function(t){return d(e,t)})});e.RTCPeerConnection.prototype[t]=r[t]});var o=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type&&(arguments[0]=(e=this,n=(t=arguments[0]).sdp,Object.keys(e._reverseStreams||[]).forEach(function(t){var r=e._reverseStreams[t];t=e._streams[r.id];n=n.replace(new RegExp(r.id,"g"),t.id)}),new RTCSessionDescription({type:t.type,sdp:n}))),o.apply(this,arguments);var e,t,n};var s=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get:function(){var e=s.get.apply(this);return""===e.type?e:d(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){var t=this;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(e._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};var n=void 0;Object.keys(this._streams).forEach(function(r){t._streams[r].getTracks().find(function(t){return e.track===t})&&(n=t._streams[r])}),n&&(1===n.getTracks().length?this.removeStream(this._reverseStreams[n.id]):n.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function d(e,t){var n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(function(t){var r=e._reverseStreams[t];t=e._streams[r.id];n=n.replace(new RegExp(t.id,"g"),r.id)}),new RTCSessionDescription({type:t.type,sdp:n})}},n.shimPeerConnection=function(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){var n=e.RTCPeerConnection.prototype[t],r=a({},t,function(){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)});e.RTCPeerConnection.prototype[t]=r[t]})},n.fixNegotiationNeeded=function(e,t){s.wrapPeerConnectionEvent(e,"negotiationneeded",function(e){var n=e.target;if(!(t.version<72||n.getConfiguration&&"plan-b"===n.getConfiguration().sdpSemantics)||"stable"===n.signalingState)return e})};var s=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}(e("../utils.js"));function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function c(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){var e=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(function(t){return e._shimmedLocalStreams[t][0]})};var t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){if(!n)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var r=t.apply(this,arguments);return this._shimmedLocalStreams[n.id]?-1===this._shimmedLocalStreams[n.id].indexOf(r)&&this._shimmedLocalStreams[n.id].push(r):this._shimmedLocalStreams[n.id]=[n,r],r};var n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){var t=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(function(e){if(t.getSenders().find(function(t){return t.track===e}))throw new DOMException("Track already exists.","InvalidAccessError")});var r=this.getSenders();n.apply(this,arguments);var i=this.getSenders().filter(function(e){return-1===r.indexOf(e)});this._shimmedLocalStreams[e.id]=[e].concat(i)};var r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],r.apply(this,arguments)};var i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){var t=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(function(n){var r=t._shimmedLocalStreams[n].indexOf(e);-1!==r&&t._shimmedLocalStreams[n].splice(r,1),1===t._shimmedLocalStreams[n].length&&delete t._shimmedLocalStreams[n]}),i.apply(this,arguments)}}},{"../utils.js":11,"./getdisplaymedia":4,"./getusermedia":5}],4:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0}),n.shimGetDisplayMedia=function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(n){return t(n).then(function(t){var r=n.video&&n.video.width,i=n.video&&n.video.height,o=n.video&&n.video.frameRate;return n.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:o||3}},r&&(n.video.mandatory.maxWidth=r),i&&(n.video.mandatory.maxHeight=i),e.navigator.mediaDevices.getUserMedia(n)})}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}},{}],5:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};n.shimGetUserMedia=function(e,t){var n,o,s,a,c=e&&e.navigator;c.mediaDevices&&(n=function(e){if("object"!==(void 0===e?"undefined":r(e))||e.mandatory||e.optional)return e;var t={};return Object.keys(e).forEach(function(n){var i,o,s;"require"!==n&&"advanced"!==n&&"mediaSource"!==n&&(void 0!==(i="object"===r(e[n])?e[n]:{ideal:e[n]}).exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact),o=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t},void 0!==i.ideal&&(t.optional=t.optional||[],s={},"number"==typeof i.ideal?(s[o("min",n)]=i.ideal,t.optional.push(s),(s={})[o("max",n)]=i.ideal):s[o("",n)]=i.ideal,t.optional.push(s)),void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[o("",n)]=i.exact):["min","max"].forEach(function(e){void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[o(e,n)]=i[e])}))}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},o=function(e,o){if(61<=t.version)return o(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"===r(e.audio)&&((a=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])})((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),a(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)),e&&"object"===r(e.video)){var s=(s=e.video.facingMode)&&("object"===(void 0===s?"undefined":r(s))?s:{ideal:s}),a=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!c.mediaDevices.getSupportedConstraints||!c.mediaDevices.getSupportedConstraints().facingMode||a)){delete e.video.facingMode;var d=void 0;if("environment"===s.exact||"environment"===s.ideal?d=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(d=["front"]),d)return c.mediaDevices.enumerateDevices().then(function(t){var r=(t=t.filter(function(e){return"videoinput"===e.kind})).find(function(e){return d.some(function(t){return e.label.toLowerCase().includes(t)})});return(r=!r&&t.length&&d.includes("back")?t[t.length-1]:r)&&(e.video.deviceId=s.exact?{exact:r.deviceId}:{ideal:r.deviceId}),e.video=n(e.video),i("chrome: "+JSON.stringify(e)),o(e)})}e.video=n(e.video)}return i("chrome: "+JSON.stringify(e)),o(e)},s=function(e){return 64<=t.version?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}}},c.getUserMedia=function(e,t,n){o(e,function(e){c.webkitGetUserMedia(e,t,function(e){n&&n(s(e))})})}.bind(c),c.mediaDevices.getUserMedia&&(a=c.mediaDevices.getUserMedia.bind(c.mediaDevices),c.mediaDevices.getUserMedia=function(e){return o(e,function(e){return a(e).then(function(t){if(e.audio&&!t.getAudioTracks().length||e.video&&!t.getVideoTracks().length)throw t.getTracks().forEach(function(e){e.stop()}),new DOMException("","NotFoundError");return t},function(e){return Promise.reject(s(e))})})}))};var i=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}(e("../utils.js")).log},{"../utils.js":11}],6:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};n.shimRTCIceCandidate=function(e){var t;!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype||(t=e.RTCIceCandidate,e.RTCIceCandidate=function(e){if("object"===(void 0===e?"undefined":r(e))&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substr(2)),e.candidate&&e.candidate.length){var n=new t(e),i=o.default.parseCandidate(e.candidate),s=Object.assign(n,i);return s.toJSON=function(){return{candidate:s.candidate,sdpMid:s.sdpMid,sdpMLineIndex:s.sdpMLineIndex,usernameFragment:s.usernameFragment}},s}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,s.wrapPeerConnectionEvent(e,"icecandidate",function(t){return t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t}))},n.shimMaxMessageSize=function(e,t){var n;e.RTCPeerConnection&&("sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get:function(){return void 0===this._sctp?null:this._sctp}}),n=e.RTCPeerConnection.prototype.setRemoteDescription,e.RTCPeerConnection.prototype.setRemoteDescription=function(){var e,r,i,s;return this._sctp=null,"chrome"===t.browser&&76<=t.version&&"plan-b"===this.getConfiguration().sdpSemantics&&Object.defineProperty(this,"sctp",{get:function(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0}),function(e){return!(!e||!e.sdp)&&((e=o.default.splitSections(e.sdp)).shift(),e.some(function(e){return(e=o.default.parseMLine(e))&&"application"===e.kind&&-1!==e.protocol.indexOf("SCTP")}))}(arguments[0])&&(r=function(e){return null===(e=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/))||e.length<2||(e=parseInt(e[1],10))!=e?-1:e}(arguments[0]),i=r,s=65536,s=s="firefox"===t.browser?t.version<57?-1===i?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637:s,r=function(e,n){var r=65536;return"firefox"===t.browser&&57===t.version&&(r=65535),0<(e=o.default.matchPrefix(e.sdp,"a=max-message-size:")).length?r=parseInt(e[0].substr(19),10):"firefox"===t.browser&&-1!==n&&(r=2147483637),r}(arguments[0],r),void 0,e=0===s&&0===r?Number.POSITIVE_INFINITY:0===s||0===r?Math.max(s,r):Math.min(s,r),r={},Object.defineProperty(r,"maxMessageSize",{get:function(){return e}}),this._sctp=r),n.apply(this,arguments)})},n.shimSendThrowTypeError=function(e){var t;function n(e,t){var n=e.send;e.send=function(){var r=(r=arguments[0]).length||r.size||r.byteLength;if("open"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return n.apply(e,arguments)}}e.RTCPeerConnection&&"createDataChannel"in e.RTCPeerConnection.prototype&&(t=e.RTCPeerConnection.prototype.createDataChannel,e.RTCPeerConnection.prototype.createDataChannel=function(){var e=t.apply(this,arguments);return n(e,this),e},s.wrapPeerConnectionEvent(e,"datachannel",function(e){return n(e.channel,e.target),e}))},n.shimConnectionState=function(e){var t;!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype||(t=e.RTCPeerConnection.prototype,Object.defineProperty(t,"connectionState",{get:function(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get:function(){return this._onconnectionstatechange||null},set:function(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(function(e){var n=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=function(e){var t,n=e.target;return n._lastConnectionState!==n.connectionState&&(n._lastConnectionState=n.connectionState,t=new Event("connectionstatechange",e),n.dispatchEvent(t)),e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}}))},n.removeExtmapAllowMixed=function(e,t){var n;e.RTCPeerConnection&&("chrome"===t.browser&&71<=t.version||"safari"===t.browser&&605<=t.version||(n=e.RTCPeerConnection.prototype.setRemoteDescription,e.RTCPeerConnection.prototype.setRemoteDescription=function(t){var r;return t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")&&(r=t.sdp.split("\n").filter(function(e){return"a=extmap-allow-mixed"!==e.trim()}).join("\n"),e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:r}):t.sdp=r),n.apply(this,arguments)}))},n.shimAddIceCandidateNullOrEmpty=function(e,t){var n;e.RTCPeerConnection&&e.RTCPeerConnection.prototype&&(n=e.RTCPeerConnection.prototype.addIceCandidate)&&0!==n.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})},n.shimParameterlessSetLocalDescription=function(e,t){var n;e.RTCPeerConnection&&e.RTCPeerConnection.prototype&&(n=e.RTCPeerConnection.prototype.setLocalDescription)&&0!==n.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){var e=this,t=arguments[0]||{};if("object"!==(void 0===t?"undefined":r(t))||t.type&&t.sdp)return n.apply(this,arguments);if(!(t={type:t.type,sdp:t.sdp}).type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":t.type="offer";break;default:t.type="answer"}return t.sdp||"offer"!==t.type&&"answer"!==t.type?n.apply(this,[t]):("offer"===t.type?this.createOffer:this.createAnswer).apply(this).then(function(t){return n.apply(e,[t])})})};var i,o=(i=e("sdp"))&&i.__esModule?i:{default:i},s=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}(e("./utils"))},{"./utils":11,sdp:12}],7:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0}),n.shimGetDisplayMedia=n.shimGetUserMedia=void 0;var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i=e("./getusermedia");Object.defineProperty(n,"shimGetUserMedia",{enumerable:!0,get:function(){return i.shimGetUserMedia}});var o=e("./getdisplaymedia");Object.defineProperty(n,"shimGetDisplayMedia",{enumerable:!0,get:function(){return o.shimGetDisplayMedia}}),n.shimOnTrack=function(e){"object"===(void 0===e?"undefined":r(e))&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})},n.shimPeerConnection=function(e,t){var n,i;"object"===(void 0===e?"undefined":r(e))&&(e.RTCPeerConnection||e.mozRTCPeerConnection)&&(!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){var n=e.RTCPeerConnection.prototype[t],r=function(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}({},t,function(){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)});e.RTCPeerConnection.prototype[t]=r[t]}),n={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats,e.RTCPeerConnection.prototype.getStats=function(){var e=(o=Array.prototype.slice.call(arguments))[0],r=o[1],o=o[2];return i.apply(this,[e||null]).then(function(e){if(t.version<53&&!r)try{e.forEach(function(e){e.type=n[e.type]||e.type})}catch(t){if("TypeError"!==t.name)throw t;e.forEach(function(t,r){e.set(r,Object.assign({},t,{type:n[t.type]||t.type}))})}return e}).then(r,o)})},n.shimSenderGetStats=function(e){var t,n;"object"===(void 0===e?"undefined":r(e))&&e.RTCPeerConnection&&e.RTCRtpSender&&(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype||((t=e.RTCPeerConnection.prototype.getSenders)&&(e.RTCPeerConnection.prototype.getSenders=function(){var e=this,n=t.apply(this,[]);return n.forEach(function(t){return t._pc=e}),n}),(n=e.RTCPeerConnection.prototype.addTrack)&&(e.RTCPeerConnection.prototype.addTrack=function(){var e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}))},n.shimReceiverGetStats=function(e){var t;"object"===(void 0===e?"undefined":r(e))&&e.RTCPeerConnection&&e.RTCRtpSender&&(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype||((t=e.RTCPeerConnection.prototype.getReceivers)&&(e.RTCPeerConnection.prototype.getReceivers=function(){var e=this,n=t.apply(this,[]);return n.forEach(function(t){return t._pc=e}),n}),s.wrapPeerConnectionEvent(e,"track",function(e){return e.receiver._pc=e.srcElement,e}),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}))},n.shimRemoveStream=function(e){!e.RTCPeerConnection||"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){var t=this;s.deprecated("removeStream","removeTrack"),this.getSenders().forEach(function(n){n.track&&e.getTracks().includes(n.track)&&t.removeTrack(n)})})},n.shimRTCDataChannel=function(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)},n.shimAddTransceiver=function(e){var t;"object"!==(void 0===e?"undefined":r(e))||!e.RTCPeerConnection||(t=e.RTCPeerConnection.prototype.addTransceiver)&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];var e=arguments[1],n=e&&"sendEncodings"in e;n&&e.sendEncodings.forEach(function(e){if("rid"in e&&!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in e&&!(1<=parseFloat(e.scaleResolutionDownBy)))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(0<=parseFloat(e.maxFramerate)))throw new RangeError("max_framerate must be >= 0.0")});var r,i=t.apply(this,arguments);return n&&("encodings"in(n=(r=i.sender).getParameters())&&(1!==n.encodings.length||0!==Object.keys(n.encodings[0]).length)||(n.encodings=e.sendEncodings,r.sendEncodings=e.sendEncodings,this.setParametersPromises.push(r.setParameters(n).then(function(){delete r.sendEncodings}).catch(function(){delete r.sendEncodings})))),i})},n.shimGetParameters=function(e){var t;"object"!==(void 0===e?"undefined":r(e))||!e.RTCRtpSender||(t=e.RTCRtpSender.prototype.getParameters)&&(e.RTCRtpSender.prototype.getParameters=function(){var e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})},n.shimCreateOffer=function(e){var t;"object"===(void 0===e?"undefined":r(e))&&e.RTCPeerConnection&&(t=e.RTCPeerConnection.prototype.createOffer,e.RTCPeerConnection.prototype.createOffer=function(){var e=this,n=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return t.apply(e,n)}).finally(function(){e.setParametersPromises=[]}):t.apply(this,arguments)})},n.shimCreateAnswer=function(e){var t;"object"===(void 0===e?"undefined":r(e))&&e.RTCPeerConnection&&(t=e.RTCPeerConnection.prototype.createAnswer,e.RTCPeerConnection.prototype.createAnswer=function(){var e=this,n=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return t.apply(e,n)}).finally(function(){e.setParametersPromises=[]}):t.apply(this,arguments)})};var s=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}(e("../utils"))},{"../utils":11,"./getdisplaymedia":8,"./getusermedia":9}],8:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0}),n.shimGetDisplayMedia=function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(n){return n&&n.video?(!0===n.video?n.video={mediaSource:t}:n.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(n)):((n=new DOMException("getDisplayMedia without video constraints is undefined")).name="NotFoundError",n.code=8,Promise.reject(n))})}},{}],9:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};n.shimGetUserMedia=function(e,t){var n,o,s,a,c=e&&e.navigator;e=e&&e.MediaStreamTrack;c.getUserMedia=function(e,t,n){i.deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),c.mediaDevices.getUserMedia(e).then(t,n)},55<t.version&&"autoGainControl"in c.mediaDevices.getSupportedConstraints()||(n=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])},o=c.mediaDevices.getUserMedia.bind(c.mediaDevices),c.mediaDevices.getUserMedia=function(e){return"object"===(void 0===e?"undefined":r(e))&&"object"===r(e.audio)&&(e=JSON.parse(JSON.stringify(e)),n(e.audio,"autoGainControl","mozAutoGainControl"),n(e.audio,"noiseSuppression","mozNoiseSuppression")),o(e)},e&&e.prototype.getSettings&&(s=e.prototype.getSettings,e.prototype.getSettings=function(){var e=s.apply(this,arguments);return n(e,"mozAutoGainControl","autoGainControl"),n(e,"mozNoiseSuppression","noiseSuppression"),e}),e&&e.prototype.applyConstraints&&(a=e.prototype.applyConstraints,e.prototype.applyConstraints=function(e){return"audio"===this.kind&&"object"===(void 0===e?"undefined":r(e))&&(e=JSON.parse(JSON.stringify(e)),n(e,"autoGainControl","mozAutoGainControl"),n(e,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[e])}))};var i=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}(e("../utils"))},{"../utils":11}],10:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};n.shimLocalStreamsAPI=function(e){var t;"object"===(void 0===e?"undefined":r(e))&&e.RTCPeerConnection&&("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),"addStream"in e.RTCPeerConnection.prototype||(t=e.RTCPeerConnection.prototype.addTrack,e.RTCPeerConnection.prototype.addStream=function(e){var n=this;this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(function(r){return t.call(n,r,e)}),e.getVideoTracks().forEach(function(r){return t.call(n,r,e)})},e.RTCPeerConnection.prototype.addTrack=function(e){for(var n=this,r=arguments.length,i=Array(1<r?r-1:0),o=1;o<r;o++)i[o-1]=arguments[o];return i&&i.forEach(function(e){n._localStreams?n._localStreams.includes(e)||n._localStreams.push(e):n._localStreams=[e]}),t.apply(this,arguments)}),"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){var t=this;this._localStreams||(this._localStreams=[]);var n,r=this._localStreams.indexOf(e);-1!==r&&(this._localStreams.splice(r,1),n=e.getTracks(),this.getSenders().forEach(function(e){n.includes(e.track)&&t.removeTrack(e)}))}))},n.shimRemoteStreamsAPI=function(e){var t;"object"===(void 0===e?"undefined":r(e))&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams||[]}),"onaddstream"in e.RTCPeerConnection.prototype||(Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get:function(){return this._onaddstream},set:function(e){var t=this;this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=function(e){e.streams.forEach(function(e){var n;t._remoteStreams||(t._remoteStreams=[]),t._remoteStreams.includes(e)||(t._remoteStreams.push(e),(n=new Event("addstream")).stream=e,t.dispatchEvent(n))})})}}),t=e.RTCPeerConnection.prototype.setRemoteDescription,e.RTCPeerConnection.prototype.setRemoteDescription=function(){var e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach(function(t){var n;e._remoteStreams||(e._remoteStreams=[]),0<=e._remoteStreams.indexOf(t)||(e._remoteStreams.push(t),(n=new Event("addstream")).stream=t,e.dispatchEvent(n))})}),t.apply(e,arguments)}))},n.shimCallbacksAPI=function(e){var t,n,i,o,s,a;"object"===(void 0===e?"undefined":r(e))&&e.RTCPeerConnection&&(t=e.RTCPeerConnection.prototype,n=t.createOffer,i=t.createAnswer,o=t.setLocalDescription,s=t.setRemoteDescription,a=t.addIceCandidate,t.createOffer=function(e,t){var r=n.apply(this,[2<=arguments.length?arguments[2]:e]);return t?(r.then(e,t),Promise.resolve()):r},t.createAnswer=function(e,t){var n=i.apply(this,[2<=arguments.length?arguments[2]:e]);return t?(n.then(e,t),Promise.resolve()):n},e=function(e,t,n){return e=o.apply(this,[e]),n?(e.then(t,n),Promise.resolve()):e},t.setLocalDescription=e,e=function(e,t,n){return e=s.apply(this,[e]),n?(e.then(t,n),Promise.resolve()):e},t.setRemoteDescription=e,e=function(e,t,n){return e=a.apply(this,[e]),n?(e.then(t,n),Promise.resolve()):e},t.addIceCandidate=e)},n.shimGetUserMedia=function(e){var t,n=e&&e.navigator;n.mediaDevices&&n.mediaDevices.getUserMedia&&(e=n.mediaDevices,t=e.getUserMedia.bind(e),n.mediaDevices.getUserMedia=function(e){return t(o(e))}),!n.getUserMedia&&n.mediaDevices&&n.mediaDevices.getUserMedia&&(n.getUserMedia=function(e,t,r){n.mediaDevices.getUserMedia(e).then(t,r)}.bind(n))},n.shimConstraints=o,n.shimRTCIceServerUrls=function(e){var t;e.RTCPeerConnection&&(t=e.RTCPeerConnection,e.RTCPeerConnection=function(e,n){if(e&&e.iceServers){for(var r=[],o=0;o<e.iceServers.length;o++){var s=e.iceServers[o];!s.hasOwnProperty("urls")&&s.hasOwnProperty("url")?(i.deprecated("RTCIceServer.url","RTCIceServer.urls"),(s=JSON.parse(JSON.stringify(s))).urls=s.url,delete s.url,r.push(s)):r.push(e.iceServers[o])}e.iceServers=r}return new t(e,n)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:function(){return t.generateCertificate}}))},n.shimTrackEventTransceiver=function(e){"object"===(void 0===e?"undefined":r(e))&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})},n.shimCreateOfferLegacy=function(e){var t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){var n;return e&&(void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio),n=this.getTransceivers().find(function(e){return"audio"===e.receiver.track.kind}),!1===e.offerToReceiveAudio&&n?"sendrecv"===n.direction?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":"recvonly"===n.direction&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):!0!==e.offerToReceiveAudio||n||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo),n=this.getTransceivers().find(function(e){return"video"===e.receiver.track.kind}),!1===e.offerToReceiveVideo&&n?"sendrecv"===n.direction?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":"recvonly"===n.direction&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):!0!==e.offerToReceiveVideo||n||this.addTransceiver("video",{direction:"recvonly"})),t.apply(this,arguments)}},n.shimAudioContext=function(e){"object"!==(void 0===e?"undefined":r(e))||e.AudioContext||(e.AudioContext=e.webkitAudioContext)};var i=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}(e("../utils"));function o(e){return e&&void 0!==e.video?Object.assign({},e,{video:i.compactObject(e.video)}):e}},{"../utils":11}],11:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};n.extractVersion=s,n.wrapPeerConnectionEvent=function(e,t,n){var r,i;e.RTCPeerConnection&&(e=e.RTCPeerConnection.prototype,r=e.addEventListener,e.addEventListener=function(e,i){if(e!==t)return r.apply(this,arguments);function o(e){(e=n(e))&&(i.handleEvent?i.handleEvent(e):i(e))}return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(i,o),r.apply(this,[e,o])},i=e.removeEventListener,e.removeEventListener=function(e,n){if(e!==t||!this._eventMap||!this._eventMap[t])return i.apply(this,arguments);if(!this._eventMap[t].has(n))return i.apply(this,arguments);var r=this._eventMap[t].get(n);return this._eventMap[t].delete(n),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,i.apply(this,[e,r])},Object.defineProperty(e,"on"+t,{get:function(){return this["_on"+t]},set:function(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0}))},n.disableLog=function(e){return"boolean"==typeof e?(i=e)?"adapter.js logging disabled":"adapter.js logging enabled":new Error("Argument type: "+(void 0===e?"undefined":r(e))+". Please use a boolean.")},n.disableWarnings=function(e){return"boolean"==typeof e?(o=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled")):new Error("Argument type: "+(void 0===e?"undefined":r(e))+". Please use a boolean.")},n.log=function(){"object"===("undefined"==typeof window?"undefined":r(window))&&(i||"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments))},n.deprecated=function(e,t){o&&console.warn(e+" is deprecated, please use "+t+" instead.")},n.detectBrowser=function(e){var t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;var n=e.navigator;if(n.mozGetUserMedia)t.browser="firefox",t.version=s(n.userAgent,/Firefox\/(\d+)\./,1);else if(n.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection&&!e.RTCIceGatherer)t.browser="chrome",t.version=s(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!n.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=s(n.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t},n.compactObject=function e(t){return a(t)?Object.keys(t).reduce(function(n,r){var i=(o=a(t[r]))?e(t[r]):t[r],o=o&&!Object.keys(i).length;return void 0===i||o?n:Object.assign(n,function(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}({},r,i))},{}):t},n.walkStats=c,n.filterStats=function(e,t,n){var r=n?"outbound-rtp":"inbound-rtp",i=new Map;if(null===t)return i;var o=[];return e.forEach(function(e){"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)}),o.forEach(function(t){e.forEach(function(n){n.type===r&&n.trackId===t.id&&c(e,n,i)})}),i};var i=!0,o=!0;function s(e,t,n){return(t=e.match(t))&&t.length>=n&&parseInt(t[n],10)}function a(e){return"[object Object]"===Object.prototype.toString.call(e)}function c(e,t,n){t&&!n.has(t.id)&&(n.set(t.id,t),Object.keys(t).forEach(function(r){r.endsWith("Id")?c(e,e.get(t[r]),n):r.endsWith("Ids")&&t[r].forEach(function(t){c(e,e.get(t),n)})}))}},{}],12:[function(e,t,n){var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};i.localCName=i.generateIdentifier(),i.splitLines=function(e){return e.trim().split("\n").map(function(e){return e.trim()})},i.splitSections=function(e){return e.split("\nm=").map(function(e,t){return(0<t?"m="+e:e).trim()+"\r\n"})},i.getDescription=function(e){return(e=i.splitSections(e))&&e[0]},i.getMediaSections=function(e){return(e=i.splitSections(e)).shift(),e},i.matchPrefix=function(e,t){return i.splitLines(e).filter(function(e){return 0===e.indexOf(t)})},i.parseCandidate=function(e){for(var t=void 0,n={foundation:(t=(0===e.indexOf("a=candidate:")?e.substring(12):e.substring(10)).split(" "))[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]},r=8;r<t.length;r+=2)switch(t[r]){case"raddr":n.relatedAddress=t[r+1];break;case"rport":n.relatedPort=parseInt(t[r+1],10);break;case"tcptype":n.tcpType=t[r+1];break;case"ufrag":n.ufrag=t[r+1],n.usernameFragment=t[r+1];break;default:void 0===n[t[r]]&&(n[t[r]]=t[r+1])}return n},i.writeCandidate=function(e){var t=[];t.push(e.foundation);var n=e.component;return"rtp"===n?t.push(1):"rtcp"===n?t.push(2):t.push(n),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port),n=e.type,t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},i.parseIceOptions=function(e){return e.substr(14).split(" ")},i.parseRtpMap=function(e){var t=e.substr(9).split(" ");e={payloadType:parseInt(t.shift(),10)},t=t[0].split("/");return e.name=t[0],e.clockRate=parseInt(t[1],10),e.channels=3===t.length?parseInt(t[2],10):1,e.numChannels=e.channels,e},i.writeRtpMap=function(e){var t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);var n=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==n?"/"+n:"")+"\r\n"},i.parseExtmap=function(e){return e=e.substr(9).split(" "),{id:parseInt(e[0],10),direction:0<e[0].indexOf("/")?e[0].split("/")[1]:"sendrecv",uri:e[1]}},i.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+"\r\n"},i.parseFmtp=function(e){for(var t={},n=void 0,r=e.substr(e.indexOf(" ")+1).split(";"),i=0;i<r.length;i++)t[(n=r[i].trim().split("="))[0].trim()]=n[1];return t},i.writeFmtp=function(e){var t,n="",r=e.payloadType;return void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length&&(t=[],Object.keys(e.parameters).forEach(function(n){void 0!==e.parameters[n]?t.push(n+"="+e.parameters[n]):t.push(n)}),n+="a=fmtp:"+r+" "+t.join(";")+"\r\n"),n},i.parseRtcpFb=function(e){return{type:(e=e.substr(e.indexOf(" ")+1).split(" ")).shift(),parameter:e.join(" ")}},i.writeRtcpFb=function(e){var t="",n=e.payloadType;return void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(function(e){t+="a=rtcp-fb:"+n+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"}),t},i.parseSsrcMedia=function(e){var t=e.indexOf(" "),n={ssrc:parseInt(e.substr(7,t-7),10)},r=e.indexOf(":",t);return-1<r?(n.attribute=e.substr(t+1,r-t-1),n.value=e.substr(r+1)):n.attribute=e.substr(t+1),n},i.parseSsrcGroup=function(e){return{semantics:(e=e.substr(13).split(" ")).shift(),ssrcs:e.map(function(e){return parseInt(e,10)})}},i.getMid=function(e){if(e=i.matchPrefix(e,"a=mid:")[0])return e.substr(6)},i.parseFingerprint=function(e){return{algorithm:(e=e.substr(14).split(" "))[0].toLowerCase(),value:e[1].toUpperCase()}},i.getDtlsParameters=function(e,t){return{role:"auto",fingerprints:i.matchPrefix(e+t,"a=fingerprint:").map(i.parseFingerprint)}},i.writeDtlsParameters=function(e,t){var n="a=setup:"+t+"\r\n";return e.fingerprints.forEach(function(e){n+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"}),n},i.parseCryptoLine=function(e){return e=e.substr(9).split(" "),{tag:parseInt(e[0],10),cryptoSuite:e[1],keyParams:e[2],sessionParams:e.slice(3)}},i.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"===r(e.keyParams)?i.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},i.parseCryptoKeyParams=function(e){return 0!==e.indexOf("inline:")?null:{keyMethod:"inline",keySalt:(e=e.substr(7).split("|"))[0],lifeTime:e[1],mkiValue:e[2]?e[2].split(":")[0]:void 0,mkiLength:e[2]?e[2].split(":")[1]:void 0}},i.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},i.getCryptoParameters=function(e,t){return i.matchPrefix(e+t,"a=crypto:").map(i.parseCryptoLine)},i.getIceParameters=function(e,t){var n=i.matchPrefix(e+t,"a=ice-ufrag:")[0];t=i.matchPrefix(e+t,"a=ice-pwd:")[0];return n&&t?{usernameFragment:n.substr(12),password:t.substr(10)}:null},i.writeIceParameters=function(e){var t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},i.parseRtpParameters=function(e){for(var t={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=i.splitLines(e)[0].split(" "),r=3;r<n.length;r++){var o=n[r];if(a=i.matchPrefix(e,"a=rtpmap:"+o+" ")[0]){var s=i.parseRtpMap(a),a=i.matchPrefix(e,"a=fmtp:"+o+" ");switch(s.parameters=a.length?i.parseFmtp(a[0]):{},s.rtcpFeedback=i.matchPrefix(e,"a=rtcp-fb:"+o+" ").map(i.parseRtcpFb),t.codecs.push(s),s.name.toUpperCase()){case"RED":case"ULPFEC":t.fecMechanisms.push(s.name.toUpperCase())}}}return i.matchPrefix(e,"a=extmap:").forEach(function(e){t.headerExtensions.push(i.parseExtmap(e))}),t},i.writeRtpDescription=function(e,t){var n="";n+="m="+e+" ",n+=0<t.codecs.length?"9":"0",n+=" UDP/TLS/RTP/SAVPF ",n+=t.codecs.map(function(e){return void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType}).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",t.codecs.forEach(function(e){n+=i.writeRtpMap(e),n+=i.writeFmtp(e),n+=i.writeRtcpFb(e)});var r=0;return t.codecs.forEach(function(e){e.maxptime>r&&(r=e.maxptime)}),0<r&&(n+="a=maxptime:"+r+"\r\n"),t.headerExtensions&&t.headerExtensions.forEach(function(e){n+=i.writeExtmap(e)}),n},i.parseRtpEncodingParameters=function(e){var t=[],n=i.parseRtpParameters(e),r=-1!==n.fecMechanisms.indexOf("RED"),o=-1!==n.fecMechanisms.indexOf("ULPFEC"),s=0<(c=i.matchPrefix(e,"a=ssrc:").map(function(e){return i.parseSsrcMedia(e)}).filter(function(e){return"cname"===e.attribute})).length&&c[0].ssrc,a=void 0,c=i.matchPrefix(e,"a=ssrc-group:FID").map(function(e){return e.substr(17).split(" ").map(function(e){return parseInt(e,10)})});0<c.length&&1<c[0].length&&c[0][0]===s&&(a=c[0][1]),n.codecs.forEach(function(e){"RTX"===e.name.toUpperCase()&&e.parameters.apt&&(e={ssrc:s,codecPayloadType:parseInt(e.parameters.apt,10)},s&&a&&(e.rtx={ssrc:a}),t.push(e),r&&((e=JSON.parse(JSON.stringify(e))).fec={ssrc:s,mechanism:o?"red+ulpfec":"red"},t.push(e)))}),0===t.length&&s&&t.push({ssrc:s});var d=i.matchPrefix(e,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substr(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substr(5),10)*.95-16e3:void 0,t.forEach(function(e){e.maxBitrate=d})),t},i.parseRtcpParameters=function(e){var t={},n=i.matchPrefix(e,"a=ssrc:").map(function(e){return i.parseSsrcMedia(e)}).filter(function(e){return"cname"===e.attribute})[0];return n&&(t.cname=n.value,t.ssrc=n.ssrc),n=i.matchPrefix(e,"a=rtcp-rsize"),t.reducedSize=0<n.length,t.compound=0===n.length,e=i.matchPrefix(e,"a=rtcp-mux"),t.mux=0<e.length,t},i.writeRtcpParameters=function(e){var t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},i.parseMsid=function(e){var t=void 0,n=i.matchPrefix(e,"a=msid:");return 1===n.length?{stream:(t=n[0].substr(7).split(" "))[0],track:t[1]}:0<(e=i.matchPrefix(e,"a=ssrc:").map(function(e){return i.parseSsrcMedia(e)}).filter(function(e){return"msid"===e.attribute})).length?{stream:(t=e[0].value.split(" "))[0],track:t[1]}:void 0},i.parseSctpDescription=function(e){var t=i.parseMLine(e),n=i.matchPrefix(e,"a=max-message-size:"),r=void 0;return 0<n.length&&(r=parseInt(n[0].substr(19),10)),isNaN(r)&&(r=65536),0<(n=i.matchPrefix(e,"a=sctp-port:")).length?{port:parseInt(n[0].substr(12),10),protocol:t.fmt,maxMessageSize:r}:0<(e=i.matchPrefix(e,"a=sctpmap:")).length?(e=e[0].substr(10).split(" "),{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:r}):void 0},i.writeSctpDescription=function(e,t){var n=[];n="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"];return void 0!==t.maxMessageSize&&n.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),n.join("")},i.generateSessionId=function(){return Math.random().toString().substr(2,21)},i.writeSessionBoilerplate=function(e,t,n){return t=void 0!==t?t:2,"v=0\r\no="+(n||"thisisadapterortc")+" "+(e||i.generateSessionId())+" "+t+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},i.getDirection=function(e,t){for(var n=i.splitLines(e),r=0;r<n.length;r++)switch(n[r]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[r].substr(2)}return t?i.getDirection(t):"sendrecv"},i.getKind=function(e){return i.splitLines(e)[0].split(" ")[0].substr(2)},i.isRejected=function(e){return"0"===e.split(" ",2)[1]},i.parseMLine=function(e){return{kind:(e=i.splitLines(e)[0].substr(2).split(" "))[0],port:parseInt(e[1],10),protocol:e[2],fmt:e.slice(3).join(" ")}},i.parseOLine=function(e){return{username:(e=i.matchPrefix(e,"o=")[0].substr(2).split(" "))[0],sessionId:e[1],sessionVersion:parseInt(e[2],10),netType:e[3],addressType:e[4],address:e[5]}},i.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;for(var t=i.splitLines(e),n=0;n<t.length;n++)if(t[n].length<2||"="!==t[n].charAt(1))return!1;return!0},"object"===(void 0===t?"undefined":r(t))&&(t.exports=i)},{}]},{},[1])(1)}),o.sessions=new Map,o.isExtensionEnabled=function(){if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)return!0;if(window.navigator.userAgent.match("Chrome")){let e=parseInt(window.navigator.userAgent.match(/Chrome\/(.*) /)[1],10),t=33;return window.navigator.userAgent.match("Linux")&&(t=35),e>=26&&e<=t||o.extension.isInstalled()}return!0};var i={extensionId:"hapfgfdkleiggjjpfpenajgdnfckjpaj",isInstalled:function(){return null!==document.querySelector("#janus-extension-installed")},getScreen:function(e){let t=window.setTimeout(function(){let t=new Error("NavigatorUserMediaError");return t.name='The required Chrome extension is not installed: click <a href="#">here</a> to install it. (NOTE: this will need you to refresh the page)',e(t)},1e3);this.cache[t]=e,window.postMessage({type:"janusGetScreen",id:t},"*")},init:function(){let e={};this.cache=e,window.addEventListener("message",function(t){if(t.origin==window.location.origin)if("janusGotScreen"==t.data.type&&e[t.data.id]){let n=e[t.data.id];if(delete e[t.data.id],""===t.data.sourceId){let e=new Error("NavigatorUserMediaError");e.name="You cancelled the request for permission, giving up...",n(e)}else n(null,t.data.sourceId)}else"janusGetScreenPending"==t.data.type&&(console.log("clearing ",t.data.id),window.clearTimeout(t.data.id))})}};function o(e){if((e=e||{}).success="function"==typeof e.success?e.success:o.noop,e.error="function"==typeof e.error?e.error:o.noop,e.destroyed="function"==typeof e.destroyed?e.destroyed:o.noop,!o.initDone)return e.error("Library not initialized"),{};if(!o.isWebrtcSupported())return e.error("WebRTC not supported by this browser"),{};if(o.log("Library initialized: "+o.initDone),!e.server)return e.error("Invalid server url"),{};let t=!1,n=null,r={},i=!1,s=null,a=0,c=e.server;o.isArray(c)?(o.log("Multiple servers provided ("+c.length+"), will use the first that works"),c=null,s=e.server,o.debug(s)):0===c.indexOf("ws")?(t=!0,o.log("Using WebSockets to contact Janus: "+c)):(t=!1,o.log("Using REST API to contact Janus: "+c));let d=e.iceServers||[{urls:"stun:stun.l.google.com:19302"}],u=e.iceTransportPolicy,l=e.bundlePolicy,p=!1;void 0!==e.withCredentials&&null!==e.withCredentials&&(p=!0===e.withCredentials);let f=10;void 0!==e.max_poll_events&&null!==e.max_poll_events&&(f=e.max_poll_events),f<1&&(f=1);let h=null;void 0!==e.token&&null!==e.token&&(h=e.token);let m=null;void 0!==e.apisecret&&null!==e.apisecret&&(m=e.apisecret),this.destroyOnUnload=!0,void 0!==e.destroyOnUnload&&null!==e.destroyOnUnload&&(this.destroyOnUnload=!0===e.destroyOnUnload);let g=6e4;function v(e){let t={high:9e5,medium:3e5,low:1e5};return null!=e&&(e.high&&(t.high=e.high),e.medium&&(t.medium=e.medium),e.low&&(t.low=e.low)),t}void 0!==e.longPollTimeout&&null!==e.longPollTimeout&&(g=e.longPollTimeout),isNaN(g)&&(g=6e4);let y=!1,T=null,b=new Map,S=this,C=0,w=new Map;function R(){if(null==T)return;if(o.debug("Long poll..."),!y)return void o.warn("Is the server down? (connected=false)");let t=c+"/"+T+"?rid="+(new Date).getTime();f&&(t=t+"&maxev="+f),h&&(t=t+"&token="+encodeURIComponent(h)),m&&(t=t+"&apisecret="+encodeURIComponent(m)),o.httpAPICall(t,{verb:"GET",withCredentials:p,success:_,timeout:g,error:function(t,n){if(o.error(t+":",n),C++,C>3)return y=!1,void e.error("Lost connection to the server (is it down?)");R()}})}function _(e,r){if(C=0,t||null==T||!0===r||R(),t||!o.isArray(e))if("keepalive"!==e.janus){if("server_info"===e.janus){o.debug("Got info on the Janus instance"),o.debug(e);const t=e.transaction;if(t){const n=w.get(t);n&&n(e),w.delete(t)}return}if("ack"===e.janus){o.debug("Got an ack on session "+T),o.debug(e);const t=e.transaction;if(t){const n=w.get(t);n&&n(e),w.delete(t)}return}if("success"===e.janus){o.debug("Got a success on session "+T),o.debug(e);const t=e.transaction;if(t){const n=w.get(t);n&&n(e),w.delete(t)}return}if("trickle"===e.janus){const t=e.sender;if(!t)return void o.warn("Missing sender...");const n=b.get(t);if(!n)return void o.debug("This handle is not attached to this session");let r=e.candidate;o.debug("Got a trickled candidate on session "+T),o.debug(r);let i=n.webrtcStuff;i.pc&&i.remoteSdp?(o.debug("Adding remote candidate:",r),r&&!0!==r.completed?i.pc.addIceCandidate(r):i.pc.addIceCandidate(o.endOfCandidates)):(o.debug("We didn't do setRemoteDescription (trickle got here before the offer?), caching candidate"),i.candidates||(i.candidates=[]),i.candidates.push(r),o.debug(i.candidates))}else{if("webrtcup"===e.janus){o.debug("Got a webrtcup event on session "+T),o.debug(e);const t=e.sender;if(!t)return void o.warn("Missing sender...");const n=b.get(t);return n?void n.webrtcState(!0):void o.debug("This handle is not attached to this session")}if("hangup"===e.janus){o.debug("Got a hangup event on session "+T),o.debug(e);const t=e.sender;if(!t)return void o.warn("Missing sender...");const n=b.get(t);if(!n)return void o.debug("This handle is not attached to this session");n.webrtcState(!1,e.reason),n.hangup()}else if("detached"===e.janus){o.debug("Got a detached event on session "+T),o.debug(e);const t=e.sender;if(!t)return void o.warn("Missing sender...");const n=b.get(t);if(!n)return;n.ondetached(),n.detach()}else if("media"===e.janus){o.debug("Got a media event on session "+T),o.debug(e);const t=e.sender;if(!t)return void o.warn("Missing sender...");const n=b.get(t);if(!n)return void o.debug("This handle is not attached to this session");n.mediaState(e.type,e.receiving,e.mid)}else if("slowlink"===e.janus){o.debug("Got a slowlink event on session "+T),o.debug(e);const t=e.sender;if(!t)return void o.warn("Missing sender...");const n=b.get(t);if(!n)return void o.debug("This handle is not attached to this session");n.slowLink(e.uplink,e.lost,e.mid)}else{if("error"===e.janus){o.error("Ooops: "+e.error.code+" "+e.error.reason),o.debug(e);let t=e.transaction;if(t){let n=w.get(t);n&&n(e),w.delete(t)}return}if("event"===e.janus){o.debug("Got a plugin event on session "+T),o.debug(e);const t=e.sender;if(!t)return void o.warn("Missing sender...");let n=e.plugindata;if(!n)return void o.warn("Missing plugindata...");o.debug(" -- Event is coming from "+t+" ("+n.plugin+")");let r=n.data;o.debug(r);const i=b.get(t);if(!i)return void o.warn("This handle is not attached to this session");let s=e.jsep;s&&(o.debug("Handling SDP as well..."),o.debug(s));let a=i.onmessage;a?(o.debug("Notifying application..."),a(r,s)):o.debug("No provided notification callback")}else{if("timeout"===e.janus)return o.error("Timeout on session "+T),o.debug(e),void(t&&n.close(3504,"Gateway timeout"));o.warn("Unknown message/event '"+e.janus+"' on session "+T),o.debug(e)}}}}else o.vdebug("Got a keepalive on session "+T);else for(let t=0;t<e.length;t++)_(e[t],!0)}function k(d){let u=o.randomString(12),l={janus:"create",transaction:u};if(d.reconnect&&(y=!1,l.janus="claim",l.session_id=T,n&&(n.onopen=null,n.onerror=null,n.onclose=null,i&&(i=!1))),h&&(l.token=h),m&&(l.apisecret=m),!c&&o.isArray(s)&&(c=s[a],0===c.indexOf("ws")?(t=!0,o.log("Server #"+(a+1)+": trying WebSockets to contact Janus ("+c+")")):(t=!1,o.log("Server #"+(a+1)+": trying REST API to contact Janus ("+c+")"))),t){n=o.newWebSocket(c,"janus-protocol"),r={error:function(){if(o.error("Error connecting to the Janus WebSockets server... "+c),o.isArray(s)&&!d.reconnect)return a++,a===s.length?void d.error("Error connecting to any of the provided Janus servers: Is the server down?"):(c=null,void setTimeout(function(){k(d)},200));d.error("Error connecting to the Janus WebSockets server: Is the server down?")},open:function(){w.set(u,function(e){if(o.debug(e),"success"!==e.janus)return o.error("Ooops: "+e.error.code+" "+e.error.reason),void d.error(e.error.reason);i=!0,y=!0,T=e.session_id?e.session_id:e.data.id,d.reconnect?o.log("Claimed session: "+T):o.log("Created session: "+T),o.sessions.set(T,S),d.success()}),n.send(JSON.stringify(l))},message:function(e){_(JSON.parse(e.data))},close:function(){c&&y&&(y=!1,e.error("Lost connection to the server (is it down?)"))}};for(let e in r)n.addEventListener(e,r[e])}else o.httpAPICall(c,{verb:"POST",withCredentials:p,body:l,success:function(e){if(o.debug(e),"success"!==e.janus)return o.error("Ooops: "+e.error.code+" "+e.error.reason),void d.error(e.error.reason);y=!0,T=e.session_id?e.session_id:e.data.id,d.reconnect?o.log("Claimed session: "+T):o.log("Created session: "+T),o.sessions.set(T,S),R(),d.success()},error:function(e,t){if(o.error(e+":",t),o.isArray(s)&&!d.reconnect)return a++,a===s.length?void d.error("Error connecting to any of the provided Janus servers: Is the server down?"):(c=null,void setTimeout(function(){k(d)},200));""===t?d.error(e+": Is the server down?"):t&&t.error?d.error(e+": "+t.error.message):d.error(e+": "+t)}})}function P(e,r){if((r=r||{}).success="function"==typeof r.success?r.success:o.noop,r.error="function"==typeof r.error?r.error:o.noop,!y)return o.warn("Is the server down? (connected=false)"),void r.error("Is the server down? (connected=false)");let i=b.get(e);if(!i||!i.webrtcStuff)return o.warn("Invalid handle"),void r.error("Invalid handle");let s=r.message,a=r.jsep,d=o.randomString(12),u={janus:"message",body:s,transaction:d};if(i.token&&(u.token=i.token),m&&(u.apisecret=m),a){u.jsep={type:a.type,sdp:a.sdp},a.e2ee&&(u.jsep.e2ee=!0),"hml"!==a.rid_order&&"lmh"!==a.rid_order||(u.jsep.rid_order=a.rid_order),a.force_relay&&(u.jsep.force_relay=!0);let e=null,t=i.webrtcStuff;if(t.pc){let n=t.pc.getTransceivers();if(n&&n.length>0)for(let t in n){let r=n[t];if(r&&r.sender&&r.sender.track&&"video"===r.sender.track.kind){let n=r.sender.getParameters();n&&n.encodings&&1===n.encodings.length&&n.encodings[0]&&n.encodings[0].scalabilityMode&&(e||(e=[]),e.push({mindex:parseInt(t),mid:r.mid,svc:n.encodings[0].scalabilityMode}))}}}e&&(u.jsep.svc=e)}if(o.debug("Sending message to plugin (handle="+e+"):"),o.debug(u),t)return u.session_id=T,u.handle_id=e,w.set(d,function(e){if(o.debug("Message sent!"),o.debug(e),"success"===e.janus){let t=e.plugindata;if(!t)return o.warn("Request succeeded, but missing plugindata..."),void r.success();o.log("Synchronous transaction successful ("+t.plugin+")");let n=t.data;return o.debug(n),void r.success(n)}"ack"===e.janus?r.success():e.error?(o.error("Ooops: "+e.error.code+" "+e.error.reason),r.error(e.error.code+" "+e.error.reason)):(o.error("Unknown error"),r.error("Unknown error"))}),void n.send(JSON.stringify(u));o.httpAPICall(c+"/"+T+"/"+e,{verb:"POST",withCredentials:p,body:u,success:function(e){if(o.debug("Message sent!"),o.debug(e),"success"===e.janus){let t=e.plugindata;if(!t)return o.warn("Request succeeded, but missing plugindata..."),void r.success();o.log("Synchronous transaction successful ("+t.plugin+")");let n=t.data;return o.debug(n),void r.success(n)}"ack"===e.janus?r.success():e.error?(o.error("Ooops: "+e.error.code+" "+e.error.reason),r.error(e.error.code+" "+e.error.reason)):(o.error("Unknown error"),r.error("Unknown error"))},error:function(e,t){o.error(e+":",t),r.error(e+": "+t)}})}function I(e,r){if(!y)return void o.warn("Is the server down? (connected=false)");let i=b.get(e);if(!i||!i.webrtcStuff)return void o.warn("Invalid handle");let s={janus:"trickle",candidate:r,transaction:o.randomString(12)};if(i.token&&(s.token=i.token),m&&(s.apisecret=m),o.vdebug("Sending trickle candidate (handle="+e+"):"),o.vdebug(s),t)return s.session_id=T,s.handle_id=e,void n.send(JSON.stringify(s));o.httpAPICall(c+"/"+T+"/"+e,{verb:"POST",withCredentials:p,body:s,success:function(e){o.vdebug("Candidate sent!"),o.vdebug(e),"ack"===e.janus||o.error("Ooops: "+e.error.code+" "+e.error.reason)},error:function(e,t){o.error(e+":",t)}})}function E(e,t,n,r,i){let s=b.get(e);if(!s||!s.webrtcStuff)return void o.warn("Invalid handle");let a=s.webrtcStuff;if(!a.pc)return void o.warn("Invalid PeerConnection");let c=function(e){o.log("Received state change on data channel:",e);let t=e.target.label,n=e.target.protocol,r=a.dataChannel[t]?a.dataChannel[t].readyState:"null";if(o.log("State change on <"+t+"> data channel: "+r),"open"===r){if(a.dataChannel[t].pending&&a.dataChannel[t].pending.length>0){o.log("Sending pending messages on <"+t+">:",a.dataChannel[t].pending.length);for(let e of a.dataChannel[t].pending)o.log("Sending data on data channel <"+t+">"),o.debug(e),a.dataChannel[t].send(e);a.dataChannel[t].pending=[]}s.ondataopen(t,n)}};if(r)a.dataChannel[t]=r;else{let e=a.dataChannelOptions;n&&(e.protocol=n),a.dataChannel[t]=a.pc.createDataChannel(t,e)}a.dataChannel[t].onmessage=function(e){o.log("Received message on data channel:",e);let t=e.target.label;s.ondata(e.data,t)},a.dataChannel[t].onopen=c,a.dataChannel[t].onclose=c,a.dataChannel[t].onerror=function(e){o.error("Got error on data channel:",e)},a.dataChannel[t].pending=[],i&&a.dataChannel[t].pending.push(i)}function A(e,t){(t=t||{}).success="function"==typeof t.success?t.success:o.noop,t.error="function"==typeof t.error?t.error:o.noop;let n=b.get(e);if(!n||!n.webrtcStuff)return o.warn("Invalid handle"),void t.error("Invalid handle");let r=n.webrtcStuff,i=t.text||t.data;if(!i)return o.warn("Invalid data"),void t.error("Invalid data");let s=t.label?t.label:o.dataChanDefaultLabel;return r.dataChannel[s]?"open"!==r.dataChannel[s].readyState?(r.dataChannel[s].pending.push(i),void t.success()):(o.log("Sending data on data channel <"+s+">"),o.debug(i),r.dataChannel[s].send(i),void t.success()):(E(e,s,t.protocol,!1,i,t.protocol),void t.success())}function D(e,t){(t=t||{}).success="function"==typeof t.success?t.success:o.noop,t.error="function"==typeof t.error?t.error:o.noop;let n=b.get(e);if(!n||!n.webrtcStuff)return o.warn("Invalid handle"),void t.error("Invalid handle");let r=n.webrtcStuff;if(!r.dtmfSender){if(r.pc){let e=r.pc.getSenders().find(function(e){return e.track&&"audio"===e.track.kind});if(!e)return o.warn("Invalid DTMF configuration (no audio track)"),void t.error("Invalid DTMF configuration (no audio track)");r.dtmfSender=e.dtmf,r.dtmfSender&&(o.log("Created DTMF Sender"),r.dtmfSender.ontonechange=function(e){o.debug("Sent DTMF tone: "+e.tone)})}if(!r.dtmfSender)return o.warn("Invalid DTMF configuration"),void t.error("Invalid DTMF configuration")}let i=t.dtmf;if(!i)return o.warn("Invalid DTMF parameters"),void t.error("Invalid DTMF parameters");let s=i.tones;if(!s)return o.warn("Invalid DTMF string"),void t.error("Invalid DTMF string");let a="number"==typeof i.duration?i.duration:500,c="number"==typeof i.gap?i.gap:50;o.debug("Sending DTMF string "+s+" (duration "+a+"ms, gap "+c+"ms)"),r.dtmfSender.insertDTMF(s,a,c),t.success()}function O(e,r){(r=r||{}).success="function"==typeof r.success?r.success:o.noop,r.error="function"==typeof r.error?r.error:o.noop;let i=!0===r.noRequest;o.log("Destroying handle "+e+" (only-locally="+i+")"),z(e);let s=b.get(e);if(!s||s.detached)return b.delete(e),void r.success();if(s.detached=!0,i)return b.delete(e),void r.success();if(!y)return o.warn("Is the server down? (connected=false)"),void r.error("Is the server down? (connected=false)");let a={janus:"detach",transaction:o.randomString(12)};if(s.token&&(a.token=s.token),m&&(a.apisecret=m),t)return a.session_id=T,a.handle_id=e,n.send(JSON.stringify(a)),b.delete(e),void r.success();o.httpAPICall(c+"/"+T+"/"+e,{verb:"POST",withCredentials:p,body:a,success:function(t){o.log("Destroyed handle:"),o.debug(t),"success"!==t.janus&&o.error("Ooops: "+t.error.code+" "+t.error.reason),b.delete(e),r.success()},error:function(t,n){o.error(t+":",n),b.delete(e),r.success()}})}function N(e,t){let n=b.get(e);if(!n||!n.webrtcStuff)throw o.warn("Invalid handle"),"Invalid handle";let r=n.webrtcStuff;if(r.pc)return;let i={iceServers:d,iceTransportPolicy:u,bundlePolicy:l,sdpSemantics:"unified-plan"},s=!1;if(t.tracks)for(let e of t.tracks)if(e.transforms&&(e.transforms.sender||e.transforms.receiver)){s=!0;break}t.externalEncryption&&(s=!0,r.externalEncryption=!0),RTCRtpSender&&(RTCRtpSender.prototype.createEncodedStreams||RTCRtpSender.prototype.createEncodedAudioStreams&&RTCRtpSender.prototype.createEncodedVideoStreams)&&s&&(r.insertableStreams=!0,i.forceEncodedAudioInsertableStreams=!0,i.forceEncodedVideoInsertableStreams=!0,i.encodedInsertableStreams=!0),o.log("Creating PeerConnection"),r.pc=new RTCPeerConnection(i),o.debug(r.pc),r.pc.getStats&&(r.volume={},r.bitrate.value="0 kbits/sec"),o.log("Preparing local SDP and gathering candidates (trickle="+r.trickle+")"),r.pc.onconnectionstatechange=function(){r.pc&&n.connectionState(r.pc.connectionState)},r.pc.oniceconnectionstatechange=function(){r.pc&&n.iceState(r.pc.iceConnectionState)},r.pc.onicecandidate=function(n){if(!n.candidate||n.candidate.candidate&&n.candidate.candidate.indexOf("endOfCandidates")>0)o.log("End of candidates."),r.iceDone=!0,!0===r.trickle?I(e,{completed:!0}):function(e,t){t=t||{},t.success="function"==typeof t.success?t.success:o.noop,t.error="function"==typeof t.error?t.error:o.noop;let n=b.get(e);if(!n||!n.webrtcStuff)return void o.warn("Invalid handle, not sending anything");let r=n.webrtcStuff;if(o.log("Sending offer/answer SDP..."),!r.mySdp)return void o.warn("Local SDP instance is invalid, not sending anything...");r.mySdp={type:r.pc.localDescription.type,sdp:r.pc.localDescription.sdp},!1===r.trickle&&(r.mySdp.trickle=!1);o.debug(t),r.sdpSent=!0,t.success(r.mySdp)}(e,t);else{let t={candidate:n.candidate.candidate,sdpMid:n.candidate.sdpMid,sdpMLineIndex:n.candidate.sdpMLineIndex};!0===r.trickle&&I(e,t)}},r.pc.ontrack=function(e){if(o.log("Handling Remote Track",e),!e.streams)return;if(!e.track)return;let t=e.transceiver?e.transceiver.mid:e.track.id;try{e.transceiver&&e.transceiver.mid&&e.track.id&&(n.mids||(n.mids={}),n.mids[e.track.id]=e.transceiver.mid),n.onremotetrack(e.track,t,!0,{reason:"created"})}catch(e){o.error("Error calling onremotetrack",e)}if(e.track.onended)return;let i=null;o.log("Adding onended callback to track:",e.track),e.track.onended=function(t){o.log("Remote track removed:",t),clearTimeout(i);let s=r.pc?r.pc.getTransceivers():null,a=s?s.find(e=>e.receiver.track===t.target):null,c=a?a.mid:t.target.id;c===t.target.id&&n.mids&&n.mids[e.track.id]&&(c=n.mids[e.track.id]);try{n.onremotetrack(t.target,c,!1,{reason:"ended"})}catch(e){o.error("Error calling onremotetrack on removal",e)}delete n.mids[e.track.id]},e.track.onmute=function(t){o.log("Remote track muted:",t),i||(i=setTimeout(function(){o.log("Removing remote track");let s=r.pc?r.pc.getTransceivers():null,a=s?s.find(e=>e.receiver.track===t.target):null,c=a?a.mid:t.target.id;c===t.target.id&&n.mids&&n.mids[e.track.id]&&(c=n.mids[e.track.id]);try{n.onremotetrack(t.target,c,!1,{reason:"mute"})}catch(e){o.error("Error calling onremotetrack on mute",e)}i=null},2520))},e.track.onunmute=function(e){if(o.log("Remote track flowing again:",e),null!=i)clearTimeout(i),i=null;else try{let t=r.pc?r.pc.getTransceivers():null,i=t?t.find(t=>t.receiver.track===e.target):null,o=i?i.mid:e.target.id;n.onremotetrack(e.target,o,!0,{reason:"unmute"})}catch(e){o.error("Error calling onremotetrack on unmute",e)}}}}async function L(e,t,n){(n=n||{}).success="function"==typeof n.success?n.success:o.noop,n.error="function"==typeof n.error?n.error:$;let r=n.jsep;if(t&&r)return o.error("Provided a JSEP to a createOffer"),void n.error("Provided a JSEP to a createOffer");if(!(t||r&&r.type&&r.sdp))return o.error("A valid JSEP is required for createAnswer"),void n.error("A valid JSEP is required for createAnswer");if(n.media&&!n.tracks){if(n.tracks=o.mediaToTracks(n.media),!0===n.simulcast||!0===n.simulcast2||n.svc)for(let e of n.tracks)if("video"===e.type){!0===n.simulcast||!0===n.simulcast2?e.simulcast=!0:n.svc&&(e.svc=n.svc);break}o.warn("Deprecated media object passed, use tracks instead. Automatically translated to:",n.tracks)}if(n.tracks&&!Array.isArray(n.tracks))return o.error("Tracks must be an array"),void n.error("Tracks must be an array");let i=b.get(e);if(!i||!i.webrtcStuff)return o.warn("Invalid handle"),void n.error("Invalid handle");let s=i.webrtcStuff;var a;s.trickle=(a=n.trickle,o.debug("isTrickleEnabled:",a),!1!==a);try{if(N(e,n),t&&await x(e,n),r){if(await s.pc.setRemoteDescription(r),o.log("Remote description accepted!"),s.remoteSdp=r.sdp,s.candidates&&s.candidates.length>0){for(let e=0;e<s.candidates.length;e++){let t=s.candidates[e];o.debug("Adding remote candidate:",t),t&&!0!==t.completed?s.pc.addIceCandidate(t):s.pc.addIceCandidate(o.endOfCandidates)}s.candidates=[]}await x(e,n);let t=await async function(e,t){t=t||{},t.customizeSdp="function"==typeof t.customizeSdp?t.customizeSdp:o.noop;let n=b.get(e);if(!n||!n.webrtcStuff)throw o.warn("Invalid handle"),"Invalid handle";let r=n.webrtcStuff;o.log("Creating answer (iceDone="+r.iceDone+")");let i=await r.pc.createAnswer();o.debug(i);let s={type:"answer",sdp:i.sdp};if(t.customizeSdp(s),i.sdp=s.sdp,o.log("Setting local description"),r.mySdp={type:"answer",sdp:i.sdp},await r.pc.setLocalDescription(i),!r.iceDone&&!r.trickle)return o.log("Waiting for all candidates..."),null;(r.insertableStreams||r.externalEncryption)&&(i.e2ee=!0);return i}(e,n);n.success(t)}else{let t=await async function(e,t){t=t||{},t.customizeSdp="function"==typeof t.customizeSdp?t.customizeSdp:o.noop;let n=b.get(e);if(!n||!n.webrtcStuff)throw o.warn("Invalid handle"),"Invalid handle";let r=n.webrtcStuff;o.log("Creating offer (iceDone="+r.iceDone+")");let i={},s=!0===t.iceRestart;s&&(i.iceRestart=!0);o.debug(i);let a=await r.pc.createOffer(i);o.debug(a);let c={type:"offer",sdp:a.sdp};if(t.customizeSdp(c),a.sdp=c.sdp,o.log("Setting local description"),r.mySdp={type:"offer",sdp:a.sdp},await r.pc.setLocalDescription(a),r.mediaConstraints=i,!r.iceDone&&!r.trickle)return o.log("Waiting for all candidates..."),null;(r.insertableStreams||r.externalEncryption)&&(a.e2ee=!0);return a}(e,n);n.success(t)}}catch(e){o.error(e),n.error(e)}}function M(e,t){(t=t||{}).success="function"==typeof t.success?t.success:o.noop,t.error="function"==typeof t.error?t.error:$,t.customizeSdp="function"==typeof t.customizeSdp?t.customizeSdp:o.noop;let n=t.jsep,r=b.get(e);if(!r||!r.webrtcStuff)return o.warn("Invalid handle"),void t.error("Invalid handle");let i=r.webrtcStuff;if(n){if(!i.pc)return o.warn("Wait, no PeerConnection?? if this is an answer, use createAnswer and not handleRemoteJsep"),void t.error("No PeerConnection: if this is an answer, use createAnswer and not handleRemoteJsep");t.customizeSdp(n),i.pc.setRemoteDescription(n).then(function(){if(o.log("Remote description accepted!"),i.remoteSdp=n.sdp,i.candidates&&i.candidates.length>0){for(let e=0;e<i.candidates.length;e++){let t=i.candidates[e];o.debug("Adding remote candidate:",t),t&&!0!==t.completed?i.pc.addIceCandidate(t):i.pc.addIceCandidate(o.endOfCandidates)}i.candidates=[]}t.success()},t.error)}else t.error("Invalid JSEP")}async function j(e,t){if((t=t||{}).success="function"==typeof t.success?t.success:o.noop,t.error="function"==typeof t.error?t.error:o.noop,t.tracks&&!Array.isArray(t.tracks))return o.error("Tracks must be an array"),void t.error("Tracks must be an array");for(let e of t.tracks)(e.add||!e.replace&&!e.remove)&&(e.replace=!0);try{await x(e,t),t.success()}catch(e){o.error(e),t.error(e)}}async function x(e,t){let n=b.get(e);if(!n||!n.webrtcStuff)throw o.warn("Invalid handle, not sending anything"),"Invalid handle";let r=n.webrtcStuff;if(!r.pc)throw o.warn("Invalid PeerConnection"),"Invalid PeerConnection";let i=t.tracks;if(!i||!Array.isArray(i)||0===i.length)return;let s=!1,a={};for(let e of i){if(delete e.gumGroup,!e.type||!["audio","video"].includes(e.type))continue;if(!e.capture||e.capture instanceof MediaStreamTrack)continue;let t=e.group?e.group:"default";a[t]||(a[t]={}),a[t][e.type]||(e.gumGroup=t,a[t][e.type]=e)}let c=Object.keys(a);for(let e of c){let t=a[e];t.audio&&t.video||(t.audio&&delete t.audio.gumGroup,t.video&&delete t.video.gumGroup,delete a[e])}let d=!!t.jsep;for(let t of i){if(!t.type){o.warn("Missing track type:",t);continue}if("data"===t.type){if(r.pc.ondatachannel){o.warn("Data channel exists already, not creating another one");continue}o.log("Creating default data channel"),E(e,o.dataChanDefaultLabel,null,!1),r.pc.ondatachannel=function(t){o.log("Data channel created by Janus:",t),E(e,t.channel.label,t.channel.protocol,t.channel)};continue}if(void 0!==t.add&&null!==t.add||void 0!==t.remove&&null!==t.remove||void 0!==t.replace&&null!==t.replace||(t.add=!0),t.add&&t.remove||t.add&&t.remove&&t.replace){o.warn("Conflicting actions for track, ignoring:",t);continue}t.add&&t.replace?(o.warn("Both add and replace provided, falling back to replace:",t),delete t.add):t.remove&&t.replace&&(o.warn("Both remove and replace provided, falling back to remove:",t),delete t.replace);let i=t.type;"screen"===t.type&&(i="video");let c=null,u=null;if(t.mid?c=r.pc.getTransceivers().find(e=>e.mid===t.mid&&e.receiver.track.kind===i):t.add||(c=r.pc.getTransceivers().find(e=>e.receiver.track.kind===i)),t.replace||t.remove){if(!c){o.warn("Couldn't find a transceiver for track:",t);continue}if(!c.sender){o.warn("No sender in the transceiver for track:",t);continue}u=c.sender}if(d&&!c&&(c=r.pc.getTransceivers().find(e=>e.receiver.track.kind===i),!c)){o.warn("Couldn't find a transceiver for track:",t);continue}let l=null,p=null;if((t.remove||t.replace)&&(o.log("Removing track from PeerConnection",t),p=u.track?u.track.id:null,await u.replaceTrack(null),p&&r.myStream)){let e=null;if("audio"===i&&r.myStream.getAudioTracks()&&r.myStream.getAudioTracks().length)for(let t of r.myStream.getAudioTracks())t.id===p&&(e=t,o.log("Removing audio track:",e));else if("video"===i&&r.myStream.getVideoTracks()&&r.myStream.getVideoTracks().length)for(let t of r.myStream.getVideoTracks())t.id===p&&(e=t,o.log("Removing video track:",e));if(e){try{r.myStream.removeTrack(e),n.onlocaltrack(e,!1)}catch(e){o.error("Error calling onlocaltrack on removal for renegotiation",e)}if(!0!==e.dontStop)try{e.stop()}catch(e){}}}if(t.capture){if(t.gumGroup&&a[t.gumGroup]&&a[t.gumGroup].stream){let e=a[t.gumGroup].stream;l="audio"===t.type?e.getAudioTracks()[0]:e.getVideoTracks()[0],delete a[t.gumGroup].stream,delete a[t.gumGroup],delete t.gumGroup}else if(t.capture instanceof MediaStreamTrack)l=t.capture;else{s||(s=!0,n.consentDialog(!0));let e=o.trackConstraints(t),r=null;if("audio"===t.type||"video"===t.type){if(t.gumGroup){let n="audio"===t.type?"video":"audio";if(a[t.gumGroup]&&a[t.gumGroup][n]){let r=a[t.gumGroup][n],i=o.trackConstraints(r);e[n]=i[n]}}r=await navigator.mediaDevices.getUserMedia(e),t.gumGroup&&e.audio&&e.video&&(a[t.gumGroup].stream=r,delete t.gumGroup)}else r=await navigator.mediaDevices.getDisplayMedia(e);l="audio"===t.type?r.getAudioTracks()[0]:r.getVideoTracks()[0]}if(t.replace){await u.replaceTrack(l);let e="sendrecv";!1!==t.recv&&"inactive"!==c.direction&&"sendonly"!==c.direction||(e="sendonly"),c.setDirection?c.setDirection(e):c.direction=e}else{if(r.myStream||(r.myStream=new MediaStream),"audio"===i||!t.simulcast&&!t.svc)u=r.pc.addTrack(l,r.myStream),c=r.pc.getTransceivers().find(e=>e.sender===u);else if(t.simulcast){o.log("Enabling rid-based simulcasting:",l);let e=v(t.simulcastMaxBitrates);c=r.pc.addTransceiver(l,{direction:"sendrecv",streams:[r.myStream],sendEncodings:t.sendEncodings||[{rid:"h",active:!0,scalabilityMode:"L1T2",maxBitrate:e.high},{rid:"m",active:!0,scalabilityMode:"L1T2",maxBitrate:e.medium,scaleResolutionDownBy:2},{rid:"l",active:!0,scalabilityMode:"L1T2",maxBitrate:e.low,scaleResolutionDownBy:4}]})}else o.log("Enabling SVC ("+t.svc+"):",l),c=r.pc.addTransceiver(l,{direction:"sendrecv",streams:[r.myStream],sendEncodings:[{scalabilityMode:t.svc}]});if(u||(u=c?c.sender:null),t.codec)if("firefox"===o.webRTCAdapter.browserDetails.browser)o.warn("setCodecPreferences not supported in Firefox, ignoring codec for track:",t);else if("string"!=typeof t.codec)o.warn("Invalid codec value, ignoring for track:",t);else{let e=i+"/"+t.codec.toLowerCase(),n=RTCRtpReceiver.getCapabilities(i).codecs.filter(function(t){return t.mimeType.toLowerCase()===e});if(n&&0!==n.length){if(c)try{c.setCodecPreferences(n)}catch(e){o.warn("Failed enforcing codec for this "+i+" track:",e)}}else o.warn("Codec not supported in this browser for this track, ignoring:",t)}if(t.bitrate)if(t.simulcast||t.svc)o.warn("Ignoring bitrate for simulcast/SVC track, use sendEncodings for that");else if(isNaN(t.bitrate)||t.bitrate<0)o.warn("Ignoring invalid bitrate for track:",t);else if(u){let e=u.getParameters();e&&e.encodings&&0!==e.encodings.length?(e.encodings[0].maxBitrate=t.bitrate,await u.setParameters(e)):o.warn("No encodings in the sender parameters, ignoring bitrate for track:",t)}if("video"===i&&t.framerate)if(t.simulcast||t.svc)o.warn("Ignoring framerate for simulcast/SVC track, use sendEncodings for that");else if(isNaN(t.framerate)||t.framerate<0)o.warn("Ignoring invalid framerate for track:",t);else if(u){let e=u.getParameters();e&&e.encodings&&0!==e.encodings.length?(e.encodings[0].maxFramerate=t.framerate,await u.setParameters(e)):o.warn("No encodings in the sender parameters, ignoring framerate for track:",t)}if(t.transforms){if(u&&t.transforms.sender){let e=null;RTCRtpSender.prototype.createEncodedStreams?e=u.createEncodedStreams():(RTCRtpSender.prototype.createAudioEncodedStreams||RTCRtpSender.prototype.createEncodedVideoStreams)&&("audio"===i?e=u.createEncodedAudioStreams():"video"===i&&(e=u.createEncodedVideoStreams())),e&&(console.log("Insertable Streams sender transform:",e),e.readableStream&&e.writableStream?e.readableStream.pipeThrough(t.transforms.sender).pipeTo(e.writableStream):e.readable&&e.writable&&e.readable.pipeThrough(t.transforms.sender).pipeTo(e.writable))}if(c&&c.receiver&&t.transforms.receiver){let e=null;RTCRtpReceiver.prototype.createEncodedStreams?e=c.receiver.createEncodedStreams():(RTCRtpReceiver.prototype.createAudioEncodedStreams||RTCRtpReceiver.prototype.createEncodedVideoStreams)&&("audio"===i?e=c.receiver.createEncodedAudioStreams():"video"===i&&(e=c.receiver.createEncodedVideoStreams())),e&&(console.log("Insertable Streams receiver transform:",e),e.readableStream&&e.writableStream?e.readableStream.pipeThrough(t.transforms.receiver).pipeTo(e.writableStream):e.readable&&e.writable&&e.readable.pipeThrough(t.transforms.receiver).pipeTo(e.writable))}}}l&&!0===t.dontStop&&(l.dontStop=!0)}else if(t.recv&&(c||(c=r.pc.addTransceiver(i)),c)){if(t.codec)if("firefox"===o.webRTCAdapter.browserDetails.browser)o.warn("setCodecPreferences not supported in Firefox, ignoring codec for track:",t);else if("string"!=typeof t.codec)o.warn("Invalid codec value, ignoring for track:",t);else{let e=i+"/"+t.codec.toLowerCase(),n=RTCRtpReceiver.getCapabilities(i).codecs.filter(function(t){return t.mimeType.toLowerCase()===e});if(n&&0!==n.length)try{c.setCodecPreferences(n)}catch(e){o.warn("Failed enforcing codec for this "+i+" track:",e)}else o.warn("Codec not supported in this browser for this track, ignoring:",t)}if(c.receiver&&t.transforms&&t.transforms.receiver){let e=null;RTCRtpReceiver.prototype.createEncodedStreams?e=c.receiver.createEncodedStreams():(RTCRtpReceiver.prototype.createAudioEncodedStreams||RTCRtpReceiver.prototype.createEncodedVideoStreams)&&("audio"===i?e=c.receiver.createEncodedAudioStreams():"video"===i&&(e=c.receiver.createEncodedVideoStreams())),e&&(console.log("Insertable Streams receiver transform:",e),e.readableStream&&e.writableStream?e.readableStream.pipeThrough(t.transforms.receiver).pipeTo(e.writableStream):e.readable&&e.writable&&e.readable.pipeThrough(t.transforms.receiver).pipeTo(e.writable))}}if(l){r.myStream.addTrack(l),l.onended=function(e){o.log("Local track removed:",e);try{n.onlocaltrack(e.target,!1)}catch(e){o.error("Error calling onlocaltrack following end",e)}};try{n.onlocaltrack(l,!0)}catch(e){o.error("Error calling onlocaltrack for track add",e)}}if(c){let e=c.direction,n=null,r=l&&c.sender.track,i=!1!==t.recv&&c.receiver.track;r&&i?n="sendrecv":r&&!i?n="sendonly":!r&&i?n="recvonly":r||i||(n="inactive"),n&&n!==e&&(o.warn("Changing direction of transceiver to "+n+" (was "+e+")",t),c.setDirection?c.setDirection(n):c.direction=n)}}s&&n.consentDialog(!1)}function G(e){let t=b.get(e);if(!t||!t.webrtcStuff)return o.warn("Invalid handle"),null;let n=t.webrtcStuff;if(!n.pc)return o.warn("Invalid PeerConnection"),null;let r=[],i=n.pc.getTransceivers();for(let e of i){let t=null;e.sender&&e.sender.track&&(t={mid:e.mid},t.type=e.sender.track.kind,t.id=e.sender.track.id,t.label=e.sender.track.label),t&&r.push(t)}return r}function U(e){let t=b.get(e);if(!t||!t.webrtcStuff)return o.warn("Invalid handle"),null;let n=t.webrtcStuff;if(!n.pc)return o.warn("Invalid PeerConnection"),null;let r=[],i=n.pc.getTransceivers();for(let e of i){let t=null;e.receiver&&e.receiver.track&&(t={mid:e.mid},t.type=e.receiver.track.kind,t.id=e.receiver.track.id,t.label=e.receiver.track.label),t&&r.push(t)}return r}function J(e,t,n,r){r="function"==typeof r?r:o.noop;let i=b.get(e);if(!i||!i.webrtcStuff)return o.warn("Invalid handle"),void r(0);let s=n?"remote":"local",a=i.webrtcStuff;if(a.volume[s]||(a.volume[s]={value:0}),a.pc&&a.pc.getStats&&("chrome"===o.webRTCAdapter.browserDetails.browser||"safari"===o.webRTCAdapter.browserDetails.browser)){let e=a.pc;if(t){let i=a.pc.getTransceivers().find(e=>e.mid===t&&"audio"===e.receiver.track.kind);if(!i)return o.warn("No audio transceiver with mid "+t),void r(0);if(n&&!i.receiver)return o.warn("Remote transceiver track unavailable"),void r(0);if(!n&&!i.sender)return o.warn("Local transceiver track unavailable"),void r(0);e=n?i.receiver:i.sender}return e.getStats().then(function(e){e.forEach(function(e){e&&"audio"===e.kind&&(n&&!e.remoteSource||!n&&"media-source"!==e.type||r(e.audioLevel?e.audioLevel:0))})}),a.volume[s].value}return o.warn("Getting the "+s+" volume unsupported by browser"),void r(0)}function F(e,t,n){let r=b.get(e);if(!r||!r.webrtcStuff)return o.warn("Invalid handle"),!0;let i=r.webrtcStuff;if(!i.pc)return o.warn("Invalid PeerConnection"),!0;if(!i.myStream)return o.warn("Invalid local MediaStream"),!0;if(n){if(!i.myStream.getVideoTracks()||0===i.myStream.getVideoTracks().length)return o.warn("No video track"),!0;if(t){let e=i.pc.getTransceivers().find(e=>e.mid===t&&"video"===e.receiver.track.kind);return e?e.sender&&e.sender.track?!e.sender.track.enabled:(o.warn("No video sender with mid "+t),!0):(o.warn("No video transceiver with mid "+t),!0)}return!i.myStream.getVideoTracks()[0].enabled}if(!i.myStream.getAudioTracks()||0===i.myStream.getAudioTracks().length)return o.warn("No audio track"),!0;if(t){let e=i.pc.getTransceivers().find(e=>e.mid===t&&"audio"===e.receiver.track.kind);return e?e.sender&&e.sender.track?!e.sender.track.enabled:(o.warn("No audio sender with mid "+t),!0):(o.warn("No audio transceiver with mid "+t),!0)}return!i.myStream.getAudioTracks()[0].enabled}function V(e,t,n,r){let i=b.get(e);if(!i||!i.webrtcStuff)return o.warn("Invalid handle"),!1;let s=i.webrtcStuff;if(!s.pc)return o.warn("Invalid PeerConnection"),!1;if(!s.myStream)return o.warn("Invalid local MediaStream"),!1;if(n){if(!s.myStream.getVideoTracks()||0===s.myStream.getVideoTracks().length)return o.warn("No video track"),!1;if(t){let e=s.pc.getTransceivers().find(e=>e.mid===t&&"video"===e.receiver.track.kind);if(!e)return o.warn("No video transceiver with mid "+t),!1;if(!e.sender||!e.sender.track)return o.warn("No video sender with mid "+t),!1;e.sender.track.enabled=!r}else for(const e of s.myStream.getVideoTracks())e.enabled=!r}else{if(!s.myStream.getAudioTracks()||0===s.myStream.getAudioTracks().length)return o.warn("No audio track"),!1;if(t){let e=s.pc.getTransceivers().find(e=>e.mid===t&&"audio"===e.receiver.track.kind);if(!e)return o.warn("No audio transceiver with mid "+t),!1;if(!e.sender||!e.sender.track)return o.warn("No audio sender with mid "+t),!1;e.sender.track.enabled=!r}else for(const e of s.myStream.getAudioTracks())e.enabled=!r}return!0}function W(e,t){let n=b.get(e);if(!n||!n.webrtcStuff)return o.warn("Invalid handle"),"Invalid handle";let r=n.webrtcStuff;if(!r.pc)return"Invalid PeerConnection";if(r.pc.getStats){let e=r.pc,n=t||"default";if(t){let n=r.pc.getTransceivers().find(e=>e.mid===t&&"video"===e.receiver.track.kind);if(!n)return o.warn("No video transceiver with mid "+t),"No video transceiver with mid "+t;if(!n.receiver)return o.warn("No video receiver with mid "+t),"No video receiver with mid "+t;e=n.receiver}return r.bitrate[n]||(r.bitrate[n]={timer:null,bsnow:null,bsbefore:null,tsnow:null,tsbefore:null,value:"0 kbits/sec"}),r.bitrate[n].timer?r.bitrate[n].value:(o.log("Starting bitrate timer"+(t?" for mid "+t:"")+" (via getStats)"),r.bitrate[n].timer=setInterval(function(){e.getStats().then(function(e){e.forEach(function(e){if(!e)return;let t=!1;if(("video"===e.mediaType||"video"===e.kind||e.id.toLowerCase().indexOf("video")>-1)&&"inbound-rtp"===e.type&&e.id.indexOf("rtcp")<0?t=!0:"ssrc"!=e.type||!e.bytesReceived||"VP8"!==e.googCodecName&&""!==e.googCodecName||(t=!0),t)if(r.bitrate[n].bsnow=e.bytesReceived,r.bitrate[n].tsnow=e.timestamp,null===r.bitrate[n].bsbefore||null===r.bitrate[n].tsbefore)r.bitrate[n].bsbefore=r.bitrate[n].bsnow,r.bitrate[n].tsbefore=r.bitrate[n].tsnow;else{let e=r.bitrate[n].tsnow-r.bitrate[n].tsbefore;"safari"===o.webRTCAdapter.browserDetails.browser&&(e/=1e3);let t=Math.round(8*(r.bitrate[n].bsnow-r.bitrate[n].bsbefore)/e);"safari"===o.webRTCAdapter.browserDetails.browser&&(t=parseInt(t/1e3)),r.bitrate[n].value=t+" kbits/sec",r.bitrate[n].bsbefore=r.bitrate[n].bsnow,r.bitrate[n].tsbefore=r.bitrate[n].tsnow}})})},1e3),"0 kbits/sec")}return o.warn("Getting the video bitrate unsupported by browser"),"Feature unsupported by browser"}function K(e,t,n){let r=b.get(e);if(!r||!r.webrtcStuff)return void o.warn("Invalid handle");let i=r.webrtcStuff;if(!i.pc)return void o.warn("Invalid PeerConnection");let s=i.pc.getTransceivers().find(e=>e.mid===t);if(!s)return void o.warn("No transceiver with mid",t);if(!s.sender)return void o.warn("No sender for transceiver with mid",t);let a=s.sender.getParameters();a&&a.encodings&&0!==a.encodings.length?a.encodings.length>1?o.warn("Ignoring bitrate for simulcast track, use sendEncodings for that"):isNaN(n)||n<0?o.warn("Invalid bitrate (must be a positive integer)"):(a.encodings[0].maxBitrate=n,s.sender.setParameters(a)):o.warn("No parameters encodings")}function $(e){o.error("WebRTC error:",e)}function z(e,r){o.log("Cleaning WebRTC stuff");let i=b.get(e);if(!i)return;let s=i.webrtcStuff;if(s){if(!0===r){let r={janus:"hangup",transaction:o.randomString(12)};i.token&&(r.token=i.token),m&&(r.apisecret=m),o.debug("Sending hangup request (handle="+e+"):"),o.debug(r),t?(r.session_id=T,r.handle_id=e,n.send(JSON.stringify(r))):o.httpAPICall(c+"/"+T+"/"+e,{verb:"POST",withCredentials:p,body:r})}s.volume&&(s.volume.local&&s.volume.local.timer&&clearInterval(s.volume.local.timer),s.volume.remote&&s.volume.remote.timer&&clearInterval(s.volume.remote.timer));for(let e in s.bitrate)s.bitrate[e].timer&&clearInterval(s.bitrate[e].timer);s.bitrate={},!s.streamExternal&&s.myStream&&(o.log("Stopping local stream tracks"),o.stopAllTracks(s.myStream)),s.streamExternal=!1,s.myStream=null;try{s.pc.close()}catch(e){}s.pc=null,s.candidates=null,s.mySdp=null,s.remoteSdp=null,s.iceDone=!1,s.dataChannel={},s.dtmfSender=null,s.insertableStreams=!1,s.externalEncryption=!1}i.oncleanup()}k(e),this.getServer=function(){return c},this.isConnected=function(){return y},this.reconnect=function(e){(e=e||{}).success="function"==typeof e.success?e.success:o.noop,e.error="function"==typeof e.error?e.error:o.noop,e.reconnect=!0,k(e)},this.getSessionId=function(){return T},this.getInfo=function(e){!function(e){if(e=e||{},e.success="function"==typeof e.success?e.success:o.noop,e.error="function"==typeof e.error?e.error:o.noop,o.log("Getting info on Janus instance"),!y)return o.warn("Is the server down? (connected=false)"),void e.error("Is the server down? (connected=false)");let r=o.randomString(12),i={janus:"info",transaction:r};h&&(i.token=h);m&&(i.apisecret=m);if(t)return w.set(r,function(t){o.log("Server info:"),o.debug(t),"server_info"!==t.janus&&o.error("Ooops: "+t.error.code+" "+t.error.reason),e.success(t)}),void n.send(JSON.stringify(i));o.httpAPICall(c,{verb:"POST",withCredentials:p,body:i,success:function(t){o.log("Server info:"),o.debug(t),"server_info"!==t.janus&&o.error("Ooops: "+t.error.code+" "+t.error.reason),e.success(t)},error:function(t,n){o.error(t+":",n),""===n?e.error(t+": Is the server down?"):e.error(t+": "+n)}})}(e)},this.destroy=function(s){!function(s){s=s||{},s.success="function"==typeof s.success?s.success:o.noop,s.error="function"==typeof s.error?s.error:o.noop;let a=!0===s.unload,d=!0;void 0!==s.notifyDestroyed&&null!==s.notifyDestroyed&&(d=!0===s.notifyDestroyed);let u=!0===s.cleanupHandles;if(o.log("Destroying session "+T+" (unload="+a+")"),!T)return o.warn("No session to destroy"),s.success(),void(d&&e.destroyed());if(u)for(const e of b.keys())O(e,{noRequest:!0});if(!y)return o.warn("Is the server down? (connected=false)"),T=null,void s.success();let l={janus:"destroy",transaction:o.randomString(12)};h&&(l.token=h);m&&(l.apisecret=m);if(a)return t?(n.onclose=null,n.close(),n=null):navigator.sendBeacon(c+"/"+T,JSON.stringify(l)),o.log("Destroyed session:"),T=null,y=!1,s.success(),void(d&&e.destroyed());if(t){l.session_id=T;let t=function(){for(let e in r)n.removeEventListener(e,r[e]);n.removeEventListener("message",o),n.removeEventListener("error",a),i&&clearTimeout(i),n.close()},o=function(n){let r=JSON.parse(n.data);r.session_id==l.session_id&&r.transaction==l.transaction&&(t(),s.success(),d&&e.destroyed())},a=function(){t(),s.error("Failed to destroy the server: Is the server down?"),d&&e.destroyed()};return n.addEventListener("message",o),n.addEventListener("error",a),void(1===n.readyState?n.send(JSON.stringify(l)):a())}o.httpAPICall(c+"/"+T,{verb:"POST",withCredentials:p,body:l,success:function(t){o.log("Destroyed session:"),o.debug(t),T=null,y=!1,"success"!==t.janus&&o.error("Ooops: "+t.error.code+" "+t.error.reason),s.success(),d&&e.destroyed()},error:function(t,n){o.error(t+":",n),T=null,y=!1,s.success(),d&&e.destroyed()}})}(s)},this.attach=function(e){!function(e){if(e=e||{},e.success="function"==typeof e.success?e.success:o.noop,e.error="function"==typeof e.error?e.error:o.noop,e.dataChannelOptions=e.dataChannelOptions||{ordered:!0},e.consentDialog="function"==typeof e.consentDialog?e.consentDialog:o.noop,e.connectionState="function"==typeof e.connectionState?e.connectionState:o.noop,e.iceState="function"==typeof e.iceState?e.iceState:o.noop,e.mediaState="function"==typeof e.mediaState?e.mediaState:o.noop,e.webrtcState="function"==typeof e.webrtcState?e.webrtcState:o.noop,e.slowLink="function"==typeof e.slowLink?e.slowLink:o.noop,e.onmessage="function"==typeof e.onmessage?e.onmessage:o.noop,e.onlocaltrack="function"==typeof e.onlocaltrack?e.onlocaltrack:o.noop,e.onremotetrack="function"==typeof e.onremotetrack?e.onremotetrack:o.noop,e.ondata="function"==typeof e.ondata?e.ondata:o.noop,e.ondataopen="function"==typeof e.ondataopen?e.ondataopen:o.noop,e.oncleanup="function"==typeof e.oncleanup?e.oncleanup:o.noop,e.ondetached="function"==typeof e.ondetached?e.ondetached:o.noop,!y)return o.warn("Is the server down? (connected=false)"),void e.error("Is the server down? (connected=false)");let r=e.plugin;if(!r)return o.error("Invalid plugin"),void e.error("Invalid plugin");let i=e.opaqueId,s=e.loopIndex,a=e.token?e.token:h,d=o.randomString(12),u={janus:"attach",plugin:r,opaque_id:i,loop_index:s,transaction:d};a&&(u.token=a);m&&(u.apisecret=m);if(t)return w.set(d,function(t){if(o.debug(t),"success"!==t.janus)return o.error("Ooops: "+t.error.code+" "+t.error.reason),void e.error("Ooops: "+t.error.code+" "+t.error.reason);let n=t.data.id;o.log("Created handle: "+n);let i={session:S,plugin:r,id:n,token:a,detached:!1,webrtcStuff:{started:!1,myStream:null,streamExternal:!1,mySdp:null,mediaConstraints:null,pc:null,dataChannelOptions:e.dataChannelOptions,dataChannel:{},dtmfSender:null,trickle:!0,iceDone:!1,bitrate:{}},getId:function(){return n},getPlugin:function(){return r},getVolume:function(e,t){return J(n,e,!0,t)},getRemoteVolume:function(e,t){return J(n,e,!0,t)},getLocalVolume:function(e,t){return J(n,e,!1,t)},isAudioMuted:function(e){return F(n,e,!1)},muteAudio:function(e){return V(n,e,!1,!0)},unmuteAudio:function(e){return V(n,e,!1,!1)},isVideoMuted:function(e){return F(n,e,!0)},muteVideo:function(e){return V(n,e,!0,!0)},unmuteVideo:function(e){return V(n,e,!0,!1)},getBitrate:function(e){return W(n,e)},setMaxBitrate:function(e,t){return K(n,e,t)},send:function(e){P(n,e)},data:function(e){A(n,e)},dtmf:function(e){D(n,e)},consentDialog:e.consentDialog,connectionState:e.connectionState,iceState:e.iceState,mediaState:e.mediaState,webrtcState:e.webrtcState,slowLink:e.slowLink,onmessage:e.onmessage,createOffer:function(e){L(n,!0,e)},createAnswer:function(e){L(n,!1,e)},handleRemoteJsep:function(e){M(n,e)},replaceTracks:function(e){j(n,e)},getLocalTracks:function(){return G(n)},getRemoteTracks:function(){return U(n)},onlocaltrack:e.onlocaltrack,onremotetrack:e.onremotetrack,ondata:e.ondata,ondataopen:e.ondataopen,oncleanup:e.oncleanup,ondetached:e.ondetached,hangup:function(e){z(n,!0===e)},detach:function(e){O(n,e)}};b.set(n,i),e.success(i)}),u.session_id=T,void n.send(JSON.stringify(u));o.httpAPICall(c+"/"+T,{verb:"POST",withCredentials:p,body:u,success:function(t){if(o.debug(t),"success"!==t.janus)return o.error("Ooops: "+t.error.code+" "+t.error.reason),void e.error("Ooops: "+t.error.code+" "+t.error.reason);let n=t.data.id;o.log("Created handle: "+n);let i={session:S,plugin:r,id:n,token:a,detached:!1,webrtcStuff:{started:!1,myStream:null,streamExternal:!1,mySdp:null,mediaConstraints:null,pc:null,dataChannelOptions:e.dataChannelOptions,dataChannel:{},dtmfSender:null,trickle:!0,iceDone:!1,bitrate:{}},getId:function(){return n},getPlugin:function(){return r},getVolume:function(e,t){return J(n,e,!0,t)},getRemoteVolume:function(e,t){return J(n,e,!0,t)},getLocalVolume:function(e,t){return J(n,e,!1,t)},isAudioMuted:function(e){return F(n,e,!1)},muteAudio:function(e){return V(n,e,!1,!0)},unmuteAudio:function(e){return V(n,e,!1,!1)},isVideoMuted:function(e){return F(n,e,!0)},muteVideo:function(e){return V(n,e,!0,!0)},unmuteVideo:function(e){return V(n,e,!0,!1)},getBitrate:function(e){return W(n,e)},setMaxBitrate:function(e,t){return K(n,e,t)},send:function(e){P(n,e)},data:function(e){A(n,e)},dtmf:function(e){D(n,e)},consentDialog:e.consentDialog,connectionState:e.connectionState,iceState:e.iceState,mediaState:e.mediaState,webrtcState:e.webrtcState,slowLink:e.slowLink,onmessage:e.onmessage,createOffer:function(e){L(n,!0,e)},createAnswer:function(e){L(n,!1,e)},handleRemoteJsep:function(e){M(n,e)},replaceTracks:function(e){j(n,e)},getLocalTracks:function(){return G(n)},getRemoteTracks:function(){return U(n)},onlocaltrack:e.onlocaltrack,onremotetrack:e.onremotetrack,ondata:e.ondata,ondataopen:e.ondataopen,oncleanup:e.oncleanup,ondetached:e.ondetached,hangup:function(e){z(n,!0===e)},detach:function(e){O(n,e)}};b.set(n,i),e.success(i)},error:function(t,n){o.error(t+":",n),""===n?e.error(t+": Is the server down?"):e.error(t+": "+n)}})}(e)},this.keepalive=()=>function(){if(!i)return;if(!c||!t||!y)return void console.log("server:",c,",","websockets:",t,",","connected:",y);let e={janus:"keepalive",session_id:T,transaction:o.randomString(12)};h&&(e.token=h);m&&(e.apisecret=m);n.send(JSON.stringify(e))}()}o.useDefaultDependencies=function(e){let t=e&&e.fetch||fetch,n=e&&e.Promise||Promise,r=e&&e.WebSocket||WebSocket;return{newWebSocket:function(e,t){return new r(e,t)},extension:e&&e.extension||i,isArray:function(e){return Array.isArray(e)},webRTCAdapter:e&&e.adapter||adapter,httpAPICall:function(e,r){let i={method:r.verb,headers:{Accept:"application/json, text/plain, */*"},cache:"no-cache"};"POST"===r.verb&&(i.headers["Content-Type"]="application/json"),void 0!==r.withCredentials&&(i.credentials=!0===r.withCredentials?"include":r.withCredentials?r.withCredentials:"omit"),r.body&&(i.body=JSON.stringify(r.body));let s=t(e,i).catch(function(e){return n.reject({message:"Probably a network error, is the server down?",error:e})});if(r.timeout){let e=new n(function(e,t){let n=setTimeout(function(){return clearTimeout(n),t({message:"Request timed out",timeout:r.timeout})},r.timeout)});s=n.race([s,e])}return s.then(function(e){return e.ok?typeof r.success==typeof o.noop?e.json().then(function(e){try{r.success(e)}catch(e){o.error("Unhandled httpAPICall success callback error",e)}},function(t){return n.reject({message:"Failed to parse response body",error:t,response:e})}):void 0:n.reject({message:"API call failed",response:e})}).catch(function(e){typeof r.error==typeof o.noop&&r.error(e.message||"<< internal error >>",e)}),s}}},o.useOldDependencies=function(e){let t=e&&e.jQuery||jQuery,n=e&&e.WebSocket||WebSocket;return{newWebSocket:function(e,t){return new n(e,t)},isArray:function(e){return t.isArray(e)},extension:e&&e.extension||i,webRTCAdapter:e&&e.adapter||adapter,httpAPICall:function(e,n){let r=void 0!==n.body?{contentType:"application/json",data:JSON.stringify(n.body)}:{},i=void 0!==n.withCredentials?{xhrFields:{withCredentials:n.withCredentials}}:{};return t.ajax(t.extend(r,i,{url:e,type:n.verb,cache:!1,dataType:"json",async:n.async,timeout:n.timeout,success:function(e){typeof n.success==typeof o.noop&&n.success(e)},error:function(e,t,r){typeof n.error==typeof o.noop&&n.error(t,r)}}))}}},o.mediaToTracks=function(e){let t=[];if(e){if(!e.keepAudio&&!1!==e.audio&&(void 0===e.audio||e.audio||e.audioSend||e.audioRecv||e.addAudio||e.replaceAudio||e.removeAudio)){let n={type:"audio"};e.removeAudio?n.remove=!0:(e.addAudio?n.add=!0:e.replaceAudio&&(n.replace=!0),!1!==e.audioSend&&(n.capture=e.audio||!0),!1!==e.audioRecv&&(n.recv=!0)),(n.remove||n.capture||n.recv)&&t.push(n)}if(!e.keepVideo&&!1!==e.video&&(void 0===e.video||e.video||e.videoSend||e.videoRecv||e.addVideo||e.replaceVideo||e.removeVideo)){let n={type:"video"};e.removeVideo?n.remove=!0:(e.addVideo?n.add=!0:e.replaceVideo&&(n.replace=!0),!1!==e.videoSend&&(n.capture=e.video||!0,["screen","window","desktop"].includes(n.capture)&&(n.type="screen",n.capture={video:{}},e.screenshareFrameRate&&(n.capture.frameRate=e.screenshareFrameRate),e.screenshareHeight&&(n.capture.height=e.screenshareHeight),e.screenshareWidth&&(n.capture.width=e.screenshareWidth))),!1!==e.videoRecv&&(n.recv=!0)),(n.remove||n.capture||n.recv)&&t.push(n)}e.data&&t.push({type:"data"})}else t.push({type:"audio",capture:!0,recv:!0}),t.push({type:"video",capture:!0,recv:!0});return t},o.trackConstraints=function(e){let t={};if(!e||!e.capture)return t;if("audio"===e.type)t.audio=e.capture;else if("video"===e.type)if((e.simulcast||e.svc)&&!0===e.capture&&(e.capture="hires"),!0===e.capture||"object"==typeof e.capture)t.video=e.capture;else{let n=0,r=0;"lowres"===e.capture?(n=320,r=240):"lowres-16:9"===e.capture?(n=320,r=180):"hires"===e.capture||"hires-16:9"===e.capture||"hdres"===e.capture?(n=1280,r=720):"fhdres"===e.capture?(n=1920,r=1080):"4kres"===e.capture?(n=3840,r=2160):"stdres"===e.capture?(n=640,r=480):"stdres-16:9"===e.capture?(n=640,r=360):(o.log("Default video setting is stdres 4:3"),n=640,r=480),t.video={width:{ideal:n},height:{ideal:r}}}else"screen"===e.type&&(t.video=e.capture);return t},o.noop=function(){},o.dataChanDefaultLabel="JanusDataChannel",o.endOfCandidates=null,o.stopAllTracks=function(e){try{let t=e.getTracks();for(let e of t)o.log(e),e&&!0!==e.dontStop&&e.stop()}catch(e){}},o.init=function(e){if((e=e||{}).callback="function"==typeof e.callback?e.callback:o.noop,o.initDone)e.callback();else{if(void 0===console.log&&(console.log=function(){}),o.trace=o.noop,o.debug=o.noop,o.vdebug=o.noop,o.log=o.noop,o.warn=o.noop,o.error=o.noop,!0===e.debug||"all"===e.debug)o.trace=console.trace.bind(console),o.debug=console.debug.bind(console),o.vdebug=console.debug.bind(console),o.log=console.log.bind(console),o.warn=console.warn.bind(console),o.error=console.error.bind(console);else if(Array.isArray(e.debug))for(let t of e.debug)switch(t){case"trace":o.trace=console.trace.bind(console);break;case"debug":o.debug=console.debug.bind(console);break;case"vdebug":o.vdebug=console.debug.bind(console);break;case"log":o.log=console.log.bind(console);break;case"warn":o.warn=console.warn.bind(console);break;case"error":o.error=console.error.bind(console);break;default:console.error("Unknown debugging option '"+t+"' (supported: 'trace', 'debug', 'vdebug', 'log', warn', 'error')")}o.log("Initializing library");let t=e.dependencies||o.useDefaultDependencies();o.isArray=t.isArray,o.webRTCAdapter=t.webRTCAdapter,o.httpAPICall=t.httpAPICall,o.newWebSocket=t.newWebSocket,o.extension=t.extension,o.extension.init(),o.listDevices=function(e,t){e="function"==typeof e?e:o.noop,t||(t={audio:!0,video:!0}),o.isGetUserMediaAvailable()?navigator.mediaDevices.getUserMedia(t).then(function(t){navigator.mediaDevices.enumerateDevices().then(function(n){o.debug(n),e(n),o.stopAllTracks(t)})}).catch(function(t){o.error(t),e([])}):(o.warn("navigator.mediaDevices unavailable"),e([]))},o.attachMediaStream=function(e,t){try{e.srcObject=t}catch(n){try{e.src=URL.createObjectURL(t)}catch(e){o.error("Error attaching stream to element",e)}}},o.reattachMediaStream=function(e,t){try{e.srcObject=t.srcObject}catch(n){try{e.src=t.src}catch(e){o.error("Error reattaching stream to element",e)}}};let n=["iPad","iPhone","iPod"].indexOf(navigator.platform)>=0?"pagehide":"beforeunload",r=window["on"+n];if(window.addEventListener(n,function(){o.log("Closing window");for(const[e,t]of o.sessions)t&&t.destroyOnUnload&&(o.log("Destroying session "+e),t.destroy({unload:!0,notifyDestroyed:!1}));r&&"function"==typeof r&&r()}),o.safariVp8=!1,o.safariVp9=!1,"safari"===o.webRTCAdapter.browserDetails.browser&&o.webRTCAdapter.browserDetails.version>=605)if(RTCRtpSender&&RTCRtpSender.getCapabilities&&RTCRtpSender.getCapabilities("video")&&RTCRtpSender.getCapabilities("video").codecs&&RTCRtpSender.getCapabilities("video").codecs.length){for(let e of RTCRtpSender.getCapabilities("video").codecs)e&&e.mimeType&&"video/vp8"===e.mimeType.toLowerCase()?o.safariVp8=!0:e&&e.mimeType&&"video/vp9"===e.mimeType.toLowerCase()&&(o.safariVp9=!0);o.safariVp8?o.log("This version of Safari supports VP8"):o.warn("This version of Safari does NOT support VP8: if you're using a Technology Preview, try enabling the 'WebRTC VP8 codec' setting in the 'Experimental Features' Develop menu")}else{let e=new RTCPeerConnection({});e.createOffer({offerToReceiveVideo:!0}).then(function(t){o.safariVp8=-1!==t.sdp.indexOf("VP8"),o.safariVp9=-1!==t.sdp.indexOf("VP9"),o.safariVp8?o.log("This version of Safari supports VP8"):o.warn("This version of Safari does NOT support VP8: if you're using a Technology Preview, try enabling the 'WebRTC VP8 codec' setting in the 'Experimental Features' Develop menu"),e.close(),e=null})}o.initDone=!0,e.callback()}},o.isWebrtcSupported=function(){return!!window.RTCPeerConnection},o.isGetUserMediaAvailable=function(){return navigator.mediaDevices&&navigator.mediaDevices.getUserMedia},o.randomString=function(e){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n="";for(let r=0;r<e;r++){let e=Math.floor(62*Math.random());n+=t.charAt(e)}return n};function s(e,t=1e4){const n=new Worker(((e=1e4)=>URL.createObjectURL(new Blob([`\n self.onmessage = (e) => {\n if (e.data === 'START') {\n // 每10秒发送一次心跳(避免过度耗电)\n setInterval(() => {\n self.postMessage('heartbeat');\n }, ${e});\n }\n };\n `])))(t));return n.postMessage("START"),n.onmessage=t=>{"heartbeat"===t.data&&(console.log("Worker active at:",new Date),e())},window.addEventListener("unload",()=>{n.terminate()}),n}const a={url:null,queue:[],timer:null,batchSize:20,flushInterval:5e3,push(e,t,n){const r=`[${(new Date).toLocaleString("zh-CN",{hour12:!1})}] [VoiceNine] [${t}]`;"warn"===e?console.warn(r,n):"error"===e?console.error(r,n):console.log(r,n)}};function c(e,t){a.push("info",e,t)}function d(e,t){a.push("warn",e,t)}function u(e,t,n){a.push("error",e,n?`${t} ${n}`:t)}const l={agentId:"",agentKey:"",companyId:"",agentType:"",token:"",wsServer:"",webrtcServer:"",sipServer:"",agentCode:"",sipPwd:"",groupId:"",groupIds:[]};const p=new class{instance=null;socket=null;connected=!1;janus=null;sipcall=null;stream=null;events={};seat={};callId=null;conference=null;conferenceList=[];status=e.LOGIN;lastStatus=e.LOGIN;reconnectState=null;autoAcceptTimer=null;code=0;msg=null;jsep=null;isHangup=!1;_userLogout=!1;_janusRetryCount=0;_janusRetryTimer=null;_janusMaxRetries=10;_sipRetryCount=0;_sipRetryTimer=null;_sipMaxRetries=5;_webrtcDownTimer=null;_sipRegisterTimeout=null;_sipRegistered=!1;_dtlsCheckTimer=null;_iceDisconnectTimer=null;constructor(){if(this.instance)return this.instance;this.instance=this,s(()=>{this._keepalive(),this.janus&&!this._userLogout&&this.janus?.keepalive()})}_init(e){this.seat={...l,...e},this.reconnectState=null,this._userLogout=!1,this._initMedia();const t=`${this.seat.wsServer}?token=${this.seat.token}`;this.connectWs(t)}_initMedia(){const e=document.getElementById("mediaContainer");e&&(e.parentNode.removeChild(e),c("_initMedia","清理旧的媒体容器"));const t=document.createElement("div");t.id="mediaContainer",t.style.width="0px",t.style.height="0px",t.style.position="absolute",t.style.top="0px",t.style.left="0px",t.style.zIndex="-1",t.style.visibility="hidden",t.style.overflow="hidden",document.body.appendChild(t);const n=document.createElement("audio");n.id="incomingcallAudio",n.loop=!0,n.src="https://r.hanfatong.com/voicenine/beep.mp3",t.appendChild(n);const r=document.createElement("audio");r.id="callEndAudio",r.loop=!1,r.src="https://r.hanfatong.com/voicenine/hangup.mp3",t.appendChild(r);const i=document.createElement("audio");i.id="peerVideo",i.autoplay=!0,t.appendChild(i)}_initJanus(){const{webrtcServer:t,sipServer:n}=this.seat;if(!t||!n)return void u("_initJanus","WebRTC server or SIP server is not configured.");if(this.janus){c("_initJanus","检测到旧 Janus session,先销毁");try{this.janus.destroy({cleanupHandles:!0,notifyDestroyed:!1})}catch(e){d("_initJanus","销毁旧 Janus 异常")}this.janus=null,this.sipcall=null}let r={},i={},s=!1;o.init({debug:"all",callback:()=>{c("_initJanus","Janus initialized.");if(!o.isWebrtcSupported())return void d("_initJanus","No WebRTC support or not HTTPS.");this.trigger("connstate",{type:"janus",state:"connecting"}),this._sipRegisterTimeout&&clearTimeout(this._sipRegisterTimeout),this._sipRegisterTimeout=setTimeout(()=>{this.sipcall&&!this._sipRegistered&&this.connected&&!this._userLogout&&(d("_initJanus","SIP 注册超时(15s),重建 Janus"),this._rebuildJanus())},15e3),this._sipRegistered=!1;const n=new o({server:t,success:()=>{this.trigger("connstate",{type:"janus",state:"connected"}),n.attach({plugin:"janus.plugin.sip",opaqueId:"voicenine_"+o.randomString(16),success:e=>{c("_initJanus","SIP plugin attached."),this.sipcall=e,this._janusRetryCount=0,this._sipRetryCount=0,this._registerSip()},onmessage:(t,n)=>{o.debug(" ::: Got a message :::",t);const{call_id:r,result:i}=t;if(i?.event){const a=i.event;if("registration_failed"===a)d("_initJanus","SIP registration failed: "+i.code+" "+i.reason),this.trigger("sipstate",{registered:!1,code:i.code,reason:i.reason}),this._retrySipRegister(i.code);else if("registered"===a)c("_initJanus","SIP registered: "+i.username),this._sipRegistered=!0,this._sipRegisterTimeout&&(clearTimeout(this._sipRegisterTimeout),this._sipRegisterTimeout=null),s||(s=!0,i.master_id),this.trigger("sipstate",{registered:!0,username:i.username});else if("calling"===a)c("_initJanus","calling...");else if("incomingcall"===a){c("_initJanus","incomingcall"),this.sipcall.callId=r,this.toggleRing(!0),n&&n.sdp&&(n.sdp=this._sanitizeSdp(n.sdp)),this.msg=t,this.jsep=n;const i=()=>{2==this.seat.workType||this.status===e.OUT_CALL||this.status===e.OUT_CALLER_RING?(this.autoAcceptTimer&&clearTimeout(this.autoAcceptTimer),this.accept(t,n)):this.status!==e.READY&&this.status!==e.NOT_READY&&this.status!==e.WORK_NOT_READY&&this.status!==e.AFTER||(this.autoAcceptTimer&&clearTimeout(this.autoAcceptTimer),this.autoAcceptTimer=setTimeout(()=>i(),50))};2==this.seat.loginType&&i()}else if("accepting"===a);else if("progress"===a)c("_initJanus","progress"),n&&(n.sdp&&(n.sdp=this._sanitizeSdp(n.sdp)),this.sipcall.handleRemoteJsep({jsep:n}));else if("accepted"===a)c("_initJanus","accepted"),this.toggleRing(!1),n&&(n.sdp&&(n.sdp=this._sanitizeSdp(n.sdp)),this.sipcall.handleRemoteJsep({jsep:n})),this.sipcall.callId=r;else if("updatingcall"===a){c("_initJanus","updatingcall");const e=n.sdp.indexOf("m=audio ")>-1,t=[];e&&!this.sipcall.doAudio&&(this.sipcall.doAudio=!0,t.push({type:"audio",capture:!0,recv:!0})),this.sipcall.createAnswer({jsep:n,tracks:t,success:t=>{o.debug("Got SDP "+t.type+"! audio="+e+":",t);this.sipcall.send({message:{request:"update"},jsep:t})},error:e=>{this.trigger("error",e),u("createAnswer","WebRTC error",e)}})}else if("message"===a);else if("info"===a);else if("notify"===a);else if("transfer"===a);else if("hangup"===a){c("_initJanus",`hangup: ${i.code} ${i.reason}`),this.msg=null,this.jsep=null;const e=i.reason||"",t=this.status&&this.status.includes("TALKING");if(e.includes("DTLS")&&this._dtlsRebuildNeeded&&this.connected&&t)return void this._onDtlsAlert();this._dtlsRebuildNeeded=!1,this._webrtcDownTimer&&(clearTimeout(this._webrtcDownTimer),this._webrtcDownTimer=null),setTimeout(()=>{this.toggleRing(!1)},0),setTimeout(()=>{this.sipcall&&this.sipcall.hangup()},150)}}},onlocaltrack:(e,t)=>{c("onlocaltrack",`${t?"added":"removed"} kind=${e.kind}`);const n=e.id.replace(/[{}]/g,"");if(!t){if(this.stream=r[n],this.stream)try{const e=this.stream.getTracks(),t=e.some(e=>"audio"===e.kind&&e.getSettings().deviceId&&e.label.toLowerCase().includes("bluetooth"));setTimeout(()=>{e.forEach(e=>{e&&"ended"!==e.readyState&&("audio"===e.kind?(e.enabled=!1,setTimeout(()=>e.stop(),50)):e.stop())})},t?300:100)}catch(e){u("onlocaltrack","停止本地轨道失败",e)}return e.kind,void delete r[n]}this.stream=r[n],this.stream||(e.kind,"completed"!==this.sipcall.webrtcStuff.pc.iceConnectionState&&this.sipcall.webrtcStuff.pc.iceConnectionState)},onremotetrack:function(e,t,n){if(n&&"audio"===e.kind){this.stream=new MediaStream([e]),i[t]=this.stream;let n=document.getElementById("peerVideo");o.attachMediaStream(n,this.stream)}},oncleanup:()=>{c("oncleanup","cleanup notification"),setTimeout(()=>{this.sipcall&&(delete this.sipcall.callId,delete this.sipcall.doAudio)},50),setTimeout(()=>{Object.values(r).forEach(e=>{if(e){e.getTracks().forEach(e=>{"ended"!==e.readyState&&e.stop()})}})},100),setTimeout(()=>{r={},i={},this.stream=null,this._iceRestarting=!1,this._dtlsRebuildNeeded=!1,this._iceRestartCooldown=null},200)},error:e=>{u("_initJanus","attach plugin error",e),this.connected&&!this._userLogout&&this._retryJanus("attach_error")},consentDialog:function(e){},webrtcTimeout:function(e){c("webrtcTimeout",e)},iceState:e=>{c("iceState",e),"disconnected"===e||"failed"===e?this._iceRestart(e):"connected"!==e&&"completed"!==e||(this._onIceRestartSuccess(),this._webrtcDownTimer&&(clearTimeout(this._webrtcDownTimer),this._webrtcDownTimer=null))},mediaState:(e,t,n)=>{c("mediaState",`${e} ${t?"started":"stopped"} mid=${n}`),"audio"===e&&t&&this._iceRestarting&&this._onIceRestartSuccess()},webrtcState:e=>{if(c("webrtcState",e?"up":"down"),e)this._webrtcDownTimer&&(clearTimeout(this._webrtcDownTimer),this._webrtcDownTimer=null);else{const e=this.status&&this.status.includes("TALKING");!this.isHangup&&this.connected&&!this._userLogout&&e&&(this._webrtcDownTimer&&clearTimeout(this._webrtcDownTimer),this._webrtcDownTimer=setTimeout(()=>{this._webrtcDownTimer=null;const e=this.status&&this.status.includes("TALKING");this.connected&&!this._userLogout&&!this._iceRestarting&&e&&(d("webrtcState","WebRTC down 超时,重建 Janus session"),this.trigger("icestate",{state:"failed",reason:"webrtc_down"}),this._rebuildJanus())},8e3))}},slowLink:function(e,t,n){d("slowLink",`${e?"sending":"receiving"} lost=${t} mid=${n}`)}})},error:e=>{u("_initJanus","janus session error",e),this.trigger("connstate",{type:"janus",state:"failed",reason:e}),this.connected&&!this._userLogout&&this._retryJanus("session_error")},destroyed:()=>{c("_initJanus","destroyed")}});this.janus=n,window.Janus=o}})}_keepalive(){if(!this.socket||!this.connected||this.socket.readyState!==WebSocket.OPEN)return;let e={cmd:"ping",agentKey:this.seat.agentKey,sequence:(new Date).getTime()};this.echo(JSON.stringify(e))}accept(e,t){(0,this.sipcall.createAnswer)({jsep:t,media:{audio:!0,video:!1},success:e=>{this.sipcall.send({message:{request:"accept"},jsep:e})},error:e=>{u("accept","WebRTC error",e),this.trigger("error",e);this.sipcall.send({message:{request:"decline",code:480}})}}),this.autoAcceptTimer&&clearTimeout(this.autoAcceptTimer)}echo(e){if(this.socket&&this.socket.readyState===WebSocket.OPEN){try{const t=JSON.parse(e);"ping"!==t.cmd&&c("echo",`cmd=${t.cmd} agentKey=${t.agentKey||""}`)}catch{c("echo","发送消息")}this.socket.send(e)}else d("echo","WebSocket 未连接,消息丢弃")}toggleRing(e){const t=document.getElementById("incomingcallAudio");e?t.play():t.pause()}playEndRing(){document.getElementById("callEndAudio").play()}connectWs(t){if(c("connectWs","连接WebSocket: "+t.split("?")[0]),!window.WebSocket)return void alert("您的浏览器不支持WebSocket协议!");this.trigger("connstate",{type:"ws",state:"connecting"});const n=new WebSocket(t);this.socket=n,n.onmessage=t=>{const n=JSON.parse(t.data);"PONG"!==n.type&&"pong"!==n.type&&c("onmessage",`type=${n.type} code=${n.code} agentKey=${n.agentKey||""}`),this.onmessage(n);let r=n.type;e[r]&&(0===n.code&&(this.lastStatus=this.status,this.status=r,c("onmessage",`状态变更: ${this.lastStatus} -> ${this.status}`)),this.code=n.code,this.handleStatusChange(n))},n.onopen=()=>{c("connectWs","WebSocket connection opened."),this.clearReconectStatus(),this.sendAction(e.LOGIN),this.connected=!0,this.trigger("connstate",{type:"ws",state:"connected"})},n.onclose=e=>{c("connectWs",`WebSocket connection closed, Code: ${e.code}${e.reason?", Reason: "+e.reason:""}`),this.reconectInterval&&clearInterval(this.reconectInterval),this.connected=!1;if(this.trigger("logout",this.code),this.trigger("connstate",{type:"ws",state:"closed",code:e.code,reason:e.reason}),2===this.seat.loginType){if(this.sipcall&&this.status&&this.status.includes("TALKING")){d("connectWs","WS 断开,挂断当前通话");try{this.sipcall.send({message:{request:"hangup"}}),this.sipcall.hangup()}catch(e){}this.isHangup=!0,this.toggleRing(!1)}this.janus?.destroy(),this.janus=null,this.sipcall=null}[1111,1403,1105,1417].includes(this.code)?c("connectWs","不自动重连, code: "+this.code):this._userLogout||1e3===e.code&&"Bye"===e.reason?c("connectWs","主动登出,不自动重连"):this.reconectInterval=setInterval(()=>{2===this.seat.loginType&&(this.janus?.destroy(),this.janus=null,this.sipcall=null);const e=`${this.seat.wsServer}?token=${this.seat.token}`;this.connectWs(e)},5e3)}}changeStatus(e){this.echo(`{"cmd":"${e}", "agentKey": "${this.seat.agentKey}", "sequence": ${(new Date).getTime()} }`),this.afterPhoneInterval&&window.clearInterval(this.afterPhoneInterval)}handleStatusChange(t){const{type:n,message:r,code:i,data:o}=t;if(o&&o.callId&&(this.callId=o.callId),o&&o.conference&&(this.conference=o.conference),o&&o.conferenceList?this.conferenceList=o.conferenceList:this.conferenceList=[],n===e.LOGIN)2===this.seat.loginType&&0===i&&(this._janusRetryTimer&&(clearTimeout(this._janusRetryTimer),this._janusRetryTimer=null),this._janusRetryCount=0,this._initJanus()),null==this.reconnectState?this.sendAction(o.loginState):this.sendAction(this.reconnectState);else if(n===e.AFTER){this.lastStatus.includes("TALKING")&&(this.isHangup?this.isHangup=!1:this.playEndRing()),2===o.loginType&&0===o.answerTime&&("404"!==o.sipStatus&&"483"!==o.sipStatus||this._initJanus());const t=o.afterInterval||3;this.afterPhoneInterval=setTimeout(()=>{this.status===e.AFTER&&(c("handleStatusChange","话后自动空闲"),this.sendAction(e.READY))},1e3*t)}else n===e.OUT_CALL||(n===e.READY||n===e.NOT_READY||n===e.WORK_NOT_READY)&&(this.reconnectState=n);this.trigger("state",t),this.trigger(n,t)}sendAction(e,n){let r={cmd:e,agentKey:this.seat.agentKey,sequence:(new Date).getTime()};if(e===t.login)r={...r,loginType:this.seat.loginType,workType:this.seat.workType},this.status&&this.status.includes("TALKING")&&(r.callId=this.callId);else if(e===t.call){this.afterPhoneInterval&&window.clearInterval(this.afterPhoneInterval);const{telNum:e,display:t="",followData:i}=n||{};r={...r,called:e,display:t,callType:1,followData:i||{}}}else if(e===t.transfer){let{transferValue:e,transferType:t="4"}=n||{};e.includes("@")&&(t="3"),r={...r,transferType:t,transferValue:e}}else if(e===t.consult){const{consultValue:e}=n||{};let t="2";e.includes("@")&&(t="4"),r={...r,callId:this.callId,transferType:t,consultValue:e}}else if(e===t.consult_cancel);else if(e===t.consult_party)r.callId=this.callId;else if(e===t.consult_transfer)r.callId=this.callId;else if(e===t.busy_work){const{busyDesc:e}=n||{};r={...r,busyDesc:e,callId:this.callId}}else if(e===t.ready)this.afterPhoneInterval&&window.clearInterval(this.afterPhoneInterval);else if(e===t.busy)this.afterPhoneInterval&&window.clearInterval(this.afterPhoneInterval);else if(e===t.conference_remove){const{deviceId:t,memberId:i,username:o}=n||{};r={cmd:e,callId:this.callId,deviceId:t,conference:this.conference,memberId:i,username:o}}else{if(e===t.logout){this._userLogout=!0,this._janusRetryTimer&&(clearTimeout(this._janusRetryTimer),this._janusRetryTimer=null),this._sipRetryTimer&&(clearTimeout(this._sipRetryTimer),this._sipRetryTimer=null),this._sipRegisterTimeout&&(clearTimeout(this._sipRegisterTimeout),this._sipRegisterTimeout=null),this._webrtcDownTimer&&(clearTimeout(this._webrtcDownTimer),this._webrtcDownTimer=null),this._dtlsCheckTimer&&(clearTimeout(this._dtlsCheckTimer),this._dtlsCheckTimer=null),this._iceDisconnectTimer&&(clearTimeout(this._iceDisconnectTimer),this._iceDisconnectTimer=null);const e=JSON.stringify(r);return this.echo(e),void(2===this.seat.loginType&&this.janus?.destroy())}e===t.followdata?r={...r,callId:this.callId,followData:n.followData||{}}:e===t.hangup&&(this.isHangup=!0,this._webrtcDownTimer&&(clearTimeout(this._webrtcDownTimer),this._webrtcDownTimer=null),this.callId&&(r={...r,callId:this.callId}))}const i=JSON.stringify(r);this.echo(i)}clearReconectStatus(){this.reconectInterval&&clearInterval(this.reconectInterval)}_iceRestart(e){if(this._userLogout||!this.connected)return;if(!(this.status&&this.status.includes("TALKING")))return void("failed"===e&&(d("_iceRestart",`ICE ${e}(非通话状态),重建 Janus session`),this.trigger("icestate",{state:"failed",reason:"ice_setup_failed"}),this._rebuildJanus()));const t=Date.now();this._iceRestartCooldown&&t<this._iceRestartCooldown?"failed"===e?(d("_iceRestart","ICE failed(冷却期内),上次 restart 未恢复,重建 Janus"),this.trigger("icestate",{state:"failed",reason:"ice_restart_ineffective"}),this._rebuildJanus()):(d("_iceRestart",`ICE ${e},冷却期内跳过(剩余 ${this._iceRestartCooldown-t}ms),等待恢复`),this._iceDisconnectTimer||(this._iceDisconnectTimer=setTimeout(()=>{if(this._iceDisconnectTimer=null,!this.connected||this._userLogout)return;if(this.status&&this.status.includes("TALKING")){try{const e=this.sipcall?.webrtcStuff?.pc,t=e?.iceConnectionState;if("connected"===t||"completed"===t)return void c("_iceRestart","ICE disconnected 后自动恢复")}catch(e){}d("_iceRestart","ICE disconnected 5s 未恢复,重建 Janus"),this.trigger("icestate",{state:"failed",reason:"ice_disconnect_timeout"}),this._rebuildJanus()}},5e3))):(d("_iceRestart",`ICE ${e},尝试 ICE restart 恢复通话`),this.trigger("icestate",{state:"disconnected"}),this.sipcall.createOffer({iceRestart:!0,tracks:[{type:"audio",capture:!0,recv:!0}],success:e=>{c("_iceRestart","offer 创建成功,发送 update"),this._iceRestarting=!0,this._dtlsRebuildNeeded=!0,this._iceRestartCooldown=Date.now()+15e3,this.trigger("icestate",{state:"reconnecting"}),this.sipcall.send({message:{request:"update"},jsep:e})},error:e=>{u("_iceRestart","ICE restart 失败",e),this.trigger("icestate",{state:"failed"}),d("_iceRestart","ICE restart 失败,2s 后重建 Janus"),setTimeout(()=>{this.connected&&!this._userLogout&&this._rebuildJanus()},2e3)}}))}_onIceRestartSuccess(){if(this._iceRestarting&&(this._iceRestarting=!1,this._iceDisconnectTimer&&(clearTimeout(this._iceDisconnectTimer),this._iceDisconnectTimer=null),c("_onIceRestartSuccess","ICE 重连成功,等待 DTLS 恢复"),this.trigger("icestate",{state:"reconnected"}),this._dtlsRebuildNeeded)){this._dtlsCheckTimer&&clearTimeout(this._dtlsCheckTimer);let e=0;const t=()=>{e++;try{const t=this.sipcall?.webrtcStuff?.pc;if(t){const n=t.iceConnectionState,r=t.connectionState||"N/A",i=t.sctp?.transport||t.getSenders?.()[0]?.transport,o=i?.state||"N/A";if(c("_dtlsCheck",`[${e}/5] ice=${n} conn=${r} dtls=${o}`),"connected"===r||"connected"===n&&"connected"===o)return c("_dtlsCheck","DTLS 恢复成功"),this._dtlsRebuildNeeded=!1,this._dtlsCheckTimer=null,void this.trigger("icestate",{state:"dtls_recovered"});if("failed"===r||"failed"===n||"failed"===o)return d("_dtlsCheck",`DTLS 恢复失败: ice=${n} conn=${r} dtls=${o},重建 Janus`),this._dtlsCheckTimer=null,this.trigger("icestate",{state:"failed",reason:"dtls_failed"}),void this._rebuildJanus()}else d("_dtlsCheck",`[${e}/5] PeerConnection 不存在`)}catch(t){d("_dtlsCheck",`[${e}/5] 检查异常: ${t}`)}if(e>=5)return d("_dtlsCheck","DTLS 恢复超时(5s),重建 Janus"),this._dtlsCheckTimer=null,this.trigger("icestate",{state:"failed",reason:"dtls_timeout"}),void(this.connected&&!this._userLogout&&this._rebuildJanus());this._dtlsCheckTimer=setTimeout(t,1e3)};this._dtlsCheckTimer=setTimeout(t,1e3)}}_onDtlsAlert(){this._dtlsRebuildNeeded=!1,this._iceRestarting=!1,d("_onDtlsAlert","DTLS alert,重建 Janus"),this.trigger("icestate",{state:"failed",reason:"dtls_alert"}),this.connected&&!this._userLogout&&this._rebuildJanus()}_sanitizeSdp(e){if(!e||!e.includes("m=video"))return e;const t=e.split("\r\n"),n=[];let r=!1;for(const e of t)e.startsWith("m=video")?(r=!0,c("_sanitizeSdp","移除 video 媒体段")):(r&&e.startsWith("m=")&&(r=!1),r||n.push(e));const i=[];return n.forEach(e=>{const t=e.match(/^a=mid:(.+)$/);t&&i.push(t[1].trim())}),n.map(e=>{if(e.startsWith("a=group:BUNDLE")){return"a=group:BUNDLE "+e.replace("a=group:BUNDLE ","").trim().split(/\s+/).filter(e=>i.includes(e)).join(" ")}return e}).join("\r\n")}_registerSip(){const e={request:"register",username:this.seat.agentCode,authuser:this.seat.agentCode,display_name:this.seat.agentCode,secret:this.seat.sipPwd,offer_video:!1};this.sipcall.send({message:e}),this.trigger("sipstate",{registered:null,username:this.seat.agentCode})}_retrySipRegister(e){const t=Number(e);if(401===t||403===t)return void d("_retrySipRegister",`SIP 注册失败 code=${e},认证错误不重试`);if(this._sipRetryCount>=this._sipMaxRetries)return u("_retrySipRegister",`SIP 注册重试已达上限 ${this._sipMaxRetries} 次,重建 Janus`),this._sipRetryCount=0,void this._rebuildJanus();this._sipRetryCount++;const n=Math.min(2e3*Math.pow(2,this._sipRetryCount-1),3e4);d("_retrySipRegister",`SIP 注册失败,${n}ms 后第 ${this._sipRetryCount} 次重试`),this._sipRetryTimer&&clearTimeout(this._sipRetryTimer),this._sipRetryTimer=setTimeout(()=>{this.sipcall&&this.connected&&!this._userLogout&&this._registerSip()},n)}_retryJanus(e){if(this._janusRetryCount>=this._janusMaxRetries)return u("_retryJanus",`Janus 重连已达上限 ${this._janusMaxRetries} 次 (${e}),停止重连`),this._janusRetryCount=0,void this.trigger("connstate",{type:"janus",state:"give_up",reason:e});this._janusRetryCount++;const t=Math.min(2e3*Math.pow(2,this._janusRetryCount-1),3e4);d("_retryJanus",`${e},${t}ms 后第 ${this._janusRetryCount} 次重建 Janus`),this._janusRetryTimer&&clearTimeout(this._janusRetryTimer),this._janusRetryTimer=setTimeout(()=>{this.connected&&!this._userLogout&&this._initJanus()},t)}_rebuildJanus(){if(this.status&&this.status.includes("TALKING")&&this.sipcall){d("_rebuildJanus","通话中 Janus 异常,先挂断通话再重建");try{this.sipcall.send({message:{request:"hangup"}}),this.sipcall.hangup()}catch(e){d("_rebuildJanus","挂断异常")}this.toggleRing(!1),this.isHangup=!0}c("_rebuildJanus","销毁旧 Janus 并重建");try{this.janus?.destroy({cleanupHandles:!0})}catch(e){d("_rebuildJanus","销毁 Janus 异常")}this.janus=null,this.sipcall=null,this._iceRestarting=!1,this._dtlsRebuildNeeded=!1,this._sipRegistered=!1,this._webrtcDownTimer&&(clearTimeout(this._webrtcDownTimer),this._webrtcDownTimer=null),this._sipRegisterTimeout&&(clearTimeout(this._sipRegisterTimeout),this._sipRegisterTimeout=null),this._sipRetryTimer&&(clearTimeout(this._sipRetryTimer),this._sipRetryTimer=null),this._dtlsCheckTimer&&(clearTimeout(this._dtlsCheckTimer),this._dtlsCheckTimer=null),this._iceDisconnectTimer&&(clearTimeout(this._iceDisconnectTimer),this._iceDisconnectTimer=null),this._retryJanus("rebuild")}on(e,t){this.events[e]||(c("on","订阅事件: "+e),this.events[e]=[]),this.events[e].push(t)}trigger(e,t){this.events[e]&&("message"!==e&&c("trigger","触发事件: "+e),this.events[e].forEach(e=>e(t)))}onmessage(e){this.trigger("message",e)}datelog(){var e=new Date,t=e.getFullYear(),n=e.getMonth()+1,r=e.getDate(),i=e.getHours(),o=e.getMinutes(),s=e.getSeconds(),a=e.getMilliseconds();return n<10&&(n="0"+n),r<10&&(r="0"+r),i<10&&(i="0"+i),o<10&&(o="0"+o),s<10&&(s="0"+s),a<10?a+="00":a<100&&(a+="0"),t+"-"+n+"-"+r+" "+i+":"+o+":"+s+"."+a}};class f{static _instance=null;static _version_="1.4.8";static _enum_={state:e,btn:t,label:n};constructor(){if(f._instance)return f._instance;f._instance=this,console.log("[VoiceNine] version:",f._version_),this.on("state",e=>this._stateHandler(e))}get version(){return f._version_}get status(){return p.status}get enum(){return f._enum_}init(e){console.log("["+p.datelog()+"] voice9 init",e),p._init(e)}logout(){p.sendAction(t.logout)}setBusy(){p.sendAction(t.busy)}setReady(){p.sendAction(t.ready)}setWorkNotReady(e){p.sendAction(t.busy_work,{busyDesc:e})}call(n,r={}){const i=[e.LOGIN,e.READY,e.NOT_READY,e.WORK_NOT_READY,e.AFTER];if(!p.connected)return{success:!1,reason:"ws_disconnected",message:"WebSocket 未连接"};if(!i.includes(p.status))return{success:!1,reason:"invalid_state",message:`当前状态不允许外呼: ${p.status}`};if(2===p.seat.loginType){if(!p.sipcall)return{success:!1,reason:"webrtc_not_ready",message:"WebRTC 未初始化"};const e=p.sipcall.webrtcStuff?.pc?.iceConnectionState;if(e&&"connected"!==e&&"completed"!==e&&"new"!==e)return{success:!1,reason:"ice_disconnected",message:`ICE 连接异常: ${e}`}}return p.sendAction(t.call,{telNum:n,...r}),{success:!0}}answer(){p.accept(p.msg,p.jsep)}sendDtmf(e){const t={cmd:"dtmf",dtmf:e,callId:p.callId,agentKey:p.seat.agentKey,sequence:(new Date).getTime()};p.echo(JSON.stringify(t))}hangup(){p.sendAction(t.hangup)}transfer(e,n={}){p.sendAction(t.transfer,{transferValue:e,...n})}consult(e,n={}){p.sendAction(t.consult,{telNum:e,...n})}cancelConsult(){p.sendAction(t.consult_cancel)}stopConsult(){p.sendAction(t.consult_stop)}consultTransfer(e,n={}){p.sendAction(t.consult_transfer,{transferValue:e,...n})}consultParty(){p.sendAction(t.consult_party)}mute(){p.sendAction(t.mute)}muteCancel(){p.sendAction(t.mute_cancel)}hold(){p.sendAction(t.hold)}holdCancel(){p.sendAction(t.hold_cancel)}monitor(e,t){const n={cmd:"MONITOR_CALL",callId:t,agentKey:p.seat.agentKey,monitorAgent:e,sequence:(new Date).getTime()};p.echo(JSON.stringify(n))}intercept(){p.sendAction("INTERCEPT_CALL")}barge(e,t){const n={cmd:"BARGE_CALL",callId:t,agentKey:p.seat.agentKey,monitorAgent:e,sequence:(new Date).getTime()};p.echo(JSON.stringify(n))}coach(e,t){const n={cmd:"COACH_CALL",callId:t,agentKey:p.seat.agentKey,monitorAgent:e,sequence:(new Date).getTime()};p.echo(JSON.stringify(n))}updateFollowData(e){const t={cmd:"UPDATE_FOLLOWDATA",followData:e,callId:p.callId,agentKey:p.seat.agentKey,sequence:(new Date).getTime()};p.echo(JSON.stringify(t))}action(e,t){p.sendAction(e,t)}message(e){p.echo(JSON.stringify(e))}on(e,t){p.on(e,t)}off(e,t){if(!p.events[e])return;if(!t)return void(p.events[e]=[]);const n=p.events[e].indexOf(t);n>-1&&p.events[e].splice(n,1)}emit(e,t){p.trigger(e,t)}_stateHandler(t){const{type:n,code:i}=t;if(p.events.btnstate){const e=r[n]||[];p.events.btnstate.forEach(t=>t(e))}if(p.events.agentstate){let t=n;t===e.LOGIN&&0!==Number(i)&&(t=""),p.events.agentstate.forEach(e=>e(t))}}}export{f as VoiceNine};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hzkj/voicenine",
3
- "version": "1.4.6",
3
+ "version": "1.4.8",
4
4
  "description": "js sdk of cloud platform base on janus gateway.",
5
5
  "main": "lib/main.js",
6
6
  "type": "module",