@hzkj/voicenine 1.6.0 → 2.0.0

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.
Files changed (2) hide show
  1. package/lib/main.js +1 -1
  2. package/package.json +1 -1
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={TASK_CALL:"TASK_CALL"},r={DIALING:"DIALING",RINGING:"RINGING",ANSWERED:"ANSWERED",HANGUP:"HANGUP"},n={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"},i={[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]:"多方通话"},o={[e.LOGIN]:[n.call],[e.LOGOUT]:[],[e.READY]:[n.call],[e.NOT_READY]:[n.call],[e.WORK_NOT_READY]:[n.call],[e.AFTER]:[n.call],[e.OUT_CALL]:[n.hangup],[e.OUT_CALLER_RING]:[n.answer,n.hangup],[e.OUT_CALLED_RING]:[n.hangup],[e.PLAY_AGENT_ID]:[n.hangup],[e.TALKING]:[n.hangup,n.hold,n.mute,n.transfer,n.consult],[e.MUTE_TALKING]:[n.mute_cancel],[e.HOLD_TALKING]:[n.hold_cancel],[e.INNER_CALL_RING]:[n.hangup,n.answer],[e.INNER_CALL_TALKING]:[n.hangup,n.mute],[e.INBOUND_RING]:[n.hangup,n.answer],[e.TRANSFER]:[n.transfer_cancel],[e.TRANSFERED_RING]:[n.hangup,n.answer],[e.TRANSFER_OUT_RING]:[n.transfer_cancel],[e.TRANSFERED_TALKING]:[n.hangup,n.mute,n.transfer,n.consult],[e.CONSULT]:[n.consult_cancel],[e.CONSULT_RING]:[n.hangup,n.answer],[e.CONSULT_OUT_RING]:[n.consult_cancel],[e.CONSULT_IVR]:[n.hangup,n.consult_cancel],[e.CONSULT_TALKING]:[n.hangup,n.mute,n.consult_party,n.consult_transfer],[e.CONSULTED_TALKING]:[n.hangup,n.mute],[e.CONFERENCE_TALKING]:[n.hangup,n.mute,n.consult]};!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).adapter=e()}}(function(){return function e(t,r,n){function i(a,s){if(!r[a]){if(!t[a]){var c="function"==typeof require&&require;if(!s&&c)return c(a,!0);if(o)return o(a,!0);var d=new Error("Cannot find module '"+a+"'");throw d.code="MODULE_NOT_FOUND",d}var u=r[a]={exports:{}};t[a][0].call(u.exports,function(e){return i(t[a][1][e]||e)},u,u.exports,e,t,r,n)}return r[a].exports}for(var o="function"==typeof require&&require,a=0;a<n.length;a++)i(n[a]);return i}({1:[function(e,t,r){var n=(0,e("./adapter_factory.js").adapterFactory)({window:"undefined"==typeof window?void 0:window});t.exports=n},{"./adapter_factory.js":2}],2:[function(e,t,r){function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(r,"__esModule",{value:!0}),r.adapterFactory=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.window,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0},n=i.log,u=i.detectBrowser(t),l={browserDetails:u,commonShim:c,extractVersion:i.extractVersion,disableLog:i.disableLog,disableWarnings:i.disableWarnings,sdp:d};switch(u.browser){case"chrome":if(!o||!o.shimPeerConnection||!r.shimChrome)return n("Chrome shim is not included in this adapter release."),l;if(null===u.version)return n("Chrome shim can not determine version, not shimming."),l;n("adapter.js shimming chrome."),l.browserShim=o,c.shimAddIceCandidateNullOrEmpty(t,u),c.shimParameterlessSetLocalDescription(t,u),o.shimGetUserMedia(t,u),o.shimMediaStream(t,u),o.shimPeerConnection(t,u),o.shimOnTrack(t,u),o.shimAddTrackRemoveTrack(t,u),o.shimGetSendersWithDtmf(t,u),o.shimSenderReceiverGetStats(t,u),o.fixNegotiationNeeded(t,u),c.shimRTCIceCandidate(t,u),c.shimRTCIceCandidateRelayProtocol(t,u),c.shimConnectionState(t,u),c.shimMaxMessageSize(t,u),c.shimSendThrowTypeError(t,u),c.removeExtmapAllowMixed(t,u);break;case"firefox":if(!a||!a.shimPeerConnection||!r.shimFirefox)return n("Firefox shim is not included in this adapter release."),l;n("adapter.js shimming firefox."),l.browserShim=a,c.shimAddIceCandidateNullOrEmpty(t,u),c.shimParameterlessSetLocalDescription(t,u),a.shimGetUserMedia(t,u),a.shimPeerConnection(t,u),a.shimOnTrack(t,u),a.shimRemoveStream(t,u),a.shimSenderGetStats(t,u),a.shimReceiverGetStats(t,u),a.shimRTCDataChannel(t,u),a.shimAddTransceiver(t,u),a.shimGetParameters(t,u),a.shimCreateOffer(t,u),a.shimCreateAnswer(t,u),c.shimRTCIceCandidate(t,u),c.shimConnectionState(t,u),c.shimMaxMessageSize(t,u),c.shimSendThrowTypeError(t,u);break;case"safari":if(!s||!r.shimSafari)return n("Safari shim is not included in this adapter release."),l;n("adapter.js shimming safari."),l.browserShim=s,c.shimAddIceCandidateNullOrEmpty(t,u),c.shimParameterlessSetLocalDescription(t,u),s.shimRTCIceServerUrls(t,u),s.shimCreateOfferLegacy(t,u),s.shimCallbacksAPI(t,u),s.shimLocalStreamsAPI(t,u),s.shimRemoteStreamsAPI(t,u),s.shimTrackEventTransceiver(t,u),s.shimGetUserMedia(t,u),s.shimAudioContext(t,u),c.shimRTCIceCandidate(t,u),c.shimRTCIceCandidateRelayProtocol(t,u),c.shimMaxMessageSize(t,u),c.shimSendThrowTypeError(t,u),c.removeExtmapAllowMixed(t,u);break;default:n("Unsupported browser!")}return l};var i=l(e("./utils")),o=l(e("./chrome/chrome_shim")),a=l(e("./firefox/firefox_shim")),s=l(e("./safari/safari_shim")),c=l(e("./common_shim")),d=l(e("sdp"));function u(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(u=function(e){return e?r:t})(e)}function l(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=n(e)&&"function"!=typeof e)return{default:e};var r=u(t);if(r&&r.has(e))return r.get(e);var i={__proto__:null},o=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var a in e)if("default"!==a&&{}.hasOwnProperty.call(e,a)){var s=o?Object.getOwnPropertyDescriptor(e,a):null;s&&(s.get||s.set)?Object.defineProperty(i,a,s):i[a]=e[a]}return i.default=e,r&&r.set(e,i),i}},{"./chrome/chrome_shim":3,"./common_shim":5,"./firefox/firefox_shim":6,"./safari/safari_shim":9,"./utils":10,sdp:11}],3:[function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.fixNegotiationNeeded=function(e,t){n.wrapPeerConnectionEvent(e,"negotiationneeded",function(e){var r=e.target;if(!(t.version<72||r.getConfiguration&&"plan-b"===r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e})},r.shimAddTrackRemoveTrack=function(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return c(e);var r=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){var e=this,t=r.apply(this);return this._reverseStreams=this._reverseStreams||{},t.map(function(t){return e._reverseStreams[t.id]})};var n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){var r=this;if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(function(e){if(r.getSenders().find(function(t){return t.track===e}))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[t.id]){var i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};var i=e.RTCPeerConnection.prototype.removeStream;function o(e,t){var r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(function(t){var n=e._reverseStreams[t],i=e._streams[n.id];r=r.replace(new RegExp(i.id,"g"),n.id)}),new RTCSessionDescription({type:t.type,sdp:r})}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]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,r){var n=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");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};var o=this._streams[r.id];if(o)o.addTrack(t),Promise.resolve().then(function(){n.dispatchEvent(new Event("negotiationneeded"))});else{var a=new e.MediaStream([t]);this._streams[r.id]=a,this._reverseStreams[a.id]=r,this.addStream(a)}return this.getSenders().find(function(e){return e.track===t})},["createOffer","createAnswer"].forEach(function(t){var r=e.RTCPeerConnection.prototype[t],n=a({},t,function(){var e=this,t=arguments;return arguments.length&&"function"==typeof arguments[0]?r.apply(this,[function(r){var n=o(e,r);t[0].apply(null,[n])},function(e){t[1]&&t[1].apply(null,e)},arguments[2]]):r.apply(this,arguments).then(function(t){return o(e,t)})});e.RTCPeerConnection.prototype[t]=n[t]});var s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=(e=this,r=(t=arguments[0]).sdp,Object.keys(e._reverseStreams||[]).forEach(function(t){var n=e._reverseStreams[t],i=e._streams[n.id];r=r.replace(new RegExp(n.id,"g"),i.id)}),new RTCSessionDescription({type:t.type,sdp:r})),s.apply(this,arguments)):s.apply(this,arguments);var e,t,r};var d=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get:function(){var e=d.get.apply(this);return""===e.type?e:o(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){var t,r=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||{},Object.keys(this._streams).forEach(function(n){r._streams[n].getTracks().find(function(t){return e.track===t})&&(t=r._streams[n])}),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}},r.shimAddTrackRemoveTrackWithNative=c,r.shimGetSendersWithDtmf=function(e){if("object"===s(e)&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){var t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};var r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){var i=r.apply(this,arguments);return i||(i=t(this,e),this._senders.push(i)),i};var n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);var t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}var i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){var r=this;this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach(function(e){r._senders.push(t(r,e))})};var o=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){var t=this;this._senders=this._senders||[],o.apply(this,[e]),e.getTracks().forEach(function(e){var r=t._senders.find(function(t){return t.track===e});r&&t._senders.splice(t._senders.indexOf(r),1)})}}else if("object"===s(e)&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){var a=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){var e=this,t=a.apply(this,[]);return t.forEach(function(t){return t._pc=e}),t},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get:function(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}},Object.defineProperty(r,"shimGetUserMedia",{enumerable:!0,get:function(){return i.shimGetUserMedia}}),r.shimMediaStream=function(e){e.MediaStream=e.MediaStream||e.webkitMediaStream},r.shimOnTrack=function(e){if("object"===s(e)&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get:function(){return this._ontrack},set:function(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});var t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){var r=this;return this._ontrackpoly||(this._ontrackpoly=function(t){t.stream.addEventListener("addtrack",function(n){var i;i=e.RTCPeerConnection.prototype.getReceivers?r.getReceivers().find(function(e){return e.track&&e.track.id===n.track.id}):{track:n.track};var o=new Event("track");o.track=n.track,o.receiver=i,o.transceiver={receiver:i},o.streams=[t.stream],r.dispatchEvent(o)}),t.stream.getTracks().forEach(function(n){var i;i=e.RTCPeerConnection.prototype.getReceivers?r.getReceivers().find(function(e){return e.track&&e.track.id===n.id}):{track:n};var o=new Event("track");o.track=n,o.receiver=i,o.transceiver={receiver:i},o.streams=[t.stream],r.dispatchEvent(o)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else n.wrapPeerConnectionEvent(e,"track",function(e){return e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e})},r.shimPeerConnection=function(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection);if(!e.RTCPeerConnection)return;t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){var r=e.RTCPeerConnection.prototype[t],n=a({},t,function(){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)});e.RTCPeerConnection.prototype[t]=n[t]})},r.shimSenderReceiverGetStats=function(e){if(!("object"===s(e)&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){var t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){var e=this,r=t.apply(this,[]);return r.forEach(function(t){return t._pc=e}),r});var r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){var e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){var e=this;return this._pc.getStats().then(function(t){return n.filterStats(t,e.track,!0)})}}if(!("getStats"in e.RTCRtpReceiver.prototype)){var i=e.RTCPeerConnection.prototype.getReceivers;i&&(e.RTCPeerConnection.prototype.getReceivers=function(){var e=this,t=i.apply(this,[]);return t.forEach(function(t){return t._pc=e}),t}),n.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 n.filterStats(t,e.track,!1)})}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;var o=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){var t,r,n,i=arguments[0];return this.getSenders().forEach(function(e){e.track===i&&(t?n=!0:t=e)}),this.getReceivers().forEach(function(e){return e.track===i&&(r?n=!0:r=e),e.track===i}),n||t&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return o.apply(this,arguments)}};var n=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=s(e)&&"function"!=typeof e)return{default:e};var r=o(t);if(r&&r.has(e))return r.get(e);var n={__proto__:null},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var a in e)if("default"!==a&&{}.hasOwnProperty.call(e,a)){var c=i?Object.getOwnPropertyDescriptor(e,a):null;c&&(c.get||c.set)?Object.defineProperty(n,a,c):n[a]=e[a]}return n.default=e,r&&r.set(e,n),n}(e("../utils.js")),i=e("./getusermedia");function o(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(o=function(e){return e?r:t})(e)}function a(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=s(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t);if("object"!=s(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==s(t)?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function s(e){return s="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},s(e)}function c(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){var e=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(function(t){return e._shimmedLocalStreams[t][0]})};var t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){if(!r)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var n=t.apply(this,arguments);return this._shimmedLocalStreams[r.id]?-1===this._shimmedLocalStreams[r.id].indexOf(n)&&this._shimmedLocalStreams[r.id].push(n):this._shimmedLocalStreams[r.id]=[r,n],n};var r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){var t=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(function(e){if(t.getSenders().find(function(t){return t.track===e}))throw new DOMException("Track already exists.","InvalidAccessError")});var n=this.getSenders();r.apply(this,arguments);var i=this.getSenders().filter(function(e){return-1===n.indexOf(e)});this._shimmedLocalStreams[e.id]=[e].concat(i)};var n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.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(r){var n=t._shimmedLocalStreams[r].indexOf(e);-1!==n&&t._shimmedLocalStreams[r].splice(n,1),1===t._shimmedLocalStreams[r].length&&delete t._shimmedLocalStreams[r]}),i.apply(this,arguments)}}},{"../utils.js":10,"./getusermedia":4}],4:[function(e,t,r){function n(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(n=function(e){return e?r:t})(e)}function i(e){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i(e)}Object.defineProperty(r,"__esModule",{value:!0}),r.shimGetUserMedia=function(e,t){var r=e&&e.navigator;if(!r.mediaDevices)return;var n=function(e){if("object"!==i(e)||e.mandatory||e.optional)return e;var t={};return Object.keys(e).forEach(function(r){if("require"!==r&&"advanced"!==r&&"mediaSource"!==r){var n="object"===i(e[r])?e[r]:{ideal:e[r]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);var o=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];var a={};"number"==typeof n.ideal?(a[o("min",r)]=n.ideal,t.optional.push(a),(a={})[o("max",r)]=n.ideal,t.optional.push(a)):(a[o("",r)]=n.ideal,t.optional.push(a))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[o("",r)]=n.exact):["min","max"].forEach(function(e){void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[o(e,r)]=n[e])})}}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},a=function(e,a){if(t.version>=61)return a(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"===i(e.audio)){var s=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])};s((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),s(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"===i(e.video)){var c=e.video.facingMode;c=c&&("object"===i(c)?c:{ideal:c});var d,u=t.version<66;if(c&&("user"===c.exact||"environment"===c.exact||"user"===c.ideal||"environment"===c.ideal)&&(!r.mediaDevices.getSupportedConstraints||!r.mediaDevices.getSupportedConstraints().facingMode||u))if(delete e.video.facingMode,"environment"===c.exact||"environment"===c.ideal?d=["back","rear"]:"user"!==c.exact&&"user"!==c.ideal||(d=["front"]),d)return r.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&&t.length&&d.includes("back")&&(r=t[t.length-1]),r&&(e.video.deviceId=c.exact?{exact:r.deviceId}:{ideal:r.deviceId}),e.video=n(e.video),o("chrome: "+JSON.stringify(e)),a(e)});e.video=n(e.video)}return o("chrome: "+JSON.stringify(e)),a(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString:function(){return this.name+(this.message&&": ")+this.message}}};if(r.getUserMedia=function(e,t,n){a(e,function(e){r.webkitGetUserMedia(e,t,function(e){n&&n(s(e))})})}.bind(r),r.mediaDevices.getUserMedia){var c=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(e){return a(e,function(e){return c(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 o=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=i(e)&&"function"!=typeof e)return{default:e};var r=n(t);if(r&&r.has(e))return r.get(e);var o={__proto__:null},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&{}.hasOwnProperty.call(e,s)){var c=a?Object.getOwnPropertyDescriptor(e,s):null;c&&(c.get||c.set)?Object.defineProperty(o,s,c):o[s]=e[s]}return o.default=e,r&&r.set(e,o),o}(e("../utils.js")).log},{"../utils.js":10}],5:[function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.removeExtmapAllowMixed=function(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t._safariVersion>=13.1)return;var r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){var n=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:n}):t.sdp=n}return r.apply(this,arguments)}},r.shimAddIceCandidateNullOrEmpty=function(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;var r=e.RTCPeerConnection.prototype.addIceCandidate;if(!r||0===r.length)return;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():r.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())}},r.shimConnectionState=function(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;var t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get:function(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get:function(){return this._onconnectionstatechange||null},set:function(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(function(e){var r=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=function(e){var t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;var r=new Event("connectionstatechange",e);t.dispatchEvent(r)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}})},r.shimMaxMessageSize=function(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get:function(){return void 0===this._sctp?null:this._sctp}});var r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){var e,n;(this._sctp=null,"chrome"===t.browser&&t.version>=76)&&("plan-b"===this.getConfiguration().sdpSemantics&&Object.defineProperty(this,"sctp",{get:function(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0}));if(function(e){if(!e||!e.sdp)return!1;var t=i.default.splitSections(e.sdp);return t.shift(),t.some(function(e){var t=i.default.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")})}(arguments[0])){var o,a=function(e){var t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;var r=parseInt(t[1],10);return r!=r?-1:r}(arguments[0]),s=(e=a,n=65536,"firefox"===t.browser&&(n=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),n),c=function(e,r){var n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);var o=i.default.matchPrefix(e.sdp,"a=max-message-size:");return o.length>0?n=parseInt(o[0].substring(19),10):"firefox"===t.browser&&-1!==r&&(n=2147483637),n}(arguments[0],a);o=0===s&&0===c?Number.POSITIVE_INFINITY:0===s||0===c?Math.max(s,c):Math.min(s,c);var d={};Object.defineProperty(d,"maxMessageSize",{get:function(){return o}}),this._sctp=d}return r.apply(this,arguments)}},r.shimParameterlessSetLocalDescription=function(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;var r=e.RTCPeerConnection.prototype.setLocalDescription;if(!r||0===r.length)return;e.RTCPeerConnection.prototype.setLocalDescription=function(){var e=this,t=arguments[0]||{};if("object"!==s(t)||t.type&&t.sdp)return r.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?r.apply(this,[t]):("offer"===t.type?this.createOffer:this.createAnswer).apply(this).then(function(t){return r.apply(e,[t])})}},r.shimRTCIceCandidate=function(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;var t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"===s(e)&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){var r=new t(e),n=i.default.parseCandidate(e.candidate);for(var o in n)o in r||Object.defineProperty(r,o,{value:n[o]});return r.toJSON=function(){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.sdpMLineIndex,usernameFragment:r.usernameFragment}},r}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,o.wrapPeerConnectionEvent(e,"icecandidate",function(t){return t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t})},r.shimRTCIceCandidateRelayProtocol=function(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype)return;o.wrapPeerConnectionEvent(e,"icecandidate",function(e){if(e.candidate){var t=i.default.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})},r.shimSendThrowTypeError=function(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){var r=e.send;e.send=function(){var n=arguments[0],i=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&i>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return r.apply(e,arguments)}}var r=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){var e=r.apply(this,arguments);return t(e,this),e},o.wrapPeerConnectionEvent(e,"datachannel",function(e){return t(e.channel,e.target),e})};var n,i=(n=e("sdp"))&&n.__esModule?n:{default:n},o=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=s(e)&&"function"!=typeof e)return{default:e};var r=a(t);if(r&&r.has(e))return r.get(e);var n={__proto__:null},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var o in e)if("default"!==o&&{}.hasOwnProperty.call(e,o)){var c=i?Object.getOwnPropertyDescriptor(e,o):null;c&&(c.get||c.set)?Object.defineProperty(n,o,c):n[o]=e[o]}return n.default=e,r&&r.set(e,n),n}(e("./utils"));function a(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(a=function(e){return e?r:t})(e)}function s(e){return s="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},s(e)}},{"./utils":10,sdp:11}],6:[function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.shimAddTransceiver=function(e){if("object"!==c(e)||!e.RTCPeerConnection)return;var t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];var e,r=arguments[1]&&arguments[1].sendEncodings;void 0===r&&(r=[]);var n=(r=function(e){if(Array.isArray(e))return s(e)}(e=r)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){if(e){if("string"==typeof e)return s(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?s(e,t):void 0}}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()).length>0;n&&r.forEach(function(e){if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});var i=t.apply(this,arguments);if(n){var o=i.sender,a=o.getParameters();(!("encodings"in a)||1===a.encodings.length&&0===Object.keys(a.encodings[0]).length)&&(a.encodings=r,o.sendEncodings=r,this.setParametersPromises.push(o.setParameters(a).then(function(){delete o.sendEncodings}).catch(function(){delete o.sendEncodings})))}return i})},r.shimCreateAnswer=function(e){if("object"!==c(e)||!e.RTCPeerConnection)return;var t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){var e=arguments,r=this;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return t.apply(r,e)}).finally(function(){r.setParametersPromises=[]}):t.apply(this,arguments)}},r.shimCreateOffer=function(e){if("object"!==c(e)||!e.RTCPeerConnection)return;var t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){var e=arguments,r=this;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return t.apply(r,e)}).finally(function(){r.setParametersPromises=[]}):t.apply(this,arguments)}},Object.defineProperty(r,"shimGetDisplayMedia",{enumerable:!0,get:function(){return o.shimGetDisplayMedia}}),r.shimGetParameters=function(e){if("object"!==c(e)||!e.RTCRtpSender)return;var t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){var e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})},Object.defineProperty(r,"shimGetUserMedia",{enumerable:!0,get:function(){return i.shimGetUserMedia}}),r.shimOnTrack=function(e){"object"===c(e)&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})},r.shimPeerConnection=function(e,t){if("object"!==c(e)||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection);t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){var r,n,i,o=e.RTCPeerConnection.prototype[t],a=(r={},i=function(){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),o.apply(this,arguments)},(n=function(e){var t=function(e,t){if("object"!=c(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t);if("object"!=c(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==c(t)?t:t+""}(n=t))in r?Object.defineProperty(r,n,{value:i,enumerable:!0,configurable:!0,writable:!0}):r[n]=i,r);e.RTCPeerConnection.prototype[t]=a[t]});var r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){var e=Array.prototype.slice.call(arguments),i=e[0],o=e[1],a=e[2];return n.apply(this,[i||null]).then(function(e){if(t.version<53&&!o)try{e.forEach(function(e){e.type=r[e.type]||e.type})}catch(t){if("TypeError"!==t.name)throw t;e.forEach(function(t,n){e.set(n,Object.assign({},t,{type:r[t.type]||t.type}))})}return e}).then(o,a)}},r.shimRTCDataChannel=function(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)},r.shimReceiverGetStats=function(e){if("object"!==c(e)||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;var t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){var e=this,r=t.apply(this,[]);return r.forEach(function(t){return t._pc=e}),r});n.wrapPeerConnectionEvent(e,"track",function(e){return e.receiver._pc=e.srcElement,e}),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}},r.shimRemoveStream=function(e){if(!e.RTCPeerConnection||"removeStream"in e.RTCPeerConnection.prototype)return;e.RTCPeerConnection.prototype.removeStream=function(e){var t=this;n.deprecated("removeStream","removeTrack"),this.getSenders().forEach(function(r){r.track&&e.getTracks().includes(r.track)&&t.removeTrack(r)})}},r.shimSenderGetStats=function(e){if("object"!==c(e)||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;var t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){var e=this,r=t.apply(this,[]);return r.forEach(function(t){return t._pc=e}),r});var r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){var e=r.apply(this,arguments);return e._pc=this,e});e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}};var n=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=c(e)&&"function"!=typeof e)return{default:e};var r=a(t);if(r&&r.has(e))return r.get(e);var n={__proto__:null},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var o in e)if("default"!==o&&{}.hasOwnProperty.call(e,o)){var s=i?Object.getOwnPropertyDescriptor(e,o):null;s&&(s.get||s.set)?Object.defineProperty(n,o,s):n[o]=e[o]}return n.default=e,r&&r.set(e,n),n}(e("../utils")),i=e("./getusermedia"),o=e("./getdisplaymedia");function a(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(a=function(e){return e?r:t})(e)}function s(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function c(e){return c="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},c(e)}},{"../utils":10,"./getdisplaymedia":7,"./getusermedia":8}],7:[function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.shimGetDisplayMedia=function(e,t){if(e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices)return;if(!e.navigator.mediaDevices)return;e.navigator.mediaDevices.getDisplayMedia=function(r){if(!r||!r.video){var n=new DOMException("getDisplayMedia without video constraints is undefined");return n.name="NotFoundError",n.code=8,Promise.reject(n)}return!0===r.video?r.video={mediaSource:t}:r.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(r)}}},{}],8:[function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.shimGetUserMedia=function(e,t){var r=e&&e.navigator,i=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,i){n.deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(e).then(t,i)},!(t.version>55&&"autoGainControl"in r.mediaDevices.getSupportedConstraints())){var a=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])},s=r.mediaDevices.getUserMedia.bind(r.mediaDevices);if(r.mediaDevices.getUserMedia=function(e){return"object"===o(e)&&"object"===o(e.audio)&&(e=JSON.parse(JSON.stringify(e)),a(e.audio,"autoGainControl","mozAutoGainControl"),a(e.audio,"noiseSuppression","mozNoiseSuppression")),s(e)},i&&i.prototype.getSettings){var c=i.prototype.getSettings;i.prototype.getSettings=function(){var e=c.apply(this,arguments);return a(e,"mozAutoGainControl","autoGainControl"),a(e,"mozNoiseSuppression","noiseSuppression"),e}}if(i&&i.prototype.applyConstraints){var d=i.prototype.applyConstraints;i.prototype.applyConstraints=function(e){return"audio"===this.kind&&"object"===o(e)&&(e=JSON.parse(JSON.stringify(e)),a(e,"autoGainControl","mozAutoGainControl"),a(e,"noiseSuppression","mozNoiseSuppression")),d.apply(this,[e])}}}};var n=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=o(e)&&"function"!=typeof e)return{default:e};var r=i(t);if(r&&r.has(e))return r.get(e);var n={__proto__:null},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&{}.hasOwnProperty.call(e,s)){var c=a?Object.getOwnPropertyDescriptor(e,s):null;c&&(c.get||c.set)?Object.defineProperty(n,s,c):n[s]=e[s]}return n.default=e,r&&r.set(e,n),n}(e("../utils"));function i(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(i=function(e){return e?r:t})(e)}function o(e){return o="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)}},{"../utils":10}],9:[function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.shimAudioContext=function(e){if("object"!==o(e)||e.AudioContext)return;e.AudioContext=e.webkitAudioContext},r.shimCallbacksAPI=function(e){if("object"!==o(e)||!e.RTCPeerConnection)return;var t=e.RTCPeerConnection.prototype,r=t.createOffer,n=t.createAnswer,i=t.setLocalDescription,a=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(e,t){var n=arguments.length>=2?arguments[2]:arguments[0],i=r.apply(this,[n]);return t?(i.then(e,t),Promise.resolve()):i},t.createAnswer=function(e,t){var r=arguments.length>=2?arguments[2]:arguments[0],i=n.apply(this,[r]);return t?(i.then(e,t),Promise.resolve()):i};var c=function(e,t,r){var n=i.apply(this,[e]);return r?(n.then(t,r),Promise.resolve()):n};t.setLocalDescription=c,c=function(e,t,r){var n=a.apply(this,[e]);return r?(n.then(t,r),Promise.resolve()):n},t.setRemoteDescription=c,c=function(e,t,r){var n=s.apply(this,[e]);return r?(n.then(t,r),Promise.resolve()):n},t.addIceCandidate=c},r.shimConstraints=a,r.shimCreateOfferLegacy=function(e){var t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);var r=this.getTransceivers().find(function(e){return"audio"===e.receiver.track.kind});!1===e.offerToReceiveAudio&&r?"sendrecv"===r.direction?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":"recvonly"===r.direction&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):!0!==e.offerToReceiveAudio||r||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);var 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"})}return t.apply(this,arguments)}},r.shimGetUserMedia=function(e){var t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){var r=t.mediaDevices,n=r.getUserMedia.bind(r);t.mediaDevices.getUserMedia=function(e){return n(a(e))}}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,r,n){t.mediaDevices.getUserMedia(e).then(r,n)}.bind(t))},r.shimLocalStreamsAPI=function(e){if("object"!==o(e)||!e.RTCPeerConnection)return;"getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams});if(!("addStream"in e.RTCPeerConnection.prototype)){var t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){var r=this;this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(function(n){return t.call(r,n,e)}),e.getVideoTracks().forEach(function(n){return t.call(r,n,e)})},e.RTCPeerConnection.prototype.addTrack=function(e){for(var r=this,n=arguments.length,i=new Array(n>1?n-1:0),o=1;o<n;o++)i[o-1]=arguments[o];return i&&i.forEach(function(e){r._localStreams?r._localStreams.includes(e)||r._localStreams.push(e):r._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 r=this._localStreams.indexOf(e);if(-1!==r){this._localStreams.splice(r,1);var n=e.getTracks();this.getSenders().forEach(function(e){n.includes(e.track)&&t.removeTrack(e)})}})},r.shimRTCIceServerUrls=function(e){if(!e.RTCPeerConnection)return;var t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,r){if(e&&e.iceServers){for(var i=[],o=0;o<e.iceServers.length;o++){var a=e.iceServers[o];void 0===a.urls&&a.url?(n.deprecated("RTCIceServer.url","RTCIceServer.urls"),(a=JSON.parse(JSON.stringify(a))).urls=a.url,delete a.url,i.push(a)):i.push(e.iceServers[o])}e.iceServers=i}return new t(e,r)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:function(){return t.generateCertificate}})},r.shimRemoteStreamsAPI=function(e){if("object"!==o(e)||!e.RTCPeerConnection)return;"getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]});if(!("onaddstream"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get:function(){return this._onaddstream},set:function(e){var t=this;this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=function(e){e.streams.forEach(function(e){if(t._remoteStreams||(t._remoteStreams=[]),!t._remoteStreams.includes(e)){t._remoteStreams.push(e);var r=new Event("addstream");r.stream=e,t.dispatchEvent(r)}})})}});var t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){var e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach(function(t){if(e._remoteStreams||(e._remoteStreams=[]),!(e._remoteStreams.indexOf(t)>=0)){e._remoteStreams.push(t);var r=new Event("addstream");r.stream=t,e.dispatchEvent(r)}})}),t.apply(e,arguments)}}},r.shimTrackEventTransceiver=function(e){"object"===o(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}}})};var n=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=o(e)&&"function"!=typeof e)return{default:e};var r=i(t);if(r&&r.has(e))return r.get(e);var n={__proto__:null},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&{}.hasOwnProperty.call(e,s)){var c=a?Object.getOwnPropertyDescriptor(e,s):null;c&&(c.get||c.set)?Object.defineProperty(n,s,c):n[s]=e[s]}return n.default=e,r&&r.set(e,n),n}(e("../utils"));function i(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(i=function(e){return e?r:t})(e)}function o(e){return o="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)}function a(e){return e&&void 0!==e.video?Object.assign({},e,{video:n.compactObject(e.video)}):e}},{"../utils":10}],10:[function(e,t,r){function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(r,"__esModule",{value:!0}),r.compactObject=function e(t){if(!s(t))return t;return Object.keys(t).reduce(function(r,i){var o,a,c,d=s(t[i]),u=d?e(t[i]):t[i],l=d&&!Object.keys(u).length;return void 0===u||l?r:Object.assign(r,(o={},c=u,(a=function(e){var t=function(e,t){if("object"!=n(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,t);if("object"!=n(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==n(t)?t:t+""}(a=i))in o?Object.defineProperty(o,a,{value:c,enumerable:!0,configurable:!0,writable:!0}):o[a]=c,o))},{})},r.deprecated=function(e,t){if(!o)return;console.warn(e+" is deprecated, please use "+t+" instead.")},r.detectBrowser=function(e){var t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;var r=e.navigator;if(r.userAgentData&&r.userAgentData.brands){var n=r.userAgentData.brands.find(function(e){return"Chromium"===e.brand});if(n)return{browser:"chrome",version:parseInt(n.version,10)}}if(r.mozGetUserMedia)t.browser="firefox",t.version=parseInt(a(r.userAgent,/Firefox\/(\d+)\./,1));else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=parseInt(a(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else{if(!e.RTCPeerConnection||!r.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=parseInt(a(r.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=a(r.userAgent,/Version\/(\d+(\.?\d+))/,1)}return t},r.disableLog=function(e){if("boolean"!=typeof e)return new Error("Argument type: "+n(e)+". Please use a boolean.");return i=e,e?"adapter.js logging disabled":"adapter.js logging enabled"},r.disableWarnings=function(e){if("boolean"!=typeof e)return new Error("Argument type: "+n(e)+". Please use a boolean.");return o=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled")},r.extractVersion=a,r.filterStats=function(e,t,r){var n=r?"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(r){r.type===n&&r.trackId===t.id&&c(e,r,i)})}),i},r.log=function(){if("object"===("undefined"==typeof window?"undefined":n(window))){if(i)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}},r.walkStats=c,r.wrapPeerConnectionEvent=function(e,t,r){if(!e.RTCPeerConnection)return;var n=e.RTCPeerConnection.prototype,i=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return i.apply(this,arguments);var o=function(e){var t=r(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,o),i.apply(this,[e,o])};var o=n.removeEventListener;n.removeEventListener=function(e,r){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(r))return o.apply(this,arguments);var n=this._eventMap[t].get(r);return this._eventMap[t].delete(r),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,o.apply(this,[e,n])},Object.defineProperty(n,"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})};var i=!0,o=!0;function a(e,t,r){var n=e.match(t);return n&&n.length>=r&&parseFloat(n[r],10)}function s(e){return"[object Object]"===Object.prototype.toString.call(e)}function c(e,t,r){t&&!r.has(t.id)&&(r.set(t.id,t),Object.keys(t).forEach(function(n){n.endsWith("Id")?c(e,e.get(t[n]),r):n.endsWith("Ids")&&t[n].forEach(function(t){c(e,e.get(t),r)})}))}},{}],11:[function(e,t,r){var n="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).substring(2,12)}};i.localCName=i.generateIdentifier(),i.splitLines=function(e){return e.trim().split("\n").map(function(e){return e.trim()})},i.splitSections=function(e){return e.split("\nm=").map(function(e,t){return(t>0?"m="+e:e).trim()+"\r\n"})},i.getDescription=function(e){var t=i.splitSections(e);return t&&t[0]},i.getMediaSections=function(e){var t=i.splitSections(e);return t.shift(),t},i.matchPrefix=function(e,t){return i.splitLines(e).filter(function(e){return 0===e.indexOf(t)})},i.parseCandidate=function(e){for(var t=void 0,r={foundation:(t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):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]},n=8;n<t.length;n+=2)switch(t[n]){case"raddr":r.relatedAddress=t[n+1];break;case"rport":r.relatedPort=parseInt(t[n+1],10);break;case"tcptype":r.tcpType=t[n+1];break;case"ufrag":r.ufrag=t[n+1],r.usernameFragment=t[n+1];break;default:void 0===r[t[n]]&&(r[t[n]]=t[n+1])}return r},i.writeCandidate=function(e){var t=[];t.push(e.foundation);var r=e.component;"rtp"===r?t.push(1):"rtcp"===r?t.push(2):t.push(r),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);var n=e.type;return 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.substring(14).split(" ")},i.parseRtpMap=function(e){var t=e.substring(9).split(" "),r={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),r.name=t[0],r.clockRate=parseInt(t[1],10),r.channels=3===t.length?parseInt(t[2],10):1,r.numChannels=r.channels,r},i.writeRtpMap=function(e){var t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);var r=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==r?"/"+r:"")+"\r\n"},i.parseExtmap=function(e){var t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},i.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},i.parseFmtp=function(e){for(var t={},r=void 0,n=e.substring(e.indexOf(" ")+1).split(";"),i=0;i<n.length;i++)t[(r=n[i].trim().split("="))[0].trim()]=r[1];return t},i.writeFmtp=function(e){var t="",r=e.payloadType;if(void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){var n=[];Object.keys(e.parameters).forEach(function(t){void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)}),t+="a=fmtp:"+r+" "+n.join(";")+"\r\n"}return t},i.parseRtcpFb=function(e){var t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},i.writeRtcpFb=function(e){var t="",r=e.payloadType;return void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(function(e){t+="a=rtcp-fb:"+r+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"}),t},i.parseSsrcMedia=function(e){var t=e.indexOf(" "),r={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(r.attribute=e.substring(t+1,n),r.value=e.substring(n+1)):r.attribute=e.substring(t+1),r},i.parseSsrcGroup=function(e){var t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map(function(e){return parseInt(e,10)})}},i.getMid=function(e){var t=i.matchPrefix(e,"a=mid:")[0];if(t)return t.substring(6)},i.parseFingerprint=function(e){var t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[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 r="a=setup:"+t+"\r\n";return e.fingerprints.forEach(function(e){r+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"}),r},i.parseCryptoLine=function(e){var t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},i.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"===n(e.keyParams)?i.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},i.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;var t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[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 r=i.matchPrefix(e+t,"a=ice-ufrag:")[0],n=i.matchPrefix(e+t,"a=ice-pwd:")[0];return r&&n?{usernameFragment:r.substring(12),password:n.substring(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){var t={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},r=i.splitLines(e)[0].split(" ");t.profile=r[2];for(var n=3;n<r.length;n++){var o=r[n],a=i.matchPrefix(e,"a=rtpmap:"+o+" ")[0];if(a){var s=i.parseRtpMap(a),c=i.matchPrefix(e,"a=fmtp:"+o+" ");switch(s.parameters=c.length?i.parseFmtp(c[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())}}}i.matchPrefix(e,"a=extmap:").forEach(function(e){t.headerExtensions.push(i.parseExtmap(e))});var d=i.matchPrefix(e,"a=rtcp-fb:* ").map(i.parseRtcpFb);return t.codecs.forEach(function(e){d.forEach(function(t){e.rtcpFeedback.find(function(e){return e.type===t.type&&e.parameter===t.parameter})||e.rtcpFeedback.push(t)})}),t},i.writeRtpDescription=function(e,t){var r="";r+="m="+e+" ",r+=t.codecs.length>0?"9":"0",r+=" "+(t.profile||"UDP/TLS/RTP/SAVPF")+" ",r+=t.codecs.map(function(e){return void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType}).join(" ")+"\r\n",r+="c=IN IP4 0.0.0.0\r\n",r+="a=rtcp:9 IN IP4 0.0.0.0\r\n",t.codecs.forEach(function(e){r+=i.writeRtpMap(e),r+=i.writeFmtp(e),r+=i.writeRtcpFb(e)});var n=0;return t.codecs.forEach(function(e){e.maxptime>n&&(n=e.maxptime)}),n>0&&(r+="a=maxptime:"+n+"\r\n"),t.headerExtensions&&t.headerExtensions.forEach(function(e){r+=i.writeExtmap(e)}),r},i.parseRtpEncodingParameters=function(e){var t=[],r=i.parseRtpParameters(e),n=-1!==r.fecMechanisms.indexOf("RED"),o=-1!==r.fecMechanisms.indexOf("ULPFEC"),a=i.matchPrefix(e,"a=ssrc:").map(function(e){return i.parseSsrcMedia(e)}).filter(function(e){return"cname"===e.attribute}),s=a.length>0&&a[0].ssrc,c=void 0,d=i.matchPrefix(e,"a=ssrc-group:FID").map(function(e){return e.substring(17).split(" ").map(function(e){return parseInt(e,10)})});d.length>0&&d[0].length>1&&d[0][0]===s&&(c=d[0][1]),r.codecs.forEach(function(e){if("RTX"===e.name.toUpperCase()&&e.parameters.apt){var r={ssrc:s,codecPayloadType:parseInt(e.parameters.apt,10)};s&&c&&(r.rtx={ssrc:c}),t.push(r),n&&((r=JSON.parse(JSON.stringify(r))).fec={ssrc:s,mechanism:o?"red+ulpfec":"red"},t.push(r))}}),0===t.length&&s&&t.push({ssrc:s});var u=i.matchPrefix(e,"b=");return u.length&&(u=0===u[0].indexOf("b=TIAS:")?parseInt(u[0].substring(7),10):0===u[0].indexOf("b=AS:")?1e3*parseInt(u[0].substring(5),10)*.95-16e3:void 0,t.forEach(function(e){e.maxBitrate=u})),t},i.parseRtcpParameters=function(e){var t={},r=i.matchPrefix(e,"a=ssrc:").map(function(e){return i.parseSsrcMedia(e)}).filter(function(e){return"cname"===e.attribute})[0];r&&(t.cname=r.value,t.ssrc=r.ssrc);var n=i.matchPrefix(e,"a=rtcp-rsize");t.reducedSize=n.length>0,t.compound=0===n.length;var o=i.matchPrefix(e,"a=rtcp-mux");return t.mux=o.length>0,t},i.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,r=i.matchPrefix(e,"a=msid:");if(1===r.length)return{stream:(t=r[0].substring(7).split(" "))[0],track:t[1]};var n=i.matchPrefix(e,"a=ssrc:").map(function(e){return i.parseSsrcMedia(e)}).filter(function(e){return"msid"===e.attribute});return n.length>0?{stream:(t=n[0].value.split(" "))[0],track:t[1]}:void 0},i.parseSctpDescription=function(e){var t=i.parseMLine(e),r=i.matchPrefix(e,"a=max-message-size:"),n=void 0;r.length>0&&(n=parseInt(r[0].substring(19),10)),isNaN(n)&&(n=65536);var o=i.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:t.fmt,maxMessageSize:n};var a=i.matchPrefix(e,"a=sctpmap:");if(a.length>0){var s=a[0].substring(10).split(" ");return{port:parseInt(s[0],10),protocol:s[1],maxMessageSize:n}}},i.writeSctpDescription=function(e,t){var r=[];return r="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&r.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),r.join("")},i.generateSessionId=function(){return Math.random().toString().substr(2,22)},i.writeSessionBoilerplate=function(e,t,r){var n=void 0!==t?t:2;return"v=0\r\no="+(r||"thisisadapterortc")+" "+(e||i.generateSessionId())+" "+n+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},i.getDirection=function(e,t){for(var r=i.splitLines(e),n=0;n<r.length;n++)switch(r[n]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[n].substring(2)}return t?i.getDirection(t):"sendrecv"},i.getKind=function(e){return i.splitLines(e)[0].split(" ")[0].substring(2)},i.isRejected=function(e){return"0"===e.split(" ",2)[1]},i.parseMLine=function(e){var t=i.splitLines(e)[0].substring(2).split(" ");return{kind:t[0],port:parseInt(t[1],10),protocol:t[2],fmt:t.slice(3).join(" ")}},i.parseOLine=function(e){var t=i.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:t[0],sessionId:t[1],sessionVersion:parseInt(t[2],10),netType:t[3],addressType:t[4],address:t[5]}},i.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;for(var t=i.splitLines(e),r=0;r<t.length;r++)if(t[r].length<2||"="!==t[r].charAt(1))return!1;return!0},"object"===(void 0===t?"undefined":n(t))&&(t.exports=i)},{}]},{},[1])(1)}),s.sessions=new Map,s.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||s.extension.isInstalled()}return!0};var a={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 r=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...",r(e)}else r(null,t.data.sourceId)}else"janusGetScreenPending"==t.data.type&&(console.log("clearing ",t.data.id),window.clearTimeout(t.data.id))})}};function s(e){if((e=e||{}).success="function"==typeof e.success?e.success:s.noop,e.error="function"==typeof e.error?e.error:s.noop,e.destroyed="function"==typeof e.destroyed?e.destroyed:s.noop,!s.initDone)return e.error("Library not initialized"),{};if(!s.isWebrtcSupported())return e.error("WebRTC not supported by this browser"),{};if(s.log("Library initialized: "+s.initDone),!e.server)return e.error("Invalid server url"),{};let t=!1,r=null,n={},i=null,o=null,a=0,c=e.server;s.isArray(c)?(s.log("Multiple servers provided ("+c.length+"), will use the first that works"),c=null,o=e.server,s.debug(o)):0===c.indexOf("ws")?(t=!0,s.log("Using WebSockets to contact Janus: "+c)):(t=!1,s.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=25e3;void 0!==e.keepAlivePeriod&&null!==e.keepAlivePeriod&&(g=e.keepAlivePeriod),isNaN(g)&&(g=25e3);let v=6e4;function y(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&&(v=e.longPollTimeout),isNaN(v)&&(v=6e4);let b=!1,T=null,S=new Map,C=this,w=0,_=new Map;function R(){if(null==T)return;if(s.debug("Long poll..."),!b)return void s.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)),s.httpAPICall(t,{verb:"GET",withCredentials:p,success:k,timeout:v,error:function(t,r){if(s.error(t+":",r),w++,w>3)return b=!1,void e.error("Lost connection to the server (is it down?)");R()}})}function k(e,n){if(w=0,t||null==T||!0===n||R(),t||!s.isArray(e))if("keepalive"!==e.janus){if("server_info"===e.janus){s.debug("Got info on the Janus instance"),s.debug(e);const t=e.transaction;if(t){const r=_.get(t);r&&r(e),_.delete(t)}return}if("ack"===e.janus){s.debug("Got an ack on session "+T),s.debug(e);const t=e.transaction;if(t){const r=_.get(t);r&&r(e),_.delete(t)}return}if("success"===e.janus){s.debug("Got a success on session "+T),s.debug(e);const t=e.transaction;if(t){const r=_.get(t);r&&r(e),_.delete(t)}return}if("trickle"===e.janus){const t=e.sender;if(!t)return void s.warn("Missing sender...");const r=S.get(t);if(!r)return void s.debug("This handle is not attached to this session");let n=e.candidate;s.debug("Got a trickled candidate on session "+T),s.debug(n);let i=r.webrtcStuff;i.pc&&i.remoteSdp?(s.debug("Adding remote candidate:",n),n&&!0!==n.completed?i.pc.addIceCandidate(n):i.pc.addIceCandidate(s.endOfCandidates)):(s.debug("We didn't do setRemoteDescription (trickle got here before the offer?), caching candidate"),i.candidates||(i.candidates=[]),i.candidates.push(n),s.debug(i.candidates))}else{if("webrtcup"===e.janus){s.debug("Got a webrtcup event on session "+T),s.debug(e);const t=e.sender;if(!t)return void s.warn("Missing sender...");const r=S.get(t);return r?void r.webrtcState(!0):void s.debug("This handle is not attached to this session")}if("hangup"===e.janus){s.debug("Got a hangup event on session "+T),s.debug(e);const t=e.sender;if(!t)return void s.warn("Missing sender...");const r=S.get(t);if(!r)return void s.debug("This handle is not attached to this session");r.webrtcState(!1,e.reason),r.hangup()}else if("detached"===e.janus){s.debug("Got a detached event on session "+T),s.debug(e);const t=e.sender;if(!t)return void s.warn("Missing sender...");const r=S.get(t);if(!r)return;r.ondetached(),r.detach()}else if("media"===e.janus){s.debug("Got a media event on session "+T),s.debug(e);const t=e.sender;if(!t)return void s.warn("Missing sender...");const r=S.get(t);if(!r)return void s.debug("This handle is not attached to this session");r.mediaState(e.type,e.receiving,e.mid)}else if("slowlink"===e.janus){s.debug("Got a slowlink event on session "+T),s.debug(e);const t=e.sender;if(!t)return void s.warn("Missing sender...");const r=S.get(t);if(!r)return void s.debug("This handle is not attached to this session");r.slowLink(e.uplink,e.lost,e.mid)}else{if("error"===e.janus){s.error("Ooops: "+e.error.code+" "+e.error.reason),s.debug(e);let t=e.transaction;if(t){let r=_.get(t);r&&r(e),_.delete(t)}return}if("event"===e.janus){s.debug("Got a plugin event on session "+T),s.debug(e);const t=e.sender;if(!t)return void s.warn("Missing sender...");let r=e.plugindata;if(!r)return void s.warn("Missing plugindata...");s.debug(" -- Event is coming from "+t+" ("+r.plugin+")");let n=r.data;s.debug(n);const i=S.get(t);if(!i)return void s.warn("This handle is not attached to this session");let o=e.jsep;o&&(s.debug("Handling SDP as well..."),s.debug(o));let a=i.onmessage;a?(s.debug("Notifying application..."),a(n,o)):s.debug("No provided notification callback")}else{if("timeout"===e.janus)return s.error("Timeout on session "+T),s.debug(e),void(t&&r.close(3504,"Gateway timeout"));s.warn("Unknown message/event '"+e.janus+"' on session "+T),s.debug(e)}}}}else s.vdebug("Got a keepalive on session "+T);else for(let t=0;t<e.length;t++)k(e[t],!0)}function P(){if(!c||!t||!b)return;i=setTimeout(P,g);let e={janus:"keepalive",session_id:T,transaction:s.randomString(12)};h&&(e.token=h),m&&(e.apisecret=m),r.send(JSON.stringify(e))}function I(d){let u=s.randomString(12),l={janus:"create",transaction:u};if(d.reconnect&&(b=!1,l.janus="claim",l.session_id=T,r&&(r.onopen=null,r.onerror=null,r.onclose=null,i&&(clearTimeout(i),i=null))),h&&(l.token=h),m&&(l.apisecret=m),!c&&s.isArray(o)&&(c=o[a],0===c.indexOf("ws")?(t=!0,s.log("Server #"+(a+1)+": trying WebSockets to contact Janus ("+c+")")):(t=!1,s.log("Server #"+(a+1)+": trying REST API to contact Janus ("+c+")"))),t){r=s.newWebSocket(c,"janus-protocol"),n={error:function(){if(s.error("Error connecting to the Janus WebSockets server... "+c),s.isArray(o)&&!d.reconnect)return a++,a===o.length?void d.error("Error connecting to any of the provided Janus servers: Is the server down?"):(c=null,void setTimeout(function(){I(d)},200));d.error("Error connecting to the Janus WebSockets server: Is the server down?")},open:function(){_.set(u,function(e){if(s.debug(e),"success"!==e.janus)return s.error("Ooops: "+e.error.code+" "+e.error.reason),void d.error(e.error.reason);i=setTimeout(P,g),b=!0,T=e.session_id?e.session_id:e.data.id,d.reconnect?s.log("Claimed session: "+T):s.log("Created session: "+T),s.sessions.set(T,C),d.success()}),r.send(JSON.stringify(l))},message:function(e){k(JSON.parse(e.data))},close:function(){c&&b&&(b=!1,e.error("Lost connection to the server (is it down?)"))}};for(let e in n)r.addEventListener(e,n[e])}else s.httpAPICall(c,{verb:"POST",withCredentials:p,body:l,success:function(e){if(s.debug(e),"success"!==e.janus)return s.error("Ooops: "+e.error.code+" "+e.error.reason),void d.error(e.error.reason);b=!0,T=e.session_id?e.session_id:e.data.id,d.reconnect?s.log("Claimed session: "+T):s.log("Created session: "+T),s.sessions.set(T,C),R(),d.success()},error:function(e,t){if(s.error(e+":",t),s.isArray(o)&&!d.reconnect)return a++,a===o.length?void d.error("Error connecting to any of the provided Janus servers: Is the server down?"):(c=null,void setTimeout(function(){I(d)},200));""===t?d.error(e+": Is the server down?"):t&&t.error?d.error(e+": "+t.error.message):d.error(e+": "+t)}})}function E(e,n){if((n=n||{}).success="function"==typeof n.success?n.success:s.noop,n.error="function"==typeof n.error?n.error:s.noop,!b)return s.warn("Is the server down? (connected=false)"),void n.error("Is the server down? (connected=false)");let i=S.get(e);if(!i||!i.webrtcStuff)return s.warn("Invalid handle"),void n.error("Invalid handle");let o=n.message,a=n.jsep,d=s.randomString(12),u={janus:"message",body:o,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 r=t.pc.getTransceivers();if(r&&r.length>0)for(let t in r){let n=r[t];if(n&&n.sender&&n.sender.track&&"video"===n.sender.track.kind){let r=n.sender.getParameters();r&&r.encodings&&1===r.encodings.length&&r.encodings[0]&&r.encodings[0].scalabilityMode&&(e||(e=[]),e.push({mindex:parseInt(t),mid:n.mid,svc:r.encodings[0].scalabilityMode}))}}}e&&(u.jsep.svc=e)}if(s.debug("Sending message to plugin (handle="+e+"):"),s.debug(u),t)return u.session_id=T,u.handle_id=e,_.set(d,function(e){if(s.debug("Message sent!"),s.debug(e),"success"===e.janus){let t=e.plugindata;if(!t)return s.warn("Request succeeded, but missing plugindata..."),void n.success();s.log("Synchronous transaction successful ("+t.plugin+")");let r=t.data;return s.debug(r),void n.success(r)}"ack"===e.janus?n.success():e.error?(s.error("Ooops: "+e.error.code+" "+e.error.reason),n.error(e.error.code+" "+e.error.reason)):(s.error("Unknown error"),n.error("Unknown error"))}),void r.send(JSON.stringify(u));s.httpAPICall(c+"/"+T+"/"+e,{verb:"POST",withCredentials:p,body:u,success:function(e){if(s.debug("Message sent!"),s.debug(e),"success"===e.janus){let t=e.plugindata;if(!t)return s.warn("Request succeeded, but missing plugindata..."),void n.success();s.log("Synchronous transaction successful ("+t.plugin+")");let r=t.data;return s.debug(r),void n.success(r)}"ack"===e.janus?n.success():e.error?(s.error("Ooops: "+e.error.code+" "+e.error.reason),n.error(e.error.code+" "+e.error.reason)):(s.error("Unknown error"),n.error("Unknown error"))},error:function(e,t){s.error(e+":",t),n.error(e+": "+t)}})}function A(e,n){if(!b)return void s.warn("Is the server down? (connected=false)");let i=S.get(e);if(!i||!i.webrtcStuff)return void s.warn("Invalid handle");let o={janus:"trickle",candidate:n,transaction:s.randomString(12)};if(i.token&&(o.token=i.token),m&&(o.apisecret=m),s.vdebug("Sending trickle candidate (handle="+e+"):"),s.vdebug(o),t)return o.session_id=T,o.handle_id=e,void r.send(JSON.stringify(o));s.httpAPICall(c+"/"+T+"/"+e,{verb:"POST",withCredentials:p,body:o,success:function(e){s.vdebug("Candidate sent!"),s.vdebug(e),"ack"===e.janus||s.error("Ooops: "+e.error.code+" "+e.error.reason)},error:function(e,t){s.error(e+":",t)}})}function O(e,t,r,n,i){let o=S.get(e);if(!o||!o.webrtcStuff)return void s.warn("Invalid handle");let a=o.webrtcStuff;if(!a.pc)return void s.warn("Invalid PeerConnection");let c=function(e){s.log("Received state change on data channel:",e);let t=e.target.label,r=e.target.protocol,n=a.dataChannel[t]?a.dataChannel[t].readyState:"null";if(s.log("State change on <"+t+"> data channel: "+n),"open"===n){if(a.dataChannel[t].pending&&a.dataChannel[t].pending.length>0){s.log("Sending pending messages on <"+t+">:",a.dataChannel[t].pending.length);for(let e of a.dataChannel[t].pending)s.log("Sending data on data channel <"+t+">"),s.debug(e),a.dataChannel[t].send(e);a.dataChannel[t].pending=[]}o.ondataopen(t,r)}};if(n)a.dataChannel[t]=n;else{let e=a.dataChannelOptions;r&&(e.protocol=r),a.dataChannel[t]=a.pc.createDataChannel(t,e)}a.dataChannel[t].onmessage=function(e){s.log("Received message on data channel:",e);let t=e.target.label;o.ondata(e.data,t)},a.dataChannel[t].onopen=c,a.dataChannel[t].onclose=c,a.dataChannel[t].onerror=function(e){s.error("Got error on data channel:",e)},a.dataChannel[t].pending=[],i&&a.dataChannel[t].pending.push(i)}function D(e,t){(t=t||{}).success="function"==typeof t.success?t.success:s.noop,t.error="function"==typeof t.error?t.error:s.noop;let r=S.get(e);if(!r||!r.webrtcStuff)return s.warn("Invalid handle"),void t.error("Invalid handle");let n=r.webrtcStuff,i=t.text||t.data;if(!i)return s.warn("Invalid data"),void t.error("Invalid data");let o=t.label?t.label:s.dataChanDefaultLabel;return n.dataChannel[o]?"open"!==n.dataChannel[o].readyState?(n.dataChannel[o].pending.push(i),void t.success()):(s.log("Sending data on data channel <"+o+">"),s.debug(i),n.dataChannel[o].send(i),void t.success()):(O(e,o,t.protocol,!1,i,t.protocol),void t.success())}function N(e,t){(t=t||{}).success="function"==typeof t.success?t.success:s.noop,t.error="function"==typeof t.error?t.error:s.noop;let r=S.get(e);if(!r||!r.webrtcStuff)return s.warn("Invalid handle"),void t.error("Invalid handle");let n=r.webrtcStuff;if(!n.dtmfSender){if(n.pc){let e=n.pc.getSenders().find(function(e){return e.track&&"audio"===e.track.kind});if(!e)return s.warn("Invalid DTMF configuration (no audio track)"),void t.error("Invalid DTMF configuration (no audio track)");n.dtmfSender=e.dtmf,n.dtmfSender&&(s.log("Created DTMF Sender"),n.dtmfSender.ontonechange=function(e){s.debug("Sent DTMF tone: "+e.tone)})}if(!n.dtmfSender)return s.warn("Invalid DTMF configuration"),void t.error("Invalid DTMF configuration")}let i=t.dtmf;if(!i)return s.warn("Invalid DTMF parameters"),void t.error("Invalid DTMF parameters");let o=i.tones;if(!o)return s.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;s.debug("Sending DTMF string "+o+" (duration "+a+"ms, gap "+c+"ms)"),n.dtmfSender.insertDTMF(o,a,c),t.success()}function L(e,n){(n=n||{}).success="function"==typeof n.success?n.success:s.noop,n.error="function"==typeof n.error?n.error:s.noop;let i=!0===n.noRequest;s.log("Destroying handle "+e+" (only-locally="+i+")"),q(e);let o=S.get(e);if(!o||o.detached)return S.delete(e),void n.success();if(o.detached=!0,i)return S.delete(e),void n.success();if(!b)return s.warn("Is the server down? (connected=false)"),void n.error("Is the server down? (connected=false)");let a={janus:"detach",transaction:s.randomString(12)};if(o.token&&(a.token=o.token),m&&(a.apisecret=m),t)return a.session_id=T,a.handle_id=e,r.send(JSON.stringify(a)),S.delete(e),void n.success();s.httpAPICall(c+"/"+T+"/"+e,{verb:"POST",withCredentials:p,body:a,success:function(t){s.log("Destroyed handle:"),s.debug(t),"success"!==t.janus&&s.error("Ooops: "+t.error.code+" "+t.error.reason),S.delete(e),n.success()},error:function(t,r){s.error(t+":",r),S.delete(e),n.success()}})}function j(e,t){let r=S.get(e);if(!r||!r.webrtcStuff)throw s.warn("Invalid handle"),"Invalid handle";let n=r.webrtcStuff;if(n.pc)return;let i={iceServers:d,iceTransportPolicy:u,bundlePolicy:l,sdpSemantics:"unified-plan"},o=!1;if(t.tracks)for(let e of t.tracks)if(e.transforms&&(e.transforms.sender||e.transforms.receiver)){o=!0;break}t.externalEncryption&&(o=!0,n.externalEncryption=!0),RTCRtpSender&&(RTCRtpSender.prototype.createEncodedStreams||RTCRtpSender.prototype.createEncodedAudioStreams&&RTCRtpSender.prototype.createEncodedVideoStreams)&&o&&(n.insertableStreams=!0,i.forceEncodedAudioInsertableStreams=!0,i.forceEncodedVideoInsertableStreams=!0,i.encodedInsertableStreams=!0),s.log("Creating PeerConnection"),n.pc=new RTCPeerConnection(i),s.debug(n.pc),n.pc.getStats&&(n.volume={},n.bitrate.value="0 kbits/sec"),s.log("Preparing local SDP and gathering candidates (trickle="+n.trickle+")"),n.pc.onconnectionstatechange=function(){n.pc&&r.connectionState(n.pc.connectionState)},n.pc.oniceconnectionstatechange=function(){n.pc&&r.iceState(n.pc.iceConnectionState)},n.pc.onicecandidate=function(r){if(!r.candidate||r.candidate.candidate&&r.candidate.candidate.indexOf("endOfCandidates")>0)s.log("End of candidates."),n.iceDone=!0,!0===n.trickle?A(e,{completed:!0}):function(e,t){t=t||{},t.success="function"==typeof t.success?t.success:s.noop,t.error="function"==typeof t.error?t.error:s.noop;let r=S.get(e);if(!r||!r.webrtcStuff)return void s.warn("Invalid handle, not sending anything");let n=r.webrtcStuff;if(s.log("Sending offer/answer SDP..."),!n.mySdp)return void s.warn("Local SDP instance is invalid, not sending anything...");n.mySdp={type:n.pc.localDescription.type,sdp:n.pc.localDescription.sdp},!1===n.trickle&&(n.mySdp.trickle=!1);s.debug(t),n.sdpSent=!0,t.success(n.mySdp)}(e,t);else{let t={candidate:r.candidate.candidate,sdpMid:r.candidate.sdpMid,sdpMLineIndex:r.candidate.sdpMLineIndex};!0===n.trickle&&A(e,t)}},n.pc.ontrack=function(e){if(s.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&&(r.mids||(r.mids={}),r.mids[e.track.id]=e.transceiver.mid),r.onremotetrack(e.track,t,!0,{reason:"created"})}catch(e){s.error("Error calling onremotetrack",e)}if(e.track.onended)return;let i=null;s.log("Adding onended callback to track:",e.track),e.track.onended=function(t){s.log("Remote track removed:",t),clearTimeout(i);let o=n.pc?n.pc.getTransceivers():null,a=o?o.find(e=>e.receiver.track===t.target):null,c=a?a.mid:t.target.id;c===t.target.id&&r.mids&&r.mids[e.track.id]&&(c=r.mids[e.track.id]);try{r.onremotetrack(t.target,c,!1,{reason:"ended"})}catch(e){s.error("Error calling onremotetrack on removal",e)}delete r.mids[e.track.id]},e.track.onmute=function(t){s.log("Remote track muted:",t),i||(i=setTimeout(function(){s.log("Removing remote track");let o=n.pc?n.pc.getTransceivers():null,a=o?o.find(e=>e.receiver.track===t.target):null,c=a?a.mid:t.target.id;c===t.target.id&&r.mids&&r.mids[e.track.id]&&(c=r.mids[e.track.id]);try{r.onremotetrack(t.target,c,!1,{reason:"mute"})}catch(e){s.error("Error calling onremotetrack on mute",e)}i=null},2520))},e.track.onunmute=function(e){if(s.log("Remote track flowing again:",e),null!=i)clearTimeout(i),i=null;else try{let t=n.pc?n.pc.getTransceivers():null,i=t?t.find(t=>t.receiver.track===e.target):null,o=i?i.mid:e.target.id;r.onremotetrack(e.target,o,!0,{reason:"unmute"})}catch(e){s.error("Error calling onremotetrack on unmute",e)}}}}async function M(e,t,r){(r=r||{}).success="function"==typeof r.success?r.success:s.noop,r.error="function"==typeof r.error?r.error:B;let n=r.jsep;if(t&&n)return s.error("Provided a JSEP to a createOffer"),void r.error("Provided a JSEP to a createOffer");if(!(t||n&&n.type&&n.sdp))return s.error("A valid JSEP is required for createAnswer"),void r.error("A valid JSEP is required for createAnswer");if(r.media&&!r.tracks){if(r.tracks=s.mediaToTracks(r.media),!0===r.simulcast||!0===r.simulcast2||r.svc)for(let e of r.tracks)if("video"===e.type){!0===r.simulcast||!0===r.simulcast2?e.simulcast=!0:r.svc&&(e.svc=r.svc);break}s.warn("Deprecated media object passed, use tracks instead. Automatically translated to:",r.tracks)}if(r.tracks&&!Array.isArray(r.tracks))return s.error("Tracks must be an array"),void r.error("Tracks must be an array");let i=S.get(e);if(!i||!i.webrtcStuff)return s.warn("Invalid handle"),void r.error("Invalid handle");let o=i.webrtcStuff;var a;o.trickle=(a=r.trickle,s.debug("isTrickleEnabled:",a),!1!==a);try{if(j(e,r),t&&await U(e,r),n){if(await o.pc.setRemoteDescription(n),s.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];s.debug("Adding remote candidate:",t),t&&!0!==t.completed?o.pc.addIceCandidate(t):o.pc.addIceCandidate(s.endOfCandidates)}o.candidates=[]}await U(e,r);let t=await async function(e,t){t=t||{},t.customizeSdp="function"==typeof t.customizeSdp?t.customizeSdp:s.noop;let r=S.get(e);if(!r||!r.webrtcStuff)throw s.warn("Invalid handle"),"Invalid handle";let n=r.webrtcStuff;s.log("Creating answer (iceDone="+n.iceDone+")");let i=await n.pc.createAnswer();s.debug(i);let o={type:"answer",sdp:i.sdp};if(t.customizeSdp(o),i.sdp=o.sdp,s.log("Setting local description"),n.mySdp={type:"answer",sdp:i.sdp},await n.pc.setLocalDescription(i),!n.iceDone&&!n.trickle)return s.log("Waiting for all candidates..."),null;(n.insertableStreams||n.externalEncryption)&&(i.e2ee=!0);return i}(e,r);r.success(t)}else{let t=await async function(e,t){t=t||{},t.customizeSdp="function"==typeof t.customizeSdp?t.customizeSdp:s.noop;let r=S.get(e);if(!r||!r.webrtcStuff)throw s.warn("Invalid handle"),"Invalid handle";let n=r.webrtcStuff;s.log("Creating offer (iceDone="+n.iceDone+")");let i={},o=!0===t.iceRestart;o&&(i.iceRestart=!0);s.debug(i);let a=await n.pc.createOffer(i);s.debug(a);let c={type:"offer",sdp:a.sdp};if(t.customizeSdp(c),a.sdp=c.sdp,s.log("Setting local description"),n.mySdp={type:"offer",sdp:a.sdp},await n.pc.setLocalDescription(a),n.mediaConstraints=i,!n.iceDone&&!n.trickle)return s.log("Waiting for all candidates..."),null;(n.insertableStreams||n.externalEncryption)&&(a.e2ee=!0);return a}(e,r);r.success(t)}}catch(e){s.error(e),r.error(e)}}function x(e,t){(t=t||{}).success="function"==typeof t.success?t.success:s.noop,t.error="function"==typeof t.error?t.error:B,t.customizeSdp="function"==typeof t.customizeSdp?t.customizeSdp:s.noop;let r=t.jsep,n=S.get(e);if(!n||!n.webrtcStuff)return s.warn("Invalid handle"),void t.error("Invalid handle");let i=n.webrtcStuff;if(r){if(!i.pc)return s.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(r),i.pc.setRemoteDescription(r).then(function(){if(s.log("Remote description accepted!"),i.remoteSdp=r.sdp,i.candidates&&i.candidates.length>0){for(let e=0;e<i.candidates.length;e++){let t=i.candidates[e];s.debug("Adding remote candidate:",t),t&&!0!==t.completed?i.pc.addIceCandidate(t):i.pc.addIceCandidate(s.endOfCandidates)}i.candidates=[]}t.success()},t.error)}else t.error("Invalid JSEP")}async function G(e,t){if((t=t||{}).success="function"==typeof t.success?t.success:s.noop,t.error="function"==typeof t.error?t.error:s.noop,t.tracks&&!Array.isArray(t.tracks))return s.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 U(e,t),t.success()}catch(e){s.error(e),t.error(e)}}async function U(e,t){let r=S.get(e);if(!r||!r.webrtcStuff)throw s.warn("Invalid handle, not sending anything"),"Invalid handle";let n=r.webrtcStuff;if(!n.pc)throw s.warn("Invalid PeerConnection"),"Invalid PeerConnection";let i=t.tracks;if(!i||!Array.isArray(i)||0===i.length)return;let o=!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){s.warn("Missing track type:",t);continue}if("data"===t.type){if(n.pc.ondatachannel){s.warn("Data channel exists already, not creating another one");continue}s.log("Creating default data channel"),O(e,s.dataChanDefaultLabel,null,!1),n.pc.ondatachannel=function(t){s.log("Data channel created by Janus:",t),O(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){s.warn("Conflicting actions for track, ignoring:",t);continue}t.add&&t.replace?(s.warn("Both add and replace provided, falling back to replace:",t),delete t.add):t.remove&&t.replace&&(s.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=n.pc.getTransceivers().find(e=>e.mid===t.mid&&e.receiver.track.kind===i):t.add||(c=n.pc.getTransceivers().find(e=>e.receiver.track.kind===i)),t.replace||t.remove){if(!c){s.warn("Couldn't find a transceiver for track:",t);continue}if(!c.sender){s.warn("No sender in the transceiver for track:",t);continue}u=c.sender}if(d&&!c&&(c=n.pc.getTransceivers().find(e=>e.receiver.track.kind===i),!c)){s.warn("Couldn't find a transceiver for track:",t);continue}let l=null,p=null;if((t.remove||t.replace)&&(s.log("Removing track from PeerConnection",t),p=u.track?u.track.id:null,await u.replaceTrack(null),p&&n.myStream)){let e=null;if("audio"===i&&n.myStream.getAudioTracks()&&n.myStream.getAudioTracks().length)for(let t of n.myStream.getAudioTracks())t.id===p&&(e=t,s.log("Removing audio track:",e));else if("video"===i&&n.myStream.getVideoTracks()&&n.myStream.getVideoTracks().length)for(let t of n.myStream.getVideoTracks())t.id===p&&(e=t,s.log("Removing video track:",e));if(e){try{n.myStream.removeTrack(e),r.onlocaltrack(e,!1)}catch(e){s.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{o||(o=!0,r.consentDialog(!0));let e=s.trackConstraints(t),n=null;if("audio"===t.type||"video"===t.type){if(t.gumGroup){let r="audio"===t.type?"video":"audio";if(a[t.gumGroup]&&a[t.gumGroup][r]){let n=a[t.gumGroup][r],i=s.trackConstraints(n);e[r]=i[r]}}n=await navigator.mediaDevices.getUserMedia(e),t.gumGroup&&e.audio&&e.video&&(a[t.gumGroup].stream=n,delete t.gumGroup)}else n=await navigator.mediaDevices.getDisplayMedia(e);l="audio"===t.type?n.getAudioTracks()[0]:n.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(n.myStream||(n.myStream=new MediaStream),"audio"===i||!t.simulcast&&!t.svc)u=n.pc.addTrack(l,n.myStream),c=n.pc.getTransceivers().find(e=>e.sender===u);else if(t.simulcast){s.log("Enabling rid-based simulcasting:",l);let e=y(t.simulcastMaxBitrates);c=n.pc.addTransceiver(l,{direction:"sendrecv",streams:[n.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 s.log("Enabling SVC ("+t.svc+"):",l),c=n.pc.addTransceiver(l,{direction:"sendrecv",streams:[n.myStream],sendEncodings:[{scalabilityMode:t.svc}]});if(u||(u=c?c.sender:null),t.codec)if("firefox"===s.webRTCAdapter.browserDetails.browser)s.warn("setCodecPreferences not supported in Firefox, ignoring codec for track:",t);else if("string"!=typeof t.codec)s.warn("Invalid codec value, ignoring for track:",t);else{let e=i+"/"+t.codec.toLowerCase(),r=RTCRtpReceiver.getCapabilities(i).codecs.filter(function(t){return t.mimeType.toLowerCase()===e});if(r&&0!==r.length){if(c)try{c.setCodecPreferences(r)}catch(e){s.warn("Failed enforcing codec for this "+i+" track:",e)}}else s.warn("Codec not supported in this browser for this track, ignoring:",t)}if(t.bitrate)if(t.simulcast||t.svc)s.warn("Ignoring bitrate for simulcast/SVC track, use sendEncodings for that");else if(isNaN(t.bitrate)||t.bitrate<0)s.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)):s.warn("No encodings in the sender parameters, ignoring bitrate for track:",t)}if("video"===i&&t.framerate)if(t.simulcast||t.svc)s.warn("Ignoring framerate for simulcast/SVC track, use sendEncodings for that");else if(isNaN(t.framerate)||t.framerate<0)s.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)):s.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=n.pc.addTransceiver(i)),c)){if(t.codec)if("firefox"===s.webRTCAdapter.browserDetails.browser)s.warn("setCodecPreferences not supported in Firefox, ignoring codec for track:",t);else if("string"!=typeof t.codec)s.warn("Invalid codec value, ignoring for track:",t);else{let e=i+"/"+t.codec.toLowerCase(),r=RTCRtpReceiver.getCapabilities(i).codecs.filter(function(t){return t.mimeType.toLowerCase()===e});if(r&&0!==r.length)try{c.setCodecPreferences(r)}catch(e){s.warn("Failed enforcing codec for this "+i+" track:",e)}else s.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){n.myStream.addTrack(l),l.onended=function(e){s.log("Local track removed:",e);try{r.onlocaltrack(e.target,!1)}catch(e){s.error("Error calling onlocaltrack following end",e)}};try{r.onlocaltrack(l,!0)}catch(e){s.error("Error calling onlocaltrack for track add",e)}}if(c){let e=c.direction,r=null,n=l&&c.sender.track,i=!1!==t.recv&&c.receiver.track;n&&i?r="sendrecv":n&&!i?r="sendonly":!n&&i?r="recvonly":n||i||(r="inactive"),r&&r!==e&&(s.warn("Changing direction of transceiver to "+r+" (was "+e+")",t),c.setDirection?c.setDirection(r):c.direction=r)}}o&&r.consentDialog(!1)}function J(e){let t=S.get(e);if(!t||!t.webrtcStuff)return s.warn("Invalid handle"),null;let r=t.webrtcStuff;if(!r.pc)return s.warn("Invalid PeerConnection"),null;let n=[],i=r.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&&n.push(t)}return n}function F(e){let t=S.get(e);if(!t||!t.webrtcStuff)return s.warn("Invalid handle"),null;let r=t.webrtcStuff;if(!r.pc)return s.warn("Invalid PeerConnection"),null;let n=[],i=r.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&&n.push(t)}return n}function W(e,t,r,n){n="function"==typeof n?n:s.noop;let i=S.get(e);if(!i||!i.webrtcStuff)return s.warn("Invalid handle"),void n(0);let o=r?"remote":"local",a=i.webrtcStuff;if(a.volume[o]||(a.volume[o]={value:0}),a.pc&&a.pc.getStats&&("chrome"===s.webRTCAdapter.browserDetails.browser||"safari"===s.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 s.warn("No audio transceiver with mid "+t),void n(0);if(r&&!i.receiver)return s.warn("Remote transceiver track unavailable"),void n(0);if(!r&&!i.sender)return s.warn("Local transceiver track unavailable"),void n(0);e=r?i.receiver:i.sender}return e.getStats().then(function(e){e.forEach(function(e){e&&"audio"===e.kind&&(r&&!e.remoteSource||!r&&"media-source"!==e.type||n(e.audioLevel?e.audioLevel:0))})}),a.volume[o].value}return s.warn("Getting the "+o+" volume unsupported by browser"),void n(0)}function V(e,t,r){let n=S.get(e);if(!n||!n.webrtcStuff)return s.warn("Invalid handle"),!0;let i=n.webrtcStuff;if(!i.pc)return s.warn("Invalid PeerConnection"),!0;if(!i.myStream)return s.warn("Invalid local MediaStream"),!0;if(r){if(!i.myStream.getVideoTracks()||0===i.myStream.getVideoTracks().length)return s.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:(s.warn("No video sender with mid "+t),!0):(s.warn("No video transceiver with mid "+t),!0)}return!i.myStream.getVideoTracks()[0].enabled}if(!i.myStream.getAudioTracks()||0===i.myStream.getAudioTracks().length)return s.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:(s.warn("No audio sender with mid "+t),!0):(s.warn("No audio transceiver with mid "+t),!0)}return!i.myStream.getAudioTracks()[0].enabled}function K(e,t,r,n){let i=S.get(e);if(!i||!i.webrtcStuff)return s.warn("Invalid handle"),!1;let o=i.webrtcStuff;if(!o.pc)return s.warn("Invalid PeerConnection"),!1;if(!o.myStream)return s.warn("Invalid local MediaStream"),!1;if(r){if(!o.myStream.getVideoTracks()||0===o.myStream.getVideoTracks().length)return s.warn("No video track"),!1;if(t){let e=o.pc.getTransceivers().find(e=>e.mid===t&&"video"===e.receiver.track.kind);if(!e)return s.warn("No video transceiver with mid "+t),!1;if(!e.sender||!e.sender.track)return s.warn("No video sender with mid "+t),!1;e.sender.track.enabled=!n}else for(const e of o.myStream.getVideoTracks())e.enabled=!n}else{if(!o.myStream.getAudioTracks()||0===o.myStream.getAudioTracks().length)return s.warn("No audio track"),!1;if(t){let e=o.pc.getTransceivers().find(e=>e.mid===t&&"audio"===e.receiver.track.kind);if(!e)return s.warn("No audio transceiver with mid "+t),!1;if(!e.sender||!e.sender.track)return s.warn("No audio sender with mid "+t),!1;e.sender.track.enabled=!n}else for(const e of o.myStream.getAudioTracks())e.enabled=!n}return!0}function z(e,t){let r=S.get(e);if(!r||!r.webrtcStuff)return s.warn("Invalid handle"),"Invalid handle";let n=r.webrtcStuff;if(!n.pc)return"Invalid PeerConnection";if(n.pc.getStats){let e=n.pc,r=t||"default";if(t){let r=n.pc.getTransceivers().find(e=>e.mid===t&&"video"===e.receiver.track.kind);if(!r)return s.warn("No video transceiver with mid "+t),"No video transceiver with mid "+t;if(!r.receiver)return s.warn("No video receiver with mid "+t),"No video receiver with mid "+t;e=r.receiver}return n.bitrate[r]||(n.bitrate[r]={timer:null,bsnow:null,bsbefore:null,tsnow:null,tsbefore:null,value:"0 kbits/sec"}),n.bitrate[r].timer?n.bitrate[r].value:(s.log("Starting bitrate timer"+(t?" for mid "+t:"")+" (via getStats)"),n.bitrate[r].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(n.bitrate[r].bsnow=e.bytesReceived,n.bitrate[r].tsnow=e.timestamp,null===n.bitrate[r].bsbefore||null===n.bitrate[r].tsbefore)n.bitrate[r].bsbefore=n.bitrate[r].bsnow,n.bitrate[r].tsbefore=n.bitrate[r].tsnow;else{let e=n.bitrate[r].tsnow-n.bitrate[r].tsbefore;"safari"===s.webRTCAdapter.browserDetails.browser&&(e/=1e3);let t=Math.round(8*(n.bitrate[r].bsnow-n.bitrate[r].bsbefore)/e);"safari"===s.webRTCAdapter.browserDetails.browser&&(t=parseInt(t/1e3)),n.bitrate[r].value=t+" kbits/sec",n.bitrate[r].bsbefore=n.bitrate[r].bsnow,n.bitrate[r].tsbefore=n.bitrate[r].tsnow}})})},1e3),"0 kbits/sec")}return s.warn("Getting the video bitrate unsupported by browser"),"Feature unsupported by browser"}function $(e,t,r){let n=S.get(e);if(!n||!n.webrtcStuff)return void s.warn("Invalid handle");let i=n.webrtcStuff;if(!i.pc)return void s.warn("Invalid PeerConnection");let o=i.pc.getTransceivers().find(e=>e.mid===t);if(!o)return void s.warn("No transceiver with mid",t);if(!o.sender)return void s.warn("No sender for transceiver with mid",t);let a=o.sender.getParameters();a&&a.encodings&&0!==a.encodings.length?a.encodings.length>1?s.warn("Ignoring bitrate for simulcast track, use sendEncodings for that"):isNaN(r)||r<0?s.warn("Invalid bitrate (must be a positive integer)"):(a.encodings[0].maxBitrate=r,o.sender.setParameters(a)):s.warn("No parameters encodings")}function B(e){s.error("WebRTC error:",e)}function q(e,n){s.log("Cleaning WebRTC stuff");let i=S.get(e);if(!i)return;let o=i.webrtcStuff;if(o){if(!0===n){let n={janus:"hangup",transaction:s.randomString(12)};i.token&&(n.token=i.token),m&&(n.apisecret=m),s.debug("Sending hangup request (handle="+e+"):"),s.debug(n),t?(n.session_id=T,n.handle_id=e,r.send(JSON.stringify(n))):s.httpAPICall(c+"/"+T+"/"+e,{verb:"POST",withCredentials:p,body:n})}o.volume&&(o.volume.local&&o.volume.local.timer&&clearInterval(o.volume.local.timer),o.volume.remote&&o.volume.remote.timer&&clearInterval(o.volume.remote.timer));for(let e in o.bitrate)o.bitrate[e].timer&&clearInterval(o.bitrate[e].timer);o.bitrate={},!o.streamExternal&&o.myStream&&(s.log("Stopping local stream tracks"),s.stopAllTracks(o.myStream)),o.streamExternal=!1,o.myStream=null;try{o.pc.close()}catch(e){}o.pc=null,o.candidates=null,o.mySdp=null,o.remoteSdp=null,o.iceDone=!1,o.dataChannel={},o.dtmfSender=null,o.insertableStreams=!1,o.externalEncryption=!1}i.oncleanup()}I(e),this.getServer=function(){return c},this.isConnected=function(){return b},this.reconnect=function(e){(e=e||{}).success="function"==typeof e.success?e.success:s.noop,e.error="function"==typeof e.error?e.error:s.noop,e.reconnect=!0,I(e)},this.getSessionId=function(){return T},this.getInfo=function(e){!function(e){if(e=e||{},e.success="function"==typeof e.success?e.success:s.noop,e.error="function"==typeof e.error?e.error:s.noop,s.log("Getting info on Janus instance"),!b)return s.warn("Is the server down? (connected=false)"),void e.error("Is the server down? (connected=false)");let n=s.randomString(12),i={janus:"info",transaction:n};h&&(i.token=h);m&&(i.apisecret=m);if(t)return _.set(n,function(t){s.log("Server info:"),s.debug(t),"server_info"!==t.janus&&s.error("Ooops: "+t.error.code+" "+t.error.reason),e.success(t)}),void r.send(JSON.stringify(i));s.httpAPICall(c,{verb:"POST",withCredentials:p,body:i,success:function(t){s.log("Server info:"),s.debug(t),"server_info"!==t.janus&&s.error("Ooops: "+t.error.code+" "+t.error.reason),e.success(t)},error:function(t,r){s.error(t+":",r),""===r?e.error(t+": Is the server down?"):e.error(t+": "+r)}})}(e)},this.destroy=function(o){!function(o){o=o||{},o.success="function"==typeof o.success?o.success:s.noop,o.error="function"==typeof o.error?o.error:s.noop;let a=!0===o.unload,d=!0;void 0!==o.notifyDestroyed&&null!==o.notifyDestroyed&&(d=!0===o.notifyDestroyed);let u=!0===o.cleanupHandles;if(s.log("Destroying session "+T+" (unload="+a+")"),!T)return s.warn("No session to destroy"),o.success(),void(d&&e.destroyed());if(u)for(const e of S.keys())L(e,{noRequest:!0});if(!b)return s.warn("Is the server down? (connected=false)"),T=null,void o.success();let l={janus:"destroy",transaction:s.randomString(12)};h&&(l.token=h);m&&(l.apisecret=m);if(a)return t?(r.onclose=null,r.close(),r=null):navigator.sendBeacon(c+"/"+T,JSON.stringify(l)),s.log("Destroyed session:"),T=null,b=!1,o.success(),void(d&&e.destroyed());if(t){l.session_id=T;let t=function(){for(let e in n)r.removeEventListener(e,n[e]);r.removeEventListener("message",a),r.removeEventListener("error",s),i&&clearTimeout(i),r.close()},a=function(r){let n=JSON.parse(r.data);n.session_id==l.session_id&&n.transaction==l.transaction&&(t(),o.success(),d&&e.destroyed())},s=function(){t(),o.error("Failed to destroy the server: Is the server down?"),d&&e.destroyed()};return r.addEventListener("message",a),r.addEventListener("error",s),void(1===r.readyState?r.send(JSON.stringify(l)):s())}s.httpAPICall(c+"/"+T,{verb:"POST",withCredentials:p,body:l,success:function(t){s.log("Destroyed session:"),s.debug(t),T=null,b=!1,"success"!==t.janus&&s.error("Ooops: "+t.error.code+" "+t.error.reason),o.success(),d&&e.destroyed()},error:function(t,r){s.error(t+":",r),T=null,b=!1,o.success(),d&&e.destroyed()}})}(o)},this.attach=function(e){!function(e){if(e=e||{},e.success="function"==typeof e.success?e.success:s.noop,e.error="function"==typeof e.error?e.error:s.noop,e.dataChannelOptions=e.dataChannelOptions||{ordered:!0},e.consentDialog="function"==typeof e.consentDialog?e.consentDialog:s.noop,e.connectionState="function"==typeof e.connectionState?e.connectionState:s.noop,e.iceState="function"==typeof e.iceState?e.iceState:s.noop,e.mediaState="function"==typeof e.mediaState?e.mediaState:s.noop,e.webrtcState="function"==typeof e.webrtcState?e.webrtcState:s.noop,e.slowLink="function"==typeof e.slowLink?e.slowLink:s.noop,e.onmessage="function"==typeof e.onmessage?e.onmessage:s.noop,e.onlocaltrack="function"==typeof e.onlocaltrack?e.onlocaltrack:s.noop,e.onremotetrack="function"==typeof e.onremotetrack?e.onremotetrack:s.noop,e.ondata="function"==typeof e.ondata?e.ondata:s.noop,e.ondataopen="function"==typeof e.ondataopen?e.ondataopen:s.noop,e.oncleanup="function"==typeof e.oncleanup?e.oncleanup:s.noop,e.ondetached="function"==typeof e.ondetached?e.ondetached:s.noop,!b)return s.warn("Is the server down? (connected=false)"),void e.error("Is the server down? (connected=false)");let n=e.plugin;if(!n)return s.error("Invalid plugin"),void e.error("Invalid plugin");let i=e.opaqueId,o=e.loopIndex,a=e.token?e.token:h,d=s.randomString(12),u={janus:"attach",plugin:n,opaque_id:i,loop_index:o,transaction:d};a&&(u.token=a);m&&(u.apisecret=m);if(t)return _.set(d,function(t){if(s.debug(t),"success"!==t.janus)return s.error("Ooops: "+t.error.code+" "+t.error.reason),void e.error("Ooops: "+t.error.code+" "+t.error.reason);let r=t.data.id;s.log("Created handle: "+r);let i={session:C,plugin:n,id:r,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 r},getPlugin:function(){return n},getVolume:function(e,t){return W(r,e,!0,t)},getRemoteVolume:function(e,t){return W(r,e,!0,t)},getLocalVolume:function(e,t){return W(r,e,!1,t)},isAudioMuted:function(e){return V(r,e,!1)},muteAudio:function(e){return K(r,e,!1,!0)},unmuteAudio:function(e){return K(r,e,!1,!1)},isVideoMuted:function(e){return V(r,e,!0)},muteVideo:function(e){return K(r,e,!0,!0)},unmuteVideo:function(e){return K(r,e,!0,!1)},getBitrate:function(e){return z(r,e)},setMaxBitrate:function(e,t){return $(r,e,t)},send:function(e){E(r,e)},data:function(e){D(r,e)},dtmf:function(e){N(r,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){M(r,!0,e)},createAnswer:function(e){M(r,!1,e)},handleRemoteJsep:function(e){x(r,e)},replaceTracks:function(e){G(r,e)},getLocalTracks:function(){return J(r)},getRemoteTracks:function(){return F(r)},onlocaltrack:e.onlocaltrack,onremotetrack:e.onremotetrack,ondata:e.ondata,ondataopen:e.ondataopen,oncleanup:e.oncleanup,ondetached:e.ondetached,hangup:function(e){q(r,!0===e)},detach:function(e){L(r,e)}};S.set(r,i),e.success(i)}),u.session_id=T,void r.send(JSON.stringify(u));s.httpAPICall(c+"/"+T,{verb:"POST",withCredentials:p,body:u,success:function(t){if(s.debug(t),"success"!==t.janus)return s.error("Ooops: "+t.error.code+" "+t.error.reason),void e.error("Ooops: "+t.error.code+" "+t.error.reason);let r=t.data.id;s.log("Created handle: "+r);let i={session:C,plugin:n,id:r,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 r},getPlugin:function(){return n},getVolume:function(e,t){return W(r,e,!0,t)},getRemoteVolume:function(e,t){return W(r,e,!0,t)},getLocalVolume:function(e,t){return W(r,e,!1,t)},isAudioMuted:function(e){return V(r,e,!1)},muteAudio:function(e){return K(r,e,!1,!0)},unmuteAudio:function(e){return K(r,e,!1,!1)},isVideoMuted:function(e){return V(r,e,!0)},muteVideo:function(e){return K(r,e,!0,!0)},unmuteVideo:function(e){return K(r,e,!0,!1)},getBitrate:function(e){return z(r,e)},setMaxBitrate:function(e,t){return $(r,e,t)},send:function(e){E(r,e)},data:function(e){D(r,e)},dtmf:function(e){N(r,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){M(r,!0,e)},createAnswer:function(e){M(r,!1,e)},handleRemoteJsep:function(e){x(r,e)},replaceTracks:function(e){G(r,e)},getLocalTracks:function(){return J(r)},getRemoteTracks:function(){return F(r)},onlocaltrack:e.onlocaltrack,onremotetrack:e.onremotetrack,ondata:e.ondata,ondataopen:e.ondataopen,oncleanup:e.oncleanup,ondetached:e.ondetached,hangup:function(e){q(r,!0===e)},detach:function(e){L(r,e)}};S.set(r,i),e.success(i)},error:function(t,r){s.error(t+":",r),""===r?e.error(t+": Is the server down?"):e.error(t+": "+r)}})}(e)}}s.useDefaultDependencies=function(e){let t=e&&e.fetch||fetch,r=e&&e.Promise||Promise,n=e&&e.WebSocket||WebSocket;return{newWebSocket:function(e,t){return new n(e,t)},extension:e&&e.extension||a,isArray:function(e){return Array.isArray(e)},webRTCAdapter:e&&e.adapter||adapter,httpAPICall:function(e,n){let i={method:n.verb,headers:{Accept:"application/json, text/plain, */*"},cache:"no-cache"};"POST"===n.verb&&(i.headers["Content-Type"]="application/json"),void 0!==n.withCredentials&&(i.credentials=!0===n.withCredentials?"include":n.withCredentials?n.withCredentials:"omit"),n.body&&(i.body=JSON.stringify(n.body));let o=t(e,i).catch(function(e){return r.reject({message:"Probably a network error, is the server down?",error:e})});if(n.timeout){let e=new r(function(e,t){let r=setTimeout(function(){return clearTimeout(r),t({message:"Request timed out",timeout:n.timeout})},n.timeout)});o=r.race([o,e])}return o.then(function(e){return e.ok?typeof n.success==typeof s.noop?e.json().then(function(e){try{n.success(e)}catch(e){s.error("Unhandled httpAPICall success callback error",e)}},function(t){return r.reject({message:"Failed to parse response body",error:t,response:e})}):void 0:r.reject({message:"API call failed",response:e})}).catch(function(e){typeof n.error==typeof s.noop&&n.error(e.message||"<< internal error >>",e)}),o}}},s.useOldDependencies=function(e){let t=e&&e.jQuery||jQuery,r=e&&e.WebSocket||WebSocket;return{newWebSocket:function(e,t){return new r(e,t)},isArray:function(e){return t.isArray(e)},extension:e&&e.extension||a,webRTCAdapter:e&&e.adapter||adapter,httpAPICall:function(e,r){let n=void 0!==r.body?{contentType:"application/json",data:JSON.stringify(r.body)}:{},i=void 0!==r.withCredentials?{xhrFields:{withCredentials:r.withCredentials}}:{};return t.ajax(t.extend(n,i,{url:e,type:r.verb,cache:!1,dataType:"json",async:r.async,timeout:r.timeout,success:function(e){typeof r.success==typeof s.noop&&r.success(e)},error:function(e,t,n){typeof r.error==typeof s.noop&&r.error(t,n)}}))}}},s.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 r={type:"audio"};e.removeAudio?r.remove=!0:(e.addAudio?r.add=!0:e.replaceAudio&&(r.replace=!0),!1!==e.audioSend&&(r.capture=e.audio||!0),!1!==e.audioRecv&&(r.recv=!0)),(r.remove||r.capture||r.recv)&&t.push(r)}if(!e.keepVideo&&!1!==e.video&&(void 0===e.video||e.video||e.videoSend||e.videoRecv||e.addVideo||e.replaceVideo||e.removeVideo)){let r={type:"video"};e.removeVideo?r.remove=!0:(e.addVideo?r.add=!0:e.replaceVideo&&(r.replace=!0),!1!==e.videoSend&&(r.capture=e.video||!0,["screen","window","desktop"].includes(r.capture)&&(r.type="screen",r.capture={video:{}},e.screenshareFrameRate&&(r.capture.frameRate=e.screenshareFrameRate),e.screenshareHeight&&(r.capture.height=e.screenshareHeight),e.screenshareWidth&&(r.capture.width=e.screenshareWidth))),!1!==e.videoRecv&&(r.recv=!0)),(r.remove||r.capture||r.recv)&&t.push(r)}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},s.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 r=0,n=0;"lowres"===e.capture?(r=320,n=240):"lowres-16:9"===e.capture?(r=320,n=180):"hires"===e.capture||"hires-16:9"===e.capture||"hdres"===e.capture?(r=1280,n=720):"fhdres"===e.capture?(r=1920,n=1080):"4kres"===e.capture?(r=3840,n=2160):"stdres"===e.capture?(r=640,n=480):"stdres-16:9"===e.capture?(r=640,n=360):(s.log("Default video setting is stdres 4:3"),r=640,n=480),t.video={width:{ideal:r},height:{ideal:n}}}else"screen"===e.type&&(t.video=e.capture);return t},s.noop=function(){},s.dataChanDefaultLabel="JanusDataChannel",s.endOfCandidates=null,s.stopAllTracks=function(e){try{let t=e.getTracks();for(let e of t)s.log(e),e&&!0!==e.dontStop&&e.stop()}catch(e){}},s.init=function(e){if((e=e||{}).callback="function"==typeof e.callback?e.callback:s.noop,s.initDone)e.callback();else{if(void 0===console.log&&(console.log=function(){}),s.trace=s.noop,s.debug=s.noop,s.vdebug=s.noop,s.log=s.noop,s.warn=s.noop,s.error=s.noop,!0===e.debug||"all"===e.debug)s.trace=console.trace.bind(console),s.debug=console.debug.bind(console),s.vdebug=console.debug.bind(console),s.log=console.log.bind(console),s.warn=console.warn.bind(console),s.error=console.error.bind(console);else if(Array.isArray(e.debug))for(let t of e.debug)switch(t){case"trace":s.trace=console.trace.bind(console);break;case"debug":s.debug=console.debug.bind(console);break;case"vdebug":s.vdebug=console.debug.bind(console);break;case"log":s.log=console.log.bind(console);break;case"warn":s.warn=console.warn.bind(console);break;case"error":s.error=console.error.bind(console);break;default:console.error("Unknown debugging option '"+t+"' (supported: 'trace', 'debug', 'vdebug', 'log', warn', 'error')")}s.log("Initializing library");let t=e.dependencies||s.useDefaultDependencies();s.isArray=t.isArray,s.webRTCAdapter=t.webRTCAdapter,s.httpAPICall=t.httpAPICall,s.newWebSocket=t.newWebSocket,s.extension=t.extension,s.extension.init(),s.listDevices=function(e,t){e="function"==typeof e?e:s.noop,t||(t={audio:!0,video:!0}),s.isGetUserMediaAvailable()?navigator.mediaDevices.getUserMedia(t).then(function(t){navigator.mediaDevices.enumerateDevices().then(function(r){s.debug(r),e(r),s.stopAllTracks(t)})}).catch(function(t){s.error(t),e([])}):(s.warn("navigator.mediaDevices unavailable"),e([]))},s.attachMediaStream=function(e,t){try{e.srcObject=t}catch(r){try{e.src=URL.createObjectURL(t)}catch(e){s.error("Error attaching stream to element",e)}}},s.reattachMediaStream=function(e,t){try{e.srcObject=t.srcObject}catch(r){try{e.src=t.src}catch(e){s.error("Error reattaching stream to element",e)}}};let r=["iPad","iPhone","iPod"].indexOf(navigator.platform)>=0?"pagehide":"beforeunload",n=window["on"+r];if(window.addEventListener(r,function(){s.log("Closing window");for(const[e,t]of s.sessions)t&&t.destroyOnUnload&&(s.log("Destroying session "+e),t.destroy({unload:!0,notifyDestroyed:!1}));n&&"function"==typeof n&&n()}),s.safariVp8=!1,s.safariVp9=!1,"safari"===s.webRTCAdapter.browserDetails.browser&&s.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()?s.safariVp8=!0:e&&e.mimeType&&"video/vp9"===e.mimeType.toLowerCase()&&(s.safariVp9=!0);s.safariVp8?s.log("This version of Safari supports VP8"):s.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){s.safariVp8=-1!==t.sdp.indexOf("VP8"),s.safariVp9=-1!==t.sdp.indexOf("VP9"),s.safariVp8?s.log("This version of Safari supports VP8"):s.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})}s.initDone=!0,e.callback()}},s.isWebrtcSupported=function(){return!!window.RTCPeerConnection},s.isGetUserMediaAvailable=function(){return navigator.mediaDevices&&navigator.mediaDevices.getUserMedia},s.randomString=function(e){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",r="";for(let n=0;n<e;n++){let e=Math.floor(62*Math.random());r+=t.charAt(e)}return r};function c(e,t=1e4){const r=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 r.postMessage("START"),r.onmessage=t=>{"heartbeat"===t.data&&(console.log("Worker active at:",new Date),e())},window.addEventListener("unload",()=>{r.terminate()}),r}const d={url:null,queue:[],timer:null,batchSize:20,flushInterval:5e3,push(e,t,r){const n=`[${(new Date).toLocaleString("zh-CN",{hour12:!1})}] [VoiceNine] [${t}]`;"warn"===e?console.warn(n,r):"error"===e?console.error(n,r):console.log(n,r)}};function u(e,t){d.push("info",e,t)}function l(e,t){d.push("warn",e,t)}function p(e,t,r){d.push("error",e,r?`${t} ${r}`:t)}const f={agentId:"",agentKey:"",companyId:"",agentType:"",token:"",wsServer:"",webrtcServer:"",sipServer:"",agentCode:"",sipPwd:"",groupId:"",groupIds:[]};class h{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;_janusInitializing=!1;static _janusInited=!1;_sipRetryCount=0;_sipRetryTimer=null;_sipMaxRetries=5;_webrtcDownTimer=null;_sipRegisterTimeout=null;_sipRegistered=!1;_dtlsCheckTimer=null;_iceDisconnectTimer=null;_worker=null;constructor(){if(this.instance)return this.instance;this.instance=this,this._worker=c(()=>{this._keepalive(),this.janus&&!this._userLogout&&this.janus?.keepalive()})}_init(e){this.seat={...f,...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),u("_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 r=document.createElement("audio");r.id="incomingcallAudio",r.loop=!0,r.src="https://r.hanfatong.com/voicenine/beep.mp3",t.appendChild(r);const n=document.createElement("audio");n.id="callEndAudio",n.loop=!1,n.src="https://r.hanfatong.com/voicenine/hangup.mp3",t.appendChild(n);const i=document.createElement("audio");i.id="peerVideo",i.autoplay=!0,t.appendChild(i)}_initJanus(){const{webrtcServer:t,sipServer:r}=this.seat;if(!t||!r)return void p("_initJanus","WebRTC server or SIP server is not configured.");if(this._janusInitializing)return void l("_initJanus","已在初始化中,跳过重复调用");if(this._janusInitializing=!0,this.janus){u("_initJanus","检测到旧 Janus session,先销毁");try{this.janus.destroy({cleanupHandles:!0,notifyDestroyed:!1})}catch(e){l("_initJanus","销毁旧 Janus 异常")}this.janus=null,this.sipcall=null}let n={},i={},o=!1;const a=this.seat.janusDebug||"warn",c=()=>{u("_initJanus","Janus initialized.");if(!s.isWebrtcSupported())return l("_initJanus","No WebRTC support or not HTTPS."),void(this._janusInitializing=!1);this.trigger("connstate",{type:"janus",state:"connecting"}),this._sipRegisterTimeout&&clearTimeout(this._sipRegisterTimeout),this._sipRegisterTimeout=setTimeout(()=>{this.sipcall&&!this._sipRegistered&&this.connected&&!this._userLogout&&(l("_initJanus","SIP 注册超时(15s),重建 Janus"),this._rebuildJanus())},15e3),this._sipRegistered=!1;const r=new s({server:t,success:()=>{this.trigger("connstate",{type:"janus",state:"connected"}),r.attach({plugin:"janus.plugin.sip",opaqueId:"voicenine_"+s.randomString(16),success:e=>{u("_initJanus","SIP plugin attached."),this.sipcall=e,this._janusRetryCount=0,this._sipRetryCount=0,this._janusInitializing=!1,this._registerSip()},onmessage:(t,r)=>{s.debug(" ::: Got a message :::",t);const{call_id:n,result:i}=t;if(i?.event){const a=i.event;if(this.msg=null,this.jsep=null,"registration_failed"===a)l("_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)u("_initJanus","SIP registered: "+i.username),this._sipRegistered=!0,this._sipRegisterTimeout&&(clearTimeout(this._sipRegisterTimeout),this._sipRegisterTimeout=null),o||(o=!0,i.master_id),this.trigger("sipstate",{registered:!0,username:i.username});else if("calling"===a)u("_initJanus","calling...");else if("incomingcall"===a){u("_initJanus","incomingcall"),this.sipcall.callId=n,this.toggleRing(!0),r&&r.sdp&&(r.sdp=this._sanitizeSdp(r.sdp)),this.msg=t,this.jsep=r;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,r)):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)u("_initJanus","progress"),r&&(r.sdp&&(r.sdp=this._sanitizeSdp(r.sdp)),this.sipcall.handleRemoteJsep({jsep:r}));else if("accepted"===a)u("_initJanus","accepted"),this.toggleRing(!1),r&&(r.sdp&&(r.sdp=this._sanitizeSdp(r.sdp)),this.sipcall.handleRemoteJsep({jsep:r})),this.sipcall.callId=n;else if("updatingcall"===a){u("_initJanus","updatingcall");const e=r.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:r,tracks:t,success:t=>{s.debug("Got SDP "+t.type+"! audio="+e+":",t);this.sipcall.send({message:{request:"update"},jsep:t})},error:e=>{this.trigger("error",e),p("createAnswer","WebRTC error",e)}})}else if("message"===a);else if("info"===a);else if("notify"===a);else if("transfer"===a);else if("hangup"===a){u("_initJanus",`hangup: ${i.code} ${i.reason}`);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)=>{u("onlocaltrack",`${t?"added":"removed"} kind=${e.kind}`);const r=e.id.replace(/[{}]/g,"");if(!t){if(this.stream=n[r],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){p("onlocaltrack","停止本地轨道失败",e)}return e.kind,void delete n[r]}this.stream=n[r],this.stream||(e.kind,"completed"!==this.sipcall.webrtcStuff.pc.iceConnectionState&&this.sipcall.webrtcStuff.pc.iceConnectionState)},onremotetrack:(e,t,r)=>{if(r&&"audio"===e.kind){const r=new MediaStream([e]);i[t]=r;let n=document.getElementById("peerVideo");s.attachMediaStream(n,r)}},oncleanup:()=>{u("oncleanup","cleanup notification"),setTimeout(()=>{this.sipcall&&(delete this.sipcall.callId,delete this.sipcall.doAudio)},50),setTimeout(()=>{Object.values(n).forEach(e=>{if(e){e.getTracks().forEach(e=>{"ended"!==e.readyState&&e.stop()})}})},100),setTimeout(()=>{n={},i={},this.stream=null,this._iceRestarting=!1,this._dtlsRebuildNeeded=!1,this._iceRestartCooldown=null},200)},error:e=>{p("_initJanus","attach plugin error",e),this._janusInitializing=!1,this.connected&&!this._userLogout&&this._retryJanus("attach_error")},consentDialog:function(e){},webrtcTimeout:function(e){u("webrtcTimeout",e)},iceState:e=>{u("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,r)=>{u("mediaState",`${e} ${t?"started":"stopped"} mid=${r}`),"audio"===e&&t&&this._iceRestarting&&this._onIceRestartSuccess()},webrtcState:e=>{if(u("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&&(l("webrtcState","WebRTC down 超时,重建 Janus session"),this.trigger("icestate",{state:"failed",reason:"webrtc_down"}),this._rebuildJanus())},8e3))}},slowLink:function(e,t,r){l("slowLink",`${e?"sending":"receiving"} lost=${t} mid=${r}`)}})},error:e=>{p("_initJanus","janus session error",e),this._janusInitializing=!1,this.trigger("connstate",{type:"janus",state:"failed",reason:e}),this.connected&&!this._userLogout&&this._retryJanus("session_error")},destroyed:()=>{u("_initJanus","destroyed")}});this.janus=r,window.Janus=s};h._janusInited?c():s.init({debug:a,callback:()=>{h._janusInited=!0,c()}})}_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=>{p("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&&u("echo",`cmd=${t.cmd} agentKey=${t.agentKey||""}`)}catch{u("echo","发送消息")}this.socket.send(e)}else l("echo","WebSocket 未连接,消息丢弃")}toggleRing(e){const t=document.getElementById("incomingcallAudio");e?t.play():t.pause()}playEndRing(){document.getElementById("callEndAudio").play()}connectWs(r){if(u("connectWs","连接WebSocket: "+r.split("?")[0]),!window.WebSocket)return void alert("您的浏览器不支持WebSocket协议!");this.trigger("connstate",{type:"ws",state:"connecting"});const n=new WebSocket(r);this.socket=n,n.onmessage=r=>{const n=JSON.parse(r.data);if("PONG"!==n.type&&"pong"!==n.type&&u("onmessage",`type=${n.type} code=${n.code} agentKey=${n.agentKey||""}`),this.onmessage(n),n.type===t.TASK_CALL)return void(0===n.code&&(this.trigger(t.TASK_CALL,n),this.trigger("taskCall",n)));let i=n.type;e[i]&&(0===n.code&&(this.lastStatus=this.status,this.status=i,u("onmessage",`状态变更: ${this.lastStatus} -> ${this.status}`)),this.code=n.code,this.handleStatusChange(n))},n.onopen=()=>{u("connectWs","WebSocket connection opened."),this.clearReconectStatus(),this.sendAction(e.LOGIN),this.connected=!0,this.trigger("connstate",{type:"ws",state:"connected"})},n.onclose=e=>{u("connectWs",`WebSocket connection closed, Code: ${e.code}${e.reason?", Reason: "+e.reason:""}`),this.reconectInterval&&(clearTimeout(this.reconectInterval),this.reconectInterval=null),this.connected=!1;if(this.trigger("logout",this.code),this.trigger("connstate",{type:"ws",state:"closed",code:e.code,reason:e.reason}),this._clearAllTimers(),2===this.seat.loginType){if(this.sipcall&&this.status&&this.status.includes("TALKING")){l("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}if([1111,1403,1105,1417].includes(this.code))return void u("connectWs","不自动重连, code: "+this.code);if(this._userLogout||1e3===e.code&&"Bye"===e.reason)return void u("connectWs","主动登出,不自动重连");(()=>{this.reconectInterval=setTimeout(()=>{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:r,message:n,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=[],r===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(r===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.sipcall&&this._sipRegistered?u("handleStatusChange",`通话未接通(${o.sipStatus}),SIP 注册正常,跳过`):this.sipcall&&!this._sipRegistered?(l("handleStatusChange",`通话未接通(${o.sipStatus}),SIP 未注册,尝试重新注册`),this._registerSip()):(l("handleStatusChange",`通话未接通(${o.sipStatus}),Janus 连接异常,重建`),this._rebuildJanus())));const t=o.afterInterval||3;this.afterPhoneInterval=setTimeout(()=>{this.status===e.AFTER&&(u("handleStatusChange","话后自动空闲"),this.sendAction(e.READY))},1e3*t)}else r===e.OUT_CALL||(r===e.READY||r===e.NOT_READY||r===e.WORK_NOT_READY)&&(this.reconnectState=r);this.trigger("state",t),this.trigger(r,t)}sendAction(e,t){let r={cmd:e,agentKey:this.seat.agentKey,sequence:(new Date).getTime()};if(e===n.login)r={...r,loginType:this.seat.loginType,workType:this.seat.workType},this.status&&this.status.includes("TALKING")&&(r.callId=this.callId);else if(e===n.call){this.afterPhoneInterval&&window.clearInterval(this.afterPhoneInterval);const{telNum:e,display:n="",followData:i}=t||{};r={...r,called:e,display:n,callType:1,followData:i||{}}}else if(e===n.transfer){let{transferValue:e,transferType:n="4"}=t||{};e.includes("@")&&(n="3"),r={...r,transferType:n,transferValue:e}}else if(e===n.consult){const{consultValue:e}=t||{};let n="2";e.includes("@")&&(n="4"),r={...r,callId:this.callId,transferType:n,consultValue:e}}else if(e===n.consult_cancel);else if(e===n.consult_party)r.callId=this.callId;else if(e===n.consult_transfer)r.callId=this.callId;else if(e===n.busy_work){const{busyDesc:e}=t||{};r={...r,busyDesc:e,callId:this.callId}}else if(e===n.ready)this.afterPhoneInterval&&window.clearInterval(this.afterPhoneInterval);else if(e===n.busy)this.afterPhoneInterval&&window.clearInterval(this.afterPhoneInterval);else if(e===n.conference_remove){const{deviceId:n,memberId:i,username:o}=t||{};r={cmd:e,callId:this.callId,deviceId:n,conference:this.conference,memberId:i,username:o}}else{if(e===n.logout){this._userLogout=!0,this._clearAllTimers();const e=JSON.stringify(r);return this.echo(e),2===this.seat.loginType&&this.janus?.destroy(),void(this._worker&&(this._worker.terminate(),this._worker=null))}e===n.followdata?r={...r,callId:this.callId,followData:t.followData||{}}:e===n.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&&(clearTimeout(this.reconectInterval),this.reconectInterval=null)}_clearAllTimers(){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),this.autoAcceptTimer&&(clearTimeout(this.autoAcceptTimer),this.autoAcceptTimer=null),this.afterPhoneInterval&&(clearTimeout(this.afterPhoneInterval),this.afterPhoneInterval=null)}_iceRestart(e){if(this._userLogout||!this.connected)return;if(!(this.status&&this.status.includes("TALKING")))return void("failed"===e&&(l("_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?(l("_iceRestart","ICE failed(冷却期内),上次 restart 未恢复,重建 Janus"),this.trigger("icestate",{state:"failed",reason:"ice_restart_ineffective"}),this._rebuildJanus()):(l("_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 u("_iceRestart","ICE disconnected 后自动恢复")}catch(e){}l("_iceRestart","ICE disconnected 5s 未恢复,重建 Janus"),this.trigger("icestate",{state:"failed",reason:"ice_disconnect_timeout"}),this._rebuildJanus()}},5e3))):(l("_iceRestart",`ICE ${e},尝试 ICE restart 恢复通话`),this.trigger("icestate",{state:"disconnected"}),this.sipcall.createOffer({iceRestart:!0,tracks:[{type:"audio",capture:!0,recv:!0}],success:e=>{u("_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=>{p("_iceRestart","ICE restart 失败",e),this.trigger("icestate",{state:"failed"}),l("_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),u("_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 r=t.iceConnectionState,n=t.connectionState||"N/A",i=t.sctp?.transport||t.getSenders?.()[0]?.transport,o=i?.state||"N/A";if(u("_dtlsCheck",`[${e}/5] ice=${r} conn=${n} dtls=${o}`),"connected"===n||"connected"===r&&"connected"===o)return u("_dtlsCheck","DTLS 恢复成功"),this._dtlsRebuildNeeded=!1,this._dtlsCheckTimer=null,void this.trigger("icestate",{state:"dtls_recovered"});if("failed"===n||"failed"===r||"failed"===o)return l("_dtlsCheck",`DTLS 恢复失败: ice=${r} conn=${n} dtls=${o},重建 Janus`),this._dtlsCheckTimer=null,this.trigger("icestate",{state:"failed",reason:"dtls_failed"}),void this._rebuildJanus()}else l("_dtlsCheck",`[${e}/5] PeerConnection 不存在`)}catch(t){l("_dtlsCheck",`[${e}/5] 检查异常: ${t}`)}if(e>=5)return l("_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,l("_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"),r=[];let n=!1;for(const e of t)e.startsWith("m=video")?(n=!0,u("_sanitizeSdp","移除 video 媒体段")):(n&&e.startsWith("m=")&&(n=!1),n||r.push(e));const i=[];return r.forEach(e=>{const t=e.match(/^a=mid:(.+)$/);t&&i.push(t[1].trim())}),r.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 l("_retrySipRegister",`SIP 注册失败 code=${e},认证错误不重试`);if(this._sipRetryCount>=this._sipMaxRetries)return p("_retrySipRegister",`SIP 注册重试已达上限 ${this._sipMaxRetries} 次,重建 Janus`),this._sipRetryCount=0,void this._rebuildJanus();this._sipRetryCount++;const r=Math.min(2e3*Math.pow(2,this._sipRetryCount-1),3e4);l("_retrySipRegister",`SIP 注册失败,${r}ms 后第 ${this._sipRetryCount} 次重试`),this._sipRetryTimer&&clearTimeout(this._sipRetryTimer),this._sipRetryTimer=setTimeout(()=>{this.sipcall&&this.connected&&!this._userLogout&&this._registerSip()},r)}_retryJanus(e){if(this._janusRetryCount>=this._janusMaxRetries)return p("_retryJanus",`Janus 重连已达上限 ${this._janusMaxRetries} 次 (${e}),停止重连`),this._janusRetryCount=0,void this.trigger("connstate",{type:"janus",state:"give_up",reason:e});this._janusRetryCount++;const t=Math.floor(3e3*Math.random()),r=Math.min(2e3*Math.pow(2,this._janusRetryCount-1),3e4)+t;l("_retryJanus",`${e},${r}ms 后第 ${this._janusRetryCount} 次重建 Janus`),this._janusRetryTimer&&clearTimeout(this._janusRetryTimer),this._janusRetryTimer=setTimeout(()=>{this.connected&&!this._userLogout&&this._initJanus()},r)}_rebuildJanus(){if(this.status&&this.status.includes("TALKING")&&this.sipcall){l("_rebuildJanus","通话中 Janus 异常,先挂断通话再重建");try{this.sipcall.send({message:{request:"hangup"}}),this.sipcall.hangup()}catch(e){l("_rebuildJanus","挂断异常")}this.toggleRing(!1),this.isHangup=!0}u("_rebuildJanus","销毁旧 Janus 并重建");try{this.janus?.destroy({cleanupHandles:!0})}catch(e){l("_rebuildJanus","销毁 Janus 异常")}this.janus=null,this.sipcall=null,this._iceRestarting=!1,this._dtlsRebuildNeeded=!1,this._sipRegistered=!1,this._janusInitializing=!1,this._clearAllTimers(),this._retryJanus("rebuild")}on(e,t){this.events[e]||(u("on","订阅事件: "+e),this.events[e]=[]),this.events[e].push(t)}trigger(e,t){this.events[e]&&("message"!==e&&u("trigger","触发事件: "+e),this.events[e].forEach(e=>e(t)))}onmessage(e){this.trigger("message",e)}datelog(){var e=new Date,t=e.getFullYear(),r=e.getMonth()+1,n=e.getDate(),i=e.getHours(),o=e.getMinutes(),a=e.getSeconds(),s=e.getMilliseconds();return r<10&&(r="0"+r),n<10&&(n="0"+n),i<10&&(i="0"+i),o<10&&(o="0"+o),a<10&&(a="0"+a),s<10?s+="00":s<100&&(s+="0"),t+"-"+r+"-"+n+" "+i+":"+o+":"+a+"."+s}}const m=new h;class g{static _instance=null;static _version_="1.5.3";static _enum_={state:e,btn:n,label:i,taskEvent:t,taskCallStatus:r};constructor(){if(g._instance)return g._instance;g._instance=this,console.log("[VoiceNine] version:",g._version_),this.on("state",e=>this._stateHandler(e))}get version(){return g._version_}get status(){return m.status}get enum(){return g._enum_}init(e){console.log("["+m.datelog()+"] voice9 init",e),m._init(e)}logout(){m.sendAction(n.logout)}setBusy(){m.sendAction(n.busy)}setReady(){m.sendAction(n.ready)}setWorkNotReady(e){m.sendAction(n.busy_work,{busyDesc:e})}call(t,r={}){const i=[e.LOGIN,e.READY,e.NOT_READY,e.WORK_NOT_READY,e.AFTER];if(!m.connected)return{success:!1,reason:"ws_disconnected",message:"WebSocket 未连接"};if(!i.includes(m.status))return{success:!1,reason:"invalid_state",message:`当前状态不允许外呼: ${m.status}`};if(2===m.seat.loginType){if(!m.sipcall)return{success:!1,reason:"webrtc_not_ready",message:"WebRTC 未初始化"};const e=m.sipcall.webrtcStuff?.pc?.iceConnectionState;if(e&&"connected"!==e&&"completed"!==e&&"new"!==e)return{success:!1,reason:"ice_disconnected",message:`ICE 连接异常: ${e}`}}return m.sendAction(n.call,{telNum:t,...r}),{success:!0}}answer(){m.accept(m.msg,m.jsep)}sendDtmf(e){const t={cmd:"dtmf",dtmf:e,callId:m.callId,agentKey:m.seat.agentKey,sequence:(new Date).getTime()};m.echo(JSON.stringify(t))}hangup(){m.sendAction(n.hangup)}transfer(e,t={}){m.sendAction(n.transfer,{transferValue:e,...t})}consult(e,t={}){m.sendAction(n.consult,{consultValue:e,...t})}cancelConsult(){m.sendAction(n.consult_cancel)}stopConsult(){m.sendAction(n.consult_stop)}consultTransfer(e,t={}){m.sendAction(n.consult_transfer,{transferValue:e,...t})}consultParty(){m.sendAction(n.consult_party)}mute(){m.sendAction(n.mute)}muteCancel(){m.sendAction(n.mute_cancel)}hold(){m.sendAction(n.hold)}holdCancel(){m.sendAction(n.hold_cancel)}monitor(e,t){const r={cmd:"MONITOR_CALL",callId:t,agentKey:m.seat.agentKey,monitorAgent:e,sequence:(new Date).getTime()};m.echo(JSON.stringify(r))}intercept(){m.sendAction("INTERCEPT_CALL")}barge(e,t){const r={cmd:"BARGE_CALL",callId:t,agentKey:m.seat.agentKey,monitorAgent:e,sequence:(new Date).getTime()};m.echo(JSON.stringify(r))}coach(e,t){const r={cmd:"COACH_CALL",callId:t,agentKey:m.seat.agentKey,monitorAgent:e,sequence:(new Date).getTime()};m.echo(JSON.stringify(r))}updateFollowData(e){const t={cmd:"UPDATE_FOLLOWDATA",followData:e,callId:m.callId,agentKey:m.seat.agentKey,sequence:(new Date).getTime()};m.echo(JSON.stringify(t))}action(e,t){m.sendAction(e,t)}message(e){m.echo(JSON.stringify(e))}on(e,t){m.on(e,t)}off(e,t){if(!m.events[e])return;if(!t)return void(m.events[e]=[]);const r=m.events[e].indexOf(t);r>-1&&m.events[e].splice(r,1)}emit(e,t){m.trigger(e,t)}_stateHandler(t){const{type:r,code:n}=t;if(m.events.btnstate){const e=o[r]||[];m.events.btnstate.forEach(t=>t(e))}if(m.events.agentstate){let t=r;t===e.LOGIN&&0!==Number(n)&&(t=""),m.events.agentstate.forEach(e=>e(t))}}}export{g 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={TASK_CALL:"TASK_CALL"},r={DIALING:"DIALING",RINGING:"RINGING",ANSWERED:"ANSWERED",HANGUP:"HANGUP"},n={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"},i={[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]:"多方通话"},o={[e.LOGIN]:[n.call],[e.LOGOUT]:[],[e.READY]:[n.call],[e.NOT_READY]:[n.call],[e.WORK_NOT_READY]:[n.call],[e.AFTER]:[n.call],[e.OUT_CALL]:[n.hangup],[e.OUT_CALLER_RING]:[n.answer,n.hangup],[e.OUT_CALLED_RING]:[n.hangup],[e.PLAY_AGENT_ID]:[n.hangup],[e.TALKING]:[n.hangup,n.hold,n.mute,n.transfer,n.consult],[e.MUTE_TALKING]:[n.mute_cancel],[e.HOLD_TALKING]:[n.hold_cancel],[e.INNER_CALL_RING]:[n.hangup,n.answer],[e.INNER_CALL_TALKING]:[n.hangup,n.mute],[e.INBOUND_RING]:[n.hangup,n.answer],[e.TRANSFER]:[n.transfer_cancel],[e.TRANSFERED_RING]:[n.hangup,n.answer],[e.TRANSFER_OUT_RING]:[n.transfer_cancel],[e.TRANSFERED_TALKING]:[n.hangup,n.mute,n.transfer,n.consult],[e.CONSULT]:[n.consult_cancel],[e.CONSULT_RING]:[n.hangup,n.answer],[e.CONSULT_OUT_RING]:[n.consult_cancel],[e.CONSULT_IVR]:[n.hangup,n.consult_cancel],[e.CONSULT_TALKING]:[n.hangup,n.mute,n.consult_party,n.consult_transfer],[e.CONSULTED_TALKING]:[n.hangup,n.mute],[e.CONFERENCE_TALKING]:[n.hangup,n.mute,n.consult]};!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).adapter=e()}}(function(){return function e(t,r,n){function i(a,s){if(!r[a]){if(!t[a]){var c="function"==typeof require&&require;if(!s&&c)return c(a,!0);if(o)return o(a,!0);var d=new Error("Cannot find module '"+a+"'");throw d.code="MODULE_NOT_FOUND",d}var u=r[a]={exports:{}};t[a][0].call(u.exports,function(e){return i(t[a][1][e]||e)},u,u.exports,e,t,r,n)}return r[a].exports}for(var o="function"==typeof require&&require,a=0;a<n.length;a++)i(n[a]);return i}({1:[function(e,t,r){var n=(0,e("./adapter_factory.js").adapterFactory)({window:"undefined"==typeof window?void 0:window});t.exports=n},{"./adapter_factory.js":2}],2:[function(e,t,r){function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(r,"__esModule",{value:!0}),r.adapterFactory=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.window,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0},n=i.log,u=i.detectBrowser(t),l={browserDetails:u,commonShim:c,extractVersion:i.extractVersion,disableLog:i.disableLog,disableWarnings:i.disableWarnings,sdp:d};switch(u.browser){case"chrome":if(!o||!o.shimPeerConnection||!r.shimChrome)return n("Chrome shim is not included in this adapter release."),l;if(null===u.version)return n("Chrome shim can not determine version, not shimming."),l;n("adapter.js shimming chrome."),l.browserShim=o,c.shimAddIceCandidateNullOrEmpty(t,u),c.shimParameterlessSetLocalDescription(t,u),o.shimGetUserMedia(t,u),o.shimMediaStream(t,u),o.shimPeerConnection(t,u),o.shimOnTrack(t,u),o.shimAddTrackRemoveTrack(t,u),o.shimGetSendersWithDtmf(t,u),o.shimSenderReceiverGetStats(t,u),o.fixNegotiationNeeded(t,u),c.shimRTCIceCandidate(t,u),c.shimRTCIceCandidateRelayProtocol(t,u),c.shimConnectionState(t,u),c.shimMaxMessageSize(t,u),c.shimSendThrowTypeError(t,u),c.removeExtmapAllowMixed(t,u);break;case"firefox":if(!a||!a.shimPeerConnection||!r.shimFirefox)return n("Firefox shim is not included in this adapter release."),l;n("adapter.js shimming firefox."),l.browserShim=a,c.shimAddIceCandidateNullOrEmpty(t,u),c.shimParameterlessSetLocalDescription(t,u),a.shimGetUserMedia(t,u),a.shimPeerConnection(t,u),a.shimOnTrack(t,u),a.shimRemoveStream(t,u),a.shimSenderGetStats(t,u),a.shimReceiverGetStats(t,u),a.shimRTCDataChannel(t,u),a.shimAddTransceiver(t,u),a.shimGetParameters(t,u),a.shimCreateOffer(t,u),a.shimCreateAnswer(t,u),c.shimRTCIceCandidate(t,u),c.shimConnectionState(t,u),c.shimMaxMessageSize(t,u),c.shimSendThrowTypeError(t,u);break;case"safari":if(!s||!r.shimSafari)return n("Safari shim is not included in this adapter release."),l;n("adapter.js shimming safari."),l.browserShim=s,c.shimAddIceCandidateNullOrEmpty(t,u),c.shimParameterlessSetLocalDescription(t,u),s.shimRTCIceServerUrls(t,u),s.shimCreateOfferLegacy(t,u),s.shimCallbacksAPI(t,u),s.shimLocalStreamsAPI(t,u),s.shimRemoteStreamsAPI(t,u),s.shimTrackEventTransceiver(t,u),s.shimGetUserMedia(t,u),s.shimAudioContext(t,u),c.shimRTCIceCandidate(t,u),c.shimRTCIceCandidateRelayProtocol(t,u),c.shimMaxMessageSize(t,u),c.shimSendThrowTypeError(t,u),c.removeExtmapAllowMixed(t,u);break;default:n("Unsupported browser!")}return l};var i=l(e("./utils")),o=l(e("./chrome/chrome_shim")),a=l(e("./firefox/firefox_shim")),s=l(e("./safari/safari_shim")),c=l(e("./common_shim")),d=l(e("sdp"));function u(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(u=function(e){return e?r:t})(e)}function l(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=n(e)&&"function"!=typeof e)return{default:e};var r=u(t);if(r&&r.has(e))return r.get(e);var i={__proto__:null},o=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var a in e)if("default"!==a&&{}.hasOwnProperty.call(e,a)){var s=o?Object.getOwnPropertyDescriptor(e,a):null;s&&(s.get||s.set)?Object.defineProperty(i,a,s):i[a]=e[a]}return i.default=e,r&&r.set(e,i),i}},{"./chrome/chrome_shim":3,"./common_shim":5,"./firefox/firefox_shim":6,"./safari/safari_shim":9,"./utils":10,sdp:11}],3:[function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.fixNegotiationNeeded=function(e,t){n.wrapPeerConnectionEvent(e,"negotiationneeded",function(e){var r=e.target;if(!(t.version<72||r.getConfiguration&&"plan-b"===r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e})},r.shimAddTrackRemoveTrack=function(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return c(e);var r=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){var e=this,t=r.apply(this);return this._reverseStreams=this._reverseStreams||{},t.map(function(t){return e._reverseStreams[t.id]})};var n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){var r=this;if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(function(e){if(r.getSenders().find(function(t){return t.track===e}))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[t.id]){var i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};var i=e.RTCPeerConnection.prototype.removeStream;function o(e,t){var r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(function(t){var n=e._reverseStreams[t],i=e._streams[n.id];r=r.replace(new RegExp(i.id,"g"),n.id)}),new RTCSessionDescription({type:t.type,sdp:r})}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]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,r){var n=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");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};var o=this._streams[r.id];if(o)o.addTrack(t),Promise.resolve().then(function(){n.dispatchEvent(new Event("negotiationneeded"))});else{var a=new e.MediaStream([t]);this._streams[r.id]=a,this._reverseStreams[a.id]=r,this.addStream(a)}return this.getSenders().find(function(e){return e.track===t})},["createOffer","createAnswer"].forEach(function(t){var r=e.RTCPeerConnection.prototype[t],n=a({},t,function(){var e=this,t=arguments;return arguments.length&&"function"==typeof arguments[0]?r.apply(this,[function(r){var n=o(e,r);t[0].apply(null,[n])},function(e){t[1]&&t[1].apply(null,e)},arguments[2]]):r.apply(this,arguments).then(function(t){return o(e,t)})});e.RTCPeerConnection.prototype[t]=n[t]});var s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=(e=this,r=(t=arguments[0]).sdp,Object.keys(e._reverseStreams||[]).forEach(function(t){var n=e._reverseStreams[t],i=e._streams[n.id];r=r.replace(new RegExp(n.id,"g"),i.id)}),new RTCSessionDescription({type:t.type,sdp:r})),s.apply(this,arguments)):s.apply(this,arguments);var e,t,r};var d=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get:function(){var e=d.get.apply(this);return""===e.type?e:o(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){var t,r=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||{},Object.keys(this._streams).forEach(function(n){r._streams[n].getTracks().find(function(t){return e.track===t})&&(t=r._streams[n])}),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}},r.shimAddTrackRemoveTrackWithNative=c,r.shimGetSendersWithDtmf=function(e){if("object"===s(e)&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){var t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};var r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){var i=r.apply(this,arguments);return i||(i=t(this,e),this._senders.push(i)),i};var n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);var t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}var i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){var r=this;this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach(function(e){r._senders.push(t(r,e))})};var o=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){var t=this;this._senders=this._senders||[],o.apply(this,[e]),e.getTracks().forEach(function(e){var r=t._senders.find(function(t){return t.track===e});r&&t._senders.splice(t._senders.indexOf(r),1)})}}else if("object"===s(e)&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){var a=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){var e=this,t=a.apply(this,[]);return t.forEach(function(t){return t._pc=e}),t},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get:function(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}},Object.defineProperty(r,"shimGetUserMedia",{enumerable:!0,get:function(){return i.shimGetUserMedia}}),r.shimMediaStream=function(e){e.MediaStream=e.MediaStream||e.webkitMediaStream},r.shimOnTrack=function(e){if("object"===s(e)&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get:function(){return this._ontrack},set:function(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});var t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){var r=this;return this._ontrackpoly||(this._ontrackpoly=function(t){t.stream.addEventListener("addtrack",function(n){var i;i=e.RTCPeerConnection.prototype.getReceivers?r.getReceivers().find(function(e){return e.track&&e.track.id===n.track.id}):{track:n.track};var o=new Event("track");o.track=n.track,o.receiver=i,o.transceiver={receiver:i},o.streams=[t.stream],r.dispatchEvent(o)}),t.stream.getTracks().forEach(function(n){var i;i=e.RTCPeerConnection.prototype.getReceivers?r.getReceivers().find(function(e){return e.track&&e.track.id===n.id}):{track:n};var o=new Event("track");o.track=n,o.receiver=i,o.transceiver={receiver:i},o.streams=[t.stream],r.dispatchEvent(o)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else n.wrapPeerConnectionEvent(e,"track",function(e){return e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e})},r.shimPeerConnection=function(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection);if(!e.RTCPeerConnection)return;t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){var r=e.RTCPeerConnection.prototype[t],n=a({},t,function(){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)});e.RTCPeerConnection.prototype[t]=n[t]})},r.shimSenderReceiverGetStats=function(e){if(!("object"===s(e)&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){var t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){var e=this,r=t.apply(this,[]);return r.forEach(function(t){return t._pc=e}),r});var r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){var e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){var e=this;return this._pc.getStats().then(function(t){return n.filterStats(t,e.track,!0)})}}if(!("getStats"in e.RTCRtpReceiver.prototype)){var i=e.RTCPeerConnection.prototype.getReceivers;i&&(e.RTCPeerConnection.prototype.getReceivers=function(){var e=this,t=i.apply(this,[]);return t.forEach(function(t){return t._pc=e}),t}),n.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 n.filterStats(t,e.track,!1)})}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;var o=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){var t,r,n,i=arguments[0];return this.getSenders().forEach(function(e){e.track===i&&(t?n=!0:t=e)}),this.getReceivers().forEach(function(e){return e.track===i&&(r?n=!0:r=e),e.track===i}),n||t&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return o.apply(this,arguments)}};var n=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=s(e)&&"function"!=typeof e)return{default:e};var r=o(t);if(r&&r.has(e))return r.get(e);var n={__proto__:null},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var a in e)if("default"!==a&&{}.hasOwnProperty.call(e,a)){var c=i?Object.getOwnPropertyDescriptor(e,a):null;c&&(c.get||c.set)?Object.defineProperty(n,a,c):n[a]=e[a]}return n.default=e,r&&r.set(e,n),n}(e("../utils.js")),i=e("./getusermedia");function o(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(o=function(e){return e?r:t})(e)}function a(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=s(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t);if("object"!=s(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==s(t)?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function s(e){return s="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},s(e)}function c(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){var e=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(function(t){return e._shimmedLocalStreams[t][0]})};var t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){if(!r)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var n=t.apply(this,arguments);return this._shimmedLocalStreams[r.id]?-1===this._shimmedLocalStreams[r.id].indexOf(n)&&this._shimmedLocalStreams[r.id].push(n):this._shimmedLocalStreams[r.id]=[r,n],n};var r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){var t=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(function(e){if(t.getSenders().find(function(t){return t.track===e}))throw new DOMException("Track already exists.","InvalidAccessError")});var n=this.getSenders();r.apply(this,arguments);var i=this.getSenders().filter(function(e){return-1===n.indexOf(e)});this._shimmedLocalStreams[e.id]=[e].concat(i)};var n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.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(r){var n=t._shimmedLocalStreams[r].indexOf(e);-1!==n&&t._shimmedLocalStreams[r].splice(n,1),1===t._shimmedLocalStreams[r].length&&delete t._shimmedLocalStreams[r]}),i.apply(this,arguments)}}},{"../utils.js":10,"./getusermedia":4}],4:[function(e,t,r){function n(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(n=function(e){return e?r:t})(e)}function i(e){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i(e)}Object.defineProperty(r,"__esModule",{value:!0}),r.shimGetUserMedia=function(e,t){var r=e&&e.navigator;if(!r.mediaDevices)return;var n=function(e){if("object"!==i(e)||e.mandatory||e.optional)return e;var t={};return Object.keys(e).forEach(function(r){if("require"!==r&&"advanced"!==r&&"mediaSource"!==r){var n="object"===i(e[r])?e[r]:{ideal:e[r]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);var o=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];var a={};"number"==typeof n.ideal?(a[o("min",r)]=n.ideal,t.optional.push(a),(a={})[o("max",r)]=n.ideal,t.optional.push(a)):(a[o("",r)]=n.ideal,t.optional.push(a))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[o("",r)]=n.exact):["min","max"].forEach(function(e){void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[o(e,r)]=n[e])})}}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},a=function(e,a){if(t.version>=61)return a(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"===i(e.audio)){var s=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])};s((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),s(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"===i(e.video)){var c=e.video.facingMode;c=c&&("object"===i(c)?c:{ideal:c});var d,u=t.version<66;if(c&&("user"===c.exact||"environment"===c.exact||"user"===c.ideal||"environment"===c.ideal)&&(!r.mediaDevices.getSupportedConstraints||!r.mediaDevices.getSupportedConstraints().facingMode||u))if(delete e.video.facingMode,"environment"===c.exact||"environment"===c.ideal?d=["back","rear"]:"user"!==c.exact&&"user"!==c.ideal||(d=["front"]),d)return r.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&&t.length&&d.includes("back")&&(r=t[t.length-1]),r&&(e.video.deviceId=c.exact?{exact:r.deviceId}:{ideal:r.deviceId}),e.video=n(e.video),o("chrome: "+JSON.stringify(e)),a(e)});e.video=n(e.video)}return o("chrome: "+JSON.stringify(e)),a(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString:function(){return this.name+(this.message&&": ")+this.message}}};if(r.getUserMedia=function(e,t,n){a(e,function(e){r.webkitGetUserMedia(e,t,function(e){n&&n(s(e))})})}.bind(r),r.mediaDevices.getUserMedia){var c=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(e){return a(e,function(e){return c(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 o=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=i(e)&&"function"!=typeof e)return{default:e};var r=n(t);if(r&&r.has(e))return r.get(e);var o={__proto__:null},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&{}.hasOwnProperty.call(e,s)){var c=a?Object.getOwnPropertyDescriptor(e,s):null;c&&(c.get||c.set)?Object.defineProperty(o,s,c):o[s]=e[s]}return o.default=e,r&&r.set(e,o),o}(e("../utils.js")).log},{"../utils.js":10}],5:[function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.removeExtmapAllowMixed=function(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t._safariVersion>=13.1)return;var r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){var n=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:n}):t.sdp=n}return r.apply(this,arguments)}},r.shimAddIceCandidateNullOrEmpty=function(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;var r=e.RTCPeerConnection.prototype.addIceCandidate;if(!r||0===r.length)return;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():r.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())}},r.shimConnectionState=function(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;var t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get:function(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get:function(){return this._onconnectionstatechange||null},set:function(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(function(e){var r=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=function(e){var t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;var r=new Event("connectionstatechange",e);t.dispatchEvent(r)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}})},r.shimMaxMessageSize=function(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get:function(){return void 0===this._sctp?null:this._sctp}});var r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){var e,n;(this._sctp=null,"chrome"===t.browser&&t.version>=76)&&("plan-b"===this.getConfiguration().sdpSemantics&&Object.defineProperty(this,"sctp",{get:function(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0}));if(function(e){if(!e||!e.sdp)return!1;var t=i.default.splitSections(e.sdp);return t.shift(),t.some(function(e){var t=i.default.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")})}(arguments[0])){var o,a=function(e){var t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;var r=parseInt(t[1],10);return r!=r?-1:r}(arguments[0]),s=(e=a,n=65536,"firefox"===t.browser&&(n=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),n),c=function(e,r){var n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);var o=i.default.matchPrefix(e.sdp,"a=max-message-size:");return o.length>0?n=parseInt(o[0].substring(19),10):"firefox"===t.browser&&-1!==r&&(n=2147483637),n}(arguments[0],a);o=0===s&&0===c?Number.POSITIVE_INFINITY:0===s||0===c?Math.max(s,c):Math.min(s,c);var d={};Object.defineProperty(d,"maxMessageSize",{get:function(){return o}}),this._sctp=d}return r.apply(this,arguments)}},r.shimParameterlessSetLocalDescription=function(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;var r=e.RTCPeerConnection.prototype.setLocalDescription;if(!r||0===r.length)return;e.RTCPeerConnection.prototype.setLocalDescription=function(){var e=this,t=arguments[0]||{};if("object"!==s(t)||t.type&&t.sdp)return r.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?r.apply(this,[t]):("offer"===t.type?this.createOffer:this.createAnswer).apply(this).then(function(t){return r.apply(e,[t])})}},r.shimRTCIceCandidate=function(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;var t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"===s(e)&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){var r=new t(e),n=i.default.parseCandidate(e.candidate);for(var o in n)o in r||Object.defineProperty(r,o,{value:n[o]});return r.toJSON=function(){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.sdpMLineIndex,usernameFragment:r.usernameFragment}},r}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,o.wrapPeerConnectionEvent(e,"icecandidate",function(t){return t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t})},r.shimRTCIceCandidateRelayProtocol=function(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype)return;o.wrapPeerConnectionEvent(e,"icecandidate",function(e){if(e.candidate){var t=i.default.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})},r.shimSendThrowTypeError=function(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){var r=e.send;e.send=function(){var n=arguments[0],i=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&i>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return r.apply(e,arguments)}}var r=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){var e=r.apply(this,arguments);return t(e,this),e},o.wrapPeerConnectionEvent(e,"datachannel",function(e){return t(e.channel,e.target),e})};var n,i=(n=e("sdp"))&&n.__esModule?n:{default:n},o=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=s(e)&&"function"!=typeof e)return{default:e};var r=a(t);if(r&&r.has(e))return r.get(e);var n={__proto__:null},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var o in e)if("default"!==o&&{}.hasOwnProperty.call(e,o)){var c=i?Object.getOwnPropertyDescriptor(e,o):null;c&&(c.get||c.set)?Object.defineProperty(n,o,c):n[o]=e[o]}return n.default=e,r&&r.set(e,n),n}(e("./utils"));function a(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(a=function(e){return e?r:t})(e)}function s(e){return s="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},s(e)}},{"./utils":10,sdp:11}],6:[function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.shimAddTransceiver=function(e){if("object"!==c(e)||!e.RTCPeerConnection)return;var t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];var e,r=arguments[1]&&arguments[1].sendEncodings;void 0===r&&(r=[]);var n=(r=function(e){if(Array.isArray(e))return s(e)}(e=r)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){if(e){if("string"==typeof e)return s(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?s(e,t):void 0}}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()).length>0;n&&r.forEach(function(e){if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});var i=t.apply(this,arguments);if(n){var o=i.sender,a=o.getParameters();(!("encodings"in a)||1===a.encodings.length&&0===Object.keys(a.encodings[0]).length)&&(a.encodings=r,o.sendEncodings=r,this.setParametersPromises.push(o.setParameters(a).then(function(){delete o.sendEncodings}).catch(function(){delete o.sendEncodings})))}return i})},r.shimCreateAnswer=function(e){if("object"!==c(e)||!e.RTCPeerConnection)return;var t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){var e=arguments,r=this;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return t.apply(r,e)}).finally(function(){r.setParametersPromises=[]}):t.apply(this,arguments)}},r.shimCreateOffer=function(e){if("object"!==c(e)||!e.RTCPeerConnection)return;var t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){var e=arguments,r=this;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return t.apply(r,e)}).finally(function(){r.setParametersPromises=[]}):t.apply(this,arguments)}},Object.defineProperty(r,"shimGetDisplayMedia",{enumerable:!0,get:function(){return o.shimGetDisplayMedia}}),r.shimGetParameters=function(e){if("object"!==c(e)||!e.RTCRtpSender)return;var t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){var e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})},Object.defineProperty(r,"shimGetUserMedia",{enumerable:!0,get:function(){return i.shimGetUserMedia}}),r.shimOnTrack=function(e){"object"===c(e)&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})},r.shimPeerConnection=function(e,t){if("object"!==c(e)||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection);t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){var r,n,i,o=e.RTCPeerConnection.prototype[t],a=(r={},i=function(){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),o.apply(this,arguments)},(n=function(e){var t=function(e,t){if("object"!=c(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t);if("object"!=c(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==c(t)?t:t+""}(n=t))in r?Object.defineProperty(r,n,{value:i,enumerable:!0,configurable:!0,writable:!0}):r[n]=i,r);e.RTCPeerConnection.prototype[t]=a[t]});var r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){var e=Array.prototype.slice.call(arguments),i=e[0],o=e[1],a=e[2];return n.apply(this,[i||null]).then(function(e){if(t.version<53&&!o)try{e.forEach(function(e){e.type=r[e.type]||e.type})}catch(t){if("TypeError"!==t.name)throw t;e.forEach(function(t,n){e.set(n,Object.assign({},t,{type:r[t.type]||t.type}))})}return e}).then(o,a)}},r.shimRTCDataChannel=function(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)},r.shimReceiverGetStats=function(e){if("object"!==c(e)||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;var t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){var e=this,r=t.apply(this,[]);return r.forEach(function(t){return t._pc=e}),r});n.wrapPeerConnectionEvent(e,"track",function(e){return e.receiver._pc=e.srcElement,e}),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}},r.shimRemoveStream=function(e){if(!e.RTCPeerConnection||"removeStream"in e.RTCPeerConnection.prototype)return;e.RTCPeerConnection.prototype.removeStream=function(e){var t=this;n.deprecated("removeStream","removeTrack"),this.getSenders().forEach(function(r){r.track&&e.getTracks().includes(r.track)&&t.removeTrack(r)})}},r.shimSenderGetStats=function(e){if("object"!==c(e)||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;var t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){var e=this,r=t.apply(this,[]);return r.forEach(function(t){return t._pc=e}),r});var r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){var e=r.apply(this,arguments);return e._pc=this,e});e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}};var n=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=c(e)&&"function"!=typeof e)return{default:e};var r=a(t);if(r&&r.has(e))return r.get(e);var n={__proto__:null},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var o in e)if("default"!==o&&{}.hasOwnProperty.call(e,o)){var s=i?Object.getOwnPropertyDescriptor(e,o):null;s&&(s.get||s.set)?Object.defineProperty(n,o,s):n[o]=e[o]}return n.default=e,r&&r.set(e,n),n}(e("../utils")),i=e("./getusermedia"),o=e("./getdisplaymedia");function a(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(a=function(e){return e?r:t})(e)}function s(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function c(e){return c="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},c(e)}},{"../utils":10,"./getdisplaymedia":7,"./getusermedia":8}],7:[function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.shimGetDisplayMedia=function(e,t){if(e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices)return;if(!e.navigator.mediaDevices)return;e.navigator.mediaDevices.getDisplayMedia=function(r){if(!r||!r.video){var n=new DOMException("getDisplayMedia without video constraints is undefined");return n.name="NotFoundError",n.code=8,Promise.reject(n)}return!0===r.video?r.video={mediaSource:t}:r.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(r)}}},{}],8:[function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.shimGetUserMedia=function(e,t){var r=e&&e.navigator,i=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,i){n.deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(e).then(t,i)},!(t.version>55&&"autoGainControl"in r.mediaDevices.getSupportedConstraints())){var a=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])},s=r.mediaDevices.getUserMedia.bind(r.mediaDevices);if(r.mediaDevices.getUserMedia=function(e){return"object"===o(e)&&"object"===o(e.audio)&&(e=JSON.parse(JSON.stringify(e)),a(e.audio,"autoGainControl","mozAutoGainControl"),a(e.audio,"noiseSuppression","mozNoiseSuppression")),s(e)},i&&i.prototype.getSettings){var c=i.prototype.getSettings;i.prototype.getSettings=function(){var e=c.apply(this,arguments);return a(e,"mozAutoGainControl","autoGainControl"),a(e,"mozNoiseSuppression","noiseSuppression"),e}}if(i&&i.prototype.applyConstraints){var d=i.prototype.applyConstraints;i.prototype.applyConstraints=function(e){return"audio"===this.kind&&"object"===o(e)&&(e=JSON.parse(JSON.stringify(e)),a(e,"autoGainControl","mozAutoGainControl"),a(e,"noiseSuppression","mozNoiseSuppression")),d.apply(this,[e])}}}};var n=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=o(e)&&"function"!=typeof e)return{default:e};var r=i(t);if(r&&r.has(e))return r.get(e);var n={__proto__:null},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&{}.hasOwnProperty.call(e,s)){var c=a?Object.getOwnPropertyDescriptor(e,s):null;c&&(c.get||c.set)?Object.defineProperty(n,s,c):n[s]=e[s]}return n.default=e,r&&r.set(e,n),n}(e("../utils"));function i(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(i=function(e){return e?r:t})(e)}function o(e){return o="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)}},{"../utils":10}],9:[function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.shimAudioContext=function(e){if("object"!==o(e)||e.AudioContext)return;e.AudioContext=e.webkitAudioContext},r.shimCallbacksAPI=function(e){if("object"!==o(e)||!e.RTCPeerConnection)return;var t=e.RTCPeerConnection.prototype,r=t.createOffer,n=t.createAnswer,i=t.setLocalDescription,a=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(e,t){var n=arguments.length>=2?arguments[2]:arguments[0],i=r.apply(this,[n]);return t?(i.then(e,t),Promise.resolve()):i},t.createAnswer=function(e,t){var r=arguments.length>=2?arguments[2]:arguments[0],i=n.apply(this,[r]);return t?(i.then(e,t),Promise.resolve()):i};var c=function(e,t,r){var n=i.apply(this,[e]);return r?(n.then(t,r),Promise.resolve()):n};t.setLocalDescription=c,c=function(e,t,r){var n=a.apply(this,[e]);return r?(n.then(t,r),Promise.resolve()):n},t.setRemoteDescription=c,c=function(e,t,r){var n=s.apply(this,[e]);return r?(n.then(t,r),Promise.resolve()):n},t.addIceCandidate=c},r.shimConstraints=a,r.shimCreateOfferLegacy=function(e){var t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);var r=this.getTransceivers().find(function(e){return"audio"===e.receiver.track.kind});!1===e.offerToReceiveAudio&&r?"sendrecv"===r.direction?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":"recvonly"===r.direction&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):!0!==e.offerToReceiveAudio||r||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);var 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"})}return t.apply(this,arguments)}},r.shimGetUserMedia=function(e){var t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){var r=t.mediaDevices,n=r.getUserMedia.bind(r);t.mediaDevices.getUserMedia=function(e){return n(a(e))}}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,r,n){t.mediaDevices.getUserMedia(e).then(r,n)}.bind(t))},r.shimLocalStreamsAPI=function(e){if("object"!==o(e)||!e.RTCPeerConnection)return;"getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams});if(!("addStream"in e.RTCPeerConnection.prototype)){var t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){var r=this;this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(function(n){return t.call(r,n,e)}),e.getVideoTracks().forEach(function(n){return t.call(r,n,e)})},e.RTCPeerConnection.prototype.addTrack=function(e){for(var r=this,n=arguments.length,i=new Array(n>1?n-1:0),o=1;o<n;o++)i[o-1]=arguments[o];return i&&i.forEach(function(e){r._localStreams?r._localStreams.includes(e)||r._localStreams.push(e):r._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 r=this._localStreams.indexOf(e);if(-1!==r){this._localStreams.splice(r,1);var n=e.getTracks();this.getSenders().forEach(function(e){n.includes(e.track)&&t.removeTrack(e)})}})},r.shimRTCIceServerUrls=function(e){if(!e.RTCPeerConnection)return;var t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,r){if(e&&e.iceServers){for(var i=[],o=0;o<e.iceServers.length;o++){var a=e.iceServers[o];void 0===a.urls&&a.url?(n.deprecated("RTCIceServer.url","RTCIceServer.urls"),(a=JSON.parse(JSON.stringify(a))).urls=a.url,delete a.url,i.push(a)):i.push(e.iceServers[o])}e.iceServers=i}return new t(e,r)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:function(){return t.generateCertificate}})},r.shimRemoteStreamsAPI=function(e){if("object"!==o(e)||!e.RTCPeerConnection)return;"getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]});if(!("onaddstream"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get:function(){return this._onaddstream},set:function(e){var t=this;this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=function(e){e.streams.forEach(function(e){if(t._remoteStreams||(t._remoteStreams=[]),!t._remoteStreams.includes(e)){t._remoteStreams.push(e);var r=new Event("addstream");r.stream=e,t.dispatchEvent(r)}})})}});var t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){var e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach(function(t){if(e._remoteStreams||(e._remoteStreams=[]),!(e._remoteStreams.indexOf(t)>=0)){e._remoteStreams.push(t);var r=new Event("addstream");r.stream=t,e.dispatchEvent(r)}})}),t.apply(e,arguments)}}},r.shimTrackEventTransceiver=function(e){"object"===o(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}}})};var n=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=o(e)&&"function"!=typeof e)return{default:e};var r=i(t);if(r&&r.has(e))return r.get(e);var n={__proto__:null},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&{}.hasOwnProperty.call(e,s)){var c=a?Object.getOwnPropertyDescriptor(e,s):null;c&&(c.get||c.set)?Object.defineProperty(n,s,c):n[s]=e[s]}return n.default=e,r&&r.set(e,n),n}(e("../utils"));function i(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(i=function(e){return e?r:t})(e)}function o(e){return o="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)}function a(e){return e&&void 0!==e.video?Object.assign({},e,{video:n.compactObject(e.video)}):e}},{"../utils":10}],10:[function(e,t,r){function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(r,"__esModule",{value:!0}),r.compactObject=function e(t){if(!s(t))return t;return Object.keys(t).reduce(function(r,i){var o,a,c,d=s(t[i]),u=d?e(t[i]):t[i],l=d&&!Object.keys(u).length;return void 0===u||l?r:Object.assign(r,(o={},c=u,(a=function(e){var t=function(e,t){if("object"!=n(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,t);if("object"!=n(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==n(t)?t:t+""}(a=i))in o?Object.defineProperty(o,a,{value:c,enumerable:!0,configurable:!0,writable:!0}):o[a]=c,o))},{})},r.deprecated=function(e,t){if(!o)return;console.warn(e+" is deprecated, please use "+t+" instead.")},r.detectBrowser=function(e){var t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;var r=e.navigator;if(r.userAgentData&&r.userAgentData.brands){var n=r.userAgentData.brands.find(function(e){return"Chromium"===e.brand});if(n)return{browser:"chrome",version:parseInt(n.version,10)}}if(r.mozGetUserMedia)t.browser="firefox",t.version=parseInt(a(r.userAgent,/Firefox\/(\d+)\./,1));else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=parseInt(a(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else{if(!e.RTCPeerConnection||!r.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=parseInt(a(r.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=a(r.userAgent,/Version\/(\d+(\.?\d+))/,1)}return t},r.disableLog=function(e){if("boolean"!=typeof e)return new Error("Argument type: "+n(e)+". Please use a boolean.");return i=e,e?"adapter.js logging disabled":"adapter.js logging enabled"},r.disableWarnings=function(e){if("boolean"!=typeof e)return new Error("Argument type: "+n(e)+". Please use a boolean.");return o=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled")},r.extractVersion=a,r.filterStats=function(e,t,r){var n=r?"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(r){r.type===n&&r.trackId===t.id&&c(e,r,i)})}),i},r.log=function(){if("object"===("undefined"==typeof window?"undefined":n(window))){if(i)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}},r.walkStats=c,r.wrapPeerConnectionEvent=function(e,t,r){if(!e.RTCPeerConnection)return;var n=e.RTCPeerConnection.prototype,i=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return i.apply(this,arguments);var o=function(e){var t=r(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,o),i.apply(this,[e,o])};var o=n.removeEventListener;n.removeEventListener=function(e,r){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(r))return o.apply(this,arguments);var n=this._eventMap[t].get(r);return this._eventMap[t].delete(r),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,o.apply(this,[e,n])},Object.defineProperty(n,"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})};var i=!0,o=!0;function a(e,t,r){var n=e.match(t);return n&&n.length>=r&&parseFloat(n[r],10)}function s(e){return"[object Object]"===Object.prototype.toString.call(e)}function c(e,t,r){t&&!r.has(t.id)&&(r.set(t.id,t),Object.keys(t).forEach(function(n){n.endsWith("Id")?c(e,e.get(t[n]),r):n.endsWith("Ids")&&t[n].forEach(function(t){c(e,e.get(t),r)})}))}},{}],11:[function(e,t,r){var n="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).substring(2,12)}};i.localCName=i.generateIdentifier(),i.splitLines=function(e){return e.trim().split("\n").map(function(e){return e.trim()})},i.splitSections=function(e){return e.split("\nm=").map(function(e,t){return(t>0?"m="+e:e).trim()+"\r\n"})},i.getDescription=function(e){var t=i.splitSections(e);return t&&t[0]},i.getMediaSections=function(e){var t=i.splitSections(e);return t.shift(),t},i.matchPrefix=function(e,t){return i.splitLines(e).filter(function(e){return 0===e.indexOf(t)})},i.parseCandidate=function(e){for(var t=void 0,r={foundation:(t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):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]},n=8;n<t.length;n+=2)switch(t[n]){case"raddr":r.relatedAddress=t[n+1];break;case"rport":r.relatedPort=parseInt(t[n+1],10);break;case"tcptype":r.tcpType=t[n+1];break;case"ufrag":r.ufrag=t[n+1],r.usernameFragment=t[n+1];break;default:void 0===r[t[n]]&&(r[t[n]]=t[n+1])}return r},i.writeCandidate=function(e){var t=[];t.push(e.foundation);var r=e.component;"rtp"===r?t.push(1):"rtcp"===r?t.push(2):t.push(r),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);var n=e.type;return 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.substring(14).split(" ")},i.parseRtpMap=function(e){var t=e.substring(9).split(" "),r={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),r.name=t[0],r.clockRate=parseInt(t[1],10),r.channels=3===t.length?parseInt(t[2],10):1,r.numChannels=r.channels,r},i.writeRtpMap=function(e){var t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);var r=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==r?"/"+r:"")+"\r\n"},i.parseExtmap=function(e){var t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},i.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},i.parseFmtp=function(e){for(var t={},r=void 0,n=e.substring(e.indexOf(" ")+1).split(";"),i=0;i<n.length;i++)t[(r=n[i].trim().split("="))[0].trim()]=r[1];return t},i.writeFmtp=function(e){var t="",r=e.payloadType;if(void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){var n=[];Object.keys(e.parameters).forEach(function(t){void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)}),t+="a=fmtp:"+r+" "+n.join(";")+"\r\n"}return t},i.parseRtcpFb=function(e){var t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},i.writeRtcpFb=function(e){var t="",r=e.payloadType;return void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(function(e){t+="a=rtcp-fb:"+r+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"}),t},i.parseSsrcMedia=function(e){var t=e.indexOf(" "),r={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(r.attribute=e.substring(t+1,n),r.value=e.substring(n+1)):r.attribute=e.substring(t+1),r},i.parseSsrcGroup=function(e){var t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map(function(e){return parseInt(e,10)})}},i.getMid=function(e){var t=i.matchPrefix(e,"a=mid:")[0];if(t)return t.substring(6)},i.parseFingerprint=function(e){var t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[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 r="a=setup:"+t+"\r\n";return e.fingerprints.forEach(function(e){r+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"}),r},i.parseCryptoLine=function(e){var t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},i.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"===n(e.keyParams)?i.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},i.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;var t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[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 r=i.matchPrefix(e+t,"a=ice-ufrag:")[0],n=i.matchPrefix(e+t,"a=ice-pwd:")[0];return r&&n?{usernameFragment:r.substring(12),password:n.substring(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){var t={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},r=i.splitLines(e)[0].split(" ");t.profile=r[2];for(var n=3;n<r.length;n++){var o=r[n],a=i.matchPrefix(e,"a=rtpmap:"+o+" ")[0];if(a){var s=i.parseRtpMap(a),c=i.matchPrefix(e,"a=fmtp:"+o+" ");switch(s.parameters=c.length?i.parseFmtp(c[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())}}}i.matchPrefix(e,"a=extmap:").forEach(function(e){t.headerExtensions.push(i.parseExtmap(e))});var d=i.matchPrefix(e,"a=rtcp-fb:* ").map(i.parseRtcpFb);return t.codecs.forEach(function(e){d.forEach(function(t){e.rtcpFeedback.find(function(e){return e.type===t.type&&e.parameter===t.parameter})||e.rtcpFeedback.push(t)})}),t},i.writeRtpDescription=function(e,t){var r="";r+="m="+e+" ",r+=t.codecs.length>0?"9":"0",r+=" "+(t.profile||"UDP/TLS/RTP/SAVPF")+" ",r+=t.codecs.map(function(e){return void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType}).join(" ")+"\r\n",r+="c=IN IP4 0.0.0.0\r\n",r+="a=rtcp:9 IN IP4 0.0.0.0\r\n",t.codecs.forEach(function(e){r+=i.writeRtpMap(e),r+=i.writeFmtp(e),r+=i.writeRtcpFb(e)});var n=0;return t.codecs.forEach(function(e){e.maxptime>n&&(n=e.maxptime)}),n>0&&(r+="a=maxptime:"+n+"\r\n"),t.headerExtensions&&t.headerExtensions.forEach(function(e){r+=i.writeExtmap(e)}),r},i.parseRtpEncodingParameters=function(e){var t=[],r=i.parseRtpParameters(e),n=-1!==r.fecMechanisms.indexOf("RED"),o=-1!==r.fecMechanisms.indexOf("ULPFEC"),a=i.matchPrefix(e,"a=ssrc:").map(function(e){return i.parseSsrcMedia(e)}).filter(function(e){return"cname"===e.attribute}),s=a.length>0&&a[0].ssrc,c=void 0,d=i.matchPrefix(e,"a=ssrc-group:FID").map(function(e){return e.substring(17).split(" ").map(function(e){return parseInt(e,10)})});d.length>0&&d[0].length>1&&d[0][0]===s&&(c=d[0][1]),r.codecs.forEach(function(e){if("RTX"===e.name.toUpperCase()&&e.parameters.apt){var r={ssrc:s,codecPayloadType:parseInt(e.parameters.apt,10)};s&&c&&(r.rtx={ssrc:c}),t.push(r),n&&((r=JSON.parse(JSON.stringify(r))).fec={ssrc:s,mechanism:o?"red+ulpfec":"red"},t.push(r))}}),0===t.length&&s&&t.push({ssrc:s});var u=i.matchPrefix(e,"b=");return u.length&&(u=0===u[0].indexOf("b=TIAS:")?parseInt(u[0].substring(7),10):0===u[0].indexOf("b=AS:")?1e3*parseInt(u[0].substring(5),10)*.95-16e3:void 0,t.forEach(function(e){e.maxBitrate=u})),t},i.parseRtcpParameters=function(e){var t={},r=i.matchPrefix(e,"a=ssrc:").map(function(e){return i.parseSsrcMedia(e)}).filter(function(e){return"cname"===e.attribute})[0];r&&(t.cname=r.value,t.ssrc=r.ssrc);var n=i.matchPrefix(e,"a=rtcp-rsize");t.reducedSize=n.length>0,t.compound=0===n.length;var o=i.matchPrefix(e,"a=rtcp-mux");return t.mux=o.length>0,t},i.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,r=i.matchPrefix(e,"a=msid:");if(1===r.length)return{stream:(t=r[0].substring(7).split(" "))[0],track:t[1]};var n=i.matchPrefix(e,"a=ssrc:").map(function(e){return i.parseSsrcMedia(e)}).filter(function(e){return"msid"===e.attribute});return n.length>0?{stream:(t=n[0].value.split(" "))[0],track:t[1]}:void 0},i.parseSctpDescription=function(e){var t=i.parseMLine(e),r=i.matchPrefix(e,"a=max-message-size:"),n=void 0;r.length>0&&(n=parseInt(r[0].substring(19),10)),isNaN(n)&&(n=65536);var o=i.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:t.fmt,maxMessageSize:n};var a=i.matchPrefix(e,"a=sctpmap:");if(a.length>0){var s=a[0].substring(10).split(" ");return{port:parseInt(s[0],10),protocol:s[1],maxMessageSize:n}}},i.writeSctpDescription=function(e,t){var r=[];return r="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&r.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),r.join("")},i.generateSessionId=function(){return Math.random().toString().substr(2,22)},i.writeSessionBoilerplate=function(e,t,r){var n=void 0!==t?t:2;return"v=0\r\no="+(r||"thisisadapterortc")+" "+(e||i.generateSessionId())+" "+n+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},i.getDirection=function(e,t){for(var r=i.splitLines(e),n=0;n<r.length;n++)switch(r[n]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[n].substring(2)}return t?i.getDirection(t):"sendrecv"},i.getKind=function(e){return i.splitLines(e)[0].split(" ")[0].substring(2)},i.isRejected=function(e){return"0"===e.split(" ",2)[1]},i.parseMLine=function(e){var t=i.splitLines(e)[0].substring(2).split(" ");return{kind:t[0],port:parseInt(t[1],10),protocol:t[2],fmt:t.slice(3).join(" ")}},i.parseOLine=function(e){var t=i.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:t[0],sessionId:t[1],sessionVersion:parseInt(t[2],10),netType:t[3],addressType:t[4],address:t[5]}},i.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;for(var t=i.splitLines(e),r=0;r<t.length;r++)if(t[r].length<2||"="!==t[r].charAt(1))return!1;return!0},"object"===(void 0===t?"undefined":n(t))&&(t.exports=i)},{}]},{},[1])(1)}),s.sessions=new Map,s.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||s.extension.isInstalled()}return!0};var a={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 r=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...",r(e)}else r(null,t.data.sourceId)}else"janusGetScreenPending"==t.data.type&&(console.log("clearing ",t.data.id),window.clearTimeout(t.data.id))})}};function s(e){if((e=e||{}).success="function"==typeof e.success?e.success:s.noop,e.error="function"==typeof e.error?e.error:s.noop,e.destroyed="function"==typeof e.destroyed?e.destroyed:s.noop,!s.initDone)return e.error("Library not initialized"),{};if(!s.isWebrtcSupported())return e.error("WebRTC not supported by this browser"),{};if(s.log("Library initialized: "+s.initDone),!e.server)return e.error("Invalid server url"),{};let t=!1,r=null,n={},i=null,o=null,a=0,c=e.server;s.isArray(c)?(s.log("Multiple servers provided ("+c.length+"), will use the first that works"),c=null,o=e.server,s.debug(o)):0===c.indexOf("ws")?(t=!0,s.log("Using WebSockets to contact Janus: "+c)):(t=!1,s.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=25e3;void 0!==e.keepAlivePeriod&&null!==e.keepAlivePeriod&&(g=e.keepAlivePeriod),isNaN(g)&&(g=25e3);let v=6e4;function y(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&&(v=e.longPollTimeout),isNaN(v)&&(v=6e4);let b=!1,T=null,S=new Map,C=this,w=0,_=new Map;function R(){if(null==T)return;if(s.debug("Long poll..."),!b)return void s.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)),s.httpAPICall(t,{verb:"GET",withCredentials:p,success:k,timeout:v,error:function(t,r){if(s.error(t+":",r),w++,w>3)return b=!1,void e.error("Lost connection to the server (is it down?)");R()}})}function k(e,n){if(w=0,t||null==T||!0===n||R(),t||!s.isArray(e))if("keepalive"!==e.janus){if("server_info"===e.janus){s.debug("Got info on the Janus instance"),s.debug(e);const t=e.transaction;if(t){const r=_.get(t);r&&r(e),_.delete(t)}return}if("ack"===e.janus){s.debug("Got an ack on session "+T),s.debug(e);const t=e.transaction;if(t){const r=_.get(t);r&&r(e),_.delete(t)}return}if("success"===e.janus){s.debug("Got a success on session "+T),s.debug(e);const t=e.transaction;if(t){const r=_.get(t);r&&r(e),_.delete(t)}return}if("trickle"===e.janus){const t=e.sender;if(!t)return void s.warn("Missing sender...");const r=S.get(t);if(!r)return void s.debug("This handle is not attached to this session");let n=e.candidate;s.debug("Got a trickled candidate on session "+T),s.debug(n);let i=r.webrtcStuff;i.pc&&i.remoteSdp?(s.debug("Adding remote candidate:",n),n&&!0!==n.completed?i.pc.addIceCandidate(n):i.pc.addIceCandidate(s.endOfCandidates)):(s.debug("We didn't do setRemoteDescription (trickle got here before the offer?), caching candidate"),i.candidates||(i.candidates=[]),i.candidates.push(n),s.debug(i.candidates))}else{if("webrtcup"===e.janus){s.debug("Got a webrtcup event on session "+T),s.debug(e);const t=e.sender;if(!t)return void s.warn("Missing sender...");const r=S.get(t);return r?void r.webrtcState(!0):void s.debug("This handle is not attached to this session")}if("hangup"===e.janus){s.debug("Got a hangup event on session "+T),s.debug(e);const t=e.sender;if(!t)return void s.warn("Missing sender...");const r=S.get(t);if(!r)return void s.debug("This handle is not attached to this session");r.webrtcState(!1,e.reason),r.hangup()}else if("detached"===e.janus){s.debug("Got a detached event on session "+T),s.debug(e);const t=e.sender;if(!t)return void s.warn("Missing sender...");const r=S.get(t);if(!r)return;r.ondetached(),r.detach()}else if("media"===e.janus){s.debug("Got a media event on session "+T),s.debug(e);const t=e.sender;if(!t)return void s.warn("Missing sender...");const r=S.get(t);if(!r)return void s.debug("This handle is not attached to this session");r.mediaState(e.type,e.receiving,e.mid)}else if("slowlink"===e.janus){s.debug("Got a slowlink event on session "+T),s.debug(e);const t=e.sender;if(!t)return void s.warn("Missing sender...");const r=S.get(t);if(!r)return void s.debug("This handle is not attached to this session");r.slowLink(e.uplink,e.lost,e.mid)}else{if("error"===e.janus){s.error("Ooops: "+e.error.code+" "+e.error.reason),s.debug(e);let t=e.transaction;if(t){let r=_.get(t);r&&r(e),_.delete(t)}return}if("event"===e.janus){s.debug("Got a plugin event on session "+T),s.debug(e);const t=e.sender;if(!t)return void s.warn("Missing sender...");let r=e.plugindata;if(!r)return void s.warn("Missing plugindata...");s.debug(" -- Event is coming from "+t+" ("+r.plugin+")");let n=r.data;s.debug(n);const i=S.get(t);if(!i)return void s.warn("This handle is not attached to this session");let o=e.jsep;o&&(s.debug("Handling SDP as well..."),s.debug(o));let a=i.onmessage;a?(s.debug("Notifying application..."),a(n,o)):s.debug("No provided notification callback")}else{if("timeout"===e.janus)return s.error("Timeout on session "+T),s.debug(e),void(t&&r.close(3504,"Gateway timeout"));s.warn("Unknown message/event '"+e.janus+"' on session "+T),s.debug(e)}}}}else s.vdebug("Got a keepalive on session "+T);else for(let t=0;t<e.length;t++)k(e[t],!0)}function P(){if(!c||!t||!b)return;i=setTimeout(P,g);let e={janus:"keepalive",session_id:T,transaction:s.randomString(12)};h&&(e.token=h),m&&(e.apisecret=m),r.send(JSON.stringify(e))}function I(d){let u=s.randomString(12),l={janus:"create",transaction:u};if(d.reconnect&&(b=!1,l.janus="claim",l.session_id=T,r&&(r.onopen=null,r.onerror=null,r.onclose=null,i&&(clearTimeout(i),i=null))),h&&(l.token=h),m&&(l.apisecret=m),!c&&s.isArray(o)&&(c=o[a],0===c.indexOf("ws")?(t=!0,s.log("Server #"+(a+1)+": trying WebSockets to contact Janus ("+c+")")):(t=!1,s.log("Server #"+(a+1)+": trying REST API to contact Janus ("+c+")"))),t){r=s.newWebSocket(c,"janus-protocol"),n={error:function(){if(s.error("Error connecting to the Janus WebSockets server... "+c),s.isArray(o)&&!d.reconnect)return a++,a===o.length?void d.error("Error connecting to any of the provided Janus servers: Is the server down?"):(c=null,void setTimeout(function(){I(d)},200));d.error("Error connecting to the Janus WebSockets server: Is the server down?")},open:function(){_.set(u,function(e){if(s.debug(e),"success"!==e.janus)return s.error("Ooops: "+e.error.code+" "+e.error.reason),void d.error(e.error.reason);i=setTimeout(P,g),b=!0,T=e.session_id?e.session_id:e.data.id,d.reconnect?s.log("Claimed session: "+T):s.log("Created session: "+T),s.sessions.set(T,C),d.success()}),r.send(JSON.stringify(l))},message:function(e){k(JSON.parse(e.data))},close:function(){c&&b&&(b=!1,e.error("Lost connection to the server (is it down?)"))}};for(let e in n)r.addEventListener(e,n[e])}else s.httpAPICall(c,{verb:"POST",withCredentials:p,body:l,success:function(e){if(s.debug(e),"success"!==e.janus)return s.error("Ooops: "+e.error.code+" "+e.error.reason),void d.error(e.error.reason);b=!0,T=e.session_id?e.session_id:e.data.id,d.reconnect?s.log("Claimed session: "+T):s.log("Created session: "+T),s.sessions.set(T,C),R(),d.success()},error:function(e,t){if(s.error(e+":",t),s.isArray(o)&&!d.reconnect)return a++,a===o.length?void d.error("Error connecting to any of the provided Janus servers: Is the server down?"):(c=null,void setTimeout(function(){I(d)},200));""===t?d.error(e+": Is the server down?"):t&&t.error?d.error(e+": "+t.error.message):d.error(e+": "+t)}})}function E(e,n){if((n=n||{}).success="function"==typeof n.success?n.success:s.noop,n.error="function"==typeof n.error?n.error:s.noop,!b)return s.warn("Is the server down? (connected=false)"),void n.error("Is the server down? (connected=false)");let i=S.get(e);if(!i||!i.webrtcStuff)return s.warn("Invalid handle"),void n.error("Invalid handle");let o=n.message,a=n.jsep,d=s.randomString(12),u={janus:"message",body:o,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 r=t.pc.getTransceivers();if(r&&r.length>0)for(let t in r){let n=r[t];if(n&&n.sender&&n.sender.track&&"video"===n.sender.track.kind){let r=n.sender.getParameters();r&&r.encodings&&1===r.encodings.length&&r.encodings[0]&&r.encodings[0].scalabilityMode&&(e||(e=[]),e.push({mindex:parseInt(t),mid:n.mid,svc:r.encodings[0].scalabilityMode}))}}}e&&(u.jsep.svc=e)}if(s.debug("Sending message to plugin (handle="+e+"):"),s.debug(u),t)return u.session_id=T,u.handle_id=e,_.set(d,function(e){if(s.debug("Message sent!"),s.debug(e),"success"===e.janus){let t=e.plugindata;if(!t)return s.warn("Request succeeded, but missing plugindata..."),void n.success();s.log("Synchronous transaction successful ("+t.plugin+")");let r=t.data;return s.debug(r),void n.success(r)}"ack"===e.janus?n.success():e.error?(s.error("Ooops: "+e.error.code+" "+e.error.reason),n.error(e.error.code+" "+e.error.reason)):(s.error("Unknown error"),n.error("Unknown error"))}),void r.send(JSON.stringify(u));s.httpAPICall(c+"/"+T+"/"+e,{verb:"POST",withCredentials:p,body:u,success:function(e){if(s.debug("Message sent!"),s.debug(e),"success"===e.janus){let t=e.plugindata;if(!t)return s.warn("Request succeeded, but missing plugindata..."),void n.success();s.log("Synchronous transaction successful ("+t.plugin+")");let r=t.data;return s.debug(r),void n.success(r)}"ack"===e.janus?n.success():e.error?(s.error("Ooops: "+e.error.code+" "+e.error.reason),n.error(e.error.code+" "+e.error.reason)):(s.error("Unknown error"),n.error("Unknown error"))},error:function(e,t){s.error(e+":",t),n.error(e+": "+t)}})}function A(e,n){if(!b)return void s.warn("Is the server down? (connected=false)");let i=S.get(e);if(!i||!i.webrtcStuff)return void s.warn("Invalid handle");let o={janus:"trickle",candidate:n,transaction:s.randomString(12)};if(i.token&&(o.token=i.token),m&&(o.apisecret=m),s.vdebug("Sending trickle candidate (handle="+e+"):"),s.vdebug(o),t)return o.session_id=T,o.handle_id=e,void r.send(JSON.stringify(o));s.httpAPICall(c+"/"+T+"/"+e,{verb:"POST",withCredentials:p,body:o,success:function(e){s.vdebug("Candidate sent!"),s.vdebug(e),"ack"===e.janus||s.error("Ooops: "+e.error.code+" "+e.error.reason)},error:function(e,t){s.error(e+":",t)}})}function O(e,t,r,n,i){let o=S.get(e);if(!o||!o.webrtcStuff)return void s.warn("Invalid handle");let a=o.webrtcStuff;if(!a.pc)return void s.warn("Invalid PeerConnection");let c=function(e){s.log("Received state change on data channel:",e);let t=e.target.label,r=e.target.protocol,n=a.dataChannel[t]?a.dataChannel[t].readyState:"null";if(s.log("State change on <"+t+"> data channel: "+n),"open"===n){if(a.dataChannel[t].pending&&a.dataChannel[t].pending.length>0){s.log("Sending pending messages on <"+t+">:",a.dataChannel[t].pending.length);for(let e of a.dataChannel[t].pending)s.log("Sending data on data channel <"+t+">"),s.debug(e),a.dataChannel[t].send(e);a.dataChannel[t].pending=[]}o.ondataopen(t,r)}};if(n)a.dataChannel[t]=n;else{let e=a.dataChannelOptions;r&&(e.protocol=r),a.dataChannel[t]=a.pc.createDataChannel(t,e)}a.dataChannel[t].onmessage=function(e){s.log("Received message on data channel:",e);let t=e.target.label;o.ondata(e.data,t)},a.dataChannel[t].onopen=c,a.dataChannel[t].onclose=c,a.dataChannel[t].onerror=function(e){s.error("Got error on data channel:",e)},a.dataChannel[t].pending=[],i&&a.dataChannel[t].pending.push(i)}function D(e,t){(t=t||{}).success="function"==typeof t.success?t.success:s.noop,t.error="function"==typeof t.error?t.error:s.noop;let r=S.get(e);if(!r||!r.webrtcStuff)return s.warn("Invalid handle"),void t.error("Invalid handle");let n=r.webrtcStuff,i=t.text||t.data;if(!i)return s.warn("Invalid data"),void t.error("Invalid data");let o=t.label?t.label:s.dataChanDefaultLabel;return n.dataChannel[o]?"open"!==n.dataChannel[o].readyState?(n.dataChannel[o].pending.push(i),void t.success()):(s.log("Sending data on data channel <"+o+">"),s.debug(i),n.dataChannel[o].send(i),void t.success()):(O(e,o,t.protocol,!1,i,t.protocol),void t.success())}function N(e,t){(t=t||{}).success="function"==typeof t.success?t.success:s.noop,t.error="function"==typeof t.error?t.error:s.noop;let r=S.get(e);if(!r||!r.webrtcStuff)return s.warn("Invalid handle"),void t.error("Invalid handle");let n=r.webrtcStuff;if(!n.dtmfSender){if(n.pc){let e=n.pc.getSenders().find(function(e){return e.track&&"audio"===e.track.kind});if(!e)return s.warn("Invalid DTMF configuration (no audio track)"),void t.error("Invalid DTMF configuration (no audio track)");n.dtmfSender=e.dtmf,n.dtmfSender&&(s.log("Created DTMF Sender"),n.dtmfSender.ontonechange=function(e){s.debug("Sent DTMF tone: "+e.tone)})}if(!n.dtmfSender)return s.warn("Invalid DTMF configuration"),void t.error("Invalid DTMF configuration")}let i=t.dtmf;if(!i)return s.warn("Invalid DTMF parameters"),void t.error("Invalid DTMF parameters");let o=i.tones;if(!o)return s.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;s.debug("Sending DTMF string "+o+" (duration "+a+"ms, gap "+c+"ms)"),n.dtmfSender.insertDTMF(o,a,c),t.success()}function L(e,n){(n=n||{}).success="function"==typeof n.success?n.success:s.noop,n.error="function"==typeof n.error?n.error:s.noop;let i=!0===n.noRequest;s.log("Destroying handle "+e+" (only-locally="+i+")"),q(e);let o=S.get(e);if(!o||o.detached)return S.delete(e),void n.success();if(o.detached=!0,i)return S.delete(e),void n.success();if(!b)return s.warn("Is the server down? (connected=false)"),void n.error("Is the server down? (connected=false)");let a={janus:"detach",transaction:s.randomString(12)};if(o.token&&(a.token=o.token),m&&(a.apisecret=m),t)return a.session_id=T,a.handle_id=e,r.send(JSON.stringify(a)),S.delete(e),void n.success();s.httpAPICall(c+"/"+T+"/"+e,{verb:"POST",withCredentials:p,body:a,success:function(t){s.log("Destroyed handle:"),s.debug(t),"success"!==t.janus&&s.error("Ooops: "+t.error.code+" "+t.error.reason),S.delete(e),n.success()},error:function(t,r){s.error(t+":",r),S.delete(e),n.success()}})}function j(e,t){let r=S.get(e);if(!r||!r.webrtcStuff)throw s.warn("Invalid handle"),"Invalid handle";let n=r.webrtcStuff;if(n.pc)return;let i={iceServers:d,iceTransportPolicy:u,bundlePolicy:l,sdpSemantics:"unified-plan"},o=!1;if(t.tracks)for(let e of t.tracks)if(e.transforms&&(e.transforms.sender||e.transforms.receiver)){o=!0;break}t.externalEncryption&&(o=!0,n.externalEncryption=!0),RTCRtpSender&&(RTCRtpSender.prototype.createEncodedStreams||RTCRtpSender.prototype.createEncodedAudioStreams&&RTCRtpSender.prototype.createEncodedVideoStreams)&&o&&(n.insertableStreams=!0,i.forceEncodedAudioInsertableStreams=!0,i.forceEncodedVideoInsertableStreams=!0,i.encodedInsertableStreams=!0),s.log("Creating PeerConnection"),n.pc=new RTCPeerConnection(i),s.debug(n.pc),n.pc.getStats&&(n.volume={},n.bitrate.value="0 kbits/sec"),s.log("Preparing local SDP and gathering candidates (trickle="+n.trickle+")"),n.pc.onconnectionstatechange=function(){n.pc&&r.connectionState(n.pc.connectionState)},n.pc.oniceconnectionstatechange=function(){n.pc&&r.iceState(n.pc.iceConnectionState)},n.pc.onicecandidate=function(r){if(!r.candidate||r.candidate.candidate&&r.candidate.candidate.indexOf("endOfCandidates")>0)s.log("End of candidates."),n.iceDone=!0,!0===n.trickle?A(e,{completed:!0}):function(e,t){t=t||{},t.success="function"==typeof t.success?t.success:s.noop,t.error="function"==typeof t.error?t.error:s.noop;let r=S.get(e);if(!r||!r.webrtcStuff)return void s.warn("Invalid handle, not sending anything");let n=r.webrtcStuff;if(s.log("Sending offer/answer SDP..."),!n.mySdp)return void s.warn("Local SDP instance is invalid, not sending anything...");n.mySdp={type:n.pc.localDescription.type,sdp:n.pc.localDescription.sdp},!1===n.trickle&&(n.mySdp.trickle=!1);s.debug(t),n.sdpSent=!0,t.success(n.mySdp)}(e,t);else{let t={candidate:r.candidate.candidate,sdpMid:r.candidate.sdpMid,sdpMLineIndex:r.candidate.sdpMLineIndex};!0===n.trickle&&A(e,t)}},n.pc.ontrack=function(e){if(s.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&&(r.mids||(r.mids={}),r.mids[e.track.id]=e.transceiver.mid),r.onremotetrack(e.track,t,!0,{reason:"created"})}catch(e){s.error("Error calling onremotetrack",e)}if(e.track.onended)return;let i=null;s.log("Adding onended callback to track:",e.track),e.track.onended=function(t){s.log("Remote track removed:",t),clearTimeout(i);let o=n.pc?n.pc.getTransceivers():null,a=o?o.find(e=>e.receiver.track===t.target):null,c=a?a.mid:t.target.id;c===t.target.id&&r.mids&&r.mids[e.track.id]&&(c=r.mids[e.track.id]);try{r.onremotetrack(t.target,c,!1,{reason:"ended"})}catch(e){s.error("Error calling onremotetrack on removal",e)}delete r.mids[e.track.id]},e.track.onmute=function(t){s.log("Remote track muted:",t),i||(i=setTimeout(function(){s.log("Removing remote track");let o=n.pc?n.pc.getTransceivers():null,a=o?o.find(e=>e.receiver.track===t.target):null,c=a?a.mid:t.target.id;c===t.target.id&&r.mids&&r.mids[e.track.id]&&(c=r.mids[e.track.id]);try{r.onremotetrack(t.target,c,!1,{reason:"mute"})}catch(e){s.error("Error calling onremotetrack on mute",e)}i=null},2520))},e.track.onunmute=function(e){if(s.log("Remote track flowing again:",e),null!=i)clearTimeout(i),i=null;else try{let t=n.pc?n.pc.getTransceivers():null,i=t?t.find(t=>t.receiver.track===e.target):null,o=i?i.mid:e.target.id;r.onremotetrack(e.target,o,!0,{reason:"unmute"})}catch(e){s.error("Error calling onremotetrack on unmute",e)}}}}async function M(e,t,r){(r=r||{}).success="function"==typeof r.success?r.success:s.noop,r.error="function"==typeof r.error?r.error:B;let n=r.jsep;if(t&&n)return s.error("Provided a JSEP to a createOffer"),void r.error("Provided a JSEP to a createOffer");if(!(t||n&&n.type&&n.sdp))return s.error("A valid JSEP is required for createAnswer"),void r.error("A valid JSEP is required for createAnswer");if(r.media&&!r.tracks){if(r.tracks=s.mediaToTracks(r.media),!0===r.simulcast||!0===r.simulcast2||r.svc)for(let e of r.tracks)if("video"===e.type){!0===r.simulcast||!0===r.simulcast2?e.simulcast=!0:r.svc&&(e.svc=r.svc);break}s.warn("Deprecated media object passed, use tracks instead. Automatically translated to:",r.tracks)}if(r.tracks&&!Array.isArray(r.tracks))return s.error("Tracks must be an array"),void r.error("Tracks must be an array");let i=S.get(e);if(!i||!i.webrtcStuff)return s.warn("Invalid handle"),void r.error("Invalid handle");let o=i.webrtcStuff;var a;o.trickle=(a=r.trickle,s.debug("isTrickleEnabled:",a),!1!==a);try{if(j(e,r),t&&await U(e,r),n){if(await o.pc.setRemoteDescription(n),s.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];s.debug("Adding remote candidate:",t),t&&!0!==t.completed?o.pc.addIceCandidate(t):o.pc.addIceCandidate(s.endOfCandidates)}o.candidates=[]}await U(e,r);let t=await async function(e,t){t=t||{},t.customizeSdp="function"==typeof t.customizeSdp?t.customizeSdp:s.noop;let r=S.get(e);if(!r||!r.webrtcStuff)throw s.warn("Invalid handle"),"Invalid handle";let n=r.webrtcStuff;s.log("Creating answer (iceDone="+n.iceDone+")");let i=await n.pc.createAnswer();s.debug(i);let o={type:"answer",sdp:i.sdp};if(t.customizeSdp(o),i.sdp=o.sdp,s.log("Setting local description"),n.mySdp={type:"answer",sdp:i.sdp},await n.pc.setLocalDescription(i),!n.iceDone&&!n.trickle)return s.log("Waiting for all candidates..."),null;(n.insertableStreams||n.externalEncryption)&&(i.e2ee=!0);return i}(e,r);r.success(t)}else{let t=await async function(e,t){t=t||{},t.customizeSdp="function"==typeof t.customizeSdp?t.customizeSdp:s.noop;let r=S.get(e);if(!r||!r.webrtcStuff)throw s.warn("Invalid handle"),"Invalid handle";let n=r.webrtcStuff;s.log("Creating offer (iceDone="+n.iceDone+")");let i={},o=!0===t.iceRestart;o&&(i.iceRestart=!0);s.debug(i);let a=await n.pc.createOffer(i);s.debug(a);let c={type:"offer",sdp:a.sdp};if(t.customizeSdp(c),a.sdp=c.sdp,s.log("Setting local description"),n.mySdp={type:"offer",sdp:a.sdp},await n.pc.setLocalDescription(a),n.mediaConstraints=i,!n.iceDone&&!n.trickle)return s.log("Waiting for all candidates..."),null;(n.insertableStreams||n.externalEncryption)&&(a.e2ee=!0);return a}(e,r);r.success(t)}}catch(e){s.error(e),r.error(e)}}function x(e,t){(t=t||{}).success="function"==typeof t.success?t.success:s.noop,t.error="function"==typeof t.error?t.error:B,t.customizeSdp="function"==typeof t.customizeSdp?t.customizeSdp:s.noop;let r=t.jsep,n=S.get(e);if(!n||!n.webrtcStuff)return s.warn("Invalid handle"),void t.error("Invalid handle");let i=n.webrtcStuff;if(r){if(!i.pc)return s.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(r),i.pc.setRemoteDescription(r).then(function(){if(s.log("Remote description accepted!"),i.remoteSdp=r.sdp,i.candidates&&i.candidates.length>0){for(let e=0;e<i.candidates.length;e++){let t=i.candidates[e];s.debug("Adding remote candidate:",t),t&&!0!==t.completed?i.pc.addIceCandidate(t):i.pc.addIceCandidate(s.endOfCandidates)}i.candidates=[]}t.success()},t.error)}else t.error("Invalid JSEP")}async function G(e,t){if((t=t||{}).success="function"==typeof t.success?t.success:s.noop,t.error="function"==typeof t.error?t.error:s.noop,t.tracks&&!Array.isArray(t.tracks))return s.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 U(e,t),t.success()}catch(e){s.error(e),t.error(e)}}async function U(e,t){let r=S.get(e);if(!r||!r.webrtcStuff)throw s.warn("Invalid handle, not sending anything"),"Invalid handle";let n=r.webrtcStuff;if(!n.pc)throw s.warn("Invalid PeerConnection"),"Invalid PeerConnection";let i=t.tracks;if(!i||!Array.isArray(i)||0===i.length)return;let o=!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){s.warn("Missing track type:",t);continue}if("data"===t.type){if(n.pc.ondatachannel){s.warn("Data channel exists already, not creating another one");continue}s.log("Creating default data channel"),O(e,s.dataChanDefaultLabel,null,!1),n.pc.ondatachannel=function(t){s.log("Data channel created by Janus:",t),O(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){s.warn("Conflicting actions for track, ignoring:",t);continue}t.add&&t.replace?(s.warn("Both add and replace provided, falling back to replace:",t),delete t.add):t.remove&&t.replace&&(s.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=n.pc.getTransceivers().find(e=>e.mid===t.mid&&e.receiver.track.kind===i):t.add||(c=n.pc.getTransceivers().find(e=>e.receiver.track.kind===i)),t.replace||t.remove){if(!c){s.warn("Couldn't find a transceiver for track:",t);continue}if(!c.sender){s.warn("No sender in the transceiver for track:",t);continue}u=c.sender}if(d&&!c&&(c=n.pc.getTransceivers().find(e=>e.receiver.track.kind===i),!c)){s.warn("Couldn't find a transceiver for track:",t);continue}let l=null,p=null;if((t.remove||t.replace)&&(s.log("Removing track from PeerConnection",t),p=u.track?u.track.id:null,await u.replaceTrack(null),p&&n.myStream)){let e=null;if("audio"===i&&n.myStream.getAudioTracks()&&n.myStream.getAudioTracks().length)for(let t of n.myStream.getAudioTracks())t.id===p&&(e=t,s.log("Removing audio track:",e));else if("video"===i&&n.myStream.getVideoTracks()&&n.myStream.getVideoTracks().length)for(let t of n.myStream.getVideoTracks())t.id===p&&(e=t,s.log("Removing video track:",e));if(e){try{n.myStream.removeTrack(e),r.onlocaltrack(e,!1)}catch(e){s.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{o||(o=!0,r.consentDialog(!0));let e=s.trackConstraints(t),n=null;if("audio"===t.type||"video"===t.type){if(t.gumGroup){let r="audio"===t.type?"video":"audio";if(a[t.gumGroup]&&a[t.gumGroup][r]){let n=a[t.gumGroup][r],i=s.trackConstraints(n);e[r]=i[r]}}n=await navigator.mediaDevices.getUserMedia(e),t.gumGroup&&e.audio&&e.video&&(a[t.gumGroup].stream=n,delete t.gumGroup)}else n=await navigator.mediaDevices.getDisplayMedia(e);l="audio"===t.type?n.getAudioTracks()[0]:n.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(n.myStream||(n.myStream=new MediaStream),"audio"===i||!t.simulcast&&!t.svc)u=n.pc.addTrack(l,n.myStream),c=n.pc.getTransceivers().find(e=>e.sender===u);else if(t.simulcast){s.log("Enabling rid-based simulcasting:",l);let e=y(t.simulcastMaxBitrates);c=n.pc.addTransceiver(l,{direction:"sendrecv",streams:[n.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 s.log("Enabling SVC ("+t.svc+"):",l),c=n.pc.addTransceiver(l,{direction:"sendrecv",streams:[n.myStream],sendEncodings:[{scalabilityMode:t.svc}]});if(u||(u=c?c.sender:null),t.codec)if("firefox"===s.webRTCAdapter.browserDetails.browser)s.warn("setCodecPreferences not supported in Firefox, ignoring codec for track:",t);else if("string"!=typeof t.codec)s.warn("Invalid codec value, ignoring for track:",t);else{let e=i+"/"+t.codec.toLowerCase(),r=RTCRtpReceiver.getCapabilities(i).codecs.filter(function(t){return t.mimeType.toLowerCase()===e});if(r&&0!==r.length){if(c)try{c.setCodecPreferences(r)}catch(e){s.warn("Failed enforcing codec for this "+i+" track:",e)}}else s.warn("Codec not supported in this browser for this track, ignoring:",t)}if(t.bitrate)if(t.simulcast||t.svc)s.warn("Ignoring bitrate for simulcast/SVC track, use sendEncodings for that");else if(isNaN(t.bitrate)||t.bitrate<0)s.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)):s.warn("No encodings in the sender parameters, ignoring bitrate for track:",t)}if("video"===i&&t.framerate)if(t.simulcast||t.svc)s.warn("Ignoring framerate for simulcast/SVC track, use sendEncodings for that");else if(isNaN(t.framerate)||t.framerate<0)s.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)):s.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=n.pc.addTransceiver(i)),c)){if(t.codec)if("firefox"===s.webRTCAdapter.browserDetails.browser)s.warn("setCodecPreferences not supported in Firefox, ignoring codec for track:",t);else if("string"!=typeof t.codec)s.warn("Invalid codec value, ignoring for track:",t);else{let e=i+"/"+t.codec.toLowerCase(),r=RTCRtpReceiver.getCapabilities(i).codecs.filter(function(t){return t.mimeType.toLowerCase()===e});if(r&&0!==r.length)try{c.setCodecPreferences(r)}catch(e){s.warn("Failed enforcing codec for this "+i+" track:",e)}else s.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){n.myStream.addTrack(l),l.onended=function(e){s.log("Local track removed:",e);try{r.onlocaltrack(e.target,!1)}catch(e){s.error("Error calling onlocaltrack following end",e)}};try{r.onlocaltrack(l,!0)}catch(e){s.error("Error calling onlocaltrack for track add",e)}}if(c){let e=c.direction,r=null,n=l&&c.sender.track,i=!1!==t.recv&&c.receiver.track;n&&i?r="sendrecv":n&&!i?r="sendonly":!n&&i?r="recvonly":n||i||(r="inactive"),r&&r!==e&&(s.warn("Changing direction of transceiver to "+r+" (was "+e+")",t),c.setDirection?c.setDirection(r):c.direction=r)}}o&&r.consentDialog(!1)}function J(e){let t=S.get(e);if(!t||!t.webrtcStuff)return s.warn("Invalid handle"),null;let r=t.webrtcStuff;if(!r.pc)return s.warn("Invalid PeerConnection"),null;let n=[],i=r.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&&n.push(t)}return n}function F(e){let t=S.get(e);if(!t||!t.webrtcStuff)return s.warn("Invalid handle"),null;let r=t.webrtcStuff;if(!r.pc)return s.warn("Invalid PeerConnection"),null;let n=[],i=r.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&&n.push(t)}return n}function W(e,t,r,n){n="function"==typeof n?n:s.noop;let i=S.get(e);if(!i||!i.webrtcStuff)return s.warn("Invalid handle"),void n(0);let o=r?"remote":"local",a=i.webrtcStuff;if(a.volume[o]||(a.volume[o]={value:0}),a.pc&&a.pc.getStats&&("chrome"===s.webRTCAdapter.browserDetails.browser||"safari"===s.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 s.warn("No audio transceiver with mid "+t),void n(0);if(r&&!i.receiver)return s.warn("Remote transceiver track unavailable"),void n(0);if(!r&&!i.sender)return s.warn("Local transceiver track unavailable"),void n(0);e=r?i.receiver:i.sender}return e.getStats().then(function(e){e.forEach(function(e){e&&"audio"===e.kind&&(r&&!e.remoteSource||!r&&"media-source"!==e.type||n(e.audioLevel?e.audioLevel:0))})}),a.volume[o].value}return s.warn("Getting the "+o+" volume unsupported by browser"),void n(0)}function V(e,t,r){let n=S.get(e);if(!n||!n.webrtcStuff)return s.warn("Invalid handle"),!0;let i=n.webrtcStuff;if(!i.pc)return s.warn("Invalid PeerConnection"),!0;if(!i.myStream)return s.warn("Invalid local MediaStream"),!0;if(r){if(!i.myStream.getVideoTracks()||0===i.myStream.getVideoTracks().length)return s.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:(s.warn("No video sender with mid "+t),!0):(s.warn("No video transceiver with mid "+t),!0)}return!i.myStream.getVideoTracks()[0].enabled}if(!i.myStream.getAudioTracks()||0===i.myStream.getAudioTracks().length)return s.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:(s.warn("No audio sender with mid "+t),!0):(s.warn("No audio transceiver with mid "+t),!0)}return!i.myStream.getAudioTracks()[0].enabled}function K(e,t,r,n){let i=S.get(e);if(!i||!i.webrtcStuff)return s.warn("Invalid handle"),!1;let o=i.webrtcStuff;if(!o.pc)return s.warn("Invalid PeerConnection"),!1;if(!o.myStream)return s.warn("Invalid local MediaStream"),!1;if(r){if(!o.myStream.getVideoTracks()||0===o.myStream.getVideoTracks().length)return s.warn("No video track"),!1;if(t){let e=o.pc.getTransceivers().find(e=>e.mid===t&&"video"===e.receiver.track.kind);if(!e)return s.warn("No video transceiver with mid "+t),!1;if(!e.sender||!e.sender.track)return s.warn("No video sender with mid "+t),!1;e.sender.track.enabled=!n}else for(const e of o.myStream.getVideoTracks())e.enabled=!n}else{if(!o.myStream.getAudioTracks()||0===o.myStream.getAudioTracks().length)return s.warn("No audio track"),!1;if(t){let e=o.pc.getTransceivers().find(e=>e.mid===t&&"audio"===e.receiver.track.kind);if(!e)return s.warn("No audio transceiver with mid "+t),!1;if(!e.sender||!e.sender.track)return s.warn("No audio sender with mid "+t),!1;e.sender.track.enabled=!n}else for(const e of o.myStream.getAudioTracks())e.enabled=!n}return!0}function $(e,t){let r=S.get(e);if(!r||!r.webrtcStuff)return s.warn("Invalid handle"),"Invalid handle";let n=r.webrtcStuff;if(!n.pc)return"Invalid PeerConnection";if(n.pc.getStats){let e=n.pc,r=t||"default";if(t){let r=n.pc.getTransceivers().find(e=>e.mid===t&&"video"===e.receiver.track.kind);if(!r)return s.warn("No video transceiver with mid "+t),"No video transceiver with mid "+t;if(!r.receiver)return s.warn("No video receiver with mid "+t),"No video receiver with mid "+t;e=r.receiver}return n.bitrate[r]||(n.bitrate[r]={timer:null,bsnow:null,bsbefore:null,tsnow:null,tsbefore:null,value:"0 kbits/sec"}),n.bitrate[r].timer?n.bitrate[r].value:(s.log("Starting bitrate timer"+(t?" for mid "+t:"")+" (via getStats)"),n.bitrate[r].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(n.bitrate[r].bsnow=e.bytesReceived,n.bitrate[r].tsnow=e.timestamp,null===n.bitrate[r].bsbefore||null===n.bitrate[r].tsbefore)n.bitrate[r].bsbefore=n.bitrate[r].bsnow,n.bitrate[r].tsbefore=n.bitrate[r].tsnow;else{let e=n.bitrate[r].tsnow-n.bitrate[r].tsbefore;"safari"===s.webRTCAdapter.browserDetails.browser&&(e/=1e3);let t=Math.round(8*(n.bitrate[r].bsnow-n.bitrate[r].bsbefore)/e);"safari"===s.webRTCAdapter.browserDetails.browser&&(t=parseInt(t/1e3)),n.bitrate[r].value=t+" kbits/sec",n.bitrate[r].bsbefore=n.bitrate[r].bsnow,n.bitrate[r].tsbefore=n.bitrate[r].tsnow}})})},1e3),"0 kbits/sec")}return s.warn("Getting the video bitrate unsupported by browser"),"Feature unsupported by browser"}function z(e,t,r){let n=S.get(e);if(!n||!n.webrtcStuff)return void s.warn("Invalid handle");let i=n.webrtcStuff;if(!i.pc)return void s.warn("Invalid PeerConnection");let o=i.pc.getTransceivers().find(e=>e.mid===t);if(!o)return void s.warn("No transceiver with mid",t);if(!o.sender)return void s.warn("No sender for transceiver with mid",t);let a=o.sender.getParameters();a&&a.encodings&&0!==a.encodings.length?a.encodings.length>1?s.warn("Ignoring bitrate for simulcast track, use sendEncodings for that"):isNaN(r)||r<0?s.warn("Invalid bitrate (must be a positive integer)"):(a.encodings[0].maxBitrate=r,o.sender.setParameters(a)):s.warn("No parameters encodings")}function B(e){s.error("WebRTC error:",e)}function q(e,n){s.log("Cleaning WebRTC stuff");let i=S.get(e);if(!i)return;let o=i.webrtcStuff;if(o){if(!0===n){let n={janus:"hangup",transaction:s.randomString(12)};i.token&&(n.token=i.token),m&&(n.apisecret=m),s.debug("Sending hangup request (handle="+e+"):"),s.debug(n),t?(n.session_id=T,n.handle_id=e,r.send(JSON.stringify(n))):s.httpAPICall(c+"/"+T+"/"+e,{verb:"POST",withCredentials:p,body:n})}o.volume&&(o.volume.local&&o.volume.local.timer&&clearInterval(o.volume.local.timer),o.volume.remote&&o.volume.remote.timer&&clearInterval(o.volume.remote.timer));for(let e in o.bitrate)o.bitrate[e].timer&&clearInterval(o.bitrate[e].timer);o.bitrate={},!o.streamExternal&&o.myStream&&(s.log("Stopping local stream tracks"),s.stopAllTracks(o.myStream)),o.streamExternal=!1,o.myStream=null;try{o.pc.close()}catch(e){}o.pc=null,o.candidates=null,o.mySdp=null,o.remoteSdp=null,o.iceDone=!1,o.dataChannel={},o.dtmfSender=null,o.insertableStreams=!1,o.externalEncryption=!1}i.oncleanup()}I(e),this.getServer=function(){return c},this.isConnected=function(){return b},this.reconnect=function(e){(e=e||{}).success="function"==typeof e.success?e.success:s.noop,e.error="function"==typeof e.error?e.error:s.noop,e.reconnect=!0,I(e)},this.getSessionId=function(){return T},this.getInfo=function(e){!function(e){if(e=e||{},e.success="function"==typeof e.success?e.success:s.noop,e.error="function"==typeof e.error?e.error:s.noop,s.log("Getting info on Janus instance"),!b)return s.warn("Is the server down? (connected=false)"),void e.error("Is the server down? (connected=false)");let n=s.randomString(12),i={janus:"info",transaction:n};h&&(i.token=h);m&&(i.apisecret=m);if(t)return _.set(n,function(t){s.log("Server info:"),s.debug(t),"server_info"!==t.janus&&s.error("Ooops: "+t.error.code+" "+t.error.reason),e.success(t)}),void r.send(JSON.stringify(i));s.httpAPICall(c,{verb:"POST",withCredentials:p,body:i,success:function(t){s.log("Server info:"),s.debug(t),"server_info"!==t.janus&&s.error("Ooops: "+t.error.code+" "+t.error.reason),e.success(t)},error:function(t,r){s.error(t+":",r),""===r?e.error(t+": Is the server down?"):e.error(t+": "+r)}})}(e)},this.destroy=function(o){!function(o){o=o||{},o.success="function"==typeof o.success?o.success:s.noop,o.error="function"==typeof o.error?o.error:s.noop;let a=!0===o.unload,d=!0;void 0!==o.notifyDestroyed&&null!==o.notifyDestroyed&&(d=!0===o.notifyDestroyed);let u=!0===o.cleanupHandles;if(s.log("Destroying session "+T+" (unload="+a+")"),!T)return s.warn("No session to destroy"),o.success(),void(d&&e.destroyed());if(u)for(const e of S.keys())L(e,{noRequest:!0});if(!b)return s.warn("Is the server down? (connected=false)"),T=null,void o.success();let l={janus:"destroy",transaction:s.randomString(12)};h&&(l.token=h);m&&(l.apisecret=m);if(a)return t?(r.onclose=null,r.close(),r=null):navigator.sendBeacon(c+"/"+T,JSON.stringify(l)),s.log("Destroyed session:"),T=null,b=!1,o.success(),void(d&&e.destroyed());if(t){l.session_id=T;let t=function(){for(let e in n)r.removeEventListener(e,n[e]);r.removeEventListener("message",a),r.removeEventListener("error",s),i&&clearTimeout(i),r.close()},a=function(r){let n=JSON.parse(r.data);n.session_id==l.session_id&&n.transaction==l.transaction&&(t(),o.success(),d&&e.destroyed())},s=function(){t(),o.error("Failed to destroy the server: Is the server down?"),d&&e.destroyed()};return r.addEventListener("message",a),r.addEventListener("error",s),void(1===r.readyState?r.send(JSON.stringify(l)):s())}s.httpAPICall(c+"/"+T,{verb:"POST",withCredentials:p,body:l,success:function(t){s.log("Destroyed session:"),s.debug(t),T=null,b=!1,"success"!==t.janus&&s.error("Ooops: "+t.error.code+" "+t.error.reason),o.success(),d&&e.destroyed()},error:function(t,r){s.error(t+":",r),T=null,b=!1,o.success(),d&&e.destroyed()}})}(o)},this.attach=function(e){!function(e){if(e=e||{},e.success="function"==typeof e.success?e.success:s.noop,e.error="function"==typeof e.error?e.error:s.noop,e.dataChannelOptions=e.dataChannelOptions||{ordered:!0},e.consentDialog="function"==typeof e.consentDialog?e.consentDialog:s.noop,e.connectionState="function"==typeof e.connectionState?e.connectionState:s.noop,e.iceState="function"==typeof e.iceState?e.iceState:s.noop,e.mediaState="function"==typeof e.mediaState?e.mediaState:s.noop,e.webrtcState="function"==typeof e.webrtcState?e.webrtcState:s.noop,e.slowLink="function"==typeof e.slowLink?e.slowLink:s.noop,e.onmessage="function"==typeof e.onmessage?e.onmessage:s.noop,e.onlocaltrack="function"==typeof e.onlocaltrack?e.onlocaltrack:s.noop,e.onremotetrack="function"==typeof e.onremotetrack?e.onremotetrack:s.noop,e.ondata="function"==typeof e.ondata?e.ondata:s.noop,e.ondataopen="function"==typeof e.ondataopen?e.ondataopen:s.noop,e.oncleanup="function"==typeof e.oncleanup?e.oncleanup:s.noop,e.ondetached="function"==typeof e.ondetached?e.ondetached:s.noop,!b)return s.warn("Is the server down? (connected=false)"),void e.error("Is the server down? (connected=false)");let n=e.plugin;if(!n)return s.error("Invalid plugin"),void e.error("Invalid plugin");let i=e.opaqueId,o=e.loopIndex,a=e.token?e.token:h,d=s.randomString(12),u={janus:"attach",plugin:n,opaque_id:i,loop_index:o,transaction:d};a&&(u.token=a);m&&(u.apisecret=m);if(t)return _.set(d,function(t){if(s.debug(t),"success"!==t.janus)return s.error("Ooops: "+t.error.code+" "+t.error.reason),void e.error("Ooops: "+t.error.code+" "+t.error.reason);let r=t.data.id;s.log("Created handle: "+r);let i={session:C,plugin:n,id:r,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 r},getPlugin:function(){return n},getVolume:function(e,t){return W(r,e,!0,t)},getRemoteVolume:function(e,t){return W(r,e,!0,t)},getLocalVolume:function(e,t){return W(r,e,!1,t)},isAudioMuted:function(e){return V(r,e,!1)},muteAudio:function(e){return K(r,e,!1,!0)},unmuteAudio:function(e){return K(r,e,!1,!1)},isVideoMuted:function(e){return V(r,e,!0)},muteVideo:function(e){return K(r,e,!0,!0)},unmuteVideo:function(e){return K(r,e,!0,!1)},getBitrate:function(e){return $(r,e)},setMaxBitrate:function(e,t){return z(r,e,t)},send:function(e){E(r,e)},data:function(e){D(r,e)},dtmf:function(e){N(r,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){M(r,!0,e)},createAnswer:function(e){M(r,!1,e)},handleRemoteJsep:function(e){x(r,e)},replaceTracks:function(e){G(r,e)},getLocalTracks:function(){return J(r)},getRemoteTracks:function(){return F(r)},onlocaltrack:e.onlocaltrack,onremotetrack:e.onremotetrack,ondata:e.ondata,ondataopen:e.ondataopen,oncleanup:e.oncleanup,ondetached:e.ondetached,hangup:function(e){q(r,!0===e)},detach:function(e){L(r,e)}};S.set(r,i),e.success(i)}),u.session_id=T,void r.send(JSON.stringify(u));s.httpAPICall(c+"/"+T,{verb:"POST",withCredentials:p,body:u,success:function(t){if(s.debug(t),"success"!==t.janus)return s.error("Ooops: "+t.error.code+" "+t.error.reason),void e.error("Ooops: "+t.error.code+" "+t.error.reason);let r=t.data.id;s.log("Created handle: "+r);let i={session:C,plugin:n,id:r,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 r},getPlugin:function(){return n},getVolume:function(e,t){return W(r,e,!0,t)},getRemoteVolume:function(e,t){return W(r,e,!0,t)},getLocalVolume:function(e,t){return W(r,e,!1,t)},isAudioMuted:function(e){return V(r,e,!1)},muteAudio:function(e){return K(r,e,!1,!0)},unmuteAudio:function(e){return K(r,e,!1,!1)},isVideoMuted:function(e){return V(r,e,!0)},muteVideo:function(e){return K(r,e,!0,!0)},unmuteVideo:function(e){return K(r,e,!0,!1)},getBitrate:function(e){return $(r,e)},setMaxBitrate:function(e,t){return z(r,e,t)},send:function(e){E(r,e)},data:function(e){D(r,e)},dtmf:function(e){N(r,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){M(r,!0,e)},createAnswer:function(e){M(r,!1,e)},handleRemoteJsep:function(e){x(r,e)},replaceTracks:function(e){G(r,e)},getLocalTracks:function(){return J(r)},getRemoteTracks:function(){return F(r)},onlocaltrack:e.onlocaltrack,onremotetrack:e.onremotetrack,ondata:e.ondata,ondataopen:e.ondataopen,oncleanup:e.oncleanup,ondetached:e.ondetached,hangup:function(e){q(r,!0===e)},detach:function(e){L(r,e)}};S.set(r,i),e.success(i)},error:function(t,r){s.error(t+":",r),""===r?e.error(t+": Is the server down?"):e.error(t+": "+r)}})}(e)}}s.useDefaultDependencies=function(e){let t=e&&e.fetch||fetch,r=e&&e.Promise||Promise,n=e&&e.WebSocket||WebSocket;return{newWebSocket:function(e,t){return new n(e,t)},extension:e&&e.extension||a,isArray:function(e){return Array.isArray(e)},webRTCAdapter:e&&e.adapter||adapter,httpAPICall:function(e,n){let i={method:n.verb,headers:{Accept:"application/json, text/plain, */*"},cache:"no-cache"};"POST"===n.verb&&(i.headers["Content-Type"]="application/json"),void 0!==n.withCredentials&&(i.credentials=!0===n.withCredentials?"include":n.withCredentials?n.withCredentials:"omit"),n.body&&(i.body=JSON.stringify(n.body));let o=t(e,i).catch(function(e){return r.reject({message:"Probably a network error, is the server down?",error:e})});if(n.timeout){let e=new r(function(e,t){let r=setTimeout(function(){return clearTimeout(r),t({message:"Request timed out",timeout:n.timeout})},n.timeout)});o=r.race([o,e])}return o.then(function(e){return e.ok?typeof n.success==typeof s.noop?e.json().then(function(e){try{n.success(e)}catch(e){s.error("Unhandled httpAPICall success callback error",e)}},function(t){return r.reject({message:"Failed to parse response body",error:t,response:e})}):void 0:r.reject({message:"API call failed",response:e})}).catch(function(e){typeof n.error==typeof s.noop&&n.error(e.message||"<< internal error >>",e)}),o}}},s.useOldDependencies=function(e){let t=e&&e.jQuery||jQuery,r=e&&e.WebSocket||WebSocket;return{newWebSocket:function(e,t){return new r(e,t)},isArray:function(e){return t.isArray(e)},extension:e&&e.extension||a,webRTCAdapter:e&&e.adapter||adapter,httpAPICall:function(e,r){let n=void 0!==r.body?{contentType:"application/json",data:JSON.stringify(r.body)}:{},i=void 0!==r.withCredentials?{xhrFields:{withCredentials:r.withCredentials}}:{};return t.ajax(t.extend(n,i,{url:e,type:r.verb,cache:!1,dataType:"json",async:r.async,timeout:r.timeout,success:function(e){typeof r.success==typeof s.noop&&r.success(e)},error:function(e,t,n){typeof r.error==typeof s.noop&&r.error(t,n)}}))}}},s.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 r={type:"audio"};e.removeAudio?r.remove=!0:(e.addAudio?r.add=!0:e.replaceAudio&&(r.replace=!0),!1!==e.audioSend&&(r.capture=e.audio||!0),!1!==e.audioRecv&&(r.recv=!0)),(r.remove||r.capture||r.recv)&&t.push(r)}if(!e.keepVideo&&!1!==e.video&&(void 0===e.video||e.video||e.videoSend||e.videoRecv||e.addVideo||e.replaceVideo||e.removeVideo)){let r={type:"video"};e.removeVideo?r.remove=!0:(e.addVideo?r.add=!0:e.replaceVideo&&(r.replace=!0),!1!==e.videoSend&&(r.capture=e.video||!0,["screen","window","desktop"].includes(r.capture)&&(r.type="screen",r.capture={video:{}},e.screenshareFrameRate&&(r.capture.frameRate=e.screenshareFrameRate),e.screenshareHeight&&(r.capture.height=e.screenshareHeight),e.screenshareWidth&&(r.capture.width=e.screenshareWidth))),!1!==e.videoRecv&&(r.recv=!0)),(r.remove||r.capture||r.recv)&&t.push(r)}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},s.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 r=0,n=0;"lowres"===e.capture?(r=320,n=240):"lowres-16:9"===e.capture?(r=320,n=180):"hires"===e.capture||"hires-16:9"===e.capture||"hdres"===e.capture?(r=1280,n=720):"fhdres"===e.capture?(r=1920,n=1080):"4kres"===e.capture?(r=3840,n=2160):"stdres"===e.capture?(r=640,n=480):"stdres-16:9"===e.capture?(r=640,n=360):(s.log("Default video setting is stdres 4:3"),r=640,n=480),t.video={width:{ideal:r},height:{ideal:n}}}else"screen"===e.type&&(t.video=e.capture);return t},s.noop=function(){},s.dataChanDefaultLabel="JanusDataChannel",s.endOfCandidates=null,s.stopAllTracks=function(e){try{let t=e.getTracks();for(let e of t)s.log(e),e&&!0!==e.dontStop&&e.stop()}catch(e){}},s.init=function(e){if((e=e||{}).callback="function"==typeof e.callback?e.callback:s.noop,s.initDone)e.callback();else{if(void 0===console.log&&(console.log=function(){}),s.trace=s.noop,s.debug=s.noop,s.vdebug=s.noop,s.log=s.noop,s.warn=s.noop,s.error=s.noop,!0===e.debug||"all"===e.debug)s.trace=console.trace.bind(console),s.debug=console.debug.bind(console),s.vdebug=console.debug.bind(console),s.log=console.log.bind(console),s.warn=console.warn.bind(console),s.error=console.error.bind(console);else if(Array.isArray(e.debug))for(let t of e.debug)switch(t){case"trace":s.trace=console.trace.bind(console);break;case"debug":s.debug=console.debug.bind(console);break;case"vdebug":s.vdebug=console.debug.bind(console);break;case"log":s.log=console.log.bind(console);break;case"warn":s.warn=console.warn.bind(console);break;case"error":s.error=console.error.bind(console);break;default:console.error("Unknown debugging option '"+t+"' (supported: 'trace', 'debug', 'vdebug', 'log', warn', 'error')")}s.log("Initializing library");let t=e.dependencies||s.useDefaultDependencies();s.isArray=t.isArray,s.webRTCAdapter=t.webRTCAdapter,s.httpAPICall=t.httpAPICall,s.newWebSocket=t.newWebSocket,s.extension=t.extension,s.extension.init(),s.listDevices=function(e,t){e="function"==typeof e?e:s.noop,t||(t={audio:!0,video:!0}),s.isGetUserMediaAvailable()?navigator.mediaDevices.getUserMedia(t).then(function(t){navigator.mediaDevices.enumerateDevices().then(function(r){s.debug(r),e(r),s.stopAllTracks(t)})}).catch(function(t){s.error(t),e([])}):(s.warn("navigator.mediaDevices unavailable"),e([]))},s.attachMediaStream=function(e,t){try{e.srcObject=t}catch(r){try{e.src=URL.createObjectURL(t)}catch(e){s.error("Error attaching stream to element",e)}}},s.reattachMediaStream=function(e,t){try{e.srcObject=t.srcObject}catch(r){try{e.src=t.src}catch(e){s.error("Error reattaching stream to element",e)}}};let r=["iPad","iPhone","iPod"].indexOf(navigator.platform)>=0?"pagehide":"beforeunload",n=window["on"+r];if(window.addEventListener(r,function(){s.log("Closing window");for(const[e,t]of s.sessions)t&&t.destroyOnUnload&&(s.log("Destroying session "+e),t.destroy({unload:!0,notifyDestroyed:!1}));n&&"function"==typeof n&&n()}),s.safariVp8=!1,s.safariVp9=!1,"safari"===s.webRTCAdapter.browserDetails.browser&&s.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()?s.safariVp8=!0:e&&e.mimeType&&"video/vp9"===e.mimeType.toLowerCase()&&(s.safariVp9=!0);s.safariVp8?s.log("This version of Safari supports VP8"):s.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){s.safariVp8=-1!==t.sdp.indexOf("VP8"),s.safariVp9=-1!==t.sdp.indexOf("VP9"),s.safariVp8?s.log("This version of Safari supports VP8"):s.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})}s.initDone=!0,e.callback()}},s.isWebrtcSupported=function(){return!!window.RTCPeerConnection},s.isGetUserMediaAvailable=function(){return navigator.mediaDevices&&navigator.mediaDevices.getUserMedia},s.randomString=function(e){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",r="";for(let n=0;n<e;n++){let e=Math.floor(62*Math.random());r+=t.charAt(e)}return r};function c(e,t=1e4){const r=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 r.postMessage("START"),r.onmessage=t=>{"heartbeat"===t.data&&(console.log("Worker active at:",new Date),e())},window.addEventListener("unload",()=>{r.terminate()}),r}const d={url:null,queue:[],timer:null,batchSize:20,flushInterval:5e3,push(e,t,r){const n=`[${(new Date).toLocaleString("zh-CN",{hour12:!1})}] [VoiceNine] [${t}]`;"warn"===e?console.warn(n,r):"error"===e?console.error(n,r):console.log(n,r)}};function u(e,t){d.push("info",e,t)}function l(e,t){d.push("warn",e,t)}function p(e,t,r){d.push("error",e,r?`${t} ${r}`:t)}const f={agentId:"",agentKey:"",companyId:"",agentType:"",token:"",wsServer:"",webrtcServer:"",sipServer:"",agentCode:"",sipPwd:"",groupId:"",groupIds:[]};class h{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;_janusInitializing=!1;static _janusInited=!1;_sipRetryCount=0;_sipRetryTimer=null;_sipMaxRetries=5;_webrtcDownTimer=null;_sipRegisterTimeout=null;_sipRegistered=!1;_dtlsCheckTimer=null;_iceDisconnectTimer=null;_worker=null;constructor(){if(this.instance)return this.instance;this.instance=this,this._worker=c(()=>{this._keepalive()})}_init(e){this.seat={...f,...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),u("_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 r=document.createElement("audio");r.id="incomingcallAudio",r.loop=!0,r.src="https://r.hanfatong.com/voicenine/beep.mp3",t.appendChild(r);const n=document.createElement("audio");n.id="callEndAudio",n.loop=!1,n.src="https://r.hanfatong.com/voicenine/hangup.mp3",t.appendChild(n);const i=document.createElement("audio");i.id="peerVideo",i.autoplay=!0,t.appendChild(i)}_initJanus(){const{webrtcServer:t,sipServer:r}=this.seat;if(!t||!r)return void p("_initJanus","WebRTC server or SIP server is not configured.");if(this._janusInitializing)return void l("_initJanus","已在初始化中,跳过重复调用");if(this._janusInitializing=!0,this.janus){u("_initJanus","检测到旧 Janus session,先销毁");try{this.janus.destroy({cleanupHandles:!0,notifyDestroyed:!1})}catch(e){l("_initJanus","销毁旧 Janus 异常")}this.janus=null,this.sipcall=null}let n={},i={},o=!1;const a=this.seat.janusDebug||"warn",c=()=>{u("_initJanus","Janus initialized.");if(!s.isWebrtcSupported())return l("_initJanus","No WebRTC support or not HTTPS."),void(this._janusInitializing=!1);this.trigger("connstate",{type:"janus",state:"connecting"}),this._sipRegisterTimeout&&clearTimeout(this._sipRegisterTimeout),this._sipRegisterTimeout=setTimeout(()=>{this.sipcall&&!this._sipRegistered&&this.connected&&!this._userLogout&&(l("_initJanus","SIP 注册超时(15s),重建 Janus"),this._rebuildJanus())},15e3),this._sipRegistered=!1;const r=new s({server:t,success:()=>{this.trigger("connstate",{type:"janus",state:"connected"}),r.attach({plugin:"janus.plugin.sip",opaqueId:"voicenine_"+s.randomString(16),success:e=>{u("_initJanus","SIP plugin attached."),this.sipcall=e,this._janusRetryCount=0,this._sipRetryCount=0,this._janusInitializing=!1,this._registerSip()},onmessage:(t,r)=>{s.debug(" ::: Got a message :::",t);const{call_id:n,result:i}=t;if(i?.event){const a=i.event;if(this.msg=null,this.jsep=null,"registration_failed"===a)l("_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)u("_initJanus","SIP registered: "+i.username),this._sipRegistered=!0,this._sipRegisterTimeout&&(clearTimeout(this._sipRegisterTimeout),this._sipRegisterTimeout=null),o||(o=!0,i.master_id),this.trigger("sipstate",{registered:!0,username:i.username});else if("calling"===a)u("_initJanus","calling...");else if("incomingcall"===a){u("_initJanus","incomingcall"),this.sipcall.callId=n,this.toggleRing(!0),r&&r.sdp&&(r.sdp=this._sanitizeSdp(r.sdp)),this.msg=t,this.jsep=r;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,r)):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)u("_initJanus","progress"),r&&(r.sdp&&(r.sdp=this._sanitizeSdp(r.sdp)),this.sipcall.handleRemoteJsep({jsep:r}));else if("accepted"===a)u("_initJanus","accepted"),this.toggleRing(!1),r&&(r.sdp&&(r.sdp=this._sanitizeSdp(r.sdp)),this.sipcall.handleRemoteJsep({jsep:r})),this.sipcall.callId=n;else if("updatingcall"===a){u("_initJanus","updatingcall");const e=r.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:r,tracks:t,success:t=>{s.debug("Got SDP "+t.type+"! audio="+e+":",t);this.sipcall.send({message:{request:"update"},jsep:t})},error:e=>{this.trigger("error",e),p("createAnswer","WebRTC error",e)}})}else if("message"===a);else if("info"===a);else if("notify"===a);else if("transfer"===a);else if("hangup"===a){u("_initJanus",`hangup: ${i.code} ${i.reason}`);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)=>{u("onlocaltrack",`${t?"added":"removed"} kind=${e.kind}`);const r=e.id.replace(/[{}]/g,"");if(!t){if(this.stream=n[r],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){p("onlocaltrack","停止本地轨道失败",e)}return e.kind,void delete n[r]}this.stream=n[r],this.stream||(e.kind,"completed"!==this.sipcall.webrtcStuff.pc.iceConnectionState&&this.sipcall.webrtcStuff.pc.iceConnectionState)},onremotetrack:(e,t,r)=>{if(r&&"audio"===e.kind){const r=new MediaStream([e]);i[t]=r;let n=document.getElementById("peerVideo");s.attachMediaStream(n,r)}},oncleanup:()=>{u("oncleanup","cleanup notification"),setTimeout(()=>{this.sipcall&&(delete this.sipcall.callId,delete this.sipcall.doAudio)},50),setTimeout(()=>{Object.values(n).forEach(e=>{if(e){e.getTracks().forEach(e=>{"ended"!==e.readyState&&e.stop()})}})},100),setTimeout(()=>{n={},i={},this.stream=null,this._iceRestarting=!1,this._dtlsRebuildNeeded=!1,this._iceRestartCooldown=null},200)},error:e=>{p("_initJanus","attach plugin error",e),this._janusInitializing=!1,this.connected&&!this._userLogout&&this._retryJanus("attach_error")},consentDialog:function(e){},webrtcTimeout:function(e){u("webrtcTimeout",e)},iceState:e=>{u("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,r)=>{u("mediaState",`${e} ${t?"started":"stopped"} mid=${r}`),"audio"===e&&t&&this._iceRestarting&&this._onIceRestartSuccess()},webrtcState:e=>{if(u("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&&(l("webrtcState","WebRTC down 超时,重建 Janus session"),this.trigger("icestate",{state:"failed",reason:"webrtc_down"}),this._rebuildJanus())},8e3))}},slowLink:function(e,t,r){l("slowLink",`${e?"sending":"receiving"} lost=${t} mid=${r}`)}})},error:e=>{p("_initJanus","janus session error",e),this._janusInitializing=!1,this.trigger("connstate",{type:"janus",state:"failed",reason:e}),this.connected&&!this._userLogout&&this._retryJanus("session_error")},destroyed:()=>{u("_initJanus","destroyed")}});this.janus=r,window.Janus=s};h._janusInited?c():s.init({debug:a,callback:()=>{h._janusInited=!0,c()}})}_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=>{p("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&&u("echo",`cmd=${t.cmd} agentKey=${t.agentKey||""}`)}catch{u("echo","发送消息")}this.socket.send(e)}else l("echo","WebSocket 未连接,消息丢弃")}toggleRing(e){const t=document.getElementById("incomingcallAudio");e?t.play():t.pause()}playEndRing(){document.getElementById("callEndAudio").play()}connectWs(r){if(u("connectWs","连接WebSocket: "+r.split("?")[0]),!window.WebSocket)return void alert("您的浏览器不支持WebSocket协议!");this.trigger("connstate",{type:"ws",state:"connecting"});const n=new WebSocket(r);this.socket=n,n.onmessage=r=>{const n=JSON.parse(r.data);if("PONG"!==n.type&&"pong"!==n.type&&u("onmessage",`type=${n.type} code=${n.code} agentKey=${n.agentKey||""}`),this.onmessage(n),n.type===t.TASK_CALL)return void(0===n.code&&(this.trigger(t.TASK_CALL,n),this.trigger("taskCall",n)));let i=n.type;e[i]&&(0===n.code&&(this.lastStatus=this.status,this.status=i,u("onmessage",`状态变更: ${this.lastStatus} -> ${this.status}`)),this.code=n.code,this.handleStatusChange(n))},n.onopen=()=>{u("connectWs","WebSocket connection opened."),this.clearReconectStatus(),this.sendAction(e.LOGIN),this.connected=!0,this.trigger("connstate",{type:"ws",state:"connected"})},n.onclose=e=>{u("connectWs",`WebSocket connection closed, Code: ${e.code}${e.reason?", Reason: "+e.reason:""}`),this.reconectInterval&&(clearTimeout(this.reconectInterval),this.reconectInterval=null),this.connected=!1;if(this.trigger("logout",this.code),this.trigger("connstate",{type:"ws",state:"closed",code:e.code,reason:e.reason}),this._clearAllTimers(),2===this.seat.loginType){if(this.sipcall&&this.status&&this.status.includes("TALKING")){l("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}if([1111,1403,1105,1417].includes(this.code))return void u("connectWs","不自动重连, code: "+this.code);if(this._userLogout||1e3===e.code&&"Bye"===e.reason)return void u("connectWs","主动登出,不自动重连");(()=>{this.reconectInterval=setTimeout(()=>{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:r,message:n,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=[],r===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(r===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.sipcall&&this._sipRegistered?u("handleStatusChange",`通话未接通(${o.sipStatus}),SIP 注册正常,跳过`):this.sipcall&&!this._sipRegistered?(l("handleStatusChange",`通话未接通(${o.sipStatus}),SIP 未注册,尝试重新注册`),this._registerSip()):(l("handleStatusChange",`通话未接通(${o.sipStatus}),Janus 连接异常,重建`),this._rebuildJanus())));const t=o.afterInterval||3;this.afterPhoneInterval=setTimeout(()=>{this.status===e.AFTER&&(u("handleStatusChange","话后自动空闲"),this.sendAction(e.READY))},1e3*t)}else r===e.OUT_CALL||(r===e.READY||r===e.NOT_READY||r===e.WORK_NOT_READY)&&(this.reconnectState=r);this.trigger("state",t),this.trigger(r,t)}sendAction(e,t){let r={cmd:e,agentKey:this.seat.agentKey,sequence:(new Date).getTime()};if(e===n.login)r={...r,loginType:this.seat.loginType,workType:this.seat.workType},this.status&&this.status.includes("TALKING")&&(r.callId=this.callId);else if(e===n.call){this.afterPhoneInterval&&window.clearInterval(this.afterPhoneInterval);const{telNum:e,display:n="",followData:i}=t||{};r={...r,called:e,display:n,callType:1,followData:i||{}}}else if(e===n.transfer){let{transferValue:e,transferType:n="4"}=t||{};e.includes("@")&&(n="3"),r={...r,transferType:n,transferValue:e}}else if(e===n.consult){const{consultValue:e}=t||{};let n="2";e.includes("@")&&(n="4"),r={...r,callId:this.callId,transferType:n,consultValue:e}}else if(e===n.consult_cancel);else if(e===n.consult_party)r.callId=this.callId;else if(e===n.consult_transfer)r.callId=this.callId;else if(e===n.busy_work){const{busyDesc:e}=t||{};r={...r,busyDesc:e,callId:this.callId}}else if(e===n.ready)this.afterPhoneInterval&&window.clearInterval(this.afterPhoneInterval);else if(e===n.busy)this.afterPhoneInterval&&window.clearInterval(this.afterPhoneInterval);else if(e===n.conference_remove){const{deviceId:n,memberId:i,username:o}=t||{};r={cmd:e,callId:this.callId,deviceId:n,conference:this.conference,memberId:i,username:o}}else{if(e===n.logout){this._userLogout=!0,this._clearAllTimers();const e=JSON.stringify(r);return this.echo(e),2===this.seat.loginType&&this.janus?.destroy(),void(this._worker&&(this._worker.terminate(),this._worker=null))}e===n.followdata?r={...r,callId:this.callId,followData:t.followData||{}}:e===n.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&&(clearTimeout(this.reconectInterval),this.reconectInterval=null)}_clearAllTimers(){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),this.autoAcceptTimer&&(clearTimeout(this.autoAcceptTimer),this.autoAcceptTimer=null),this.afterPhoneInterval&&(clearTimeout(this.afterPhoneInterval),this.afterPhoneInterval=null)}_iceRestart(e){if(this._userLogout||!this.connected)return;if(!(this.status&&this.status.includes("TALKING")))return void("failed"===e&&(l("_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?(l("_iceRestart","ICE failed(冷却期内),上次 restart 未恢复,重建 Janus"),this.trigger("icestate",{state:"failed",reason:"ice_restart_ineffective"}),this._rebuildJanus()):(l("_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 u("_iceRestart","ICE disconnected 后自动恢复")}catch(e){}l("_iceRestart","ICE disconnected 5s 未恢复,重建 Janus"),this.trigger("icestate",{state:"failed",reason:"ice_disconnect_timeout"}),this._rebuildJanus()}},5e3))):(l("_iceRestart",`ICE ${e},尝试 ICE restart 恢复通话`),this.trigger("icestate",{state:"disconnected"}),this.sipcall.createOffer({iceRestart:!0,tracks:[{type:"audio",capture:!0,recv:!0}],success:e=>{u("_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=>{p("_iceRestart","ICE restart 失败",e),this.trigger("icestate",{state:"failed"}),l("_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),u("_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 r=t.iceConnectionState,n=t.connectionState||"N/A",i=t.sctp?.transport||t.getSenders?.()[0]?.transport,o=i?.state||"N/A";if(u("_dtlsCheck",`[${e}/5] ice=${r} conn=${n} dtls=${o}`),"connected"===n||"connected"===r&&"connected"===o)return u("_dtlsCheck","DTLS 恢复成功"),this._dtlsRebuildNeeded=!1,this._dtlsCheckTimer=null,void this.trigger("icestate",{state:"dtls_recovered"});if("failed"===n||"failed"===r||"failed"===o)return l("_dtlsCheck",`DTLS 恢复失败: ice=${r} conn=${n} dtls=${o},重建 Janus`),this._dtlsCheckTimer=null,this.trigger("icestate",{state:"failed",reason:"dtls_failed"}),void this._rebuildJanus()}else l("_dtlsCheck",`[${e}/5] PeerConnection 不存在`)}catch(t){l("_dtlsCheck",`[${e}/5] 检查异常: ${t}`)}if(e>=5)return l("_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,l("_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"),r=[];let n=!1;for(const e of t)e.startsWith("m=video")?(n=!0,u("_sanitizeSdp","移除 video 媒体段")):(n&&e.startsWith("m=")&&(n=!1),n||r.push(e));const i=[];return r.forEach(e=>{const t=e.match(/^a=mid:(.+)$/);t&&i.push(t[1].trim())}),r.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")}_sipRegisterTarget(){const e=(this.seat.sipServer||"").replace(/^sip:/i,"").trim();let t=e,r="7480";const n=e.lastIndexOf(":");return n>0&&/^\d+$/.test(e.slice(n+1))&&(r=e.slice(n+1),t=e.slice(0,n)),{host:t,proxy:`sip:${t}:${r}`}}_sipUri(e){if(!e)return e;if(e.startsWith("sip:")||e.startsWith("sips:"))return e;if(e.includes("@"))return`sip:${e}`;const{host:t}=this._sipRegisterTarget();return t?`sip:${e}@${t}`:`sip:${e}`}_registerSip(){const e=this.seat.agentCode,t=e.includes("@")?e.split("@")[0]:e,{proxy:r}=this._sipRegisterTarget(),n={request:"register",username:this._sipUri(e),authuser:t,display_name:e,secret:this.seat.sipPwd,proxy:r,offer_video:!1};this.sipcall.send({message:n}),this.trigger("sipstate",{registered:null,username:this.seat.agentCode})}_retrySipRegister(e){const t=Number(e);if(401===t||403===t)return void l("_retrySipRegister",`SIP 注册失败 code=${e},认证错误不重试`);if(this._sipRetryCount>=this._sipMaxRetries)return p("_retrySipRegister",`SIP 注册重试已达上限 ${this._sipMaxRetries} 次,重建 Janus`),this._sipRetryCount=0,void this._rebuildJanus();this._sipRetryCount++;const r=Math.min(2e3*Math.pow(2,this._sipRetryCount-1),3e4);l("_retrySipRegister",`SIP 注册失败,${r}ms 后第 ${this._sipRetryCount} 次重试`),this._sipRetryTimer&&clearTimeout(this._sipRetryTimer),this._sipRetryTimer=setTimeout(()=>{this.sipcall&&this.connected&&!this._userLogout&&this._registerSip()},r)}_retryJanus(e){if(this._janusRetryCount>=this._janusMaxRetries)return p("_retryJanus",`Janus 重连已达上限 ${this._janusMaxRetries} 次 (${e}),停止重连`),this._janusRetryCount=0,void this.trigger("connstate",{type:"janus",state:"give_up",reason:e});this._janusRetryCount++;const t=Math.floor(3e3*Math.random()),r=Math.min(2e3*Math.pow(2,this._janusRetryCount-1),3e4)+t;l("_retryJanus",`${e},${r}ms 后第 ${this._janusRetryCount} 次重建 Janus`),this._janusRetryTimer&&clearTimeout(this._janusRetryTimer),this._janusRetryTimer=setTimeout(()=>{this.connected&&!this._userLogout&&this._initJanus()},r)}_rebuildJanus(){if(this.status&&this.status.includes("TALKING")&&this.sipcall){l("_rebuildJanus","通话中 Janus 异常,先挂断通话再重建");try{this.sipcall.send({message:{request:"hangup"}}),this.sipcall.hangup()}catch(e){l("_rebuildJanus","挂断异常")}this.toggleRing(!1),this.isHangup=!0}u("_rebuildJanus","销毁旧 Janus 并重建");try{this.janus?.destroy({cleanupHandles:!0})}catch(e){l("_rebuildJanus","销毁 Janus 异常")}this.janus=null,this.sipcall=null,this._iceRestarting=!1,this._dtlsRebuildNeeded=!1,this._sipRegistered=!1,this._janusInitializing=!1,this._clearAllTimers(),this._retryJanus("rebuild")}on(e,t){this.events[e]||(u("on","订阅事件: "+e),this.events[e]=[]),this.events[e].push(t)}trigger(e,t){this.events[e]&&("message"!==e&&u("trigger","触发事件: "+e),this.events[e].forEach(e=>e(t)))}onmessage(e){this.trigger("message",e)}datelog(){var e=new Date,t=e.getFullYear(),r=e.getMonth()+1,n=e.getDate(),i=e.getHours(),o=e.getMinutes(),a=e.getSeconds(),s=e.getMilliseconds();return r<10&&(r="0"+r),n<10&&(n="0"+n),i<10&&(i="0"+i),o<10&&(o="0"+o),a<10&&(a="0"+a),s<10?s+="00":s<100&&(s+="0"),t+"-"+r+"-"+n+" "+i+":"+o+":"+a+"."+s}}const m=new h;class g{static _instance=null;static _version_="2.0.0";static _enum_={state:e,btn:n,label:i,taskEvent:t,taskCallStatus:r};constructor(){if(g._instance)return g._instance;g._instance=this,console.log("[VoiceNine] version:",g._version_),this.on("state",e=>this._stateHandler(e))}get version(){return g._version_}get status(){return m.status}get enum(){return g._enum_}init(e){console.log("["+m.datelog()+"] voice9 init",e),m._init(e)}logout(){m.sendAction(n.logout)}setBusy(){m.sendAction(n.busy)}setReady(){m.sendAction(n.ready)}setWorkNotReady(e){m.sendAction(n.busy_work,{busyDesc:e})}call(t,r={}){const i=[e.LOGIN,e.READY,e.NOT_READY,e.WORK_NOT_READY,e.AFTER];if(!m.connected)return{success:!1,reason:"ws_disconnected",message:"WebSocket 未连接"};if(!i.includes(m.status))return{success:!1,reason:"invalid_state",message:`当前状态不允许外呼: ${m.status}`};if(2===m.seat.loginType){if(!m.sipcall)return{success:!1,reason:"webrtc_not_ready",message:"WebRTC 未初始化"};const e=m.sipcall.webrtcStuff?.pc?.iceConnectionState;if(e&&"connected"!==e&&"completed"!==e&&"new"!==e)return{success:!1,reason:"ice_disconnected",message:`ICE 连接异常: ${e}`}}return m.sendAction(n.call,{telNum:t,...r}),{success:!0}}answer(){m.accept(m.msg,m.jsep)}sendDtmf(e){const t={cmd:"dtmf",dtmf:e,callId:m.callId,agentKey:m.seat.agentKey,sequence:(new Date).getTime()};m.echo(JSON.stringify(t))}hangup(){m.sendAction(n.hangup)}transfer(e,t={}){m.sendAction(n.transfer,{transferValue:e,...t})}consult(e,t={}){m.sendAction(n.consult,{consultValue:e,...t})}cancelConsult(){m.sendAction(n.consult_cancel)}stopConsult(){m.sendAction(n.consult_stop)}consultTransfer(e,t={}){m.sendAction(n.consult_transfer,{transferValue:e,...t})}consultParty(){m.sendAction(n.consult_party)}mute(){m.sendAction(n.mute)}muteCancel(){m.sendAction(n.mute_cancel)}hold(){m.sendAction(n.hold)}holdCancel(){m.sendAction(n.hold_cancel)}monitor(e,t){const r={cmd:"MONITOR_CALL",callId:t,agentKey:m.seat.agentKey,monitorAgent:e,sequence:(new Date).getTime()};m.echo(JSON.stringify(r))}intercept(){m.sendAction("INTERCEPT_CALL")}barge(e,t){const r={cmd:"BARGE_CALL",callId:t,agentKey:m.seat.agentKey,monitorAgent:e,sequence:(new Date).getTime()};m.echo(JSON.stringify(r))}coach(e,t){const r={cmd:"COACH_CALL",callId:t,agentKey:m.seat.agentKey,monitorAgent:e,sequence:(new Date).getTime()};m.echo(JSON.stringify(r))}updateFollowData(e){const t={cmd:"UPDATE_FOLLOWDATA",followData:e,callId:m.callId,agentKey:m.seat.agentKey,sequence:(new Date).getTime()};m.echo(JSON.stringify(t))}action(e,t){m.sendAction(e,t)}message(e){m.echo(JSON.stringify(e))}on(e,t){m.on(e,t)}off(e,t){if(!m.events[e])return;if(!t)return void(m.events[e]=[]);const r=m.events[e].indexOf(t);r>-1&&m.events[e].splice(r,1)}emit(e,t){m.trigger(e,t)}_stateHandler(t){const{type:r,code:n}=t;if(m.events.btnstate){const e=o[r]||[];m.events.btnstate.forEach(t=>t(e))}if(m.events.agentstate){let t=r;t===e.LOGIN&&0!==Number(n)&&(t=""),m.events.agentstate.forEach(e=>e(t))}}}export{g as VoiceNine};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hzkj/voicenine",
3
- "version": "1.6.0",
3
+ "version": "2.0.0",
4
4
  "description": "js sdk of cloud platform base on janus gateway.",
5
5
  "main": "lib/main.js",
6
6
  "type": "module",