UNPKG

@cloudinary/js-streaming

Version:

Cloudinary client-side package for live video streaming

1 lines 259 kB
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("cloudinaryJsStreaming",[],t):"object"==typeof exports?exports.cloudinaryJsStreaming=t():e.cloudinaryJsStreaming=t()}("undefined"!=typeof self?self:this,(function(){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)r.d(n,i,function(t){return e[t]}.bind(null,i));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=133)}([function(e,t,r){var n=r(2),i=r(19),o=r(12),a=r(13),s=r(20),c=function(e,t,r){var u,d,f,l,p=e&c.F,v=e&c.G,h=e&c.S,m=e&c.P,g=e&c.B,y=v?n:h?n[t]||(n[t]={}):(n[t]||{}).prototype,b=v?i:i[t]||(i[t]={}),S=b.prototype||(b.prototype={});for(u in v&&(r=t),r)f=((d=!p&&y&&void 0!==y[u])?y:r)[u],l=g&&d?s(f,n):m&&"function"==typeof f?s(Function.call,f):f,y&&a(y,u,f,e&c.U),b[u]!=f&&o(b,u,l),m&&S[u]!=f&&(S[u]=f)};n.core=i,c.F=1,c.G=2,c.S=4,c.P=8,c.B=16,c.W=32,c.U=64,c.R=128,e.exports=c},function(e,t,r){var n=r(4);e.exports=function(e){if(!n(e))throw TypeError(e+" is not an object!");return e}},function(e,t){var r=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=r)},function(e,t){e.exports=function(e){try{return!!e()}catch(e){return!0}}},function(e,t){e.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},function(e,t,r){(function(e){n.sessions={},n.isExtensionEnabled=function(){if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)return!0;if(window.navigator.userAgent.match("Chrome")){var e=parseInt(window.navigator.userAgent.match(/Chrome\/(.*) /)[1],10),t=33;return window.navigator.userAgent.match("Linux")&&(t=35),e>=26&&e<=t||n.extension.isInstalled()}return!0};var r={extensionId:"hapfgfdkleiggjjpfpenajgdnfckjpaj",isInstalled:function(){return null!==document.querySelector("#janus-extension-installed")},getScreen:function(e){var t=window.setTimeout((function(){var 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(){var e={};this.cache=e,window.addEventListener("message",(function(t){if(t.origin==window.location.origin)if("janusGotScreen"==t.data.type&&e[t.data.id]){var r=e[t.data.id];if(delete e[t.data.id],""===t.data.sourceId){var n=new Error("NavigatorUserMediaError");n.name="You cancelled the request for permission, giving up...",r(n)}else r(null,t.data.sourceId)}else"janusGetScreenPending"==t.data.type&&(console.log("clearing ",t.data.id),window.clearTimeout(t.data.id))}))}};function n(e){if(!n.initDone)return e.error("Library not initialized"),{};if(!n.isWebrtcSupported())return e.error("WebRTC not supported by this browser"),{};if(n.log("Library initialized: "+n.initDone),(e=e||{}).success="function"==typeof e.success?e.success:n.noop,e.error="function"==typeof e.error?e.error:n.noop,e.destroyed="function"==typeof e.destroyed?e.destroyed:n.noop,!e.server)return e.error("Invalid server url"),{};var t=!1,r=null,i={},o=null,a=null,s=0,c=e.server;n.isArray(c)?(n.log("Multiple servers provided ("+c.length+"), will use the first that works"),c=null,a=e.server,n.debug(a)):0===c.indexOf("ws")?(t=!0,n.log("Using WebSockets to contact Janus: "+c)):(t=!1,n.log("Using REST API to contact Janus: "+c));var u=e.iceServers||[{urls:"stun:stun.l.google.com:19302"}],d=e.iceTransportPolicy,f=e.bundlePolicy,l=!0===e.ipv6,p=!1;void 0!==e.withCredentials&&null!==e.withCredentials&&(p=!0===e.withCredentials);var v=10;void 0!==e.max_poll_events&&null!==e.max_poll_events&&(v=e.max_poll_events),v<1&&(v=1);var h=null;void 0!==e.token&&null!==e.token&&(h=e.token);var 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);var g=25e3;void 0!==e.keepAlivePeriod&&null!==e.keepAlivePeriod&&(g=e.keepAlivePeriod),isNaN(g)&&(g=25e3);var y=6e4;function b(e){var 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&&(y=e.longPollTimeout),isNaN(y)&&(y=6e4);var S=!1,w=null,T={},C=this,k=0,R={};function P(){if(null!=w)if(n.debug("Long poll..."),S){var t=c+"/"+w+"?rid="+(new Date).getTime();v&&(t=t+"&maxev="+v),h&&(t=t+"&token="+encodeURIComponent(h)),m&&(t=t+"&apisecret="+encodeURIComponent(m)),n.httpAPICall(t,{verb:"GET",withCredentials:p,success:x,timeout:y,error:function(t,r){if(n.error(t+":",r),++k>3)return S=!1,void e.error("Lost connection to the server (is it down?)");P()}})}else n.warn("Is the server down? (connected=false)")}function x(e,i){if(k=0,t||null==w||!0===i||P(),t||!n.isArray(e))if("keepalive"!==e.janus)if("ack"!==e.janus)if("success"!==e.janus)if("trickle"===e.janus){if(!(u=e.sender))return void n.warn("Missing sender...");if(!(f=T[u]))return void n.debug("This handle is not attached to this session");var o=e.candidate;n.debug("Got a trickled candidate on session "+w),n.debug(o);var a=f.webrtcStuff;a.pc&&a.remoteSdp?(n.debug("Adding remote candidate:",o),o&&!0!==o.completed?a.pc.addIceCandidate(o):a.pc.addIceCandidate(n.endOfCandidates)):(n.debug("We didn't do setRemoteDescription (trickle got here before the offer?), caching candidate"),a.candidates||(a.candidates=[]),a.candidates.push(o),n.debug(a.candidates))}else{if("webrtcup"===e.janus)return n.debug("Got a webrtcup event on session "+w),n.debug(e),(u=e.sender)?(f=T[u])?void f.webrtcState(!0):void n.debug("This handle is not attached to this session"):void n.warn("Missing sender...");if("hangup"===e.janus){if(n.debug("Got a hangup event on session "+w),n.debug(e),!(u=e.sender))return void n.warn("Missing sender...");if(!(f=T[u]))return void n.debug("This handle is not attached to this session");f.webrtcState(!1,e.reason),f.hangup()}else if("detached"===e.janus){if(n.debug("Got a detached event on session "+w),n.debug(e),!(u=e.sender))return void n.warn("Missing sender...");if(!(f=T[u]))return;f.detached=!0,f.ondetached(),f.detach()}else if("media"===e.janus){if(n.debug("Got a media event on session "+w),n.debug(e),!(u=e.sender))return void n.warn("Missing sender...");if(!(f=T[u]))return void n.debug("This handle is not attached to this session");f.mediaState(e.type,e.receiving)}else if("slowlink"===e.janus){if(n.debug("Got a slowlink event on session "+w),n.debug(e),!(u=e.sender))return void n.warn("Missing sender...");if(!(f=T[u]))return void n.debug("This handle is not attached to this session");f.slowLink(e.uplink,e.lost)}else{if("error"===e.janus){var s,c;if(n.error("Ooops: "+e.error.code+" "+e.error.reason),n.debug(e),s=e.transaction)(c=R[s])&&c(e),delete R[s];return}if("event"===e.janus){var u;if(n.debug("Got a plugin event on session "+w),n.debug(e),!(u=e.sender))return void n.warn("Missing sender...");var d=e.plugindata;if(!d)return void n.warn("Missing plugindata...");n.debug(" -- Event is coming from "+u+" ("+d.plugin+")");var f,l=d.data;if(n.debug(l),!(f=T[u]))return void n.warn("This handle is not attached to this session");var p=e.jsep;p&&(n.debug("Handling SDP as well..."),n.debug(p));var v=f.onmessage;v?(n.debug("Notifying application..."),v(l,p)):n.debug("No provided notification callback")}else{if("timeout"===e.janus)return n.error("Timeout on session "+w),n.debug(e),void(t&&r.close(3504,"Gateway timeout"));n.warn("Unknown message/event '"+e.janus+"' on session "+w),n.debug(e)}}}else n.debug("Got a success on session "+w),n.debug(e),(s=e.transaction)&&((c=R[s])&&c(e),delete R[s]);else n.debug("Got an ack on session "+w),n.debug(e),(s=e.transaction)&&((c=R[s])&&c(e),delete R[s]);else n.vdebug("Got a keepalive on session "+w);else for(var h=0;h<e.length;h++)x(e[h],!0)}function E(){if(c&&t&&S){o=setTimeout(E,g);var e={janus:"keepalive",session_id:w,transaction:n.randomString(12)};h&&(e.token=h),m&&(e.apisecret=m),r.send(JSON.stringify(e))}}function _(u){var d=n.randomString(12),f={janus:"create",transaction:d};if(u.reconnect&&(S=!1,f.janus="claim",f.session_id=w,r&&(r.onopen=null,r.onerror=null,r.onclose=null,o&&(clearTimeout(o),o=null))),h&&(f.token=h),m&&(f.apisecret=m),!c&&n.isArray(a)&&(0===(c=a[s]).indexOf("ws")?(t=!0,n.log("Server #"+(s+1)+": trying WebSockets to contact Janus ("+c+")")):(t=!1,n.log("Server #"+(s+1)+": trying REST API to contact Janus ("+c+")"))),t)for(var l in r=n.newWebSocket(c,"janus-protocol"),i={error:function(){if(n.error("Error connecting to the Janus WebSockets server... "+c),n.isArray(a)&&!u.reconnect)return++s==a.length?void u.error("Error connecting to any of the provided Janus servers: Is the server down?"):(c=null,void setTimeout((function(){_(u)}),200));u.error("Error connecting to the Janus WebSockets server: Is the server down?")},open:function(){R[d]=function(e){if(n.debug(e),"success"!==e.janus)return n.error("Ooops: "+e.error.code+" "+e.error.reason),void u.error(e.error.reason);o=setTimeout(E,g),S=!0,w=e.session_id?e.session_id:e.data.id,u.reconnect?n.log("Claimed session: "+w):n.log("Created session: "+w),n.sessions[w]=C,u.success()},r.send(JSON.stringify(f))},message:function(e){x(JSON.parse(e.data))},close:function(){c&&S&&(S=!1,e.error("Lost connection to the server (is it down?)"))}})r.addEventListener(l,i[l]);else n.httpAPICall(c,{verb:"POST",withCredentials:p,body:f,success:function(e){if(n.debug(e),"success"!==e.janus)return n.error("Ooops: "+e.error.code+" "+e.error.reason),void u.error(e.error.reason);S=!0,w=e.session_id?e.session_id:e.data.id,u.reconnect?n.log("Claimed session: "+w):n.log("Created session: "+w),n.sessions[w]=C,P(),u.success()},error:function(e,t){if(n.error(e+":",t),n.isArray(a)&&!u.reconnect)return++s==a.length?void u.error("Error connecting to any of the provided Janus servers: Is the server down?"):(c=null,void setTimeout((function(){_(u)}),200));""===t?u.error(e+": Is the server down?"):u.error(e+": "+t)}})}function O(e,i){if((i=i||{}).success="function"==typeof i.success?i.success:n.noop,i.error="function"==typeof i.error?i.error:n.noop,!S)return n.warn("Is the server down? (connected=false)"),void i.error("Is the server down? (connected=false)");var o=T[e];if(!o||!o.webrtcStuff)return n.warn("Invalid handle"),void i.error("Invalid handle");var a=i.message,s=i.jsep,u=n.randomString(12),d={janus:"message",body:a,transaction:u};if(o.token&&(d.token=o.token),m&&(d.apisecret=m),s&&(d.jsep=s),n.debug("Sending message to plugin (handle="+e+"):"),n.debug(d),t)return d.session_id=w,d.handle_id=e,R[u]=function(e){if(n.debug("Message sent!"),n.debug(e),"success"===e.janus){var t=e.plugindata;if(!t)return n.warn("Request succeeded, but missing plugindata..."),void i.success();n.log("Synchronous transaction successful ("+t.plugin+")");var r=t.data;return n.debug(r),void i.success(r)}"ack"===e.janus?i.success():e.error?(n.error("Ooops: "+e.error.code+" "+e.error.reason),i.error(e.error.code+" "+e.error.reason)):(n.error("Unknown error"),i.error("Unknown error"))},void r.send(JSON.stringify(d));n.httpAPICall(c+"/"+w+"/"+e,{verb:"POST",withCredentials:p,body:d,success:function(e){if(n.debug("Message sent!"),n.debug(e),"success"===e.janus){var t=e.plugindata;if(!t)return n.warn("Request succeeded, but missing plugindata..."),void i.success();n.log("Synchronous transaction successful ("+t.plugin+")");var r=t.data;return n.debug(r),void i.success(r)}"ack"===e.janus?i.success():e.error?(n.error("Ooops: "+e.error.code+" "+e.error.reason),i.error(e.error.code+" "+e.error.reason)):(n.error("Unknown error"),i.error("Unknown error"))},error:function(e,t){n.error(e+":",t),i.error(e+": "+t)}})}function D(e,i){if(S){var o=T[e];if(o&&o.webrtcStuff){var a={janus:"trickle",candidate:i,transaction:n.randomString(12)};if(o.token&&(a.token=o.token),m&&(a.apisecret=m),n.vdebug("Sending trickle candidate (handle="+e+"):"),n.vdebug(a),t)return a.session_id=w,a.handle_id=e,void r.send(JSON.stringify(a));n.httpAPICall(c+"/"+w+"/"+e,{verb:"POST",withCredentials:p,body:a,success:function(e){n.vdebug("Candidate sent!"),n.vdebug(e),"ack"===e.janus||n.error("Ooops: "+e.error.code+" "+e.error.reason)},error:function(e,t){n.error(e+":",t)}})}else n.warn("Invalid handle")}else n.warn("Is the server down? (connected=false)")}function M(e,t,r,i){var o=T[e];if(o&&o.webrtcStuff){var a=o.webrtcStuff,s=function(e){n.log("Received state change on data channel:",e);var t=e.target.label,r=a.dataChannel[t]?a.dataChannel[t].readyState:"null";if(n.log("State change on <"+t+"> data channel: "+r),"open"===r){if(a.dataChannel[t].pending&&a.dataChannel[t].pending.length>0){for(var i of(n.log("Sending pending messages on <"+t+">:",a.dataChannel[t].pending.length),a.dataChannel[t].pending))n.log("Sending string on data channel <"+t+">: "+i),a.dataChannel[t].send(i);a.dataChannel[t].pending=[]}o.ondataopen(t)}};a.dataChannel[t]=r||a.pc.createDataChannel(t,{ordered:!1}),a.dataChannel[t].onmessage=function(e){n.log("Received message on data channel:",e);var t=e.target.label;o.ondata(e.data,t)},a.dataChannel[t].onopen=s,a.dataChannel[t].onclose=s,a.dataChannel[t].onerror=function(e){n.error("Got error on data channel:",e)},a.dataChannel[t].pending=[],i&&a.dataChannel[t].pending.push(i)}else n.warn("Invalid handle")}function A(e,t){(t=t||{}).success="function"==typeof t.success?t.success:n.noop,t.error="function"==typeof t.error?t.error:n.noop;var r=T[e];if(!r||!r.webrtcStuff)return n.warn("Invalid handle"),void t.error("Invalid handle");var i=r.webrtcStuff,o=t.text;if(!o)return n.warn("Invalid text"),void t.error("Invalid text");var a=t.label?t.label:n.dataChanDefaultLabel;return i.dataChannel[a]?"open"!==i.dataChannel[a].readyState?(i.dataChannel[a].pending.push(o),void t.success()):(n.log("Sending string on data channel <"+a+">: "+o),i.dataChannel[a].send(o),void t.success()):(M(e,a,!1,o),void t.success())}function I(e,t){(t=t||{}).success="function"==typeof t.success?t.success:n.noop,t.error="function"==typeof t.error?t.error:n.noop;var r=T[e];if(!r||!r.webrtcStuff)return n.warn("Invalid handle"),void t.error("Invalid handle");var i=r.webrtcStuff;if(!i.dtmfSender){if(i.pc){var o=i.pc.getSenders().find((function(e){return e.track&&"audio"===e.track.kind}));if(!o)return n.warn("Invalid DTMF configuration (no audio track)"),void t.error("Invalid DTMF configuration (no audio track)");i.dtmfSender=o.dtmf,i.dtmfSender&&(n.log("Created DTMF Sender"),i.dtmfSender.ontonechange=function(e){n.debug("Sent DTMF tone: "+e.tone)})}if(!i.dtmfSender)return n.warn("Invalid DTMF configuration"),void t.error("Invalid DTMF configuration")}var a=t.dtmf;if(!a)return n.warn("Invalid DTMF parameters"),void t.error("Invalid DTMF parameters");var s=a.tones;if(!s)return n.warn("Invalid DTMF string"),void t.error("Invalid DTMF string");var c="number"==typeof a.duration?a.duration:500,u="number"==typeof a.gap?a.gap:50;n.debug("Sending DTMF string "+s+" (duration "+c+"ms, gap "+u+"ms)"),i.dtmfSender.insertDTMF(s,c,u),t.success()}function j(e,i){(i=i||{}).success="function"==typeof i.success?i.success:n.noop,i.error="function"==typeof i.error?i.error:n.noop;var o=!0;void 0!==i.asyncRequest&&null!==i.asyncRequest&&(o=!0===i.asyncRequest);var a=!0;void 0!==i.noRequest&&null!==i.noRequest&&(a=!0===i.noRequest),n.log("Destroying handle "+e+" (async="+o+")"),W(e);var s=T[e];if(!s||s.detached)return delete T[e],void i.success();if(a)return delete T[e],void i.success();if(!S)return n.warn("Is the server down? (connected=false)"),void i.error("Is the server down? (connected=false)");var u={janus:"detach",transaction:n.randomString(12)};if(s.token&&(u.token=s.token),m&&(u.apisecret=m),t)return u.session_id=w,u.handle_id=e,r.send(JSON.stringify(u)),delete T[e],void i.success();n.httpAPICall(c+"/"+w+"/"+e,{verb:"POST",async:o,withCredentials:p,body:u,success:function(t){n.log("Destroyed handle:"),n.debug(t),"success"!==t.janus&&n.error("Ooops: "+t.error.code+" "+t.error.reason),delete T[e],i.success()},error:function(t,r){n.error(t+":",r),delete T[e],i.success()}})}function L(e,t,r,i,o){var a=T[e];if(!a||!a.webrtcStuff)return n.warn("Invalid handle"),void i.error("Invalid handle");var s=a.webrtcStuff;n.debug("streamsDone:",o),o&&(n.debug(" -- Audio tracks:",o.getAudioTracks()),n.debug(" -- Video tracks:",o.getVideoTracks()));var c=!1;if(s.myStream&&r.update&&!s.streamExternal){if((!r.update&&z(r)||r.update&&(r.addAudio||r.replaceAudio))&&o.getAudioTracks()&&o.getAudioTracks().length)if(s.myStream.addTrack(o.getAudioTracks()[0]),n.unifiedPlan){n.log((r.replaceAudio?"Replacing":"Adding")+" audio track:",o.getAudioTracks()[0]);var p=null;if((h=s.pc.getTransceivers())&&h.length>0)for(var v of h)if(v.sender&&v.sender.track&&"audio"===v.sender.track.kind||v.receiver&&v.receiver.track&&"audio"===v.receiver.track.kind){p=v;break}p&&p.sender?p.sender.replaceTrack(o.getAudioTracks()[0]):s.pc.addTrack(o.getAudioTracks()[0],o)}else n.log((r.replaceAudio?"Replacing":"Adding")+" audio track:",o.getAudioTracks()[0]),s.pc.addTrack(o.getAudioTracks()[0],o);if((!r.update&&H(r)||r.update&&(r.addVideo||r.replaceVideo))&&o.getVideoTracks()&&o.getVideoTracks().length)if(s.myStream.addTrack(o.getVideoTracks()[0]),n.unifiedPlan){n.log((r.replaceVideo?"Replacing":"Adding")+" video track:",o.getVideoTracks()[0]);var h,m=null;if((h=s.pc.getTransceivers())&&h.length>0)for(var v of h)if(v.sender&&v.sender.track&&"video"===v.sender.track.kind||v.receiver&&v.receiver.track&&"video"===v.receiver.track.kind){m=v;break}m&&m.sender?m.sender.replaceTrack(o.getVideoTracks()[0]):s.pc.addTrack(o.getVideoTracks()[0],o)}else n.log((r.replaceVideo?"Replacing":"Adding")+" video track:",o.getVideoTracks()[0]),s.pc.addTrack(o.getVideoTracks()[0],o)}else s.myStream=o,c=!0;if(!s.pc){var g={iceServers:u,iceTransportPolicy:d,bundlePolicy:f};"chrome"===n.webRTCAdapter.browserDetails.browser&&(g.sdpSemantics=n.webRTCAdapter.browserDetails.version<72?"plan-b":"unified-plan");var y={optional:[{DtlsSrtpKeyAgreement:!0}]};if(l&&y.optional.push({googIPv6:!0}),i.rtcConstraints&&"object"==typeof i.rtcConstraints)for(var S in n.debug("Adding custom PeerConnection constraints:",i.rtcConstraints),i.rtcConstraints)y.optional.push(i.rtcConstraints[S]);"edge"===n.webRTCAdapter.browserDetails.browser&&(g.bundlePolicy="max-bundle"),n.log("Creating PeerConnection"),n.debug(y),s.pc=new RTCPeerConnection(g,y),n.debug(s.pc),s.pc.getStats&&(s.volume={},s.bitrate.value="0 kbits/sec"),n.log("Preparing local SDP and gathering candidates (trickle="+s.trickle+")"),s.pc.oniceconnectionstatechange=function(e){s.pc&&a.iceState(s.pc.iceConnectionState)},s.pc.onicecandidate=function(t){if(!t.candidate||"edge"===n.webRTCAdapter.browserDetails.browser&&t.candidate.candidate.indexOf("endOfCandidates")>0)n.log("End of candidates."),s.iceDone=!0,!0===s.trickle?D(e,{completed:!0}):function(e,t){(t=t||{}).success="function"==typeof t.success?t.success:n.noop,t.error="function"==typeof t.error?t.error:n.noop;var r=T[e];if(!r||!r.webrtcStuff)return void n.warn("Invalid handle, not sending anything");var i=r.webrtcStuff;if(n.log("Sending offer/answer SDP..."),!i.mySdp)return void n.warn("Local SDP instance is invalid, not sending anything...");i.mySdp={type:i.pc.localDescription.type,sdp:i.pc.localDescription.sdp},!1===i.trickle&&(i.mySdp.trickle=!1);n.debug(t),i.sdpSent=!0,t.success(i.mySdp)}(e,i);else{var r={candidate:t.candidate.candidate,sdpMid:t.candidate.sdpMid,sdpMLineIndex:t.candidate.sdpMLineIndex};!0===s.trickle&&D(e,r)}},s.pc.ontrack=function(e){n.log("Handling Remote Track"),n.debug(e),e.streams&&(s.remoteStream=e.streams[0],a.onremotestream(s.remoteStream),e.track.onended||(n.log("Adding onended callback to track:",e.track),e.track.onended=function(e){n.log("Remote track muted/removed:",e),s.remoteStream&&(s.remoteStream.removeTrack(e.target),a.onremotestream(s.remoteStream))},e.track.onmute=e.track.onended,e.track.onunmute=function(e){n.log("Remote track flowing again:",e);try{s.remoteStream.addTrack(e.target),a.onremotestream(s.remoteStream)}catch(e){n.error(e)}}))}}if(c&&o){n.log("Adding local stream");var w=!0===i.simulcast2;o.getTracks().forEach((function(e){if(n.log("Adding local track:",e),w)if("audio"===e.kind)s.pc.addTrack(e,o);else{n.log("Enabling rid-based simulcasting:",e);const t=b(i.simulcastMaxBitrates);s.pc.addTransceiver(e,{direction:"sendrecv",streams:[o],sendEncodings:[{rid:"h",active:!0,maxBitrate:t.high},{rid:"m",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:2},{rid:"l",active:!0,maxBitrate:t.low,scaleResolutionDownBy:4}]})}else s.pc.addTrack(e,o)}))}(function(e){if(n.debug("isDataEnabled:",e),"edge"===n.webRTCAdapter.browserDetails.browser)return n.warn("Edge doesn't support data channels yet"),!1;return null!=e&&!0===e.data})(r)&&!s.dataChannel[n.dataChanDefaultLabel]&&(n.log("Creating data channel"),M(e,n.dataChanDefaultLabel,!1),s.pc.ondatachannel=function(t){n.log("Data channel created by Janus:",t),M(e,t.channel.label,t.channel)}),s.myStream&&a.onlocalstream(s.myStream),t?s.pc.setRemoteDescription(t).then((function(){if(n.log("Remote description accepted!"),s.remoteSdp=t.sdp,s.candidates&&s.candidates.length>0){for(var o=0;o<s.candidates.length;o++){var a=s.candidates[o];n.debug("Adding remote candidate:",a),a&&!0!==a.completed?s.pc.addIceCandidate(a):s.pc.addIceCandidate(n.endOfCandidates)}s.candidates=[]}!function(e,t,r){(r=r||{}).success="function"==typeof r.success?r.success:n.noop,r.error="function"==typeof r.error?r.error:n.noop,r.customizeSdp="function"==typeof r.customizeSdp?r.customizeSdp:n.noop;var i=T[e];if(!i||!i.webrtcStuff)return n.warn("Invalid handle"),void r.error("Invalid handle");var o=i.webrtcStuff,a=!0===r.simulcast;a?n.log("Creating answer (iceDone="+o.iceDone+", simulcast="+a+")"):n.log("Creating answer (iceDone="+o.iceDone+")");var s=null;if(n.unifiedPlan){s={};var c=null,u=null,d=o.pc.getTransceivers();if(d&&d.length>0)for(var f of d)f.sender&&f.sender.track&&"audio"===f.sender.track.kind||f.receiver&&f.receiver.track&&"audio"===f.receiver.track.kind?c||(c=f):(f.sender&&f.sender.track&&"video"===f.sender.track.kind||f.receiver&&f.receiver.track&&"video"===f.receiver.track.kind)&&(u||(u=f));var l=z(t),p=q(t);if(l||p){if(l&&p){if(c)try{c.setDirection?c.setDirection("sendrecv"):c.direction="sendrecv",n.log("Setting audio transceiver to sendrecv:",c)}catch(e){n.error(e)}}else if(l&&!p)try{c&&(c.setDirection?c.setDirection("sendonly"):c.direction="sendonly",n.log("Setting audio transceiver to sendonly:",c))}catch(e){n.error(e)}else if(!l&&p)if(c)try{c.setDirection?c.setDirection("recvonly"):c.direction="recvonly",n.log("Setting audio transceiver to recvonly:",c)}catch(e){n.error(e)}else c=o.pc.addTransceiver("audio",{direction:"recvonly"}),n.log("Adding recvonly audio transceiver:",c)}else if(t.removeAudio&&c)try{c.setDirection?c.setDirection("inactive"):c.direction="inactive",n.log("Setting audio transceiver to inactive:",c)}catch(e){n.error(e)}var v=H(t),h=K(t);if(v||h){if(v&&h){if(u)try{u.setDirection?u.setDirection("sendrecv"):u.direction="sendrecv",n.log("Setting video transceiver to sendrecv:",u)}catch(e){n.error(e)}}else if(v&&!h){if(u)try{u.setDirection?u.setDirection("sendonly"):u.direction="sendonly",n.log("Setting video transceiver to sendonly:",u)}catch(e){n.error(e)}}else if(!v&&h)if(u)try{u.setDirection?u.setDirection("recvonly"):u.direction="recvonly",n.log("Setting video transceiver to recvonly:",u)}catch(e){n.error(e)}else u=o.pc.addTransceiver("video",{direction:"recvonly"}),n.log("Adding recvonly video transceiver:",u)}else if(t.removeVideo&&u)try{u.setDirection?u.setDirection("inactive"):u.direction="inactive",n.log("Setting video transceiver to inactive:",u)}catch(e){n.error(e)}}else s="firefox"===n.webRTCAdapter.browserDetails.browser||"edge"===n.webRTCAdapter.browserDetails.browser?{offerToReceiveAudio:q(t),offerToReceiveVideo:K(t)}:{mandatory:{OfferToReceiveAudio:q(t),OfferToReceiveVideo:K(t)}};n.debug(s);var m=H(t);if(m&&a&&"firefox"===n.webRTCAdapter.browserDetails.browser){n.log("Enabling Simulcasting for Firefox (RID)");var g=o.pc.getSenders()[1];n.log(g);var y=g.getParameters();n.log(y);const e=b(r.simulcastMaxBitrates);g.setParameters({encodings:[{rid:"high",active:!0,priority:"high",maxBitrate:e.high},{rid:"medium",active:!0,priority:"medium",maxBitrate:e.medium},{rid:"low",active:!0,priority:"low",maxBitrate:e.low}]})}o.pc.createAnswer(s).then((function(e){n.debug(e);var t={type:e.type,sdp:e.sdp};r.customizeSdp(t),e.sdp=t.sdp,n.log("Setting local description"),m&&a&&("chrome"===n.webRTCAdapter.browserDetails.browser?n.warn("simulcast=true, but this is an answer, and video breaks in Chrome if we enable it"):"firefox"!==n.webRTCAdapter.browserDetails.browser&&n.warn("simulcast=true, but this is not Chrome nor Firefox, ignoring")),o.mySdp=e.sdp,o.pc.setLocalDescription(e).catch(r.error),o.mediaConstraints=s,o.iceDone||o.trickle?r.success(e):n.log("Waiting for all candidates...")}),r.error)}(e,r,i)}),i.error):function(e,t,r){(r=r||{}).success="function"==typeof r.success?r.success:n.noop,r.error="function"==typeof r.error?r.error:n.noop,r.customizeSdp="function"==typeof r.customizeSdp?r.customizeSdp:n.noop;var i=T[e];if(!i||!i.webrtcStuff)return n.warn("Invalid handle"),void r.error("Invalid handle");var o=i.webrtcStuff,a=!0===r.simulcast;a?n.log("Creating offer (iceDone="+o.iceDone+", simulcast="+a+")"):n.log("Creating offer (iceDone="+o.iceDone+")");var s={};if(n.unifiedPlan){var c=null,u=null,d=o.pc.getTransceivers();if(d&&d.length>0)for(var f of d)f.sender&&f.sender.track&&"audio"===f.sender.track.kind||f.receiver&&f.receiver.track&&"audio"===f.receiver.track.kind?c||(c=f):(f.sender&&f.sender.track&&"video"===f.sender.track.kind||f.receiver&&f.receiver.track&&"video"===f.receiver.track.kind)&&(u||(u=f));var l=z(t),p=q(t);l||p?l&&p?c&&(c.setDirection?c.setDirection("sendrecv"):c.direction="sendrecv",n.log("Setting audio transceiver to sendrecv:",c)):l&&!p?c&&(c.setDirection?c.setDirection("sendonly"):c.direction="sendonly",n.log("Setting audio transceiver to sendonly:",c)):!l&&p&&(c?(c.setDirection?c.setDirection("recvonly"):c.direction="recvonly",n.log("Setting audio transceiver to recvonly:",c)):(c=o.pc.addTransceiver("audio",{direction:"recvonly"}),n.log("Adding recvonly audio transceiver:",c))):t.removeAudio&&c&&(c.setDirection?c.setDirection("inactive"):c.direction="inactive",n.log("Setting audio transceiver to inactive:",c));var v=H(t),h=K(t);v||h?v&&h?u&&(u.setDirection?u.setDirection("sendrecv"):u.direction="sendrecv",n.log("Setting video transceiver to sendrecv:",u)):v&&!h?u&&(u.setDirection?u.setDirection("sendonly"):u.direction="sendonly",n.log("Setting video transceiver to sendonly:",u)):!v&&h&&(u?(u.setDirection?u.setDirection("recvonly"):u.direction="recvonly",n.log("Setting video transceiver to recvonly:",u)):(u=o.pc.addTransceiver("video",{direction:"recvonly"}),n.log("Adding recvonly video transceiver:",u))):t.removeVideo&&u&&(u.setDirection?u.setDirection("inactive"):u.direction="inactive",n.log("Setting video transceiver to inactive:",u))}else s.offerToReceiveAudio=q(t),s.offerToReceiveVideo=K(t);!0===r.iceRestart&&(s.iceRestart=!0);n.debug(s);var m=H(t);if(m&&a&&"firefox"===n.webRTCAdapter.browserDetails.browser){n.log("Enabling Simulcasting for Firefox (RID)");var g=o.pc.getSenders().find((function(e){return"video"==e.track.kind}));if(g){var y=g.getParameters();y||(y={});const e=b(r.simulcastMaxBitrates);y.encodings=[{rid:"h",active:!0,maxBitrate:e.high},{rid:"m",active:!0,maxBitrate:e.medium,scaleResolutionDownBy:2},{rid:"l",active:!0,maxBitrate:e.low,scaleResolutionDownBy:4}],g.setParameters(y)}}o.pc.createOffer(s).then((function(e){n.debug(e);var t={type:e.type,sdp:e.sdp};r.customizeSdp(t),e.sdp=t.sdp,n.log("Setting local description"),m&&a&&("chrome"===n.webRTCAdapter.browserDetails.browser||"safari"===n.webRTCAdapter.browserDetails.browser?(n.log("Enabling Simulcasting for Chrome (SDP munging)"),e.sdp=function(e){for(var t=e.split("\r\n"),r=!1,i=[-1],o=[-1],a=null,s=null,c=null,u=null,d=-1,f=0;f<t.length;f++){if(p=t[f].match(/m=(\w+) */)){if("video"===p[1]){if(!(i[0]<0)){d=f;break}r=!0}else if(i[0]>-1){d=f;break}}else if(r){var l=t[f].match(/a=ssrc-group:FID (\d+) (\d+)/);if(l)i[0]=l[1],o[0]=l[2],t.splice(f,1),f--;else{if(i[0]){if((h=t[f].match("a=ssrc:"+i[0]+" cname:(.+)"))&&(a=h[1]),(h=t[f].match("a=ssrc:"+i[0]+" msid:(.+)"))&&(s=h[1]),(h=t[f].match("a=ssrc:"+i[0]+" mslabel:(.+)"))&&(c=h[1]),(h=t[f].match("a=ssrc:"+i[0]+" label:(.+)"))&&(u=h[1]),0===t[f].indexOf("a=ssrc:"+o[0])){t.splice(f,1),f--;continue}if(0===t[f].indexOf("a=ssrc:"+i[0])){t.splice(f,1),f--;continue}}0!=t[f].length||(t.splice(f,1),f--)}}}if(i[0]<0){d=-1,r=!1;for(f=0;f<t.length;f++){var p;if(p=t[f].match(/m=(\w+) */)){if("video"===p[1]){if(!(i[0]<0)){d=f;break}r=!0}else if(i[0]>-1){d=f;break}}else if(r){if(i[0]<0){var v=t[f].match(/a=ssrc:(\d+)/);if(v){i[0]=v[1],t.splice(f,1),f--;continue}}else{var h;if((h=t[f].match("a=ssrc:"+i[0]+" cname:(.+)"))&&(a=h[1]),(h=t[f].match("a=ssrc:"+i[0]+" msid:(.+)"))&&(s=h[1]),(h=t[f].match("a=ssrc:"+i[0]+" mslabel:(.+)"))&&(c=h[1]),(h=t[f].match("a=ssrc:"+i[0]+" label:(.+)"))&&(u=h[1]),0===t[f].indexOf("a=ssrc:"+o[0])){t.splice(f,1),f--;continue}if(0===t[f].indexOf("a=ssrc:"+i[0])){t.splice(f,1),f--;continue}}0!=t[f].length||(t.splice(f,1),f--)}}}if(i[0]<0)return n.warn("Couldn't find the video SSRC, simulcasting NOT enabled"),e;d<0&&(d=t.length);i[1]=Math.floor(4294967295*Math.random()),i[2]=Math.floor(4294967295*Math.random()),o[1]=Math.floor(4294967295*Math.random()),o[2]=Math.floor(4294967295*Math.random());for(f=0;f<i.length;f++)a&&(t.splice(d,0,"a=ssrc:"+i[f]+" cname:"+a),d++),s&&(t.splice(d,0,"a=ssrc:"+i[f]+" msid:"+s),d++),c&&(t.splice(d,0,"a=ssrc:"+i[f]+" mslabel:"+c),d++),u&&(t.splice(d,0,"a=ssrc:"+i[f]+" label:"+u),d++),a&&(t.splice(d,0,"a=ssrc:"+o[f]+" cname:"+a),d++),s&&(t.splice(d,0,"a=ssrc:"+o[f]+" msid:"+s),d++),c&&(t.splice(d,0,"a=ssrc:"+o[f]+" mslabel:"+c),d++),u&&(t.splice(d,0,"a=ssrc:"+o[f]+" label:"+u),d++);t.splice(d,0,"a=ssrc-group:FID "+i[2]+" "+o[2]),t.splice(d,0,"a=ssrc-group:FID "+i[1]+" "+o[1]),t.splice(d,0,"a=ssrc-group:FID "+i[0]+" "+o[0]),t.splice(d,0,"a=ssrc-group:SIM "+i[0]+" "+i[1]+" "+i[2]),(e=t.join("\r\n")).endsWith("\r\n")||(e+="\r\n");return e}(e.sdp)):"firefox"!==n.webRTCAdapter.browserDetails.browser&&n.warn("simulcast=true, but this is not Chrome nor Firefox, ignoring")),o.mySdp=e.sdp,o.pc.setLocalDescription(e).catch(r.error),o.mediaConstraints=s,o.iceDone||o.trickle?(n.log("Offer ready"),n.debug(r),r.success(e)):n.log("Waiting for all candidates...")}),r.error)}(e,r,i)}function N(e,t,r){(r=r||{}).success="function"==typeof r.success?r.success:n.noop,r.error="function"==typeof r.error?r.error:J;var i=r.jsep;if(t&&i)return n.error("Provided a JSEP to a createOffer"),void r.error("Provided a JSEP to a createOffer");if(!(t||i&&i.type&&i.sdp))return n.error("A valid JSEP is required for createAnswer"),void r.error("A valid JSEP is required for createAnswer");r.media="object"==typeof r.media&&r.media?r.media:{audio:!0,video:!0};var o=r.media,a=T[e];if(!a||!a.webrtcStuff)return n.warn("Invalid handle"),void r.error("Invalid handle");var s,c=a.webrtcStuff;if(c.trickle=(s=r.trickle,n.debug("isTrickleEnabled:",s),!1!==s),c.pc){if(n.log("Updating existing media session"),o.update=!0,r.stream)r.stream!==c.myStream&&n.log("Renegotiation involves a new external stream");else{if(o.addAudio){if(o.keepAudio=!1,o.replaceAudio=!1,o.removeAudio=!1,o.audioSend=!0,c.myStream&&c.myStream.getAudioTracks()&&c.myStream.getAudioTracks().length)return n.error("Can't add audio stream, there already is one"),void r.error("Can't add audio stream, there already is one")}else o.removeAudio?(o.keepAudio=!1,o.replaceAudio=!1,o.addAudio=!1,o.audioSend=!1):o.replaceAudio&&(o.keepAudio=!1,o.addAudio=!1,o.removeAudio=!1,o.audioSend=!0);if(c.myStream?c.myStream.getAudioTracks()&&0!==c.myStream.getAudioTracks().length?!z(o)||o.removeAudio||o.replaceAudio||(o.keepAudio=!0):(o.replaceAudio&&(o.keepAudio=!1,o.replaceAudio=!1,o.addAudio=!0,o.audioSend=!0),z(o)&&(o.keepVideo=!1,o.addAudio=!0)):(o.replaceAudio&&(o.keepAudio=!1,o.replaceAudio=!1,o.addAudio=!0,o.audioSend=!0),z(o)&&(o.keepAudio=!1,o.addAudio=!0)),o.addVideo){if(o.keepVideo=!1,o.replaceVideo=!1,o.removeVideo=!1,o.videoSend=!0,c.myStream&&c.myStream.getVideoTracks()&&c.myStream.getVideoTracks().length)return n.error("Can't add video stream, there already is one"),void r.error("Can't add video stream, there already is one")}else o.removeVideo?(o.keepVideo=!1,o.replaceVideo=!1,o.addVideo=!1,o.videoSend=!1):o.replaceVideo&&(o.keepVideo=!1,o.addVideo=!1,o.removeVideo=!1,o.videoSend=!0);c.myStream&&c.myStream.getVideoTracks()&&0!==c.myStream.getVideoTracks().length?!H(o)||o.removeVideo||o.replaceVideo||(o.keepVideo=!0):(o.replaceVideo&&(o.keepVideo=!1,o.replaceVideo=!1,o.addVideo=!0,o.videoSend=!0),H(o)&&(o.keepVideo=!1,o.addVideo=!0)),o.addData&&(o.data=!0)}if(z(o)&&o.keepAudio&&H(o)&&o.keepVideo)return a.consentDialog(!1),void L(e,i,o,r,c.myStream)}else o.update=!1,o.keepAudio=!1,o.keepVideo=!1;if(o.update&&!c.streamExternal){if(o.removeAudio||o.replaceAudio){if(c.myStream&&c.myStream.getAudioTracks()&&c.myStream.getAudioTracks().length){var u=c.myStream.getAudioTracks()[0];n.log("Removing audio track:",u),c.myStream.removeTrack(u);try{u.stop()}catch(e){}}if(c.pc.getSenders()&&c.pc.getSenders().length){var d=!0;if(o.replaceAudio&&n.unifiedPlan&&(d=!1),d)for(var u of c.pc.getSenders())u&&u.track&&"audio"===u.track.kind&&(n.log("Removing audio sender:",u),c.pc.removeTrack(u))}}if(o.removeVideo||o.replaceVideo){if(c.myStream&&c.myStream.getVideoTracks()&&c.myStream.getVideoTracks().length){u=c.myStream.getVideoTracks()[0];n.log("Removing video track:",u),c.myStream.removeTrack(u);try{u.stop()}catch(e){}}if(c.pc.getSenders()&&c.pc.getSenders().length){var f=!0;if(o.replaceVideo&&n.unifiedPlan&&(f=!1),f)for(var u of c.pc.getSenders())u&&u.track&&"video"===u.track.kind&&(n.log("Removing video sender:",u),c.pc.removeTrack(u))}}}if(r.stream){var l=r.stream;if(n.log("MediaStream provided by the application"),n.debug(l),o.update&&c.myStream&&c.myStream!==r.stream&&!c.streamExternal){try{var p=c.myStream.getTracks();for(var v of p)n.log(v),v&&v.stop()}catch(e){}c.myStream=null}return c.streamExternal=!0,a.consentDialog(!1),void L(e,i,o,r,l)}if(z(o)||H(o)){if(!n.isGetUserMediaAvailable())return void r.error("getUserMedia not available");var h={mandatory:{},optional:[]};a.consentDialog(!0);var m=z(o);m&&o&&"object"==typeof o.audio&&(m=o.audio);var g=H(o);if(g&&o){var y=!0===r.simulcast,b=!0===r.simulcast2;if(!y&&!b||i||o.video||(o.video="hires"),o.video&&"screen"!=o.video&&"window"!=o.video)if("object"==typeof o.video)g=o.video;else{var S=0,w=0;"lowres"===o.video?(w=240,240,S=320):"lowres-16:9"===o.video?(w=180,180,S=320):"hires"===o.video||"hires-16:9"===o.video||"hdres"===o.video?(w=720,720,S=1280):"fhdres"===o.video?(w=1080,1080,S=1920):"4kres"===o.video?(w=2160,2160,S=3840):"stdres"===o.video?(w=480,480,S=640):"stdres-16:9"===o.video?(w=360,360,S=640):(n.log("Default video setting is stdres 4:3"),w=480,480,S=640),n.log("Adding media constraint:",o.video),g={height:{ideal:w},width:{ideal:S}},n.log("Adding video constraint:",g)}else if("screen"===o.video||"window"===o.video){if(o.screenshareFrameRate||(o.screenshareFrameRate=3),navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)return void navigator.mediaDevices.getDisplayMedia({video:!0,audio:o.captureDesktopAudio}).then((function(t){a.consentDialog(!1),z(o)&&!o.keepAudio?navigator.mediaDevices.getUserMedia({audio:!0,video:!1}).then((function(n){t.addTrack(n.getAudioTracks()[0]),L(e,i,o,r,t)})):L(e,i,o,r,t)}),(function(e){a.consentDialog(!1),r.error(e)}));function C(t,n){a.consentDialog(!1),t?r.error(t):L(e,i,o,r,n)}function k(e,t,r){n.log("Adding media constraint (screen capture)"),n.debug(e),navigator.mediaDevices.getUserMedia(e).then((function(e){r?navigator.mediaDevices.getUserMedia({audio:!0,video:!1}).then((function(r){e.addTrack(r.getAudioTracks()[0]),t(null,e)})):t(null,e)})).catch((function(e){a.consentDialog(!1),t(e)}))}if("chrome"===n.webRTCAdapter.browserDetails.browser){var R=n.webRTCAdapter.browserDetails.version,P=33;window.navigator.userAgent.match("Linux")&&(P=35),R>=26&&R<=P?k(h={video:{mandatory:{googLeakyBucket:!0,maxWidth:window.screen.width,maxHeight:window.screen.height,minFrameRate:o.screenshareFrameRate,maxFrameRate:o.screenshareFrameRate,chromeMediaSource:"screen"}},audio:z(o)&&!o.keepAudio},C):n.extension.getScreen((function(e,t){if(e)return a.consentDialog(!1),r.error(e);(h={audio:!1,video:{mandatory:{chromeMediaSource:"desktop",maxWidth:window.screen.width,maxHeight:window.screen.height,minFrameRate:o.screenshareFrameRate,maxFrameRate:o.screenshareFrameRate},optional:[{googLeakyBucket:!0},{googTemporalLayeredScreencast:!0}]}}).video.mandatory.chromeMediaSourceId=t,k(h,C,z(o)&&!o.keepAudio)}))}else if("firefox"===n.webRTCAdapter.browserDetails.browser){if(!(n.webRTCAdapter.browserDetails.version>=33)){var x=new Error("NavigatorUserMediaError");return x.name="Your version of Firefox does not support screen sharing, please install Firefox 33 (or more recent versions)",a.consentDialog(!1),void r.error(x)}k(h={video:{mozMediaSource:o.video,mediaSource:o.video},audio:z(o)&&!o.keepAudio},(function(e,t){if(C(e,t),!e)var r=t.currentTime,n=window.setInterval((function(){t||window.clearInterval(n),t.currentTime==r&&(window.clearInterval(n),t.onended&&t.onended()),r=t.currentTime}),500)}))}return}}o&&"screen"===o.video||navigator.mediaDevices.enumerateDevices().then((function(t){var s=t.some((function(e){return"audioinput"===e.kind})),c=function(e){if(n.debug("isScreenSendEnabled:",e),!e)return!1;if("object"!=typeof e.video||"object"!=typeof e.video.mandatory)return!1;var t=e.video.mandatory;if(t.chromeMediaSource)return"desktop"===t.chromeMediaSource||"screen"===t.chromeMediaSource;if(t.mozMediaSource)return"window"===t.mozMediaSource||"screen"===t.mozMediaSource;if(t.mediaSource)return"window"===t.mediaSource||"screen"===t.mediaSource;return!1}(o)||t.some((function(e){return"videoinput"===e.kind})),u=z(o),d=H(o),f=function(e){return n.debug("isAudioSendRequired:",e),!!e&&(!1!==e.audio&&!1!==e.audioSend&&(void 0!==e.failIfNoAudio&&null!==e.failIfNoAudio&&!0===e.failIfNoAudio))}(o),p=function(e){return n.debug("isVideoSendRequired:",e),!!e&&(!1!==e.video&&!1!==e.videoSend&&(void 0!==e.failIfNoVideo&&null!==e.failIfNoVideo&&!0===e.failIfNoVideo))}(o);if(u||d||f||p){var v=!!u&&s,h=!!d&&c;if(!v&&!h)return a.consentDialog(!1),r.error("No capture device found"),!1;if(!v&&f)return a.consentDialog(!1),r.error("Audio capture is required, but no capture device found"),!1;if(!h&&p)return a.consentDialog(!1),r.error("Video capture is required, but no capture device found"),!1}var y={audio:!(!s||o.keepAudio)&&m,video:!(!c||o.keepVideo)&&g};n.debug("getUserMedia constraints",y),y.audio||y.video?navigator.mediaDevices.getUserMedia(y).then((function(t){a.consentDialog(!1),L(e,i,o,r,t)})).catch((function(e){a.consentDialog(!1),r.error({code:e.code,name:e.name,message:e.message})})):(a.consentDialog(!1),L(e,i,o,r,l))})).catch((function(e){a.consentDialog(!1),r.error("enumerateDevices error",e)}))}else L(e,i,o,r)}function F(e,t){(t=t||{}).success="function"==typeof t.success?t.success:n.noop,t.error="function"==typeof t.error?t.error:J;var r=t.jsep,i=T[e];if(!i||!i.webrtcStuff)return n.warn("Invalid handle"),void t.error("Invalid handle");var o=i.webrtcStuff;if(r){if(!o.pc)return n.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");o.pc.setRemoteDescription(r).then((function(){if(n.log("Remote description accepted!"),o.remoteSdp=r.sdp,o.candidates&&o.candidates.length>0){for(var e=0;e<o.candidates.length;e++){var i=o.candidates[e];n.debug("Adding remote candidate:",i),i&&!0!==i.completed?o.pc.addIceCandidate(i):o.pc.addIceCandidate(n.endOfCandidates)}o.candidates=[]}t.success()}),t.error)}else t.error("Invalid JSEP")}function U(e,t){var r=T[e];if(!r||!r.webrtcStuff)return n.warn("Invalid handle"),0;var i=t?"remote":"local",o=r.webrtcStuff;return o.volume[i]||(o.volume[i]={value:0}),o.pc.getStats&&"chrome"===n.webRTCAdapter.browserDetails.browser?t&&!o.remoteStream?(n.warn("Remote stream unavailable"),0):t||o.myStream?o.volume[i].timer?o.volume[i].value:(n.log("Starting "+i+" volume monitor"),o.volume[i].timer=setInterval((function(){o.pc.getStats().then((function(e){for(var r=e.result(),n=0;n<r.length;n++){var a=r[n];"ssrc"==a.type&&(t&&a.stat("audioOutputLevel")?o.volume[i].value=parseInt(a.stat("audioOutputLevel")):!t&&a.stat("audioInputLevel")&&(o.volume[i].value=parseInt(a.stat("audioInputLevel"))))}}))}),200),0):(n.warn("Local stream unavailable"),0):(n.warn("Getting the "+i+" volume unsupported by browser"),0)}function V(e,t){var r=T[e];if(!r||!r.webrtcStuff)return n.warn("Invalid handle"),!0;var i=r.webrtcStuff;return i.pc?i.myStream?t?i.myStream.getVideoTracks()&&0!==i.myStream.getVideoTracks().length?!i.myStream.getVideoTracks()[0].enabled:(n.warn("No video track"),!0):i.myStream.getAudioTracks()&&0!==i.myStream.getAudioTracks().length?!i.myStream.getAudioTracks()[0].enabled:(n.warn("No audio track"),!0):(n.warn("Invalid local MediaStream"),!0):(n.warn("Invalid PeerConnection"),!0)}function G(e,t,r){var i=T[e];if(!i||!i.webrtcStuff)return n.warn("Invalid handle"),!1;var o=i.webrtcStuff;return o.pc?o.myStream?t?o.myStream.getVideoTracks()&&0!==o.myStream.getVideoTracks().length?(o.myStream.getVideoTracks()[0].enabled=!r,!0):(n.warn("No video track"),!1):o.myStream.getAudioTracks()&&0!==o.myStream.getAudioTracks().length?(o.myStream.getAudioTracks()[0].enabled=!r,!0):(n.warn("No audio track"),!1):(n.warn("Invalid local MediaStream"),!1):(n.warn("Invalid PeerConnection"),!1)}function B(e){var t=T[e];if(!t||!t.webrtcStuff)return n.warn("Invalid handle"),"Invalid handle";var r=t.webrtcStuff;return r.pc?r.pc.getStats?r.bitrate.timer?r.bitrate.value:(n.log("Starting bitrate timer (via getStats)"),r.bitrate.timer=setInterval((function(){r.pc.getStats().then((function(e){e.forEach((function(e){if(e){var t=!1;if(("video"===e.mediaType||e.id.toLowerCase().indexOf("video")>-1)&&"inbound-rtp"===e.type&&e.id.indexOf("rtcp")<0?t=!0:"ssrc"!=e.type||!e.bytesReceived||"VP8"!==e.googCodecName&&""!==e.googCodecName||(t=!0),t)if(r.bitrate.bsnow=e.bytesReceived,r.bitrate.tsnow=e.timestamp,null===r.bitrate.bsbefore||null===r.bitrate.tsbefore)r.bitrate.bsbefore=r.bitrate.bsnow,r.bitrate.tsbefore=r.bitrate.tsnow;else{var i=r.bitrate.tsnow-r.bitrate.tsbefore;"safari"===n.webRTCAdapter.browserDetails.browser&&(i/=1e3);var o=Math.round(8*(r.bitrate.bsnow-r.bitrate.bsbefore)/i);"safari"===n.webRTCAdapter.browserDetails.browser&&(o=parseInt(o/1e3)),r.bitrate.value=o+" kbits/sec",r.bitrate.bsbefore=r.bitrate.bsnow,r.bitrate.tsbefore=r.bitrate.tsnow}}}))}))}),1e3),"0 kbits/sec"):(n.warn("Getting the video bitrate unsupported by browser"),"Feature unsupported by browser"):"Invalid PeerConnection"}function J(e){n.error("WebRTC error:",e)}function W(e,i){n.log("Cleaning WebRTC stuff");var o=T[e];if(o){var a=o.webrtcStuff;if(a){if(!0===i){var s={janus:"hangup",transaction:n.randomString(12)};o.token&&(s.token=o.token),m&&(s.apisecret=m),n.debug("Sending hangup request (handle="+e+"):"),n.debug(s),t?(s.session_id=w,s.handle_id=e,r.send(JSON.stringify(s))):n.httpAPICall(c+"/"+w+"/"+e,{verb:"POST",withCredentials:p,body:s})}a.remoteStream=null,a.volume&&(a.volume.local&&a.volume.local.timer&&clearInterval(a.volume.local.timer),a.volume.remote&&a.volume.remote.timer&&clearInterval(a.volume.remote.timer)),a.volume={},a.bitrate.timer&&clearInterval(a.bitrate.timer),a.bitrate.timer=null,a.bitrate.bsnow=null,a.bitrate.bsbefore=null,a.bitrate.tsnow=null,a.bitrate.tsbefore=null,a.bitrate.value=null;try{if(!a.streamExternal&&a.myStream){n.log("Stopping local stream tracks");var u=a.myStream.getTracks();for(var d of u)n.log(d),d&&d.stop()}}catch(e){}a.streamExternal=!1,a.myStream=null;try{a.pc.close()}catch(e){}a.pc=null,a.candidates=null,a.mySdp=null,a.remoteSdp=null,a.iceDone=!1,a.dataChannel={},a.dtmfSender=null}o.oncleanup()}}function z(e){return n.debug("isAudioSendEnabled:",e),!e||!1!==e.audio&&(void 0===e.audioSend||null===e.audioSend||!0===e.audioSend)}function q(e){return n.debug("isAudioRecvEnabled:",e),!e||!1!==e.audio&&(void 0===e.audioRecv||null===e.audioRecv||!0===e.audioRecv)}function H(e){return n.debug("isVideoSendEnabled:",e),!e||!1!==e.video&&(void 0===e.videoSend||null===e.videoSend||!0===e.videoSend)}function K(e){return n.debug("isVideoRecvEnabled:",e),!e||!1!==e.video&&(void 0===e.videoRecv||null===e.videoRecv||!0===e.videoRecv)}_(e),this.getServer=function(){return c},this.isConnected=function(){return S},this.reconnect=function(e){(e=e||{}).success="function"==typeof e.success?e.success:n.noop,e.error="function"==typeof e.error?e.error:n.noop,e.reconnect=!0,_(e)},this.getSessionId=function(){return w},this.destroy=function(a){!function(a){(a=a||{}).success="function"==typeof a.success?a.success:n.noop;var s=!0;void 0!==a.asyncRequest&&null!==a.asyncRequest&&(s=!0===a.asyncRequest);var u=!0;void 0!==a.notifyDestroyed&&null!==a.notifyDestroyed&&(u=!0===a.notifyDestroyed);var d=!1;void 0!==a.cleanupHandles&&null!==a.cleanupHandles&&(d=!0===a.cleanupHandles);if(n.log("Destroying session "+w+" (async="+s+")"),!w)return n.warn("No session to destroy"),a.success(),void(u&&e.destroyed());if(d)for(var f in T)j(f,{noRequest:!0});if(!S)return n.warn("Is the server down? (connected=false)"),void a.success();var l={janus:"destroy",transaction:n.randomString(12)};h&&(l.token=h);m&&(l.apisecret=m);if(t){l.session_id=w;var v=function(){for(var e in i)r.removeEventListener(e,i[e]);r.removeEventListener("message",g),r.removeEventListener("error",y),o&&clearTimeout(o),r.close()},g=function(t){var r=JSON.parse(t.data);r.session_id==l.session_id&&r.transaction==l.transaction&&(v(),a.success(),u&&e.destroyed())},y=function(t){v(),a.error("Failed to destroy the server: Is the server down?"),u&&e.destroyed()};return r.addEventListener("message",g),r.addEventListener("error",y),void r.send(JSON.stringify(l))}n.httpAPICall(c+"/"+w,{verb:"POST",async:s,withCredentials:p,body:l,success:function(t){n.log("Destroyed session:"),n.debug(t),w=null,S=!1,"success"!==t.janus&&n.error("Ooops: "+t.error.code+" "+t.error.reason),a.success(),u&&e.destroyed()},error:function(t,r){n.error(t+":",r),w=null,S=!1,a.success(),u&&e.destroyed()}})}(a)},this.attach=function(e){!function(e){if((e=e||{}).success="function"==typeof e.success?e.success:n.noop,e.error="function"==typeof e.error?e.error:n.noop,e.consentDialog="function"==typeof e.consentDialog?e.consentDialog:n.noop,e.iceState="function"==typeof e.iceState?e.iceState:n.noop,e.mediaState="function"==typeof e.mediaState?e.mediaState:n.noop,e.webrtcState="function"==typeof e.webrtcState?e.webrtcState:n.noop,e.slowLink="function"==typeof e.slowLink?e.slowLink:n.noop,e.onmessage="function"==typeof e.onmessage?e.onmessage:n.noop,e.onlocalstream="function"==typeof e.onlocalstream?e.onlocalstream:n.noop,e.onremotestream="function"==typeof e.onremotestream?e.onremotestream:n.noop,e.ondata="function"==typeof e.ondata?e.ondata:n.noop,e.ondataopen="function"==typeof e.ondataopen?e.ondataopen:n.noop,e.oncleanup="function"==typeof e.oncleanup?e.oncleanup:n.noop,e.ondetached="function"==typeof e.ondetached?e.ondetached:n.noop,!S)return n.warn("Is the server down? (connected=false)"),void e.error("Is the server down? (connected=false)");var i=e.plugin;if(!i)return n.error("Invalid plugin"),void e.error("Invalid plugin");var o=e.opaqueId,a=e.token?e.token:h,s=n.randomString(12),u={janus:"attach",plugin:i,opaque_id:o,transaction:s};a&&(u.token=a);m&&(u.apisecret=m);if(t)return R[s]=function(t){if(n.debug(t),"success"!==t.janus)return n.error("Ooops: "+t.error.code+" "+t.error.reason),void e.error("Ooops: "+t.error.code+" "+t.error.reason);var r=t.data.id;n.log("Created handle: "+r);var o={session:C,plugin:i,id:r,token:a,detached:!1,webrtcStuff:{started:!1,myStream:null,streamExternal:!1,remoteStream:null,mySdp:null,mediaConstraints:null,pc:null,dataChannel:{},dtmfSender:null,trickle:!0,iceDone:!1,volume:{value:null,timer:null},bitrate:{value:null,bsnow:null,bsbefore:null,tsnow:null,tsbefore:null,timer:null}},getId:function(){return r},getPlugin:function(){return i},getVolume:function(){return U(r,!0)},getRemoteVolume:function(){return U(r,!0)},getLocalVolume:function(){return U(r,!1)},isAudioMuted:function(){return V(r,!1)},muteAudio:function(){return G(r,!1,!0)},unmuteAudio:function(){return G(r,!1,!1)},isVideoMuted:function(){return V(r,!0)},muteVideo:function(){return G(r,!0,!0)},unmuteVideo:function(){return G(r,!0,!1)},getBitrate:function(){return B(r)},send:function(e){O(r,e)},data:function(e){A(r,e)},dtmf:function(e){I(r,e)},consentDialog:e.consentDialog,iceState:e.iceState,mediaState:e.mediaState,webrtcSt