diff --git a/Gruntfile.js b/Gruntfile.js
index 86549557..bf2c82ae 100755
--- a/Gruntfile.js
+++ b/Gruntfile.js
@@ -7,6 +7,8 @@ module.exports = function(grunt) {
scope: 'devDependencies'
});
+ var banner = '// Last time updated: <%= grunt.template.today("UTC:yyyy-mm-dd h:MM:ss TT Z") %>\n\n';
+
// configure project
grunt.initConfig({
// make node configurations available
@@ -15,7 +17,7 @@ module.exports = function(grunt) {
options: {
stripBanners: true,
separator: '\n',
- banner: '// Last time updated at <%= grunt.template.today("dddd, mmmm dS, yyyy, h:MM:ss TT") %> \n\n'
+ banner: banner
},
dist: {
src: [
@@ -67,7 +69,7 @@ module.exports = function(grunt) {
uglify: {
options: {
mangle: false,
- banner: '// Last time updated at <%= grunt.template.today("dddd, mmmm dS, yyyy, h:MM:ss TT") %> \n\n'
+ banner: banner
},
my_target: {
files: {
diff --git a/README.md b/README.md
index e11e8c8e..d894af66 100755
--- a/README.md
+++ b/README.md
@@ -64,7 +64,7 @@ All files from `/dist` directory are available on CDN: `https://cdn.webrtc-exper
-
+
```
If you're sharing files, you also need to link:
@@ -76,7 +76,7 @@ If you're sharing files, you also need to link:
-
+
```
> You can link multiple files from `dev` directory. Order doesn't matters.
diff --git a/RTCMultiConnection.js b/RTCMultiConnection.js
index 6796b971..657ebb4a 100644
--- a/RTCMultiConnection.js
+++ b/RTCMultiConnection.js
@@ -1,4 +1,4 @@
-// Last time updated at Sunday, January 17th, 2016, 5:28:51 PM
+// Last time updated: 2016-01-19 9:53:08 AM UTC
// ______________________________
// RTCMultiConnection-v3.0 (Beta)
@@ -1248,7 +1248,7 @@
// default value is 15k because Firefox's receiving limit is 16k!
// however 64k works chrome-to-chrome
- connection.chunkSize = 15 * 1000;
+ connection.chunkSize = 65 * 1000;
connection.maxParticipantsAllowed = 1000;
@@ -2025,7 +2025,7 @@
}, {
userid: connection.userid,
// extra: connection.extra,
- chunkSize: connection.chunkSize || 0
+ chunkSize: isFirefox ? 15 * 1000 : connection.chunkSize || 0
});
};
@@ -2050,7 +2050,13 @@
};
this.onDataChannelOpened = function(channel, remoteUserId) {
+ // keep last channel only; we are not expecting parallel/channels channels
+ if (connection.peers[remoteUserId].channels.length) {
+ return;
+ }
+
connection.peers[remoteUserId].channels.push(channel);
+
connection.onopen({
userid: remoteUserId,
extra: connection.peers[remoteUserId] ? connection.peers[remoteUserId].extra : {},
diff --git a/RTCMultiConnection.min.js b/RTCMultiConnection.min.js
index fb8c1ac0..42b44832 100644
--- a/RTCMultiConnection.min.js
+++ b/RTCMultiConnection.min.js
@@ -1,6 +1,6 @@
-// Last time updated at Sunday, January 17th, 2016, 5:28:52 PM
+// Last time updated: 2016-01-19 9:53:09 AM UTC
-"use strict";!function(){function RTCMultiConnection(roomid){function onUserLeft(remoteUserId){connection.peers[remoteUserId]&&connection.peers[remoteUserId].peer&&(connection.peers[remoteUserId].streams.forEach(function(stream){stream.stop()}),connection.peers[remoteUserId]&&(connection.peers[remoteUserId].peer.close(),connection.peers[remoteUserId]&&(connection.peers[remoteUserId].peer=null)),connection.onleave({userid:remoteUserId,extra:connection.peers[remoteUserId]?connection.peers[remoteUserId].extra:{}})),delete connection.peers[remoteUserId]}function connectSocket(connectCallback){if(socket)return void(connectCallback&&connectCallback(socket));if("undefined"==typeof SocketConnection)if("undefined"!=typeof FirebaseConnection)window.SocketConnection=FirebaseConnection;else{if("undefined"==typeof PubNubConnection)throw"SocketConnection.js seems missed.";window.SocketConnection=PubNubConnection}socket=new SocketConnection(connection,function(s){socket=s,connectCallback&&connectCallback(socket)})}function beforeUnload(shiftModerationControlOnLeave){if(connection.closeBeforeUnload&&(connection.peers.getAllParticipants().forEach(function(participant){mPeer.onNegotiationNeeded({userLeft:!0,autoCloseEntireSession:!!connection.autoCloseEntireSession},participant),connection.peers[participant]&&connection.peers[participant].peer&&connection.peers[participant].peer.close()}),socket&&("undefined"!=typeof socket.disconnect&&(connection.autoReDialOnFailure=!1,socket.disconnect()),socket=null),connection.broadcasters.length&&!connection.autoCloseEntireSession)){var firstBroadcaster=connection.broadcasters[0],otherBroadcasters=[];connection.broadcasters.forEach(function(broadcaster){broadcaster!==firstBroadcaster&&otherBroadcasters.push(broadcaster)}),connection.shiftModerationControl(firstBroadcaster,otherBroadcasters,"undefined"!=typeof shiftModerationControlOnLeave?shiftModerationControlOnLeave:!0),connection.broadcasters=[],connection.isInitiator=!1}}function applyConstraints(stream,mediaConstraints){return stream?(mediaConstraints.audio&&stream.getAudioTracks().forEach(function(track){track.applyConstraints(mediaConstraints.audio)}),void(mediaConstraints.video&&stream.getVideoTracks().forEach(function(track){track.applyConstraints(mediaConstraints.video)}))):void(connection.enableLogs&&console.error("No stream to applyConstraints."))}function replaceTrack(track,remoteUserId,isVideoTrack){return remoteUserId?void mPeer.replaceTrack(track,remoteUserId,isVideoTrack):void connection.peers.getAllParticipants().forEach(function(participant){mPeer.replaceTrack(track,participant,isVideoTrack)})}function setStreamEndHandler(stream,isRemote){isRemote=!!isRemote,stream.alreadySetEndHandler||(stream.alreadySetEndHandler=!0,stream&&stream.addEventListener&&stream.addEventListener("ended",function(){stream.idInstance&¤tUserMediaRequest.remove(stream.idInstance),isRemote||(delete connection.attachStreams[connection.attachStreams.indexOf(stream)],-1===connection.removeStreams.indexOf(stream)&&connection.removeStreams.push(stream),connection.attachStreams=removeNullEntries(connection.attachStreams),connection.removeStreams=removeNullEntries(connection.removeStreams),connection.observers.all());var streamEvent=connection.streamEvents[stream.streamid];streamEvent||(streamEvent={stream:stream,streamid:stream.streamid,type:isRemote?"remote":"local",userid:connection.userid,extra:connection.extra,mediaElement:connection.streamEvents[stream.streamid]?connection.streamEvents[stream.streamid].mediaElement:null}),connection.onstreamended(streamEvent),delete connection.streamEvents[stream.streamid]},!1))}var connection=this;connection.channel=connection.sessionid=(roomid||location.href.replace(/\/|:|#|\?|\$|\^|%|\.|`|~|!|\+|@|\[|\||]|\|*. /g,"").split("\n").join("").split("\r").join(""))+"";var mPeer=new MultiPeers(connection);mPeer.onGettingLocalMedia=function(stream){stream.type="local",setStreamEndHandler(stream),getRMCMediaElement(stream,function(mediaElement){mediaElement.id=stream.streamid,mediaElement.muted=!0,mediaElement.volume=0,-1===connection.attachStreams.indexOf(stream)&&connection.attachStreams.push(stream),"undefined"!=typeof StreamsHandler&&StreamsHandler.setHandlers(stream,!0,connection),connection.streamEvents[stream.streamid]={stream:stream,type:"local",mediaElement:mediaElement,userid:connection.userid,extra:connection.extra,streamid:stream.streamid,blobURL:mediaElement.src||URL.createObjectURL(stream),isAudioMuted:!0},setHarkEvents(connection,connection.streamEvents[stream.streamid]),setMuteHandlers(connection,connection.streamEvents[stream.streamid]),connection.onstream(connection.streamEvents[stream.streamid])},connection),connection.observers.all()},mPeer.onGettingRemoteMedia=function(stream,remoteUserId){stream.type="remote",setStreamEndHandler(stream,"remote-stream"),getRMCMediaElement(stream,function(mediaElement){mediaElement.id=stream.streamid,"undefined"!=typeof StreamsHandler&&StreamsHandler.setHandlers(stream,!1,connection),connection.streamEvents[stream.streamid]={stream:stream,type:"remote",userid:remoteUserId,extra:connection.peers[remoteUserId]?connection.peers[remoteUserId].extra:{},mediaElement:mediaElement,streamid:stream.streamid,blobURL:mediaElement.src||URL.createObjectURL(stream)},setMuteHandlers(connection,connection.streamEvents[stream.streamid]),connection.onstream(connection.streamEvents[stream.streamid])},connection)},mPeer.onRemovingRemoteMedia=function(stream,remoteUserId){var streamEvent=connection.streamEvents[stream.streamid];streamEvent||(streamEvent={stream:stream,type:"remote",userid:remoteUserId,extra:connection.peers[remoteUserId]?connection.peers[remoteUserId].extra:{},streamid:stream.streamid,mediaElement:connection.streamEvents[stream.streamid]?connection.streamEvents[stream.streamid].mediaElement:null}),connection.onstreamended(streamEvent),delete connection.streamEvents[stream.streamid]},mPeer.onNegotiationNeeded=function(message,remoteUserId,callback){connectSocket(function(){socket.emit(connection.socketMessageEvent,"password"in message?message:{remoteUserId:message.remoteUserId||remoteUserId,message:message,sender:connection.userid},callback||function(){})})},mPeer.onUserLeft=onUserLeft,mPeer.disconnectWith=function(remoteUserId,callback){socket&&socket.emit("disconnect-with",remoteUserId,callback||function(){}),connection.peers[remoteUserId]&&(connection.peers[remoteUserId].peer&&connection.peers[remoteUserId].peer.close(),delete connection.peers[remoteUserId])},connection.broadcasters=[],connection.socketOptions={transport:"polling"};var socket;connection.openOrJoin=function(localUserid,password){connection.checkPresence(localUserid,function(isRoomExists,roomid){if("function"==typeof password&&(password(isRoomExists,roomid),password=null),isRoomExists){connection.sessionid=roomid;var localPeerSdpConstraints=!1,remotePeerSdpConstraints=!1,isOneWay=!!connection.session.oneway,isDataOnly=isData(connection.session);remotePeerSdpConstraints={OfferToReceiveAudio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.sdpConstraints.mandatory.OfferToReceiveVideo},localPeerSdpConstraints={OfferToReceiveAudio:isOneWay?!!connection.session.audio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:isOneWay?!!connection.session.video||!!connection.session.screen:connection.sdpConstraints.mandatory.OfferToReceiveVideo};var connectionDescription={remoteUserId:connection.sessionid,message:{newParticipationRequest:!0,isOneWay:isOneWay,isDataOnly:isDataOnly,localPeerSdpConstraints:localPeerSdpConstraints,remotePeerSdpConstraints:remotePeerSdpConstraints},sender:connection.userid,password:password||!1};return void mPeer.onNegotiationNeeded(connectionDescription)}connection.userid;connection.userid=connection.sessionid=localUserid||connection.sessionid,connection.userid+="",socket.emit("changed-uuid",connection.userid),password&&socket.emit("set-password",password),connection.isInitiator=!0,isData(connection.session)||connection.captureUserMedia()})},connection.open=function(localUserid,isPublicModerator){connection.userid;return connection.userid=connection.sessionid=localUserid||connection.sessionid,connection.userid+="",connection.isInitiator=!0,connectSocket(function(){socket.emit("changed-uuid",connection.userid),1==isPublicModerator&&connection.becomePublicModerator()}),isData(connection.session)?void("function"==typeof isPublicModerator&&isPublicModerator()):void connection.captureUserMedia("function"==typeof isPublicModerator?isPublicModerator:null)},connection.becomePublicModerator=function(){connection.isInitiator&&socket.emit("become-a-public-moderator")},connection.rejoin=function(connectionDescription){if(!connection.isInitiator&&connectionDescription&&Object.keys(connectionDescription).length){var extra={};connection.peers[connectionDescription.remoteUserId]&&(extra=connection.peers[connectionDescription.remoteUserId].extra,connection.peers[connectionDescription.remoteUserId].peer&&(connection.peers[connectionDescription.remoteUserId].peer=null),delete connection.peers[connectionDescription.remoteUserId]),connectionDescription&&connectionDescription.remoteUserId&&(connection.join(connectionDescription.remoteUserId),connection.onReConnecting({userid:connectionDescription.remoteUserId,extra:extra}))}},connection.join=connection.connect=function(remoteUserId,options){connection.sessionid=(remoteUserId?remoteUserId.sessionid||remoteUserId.remoteUserId||remoteUserId:!1)||connection.sessionid,connection.sessionid+="";var localPeerSdpConstraints=!1,remotePeerSdpConstraints=!1,isOneWay=!1,isDataOnly=!1;if(remoteUserId&&remoteUserId.session||!remoteUserId||"string"==typeof remoteUserId){var session=remoteUserId?remoteUserId.session||connection.session:connection.session;isOneWay=!!session.oneway,isDataOnly=isData(session),remotePeerSdpConstraints={OfferToReceiveAudio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.sdpConstraints.mandatory.OfferToReceiveVideo},localPeerSdpConstraints={OfferToReceiveAudio:isOneWay?!!connection.session.audio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:isOneWay?!!connection.session.video||!!connection.session.screen:connection.sdpConstraints.mandatory.OfferToReceiveVideo}}options=options||{},"undefined"!=typeof options.localPeerSdpConstraints&&(localPeerSdpConstraints=options.localPeerSdpConstraints),"undefined"!=typeof options.remotePeerSdpConstraints&&(remotePeerSdpConstraints=options.remotePeerSdpConstraints),"undefined"!=typeof options.isOneWay&&(isOneWay=options.isOneWay),"undefined"!=typeof options.isDataOnly&&(isDataOnly=options.isDataOnly);var connectionDescription={remoteUserId:connection.sessionid,message:{newParticipationRequest:!0,isOneWay:isOneWay,isDataOnly:isDataOnly,localPeerSdpConstraints:localPeerSdpConstraints,remotePeerSdpConstraints:remotePeerSdpConstraints},sender:connection.userid,password:!1};return connectSocket(function(){connection.peers[connection.sessionid]||mPeer.onNegotiationNeeded(connectionDescription)}),connectionDescription},connection.connectWithAllParticipants=function(remoteUserId){mPeer.onNegotiationNeeded("connectWithAllParticipants",remoteUserId||connection.sessionid)},connection.removeFromBroadcastersList=function(remoteUserId){mPeer.onNegotiationNeeded("removeFromBroadcastersList",remoteUserId||connection.sessionid),connection.peers.getAllParticipants(remoteUserId||connection.sessionid).forEach(function(participant){mPeer.onNegotiationNeeded("dropPeerConnection",participant),connection.peers[participant].peer.close(),connection.peers[participant].peer=null,delete connection.peers[participant]}),connection.attachStreams.forEach(function(stream){stream.addEventListener("ended",function(){connection.renegotiate(remoteUserId||connection.sessionid)},!1),stream.stop()})},connection.getUserMedia=connection.captureUserMedia=function(callback,session){function invokeGetUserMedia(localMediaConstraints,getUserMedia_callback){var isScreen=!1;localMediaConstraints&&(isScreen=localMediaConstraints.isScreen,delete localMediaConstraints.isScreen),getUserMediaHandler({onGettingLocalMedia:function(stream){return stream.isAudio=stream.isVideo=stream.isScreen=!1,isScreen?stream.isScreen=!0:session.audio&&session.video?stream.isVideo=!0:session.audio&&(stream.isAudio=!0),mPeer.onGettingLocalMedia(stream),getUserMedia_callback?getUserMedia_callback():void(callback&&callback(stream))},onLocalMediaError:function(error){mPeer.onLocalMediaError(error),callback&&callback()},localMediaConstraints:localMediaConstraints||{audio:session.audio?connection.mediaConstraints.audio:!1,video:session.video?connection.mediaConstraints.video:!1}})}return connection.observers.all(),session=session||connection.session,connection.dontCaptureUserMedia||isData(session)?void(callback&&callback()):void((session.audio||session.video||session.screen)&&(session.screen?connection.getScreenConstraints(function(error,screen_constraints){if(error)throw error;invokeGetUserMedia({video:screen_constraints,isScreen:!0},session.audio||session.video?invokeGetUserMedia:!1)}):(session.audio||session.video)&&invokeGetUserMedia()))},connection.closeBeforeUnload=!0,window.addEventListener("beforeunload",beforeUnload,!1),connection.userid=getRandomString(),connection.changeUserId=function(newUserId){connection.userid=newUserId||getRandomString(),socket.emit("changed-uuid",connection.userid)},connection.observers={extra:function(){observeObject(connection.extra,function(changes){socket.emit("extra-data-updated",connection.extra)})},attachStreams:function(){observeObject(connection.attachStreams,function(changes){changes.forEach(function(change){"add"===change.type&&setStreamEndHandler(change.object[change.name]),("remove"===change.type||"delete"===change.type)&&-1===connection.removeStreams.indexOf(change.object[change.name])&&connection.removeStreams.push(change.object[change.name]),connection.attachStreams=removeNullEntries(connection.attachStreams),connection.removeStreams=removeNullEntries(connection.removeStreams),connection.observers.all()})})},all:function(){this.extra(),this.attachStreams(),socket&&socket.emit("extra-data-updated",connection.extra)}},connection.extra={},connection.attachStreams=[],connection.removeStreams=[],connection.observers.all(),connection.session={audio:!0,video:!0},connection.enableFileSharing=!1,connection.mediaConstraints={audio:{mandatory:{},optional:[]},video:{mandatory:{},optional:[]}},DetectRTC.load(function(){DetectRTC.MediaDevices.forEach(function(device){"audioinput"===device.kind&&(connection.mediaConstraints.audio={optional:[{sourceId:device.id},{bandwidth:connection.bandwidth.audio||1024e3}],mandatory:{}},isFirefox&&(connection.mediaConstraints.audio={deviceId:device.id})),"videoinput"===device.kind&&(connection.mediaConstraints.video={optional:[{sourceId:device.id},{googLeakyBucket:!0},{bandwidth:connection.bandwidth.video||2048e3}],mandatory:{}},isFirefox&&(connection.mediaConstraints.video={deviceId:device.id}))})}),connection.sdpConstraints={mandatory:{OfferToReceiveAudio:!0,OfferToReceiveVideo:!0},optional:[{VoiceActivityDetection:!1}]},connection.optionalArgument={optional:[{DtlsSrtpKeyAgreement:!0},{googImprovedWifiBwe:!0},{googScreencastMinBitrate:300},{googIPv6:!0},{googDscp:!0},{googCpuUnderuseThreshold:55},{googCpuOveruseThreshold:85},{googSuspendBelowMinBitrate:!0},{googCpuOveruseDetection:!0}],mandatory:{}},connection.iceServers=IceServersHandler.getIceServers(connection),connection.candidates={host:!0,stun:!0,turn:!0},connection.iceProtocols={tcp:!0,udp:!0},connection.onopen=function(event){connection.enableLogs&&console.info("Data connection has been opened between you & ",event.userid)},connection.onclose=function(event){connection.enableLogs&&console.warn("Data connection has been closed between you & ",event.userid)},connection.onerror=function(error){connection.enableLogs&&console.error(error.userid,"data-error",error)},connection.onmessage=function(event){connection.enableLogs&&console.debug("data-message",event.userid,event.data)},connection.send=function(data,remoteUserId){connection.peers.send(data,remoteUserId)},connection.close=connection.disconnect=connection.leave=function(){beforeUnload(!1)},connection.onstream=function(e){var parentNode=connection.videosContainer;parentNode.insertBefore(e.mediaElement,parentNode.firstChild)},connection.onstreamended=function(e){e.mediaElement||(e.mediaElement=document.getElementById(e.streamid)),e.mediaElement&&e.mediaElement.parentNode&&e.mediaElement.parentNode.removeChild(e.mediaElement)},connection.direction="many-to-many",Array.prototype.getStreamById=function(streamid){var stream;return this.forEach(function(_stream){_stream.streamid==streamid&&(stream=_stream)}),stream},connection.removeStream=function(streamid){var stream;return connection.attachStreams.forEach(function(localStream){localStream.id===streamid&&(stream=localStream)}),stream?void(-1===connection.removeStreams.indexOf(stream)&&(connection.removeStreams.push(stream),connection.peers.getAllParticipants().forEach(function(participant){mPeer.renegotiatePeer(participant)}))):void console.warn("No such stream exists.",streamid)},connection.addStream=function(session){function invokeGetUserMedia(localMediaConstraints,callback){getUserMediaHandler({onGettingLocalMedia:function(stream){var videoConstraints=localMediaConstraints?localMediaConstraints.video:connection.mediaConstraints;return videoConstraints&&(videoConstraints.mediaSource||videoConstraints.mozMediaSource?stream.isScreen=!0:videoConstraints.mandatory&&videoConstraints.mandatory.chromeMediaSource&&(stream.isScreen=!0)),stream.isScreen||(stream.isVideo=stream.getVideoTracks().length,stream.isAudio=!stream.isVideo&&stream.getAudioTracks().length),mPeer.onGettingLocalMedia(stream),session.streamCallback&&session.streamCallback(stream),callback?callback():void connection.renegotiate()},onLocalMediaError:function(error){return mPeer.onLocalMediaError(error),callback?callback():void connection.renegotiate()},localMediaConstraints:localMediaConstraints||{audio:session.audio?connection.mediaConstraints.audio:!1,video:session.video?connection.mediaConstraints.video:!1}})}return isData(session)?void connection.renegotiate():void((!session.audio||session.video||session.screen)&&(session.screen?connection.getScreenConstraints(function(error,screen_constraints){return error?alert(error):void invokeGetUserMedia({video:screen_constraints},session.audio||session.video?invokeGetUserMedia:!1)}):(session.audio||session.video)&&invokeGetUserMedia()))},connection.applyConstraints=function(mediaConstraints,streamid){if(!MediaStreamTrack||!MediaStreamTrack.prototype.applyConstraints)return void alert("track.applyConstraints is NOT supported in your browser.");if(streamid){return connection.streamEvents[streamid]&&(stream=connection.streamEvents[streamid].stream),void applyConstraints(stream,mediaConstraints)}connection.attachStreams.forEach(function(stream){applyConstraints(stream,mediaConstraints)})},connection.replaceTrack=function(session,remoteUserId,isVideoTrack){function invokeGetUserMedia(localMediaConstraints,callback){getUserMediaHandler({onGettingLocalMedia:function(stream){return mPeer.onGettingLocalMedia(stream),callback?callback():void connection.replaceTrack(stream,remoteUserId,isVideoTrack||session.video||session.screen)},onLocalMediaError:function(error){mPeer.onLocalMediaError(error),callback&&callback()},localMediaConstraints:localMediaConstraints||{audio:session.audio?connection.mediaConstraints.audio:!1,video:session.video?connection.mediaConstraints.video:!1}})}if(session=session||{},!RTCPeerConnection.prototype.getSenders)return void this.addStream(session);if(session instanceof MediaStreamTrack)return void replaceTrack(session,remoteUserId,isVideoTrack);if(session instanceof MediaStream)return void replaceTrack(session.getVideoTracks()[0],remoteUserId,isVideoTrack);if(isData(session))throw"connection.replaceTrack requires audio and/or video and/or screen.";(!session.audio||session.video||session.screen)&&(session.screen?connection.getScreenConstraints(function(error,screen_constraints){return error?alert(error):void invokeGetUserMedia({video:screen_constraints},session.audio||session.video?invokeGetUserMedia:!1)}):(session.audio||session.video)&&invokeGetUserMedia())},connection.resetTrack=function(remoteUsersIds,isVideoTrack){remoteUsersIds||(remoteUsersIds=connection.getAllParticipants()),"string"==typeof remoteUsersIds&&(remoteUsersIds=[remoteUsersIds]),remoteUsersIds.forEach(function(participant){var peer=connection.peers[participant].peer;"undefined"!=typeof isVideoTrack&&isVideoTrack!==!0||!peer.lastVideoTrack||connection.replaceTrack(peer.lastVideoTrack,participant,!0),"undefined"!=typeof isVideoTrack&&isVideoTrack!==!1||!peer.lastAudioTrack||connection.replaceTrack(peer.lastAudioTrack,participant,!1)})},connection.renegotiate=function(remoteUserId){return remoteUserId?void mPeer.renegotiatePeer(remoteUserId):void connection.peers.getAllParticipants().forEach(function(participant){mPeer.renegotiatePeer(participant)})},connection.onMediaError=function(error){connection.enableLogs&&console.error(error)},connection.addNewBroadcaster=function(broadcasterId,userPreferences){connection.broadcasters.forEach(function(broadcaster){mPeer.onNegotiationNeeded({newParticipant:broadcasterId,userPreferences:userPreferences||!1},broadcaster)}),connection.session.oneway||"many-to-many"!==connection.direction||-1!==connection.broadcasters.indexOf(broadcasterId)||connection.broadcasters.push(broadcasterId)},connection.filesContainer=connection.videosContainer=document.body||document.documentElement,connection.isInitiator=!1,connection.shareFile=mPeer.shareFile,"undefined"!=typeof FileProgressBarHandler&&FileProgressBarHandler.handle(connection),connection.autoCloseEntireSession=!1,"undefined"!=typeof TranslationHandler&&TranslationHandler.handle(connection),connection.token=getRandomString,connection.onNewParticipant=function(participantId,userPreferences){connection.acceptParticipationRequest(participantId,userPreferences)},connection.acceptParticipationRequest=function(participantId,userPreferences){userPreferences.successCallback&&(userPreferences.successCallback(),delete userPreferences.successCallback),mPeer.createNewPeer(participantId,userPreferences)},connection.onShiftedModerationControl=function(sender,existingBroadcasters){connection.acceptModerationControl(sender,existingBroadcasters)},connection.acceptModerationControl=function(sender,existingBroadcasters){connection.isInitiator=!0,connection.broadcasters=existingBroadcasters,connection.peers.getAllParticipants().forEach(function(participant){mPeer.onNegotiationNeeded({changedUUID:sender,oldUUID:connection.userid,newUUID:sender},participant)}),connection.userid=sender,socket.emit("changed-uuid",connection.userid)},connection.shiftModerationControl=function(remoteUserId,existingBroadcasters,firedOnLeave){mPeer.onNegotiationNeeded({shiftedModerationControl:!0,broadcasters:existingBroadcasters,firedOnLeave:!!firedOnLeave},remoteUserId)},connection.processSdp=function(sdp){return sdp=BandwidthHandler.setApplicationSpecificBandwidth(sdp,connection.bandwidth,!!connection.session.screen),sdp=BandwidthHandler.setVideoBitrates(sdp,{min:connection.bandwidth.video,max:connection.bandwidth.video}),sdp=BandwidthHandler.setOpusAttributes(sdp)},"undefined"!=typeof BandwidthHandler&&(connection.BandwidthHandler=BandwidthHandler),"undefined"!=typeof StreamsHandler&&(connection.StreamsHandler=StreamsHandler),connection.bandwidth={screen:300,audio:50,video:256},connection.onleave=function(userid){},connection.invokeSelectFileDialog=function(callback){var selector=new FileSelector;selector.selectSingleFile(callback)},connection.getPublicModerators=function(userIdStartsWith,callback){"function"==typeof userIdStartsWith&&(callback=userIdStartsWith),connectSocket(function(socket){socket.emit("get-public-moderators","string"==typeof userIdStartsWith?userIdStartsWith:"",callback)})},connection.onmute=function(e){e.mediaElement&&("both"===e.muteType||"video"===e.muteType?(e.mediaElement.src=null,e.mediaElement.pause(),e.mediaElement.poster=e.snapshot||"https://cdn.webrtc-experiment.com/images/muted.png"):"audio"===e.muteType&&(e.mediaElement.muted=!0))},connection.onunmute=function(e){e.mediaElement&&("both"===e.unmuteType||"video"===e.unmuteType?(e.mediaElement.poster=null,e.mediaElement.src=URL.createObjectURL(e.stream),e.mediaElement.play()):"audio"===e.unmuteType&&(e.mediaElement.muted=!1))},connection.onExtraDataUpdated=function(event){event.status="online",connection.onUserStatusChanged(event,!0)},connection.onJoinWithPassword=function(remoteUserId){console.warn(remoteUserId,"is password protected. Please join with password.")},connection.onInvalidPassword=function(remoteUserId,oldPassword){console.warn(remoteUserId,"is password protected. Please join with valid password. Your old password",oldPassword,"is wrong.")},connection.onPasswordMaxTriesOver=function(remoteUserId){console.warn(remoteUserId,"is password protected. Your max password tries exceeded the limit.")},connection.getAllParticipants=function(){return connection.peers.getAllParticipants()},"undefined"!=typeof StreamsHandler&&(StreamsHandler.onSyncNeeded=function(streamid,action,type){connection.peers.getAllParticipants().forEach(function(participant){mPeer.onNegotiationNeeded({streamid:streamid,action:action,streamSyncNeeded:!0,type:type||"both"},participant)})}),connection.getAllVideos=function(remoteUserId){var videos=[];return Array.prototype.slice.call(document.querySelectorAll("video")).forEach(function(video){video.getAttribute("data-userid")===remoteUserId&&videos.push(video)}),videos},connection.connectSocket=function(callback){connectSocket(callback)},connection.getSocket=function(callback){return socket?callback&&callback(socket):connectSocket(callback),socket},connection.getRemoteStreams=mPeer.getRemoteStreams,connection.autoReDialOnFailure=!0;var skipStreams=["selectFirst","selectAll","forEach"];connection.streamEvents={selectFirst:function(options){if(!options){var firstStream;for(var str in connection.streamEvents)-1!==skipStreams.indexOf(str)||firstStream||(firstStream=connection.streamEvents[str]);return firstStream}},selectAll:function(){}},connection.socketURL="/",connection.socketMessageEvent="RTCMultiConnection-Message",connection.socketCustomEvent="RTCMultiConnection-Custom-Message",connection.DetectRTC=DetectRTC,connection.onUserStatusChanged=function(event,dontWriteLogs){connection.enableLogs&&!dontWriteLogs&&console.info(event.userid,event.status)},connection.getUserMediaHandler=getUserMediaHandler,connection.multiPeersHandler=mPeer,connection.enableLogs=!0,connection.setCustomSocketHandler=function(customSocketHandler){"undefined"!=typeof SocketConnection&&(SocketConnection=customSocketHandler)},connection.chunkSize=15e3,connection.maxParticipantsAllowed=1e3,connection.disconnectWith=mPeer.disconnectWith,connection.checkPresence=function(remoteUserId,callback){mPeer.onNegotiationNeeded({detectPresence:!0,userid:(remoteUserId||connection.sessionid)+""},"system",callback)},connection.onReadyForOffer=function(remoteUserId,userPreferences){connection.multiPeersHandler.createNewPeer(remoteUserId,userPreferences)},connection.setUserPreferences=function(userPreferences){return connection.dontAttachStream&&(userPreferences.dontAttachLocalStream=!0),connection.dontGetRemoteStream&&(userPreferences.dontGetRemoteStream=!0),userPreferences},connection.updateExtraData=function(){socket.emit("extra-data-updated",connection.extra)},connection.enableScalableBroadcast=!1,connection.singleBroadcastAttendees=3,connection.dontCaptureUserMedia=!1,connection.dontAttachStream=!1,connection.dontGetRemoteStream=!1,connection.onReConnecting=function(event){connection.enableLogs&&console.info("ReConnecting with",event.userid,"...")},connection.beforeAddingStream=function(stream){return stream},connection.beforeRemovingStream=function(stream){return stream},"undefined"!=typeof isChromeExtensionAvailable&&(connection.checkIfChromeExtensionAvailable=isChromeExtensionAvailable),"undefined"!=typeof isFirefoxExtensionAvailable&&(connection.checkIfChromeExtensionAvailable=isFirefoxExtensionAvailable),"undefined"!=typeof getChromeExtensionStatus&&(connection.getChromeExtensionStatus=getChromeExtensionStatus),connection.getScreenConstraints=function(callback){getScreenConstraints(function(error,screen_constraints){error||(screen_constraints=connection.modifyScreenConstraints(screen_constraints),callback(error,screen_constraints))})},connection.modifyScreenConstraints=function(screen_constraints){return screen_constraints},connection.onPeerStateChanged=function(state){connection.enableLogs&&-1!==state.iceConnectionState.search(/closed|failed/gi)&&console.error("Peer connection is closed between you & ",state.userid,state.extra,"state:",state.iceConnectionState)}}function SocketConnection(connection,connectCallback){var parameters="";parameters+="?userid="+connection.userid,parameters+="&msgEvent="+connection.socketMessageEvent,parameters+="&socketCustomEvent="+connection.socketCustomEvent,connection.enableScalableBroadcast&&(parameters+="&enableScalableBroadcast=true",parameters+="&singleBroadcastAttendees="+connection.singleBroadcastAttendees);var socket=io.connect((connection.socketURL||"/")+parameters,connection.socketOptions),mPeer=connection.multiPeersHandler;return socket.on("extra-data-updated",function(remoteUserId,extra){connection.peers[remoteUserId]&&(connection.peers[remoteUserId].extra=extra,connection.onExtraDataUpdated({userid:remoteUserId,extra:extra}))}),socket.on(connection.socketMessageEvent,function(message){if(message.remoteUserId==connection.userid){if(connection.peers[message.sender]&&connection.peers[message.sender].extra!=message.extra&&(connection.peers[message.sender].extra=message.extra,connection.onExtraDataUpdated({userid:message.sender,extra:message.extra})),message.message.streamSyncNeeded&&connection.peers[message.sender]){var stream=connection.streamEvents[message.message.streamid];if(!stream||!stream.stream)return;var action=message.message.action;if("ended"===action||"stream-removed"===action)return void connection.onstreamended(stream);var type="both"!=message.message.type?message.message.type:null;return void stream.stream[action](type)}if("connectWithAllParticipants"===message.message)return-1===connection.broadcasters.indexOf(message.sender)&&connection.broadcasters.push(message.sender),void mPeer.onNegotiationNeeded({allParticipants:connection.peers.getAllParticipants(message.sender)},message.sender);if("removeFromBroadcastersList"===message.message)return void(-1!==connection.broadcasters.indexOf(message.sender)&&(delete connection.broadcasters[connection.broadcasters.indexOf(message.sender)],connection.broadcasters=removeNullEntries(connection.broadcasters)));if("dropPeerConnection"===message.message)return void(connection.peers[message.sender]&&(connection.peers[message.sender].peer.close(),connection.peers[message.sender].peer=null,delete connection.peers[message.sender]));if(message.message.allParticipants)return-1===message.message.allParticipants.indexOf(message.sender)&&message.message.allParticipants.push(message.sender),void message.message.allParticipants.forEach(function(participant){mPeer[connection.peers[participant]?"renegotiatePeer":"createNewPeer"](participant,{localPeerSdpConstraints:{OfferToReceiveAudio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.sdpConstraints.mandatory.OfferToReceiveVideo},remotePeerSdpConstraints:{OfferToReceiveAudio:connection.session.oneway?!!connection.session.audio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.session.oneway?!!connection.session.video||!!connection.session.screen:connection.sdpConstraints.mandatory.OfferToReceiveVideo
-},isOneWay:!!connection.session.oneway||"one-way"===connection.direction,isDataOnly:isData(connection.session)})});if(message.message.newParticipant){if(message.message.newParticipant==connection.userid)return;if(connection.peers[message.message.newParticipant])return;return void mPeer.createNewPeer(message.message.newParticipant,message.message.userPreferences||{localPeerSdpConstraints:{OfferToReceiveAudio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.sdpConstraints.mandatory.OfferToReceiveVideo},remotePeerSdpConstraints:{OfferToReceiveAudio:connection.session.oneway?!!connection.session.audio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.session.oneway?!!connection.session.video||!!connection.session.screen:connection.sdpConstraints.mandatory.OfferToReceiveVideo},isOneWay:!!connection.session.oneway||"one-way"===connection.direction,isDataOnly:isData(connection.session)})}if((message.message.readyForOffer||message.message.addMeAsBroadcaster)&&connection.addNewBroadcaster(message.sender),message.message.newParticipationRequest&&message.sender!==connection.userid){connection.peers[message.sender]&&(connection.peers[message.sender].peer&&(connection.peers[message.sender].peer.close(),connection.peers[message.sender].peer=null),delete connection.peers[message.sender]);var userPreferences={extra:message.extra||{},localPeerSdpConstraints:message.message.remotePeerSdpConstraints||{OfferToReceiveAudio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.sdpConstraints.mandatory.OfferToReceiveVideo},remotePeerSdpConstraints:message.message.localPeerSdpConstraints||{OfferToReceiveAudio:connection.session.oneway?!!connection.session.audio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.session.oneway?!!connection.session.video||!!connection.session.screen:connection.sdpConstraints.mandatory.OfferToReceiveVideo},isOneWay:"undefined"!=typeof message.message.isOneWay?message.message.isOneWay:!!connection.session.oneway||"one-way"===connection.direction,isDataOnly:"undefined"!=typeof message.message.isDataOnly?message.message.isDataOnly:isData(connection.session),dontGetRemoteStream:"undefined"!=typeof message.message.isOneWay?message.message.isOneWay:!!connection.session.oneway||"one-way"===connection.direction,dontAttachLocalStream:!!message.message.dontGetRemoteStream,connectionDescription:message,successCallback:function(){("undefined"!=typeof message.message.isOneWay?message.message.isOneWay:!!connection.session.oneway||"one-way"===connection.direction)&&connection.addNewBroadcaster(message.sender,userPreferences),(connection.session.oneway||"one-way"===connection.direction||isData(connection.session))&&connection.addNewBroadcaster(message.sender,userPreferences)}};return void connection.onNewParticipant(message.sender,userPreferences)}return message.message.shiftedModerationControl?void connection.onShiftedModerationControl(message.sender,message.message.broadcasters):(message.message.changedUUID&&connection.peers[message.message.oldUUID]&&(connection.peers[message.message.newUUID]=connection.peers[message.message.oldUUID],delete connection.peers[message.message.oldUUID]),message.message.userLeft?(mPeer.onUserLeft(message.sender),void(message.message.autoCloseEntireSession&&connection.leave())):void mPeer.addNegotiatedMessage(message.message,message.sender))}}),socket.on("user-left",function(userid){onUserLeft(userid),connection.onUserStatusChanged({userid:userid,status:"offline",extra:connection.peers[userid]?connection.peers[userid].extra||{}:{}}),connection.onleave({userid:userid,extra:{}})}),socket.on("connect",function(){connection.enableLogs&&console.info("socket.io connection is opened."),socket.emit("extra-data-updated",connection.extra),connectCallback&&connectCallback(socket)}),socket.on("disconnect",function(){connection.enableLogs&&(console.info("socket.io connection is closed"),console.warn("socket.io reconnecting"))}),socket.on("join-with-password",function(remoteUserId){connection.onJoinWithPassword(remoteUserId)}),socket.on("invalid-password",function(remoteUserId,oldPassword){connection.onInvalidPassword(remoteUserId,oldPassword)}),socket.on("password-max-tries-over",function(remoteUserId){connection.onPasswordMaxTriesOver(remoteUserId)}),socket.on("user-disconnected",function(remoteUserId){remoteUserId!==connection.userid&&(connection.onUserStatusChanged({userid:remoteUserId,status:"offline",extra:connection.peers[remoteUserId]?connection.peers[remoteUserId].extra||{}:{}}),connection.peers[remoteUserId]&&connection.peers[remoteUserId].peer&&(connection.peers[remoteUserId].peer.close(),delete connection.peers[remoteUserId]))}),socket.on("user-connected",function(userid){userid!==connection.userid&&connection.onUserStatusChanged({userid:userid,status:"online",extra:connection.peers[userid]?connection.peers[userid].extra||{}:{}})}),socket.on("logs",function(log){connection.enableLogs&&console.debug("server-logs",log)}),socket}function MultiPeers(connection){function initFileBufferReader(){fbr=new FileBufferReader,fbr.onProgress=function(chunk){connection.onFileProgress(chunk)},fbr.onBegin=function(file){connection.onFileStart(file)},fbr.onEnd=function(file){connection.onFileEnd(file)}}var self=this,skipPeers=["getAllParticipants","getLength","selectFirst","streams","send","forEach"];connection.peers={getLength:function(){var numberOfPeers=0;for(var peer in this)-1==skipPeers.indexOf(peer)&&numberOfPeers++;return numberOfPeers},selectFirst:function(){var firstPeer;for(var peer in this)-1==skipPeers.indexOf(peer)&&(firstPeer=this[peer]);return firstPeer},getAllParticipants:function(sender){var allPeers=[];for(var peer in this)-1==skipPeers.indexOf(peer)&&peer!=sender&&allPeers.push(peer);return allPeers},forEach:function(callbcak){this.getAllParticipants().forEach(function(participant){callbcak(connection.peers[participant])})},send:function(data,remoteUserId){var that=this;if(!isNull(data.size)&&!isNull(data.type))return void self.shareFile(data,remoteUserId);if(!("text"===data.type||data instanceof ArrayBuffer||data instanceof DataView))return void TextSender.send({text:data,channel:this,connection:connection,remoteUserId:remoteUserId});if("text"===data.type&&(data=JSON.stringify(data)),remoteUserId){var remoteUser=connection.peers[remoteUserId];if(remoteUser)return void remoteUser.channels.forEach(function(channel){channel.send(data)})}this.getAllParticipants().forEach(function(participant){that[participant].channels.forEach(function(channel){channel.send(data)})})}},this.uuid=connection.userid,this.getLocalConfig=function(remoteSdp,remoteUserId,userPreferences){return userPreferences||(userPreferences={}),{streamsToShare:userPreferences.streamsToShare||{},session:connection.session,rtcMultiConnection:connection,connectionDescription:userPreferences.connectionDescription,remoteUserId:remoteUserId,localPeerSdpConstraints:userPreferences.localPeerSdpConstraints,remotePeerSdpConstraints:userPreferences.remotePeerSdpConstraints,dontGetRemoteStream:!!userPreferences.dontGetRemoteStream,dontAttachLocalStream:!!userPreferences.dontAttachLocalStream,optionalArgument:connection.optionalArgument,iceServers:connection.iceServers,renegotiatingPeer:!!userPreferences.renegotiatingPeer,peerRef:userPreferences.peerRef,enableDataChannels:!!connection.session.data,localStreams:connection.attachStreams,removeStreams:connection.removeStreams,onLocalSdp:function(localSdp){self.onNegotiationNeeded(localSdp,remoteUserId)},onLocalCandidate:function(localCandidate){localCandidate=OnIceCandidateHandler.processCandidates(connection,localCandidate),localCandidate&&self.onNegotiationNeeded(localCandidate,remoteUserId)},remoteSdp:remoteSdp,onDataChannelMessage:function(message){if(!fbr&&connection.enableFileSharing&&initFileBufferReader(),"string"==typeof message||!connection.enableFileSharing)return void self.onDataChannelMessage(message,remoteUserId);var that=this;return message instanceof ArrayBuffer||message instanceof DataView?void fbr.convertToObject(message,function(object){that.onDataChannelMessage(object)}):message.readyForNextChunk?void fbr.getNextChunk(message.uuid,function(nextChunk,isLastChunk){connection.peers[remoteUserId].channels.forEach(function(channel){channel.send(nextChunk)})},remoteUserId):void fbr.addChunk(message,function(promptNextChunk){connection.peers[remoteUserId].peer.channel.send(promptNextChunk)})},onDataChannelError:function(error){self.onDataChannelError(error,remoteUserId)},onDataChannelOpened:function(channel){self.onDataChannelOpened(channel,remoteUserId)},onDataChannelClosed:function(event){self.onDataChannelClosed(event,remoteUserId)},onRemoteStream:function(stream){if(connection.peers[remoteUserId].streams.push(stream),isPluginRTC){var mediaElement=document.createElement("video"),body=document.body||document.documentElement;return body.insertBefore(mediaElement,body.firstChild),void setTimeout(function(){Plugin.attachMediaStream(mediaElement,stream),self.onGettingRemoteMedia(mediaElement,remoteUserId)},3e3)}self.onGettingRemoteMedia(stream,remoteUserId)},onRemoteStreamRemoved:function(stream){self.onRemovingRemoteMedia(stream,remoteUserId)},onPeerStateChanged:function(states){self.onPeerStateChanged(states),"new"===states.iceConnectionState&&self.onNegotiationStarted(remoteUserId,states),"connected"===states.iceConnectionState&&self.onNegotiationCompleted(remoteUserId,states),-1!==states.iceConnectionState.search(/closed|failed/gi)&&(self.onUserLeft(remoteUserId),self.disconnectWith(remoteUserId))},processSdp:connection.processSdp,beforeAddingStream:connection.beforeAddingStream,beforeRemovingStream:connection.beforeRemovingStream}},this.createNewPeer=function(remoteUserId,userPreferences){if(!(connection.maxParticipantsAllowed<=connection.getAllParticipants().length)){if(userPreferences=userPreferences||{},!userPreferences.isOneWay&&!userPreferences.isDataOnly)return userPreferences.isOneWay=!0,void this.onNegotiationNeeded({enableMedia:!0,userPreferences:userPreferences},remoteUserId);userPreferences=connection.setUserPreferences(userPreferences,remoteUserId);var localConfig=this.getLocalConfig(null,remoteUserId,userPreferences);connection.peers[remoteUserId]=new PeerInitiator(localConfig)}},this.createAnsweringPeer=function(remoteSdp,remoteUserId,userPreferences){userPreferences=connection.setUserPreferences(userPreferences||{},remoteUserId);var localConfig=this.getLocalConfig(remoteSdp,remoteUserId,userPreferences);connection.peers[remoteUserId]=new PeerInitiator(localConfig)},this.renegotiatePeer=function(remoteUserId,userPreferences,remoteSdp){if(!connection.peers[remoteUserId])throw"This peer ("+remoteUserId+") does not exists.";userPreferences||(userPreferences={}),userPreferences.renegotiatingPeer=!0,userPreferences.peerRef=connection.peers[remoteUserId].peer;var localConfig=this.getLocalConfig(remoteSdp,remoteUserId,userPreferences);connection.peers[remoteUserId]=new PeerInitiator(localConfig)},this.replaceTrack=function(track,remoteUserId,isVideoTrack){if(!connection.peers[remoteUserId])throw"This peer ("+remoteUserId+") does not exists.";var peer=connection.peers[remoteUserId].peer;return peer.getSenders&&"function"==typeof peer.getSenders&&peer.getSenders().length?void peer.getSenders().forEach(function(rtpSender){isVideoTrack&&rtpSender.track instanceof VideoStreamTrack&&(connection.peers[remoteUserId].peer.lastVideoTrack=rtpSender.track,rtpSender.replaceTrack(track)),!isVideoTrack&&rtpSender.track instanceof AudioStreamTrack&&(connection.peers[remoteUserId].peer.lastAudioTrack=rtpSender.track,rtpSender.replaceTrack(track))}):(console.warn("RTPSender.replaceTrack is NOT supported."),void this.renegotiatePeer(remoteUserId))},this.onNegotiationNeeded=function(message,remoteUserId){},this.addNegotiatedMessage=function(message,remoteUserId){if(message.type&&message.sdp)return"answer"==message.type&&connection.peers[remoteUserId]&&connection.peers[remoteUserId].addRemoteSdp(message),"offer"==message.type&&(message.renegotiatingPeer?this.renegotiatePeer(remoteUserId,null,message):this.createAnsweringPeer(message,remoteUserId)),void(connection.enableLogs&&console.log("Remote peer's sdp:",message.sdp));if(message.candidate)return connection.peers[remoteUserId]&&connection.peers[remoteUserId].addRemoteCandidate(message),void(connection.enableLogs&&console.log("Remote peer's candidate pairs:",message.candidate));if(message.enableMedia){if(connection.attachStreams.length){var streamsToShare={};return connection.attachStreams.forEach(function(stream){streamsToShare[stream.streamid]={isAudio:!!stream.isAudio,isVideo:!!stream.isVideo,isScreen:!!stream.isScreen}}),message.userPreferences.streamsToShare=streamsToShare,void self.onNegotiationNeeded({readyForOffer:!0,userPreferences:message.userPreferences},remoteUserId)}var localMediaConstraints={},userPreferences=message.userPreferences;userPreferences.localPeerSdpConstraints.OfferToReceiveAudio&&(localMediaConstraints.audio=connection.mediaConstraints.audio),userPreferences.localPeerSdpConstraints.OfferToReceiveVideo&&(localMediaConstraints.video=connection.mediaConstraints.video),getUserMediaHandler({onGettingLocalMedia:function(localStream){self.onGettingLocalMedia(localStream);var streamsToShare={};connection.attachStreams.forEach(function(stream){streamsToShare[stream.streamid]={isAudio:!!stream.isAudio,isVideo:!!stream.isVideo,isScreen:!!stream.isScreen}}),message.userPreferences.streamsToShare=streamsToShare,self.onNegotiationNeeded({readyForOffer:!0,userPreferences:message.userPreferences},remoteUserId)},onLocalMediaError:function(error){self.onLocalMediaError(error),self.onNegotiationNeeded({readyForOffer:!0,userPreferences:message.userPreferences},remoteUserId)},localMediaConstraints:localMediaConstraints})}message.readyForOffer&&connection.onReadyForOffer(remoteUserId,message.userPreferences)},this.onGettingRemoteMedia=function(stream,remoteUserId){},this.onRemovingRemoteMedia=function(stream,remoteUserId){},this.onGettingLocalMedia=function(localStream){},this.onLocalMediaError=function(error){connection.enableLogs&&console.error("onLocalMediaError",JSON.stringify(error,null," ")),connection.onMediaError(error)};var fbr;this.shareFile=function(file,remoteUserId){if(!connection.enableFileSharing)throw'"connection.enableFileSharing" is false.';initFileBufferReader(),fbr.readAsArrayBuffer(file,function(uuid){var arrayOfUsers=connection.getAllParticipants();remoteUserId&&(arrayOfUsers=[remoteUserId]),arrayOfUsers.forEach(function(participant){fbr.getNextChunk(uuid,function(nextChunk){connection.peers[participant].channels.forEach(function(channel){channel.send(nextChunk)})},participant)})},{userid:connection.userid,chunkSize:connection.chunkSize||0})};var textReceiver=new TextReceiver(connection);this.onDataChannelMessage=function(message,remoteUserId){textReceiver.receive(JSON.parse(message),remoteUserId,connection.peers[remoteUserId]?connection.peers[remoteUserId].extra:{})},this.onDataChannelClosed=function(event,remoteUserId){event.userid=remoteUserId,event.extra=connection.peers[remoteUserId]?connection.peers[remoteUserId].extra:{},connection.onclose(event)},this.onDataChannelError=function(error,remoteUserId){error.userid=remoteUserId,event.extra=connection.peers[remoteUserId]?connection.peers[remoteUserId].extra:{},connection.onerror(error)},this.onDataChannelOpened=function(channel,remoteUserId){connection.peers[remoteUserId].channels.push(channel),connection.onopen({userid:remoteUserId,extra:connection.peers[remoteUserId]?connection.peers[remoteUserId].extra:{},channel:channel}),connection.observers.all()},this.onPeerStateChanged=function(state){connection.onPeerStateChanged(state)},this.onNegotiationStarted=function(remoteUserId,states){},this.onNegotiationCompleted=function(remoteUserId,states){},this.getRemoteStreams=function(remoteUserId){return remoteUserId=remoteUserId||connection.peers.getAllParticipants()[0],connection.peers[remoteUserId]?connection.peers[remoteUserId].streams:[]},this.isPluginRTC=connection.isPluginRTC=isPluginRTC}function fireEvent(obj,eventName,args){if("undefined"!=typeof CustomEvent){var eventDetail={arguments:args,__exposedProps__:args},event=new CustomEvent(eventName,eventDetail);obj.dispatchEvent(event)}}function setHarkEvents(connection,streamEvent){if(!connection||!streamEvent)throw"Both arguments are required.";if(connection.onspeaking&&connection.onsilence){if("undefined"==typeof hark)throw"hark.js not found.";hark(streamEvent.stream,{onspeaking:function(){connection.onspeaking(streamEvent)},onsilence:function(){connection.onsilence(streamEvent)},onvolumechange:function(volume,threshold){connection.onvolumechange&&connection.onvolumechange(merge({volume:volume,threshold:threshold},streamEvent))}})}}function setMuteHandlers(connection,streamEvent){streamEvent.stream.addEventListener("mute",function(event){event=connection.streamEvents[event.target.streamid],event.session={audio:"audio"===event.muteType,video:"video"===event.muteType},connection.onmute(event)},!1),streamEvent.stream.addEventListener("unmute",function(event){event=connection.streamEvents[event.target.streamid],event.session={audio:"audio"===event.unmuteType,video:"video"===event.unmuteType},connection.onunmute(event)},!1)}function getRandomString(){if(window.crypto&&window.crypto.getRandomValues&&-1===navigator.userAgent.indexOf("Safari")){for(var a=window.crypto.getRandomValues(new Uint32Array(3)),token="",i=0,l=a.length;l>i;i++)token+=a[i].toString(36);return token}return(Math.random()*(new Date).getTime()).toString(36).replace(/\./g,"")}function getRMCMediaElement(stream,callback,connection){var isAudioOnly=!1;stream.getVideoTracks().length||(isAudioOnly=!0);var mediaElement=document.createElement(isAudioOnly?"audio":"video");return isPluginRTC?(connection.videosContainer.insertBefore(mediaElement,connection.videosContainer.firstChild),void setTimeout(function(){Plugin.attachMediaStream(mediaElement,stream),callback(mediaElement)},1e3)):(mediaElement[isFirefox?"mozSrcObject":"src"]=isFirefox?stream:window.URL.createObjectURL(stream),mediaElement.controls=!0,isFirefox&&mediaElement.addEventListener("ended",function(){if(fireEvent(stream,"ended",stream),currentUserMediaRequest.remove(stream.idInstance),"local"===stream.type){StreamsHandler.onSyncNeeded(stream.streamid,"ended"),connection.attachStreams.forEach(function(aStream,idx){stream.streamid===aStream.streamid&&delete connection.attachStreams[idx]});var newStreamsArray=[];connection.attachStreams.forEach(function(aStream){aStream&&newStreamsArray.push(aStream)}),connection.attachStreams=newStreamsArray,connection.observers.all();var streamEvent=connection.streamEvents[stream.streamid];if(streamEvent)return void connection.onstreamended(streamEvent);this.parentNode&&this.parentNode.removeChild(this)}},!1),mediaElement.play(),void callback(mediaElement))}function listenEventHandler(eventName,eventHandler){window.removeEventListener(eventName,eventHandler),window.addEventListener(eventName,eventHandler,!1)}function removeNullEntries(array){var newArray=[];return array.forEach(function(item){item&&newArray.push(item)}),newArray}function isData(session){return!session.audio&&!session.video&&!session.screen&&session.data}function isNull(obj){return"undefined"==typeof obj}function isString(obj){return"string"==typeof obj}function observeObject(obj,callback){Object.observe&&Object.observe(obj,function(changes){var jsonStringified=JSON.stringify(changes);lastChanges!=jsonStringified&&(lastChanges=jsonStringified,callback(changes))})}function setSdpConstraints(config){var sdpConstraints,sdpConstraints_mandatory={OfferToReceiveAudio:!!config.OfferToReceiveAudio,OfferToReceiveVideo:!!config.OfferToReceiveVideo};return sdpConstraints={mandatory:sdpConstraints_mandatory,optional:[{VoiceActivityDetection:!1}]},navigator.mozGetUserMedia&&firefoxVersion>34&&(sdpConstraints={OfferToReceiveAudio:!!config.OfferToReceiveAudio,OfferToReceiveVideo:!!config.OfferToReceiveVideo}),sdpConstraints}function onPluginRTCInitialized(pluginRTCObject){Plugin=pluginRTCObject,MediaStreamTrack=Plugin.MediaStreamTrack,RTCPeerConnection=Plugin.RTCPeerConnection,RTCIceCandidate=Plugin.RTCIceCandidate,RTCSessionDescription=Plugin.RTCSessionDescription}function PeerInitiator(config){function createDataChannel(){if(!isOfferer)return void(peer.ondatachannel=function(event){var channel=event.channel;setChannelEvents(channel)});var channel=peer.createDataChannel("RTCDataChannel",{});setChannelEvents(channel)}function setChannelEvents(channel){channel.binaryType="arraybuffer",channel.onmessage=function(event){config.onDataChannelMessage(event.data)},channel.onopen=function(){config.onDataChannelOpened(channel)},channel.onerror=function(error){config.onDataChannelError(error)},channel.onclose=function(event){config.onDataChannelClosed(event)},channel.internalSend=channel.send,channel.send=function(data){"open"===channel.readyState&&channel.internalSend(data)},peer.channel=channel}var connection=config.rtcMultiConnection;this.extra=config.remoteSdp?config.remoteSdp.extra:connection.extra,this.remoteUserId=config.remoteUserId,this.streams=[],this.channels=[],this.connectionDescription=config.connectionDescription;var that=this;config.remoteSdp&&(this.connectionDescription=config.remoteSdp.connectionDescription);var allRemoteStreams={};if(Object.observe){var that=this;Object.observe(this.channels,function(changes){changes.forEach(function(change){"add"===change.type&&change.object[change.name].addEventListener("close",function(){delete that.channels[that.channels.indexOf(change.object[change.name])],that.channels=removeNullEntries(that.channels)},!1),("remove"===change.type||"delete"===change.type)&&-1!==that.channels.indexOf(change.object[change.name])&&delete that.channels.indexOf(change.object[change.name]),that.channels=removeNullEntries(that.channels)})})}defaults.sdpConstraints=setSdpConstraints({OfferToReceiveAudio:!0,OfferToReceiveVideo:!0});var peer,renegotiatingPeer=!!config.renegotiatingPeer;config.remoteSdp&&(renegotiatingPeer=!!config.remoteSdp.renegotiatingPeer);var localStreams=[];config.localStreams.forEach(function(stream){stream&&localStreams.push(stream)}),renegotiatingPeer?(peer=config.peerRef,peer.getLocalStreams().forEach(function(stream){localStreams.forEach(function(localStream,index){stream==localStream&&delete localStreams[index]}),config.removeStreams.forEach(function(streamToRemove,index){stream===streamToRemove&&(stream=config.beforeRemovingStream(stream),stream&&peer.removeStream&&peer.removeStream(stream),localStreams.forEach(function(localStream,index){streamToRemove==localStream&&delete localStreams[index]}))})})):peer=new RTCPeerConnection(navigator.onLine?{iceServers:config.iceServers,iceTransports:"all"}:null,config.optionalArgument),"Firefox"===connection.DetectRTC.browser.name&&(peer.removeStream=function(stream){stream.mute(),connection.StreamsHandler.onSyncNeeded(stream.streamid,"stream-removed")}),peer.onicecandidate=function(event){event.candidate&&config.onLocalCandidate({candidate:event.candidate.candidate,sdpMid:event.candidate.sdpMid,sdpMLineIndex:event.candidate.sdpMLineIndex})};var isFirefoxOffered=!isFirefox;config.remoteSdp&&config.remoteSdp.remotePeerSdpConstraints&&config.remoteSdp.remotePeerSdpConstraints.isFirefoxOffered&&(isFirefoxOffered=!0),localStreams.forEach(function(localStream){config.remoteSdp&&config.remoteSdp.remotePeerSdpConstraints&&config.remoteSdp.remotePeerSdpConstraints.dontGetRemoteStream||config.dontAttachLocalStream||(localStream=config.beforeAddingStream(localStream),localStream&&peer.addStream(localStream))}),peer.oniceconnectionstatechange=peer.onsignalingstatechange=function(){var extra=that.extra;if(connection.peers[that.remoteUserId]&&(extra=connection.peers[that.remoteUserId].extra||extra),!peer)return void that.removeAllRemoteStreams();if(-1!==peer.iceConnectionState.search(/closed|failed/gi)){if(peer.firedOnce)return;if(peer.firedOnce=!0,that.removeAllRemoteStreams(),that.connectionDescription&&connection.userid==that.connectionDescription.sender&&connection.autoReDialOnFailure){if(connection.isInitiator)return;setTimeout(function(){connection.rejoin(that.connectionDescription),peer&&(peer.firedOnce=!1)},5e3)}}config.onPeerStateChanged({iceConnectionState:peer.iceConnectionState,iceGatheringState:peer.iceGatheringState,signalingState:peer.signalingState,extra:extra,userid:that.remoteUserId})};var sdpConstraints={OfferToReceiveAudio:!!localStreams.length,OfferToReceiveVideo:!!localStreams.length};config.localPeerSdpConstraints&&(sdpConstraints=config.localPeerSdpConstraints),defaults.sdpConstraints=setSdpConstraints(sdpConstraints),peer.onaddstream=function(event){var streamsToShare={};config.remoteSdp&&config.remoteSdp.streamsToShare?streamsToShare=config.remoteSdp.streamsToShare:config.streamsToShare&&(streamsToShare=config.streamsToShare);var streamToShare=streamsToShare[event.stream.id];streamToShare&&(event.stream.isAudio=streamToShare.isAudio,event.stream.isVideo=streamToShare.isVideo,event.stream.isScreen=streamToShare.isScreen),event.stream.streamid=event.stream.id,event.stream.stop||(event.stream.stop=function(){fireEvent(event.stream,"ended",event)}),allRemoteStreams[event.stream.id]=event.stream,config.onRemoteStream(event.stream)},peer.onremovestream=function(event){event.stream.streamid=event.stream.id,allRemoteStreams[event.stream.id]&&delete allRemoteStreams[event.stream.id],config.onRemoteStreamRemoved(event.stream)},this.addRemoteCandidate=function(remoteCandidate){peer.addIceCandidate(new RTCIceCandidate(remoteCandidate))},this.addRemoteSdp=function(remoteSdp){peer.setRemoteDescription(new RTCSessionDescription(remoteSdp),function(){},function(error){connection.enableLogs&&console.error(JSON.stringify(error,null," ")),connection.autoReDialOnFailure&&setTimeout(function(){connection.rejoin(that.connectionDescription)},2e3)})};var isOfferer=!0;config.remoteSdp&&(isOfferer=!1),config.enableDataChannels===!0&&createDataChannel(),config.remoteSdp&&(config.remoteSdp.remotePeerSdpConstraints&&(sdpConstraints=config.remoteSdp.remotePeerSdpConstraints),defaults.sdpConstraints=setSdpConstraints(sdpConstraints),this.addRemoteSdp(config.remoteSdp)),("two-way"==config.session.audio||"two-way"==config.session.video||"two-way"==config.session.screen)&&(defaults.sdpConstraints=setSdpConstraints({OfferToReceiveAudio:"two-way"==config.session.audio||config.remoteSdp&&config.remoteSdp.remotePeerSdpConstraints&&config.remoteSdp.remotePeerSdpConstraints.OfferToReceiveAudio,OfferToReceiveVideo:"two-way"==config.session.video||"two-way"==config.session.screen||config.remoteSdp&&config.remoteSdp.remotePeerSdpConstraints&&config.remoteSdp.remotePeerSdpConstraints.OfferToReceiveAudio}));var streamsToShare={};peer.getLocalStreams().forEach(function(stream){streamsToShare[stream.streamid]={isAudio:!!stream.isAudio,isVideo:!!stream.isVideo,isScreen:!!stream.isScreen}}),peer[isOfferer?"createOffer":"createAnswer"](function(localSdp){localSdp.sdp=config.processSdp(localSdp.sdp),peer.setLocalDescription(localSdp),config.onLocalSdp({type:localSdp.type,sdp:localSdp.sdp,remotePeerSdpConstraints:config.remotePeerSdpConstraints||!1,renegotiatingPeer:!!config.renegotiatingPeer||!1,connectionDescription:that.connectionDescription,dontGetRemoteStream:!!config.dontGetRemoteStream,extra:connection?connection.extra:{},streamsToShare:streamsToShare,isFirefoxOffered:isFirefox})},function(error){connection.enableLogs&&console.error("sdp-error",error),connection.autoReDialOnFailure&&connection.isInitiator&&isFirefox&&isFirefoxOffered&&setTimeout(function(){connection.rejoin(that.connectionDescription)},5e3)},defaults.sdpConstraints),peer.nativeClose=peer.close,peer.close=function(){if(!peer)return void that.removeAllRemoteStreams();connection.multiPeersHandler.onNegotiationNeeded({userLeft:!0,autoCloseEntireSession:!!connection.autoCloseEntireSession},that.remoteUserId);try{-1===peer.iceConnectionState.search(/closed|failed/gi)&&peer.getRemoteStreams().forEach(function(stream){stream.stop()}),peer.nativeClose()}catch(e){}peer=null},this.removeAllRemoteStreams=function(){for(var id in allRemoteStreams)config.onRemoteStreamRemoved(allRemoteStreams[id]);allRemoteStreams={},that.streams.forEach(function(stream){stream.stop()}),that.streams=[]},this.peer=peer}function loadIceFrame(callback,skip){if(!loadedIceFrame){if(!skip)return loadIceFrame(callback,!0);loadedIceFrame=!0;var iframe=document.createElement("iframe");iframe.onload=function(){function iFrameLoaderCallback(event){event.data&&event.data.iceServers&&(callback(event.data.iceServers),window.removeEventListener("message",iFrameLoaderCallback))}iframe.isLoaded=!0,listenEventHandler("message",iFrameLoaderCallback),iframe.contentWindow.postMessage("get-ice-servers","*")},iframe.src="https://cdn.webrtc-experiment.com/getIceServers/",iframe.style.display="none",(document.body||document.documentElement).appendChild(iframe)}}function requestUserMedia(constraints){return new Promise(function(resolve,reject){getUserMedia(constraints,resolve,reject)})}function setStreamType(constraints,stream){constraints.mandatory&&constraints.mandatory.chromeMediaSource?stream.isScreen=!0:constraints.mozMediaSource||constraints.mediaSource?stream.isScreen=!0:constraints.video?stream.isVideo=!0:constraints.audio&&(stream.isAudio=!0)}function getUserMediaHandler(options){function streaming(stream,returnBack){setStreamType(options.localMediaConstraints,stream),options.onGettingLocalMedia(stream,returnBack),stream.addEventListener("ended",function(){delete currentUserMediaRequest.streams[idInstance],currentUserMediaRequest.mutex=!1,currentUserMediaRequest.queueRequests.indexOf(options)&&(delete currentUserMediaRequest.queueRequests[currentUserMediaRequest.queueRequests.indexOf(options)],currentUserMediaRequest.queueRequests=removeNullEntries(currentUserMediaRequest.queueRequests))},!1),currentUserMediaRequest.streams[idInstance]={stream:stream},currentUserMediaRequest.mutex=!1,currentUserMediaRequest.queueRequests.length&&getUserMediaHandler(currentUserMediaRequest.queueRequests.shift())}if(currentUserMediaRequest.mutex===!0)return void currentUserMediaRequest.queueRequests.push(options);currentUserMediaRequest.mutex=!0;var idInstance=JSON.stringify(options.localMediaConstraints);if(currentUserMediaRequest.streams[idInstance])streaming(currentUserMediaRequest.streams[idInstance].stream,!0);else{if(isPluginRTC){document.createElement("video");return void Plugin.getUserMedia({audio:!0,video:!0},function(stream){stream.streamid=stream.id||getRandomString(),streaming(stream)},function(error){})}"undefined"!=typeof DetectRTC&&(DetectRTC.hasMicrophone||(options.localMediaConstraints.audio=!1),DetectRTC.hasWebcam||(options.localMediaConstraints.video=!1)),navigator.mediaDevices.getUserMedia(options.localMediaConstraints).then(function(stream){stream.streamid=stream.streamid||stream.id||getRandomString(),stream.idInstance=idInstance,streaming(stream)})["catch"](function(error){options.onLocalMediaError(error,options.localMediaConstraints)})}}function TextReceiver(connection){function receive(data,userid,extra){var uuid=data.uuid;if(content[uuid]||(content[uuid]=[]),content[uuid].push(data.message),data.last){var message=content[uuid].join("");data.isobject&&(message=JSON.parse(message));var receivingTime=(new Date).getTime(),latency=receivingTime-data.sendingTime,e={data:message,userid:userid,extra:extra,latency:latency};connection.autoTranslateText?(e.original=e.data,connection.Translator.TranslateText(e.data,function(translatedText){e.data=translatedText,connection.onmessage(e)})):connection.onmessage(e),delete content[uuid]}}var content={};return{receive:receive}}var isOpera=!!window.opera||navigator.userAgent.indexOf(" OPR/")>=0,isFirefox="undefined"!=typeof window.InstallTrigger,isSafari=Object.prototype.toString.call(window.HTMLElement).indexOf("Constructor")>0,isChrome=!!window.chrome&&!isOpera,isIE=!!document.documentMode,isPluginRTC=isSafari||isIE,chromeVersion=(!!navigator.userAgent.match(/Android|iPhone|iPad|iPod|BlackBerry|IEMobile/i),
+"use strict";!function(){function RTCMultiConnection(roomid){function onUserLeft(remoteUserId){connection.peers[remoteUserId]&&connection.peers[remoteUserId].peer&&(connection.peers[remoteUserId].streams.forEach(function(stream){stream.stop()}),connection.peers[remoteUserId]&&(connection.peers[remoteUserId].peer.close(),connection.peers[remoteUserId]&&(connection.peers[remoteUserId].peer=null)),connection.onleave({userid:remoteUserId,extra:connection.peers[remoteUserId]?connection.peers[remoteUserId].extra:{}})),delete connection.peers[remoteUserId]}function connectSocket(connectCallback){if(socket)return void(connectCallback&&connectCallback(socket));if("undefined"==typeof SocketConnection)if("undefined"!=typeof FirebaseConnection)window.SocketConnection=FirebaseConnection;else{if("undefined"==typeof PubNubConnection)throw"SocketConnection.js seems missed.";window.SocketConnection=PubNubConnection}socket=new SocketConnection(connection,function(s){socket=s,connectCallback&&connectCallback(socket)})}function beforeUnload(shiftModerationControlOnLeave){if(connection.closeBeforeUnload&&(connection.peers.getAllParticipants().forEach(function(participant){mPeer.onNegotiationNeeded({userLeft:!0,autoCloseEntireSession:!!connection.autoCloseEntireSession},participant),connection.peers[participant]&&connection.peers[participant].peer&&connection.peers[participant].peer.close()}),socket&&("undefined"!=typeof socket.disconnect&&(connection.autoReDialOnFailure=!1,socket.disconnect()),socket=null),connection.broadcasters.length&&!connection.autoCloseEntireSession)){var firstBroadcaster=connection.broadcasters[0],otherBroadcasters=[];connection.broadcasters.forEach(function(broadcaster){broadcaster!==firstBroadcaster&&otherBroadcasters.push(broadcaster)}),connection.shiftModerationControl(firstBroadcaster,otherBroadcasters,"undefined"!=typeof shiftModerationControlOnLeave?shiftModerationControlOnLeave:!0),connection.broadcasters=[],connection.isInitiator=!1}}function applyConstraints(stream,mediaConstraints){return stream?(mediaConstraints.audio&&stream.getAudioTracks().forEach(function(track){track.applyConstraints(mediaConstraints.audio)}),void(mediaConstraints.video&&stream.getVideoTracks().forEach(function(track){track.applyConstraints(mediaConstraints.video)}))):void(connection.enableLogs&&console.error("No stream to applyConstraints."))}function replaceTrack(track,remoteUserId,isVideoTrack){return remoteUserId?void mPeer.replaceTrack(track,remoteUserId,isVideoTrack):void connection.peers.getAllParticipants().forEach(function(participant){mPeer.replaceTrack(track,participant,isVideoTrack)})}function setStreamEndHandler(stream,isRemote){isRemote=!!isRemote,stream.alreadySetEndHandler||(stream.alreadySetEndHandler=!0,stream&&stream.addEventListener&&stream.addEventListener("ended",function(){stream.idInstance&¤tUserMediaRequest.remove(stream.idInstance),isRemote||(delete connection.attachStreams[connection.attachStreams.indexOf(stream)],-1===connection.removeStreams.indexOf(stream)&&connection.removeStreams.push(stream),connection.attachStreams=removeNullEntries(connection.attachStreams),connection.removeStreams=removeNullEntries(connection.removeStreams),connection.observers.all());var streamEvent=connection.streamEvents[stream.streamid];streamEvent||(streamEvent={stream:stream,streamid:stream.streamid,type:isRemote?"remote":"local",userid:connection.userid,extra:connection.extra,mediaElement:connection.streamEvents[stream.streamid]?connection.streamEvents[stream.streamid].mediaElement:null}),connection.onstreamended(streamEvent),delete connection.streamEvents[stream.streamid]},!1))}var connection=this;connection.channel=connection.sessionid=(roomid||location.href.replace(/\/|:|#|\?|\$|\^|%|\.|`|~|!|\+|@|\[|\||]|\|*. /g,"").split("\n").join("").split("\r").join(""))+"";var mPeer=new MultiPeers(connection);mPeer.onGettingLocalMedia=function(stream){stream.type="local",setStreamEndHandler(stream),getRMCMediaElement(stream,function(mediaElement){mediaElement.id=stream.streamid,mediaElement.muted=!0,mediaElement.volume=0,-1===connection.attachStreams.indexOf(stream)&&connection.attachStreams.push(stream),"undefined"!=typeof StreamsHandler&&StreamsHandler.setHandlers(stream,!0,connection),connection.streamEvents[stream.streamid]={stream:stream,type:"local",mediaElement:mediaElement,userid:connection.userid,extra:connection.extra,streamid:stream.streamid,blobURL:mediaElement.src||URL.createObjectURL(stream),isAudioMuted:!0},setHarkEvents(connection,connection.streamEvents[stream.streamid]),setMuteHandlers(connection,connection.streamEvents[stream.streamid]),connection.onstream(connection.streamEvents[stream.streamid])},connection),connection.observers.all()},mPeer.onGettingRemoteMedia=function(stream,remoteUserId){stream.type="remote",setStreamEndHandler(stream,"remote-stream"),getRMCMediaElement(stream,function(mediaElement){mediaElement.id=stream.streamid,"undefined"!=typeof StreamsHandler&&StreamsHandler.setHandlers(stream,!1,connection),connection.streamEvents[stream.streamid]={stream:stream,type:"remote",userid:remoteUserId,extra:connection.peers[remoteUserId]?connection.peers[remoteUserId].extra:{},mediaElement:mediaElement,streamid:stream.streamid,blobURL:mediaElement.src||URL.createObjectURL(stream)},setMuteHandlers(connection,connection.streamEvents[stream.streamid]),connection.onstream(connection.streamEvents[stream.streamid])},connection)},mPeer.onRemovingRemoteMedia=function(stream,remoteUserId){var streamEvent=connection.streamEvents[stream.streamid];streamEvent||(streamEvent={stream:stream,type:"remote",userid:remoteUserId,extra:connection.peers[remoteUserId]?connection.peers[remoteUserId].extra:{},streamid:stream.streamid,mediaElement:connection.streamEvents[stream.streamid]?connection.streamEvents[stream.streamid].mediaElement:null}),connection.onstreamended(streamEvent),delete connection.streamEvents[stream.streamid]},mPeer.onNegotiationNeeded=function(message,remoteUserId,callback){connectSocket(function(){socket.emit(connection.socketMessageEvent,"password"in message?message:{remoteUserId:message.remoteUserId||remoteUserId,message:message,sender:connection.userid},callback||function(){})})},mPeer.onUserLeft=onUserLeft,mPeer.disconnectWith=function(remoteUserId,callback){socket&&socket.emit("disconnect-with",remoteUserId,callback||function(){}),connection.peers[remoteUserId]&&(connection.peers[remoteUserId].peer&&connection.peers[remoteUserId].peer.close(),delete connection.peers[remoteUserId])},connection.broadcasters=[],connection.socketOptions={transport:"polling"};var socket;connection.openOrJoin=function(localUserid,password){connection.checkPresence(localUserid,function(isRoomExists,roomid){if("function"==typeof password&&(password(isRoomExists,roomid),password=null),isRoomExists){connection.sessionid=roomid;var localPeerSdpConstraints=!1,remotePeerSdpConstraints=!1,isOneWay=!!connection.session.oneway,isDataOnly=isData(connection.session);remotePeerSdpConstraints={OfferToReceiveAudio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.sdpConstraints.mandatory.OfferToReceiveVideo},localPeerSdpConstraints={OfferToReceiveAudio:isOneWay?!!connection.session.audio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:isOneWay?!!connection.session.video||!!connection.session.screen:connection.sdpConstraints.mandatory.OfferToReceiveVideo};var connectionDescription={remoteUserId:connection.sessionid,message:{newParticipationRequest:!0,isOneWay:isOneWay,isDataOnly:isDataOnly,localPeerSdpConstraints:localPeerSdpConstraints,remotePeerSdpConstraints:remotePeerSdpConstraints},sender:connection.userid,password:password||!1};return void mPeer.onNegotiationNeeded(connectionDescription)}connection.userid;connection.userid=connection.sessionid=localUserid||connection.sessionid,connection.userid+="",socket.emit("changed-uuid",connection.userid),password&&socket.emit("set-password",password),connection.isInitiator=!0,isData(connection.session)||connection.captureUserMedia()})},connection.open=function(localUserid,isPublicModerator){connection.userid;return connection.userid=connection.sessionid=localUserid||connection.sessionid,connection.userid+="",connection.isInitiator=!0,connectSocket(function(){socket.emit("changed-uuid",connection.userid),1==isPublicModerator&&connection.becomePublicModerator()}),isData(connection.session)?void("function"==typeof isPublicModerator&&isPublicModerator()):void connection.captureUserMedia("function"==typeof isPublicModerator?isPublicModerator:null)},connection.becomePublicModerator=function(){connection.isInitiator&&socket.emit("become-a-public-moderator")},connection.rejoin=function(connectionDescription){if(!connection.isInitiator&&connectionDescription&&Object.keys(connectionDescription).length){var extra={};connection.peers[connectionDescription.remoteUserId]&&(extra=connection.peers[connectionDescription.remoteUserId].extra,connection.peers[connectionDescription.remoteUserId].peer&&(connection.peers[connectionDescription.remoteUserId].peer=null),delete connection.peers[connectionDescription.remoteUserId]),connectionDescription&&connectionDescription.remoteUserId&&(connection.join(connectionDescription.remoteUserId),connection.onReConnecting({userid:connectionDescription.remoteUserId,extra:extra}))}},connection.join=connection.connect=function(remoteUserId,options){connection.sessionid=(remoteUserId?remoteUserId.sessionid||remoteUserId.remoteUserId||remoteUserId:!1)||connection.sessionid,connection.sessionid+="";var localPeerSdpConstraints=!1,remotePeerSdpConstraints=!1,isOneWay=!1,isDataOnly=!1;if(remoteUserId&&remoteUserId.session||!remoteUserId||"string"==typeof remoteUserId){var session=remoteUserId?remoteUserId.session||connection.session:connection.session;isOneWay=!!session.oneway,isDataOnly=isData(session),remotePeerSdpConstraints={OfferToReceiveAudio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.sdpConstraints.mandatory.OfferToReceiveVideo},localPeerSdpConstraints={OfferToReceiveAudio:isOneWay?!!connection.session.audio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:isOneWay?!!connection.session.video||!!connection.session.screen:connection.sdpConstraints.mandatory.OfferToReceiveVideo}}options=options||{},"undefined"!=typeof options.localPeerSdpConstraints&&(localPeerSdpConstraints=options.localPeerSdpConstraints),"undefined"!=typeof options.remotePeerSdpConstraints&&(remotePeerSdpConstraints=options.remotePeerSdpConstraints),"undefined"!=typeof options.isOneWay&&(isOneWay=options.isOneWay),"undefined"!=typeof options.isDataOnly&&(isDataOnly=options.isDataOnly);var connectionDescription={remoteUserId:connection.sessionid,message:{newParticipationRequest:!0,isOneWay:isOneWay,isDataOnly:isDataOnly,localPeerSdpConstraints:localPeerSdpConstraints,remotePeerSdpConstraints:remotePeerSdpConstraints},sender:connection.userid,password:!1};return connectSocket(function(){connection.peers[connection.sessionid]||mPeer.onNegotiationNeeded(connectionDescription)}),connectionDescription},connection.connectWithAllParticipants=function(remoteUserId){mPeer.onNegotiationNeeded("connectWithAllParticipants",remoteUserId||connection.sessionid)},connection.removeFromBroadcastersList=function(remoteUserId){mPeer.onNegotiationNeeded("removeFromBroadcastersList",remoteUserId||connection.sessionid),connection.peers.getAllParticipants(remoteUserId||connection.sessionid).forEach(function(participant){mPeer.onNegotiationNeeded("dropPeerConnection",participant),connection.peers[participant].peer.close(),connection.peers[participant].peer=null,delete connection.peers[participant]}),connection.attachStreams.forEach(function(stream){stream.addEventListener("ended",function(){connection.renegotiate(remoteUserId||connection.sessionid)},!1),stream.stop()})},connection.getUserMedia=connection.captureUserMedia=function(callback,session){function invokeGetUserMedia(localMediaConstraints,getUserMedia_callback){var isScreen=!1;localMediaConstraints&&(isScreen=localMediaConstraints.isScreen,delete localMediaConstraints.isScreen),getUserMediaHandler({onGettingLocalMedia:function(stream){return stream.isAudio=stream.isVideo=stream.isScreen=!1,isScreen?stream.isScreen=!0:session.audio&&session.video?stream.isVideo=!0:session.audio&&(stream.isAudio=!0),mPeer.onGettingLocalMedia(stream),getUserMedia_callback?getUserMedia_callback():void(callback&&callback(stream))},onLocalMediaError:function(error){mPeer.onLocalMediaError(error),callback&&callback()},localMediaConstraints:localMediaConstraints||{audio:session.audio?connection.mediaConstraints.audio:!1,video:session.video?connection.mediaConstraints.video:!1}})}return connection.observers.all(),session=session||connection.session,connection.dontCaptureUserMedia||isData(session)?void(callback&&callback()):void((session.audio||session.video||session.screen)&&(session.screen?connection.getScreenConstraints(function(error,screen_constraints){if(error)throw error;invokeGetUserMedia({video:screen_constraints,isScreen:!0},session.audio||session.video?invokeGetUserMedia:!1)}):(session.audio||session.video)&&invokeGetUserMedia()))},connection.closeBeforeUnload=!0,window.addEventListener("beforeunload",beforeUnload,!1),connection.userid=getRandomString(),connection.changeUserId=function(newUserId){connection.userid=newUserId||getRandomString(),socket.emit("changed-uuid",connection.userid)},connection.observers={extra:function(){observeObject(connection.extra,function(changes){socket.emit("extra-data-updated",connection.extra)})},attachStreams:function(){observeObject(connection.attachStreams,function(changes){changes.forEach(function(change){"add"===change.type&&setStreamEndHandler(change.object[change.name]),("remove"===change.type||"delete"===change.type)&&-1===connection.removeStreams.indexOf(change.object[change.name])&&connection.removeStreams.push(change.object[change.name]),connection.attachStreams=removeNullEntries(connection.attachStreams),connection.removeStreams=removeNullEntries(connection.removeStreams),connection.observers.all()})})},all:function(){this.extra(),this.attachStreams(),socket&&socket.emit("extra-data-updated",connection.extra)}},connection.extra={},connection.attachStreams=[],connection.removeStreams=[],connection.observers.all(),connection.session={audio:!0,video:!0},connection.enableFileSharing=!1,connection.mediaConstraints={audio:{mandatory:{},optional:[]},video:{mandatory:{},optional:[]}},DetectRTC.load(function(){DetectRTC.MediaDevices.forEach(function(device){"audioinput"===device.kind&&(connection.mediaConstraints.audio={optional:[{sourceId:device.id},{bandwidth:connection.bandwidth.audio||1024e3}],mandatory:{}},isFirefox&&(connection.mediaConstraints.audio={deviceId:device.id})),"videoinput"===device.kind&&(connection.mediaConstraints.video={optional:[{sourceId:device.id},{googLeakyBucket:!0},{bandwidth:connection.bandwidth.video||2048e3}],mandatory:{}},isFirefox&&(connection.mediaConstraints.video={deviceId:device.id}))})}),connection.sdpConstraints={mandatory:{OfferToReceiveAudio:!0,OfferToReceiveVideo:!0},optional:[{VoiceActivityDetection:!1}]},connection.optionalArgument={optional:[{DtlsSrtpKeyAgreement:!0},{googImprovedWifiBwe:!0},{googScreencastMinBitrate:300},{googIPv6:!0},{googDscp:!0},{googCpuUnderuseThreshold:55},{googCpuOveruseThreshold:85},{googSuspendBelowMinBitrate:!0},{googCpuOveruseDetection:!0}],mandatory:{}},connection.iceServers=IceServersHandler.getIceServers(connection),connection.candidates={host:!0,stun:!0,turn:!0},connection.iceProtocols={tcp:!0,udp:!0},connection.onopen=function(event){connection.enableLogs&&console.info("Data connection has been opened between you & ",event.userid)},connection.onclose=function(event){connection.enableLogs&&console.warn("Data connection has been closed between you & ",event.userid)},connection.onerror=function(error){connection.enableLogs&&console.error(error.userid,"data-error",error)},connection.onmessage=function(event){connection.enableLogs&&console.debug("data-message",event.userid,event.data)},connection.send=function(data,remoteUserId){connection.peers.send(data,remoteUserId)},connection.close=connection.disconnect=connection.leave=function(){beforeUnload(!1)},connection.onstream=function(e){var parentNode=connection.videosContainer;parentNode.insertBefore(e.mediaElement,parentNode.firstChild)},connection.onstreamended=function(e){e.mediaElement||(e.mediaElement=document.getElementById(e.streamid)),e.mediaElement&&e.mediaElement.parentNode&&e.mediaElement.parentNode.removeChild(e.mediaElement)},connection.direction="many-to-many",Array.prototype.getStreamById=function(streamid){var stream;return this.forEach(function(_stream){_stream.streamid==streamid&&(stream=_stream)}),stream},connection.removeStream=function(streamid){var stream;return connection.attachStreams.forEach(function(localStream){localStream.id===streamid&&(stream=localStream)}),stream?void(-1===connection.removeStreams.indexOf(stream)&&(connection.removeStreams.push(stream),connection.peers.getAllParticipants().forEach(function(participant){mPeer.renegotiatePeer(participant)}))):void console.warn("No such stream exists.",streamid)},connection.addStream=function(session){function invokeGetUserMedia(localMediaConstraints,callback){getUserMediaHandler({onGettingLocalMedia:function(stream){var videoConstraints=localMediaConstraints?localMediaConstraints.video:connection.mediaConstraints;return videoConstraints&&(videoConstraints.mediaSource||videoConstraints.mozMediaSource?stream.isScreen=!0:videoConstraints.mandatory&&videoConstraints.mandatory.chromeMediaSource&&(stream.isScreen=!0)),stream.isScreen||(stream.isVideo=stream.getVideoTracks().length,stream.isAudio=!stream.isVideo&&stream.getAudioTracks().length),mPeer.onGettingLocalMedia(stream),session.streamCallback&&session.streamCallback(stream),callback?callback():void connection.renegotiate()},onLocalMediaError:function(error){return mPeer.onLocalMediaError(error),callback?callback():void connection.renegotiate()},localMediaConstraints:localMediaConstraints||{audio:session.audio?connection.mediaConstraints.audio:!1,video:session.video?connection.mediaConstraints.video:!1}})}return isData(session)?void connection.renegotiate():void((!session.audio||session.video||session.screen)&&(session.screen?connection.getScreenConstraints(function(error,screen_constraints){return error?alert(error):void invokeGetUserMedia({video:screen_constraints},session.audio||session.video?invokeGetUserMedia:!1)}):(session.audio||session.video)&&invokeGetUserMedia()))},connection.applyConstraints=function(mediaConstraints,streamid){if(!MediaStreamTrack||!MediaStreamTrack.prototype.applyConstraints)return void alert("track.applyConstraints is NOT supported in your browser.");if(streamid){return connection.streamEvents[streamid]&&(stream=connection.streamEvents[streamid].stream),void applyConstraints(stream,mediaConstraints)}connection.attachStreams.forEach(function(stream){applyConstraints(stream,mediaConstraints)})},connection.replaceTrack=function(session,remoteUserId,isVideoTrack){function invokeGetUserMedia(localMediaConstraints,callback){getUserMediaHandler({onGettingLocalMedia:function(stream){return mPeer.onGettingLocalMedia(stream),callback?callback():void connection.replaceTrack(stream,remoteUserId,isVideoTrack||session.video||session.screen)},onLocalMediaError:function(error){mPeer.onLocalMediaError(error),callback&&callback()},localMediaConstraints:localMediaConstraints||{audio:session.audio?connection.mediaConstraints.audio:!1,video:session.video?connection.mediaConstraints.video:!1}})}if(session=session||{},!RTCPeerConnection.prototype.getSenders)return void this.addStream(session);if(session instanceof MediaStreamTrack)return void replaceTrack(session,remoteUserId,isVideoTrack);if(session instanceof MediaStream)return void replaceTrack(session.getVideoTracks()[0],remoteUserId,isVideoTrack);if(isData(session))throw"connection.replaceTrack requires audio and/or video and/or screen.";(!session.audio||session.video||session.screen)&&(session.screen?connection.getScreenConstraints(function(error,screen_constraints){return error?alert(error):void invokeGetUserMedia({video:screen_constraints},session.audio||session.video?invokeGetUserMedia:!1)}):(session.audio||session.video)&&invokeGetUserMedia())},connection.resetTrack=function(remoteUsersIds,isVideoTrack){remoteUsersIds||(remoteUsersIds=connection.getAllParticipants()),"string"==typeof remoteUsersIds&&(remoteUsersIds=[remoteUsersIds]),remoteUsersIds.forEach(function(participant){var peer=connection.peers[participant].peer;"undefined"!=typeof isVideoTrack&&isVideoTrack!==!0||!peer.lastVideoTrack||connection.replaceTrack(peer.lastVideoTrack,participant,!0),"undefined"!=typeof isVideoTrack&&isVideoTrack!==!1||!peer.lastAudioTrack||connection.replaceTrack(peer.lastAudioTrack,participant,!1)})},connection.renegotiate=function(remoteUserId){return remoteUserId?void mPeer.renegotiatePeer(remoteUserId):void connection.peers.getAllParticipants().forEach(function(participant){mPeer.renegotiatePeer(participant)})},connection.onMediaError=function(error){connection.enableLogs&&console.error(error)},connection.addNewBroadcaster=function(broadcasterId,userPreferences){connection.broadcasters.forEach(function(broadcaster){mPeer.onNegotiationNeeded({newParticipant:broadcasterId,userPreferences:userPreferences||!1},broadcaster)}),connection.session.oneway||"many-to-many"!==connection.direction||-1!==connection.broadcasters.indexOf(broadcasterId)||connection.broadcasters.push(broadcasterId)},connection.filesContainer=connection.videosContainer=document.body||document.documentElement,connection.isInitiator=!1,connection.shareFile=mPeer.shareFile,"undefined"!=typeof FileProgressBarHandler&&FileProgressBarHandler.handle(connection),connection.autoCloseEntireSession=!1,"undefined"!=typeof TranslationHandler&&TranslationHandler.handle(connection),connection.token=getRandomString,connection.onNewParticipant=function(participantId,userPreferences){connection.acceptParticipationRequest(participantId,userPreferences)},connection.acceptParticipationRequest=function(participantId,userPreferences){userPreferences.successCallback&&(userPreferences.successCallback(),delete userPreferences.successCallback),mPeer.createNewPeer(participantId,userPreferences)},connection.onShiftedModerationControl=function(sender,existingBroadcasters){connection.acceptModerationControl(sender,existingBroadcasters)},connection.acceptModerationControl=function(sender,existingBroadcasters){connection.isInitiator=!0,connection.broadcasters=existingBroadcasters,connection.peers.getAllParticipants().forEach(function(participant){mPeer.onNegotiationNeeded({changedUUID:sender,oldUUID:connection.userid,newUUID:sender},participant)}),connection.userid=sender,socket.emit("changed-uuid",connection.userid)},connection.shiftModerationControl=function(remoteUserId,existingBroadcasters,firedOnLeave){mPeer.onNegotiationNeeded({shiftedModerationControl:!0,broadcasters:existingBroadcasters,firedOnLeave:!!firedOnLeave},remoteUserId)},connection.processSdp=function(sdp){return sdp=BandwidthHandler.setApplicationSpecificBandwidth(sdp,connection.bandwidth,!!connection.session.screen),sdp=BandwidthHandler.setVideoBitrates(sdp,{min:connection.bandwidth.video,max:connection.bandwidth.video}),sdp=BandwidthHandler.setOpusAttributes(sdp)},"undefined"!=typeof BandwidthHandler&&(connection.BandwidthHandler=BandwidthHandler),"undefined"!=typeof StreamsHandler&&(connection.StreamsHandler=StreamsHandler),connection.bandwidth={screen:300,audio:50,video:256},connection.onleave=function(userid){},connection.invokeSelectFileDialog=function(callback){var selector=new FileSelector;selector.selectSingleFile(callback)},connection.getPublicModerators=function(userIdStartsWith,callback){"function"==typeof userIdStartsWith&&(callback=userIdStartsWith),connectSocket(function(socket){socket.emit("get-public-moderators","string"==typeof userIdStartsWith?userIdStartsWith:"",callback)})},connection.onmute=function(e){e.mediaElement&&("both"===e.muteType||"video"===e.muteType?(e.mediaElement.src=null,e.mediaElement.pause(),e.mediaElement.poster=e.snapshot||"https://cdn.webrtc-experiment.com/images/muted.png"):"audio"===e.muteType&&(e.mediaElement.muted=!0))},connection.onunmute=function(e){e.mediaElement&&("both"===e.unmuteType||"video"===e.unmuteType?(e.mediaElement.poster=null,e.mediaElement.src=URL.createObjectURL(e.stream),e.mediaElement.play()):"audio"===e.unmuteType&&(e.mediaElement.muted=!1))},connection.onExtraDataUpdated=function(event){event.status="online",connection.onUserStatusChanged(event,!0)},connection.onJoinWithPassword=function(remoteUserId){console.warn(remoteUserId,"is password protected. Please join with password.")},connection.onInvalidPassword=function(remoteUserId,oldPassword){console.warn(remoteUserId,"is password protected. Please join with valid password. Your old password",oldPassword,"is wrong.")},connection.onPasswordMaxTriesOver=function(remoteUserId){console.warn(remoteUserId,"is password protected. Your max password tries exceeded the limit.")},connection.getAllParticipants=function(){return connection.peers.getAllParticipants()},"undefined"!=typeof StreamsHandler&&(StreamsHandler.onSyncNeeded=function(streamid,action,type){connection.peers.getAllParticipants().forEach(function(participant){mPeer.onNegotiationNeeded({streamid:streamid,action:action,streamSyncNeeded:!0,type:type||"both"},participant)})}),connection.getAllVideos=function(remoteUserId){var videos=[];return Array.prototype.slice.call(document.querySelectorAll("video")).forEach(function(video){video.getAttribute("data-userid")===remoteUserId&&videos.push(video)}),videos},connection.connectSocket=function(callback){connectSocket(callback)},connection.getSocket=function(callback){return socket?callback&&callback(socket):connectSocket(callback),socket},connection.getRemoteStreams=mPeer.getRemoteStreams,connection.autoReDialOnFailure=!0;var skipStreams=["selectFirst","selectAll","forEach"];connection.streamEvents={selectFirst:function(options){if(!options){var firstStream;for(var str in connection.streamEvents)-1!==skipStreams.indexOf(str)||firstStream||(firstStream=connection.streamEvents[str]);return firstStream}},selectAll:function(){}},connection.socketURL="/",connection.socketMessageEvent="RTCMultiConnection-Message",connection.socketCustomEvent="RTCMultiConnection-Custom-Message",connection.DetectRTC=DetectRTC,connection.onUserStatusChanged=function(event,dontWriteLogs){connection.enableLogs&&!dontWriteLogs&&console.info(event.userid,event.status)},connection.getUserMediaHandler=getUserMediaHandler,connection.multiPeersHandler=mPeer,connection.enableLogs=!0,connection.setCustomSocketHandler=function(customSocketHandler){"undefined"!=typeof SocketConnection&&(SocketConnection=customSocketHandler)},connection.chunkSize=65e3,connection.maxParticipantsAllowed=1e3,connection.disconnectWith=mPeer.disconnectWith,connection.checkPresence=function(remoteUserId,callback){mPeer.onNegotiationNeeded({detectPresence:!0,userid:(remoteUserId||connection.sessionid)+""},"system",callback)},connection.onReadyForOffer=function(remoteUserId,userPreferences){connection.multiPeersHandler.createNewPeer(remoteUserId,userPreferences)},connection.setUserPreferences=function(userPreferences){return connection.dontAttachStream&&(userPreferences.dontAttachLocalStream=!0),connection.dontGetRemoteStream&&(userPreferences.dontGetRemoteStream=!0),userPreferences},connection.updateExtraData=function(){socket.emit("extra-data-updated",connection.extra)},connection.enableScalableBroadcast=!1,connection.singleBroadcastAttendees=3,connection.dontCaptureUserMedia=!1,connection.dontAttachStream=!1,connection.dontGetRemoteStream=!1,connection.onReConnecting=function(event){connection.enableLogs&&console.info("ReConnecting with",event.userid,"...")},connection.beforeAddingStream=function(stream){return stream},connection.beforeRemovingStream=function(stream){return stream},"undefined"!=typeof isChromeExtensionAvailable&&(connection.checkIfChromeExtensionAvailable=isChromeExtensionAvailable),"undefined"!=typeof isFirefoxExtensionAvailable&&(connection.checkIfChromeExtensionAvailable=isFirefoxExtensionAvailable),"undefined"!=typeof getChromeExtensionStatus&&(connection.getChromeExtensionStatus=getChromeExtensionStatus),connection.getScreenConstraints=function(callback){getScreenConstraints(function(error,screen_constraints){error||(screen_constraints=connection.modifyScreenConstraints(screen_constraints),callback(error,screen_constraints))})},connection.modifyScreenConstraints=function(screen_constraints){return screen_constraints},connection.onPeerStateChanged=function(state){connection.enableLogs&&-1!==state.iceConnectionState.search(/closed|failed/gi)&&console.error("Peer connection is closed between you & ",state.userid,state.extra,"state:",state.iceConnectionState)}}function SocketConnection(connection,connectCallback){var parameters="";parameters+="?userid="+connection.userid,parameters+="&msgEvent="+connection.socketMessageEvent,parameters+="&socketCustomEvent="+connection.socketCustomEvent,connection.enableScalableBroadcast&&(parameters+="&enableScalableBroadcast=true",parameters+="&singleBroadcastAttendees="+connection.singleBroadcastAttendees);var socket=io.connect((connection.socketURL||"/")+parameters,connection.socketOptions),mPeer=connection.multiPeersHandler;return socket.on("extra-data-updated",function(remoteUserId,extra){connection.peers[remoteUserId]&&(connection.peers[remoteUserId].extra=extra,connection.onExtraDataUpdated({userid:remoteUserId,extra:extra}))}),socket.on(connection.socketMessageEvent,function(message){if(message.remoteUserId==connection.userid){if(connection.peers[message.sender]&&connection.peers[message.sender].extra!=message.extra&&(connection.peers[message.sender].extra=message.extra,connection.onExtraDataUpdated({userid:message.sender,extra:message.extra})),message.message.streamSyncNeeded&&connection.peers[message.sender]){var stream=connection.streamEvents[message.message.streamid];if(!stream||!stream.stream)return;var action=message.message.action;if("ended"===action||"stream-removed"===action)return void connection.onstreamended(stream);var type="both"!=message.message.type?message.message.type:null;return void stream.stream[action](type)}if("connectWithAllParticipants"===message.message)return-1===connection.broadcasters.indexOf(message.sender)&&connection.broadcasters.push(message.sender),void mPeer.onNegotiationNeeded({allParticipants:connection.peers.getAllParticipants(message.sender)},message.sender);if("removeFromBroadcastersList"===message.message)return void(-1!==connection.broadcasters.indexOf(message.sender)&&(delete connection.broadcasters[connection.broadcasters.indexOf(message.sender)],connection.broadcasters=removeNullEntries(connection.broadcasters)));if("dropPeerConnection"===message.message)return void(connection.peers[message.sender]&&(connection.peers[message.sender].peer.close(),connection.peers[message.sender].peer=null,delete connection.peers[message.sender]));if(message.message.allParticipants)return-1===message.message.allParticipants.indexOf(message.sender)&&message.message.allParticipants.push(message.sender),void message.message.allParticipants.forEach(function(participant){mPeer[connection.peers[participant]?"renegotiatePeer":"createNewPeer"](participant,{localPeerSdpConstraints:{OfferToReceiveAudio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.sdpConstraints.mandatory.OfferToReceiveVideo},remotePeerSdpConstraints:{OfferToReceiveAudio:connection.session.oneway?!!connection.session.audio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.session.oneway?!!connection.session.video||!!connection.session.screen:connection.sdpConstraints.mandatory.OfferToReceiveVideo
+},isOneWay:!!connection.session.oneway||"one-way"===connection.direction,isDataOnly:isData(connection.session)})});if(message.message.newParticipant){if(message.message.newParticipant==connection.userid)return;if(connection.peers[message.message.newParticipant])return;return void mPeer.createNewPeer(message.message.newParticipant,message.message.userPreferences||{localPeerSdpConstraints:{OfferToReceiveAudio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.sdpConstraints.mandatory.OfferToReceiveVideo},remotePeerSdpConstraints:{OfferToReceiveAudio:connection.session.oneway?!!connection.session.audio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.session.oneway?!!connection.session.video||!!connection.session.screen:connection.sdpConstraints.mandatory.OfferToReceiveVideo},isOneWay:!!connection.session.oneway||"one-way"===connection.direction,isDataOnly:isData(connection.session)})}if((message.message.readyForOffer||message.message.addMeAsBroadcaster)&&connection.addNewBroadcaster(message.sender),message.message.newParticipationRequest&&message.sender!==connection.userid){connection.peers[message.sender]&&(connection.peers[message.sender].peer&&(connection.peers[message.sender].peer.close(),connection.peers[message.sender].peer=null),delete connection.peers[message.sender]);var userPreferences={extra:message.extra||{},localPeerSdpConstraints:message.message.remotePeerSdpConstraints||{OfferToReceiveAudio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.sdpConstraints.mandatory.OfferToReceiveVideo},remotePeerSdpConstraints:message.message.localPeerSdpConstraints||{OfferToReceiveAudio:connection.session.oneway?!!connection.session.audio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.session.oneway?!!connection.session.video||!!connection.session.screen:connection.sdpConstraints.mandatory.OfferToReceiveVideo},isOneWay:"undefined"!=typeof message.message.isOneWay?message.message.isOneWay:!!connection.session.oneway||"one-way"===connection.direction,isDataOnly:"undefined"!=typeof message.message.isDataOnly?message.message.isDataOnly:isData(connection.session),dontGetRemoteStream:"undefined"!=typeof message.message.isOneWay?message.message.isOneWay:!!connection.session.oneway||"one-way"===connection.direction,dontAttachLocalStream:!!message.message.dontGetRemoteStream,connectionDescription:message,successCallback:function(){("undefined"!=typeof message.message.isOneWay?message.message.isOneWay:!!connection.session.oneway||"one-way"===connection.direction)&&connection.addNewBroadcaster(message.sender,userPreferences),(connection.session.oneway||"one-way"===connection.direction||isData(connection.session))&&connection.addNewBroadcaster(message.sender,userPreferences)}};return void connection.onNewParticipant(message.sender,userPreferences)}return message.message.shiftedModerationControl?void connection.onShiftedModerationControl(message.sender,message.message.broadcasters):(message.message.changedUUID&&connection.peers[message.message.oldUUID]&&(connection.peers[message.message.newUUID]=connection.peers[message.message.oldUUID],delete connection.peers[message.message.oldUUID]),message.message.userLeft?(mPeer.onUserLeft(message.sender),void(message.message.autoCloseEntireSession&&connection.leave())):void mPeer.addNegotiatedMessage(message.message,message.sender))}}),socket.on("user-left",function(userid){onUserLeft(userid),connection.onUserStatusChanged({userid:userid,status:"offline",extra:connection.peers[userid]?connection.peers[userid].extra||{}:{}}),connection.onleave({userid:userid,extra:{}})}),socket.on("connect",function(){connection.enableLogs&&console.info("socket.io connection is opened."),socket.emit("extra-data-updated",connection.extra),connectCallback&&connectCallback(socket)}),socket.on("disconnect",function(){connection.enableLogs&&(console.info("socket.io connection is closed"),console.warn("socket.io reconnecting"))}),socket.on("join-with-password",function(remoteUserId){connection.onJoinWithPassword(remoteUserId)}),socket.on("invalid-password",function(remoteUserId,oldPassword){connection.onInvalidPassword(remoteUserId,oldPassword)}),socket.on("password-max-tries-over",function(remoteUserId){connection.onPasswordMaxTriesOver(remoteUserId)}),socket.on("user-disconnected",function(remoteUserId){remoteUserId!==connection.userid&&(connection.onUserStatusChanged({userid:remoteUserId,status:"offline",extra:connection.peers[remoteUserId]?connection.peers[remoteUserId].extra||{}:{}}),connection.peers[remoteUserId]&&connection.peers[remoteUserId].peer&&(connection.peers[remoteUserId].peer.close(),delete connection.peers[remoteUserId]))}),socket.on("user-connected",function(userid){userid!==connection.userid&&connection.onUserStatusChanged({userid:userid,status:"online",extra:connection.peers[userid]?connection.peers[userid].extra||{}:{}})}),socket.on("logs",function(log){connection.enableLogs&&console.debug("server-logs",log)}),socket}function MultiPeers(connection){function initFileBufferReader(){fbr=new FileBufferReader,fbr.onProgress=function(chunk){connection.onFileProgress(chunk)},fbr.onBegin=function(file){connection.onFileStart(file)},fbr.onEnd=function(file){connection.onFileEnd(file)}}var self=this,skipPeers=["getAllParticipants","getLength","selectFirst","streams","send","forEach"];connection.peers={getLength:function(){var numberOfPeers=0;for(var peer in this)-1==skipPeers.indexOf(peer)&&numberOfPeers++;return numberOfPeers},selectFirst:function(){var firstPeer;for(var peer in this)-1==skipPeers.indexOf(peer)&&(firstPeer=this[peer]);return firstPeer},getAllParticipants:function(sender){var allPeers=[];for(var peer in this)-1==skipPeers.indexOf(peer)&&peer!=sender&&allPeers.push(peer);return allPeers},forEach:function(callbcak){this.getAllParticipants().forEach(function(participant){callbcak(connection.peers[participant])})},send:function(data,remoteUserId){var that=this;if(!isNull(data.size)&&!isNull(data.type))return void self.shareFile(data,remoteUserId);if(!("text"===data.type||data instanceof ArrayBuffer||data instanceof DataView))return void TextSender.send({text:data,channel:this,connection:connection,remoteUserId:remoteUserId});if("text"===data.type&&(data=JSON.stringify(data)),remoteUserId){var remoteUser=connection.peers[remoteUserId];if(remoteUser)return void remoteUser.channels.forEach(function(channel){channel.send(data)})}this.getAllParticipants().forEach(function(participant){that[participant].channels.forEach(function(channel){channel.send(data)})})}},this.uuid=connection.userid,this.getLocalConfig=function(remoteSdp,remoteUserId,userPreferences){return userPreferences||(userPreferences={}),{streamsToShare:userPreferences.streamsToShare||{},session:connection.session,rtcMultiConnection:connection,connectionDescription:userPreferences.connectionDescription,remoteUserId:remoteUserId,localPeerSdpConstraints:userPreferences.localPeerSdpConstraints,remotePeerSdpConstraints:userPreferences.remotePeerSdpConstraints,dontGetRemoteStream:!!userPreferences.dontGetRemoteStream,dontAttachLocalStream:!!userPreferences.dontAttachLocalStream,optionalArgument:connection.optionalArgument,iceServers:connection.iceServers,renegotiatingPeer:!!userPreferences.renegotiatingPeer,peerRef:userPreferences.peerRef,enableDataChannels:!!connection.session.data,localStreams:connection.attachStreams,removeStreams:connection.removeStreams,onLocalSdp:function(localSdp){self.onNegotiationNeeded(localSdp,remoteUserId)},onLocalCandidate:function(localCandidate){localCandidate=OnIceCandidateHandler.processCandidates(connection,localCandidate),localCandidate&&self.onNegotiationNeeded(localCandidate,remoteUserId)},remoteSdp:remoteSdp,onDataChannelMessage:function(message){if(!fbr&&connection.enableFileSharing&&initFileBufferReader(),"string"==typeof message||!connection.enableFileSharing)return void self.onDataChannelMessage(message,remoteUserId);var that=this;return message instanceof ArrayBuffer||message instanceof DataView?void fbr.convertToObject(message,function(object){that.onDataChannelMessage(object)}):message.readyForNextChunk?void fbr.getNextChunk(message.uuid,function(nextChunk,isLastChunk){connection.peers[remoteUserId].channels.forEach(function(channel){channel.send(nextChunk)})},remoteUserId):void fbr.addChunk(message,function(promptNextChunk){connection.peers[remoteUserId].peer.channel.send(promptNextChunk)})},onDataChannelError:function(error){self.onDataChannelError(error,remoteUserId)},onDataChannelOpened:function(channel){self.onDataChannelOpened(channel,remoteUserId)},onDataChannelClosed:function(event){self.onDataChannelClosed(event,remoteUserId)},onRemoteStream:function(stream){if(connection.peers[remoteUserId].streams.push(stream),isPluginRTC){var mediaElement=document.createElement("video"),body=document.body||document.documentElement;return body.insertBefore(mediaElement,body.firstChild),void setTimeout(function(){Plugin.attachMediaStream(mediaElement,stream),self.onGettingRemoteMedia(mediaElement,remoteUserId)},3e3)}self.onGettingRemoteMedia(stream,remoteUserId)},onRemoteStreamRemoved:function(stream){self.onRemovingRemoteMedia(stream,remoteUserId)},onPeerStateChanged:function(states){self.onPeerStateChanged(states),"new"===states.iceConnectionState&&self.onNegotiationStarted(remoteUserId,states),"connected"===states.iceConnectionState&&self.onNegotiationCompleted(remoteUserId,states),-1!==states.iceConnectionState.search(/closed|failed/gi)&&(self.onUserLeft(remoteUserId),self.disconnectWith(remoteUserId))},processSdp:connection.processSdp,beforeAddingStream:connection.beforeAddingStream,beforeRemovingStream:connection.beforeRemovingStream}},this.createNewPeer=function(remoteUserId,userPreferences){if(!(connection.maxParticipantsAllowed<=connection.getAllParticipants().length)){if(userPreferences=userPreferences||{},!userPreferences.isOneWay&&!userPreferences.isDataOnly)return userPreferences.isOneWay=!0,void this.onNegotiationNeeded({enableMedia:!0,userPreferences:userPreferences},remoteUserId);userPreferences=connection.setUserPreferences(userPreferences,remoteUserId);var localConfig=this.getLocalConfig(null,remoteUserId,userPreferences);connection.peers[remoteUserId]=new PeerInitiator(localConfig)}},this.createAnsweringPeer=function(remoteSdp,remoteUserId,userPreferences){userPreferences=connection.setUserPreferences(userPreferences||{},remoteUserId);var localConfig=this.getLocalConfig(remoteSdp,remoteUserId,userPreferences);connection.peers[remoteUserId]=new PeerInitiator(localConfig)},this.renegotiatePeer=function(remoteUserId,userPreferences,remoteSdp){if(!connection.peers[remoteUserId])throw"This peer ("+remoteUserId+") does not exists.";userPreferences||(userPreferences={}),userPreferences.renegotiatingPeer=!0,userPreferences.peerRef=connection.peers[remoteUserId].peer;var localConfig=this.getLocalConfig(remoteSdp,remoteUserId,userPreferences);connection.peers[remoteUserId]=new PeerInitiator(localConfig)},this.replaceTrack=function(track,remoteUserId,isVideoTrack){if(!connection.peers[remoteUserId])throw"This peer ("+remoteUserId+") does not exists.";var peer=connection.peers[remoteUserId].peer;return peer.getSenders&&"function"==typeof peer.getSenders&&peer.getSenders().length?void peer.getSenders().forEach(function(rtpSender){isVideoTrack&&rtpSender.track instanceof VideoStreamTrack&&(connection.peers[remoteUserId].peer.lastVideoTrack=rtpSender.track,rtpSender.replaceTrack(track)),!isVideoTrack&&rtpSender.track instanceof AudioStreamTrack&&(connection.peers[remoteUserId].peer.lastAudioTrack=rtpSender.track,rtpSender.replaceTrack(track))}):(console.warn("RTPSender.replaceTrack is NOT supported."),void this.renegotiatePeer(remoteUserId))},this.onNegotiationNeeded=function(message,remoteUserId){},this.addNegotiatedMessage=function(message,remoteUserId){if(message.type&&message.sdp)return"answer"==message.type&&connection.peers[remoteUserId]&&connection.peers[remoteUserId].addRemoteSdp(message),"offer"==message.type&&(message.renegotiatingPeer?this.renegotiatePeer(remoteUserId,null,message):this.createAnsweringPeer(message,remoteUserId)),void(connection.enableLogs&&console.log("Remote peer's sdp:",message.sdp));if(message.candidate)return connection.peers[remoteUserId]&&connection.peers[remoteUserId].addRemoteCandidate(message),void(connection.enableLogs&&console.log("Remote peer's candidate pairs:",message.candidate));if(message.enableMedia){if(connection.attachStreams.length){var streamsToShare={};return connection.attachStreams.forEach(function(stream){streamsToShare[stream.streamid]={isAudio:!!stream.isAudio,isVideo:!!stream.isVideo,isScreen:!!stream.isScreen}}),message.userPreferences.streamsToShare=streamsToShare,void self.onNegotiationNeeded({readyForOffer:!0,userPreferences:message.userPreferences},remoteUserId)}var localMediaConstraints={},userPreferences=message.userPreferences;userPreferences.localPeerSdpConstraints.OfferToReceiveAudio&&(localMediaConstraints.audio=connection.mediaConstraints.audio),userPreferences.localPeerSdpConstraints.OfferToReceiveVideo&&(localMediaConstraints.video=connection.mediaConstraints.video),getUserMediaHandler({onGettingLocalMedia:function(localStream){self.onGettingLocalMedia(localStream);var streamsToShare={};connection.attachStreams.forEach(function(stream){streamsToShare[stream.streamid]={isAudio:!!stream.isAudio,isVideo:!!stream.isVideo,isScreen:!!stream.isScreen}}),message.userPreferences.streamsToShare=streamsToShare,self.onNegotiationNeeded({readyForOffer:!0,userPreferences:message.userPreferences},remoteUserId)},onLocalMediaError:function(error){self.onLocalMediaError(error),self.onNegotiationNeeded({readyForOffer:!0,userPreferences:message.userPreferences},remoteUserId)},localMediaConstraints:localMediaConstraints})}message.readyForOffer&&connection.onReadyForOffer(remoteUserId,message.userPreferences)},this.onGettingRemoteMedia=function(stream,remoteUserId){},this.onRemovingRemoteMedia=function(stream,remoteUserId){},this.onGettingLocalMedia=function(localStream){},this.onLocalMediaError=function(error){connection.enableLogs&&console.error("onLocalMediaError",JSON.stringify(error,null," ")),connection.onMediaError(error)};var fbr;this.shareFile=function(file,remoteUserId){if(!connection.enableFileSharing)throw'"connection.enableFileSharing" is false.';initFileBufferReader(),fbr.readAsArrayBuffer(file,function(uuid){var arrayOfUsers=connection.getAllParticipants();remoteUserId&&(arrayOfUsers=[remoteUserId]),arrayOfUsers.forEach(function(participant){fbr.getNextChunk(uuid,function(nextChunk){connection.peers[participant].channels.forEach(function(channel){channel.send(nextChunk)})},participant)})},{userid:connection.userid,chunkSize:isFirefox?15e3:connection.chunkSize||0})};var textReceiver=new TextReceiver(connection);this.onDataChannelMessage=function(message,remoteUserId){textReceiver.receive(JSON.parse(message),remoteUserId,connection.peers[remoteUserId]?connection.peers[remoteUserId].extra:{})},this.onDataChannelClosed=function(event,remoteUserId){event.userid=remoteUserId,event.extra=connection.peers[remoteUserId]?connection.peers[remoteUserId].extra:{},connection.onclose(event)},this.onDataChannelError=function(error,remoteUserId){error.userid=remoteUserId,event.extra=connection.peers[remoteUserId]?connection.peers[remoteUserId].extra:{},connection.onerror(error)},this.onDataChannelOpened=function(channel,remoteUserId){connection.peers[remoteUserId].channels.length||(connection.peers[remoteUserId].channels.push(channel),connection.onopen({userid:remoteUserId,extra:connection.peers[remoteUserId]?connection.peers[remoteUserId].extra:{},channel:channel}),connection.observers.all())},this.onPeerStateChanged=function(state){connection.onPeerStateChanged(state)},this.onNegotiationStarted=function(remoteUserId,states){},this.onNegotiationCompleted=function(remoteUserId,states){},this.getRemoteStreams=function(remoteUserId){return remoteUserId=remoteUserId||connection.peers.getAllParticipants()[0],connection.peers[remoteUserId]?connection.peers[remoteUserId].streams:[]},this.isPluginRTC=connection.isPluginRTC=isPluginRTC}function fireEvent(obj,eventName,args){if("undefined"!=typeof CustomEvent){var eventDetail={arguments:args,__exposedProps__:args},event=new CustomEvent(eventName,eventDetail);obj.dispatchEvent(event)}}function setHarkEvents(connection,streamEvent){if(!connection||!streamEvent)throw"Both arguments are required.";if(connection.onspeaking&&connection.onsilence){if("undefined"==typeof hark)throw"hark.js not found.";hark(streamEvent.stream,{onspeaking:function(){connection.onspeaking(streamEvent)},onsilence:function(){connection.onsilence(streamEvent)},onvolumechange:function(volume,threshold){connection.onvolumechange&&connection.onvolumechange(merge({volume:volume,threshold:threshold},streamEvent))}})}}function setMuteHandlers(connection,streamEvent){streamEvent.stream.addEventListener("mute",function(event){event=connection.streamEvents[event.target.streamid],event.session={audio:"audio"===event.muteType,video:"video"===event.muteType},connection.onmute(event)},!1),streamEvent.stream.addEventListener("unmute",function(event){event=connection.streamEvents[event.target.streamid],event.session={audio:"audio"===event.unmuteType,video:"video"===event.unmuteType},connection.onunmute(event)},!1)}function getRandomString(){if(window.crypto&&window.crypto.getRandomValues&&-1===navigator.userAgent.indexOf("Safari")){for(var a=window.crypto.getRandomValues(new Uint32Array(3)),token="",i=0,l=a.length;l>i;i++)token+=a[i].toString(36);return token}return(Math.random()*(new Date).getTime()).toString(36).replace(/\./g,"")}function getRMCMediaElement(stream,callback,connection){var isAudioOnly=!1;stream.getVideoTracks().length||(isAudioOnly=!0);var mediaElement=document.createElement(isAudioOnly?"audio":"video");return isPluginRTC?(connection.videosContainer.insertBefore(mediaElement,connection.videosContainer.firstChild),void setTimeout(function(){Plugin.attachMediaStream(mediaElement,stream),callback(mediaElement)},1e3)):(mediaElement[isFirefox?"mozSrcObject":"src"]=isFirefox?stream:window.URL.createObjectURL(stream),mediaElement.controls=!0,isFirefox&&mediaElement.addEventListener("ended",function(){if(fireEvent(stream,"ended",stream),currentUserMediaRequest.remove(stream.idInstance),"local"===stream.type){StreamsHandler.onSyncNeeded(stream.streamid,"ended"),connection.attachStreams.forEach(function(aStream,idx){stream.streamid===aStream.streamid&&delete connection.attachStreams[idx]});var newStreamsArray=[];connection.attachStreams.forEach(function(aStream){aStream&&newStreamsArray.push(aStream)}),connection.attachStreams=newStreamsArray,connection.observers.all();var streamEvent=connection.streamEvents[stream.streamid];if(streamEvent)return void connection.onstreamended(streamEvent);this.parentNode&&this.parentNode.removeChild(this)}},!1),mediaElement.play(),void callback(mediaElement))}function listenEventHandler(eventName,eventHandler){window.removeEventListener(eventName,eventHandler),window.addEventListener(eventName,eventHandler,!1)}function removeNullEntries(array){var newArray=[];return array.forEach(function(item){item&&newArray.push(item)}),newArray}function isData(session){return!session.audio&&!session.video&&!session.screen&&session.data}function isNull(obj){return"undefined"==typeof obj}function isString(obj){return"string"==typeof obj}function observeObject(obj,callback){Object.observe&&Object.observe(obj,function(changes){var jsonStringified=JSON.stringify(changes);lastChanges!=jsonStringified&&(lastChanges=jsonStringified,callback(changes))})}function setSdpConstraints(config){var sdpConstraints,sdpConstraints_mandatory={OfferToReceiveAudio:!!config.OfferToReceiveAudio,OfferToReceiveVideo:!!config.OfferToReceiveVideo};return sdpConstraints={mandatory:sdpConstraints_mandatory,optional:[{VoiceActivityDetection:!1}]},navigator.mozGetUserMedia&&firefoxVersion>34&&(sdpConstraints={OfferToReceiveAudio:!!config.OfferToReceiveAudio,OfferToReceiveVideo:!!config.OfferToReceiveVideo}),sdpConstraints}function onPluginRTCInitialized(pluginRTCObject){Plugin=pluginRTCObject,MediaStreamTrack=Plugin.MediaStreamTrack,RTCPeerConnection=Plugin.RTCPeerConnection,RTCIceCandidate=Plugin.RTCIceCandidate,RTCSessionDescription=Plugin.RTCSessionDescription}function PeerInitiator(config){function createDataChannel(){if(!isOfferer)return void(peer.ondatachannel=function(event){var channel=event.channel;setChannelEvents(channel)});var channel=peer.createDataChannel("RTCDataChannel",{});setChannelEvents(channel)}function setChannelEvents(channel){channel.binaryType="arraybuffer",channel.onmessage=function(event){config.onDataChannelMessage(event.data)},channel.onopen=function(){config.onDataChannelOpened(channel)},channel.onerror=function(error){config.onDataChannelError(error)},channel.onclose=function(event){config.onDataChannelClosed(event)},channel.internalSend=channel.send,channel.send=function(data){"open"===channel.readyState&&channel.internalSend(data)},peer.channel=channel}var connection=config.rtcMultiConnection;this.extra=config.remoteSdp?config.remoteSdp.extra:connection.extra,this.remoteUserId=config.remoteUserId,this.streams=[],this.channels=[],this.connectionDescription=config.connectionDescription;var that=this;config.remoteSdp&&(this.connectionDescription=config.remoteSdp.connectionDescription);var allRemoteStreams={};if(Object.observe){var that=this;Object.observe(this.channels,function(changes){changes.forEach(function(change){"add"===change.type&&change.object[change.name].addEventListener("close",function(){delete that.channels[that.channels.indexOf(change.object[change.name])],that.channels=removeNullEntries(that.channels)},!1),("remove"===change.type||"delete"===change.type)&&-1!==that.channels.indexOf(change.object[change.name])&&delete that.channels.indexOf(change.object[change.name]),that.channels=removeNullEntries(that.channels)})})}defaults.sdpConstraints=setSdpConstraints({OfferToReceiveAudio:!0,OfferToReceiveVideo:!0});var peer,renegotiatingPeer=!!config.renegotiatingPeer;config.remoteSdp&&(renegotiatingPeer=!!config.remoteSdp.renegotiatingPeer);var localStreams=[];config.localStreams.forEach(function(stream){stream&&localStreams.push(stream)}),renegotiatingPeer?(peer=config.peerRef,peer.getLocalStreams().forEach(function(stream){localStreams.forEach(function(localStream,index){stream==localStream&&delete localStreams[index]}),config.removeStreams.forEach(function(streamToRemove,index){stream===streamToRemove&&(stream=config.beforeRemovingStream(stream),stream&&peer.removeStream&&peer.removeStream(stream),localStreams.forEach(function(localStream,index){streamToRemove==localStream&&delete localStreams[index]}))})})):peer=new RTCPeerConnection(navigator.onLine?{iceServers:config.iceServers,iceTransports:"all"}:null,config.optionalArgument),"Firefox"===connection.DetectRTC.browser.name&&(peer.removeStream=function(stream){stream.mute(),connection.StreamsHandler.onSyncNeeded(stream.streamid,"stream-removed")}),peer.onicecandidate=function(event){event.candidate&&config.onLocalCandidate({candidate:event.candidate.candidate,sdpMid:event.candidate.sdpMid,sdpMLineIndex:event.candidate.sdpMLineIndex})};var isFirefoxOffered=!isFirefox;config.remoteSdp&&config.remoteSdp.remotePeerSdpConstraints&&config.remoteSdp.remotePeerSdpConstraints.isFirefoxOffered&&(isFirefoxOffered=!0),localStreams.forEach(function(localStream){config.remoteSdp&&config.remoteSdp.remotePeerSdpConstraints&&config.remoteSdp.remotePeerSdpConstraints.dontGetRemoteStream||config.dontAttachLocalStream||(localStream=config.beforeAddingStream(localStream),localStream&&peer.addStream(localStream))}),peer.oniceconnectionstatechange=peer.onsignalingstatechange=function(){var extra=that.extra;if(connection.peers[that.remoteUserId]&&(extra=connection.peers[that.remoteUserId].extra||extra),!peer)return void that.removeAllRemoteStreams();if(-1!==peer.iceConnectionState.search(/closed|failed/gi)){if(peer.firedOnce)return;if(peer.firedOnce=!0,that.removeAllRemoteStreams(),that.connectionDescription&&connection.userid==that.connectionDescription.sender&&connection.autoReDialOnFailure){if(connection.isInitiator)return;setTimeout(function(){connection.rejoin(that.connectionDescription),peer&&(peer.firedOnce=!1)},5e3)}}config.onPeerStateChanged({iceConnectionState:peer.iceConnectionState,iceGatheringState:peer.iceGatheringState,signalingState:peer.signalingState,extra:extra,userid:that.remoteUserId})};var sdpConstraints={OfferToReceiveAudio:!!localStreams.length,OfferToReceiveVideo:!!localStreams.length};config.localPeerSdpConstraints&&(sdpConstraints=config.localPeerSdpConstraints),defaults.sdpConstraints=setSdpConstraints(sdpConstraints),peer.onaddstream=function(event){var streamsToShare={};config.remoteSdp&&config.remoteSdp.streamsToShare?streamsToShare=config.remoteSdp.streamsToShare:config.streamsToShare&&(streamsToShare=config.streamsToShare);var streamToShare=streamsToShare[event.stream.id];streamToShare&&(event.stream.isAudio=streamToShare.isAudio,event.stream.isVideo=streamToShare.isVideo,event.stream.isScreen=streamToShare.isScreen),event.stream.streamid=event.stream.id,event.stream.stop||(event.stream.stop=function(){fireEvent(event.stream,"ended",event)}),allRemoteStreams[event.stream.id]=event.stream,config.onRemoteStream(event.stream)},peer.onremovestream=function(event){event.stream.streamid=event.stream.id,allRemoteStreams[event.stream.id]&&delete allRemoteStreams[event.stream.id],config.onRemoteStreamRemoved(event.stream)},this.addRemoteCandidate=function(remoteCandidate){peer.addIceCandidate(new RTCIceCandidate(remoteCandidate))},this.addRemoteSdp=function(remoteSdp){peer.setRemoteDescription(new RTCSessionDescription(remoteSdp),function(){},function(error){connection.enableLogs&&console.error(JSON.stringify(error,null," ")),connection.autoReDialOnFailure&&setTimeout(function(){connection.rejoin(that.connectionDescription)},2e3)})};var isOfferer=!0;config.remoteSdp&&(isOfferer=!1),config.enableDataChannels===!0&&createDataChannel(),config.remoteSdp&&(config.remoteSdp.remotePeerSdpConstraints&&(sdpConstraints=config.remoteSdp.remotePeerSdpConstraints),defaults.sdpConstraints=setSdpConstraints(sdpConstraints),this.addRemoteSdp(config.remoteSdp)),("two-way"==config.session.audio||"two-way"==config.session.video||"two-way"==config.session.screen)&&(defaults.sdpConstraints=setSdpConstraints({OfferToReceiveAudio:"two-way"==config.session.audio||config.remoteSdp&&config.remoteSdp.remotePeerSdpConstraints&&config.remoteSdp.remotePeerSdpConstraints.OfferToReceiveAudio,OfferToReceiveVideo:"two-way"==config.session.video||"two-way"==config.session.screen||config.remoteSdp&&config.remoteSdp.remotePeerSdpConstraints&&config.remoteSdp.remotePeerSdpConstraints.OfferToReceiveAudio}));var streamsToShare={};peer.getLocalStreams().forEach(function(stream){streamsToShare[stream.streamid]={isAudio:!!stream.isAudio,isVideo:!!stream.isVideo,isScreen:!!stream.isScreen}}),peer[isOfferer?"createOffer":"createAnswer"](function(localSdp){localSdp.sdp=config.processSdp(localSdp.sdp),peer.setLocalDescription(localSdp),config.onLocalSdp({type:localSdp.type,sdp:localSdp.sdp,remotePeerSdpConstraints:config.remotePeerSdpConstraints||!1,renegotiatingPeer:!!config.renegotiatingPeer||!1,connectionDescription:that.connectionDescription,dontGetRemoteStream:!!config.dontGetRemoteStream,extra:connection?connection.extra:{},streamsToShare:streamsToShare,isFirefoxOffered:isFirefox})},function(error){connection.enableLogs&&console.error("sdp-error",error),connection.autoReDialOnFailure&&connection.isInitiator&&isFirefox&&isFirefoxOffered&&setTimeout(function(){connection.rejoin(that.connectionDescription)},5e3)},defaults.sdpConstraints),peer.nativeClose=peer.close,peer.close=function(){if(!peer)return void that.removeAllRemoteStreams();connection.multiPeersHandler.onNegotiationNeeded({userLeft:!0,autoCloseEntireSession:!!connection.autoCloseEntireSession},that.remoteUserId);try{-1===peer.iceConnectionState.search(/closed|failed/gi)&&peer.getRemoteStreams().forEach(function(stream){stream.stop()}),peer.nativeClose()}catch(e){}peer=null},this.removeAllRemoteStreams=function(){for(var id in allRemoteStreams)config.onRemoteStreamRemoved(allRemoteStreams[id]);allRemoteStreams={},that.streams.forEach(function(stream){stream.stop()}),that.streams=[]},this.peer=peer}function loadIceFrame(callback,skip){if(!loadedIceFrame){if(!skip)return loadIceFrame(callback,!0);loadedIceFrame=!0;var iframe=document.createElement("iframe");iframe.onload=function(){function iFrameLoaderCallback(event){event.data&&event.data.iceServers&&(callback(event.data.iceServers),window.removeEventListener("message",iFrameLoaderCallback))}iframe.isLoaded=!0,listenEventHandler("message",iFrameLoaderCallback),iframe.contentWindow.postMessage("get-ice-servers","*")},iframe.src="https://cdn.webrtc-experiment.com/getIceServers/",iframe.style.display="none",(document.body||document.documentElement).appendChild(iframe)}}function requestUserMedia(constraints){return new Promise(function(resolve,reject){getUserMedia(constraints,resolve,reject)})}function setStreamType(constraints,stream){constraints.mandatory&&constraints.mandatory.chromeMediaSource?stream.isScreen=!0:constraints.mozMediaSource||constraints.mediaSource?stream.isScreen=!0:constraints.video?stream.isVideo=!0:constraints.audio&&(stream.isAudio=!0)}function getUserMediaHandler(options){function streaming(stream,returnBack){setStreamType(options.localMediaConstraints,stream),options.onGettingLocalMedia(stream,returnBack),stream.addEventListener("ended",function(){delete currentUserMediaRequest.streams[idInstance],currentUserMediaRequest.mutex=!1,currentUserMediaRequest.queueRequests.indexOf(options)&&(delete currentUserMediaRequest.queueRequests[currentUserMediaRequest.queueRequests.indexOf(options)],currentUserMediaRequest.queueRequests=removeNullEntries(currentUserMediaRequest.queueRequests))},!1),currentUserMediaRequest.streams[idInstance]={stream:stream},currentUserMediaRequest.mutex=!1,currentUserMediaRequest.queueRequests.length&&getUserMediaHandler(currentUserMediaRequest.queueRequests.shift())}if(currentUserMediaRequest.mutex===!0)return void currentUserMediaRequest.queueRequests.push(options);currentUserMediaRequest.mutex=!0;var idInstance=JSON.stringify(options.localMediaConstraints);if(currentUserMediaRequest.streams[idInstance])streaming(currentUserMediaRequest.streams[idInstance].stream,!0);else{if(isPluginRTC){document.createElement("video");return void Plugin.getUserMedia({audio:!0,video:!0},function(stream){stream.streamid=stream.id||getRandomString(),streaming(stream)},function(error){})}"undefined"!=typeof DetectRTC&&(DetectRTC.hasMicrophone||(options.localMediaConstraints.audio=!1),DetectRTC.hasWebcam||(options.localMediaConstraints.video=!1)),navigator.mediaDevices.getUserMedia(options.localMediaConstraints).then(function(stream){stream.streamid=stream.streamid||stream.id||getRandomString(),stream.idInstance=idInstance,streaming(stream)})["catch"](function(error){options.onLocalMediaError(error,options.localMediaConstraints)})}}function TextReceiver(connection){function receive(data,userid,extra){var uuid=data.uuid;if(content[uuid]||(content[uuid]=[]),content[uuid].push(data.message),data.last){var message=content[uuid].join("");data.isobject&&(message=JSON.parse(message));var receivingTime=(new Date).getTime(),latency=receivingTime-data.sendingTime,e={data:message,userid:userid,extra:extra,latency:latency};connection.autoTranslateText?(e.original=e.data,connection.Translator.TranslateText(e.data,function(translatedText){e.data=translatedText,connection.onmessage(e)})):connection.onmessage(e),delete content[uuid]}}var content={};return{receive:receive}}var isOpera=!!window.opera||navigator.userAgent.indexOf(" OPR/")>=0,isFirefox="undefined"!=typeof window.InstallTrigger,isSafari=Object.prototype.toString.call(window.HTMLElement).indexOf("Constructor")>0,isChrome=!!window.chrome&&!isOpera,isIE=!!document.documentMode,isPluginRTC=isSafari||isIE,chromeVersion=(!!navigator.userAgent.match(/Android|iPhone|iPad|iPod|BlackBerry|IEMobile/i),
!!(window.process&&"object"==typeof window.process&&window.process.versions&&window.process.versions["node-webkit"]),50),matchArray=navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./);isChrome&&matchArray&&matchArray[2]&&(chromeVersion=parseInt(matchArray[2],10));var firefoxVersion=50;matchArray=navigator.userAgent.match(/Firefox\/(.*)/),isFirefox&&matchArray&&matchArray[1]&&(firefoxVersion=parseInt(matchArray[1],10)),window.addEventListener||(window.addEventListener=function(el,eventName,eventHandler){el.attachEvent&&el.attachEvent("on"+eventName,eventHandler)}),window.attachEventListener=function(video,type,listener,useCapture){video.addEventListener(type,listener,useCapture)};var MediaStream=window.MediaStream;"undefined"==typeof MediaStream&&"undefined"!=typeof webkitMediaStream&&(MediaStream=webkitMediaStream),"undefined"==typeof MediaStream||"stop"in MediaStream.prototype||(MediaStream.prototype.stop=function(){this.getAudioTracks().forEach(function(track){track.stop()}),this.getVideoTracks().forEach(function(track){track.stop()}),fireEvent(this,"ended")}),"undefined"!=typeof MediaStream&&("getAudioTracks"in MediaStream.prototype&&"function"==typeof MediaStream.prototype.getAudioTracks||(MediaStream.prototype.getAudioTracks=function(){}),"getVideoTracks"in MediaStream.prototype&&"function"==typeof MediaStream.prototype.getVideoTracks||(MediaStream.prototype.getVideoTracks=function(){}));var lastChanges="";!function(){function LoadPluginRTC(){function getPlugin(){return document.getElementById("WebrtcEverywherePluginId")}window.PluginRTC={};var extractPluginObj=function(elt){return elt.isWebRtcPlugin?elt:elt.pluginObj},attachEventListener=function(elt,type,listener,useCapture){var _pluginObj=extractPluginObj(elt);_pluginObj?_pluginObj.bindEventListener(type,listener,useCapture):"undefined"!=typeof elt.addEventListener?elt.addEventListener(type,listener,useCapture):"undefined"!=typeof elt.addEvent&&elt.addEventListener("on"+type,listener,useCapture)},installPlugin=function(){if(!document.getElementById("WebrtcEverywherePluginId")){var pluginObj=document.createElement("object");isIE?pluginObj.setAttribute("classid","CLSID:7FD49E23-C8D7-4C4F-93A1-F7EACFA1EC53"):pluginObj.setAttribute("type","application/webrtc-everywhere"),pluginObj.setAttribute("id","WebrtcEverywherePluginId"),(document.body||document.documentElement).appendChild(pluginObj),pluginObj.setAttribute("width","0"),pluginObj.setAttribute("height","0")}};document.body?installPlugin():(attachEventListener(window,"load",function(){installPlugin()}),attachEventListener(document,"readystatechange",function(){"complete"==document.readyState&&installPlugin()}));var getUserMediaDelayed;window.PluginRTC.getUserMedia=navigator.getUserMedia=function(constraints,successCallback,errorCallback){"complete"!==document.readyState?getUserMediaDelayed||(getUserMediaDelayed=!0,attachEventListener(document,"readystatechange",function(){getUserMediaDelayed&&"complete"==document.readyState&&(getUserMediaDelayed=!1,getPlugin().getUserMedia(constraints,successCallback,errorCallback))})):getPlugin().getUserMedia(constraints,successCallback,errorCallback)},window.PluginRTC.attachMediaStream=function(element,stream){if(element.isWebRtcPlugin)return element.src=stream,element;if("video"===element.nodeName.toLowerCase()){if(!element.pluginObj&&stream){var _pluginObj=document.createElement("object"),_isIE=Object.getOwnPropertyDescriptor&&Object.getOwnPropertyDescriptor(window,"ActiveXObject")||"ActiveXObject"in window;_isIE?_pluginObj.setAttribute("classid","CLSID:7FD49E23-C8D7-4C4F-93A1-F7EACFA1EC53"):_pluginObj.setAttribute("type","application/webrtc-everywhere"),element.pluginObj=_pluginObj,_pluginObj.setAttribute("className",element.className),_pluginObj.setAttribute("innerHTML",element.innerHTML);var width=element.getAttribute("width"),height=element.getAttribute("height"),bounds=element.getBoundingClientRect();if(width||(width=bounds.right-bounds.left),height||(height=bounds.bottom-bounds.top),"getComputedStyle"in window){var computedStyle=window.getComputedStyle(element,null);width||"auto"==computedStyle.width||"0px"==computedStyle.width||(width=computedStyle.width),height||"auto"==computedStyle.height||"0px"==computedStyle.height||(height=computedStyle.height)}width?_pluginObj.setAttribute("width",width):_pluginObj.setAttribute("autowidth",!0),height?_pluginObj.setAttribute("height",height):_pluginObj.setAttribute("autoheight",!0),(document.body||document.documentElement).appendChild(_pluginObj),element.parentNode&&(element.parentNode.replaceChild(_pluginObj,element),document.body.appendChild(element),element.style.visibility="hidden")}return element.pluginObj&&(element.pluginObj.bindEventListener("play",function(objvid){element.pluginObj&&(element.pluginObj.getAttribute("autowidth")&&objvid.videoWidth&&element.pluginObj.setAttribute("width",objvid.videoWidth),element.pluginObj.getAttribute("autoheight")&&objvid.videoHeight&&element.pluginObj.setAttribute("height",objvid.videoHeight))}),element.pluginObj.src=stream),element.pluginObj}return"audio"===element.nodeName.toLowerCase()?element:void 0},window.PluginRTC.MediaStreamTrack={};var getSourcesDelayed;window.PluginRTC.MediaStreamTrack.getSources=function(gotSources){"complete"!==document.readyState?getSourcesDelayed||(getSourcesDelayed=!0,attachEventListener(document,"readystatechange",function(){getSourcesDelayed&&"complete"==document.readyState&&(getSourcesDelayed=!1,getPlugin().getSources(gotSources))})):getPlugin().getSources(gotSources)},window.PluginRTC.RTCPeerConnection=function(configuration,constraints){return getPlugin().createPeerConnection(configuration,constraints)},window.PluginRTC.RTCIceCandidate=function(RTCIceCandidateInit){return getPlugin().createIceCandidate(RTCIceCandidateInit)},window.PluginRTC.RTCSessionDescription=function(RTCSessionDescriptionInit){return getPlugin().createSessionDescription(RTCSessionDescriptionInit)},window.onPluginRTCInitialized&&window.onPluginRTCInitialized(window.PluginRTC)}var ua=navigator.userAgent.toLowerCase(),isSafari=-1!=ua.indexOf("safari")&&-1==ua.indexOf("chrome"),isIE=!!(Object.getOwnPropertyDescriptor&&Object.getOwnPropertyDescriptor(window,"ActiveXObject")||"ActiveXObject"in window);(isSafari||isIE)&&window.addEventListener("load",LoadPluginRTC,!1)}();var RTCPeerConnection,defaults={};"undefined"!=typeof mozRTCPeerConnection?RTCPeerConnection=mozRTCPeerConnection:"undefined"!=typeof webkitRTCPeerConnection?RTCPeerConnection=webkitRTCPeerConnection:"undefined"!=typeof window.RTCPeerConnection?RTCPeerConnection=window.RTCPeerConnection:(console.error("WebRTC 1.0 (RTCPeerConnection) API are NOT available in this browser."),RTCPeerConnection=window.RTCSessionDescription=window.RTCIceCandidate=function(){});var RTCSessionDescription=window.RTCSessionDescription||window.mozRTCSessionDescription,RTCIceCandidate=window.RTCIceCandidate||window.mozRTCIceCandidate,MediaStreamTrack=window.MediaStreamTrack,Plugin={};"undefined"!=typeof PluginRTC&&onPluginRTCInitialized(PluginRTC);var loadedIceFrame,isSafari=Object.prototype.toString.call(window.HTMLElement).indexOf("Constructor")>0,isIE=!!document.documentMode,isPluginRTC=isSafari||isIE,OnIceCandidateHandler=function(){function processCandidates(connection,icePair){var candidate=icePair.candidate,iceRestrictions=connection.candidates,stun=iceRestrictions.stun,turn=iceRestrictions.turn;if(isNull(iceRestrictions.reflexive)||(stun=iceRestrictions.reflexive),isNull(iceRestrictions.relay)||(turn=iceRestrictions.relay),(iceRestrictions.host||!candidate.match(/typ host/g))&&(turn||!candidate.match(/typ relay/g))&&(stun||!candidate.match(/typ srflx/g))){var protocol=connection.iceProtocols;if((protocol.udp||!candidate.match(/ udp /g))&&(protocol.tcp||!candidate.match(/ tcp /g)))return connection.enableLogs&&console.debug("Your candidate pairs:",candidate),{candidate:candidate,sdpMid:icePair.sdpMid,sdpMLineIndex:icePair.sdpMLineIndex}}}return{processCandidates:processCandidates}}();("undefined"==typeof window.getExternalIceServers||1==window.getExternalIceServers)&&loadIceFrame(function(externalIceServers){externalIceServers&&externalIceServers.length&&(window.RMCExternalIceServers=externalIceServers,window.iceServersLoadCallback&&"function"==typeof window.iceServersLoadCallback&&window.iceServersLoadCallback(externalIceServers))});var IceServersHandler=function(){function getIceServers(connection){var iceServers=[];return iceServers.push({urls:"stun:stun.l.google.com:19302"}),iceServers.push({urls:"stun:stun.anyfirewall.com:3478"}),iceServers.push({urls:"turn:turn.bistri.com:80",credential:"homeo",username:"homeo"}),iceServers.push({urls:"turn:turn.anyfirewall.com:443?transport=tcp",credential:"webrtc",username:"webrtc"}),window.RMCExternalIceServers?(iceServers=window.RMCExternalIceServers.concat(iceServers),connection.iceServers=iceServers):"undefined"==typeof window.getExternalIceServers||1==window.getExternalIceServers?window.iceServersLoadCallback=function(){iceServers=window.RMCExternalIceServers.concat(iceServers),connection.iceServers=iceServers}:iceServers.push({urls:"turn:turn.anyfirewall.com:443?transport=udp",credential:"webrtc",username:"webrtc"}),iceServers}return{getIceServers:getIceServers}}(),BandwidthHandler=function(){function setBAS(sdp,bandwidth,isScreen){return bandwidth?"undefined"!=typeof isFirefox&&isFirefox?sdp:(isScreen&&(bandwidth.screen?bandwidth.screen<300&&console.warn("It seems that you are using wrong bandwidth value for screen. Screen sharing is expected to fail."):console.warn("It seems that you are not using bandwidth for screen. Screen sharing is expected to fail.")),bandwidth.screen&&isScreen&&(sdp=sdp.replace(/b=AS([^\r\n]+\r\n)/g,""),sdp=sdp.replace(/a=mid:video\r\n/g,"a=mid:video\r\nb=AS:"+bandwidth.screen+"\r\n")),(bandwidth.audio||bandwidth.video||bandwidth.data)&&(sdp=sdp.replace(/b=AS([^\r\n]+\r\n)/g,"")),bandwidth.audio&&(sdp=sdp.replace(/a=mid:audio\r\n/g,"a=mid:audio\r\nb=AS:"+bandwidth.audio+"\r\n")),bandwidth.video&&(sdp=sdp.replace(/a=mid:video\r\n/g,"a=mid:video\r\nb=AS:"+(isScreen?bandwidth.screen:bandwidth.video)+"\r\n")),sdp):sdp}function findLine(sdpLines,prefix,substr){return findLineInRange(sdpLines,0,-1,prefix,substr)}function findLineInRange(sdpLines,startLine,endLine,prefix,substr){for(var realEndLine=-1!==endLine?endLine:sdpLines.length,i=startLine;realEndLine>i;++i)if(0===sdpLines[i].indexOf(prefix)&&(!substr||-1!==sdpLines[i].toLowerCase().indexOf(substr.toLowerCase())))return i;return null}function getCodecPayloadType(sdpLine){var pattern=new RegExp("a=rtpmap:(\\d+) \\w+\\/\\d+"),result=sdpLine.match(pattern);return result&&2===result.length?result[1]:null}function setVideoBitrates(sdp,params){params=params||{};var vp8Payload,xgoogle_min_bitrate=params.min,xgoogle_max_bitrate=params.max,sdpLines=sdp.split("\r\n"),vp8Index=findLine(sdpLines,"a=rtpmap","VP8/90000");if(vp8Index&&(vp8Payload=getCodecPayloadType(sdpLines[vp8Index])),!vp8Payload)return sdp;var rtxPayload,rtxIndex=findLine(sdpLines,"a=rtpmap","rtx/90000");if(rtxIndex&&(rtxPayload=getCodecPayloadType(sdpLines[rtxIndex])),!rtxIndex)return sdp;var rtxFmtpLineIndex=findLine(sdpLines,"a=fmtp:"+rtxPayload.toString());if(null!==rtxFmtpLineIndex){var appendrtxNext="\r\n";appendrtxNext+="a=fmtp:"+vp8Payload+" x-google-min-bitrate="+(xgoogle_min_bitrate||"228")+"; x-google-max-bitrate="+(xgoogle_max_bitrate||"228"),sdpLines[rtxFmtpLineIndex]=sdpLines[rtxFmtpLineIndex].concat(appendrtxNext),sdp=sdpLines.join("\r\n")}return sdp}function setOpusAttributes(sdp,params){params=params||{};var opusPayload,sdpLines=sdp.split("\r\n"),opusIndex=findLine(sdpLines,"a=rtpmap","opus/48000");if(opusIndex&&(opusPayload=getCodecPayloadType(sdpLines[opusIndex])),!opusPayload)return sdp;var opusFmtpLineIndex=findLine(sdpLines,"a=fmtp:"+opusPayload.toString());if(null===opusFmtpLineIndex)return sdp;var appendOpusNext="";return appendOpusNext+="; stereo="+("undefined"!=typeof params.stereo?params.stereo:"1"),appendOpusNext+="; sprop-stereo="+("undefined"!=typeof params["sprop-stereo"]?params["sprop-stereo"]:"1"),"undefined"!=typeof params.maxaveragebitrate&&(appendOpusNext+="; maxaveragebitrate="+(params.maxaveragebitrate||1048576)),"undefined"!=typeof params.maxplaybackrate&&(appendOpusNext+="; maxplaybackrate="+(params.maxplaybackrate||1048576)),"undefined"!=typeof params.cbr&&(appendOpusNext+="; cbr="+("undefined"!=typeof params.cbr?params.cbr:"1")),"undefined"!=typeof params.useinbandfec&&(appendOpusNext+="; useinbandfec="+params.useinbandfec),"undefined"!=typeof params.usedtx&&(appendOpusNext+="; usedtx="+params.usedtx),"undefined"!=typeof params.maxptime&&(appendOpusNext+="\r\na=maxptime:"+params.maxptime),sdpLines[opusFmtpLineIndex]=sdpLines[opusFmtpLineIndex].concat(appendOpusNext),sdp=sdpLines.join("\r\n")}return{setApplicationSpecificBandwidth:function(sdp,bandwidth,isScreen){return setBAS(sdp,bandwidth,isScreen)},setVideoBitrates:function(sdp,params){return setVideoBitrates(sdp,params)},setOpusAttributes:function(sdp,params){return setOpusAttributes(sdp,params)}}}(),getUserMedia=null,webrtcDetectedBrowser=null,webrtcDetectedVersion=null,webrtcMinimumVersion=null,webrtcUtils=window.webrtcUtils||{};if(webrtcUtils.enableLogs||(webrtcUtils.enableLogs=!0),webrtcUtils.log||(webrtcUtils.log=function(){webrtcUtils.enableLogs&&("undefined"!=typeof module||"function"==typeof require&&"function"==typeof define||console.log.apply(console,arguments))}),webrtcUtils.extractVersion||(webrtcUtils.extractVersion=function(uastring,expr,pos){var match=uastring.match(expr);return match&&match.length>=pos&&parseInt(match[pos],10)}),"object"==typeof window&&(!window.HTMLMediaElement||"srcObject"in window.HTMLMediaElement.prototype||Object.defineProperty(window.HTMLMediaElement.prototype,"srcObject",{get:function(){return"mozSrcObject"in this?this.mozSrcObject:this._srcObject},set:function(stream){"mozSrcObject"in this?this.mozSrcObject=stream:(this._srcObject=stream,this.src=stream?URL.createObjectURL(stream):null)}}),getUserMedia=window.navigator&&window.navigator.getUserMedia),"undefined"!=typeof window&&window.navigator)if(navigator.mozGetUserMedia&&window.mozRTCPeerConnection){if(webrtcDetectedBrowser="firefox",webrtcDetectedVersion=webrtcUtils.extractVersion(navigator.userAgent,/Firefox\/([0-9]+)\./,1),webrtcMinimumVersion=31,getUserMedia=function(constraints,onSuccess,onError){var constraintsToFF37=function(c){if("object"!=typeof c||c.require)return c;var require=[];return Object.keys(c).forEach(function(key){if("require"!==key&&"advanced"!==key&&"mediaSource"!==key){var r=c[key]="object"==typeof c[key]?c[key]:{ideal:c[key]};if((void 0!==r.min||void 0!==r.max||void 0!==r.exact)&&require.push(key),void 0!==r.exact&&("number"==typeof r.exact?r.min=r.max=r.exact:c[key]=r.exact,delete r.exact),void 0!==r.ideal){c.advanced=c.advanced||[];var oc={};"number"==typeof r.ideal?oc[key]={min:r.ideal,max:r.ideal}:oc[key]=r.ideal,c.advanced.push(oc),delete r.ideal,Object.keys(r).length||delete c[key]}}}),require.length&&(c.require=require),c};return 38>webrtcDetectedVersion&&(webrtcUtils.log("spec: "+JSON.stringify(constraints)),constraints.audio&&(constraints.audio=constraintsToFF37(constraints.audio)),constraints.video&&(constraints.video=constraintsToFF37(constraints.video)),webrtcUtils.log("ff37: "+JSON.stringify(constraints))),navigator.mozGetUserMedia(constraints,onSuccess,onError)},navigator.getUserMedia=getUserMedia,navigator.mediaDevices||(navigator.mediaDevices={getUserMedia:requestUserMedia,addEventListener:function(){},removeEventListener:function(){}}),navigator.mediaDevices.enumerateDevices=navigator.mediaDevices.enumerateDevices||function(){return new Promise(function(resolve){var infos=[{kind:"audioinput",deviceId:"default",label:"",groupId:""},{kind:"videoinput",deviceId:"default",label:"",groupId:""}];resolve(infos)})},41>webrtcDetectedVersion){var orgEnumerateDevices=navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices);navigator.mediaDevices.enumerateDevices=function(){return orgEnumerateDevices().then(void 0,function(e){if("NotFoundError"===e.name)return[];throw e})}}}else if(navigator.webkitGetUserMedia&&window.webkitRTCPeerConnection){webrtcDetectedBrowser="chrome",webrtcDetectedVersion=webrtcUtils.extractVersion(navigator.userAgent,/Chrom(e|ium)\/([0-9]+)\./,2),webrtcMinimumVersion=38;var constraintsToChrome=function(c){if("object"!=typeof c||c.mandatory||c.optional)return c;var cc={};return Object.keys(c).forEach(function(key){if("require"!==key&&"advanced"!==key&&"mediaSource"!==key){var r="object"==typeof c[key]?c[key]:{ideal:c[key]};void 0!==r.exact&&"number"==typeof r.exact&&(r.min=r.max=r.exact);var oldname=function(prefix,name){return prefix?prefix+name.charAt(0).toUpperCase()+name.slice(1):"deviceId"===name?"sourceId":name};if(void 0!==r.ideal){cc.optional=cc.optional||[];var oc={};"number"==typeof r.ideal?(oc[oldname("min",key)]=r.ideal,cc.optional.push(oc),oc={},oc[oldname("max",key)]=r.ideal,cc.optional.push(oc)):(oc[oldname("",key)]=r.ideal,cc.optional.push(oc))}void 0!==r.exact&&"number"!=typeof r.exact?(cc.mandatory=cc.mandatory||{},cc.mandatory[oldname("",key)]=r.exact):["min","max"].forEach(function(mix){void 0!==r[mix]&&(cc.mandatory=cc.mandatory||{},cc.mandatory[oldname(mix,key)]=r[mix])})}}),c.advanced&&(cc.optional=(cc.optional||[]).concat(c.advanced)),cc};if(getUserMedia=function(constraints,onSuccess,onError){return constraints.audio&&(constraints.audio=constraintsToChrome(constraints.audio)),constraints.video&&(constraints.video=constraintsToChrome(constraints.video)),webrtcUtils.log("chrome: "+JSON.stringify(constraints)),navigator.webkitGetUserMedia(constraints,onSuccess,onError)},navigator.getUserMedia=getUserMedia,navigator.mediaDevices||(navigator.mediaDevices={getUserMedia:requestUserMedia}),navigator.mediaDevices.getUserMedia){var origGetUserMedia=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getUserMedia=function(c){return webrtcUtils.log("spec: "+JSON.stringify(c)),c.audio=constraintsToChrome(c.audio),c.video=constraintsToChrome(c.video),webrtcUtils.log("chrome: "+JSON.stringify(c)),origGetUserMedia(c)}}else navigator.mediaDevices.getUserMedia=function(constraints){return requestUserMedia(constraints)};"undefined"==typeof navigator.mediaDevices.addEventListener&&(navigator.mediaDevices.addEventListener=function(){webrtcUtils.log("Dummy mediaDevices.addEventListener called.")}),"undefined"==typeof navigator.mediaDevices.removeEventListener&&(navigator.mediaDevices.removeEventListener=function(){webrtcUtils.log("Dummy mediaDevices.removeEventListener called.")})}else navigator.mediaDevices&&navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)?(webrtcUtils.log("This appears to be Edge"),webrtcDetectedBrowser="edge",webrtcDetectedVersion=webrtcUtils.extractVersion(navigator.userAgent,/Edge\/(\d+).(\d+)$/,2),webrtcMinimumVersion=12):webrtcUtils.log("Browser does not appear to be WebRTC-capable");else webrtcDetectedBrowser="not a browser";"undefined"!=typeof module?module.exports={getUserMedia:getUserMedia,webrtcDetectedBrowser:webrtcDetectedBrowser,webrtcDetectedVersion:webrtcDetectedVersion,webrtcMinimumVersion:webrtcMinimumVersion,webrtcUtils:webrtcUtils}:"function"==typeof require&&"function"==typeof define&&define([],function(){return{getUserMedia:getUserMedia,webrtcDetectedBrowser:webrtcDetectedBrowser,webrtcDetectedVersion:webrtcDetectedVersion,webrtcMinimumVersion:webrtcMinimumVersion,webrtcUtils:webrtcUtils}}),"undefined"!=typeof webrtcUtils&&(webrtcUtils.enableLogs=!1);var currentUserMediaRequest={streams:[],mutex:!1,queueRequests:[],remove:function(idInstance){this.mutex=!1;var stream=this.streams[idInstance];if(stream){stream=stream.stream;var options=stream.currentUserMediaRequestOptions;this.queueRequests.indexOf(options)&&(delete this.queueRequests[this.queueRequests.indexOf(options)],this.queueRequests=removeNullEntries(this.queueRequests)),this.streams[idInstance].stream=null,delete this.streams[idInstance]}}},StreamsHandler=function(){function handleType(type){return type?"string"==typeof type||"undefined"==typeof type?type:type.audio&&type.video?null:type.audio?"audio":type.video?"video":void 0:void 0}function setHandlers(stream,syncAction,connection){function graduallyIncreaseVolume(){if(connection.streamEvents[stream.streamid].mediaElement){var mediaElement=connection.streamEvents[stream.streamid].mediaElement;mediaElement.volume=0,afterEach(200,5,function(){mediaElement.volume+=.2})}}("undefined"==typeof syncAction||1==syncAction)&&stream.addEventListener("ended",function(){StreamsHandler.onSyncNeeded(stream.streamid,"ended")},!1),stream.mute=function(type,isSyncAction){type=handleType(type),"undefined"!=typeof isSyncAction&&(syncAction=isSyncAction),("undefined"==typeof type||"audio"==type)&&stream.getAudioTracks().forEach(function(track){track.enabled=!1,connection.streamEvents[stream.streamid].isAudioMuted=!0}),("undefined"==typeof type||"video"==type)&&stream.getVideoTracks().forEach(function(track){track.enabled=!1}),("undefined"==typeof syncAction||1==syncAction)&&StreamsHandler.onSyncNeeded(stream.streamid,"mute",type),connection.streamEvents[stream.streamid].muteType=type||"both",fireEvent(stream,"mute",type)},stream.unmute=function(type,isSyncAction){type=handleType(type),"undefined"!=typeof isSyncAction&&(syncAction=isSyncAction),graduallyIncreaseVolume(),("undefined"==typeof type||"audio"==type)&&stream.getAudioTracks().forEach(function(track){track.enabled=!0,connection.streamEvents[stream.streamid].isAudioMuted=!1}),("undefined"==typeof type||"video"==type)&&(stream.getVideoTracks().forEach(function(track){track.enabled=!0}),"undefined"!=typeof type&&"video"==type&&connection.streamEvents[stream.streamid].isAudioMuted&&!function looper(times){times||(times=0),times++,100>times&&connection.streamEvents[stream.streamid].isAudioMuted&&(stream.mute("audio"),setTimeout(function(){looper(times)},50))}()),("undefined"==typeof syncAction||1==syncAction)&&StreamsHandler.onSyncNeeded(stream.streamid,"unmute",type),connection.streamEvents[stream.streamid].unmuteType=type||"both",fireEvent(stream,"unmute",type)}}function afterEach(setTimeoutInteval,numberOfTimes,callback,startedTimes){startedTimes=(startedTimes||0)+1,startedTimes>=numberOfTimes||setTimeout(function(){callback(),afterEach(setTimeoutInteval,numberOfTimes,callback,startedTimes)},setTimeoutInteval)}return{setHandlers:setHandlers,onSyncNeeded:function(streamid,action,type){}}}();!function(){function getBrowserInfo(){var nameOffset,verOffset,ix,nAgt=(navigator.appVersion,navigator.userAgent),browserName=navigator.appName,fullVersion=""+parseFloat(navigator.appVersion),majorVersion=parseInt(navigator.appVersion,10);if(isOpera){browserName="Opera";try{fullVersion=navigator.userAgent.split("OPR/")[1].split(" ")[0],majorVersion=fullVersion.split(".")[0]}catch(e){fullVersion="0.0.0.0",majorVersion=0}}else isIE?(verOffset=nAgt.indexOf("MSIE"),browserName="IE",fullVersion=nAgt.substring(verOffset+5)):isChrome?(verOffset=nAgt.indexOf("Chrome"),browserName="Chrome",fullVersion=nAgt.substring(verOffset+7)):isSafari?(verOffset=nAgt.indexOf("Safari"),browserName="Safari",fullVersion=nAgt.substring(verOffset+7),-1!==(verOffset=nAgt.indexOf("Version"))&&(fullVersion=nAgt.substring(verOffset+8))):isFirefox?(verOffset=nAgt.indexOf("Firefox"),browserName="Firefox",fullVersion=nAgt.substring(verOffset+8)):(nameOffset=nAgt.lastIndexOf(" ")+1)<(verOffset=nAgt.lastIndexOf("/"))&&(browserName=nAgt.substring(nameOffset,verOffset),fullVersion=nAgt.substring(verOffset+1),browserName.toLowerCase()===browserName.toUpperCase()&&(browserName=navigator.appName));return isEdge&&(browserName="Edge",fullVersion=parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2],10).toString()),-1!==(ix=fullVersion.indexOf(";"))&&(fullVersion=fullVersion.substring(0,ix)),-1!==(ix=fullVersion.indexOf(" "))&&(fullVersion=fullVersion.substring(0,ix)),majorVersion=parseInt(""+fullVersion,10),isNaN(majorVersion)&&(fullVersion=""+parseFloat(navigator.appVersion),majorVersion=parseInt(navigator.appVersion,10)),{fullVersion:fullVersion,version:majorVersion,name:browserName,isPrivateBrowsing:!1}}function retry(isDone,next){var currentTrial=0,maxRetry=50,isTimeout=!1,id=window.setInterval(function(){isDone()&&(window.clearInterval(id),next(isTimeout)),currentTrial++>maxRetry&&(window.clearInterval(id),isTimeout=!0,next(isTimeout))},10)}function isIE10OrLater(userAgent){var ua=userAgent.toLowerCase();if(0===ua.indexOf("msie")&&0===ua.indexOf("trident"))return!1;var match=/(?:msie|rv:)\s?([\d\.]+)/.exec(ua);return match&&parseInt(match[1],10)>=10?!0:!1}function detectPrivateMode(callback){var isPrivate;if(window.webkitRequestFileSystem)window.webkitRequestFileSystem(window.TEMPORARY,1,function(){isPrivate=!1},function(e){console.log(e),isPrivate=!0});else if(window.indexedDB&&/Firefox/.test(window.navigator.userAgent)){var db;try{db=window.indexedDB.open("test")}catch(e){isPrivate=!0}"undefined"==typeof isPrivate&&retry(function(){return"done"===db.readyState?!0:!1},function(isTimeout){isTimeout||(isPrivate=db.result?!1:!0)})}else if(isIE10OrLater(window.navigator.userAgent)){isPrivate=!1;try{window.indexedDB||(isPrivate=!0)}catch(e){isPrivate=!0}}else if(window.localStorage&&/Safari/.test(window.navigator.userAgent)){try{window.localStorage.setItem("test",1)}catch(e){isPrivate=!0}"undefined"==typeof isPrivate&&(isPrivate=!1,window.localStorage.removeItem("test"))}retry(function(){return"undefined"!=typeof isPrivate?!0:!1},function(isTimeout){callback(isPrivate)})}function detectDesktopOS(){var unknown="-",nVer=navigator.appVersion,nAgt=navigator.userAgent,os=unknown,clientStrings=[{s:"Windows 10",r:/(Windows 10.0|Windows NT 10.0)/},{s:"Windows 8.1",r:/(Windows 8.1|Windows NT 6.3)/},{s:"Windows 8",r:/(Windows 8|Windows NT 6.2)/},{s:"Windows 7",r:/(Windows 7|Windows NT 6.1)/},{s:"Windows Vista",r:/Windows NT 6.0/},{s:"Windows Server 2003",r:/Windows NT 5.2/},{s:"Windows XP",r:/(Windows NT 5.1|Windows XP)/},{s:"Windows 2000",r:/(Windows NT 5.0|Windows 2000)/},{s:"Windows ME",r:/(Win 9x 4.90|Windows ME)/},{s:"Windows 98",r:/(Windows 98|Win98)/},{s:"Windows 95",r:/(Windows 95|Win95|Windows_95)/},{s:"Windows NT 4.0",r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},{s:"Windows CE",r:/Windows CE/},{s:"Windows 3.11",r:/Win16/},{s:"Android",r:/Android/},{s:"Open BSD",r:/OpenBSD/},{s:"Sun OS",r:/SunOS/},{s:"Linux",r:/(Linux|X11)/},{s:"iOS",r:/(iPhone|iPad|iPod)/},{s:"Mac OS X",r:/Mac OS X/},{s:"Mac OS",r:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},{s:"QNX",r:/QNX/},{s:"UNIX",r:/UNIX/},{s:"BeOS",r:/BeOS/},{s:"OS/2",r:/OS\/2/},{s:"Search Bot",r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}];for(var id in clientStrings){var cs=clientStrings[id];if(cs.r.test(nAgt)){os=cs.s;break}}var osVersion=unknown;switch(/Windows/.test(os)&&(osVersion=/Windows (.*)/.exec(os)[1],os="Windows"),os){case"Mac OS X":osVersion=/Mac OS X (10[\.\_\d]+)/.exec(nAgt)[1];break;case"Android":osVersion=/Android ([\.\_\d]+)/.exec(nAgt)[1];break;case"iOS":osVersion=/OS (\d+)_(\d+)_?(\d+)?/.exec(nVer),osVersion=osVersion[1]+"."+osVersion[2]+"."+(0|osVersion[3])}return{osName:os,osVersion:osVersion}}function DetectLocalIPAddress(callback){DetectRTC.isWebRTCSupported&&(DetectRTC.isORTCSupported||getIPs(function(ip){callback(ip.match(/^(192\.168\.|169\.254\.|10\.|172\.(1[6-9]|2\d|3[01]))/)?"Local: "+ip:"Public: "+ip)}))}function getIPs(callback){function handleCandidate(candidate){var ipRegex=/([0-9]{1,3}(\.[0-9]{1,3}){3})/,match=ipRegex.exec(candidate);if(!match)return void console.warn("Could not match IP address in",candidate);var ipAddress=match[1];void 0===ipDuplicates[ipAddress]&&callback(ipAddress),ipDuplicates[ipAddress]=!0}var ipDuplicates={},RTCPeerConnection=window.RTCPeerConnection||window.mozRTCPeerConnection||window.webkitRTCPeerConnection,useWebKit=!!window.webkitRTCPeerConnection;if(!RTCPeerConnection){var iframe=document.getElementById("iframe");if(!iframe)throw"NOTE: you need to have an iframe in the page right above the script tag.";var win=iframe.contentWindow;RTCPeerConnection=win.RTCPeerConnection||win.mozRTCPeerConnection||win.webkitRTCPeerConnection,useWebKit=!!win.webkitRTCPeerConnection}if(RTCPeerConnection){var servers,mediaConstraints={optional:[{RtpDataChannels:!0}]};useWebKit&&(servers={iceServers:[{urls:"stun:stun.services.mozilla.com"}]},"undefined"!=typeof DetectRTC&&DetectRTC.browser.isFirefox&&DetectRTC.browser.version<=38&&(servers[0]={url:servers[0].urls}));var pc=new RTCPeerConnection(servers,mediaConstraints);pc.onicecandidate=function(ice){ice.candidate&&handleCandidate(ice.candidate.candidate)},pc.createDataChannel(""),pc.createOffer(function(result){pc.setLocalDescription(result,function(){},function(){})},function(){}),setTimeout(function(){var lines=pc.localDescription.sdp.split("\n");lines.forEach(function(line){0===line.indexOf("a=candidate:")&&handleCandidate(line)})},1e3)}}function checkDeviceSupport(callback){if(canEnumerate){if(!navigator.enumerateDevices&&window.MediaStreamTrack&&window.MediaStreamTrack.getSources&&(navigator.enumerateDevices=window.MediaStreamTrack.getSources.bind(window.MediaStreamTrack)),!navigator.enumerateDevices&&navigator.enumerateDevices&&(navigator.enumerateDevices=navigator.enumerateDevices.bind(navigator)),!navigator.enumerateDevices)return void(callback&&callback());MediaDevices=[],audioInputDevices=[],audioOutputDevices=[],videoInputDevices=[],navigator.enumerateDevices(function(devices){devices.forEach(function(_device){var device={};for(var d in _device)device[d]=_device[d];"audio"===device.kind&&(device.kind="audioinput"),"video"===device.kind&&(device.kind="videoinput");var skip;MediaDevices.forEach(function(d){d.id===device.id&&d.kind===device.kind&&(skip=!0)}),skip||(device.deviceId||(device.deviceId=device.id),device.id||(device.id=device.deviceId),device.label?("videoinput"!==device.kind||isWebsiteHasWebcamPermissions||(isWebsiteHasWebcamPermissions=!0),"audioinput"!==device.kind||isWebsiteHasMicrophonePermissions||(isWebsiteHasMicrophonePermissions=!0)):(device.label="Please invoke getUserMedia once.","https:"!==location.protocol&&(device.label="HTTPs is required to get label of this "+device.kind+" device.")),"audioinput"===device.kind&&(hasMicrophone=!0,-1===audioInputDevices.indexOf(device)&&audioInputDevices.push(device)),"audiooutput"===device.kind&&(hasSpeakers=!0,-1===audioOutputDevices.indexOf(device)&&audioOutputDevices.push(device)),"videoinput"===device.kind&&(hasWebcam=!0,-1===videoInputDevices.indexOf(device)&&videoInputDevices.push(device)),-1===MediaDevices.indexOf(device)&&MediaDevices.push(device))}),"undefined"!=typeof DetectRTC&&(DetectRTC.MediaDevices=MediaDevices,DetectRTC.hasMicrophone=hasMicrophone,DetectRTC.hasSpeakers=hasSpeakers,DetectRTC.hasWebcam=hasWebcam,DetectRTC.isWebsiteHasWebcamPermissions=isWebsiteHasWebcamPermissions,DetectRTC.isWebsiteHasMicrophonePermissions=isWebsiteHasMicrophonePermissions,DetectRTC.audioInputDevices=audioInputDevices,DetectRTC.audioOutputDevices=audioOutputDevices,DetectRTC.videoInputDevices=videoInputDevices),callback&&callback()})}}var navigator=window.navigator;"undefined"!=typeof navigator?("undefined"!=typeof navigator.webkitGetUserMedia&&(navigator.getUserMedia=navigator.webkitGetUserMedia),"undefined"!=typeof navigator.mozGetUserMedia&&(navigator.getUserMedia=navigator.mozGetUserMedia)):navigator={getUserMedia:function(){},userAgent:"Fake/5.0 (FakeOS) AppleWebKit/123 (KHTML, like Gecko) Fake/12.3.4567.89 Fake/123.45"};var isMobileDevice=!!navigator.userAgent.match(/Android|iPhone|iPad|iPod|BlackBerry|IEMobile/i),isEdge=!(-1===navigator.userAgent.indexOf("Edge")||!navigator.msSaveOrOpenBlob&&!navigator.msSaveBlob),isOpera=!!window.opera||navigator.userAgent.indexOf(" OPR/")>=0,isFirefox="undefined"!=typeof window.InstallTrigger,isSafari=Object.prototype.toString.call(window.HTMLElement).indexOf("Constructor")>0,isChrome=!!window.chrome&&!isOpera,isIE=!!document.documentMode&&!isEdge,isMobile={
Android:function(){return navigator.userAgent.match(/Android/i)},BlackBerry:function(){return navigator.userAgent.match(/BlackBerry/i)},iOS:function(){return navigator.userAgent.match(/iPhone|iPad|iPod/i)},Opera:function(){return navigator.userAgent.match(/Opera Mini/i)},Windows:function(){return navigator.userAgent.match(/IEMobile/i)},any:function(){return isMobile.Android()||isMobile.BlackBerry()||isMobile.iOS()||isMobile.Opera()||isMobile.Windows()},getOsName:function(){var osName="Unknown OS";return isMobile.Android()&&(osName="Android"),isMobile.BlackBerry()&&(osName="BlackBerry"),isMobile.iOS()&&(osName="iOS"),isMobile.Opera()&&(osName="Opera Mini"),isMobile.Windows()&&(osName="Windows"),osName}},osName="Unknown OS",osVersion="Unknown OS Version";if(isMobile.any())osName=isMobile.getOsName();else{var osInfo=detectDesktopOS();osName=osInfo.osName,osVersion=osInfo.osVersion}var isCanvasSupportsStreamCapturing=!1,isVideoSupportsStreamCapturing=!1;["captureStream","mozCaptureStream","webkitCaptureStream"].forEach(function(item){!isCanvasSupportsStreamCapturing&&item in document.createElement("canvas")&&(isCanvasSupportsStreamCapturing=!0),!isVideoSupportsStreamCapturing&&item in document.createElement("video")&&(isVideoSupportsStreamCapturing=!0)});var MediaDevices=[],audioInputDevices=[],audioOutputDevices=[],videoInputDevices=[];navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices&&(navigator.enumerateDevices=function(callback){navigator.mediaDevices.enumerateDevices().then(callback)});var canEnumerate=!1;"undefined"!=typeof MediaStreamTrack&&"getSources"in MediaStreamTrack?canEnumerate=!0:navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices&&(canEnumerate=!0);var hasMicrophone=!1,hasSpeakers=!1,hasWebcam=!1,isWebsiteHasMicrophonePermissions=!1,isWebsiteHasWebcamPermissions=!1;checkDeviceSupport();var DetectRTC=window.DetectRTC||{};DetectRTC.browser=getBrowserInfo(),detectPrivateMode(function(isPrivateBrowsing){DetectRTC.browser.isPrivateBrowsing=!!isPrivateBrowsing}),DetectRTC.browser["is"+DetectRTC.browser.name]=!0;var isWebRTCSupported=(!!(window.process&&"object"==typeof window.process&&window.process.versions&&window.process.versions["node-webkit"]),!1);["RTCPeerConnection","webkitRTCPeerConnection","mozRTCPeerConnection","RTCIceGatherer"].forEach(function(item){isWebRTCSupported||item in window&&(isWebRTCSupported=!0)}),DetectRTC.isWebRTCSupported=isWebRTCSupported,DetectRTC.isORTCSupported="undefined"!=typeof RTCIceGatherer;var isScreenCapturingSupported=!1;DetectRTC.browser.isChrome&&DetectRTC.browser.version>=35?isScreenCapturingSupported=!0:DetectRTC.browser.isFirefox&&DetectRTC.browser.version>=34&&(isScreenCapturingSupported=!0),"https:"!==location.protocol&&(isScreenCapturingSupported=!1),DetectRTC.isScreenCapturingSupported=isScreenCapturingSupported;var webAudio={isSupported:!1,isCreateMediaStreamSourceSupported:!1};["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"].forEach(function(item){webAudio.isSupported||item in window&&(webAudio.isSupported=!0,"createMediaStreamSource"in window[item].prototype&&(webAudio.isCreateMediaStreamSourceSupported=!0))}),DetectRTC.isAudioContextSupported=webAudio.isSupported,DetectRTC.isCreateMediaStreamSourceSupported=webAudio.isCreateMediaStreamSourceSupported;var isRtpDataChannelsSupported=!1;DetectRTC.browser.isChrome&&DetectRTC.browser.version>31&&(isRtpDataChannelsSupported=!0),DetectRTC.isRtpDataChannelsSupported=isRtpDataChannelsSupported;var isSCTPSupportd=!1;DetectRTC.browser.isFirefox&&DetectRTC.browser.version>28?isSCTPSupportd=!0:DetectRTC.browser.isChrome&&DetectRTC.browser.version>25?isSCTPSupportd=!0:DetectRTC.browser.isOpera&&DetectRTC.browser.version>=11&&(isSCTPSupportd=!0),DetectRTC.isSctpDataChannelsSupported=isSCTPSupportd,DetectRTC.isMobileDevice=isMobileDevice;var isGetUserMediaSupported=!1;navigator.getUserMedia?isGetUserMediaSupported=!0:navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&(isGetUserMediaSupported=!0),DetectRTC.browser.isChrome&&DetectRTC.browser.version>=46&&"https:"!==location.protocol&&(DetectRTC.isGetUserMediaSupported="Requires HTTPs"),DetectRTC.isGetUserMediaSupported=isGetUserMediaSupported,DetectRTC.osName=osName,DetectRTC.osVersion=osVersion;var displayResolution="";if(screen.width){var width=screen.width?screen.width:"",height=screen.height?screen.height:"";displayResolution+=""+width+" x "+height}DetectRTC.displayResolution=displayResolution,DetectRTC.isCanvasSupportsStreamCapturing=isCanvasSupportsStreamCapturing,DetectRTC.isVideoSupportsStreamCapturing=isVideoSupportsStreamCapturing,DetectRTC.DetectLocalIPAddress=DetectLocalIPAddress,DetectRTC.isWebSocketsSupported="WebSocket"in window&&2===window.WebSocket.CLOSING,DetectRTC.isWebSocketsBlocked=!DetectRTC.isWebSocketsSupported,DetectRTC.checkWebSocketsSupport=function(callback){callback=callback||function(){};try{var websocket=new WebSocket("wss://echo.websocket.org:443/");websocket.onopen=function(){DetectRTC.isWebSocketsBlocked=!1,callback(),websocket.close(),websocket=null},websocket.onerror=function(){DetectRTC.isWebSocketsBlocked=!0,callback()}}catch(e){DetectRTC.isWebSocketsBlocked=!0,callback()}},DetectRTC.load=function(callback){callback=callback||function(){},checkDeviceSupport(callback)},DetectRTC.MediaDevices=MediaDevices,DetectRTC.hasMicrophone=hasMicrophone,DetectRTC.hasSpeakers=hasSpeakers,DetectRTC.hasWebcam=hasWebcam,DetectRTC.isWebsiteHasWebcamPermissions=isWebsiteHasWebcamPermissions,DetectRTC.isWebsiteHasMicrophonePermissions=isWebsiteHasMicrophonePermissions,DetectRTC.audioInputDevices=audioInputDevices,DetectRTC.audioOutputDevices=audioOutputDevices,DetectRTC.videoInputDevices=videoInputDevices;var isSetSinkIdSupported=!1;"setSinkId"in document.createElement("video")&&(isSetSinkIdSupported=!0),DetectRTC.isSetSinkIdSupported=isSetSinkIdSupported;var isRTPSenderReplaceTracksSupported=!1;DetectRTC.browser.isFirefox?"getSenders"in mozRTCPeerConnection.prototype&&(isRTPSenderReplaceTracksSupported=!0):DetectRTC.browser.isChrome&&"getSenders"in webkitRTCPeerConnection.prototype&&(isRTPSenderReplaceTracksSupported=!0),DetectRTC.isRTPSenderReplaceTracksSupported=isRTPSenderReplaceTracksSupported;var isRemoteStreamProcessingSupported=!1;DetectRTC.browser.isFirefox&&DetectRTC.browser.version>38&&(isRemoteStreamProcessingSupported=!0),DetectRTC.isRemoteStreamProcessingSupported=isRemoteStreamProcessingSupported;var isApplyConstraintsSupported=!1;"undefined"!=typeof MediaStreamTrack&&"applyConstraints"in MediaStreamTrack.prototype&&(isApplyConstraintsSupported=!0),DetectRTC.isApplyConstraintsSupported=isApplyConstraintsSupported;var isMultiMonitorScreenCapturingSupported=!1;DetectRTC.browser.isFirefox&&DetectRTC.browser.version>=43&&(isMultiMonitorScreenCapturingSupported=!0),DetectRTC.isMultiMonitorScreenCapturingSupported=isMultiMonitorScreenCapturingSupported,window.DetectRTC=DetectRTC}(),function(){function getScreenConstraints(error,sourceId){var screen_constraints={audio:!1,video:{mandatory:{chromeMediaSource:error?"screen":"desktop",maxWidth:15360,maxHeight:8640,minFrameRate:30,maxFrameRate:64,minAspectRatio:1.77,googLeakyBucket:!0,googTemporalLayeredScreencast:!0},optional:[]}};return sourceId&&(screen_constraints.video.mandatory.chromeMediaSourceId=sourceId),screen_constraints}function postMessage(){return iframe?iframe.isLoaded?void iframe.contentWindow.postMessage({captureSourceId:!0},"*"):void setTimeout(postMessage,100):void loadIFrame(postMessage)}function loadIFrame(loadCallback){return iframe?void loadCallback():(iframe=document.createElement("iframe"),iframe.onload=function(){iframe.isLoaded=!0,loadCallback()},iframe.src="https://www.webrtc-experiment.com/getSourceId/",iframe.style.display="none",void(document.body||document.documentElement).appendChild(iframe))}window.getScreenId=function(callback){function onIFrameCallback(event){event.data&&(event.data.chromeMediaSourceId&&("PermissionDeniedError"===event.data.chromeMediaSourceId?callback("permission-denied"):callback(null,event.data.chromeMediaSourceId,getScreenConstraints(null,event.data.chromeMediaSourceId))),event.data.chromeExtensionStatus&&callback(event.data.chromeExtensionStatus,null,getScreenConstraints(event.data.chromeExtensionStatus)),window.removeEventListener("message",onIFrameCallback))}return navigator.mozGetUserMedia?void callback(null,"firefox",{video:{mozMediaSource:"window",mediaSource:"window",width:15360,height:8640}}):(postMessage(),void window.addEventListener("message",onIFrameCallback))};var iframe;window.getScreenConstraints=function(callback){loadIFrame(function(){getScreenId(function(error,sourceId,screen_constraints){callback(error,screen_constraints.video)})})}}(),function(){function getScreenConstraints(error,sourceId){var screen_constraints={audio:!1,video:{mandatory:{chromeMediaSource:error?"screen":"desktop",maxWidth:15360,maxHeight:8640,minFrameRate:30,maxFrameRate:64,minAspectRatio:1.77,googLeakyBucket:!0,googTemporalLayeredScreencast:!0},optional:[]}};return sourceId&&(screen_constraints.video.mandatory.chromeMediaSourceId=sourceId),screen_constraints}function postMessage(){return iframe?iframe.isLoaded?void iframe.contentWindow.postMessage({captureSourceId:!0},"*"):void setTimeout(postMessage,100):void loadIFrame(postMessage)}function loadIFrame(loadCallback){return iframe?void loadCallback():(iframe=document.createElement("iframe"),iframe.onload=function(){iframe.isLoaded=!0,loadCallback()},iframe.src="https://www.webrtc-experiment.com/getSourceId/",iframe.style.display="none",void(document.body||document.documentElement).appendChild(iframe))}if(-1!==document.domain.indexOf("webrtc-experiment.com")){window.getScreenId=function(callback){function onIFrameCallback(event){event.data&&(event.data.chromeMediaSourceId&&("PermissionDeniedError"===event.data.chromeMediaSourceId?callback("permission-denied"):callback(null,event.data.chromeMediaSourceId,getScreenConstraints(null,event.data.chromeMediaSourceId))),event.data.chromeExtensionStatus&&callback(event.data.chromeExtensionStatus,null,getScreenConstraints(event.data.chromeExtensionStatus)),window.removeEventListener("message",onIFrameCallback))}return navigator.mozGetUserMedia?void callback(null,"firefox",{video:{mozMediaSource:"window",mediaSource:"window",width:15360,height:8640}}):(postMessage(),void window.addEventListener("message",onIFrameCallback))};var iframe;window.getScreenConstraints=function(callback){loadIFrame(function(){getScreenId(function(error,sourceId,screen_constraints){callback(error,screen_constraints.video)})})}}}();var TextSender={send:function(config){function sendText(textMessage,text){var data={type:"text",uuid:uuid,sendingTime:sendingTime};textMessage&&(text=textMessage,data.packets=parseInt(text.length/packetSize)),text.length>packetSize?data.message=text.slice(0,packetSize):(data.message=text,data.last=!0,data.isobject=isobject),channel.send(data,remoteUserId),textToTransfer=text.slice(data.message.length),textToTransfer.length&&setTimeout(function(){sendText(null,textToTransfer)},connection.chunkInterval||100)}var connection=config.connection,channel=config.channel,remoteUserId=config.remoteUserId,initialText=config.text,packetSize=connection.chunkSize||1e3,textToTransfer="",isobject=!1;isString(initialText)||(isobject=!0,initialText=JSON.stringify(initialText));var uuid=getRandomString(),sendingTime=(new Date).getTime();sendText(initialText)}},FileProgressBarHandler=function(){function handle(connection){function updateLabel(progress,label){if(-1!==progress.position){var position=+progress.position.toFixed(2).split(".")[1]||100;label.innerHTML=position+"%"}}var progressHelper={};connection.onFileStart=function(file){var div=document.createElement("div");return div.title=file.name,div.innerHTML=" ",file.remoteUserId&&(div.innerHTML+=" (Sharing with:"+file.remoteUserId+")"),connection.filesContainer||(connection.filesContainer=document.body||document.documentElement),connection.filesContainer.insertBefore(div,connection.filesContainer.firstChild),file.remoteUserId?(progressHelper[file.uuid]||(progressHelper[file.uuid]={}),progressHelper[file.uuid][file.remoteUserId]={div:div,progress:div.querySelector("progress"),label:div.querySelector("label")},void(progressHelper[file.uuid][file.remoteUserId].progress.max=file.maxChunks)):(progressHelper[file.uuid]={div:div,progress:div.querySelector("progress"),label:div.querySelector("label")},void(progressHelper[file.uuid].progress.max=file.maxChunks))},connection.onFileProgress=function(chunk){var helper=progressHelper[chunk.uuid];helper&&(!chunk.remoteUserId||(helper=progressHelper[chunk.uuid][chunk.remoteUserId]))&&(helper.progress.value=chunk.currentPosition||chunk.maxChunks||helper.progress.max,updateLabel(helper.progress,helper.label))},connection.onFileEnd=function(file){var helper=progressHelper[file.uuid];if(!helper)return void console.error("No such progress-helper element exists.",file);if(!file.remoteUserId||(helper=progressHelper[file.uuid][file.remoteUserId])){var div=helper.div;-1!=file.type.indexOf("image")?div.innerHTML='Download '+file.name+'
':div.innerHTML='Download '+file.name+'
'}}}return{handle:handle}}(),TranslationHandler=function(){function handle(connection){connection.autoTranslateText=!1,connection.language="en",connection.googKey="AIzaSyCgB5hmFY74WYB-EoWkhr9cAGr6TiTHrEE",connection.Translator={TranslateText:function(text,callback){var newScript=document.createElement("script");newScript.type="text/javascript";var sourceText=encodeURIComponent(text),randomNumber="method"+connection.token();window[randomNumber]=function(response){response.data&&response.data.translations[0]&&callback&&callback(response.data.translations[0].translatedText),response.error&&"Daily Limit Exceeded"===response.error.message&&(warn('Text translation failed. Error message: "Daily Limit Exceeded."'),callback(text))};var source="https://www.googleapis.com/language/translate/v2?key="+connection.googKey+"&target="+(connection.language||"en-US")+"&callback=window."+randomNumber+"&q="+sourceText;newScript.src=source,document.getElementsByTagName("head")[0].appendChild(newScript)}}}return{handle:handle}}();window.RTCMultiConnection=RTCMultiConnection}();
\ No newline at end of file
diff --git a/dev/FileBufferReader.js b/dev/FileBufferReader.js
index f6eaf14a..59cce28a 100755
--- a/dev/FileBufferReader.js
+++ b/dev/FileBufferReader.js
@@ -38,7 +38,8 @@ function FileBufferReader() {
uuid: file.uuid || 0,
file: file,
earlyCallback: earlyCallback,
- extra: extra
+ extra: extra,
+ chunkSize: extra.chunkSize
};
fbrHelper.readAsArrayBuffer(fbr, options);
diff --git a/dev/MultiPeersHandler.js b/dev/MultiPeersHandler.js
index 8b67b81f..4dd7c27b 100755
--- a/dev/MultiPeersHandler.js
+++ b/dev/MultiPeersHandler.js
@@ -412,7 +412,7 @@ function MultiPeers(connection) {
}, {
userid: connection.userid,
// extra: connection.extra,
- chunkSize: connection.chunkSize || 0
+ chunkSize: isFirefox ? 15 * 1000 : connection.chunkSize || 0
});
};
@@ -437,7 +437,13 @@ function MultiPeers(connection) {
};
this.onDataChannelOpened = function(channel, remoteUserId) {
+ // keep last channel only; we are not expecting parallel/channels channels
+ if (connection.peers[remoteUserId].channels.length) {
+ return;
+ }
+
connection.peers[remoteUserId].channels.push(channel);
+
connection.onopen({
userid: remoteUserId,
extra: connection.peers[remoteUserId] ? connection.peers[remoteUserId].extra : {},
diff --git a/dev/RTCMultiConnection.js b/dev/RTCMultiConnection.js
index bb7e4132..db14f614 100755
--- a/dev/RTCMultiConnection.js
+++ b/dev/RTCMultiConnection.js
@@ -1239,7 +1239,7 @@ function RTCMultiConnection(roomid) {
// default value is 15k because Firefox's receiving limit is 16k!
// however 64k works chrome-to-chrome
- connection.chunkSize = 15 * 1000;
+ connection.chunkSize = 65 * 1000;
connection.maxParticipantsAllowed = 1000;
diff --git a/dist/rmc3.fbr.js b/dist/rmc3.fbr.js
index f6eaf14a..59cce28a 100644
--- a/dist/rmc3.fbr.js
+++ b/dist/rmc3.fbr.js
@@ -38,7 +38,8 @@ function FileBufferReader() {
uuid: file.uuid || 0,
file: file,
earlyCallback: earlyCallback,
- extra: extra
+ extra: extra,
+ chunkSize: extra.chunkSize
};
fbrHelper.readAsArrayBuffer(fbr, options);
diff --git a/dist/rmc3.fbr.min.js b/dist/rmc3.fbr.min.js
index 0d6daef5..73733b48 100644
--- a/dist/rmc3.fbr.min.js
+++ b/dist/rmc3.fbr.min.js
@@ -1,3 +1,3 @@
-// Last time updated at Sunday, January 17th, 2016, 5:28:52 PM
+// Last time updated: 2016-01-19 9:53:09 AM UTC
-function FileBufferReader(){function fbrClone(from,to){if(null==from||"object"!=typeof from)return from;if(from.constructor!=Object&&from.constructor!=Array)return from;if(from.constructor==Date||from.constructor==RegExp||from.constructor==Function||from.constructor==String||from.constructor==Number||from.constructor==Boolean)return new from.constructor(from);to=to||new from.constructor;for(var name in from)to[name]="undefined"==typeof to[name]?fbrClone(from[name],null):to[name];return to}var fbr=this,fbrHelper=new FileBufferReaderHelper;fbr.chunks={},fbr.users={},fbr.readAsArrayBuffer=function(file,earlyCallback,extra){if(!file.slice)return void console.warn("Not a real File object.",file);if(extra=extra||{userid:0},file.extra)if("string"==typeof file.extra)extra.extra=file.extra;else for(var e in file.extra)extra[e]=file.extra[e];extra.fileName=file.name,file.uuid&&(extra.fileUniqueId=file.uuid);var options={uuid:file.uuid||0,file:file,earlyCallback:earlyCallback,extra:extra};fbrHelper.readAsArrayBuffer(fbr,options)},fbr.getNextChunk=function(fileUUID,callback,userid){var allFileChunks=fbr.chunks[fileUUID];if(allFileChunks){var currentPosition;"undefined"!=typeof userid?(fbr.users[userid+""]||(fbr.users[userid+""]={fileUUID:fileUUID,userid:userid,currentPosition:-1}),fbr.users[userid+""].currentPosition++,currentPosition=fbr.users[userid+""].currentPosition):(fbr.chunks[fileUUID].currentPosition++,currentPosition=fbr.chunks[fileUUID].currentPosition);var nextChunk=allFileChunks[currentPosition];nextChunk&&(nextChunk=fbrClone(nextChunk),"undefined"!=typeof userid&&(nextChunk.remoteUserId=userid+""),nextChunk.start&&fbr.onBegin(nextChunk),nextChunk.end&&fbr.onEnd(nextChunk),fbr.onProgress(nextChunk),fbr.convertToArrayBuffer(nextChunk,function(buffer){return nextChunk.currentPosition==nextChunk.maxChunks?void callback(buffer,!0):void callback(buffer,!1)}))}};var fbReceiver=new FileBufferReceiver(fbr);fbr.addChunk=function(chunk,callback){return chunk?void fbReceiver.receive(chunk,function(uuid){fbr.convertToArrayBuffer({readyForNextChunk:!0,uuid:uuid},callback)}):void console.error("Chunk is missing.")},fbr.onBegin=function(){},fbr.onEnd=function(){},fbr.onProgress=function(){},fbr.convertToObject=FileConverter.ConvertToObject,fbr.convertToArrayBuffer=FileConverter.ConvertToArrayBuffer,fbr.setMultipleUsers=function(){}}function FileBufferReaderHelper(){function processInWebWorker(_function){var blob=URL.createObjectURL(new Blob([_function.toString(),"this.onmessage = function (e) {"+_function.name+"(e.data);}"],{type:"application/javascript"}));return window.fileBufferWorker||(window.fileBufferWorker=new Worker(blob)),window.fileBufferWorker}function fileReaderWrapper(options,callback){function addChunks(fileName,binarySlice,addChunkCallback){numOfChunksInSlice=Math.ceil(binarySlice.byteLength/chunkSize);for(var i=0;numOfChunksInSlice>i;i++){var start=i*chunkSize;chunks[currentPosition]=binarySlice.slice(start,Math.min(start+chunkSize,binarySlice.byteLength)),callback({uuid:file.uuid,buffer:chunks[currentPosition],currentPosition:currentPosition,maxChunks:maxChunks,size:file.size,name:file.name||options.extra.fileName,lastModifiedDate:file.lastModifiedDate?file.lastModifiedDate.toString():"",type:file.type,extra:options}),currentPosition++}currentPosition==maxChunks&&(hasEntireFile=!0),addChunkCallback()}callback=callback||function(chunk){postMessage(chunk)};var file=options.file;file.uuid||(file.uuid=options.fileUniqueId||(100*Math.random()).toString().replace(/\./g,""));var chunkSize=options.chunkSize||15e3,sliceId=0,cacheSize=chunkSize,chunksPerSlice=Math.floor(Math.min(1e8,cacheSize)/chunkSize),sliceSize=chunksPerSlice*chunkSize,maxChunks=Math.ceil(file.size/chunkSize);file.maxChunks=maxChunks;var numOfChunksInSlice,hasEntireFile,currentPosition=0,chunks=[];callback({currentPosition:currentPosition,uuid:file.uuid,maxChunks:maxChunks,size:file.size,name:file.name||options.extra.fileName,type:file.type,lastModifiedDate:file.lastModifiedDate?file.lastModifiedDate.toString():"",start:!0,extra:options});var blob,reader=new FileReader;reader.onloadend=function(evt){evt.target.readyState==FileReader.DONE&&addChunks(file.name,evt.target.result,function(){sliceId++,(sliceId+1)*sliceSize5&&5==chunk.currentPosition&&earlyCallback&&(earlyCallback(chunk.uuid),earlyCallback=null)}var earlyCallback=options.earlyCallback;if(delete options.earlyCallback,navigator.mozGetUserMedia&&(window.___Worker=window.Worker,delete window.Worker),window.Worker&&"function"==typeof Worker){var webWorker=processInWebWorker(fileReaderWrapper);webWorker.onmessage=function(event){processChunk(event.data)},webWorker.postMessage(options)}else fileReaderWrapper(options,processChunk),navigator.mozGetUserMedia&&(window.Worker=window.___Worker)}}function FileBufferReceiver(fbr){function receive(chunk,callback){if(!chunk.uuid)return void fbr.convertToObject(chunk,function(object){receive(object)});if(chunk.start&&!packets[chunk.uuid]&&(packets[chunk.uuid]=[],missedChunks[chunk.uuid]&&(packets[chunk.uuid].push(chunk.buffer),missedChunks[chunk.uuid].forEach(function(chunk){receive(chunk,callback)}),delete missedChunks[chunk.uuid]),fbr.onBegin&&fbr.onBegin(chunk)),!chunk.end&&chunk.buffer){if(!packets[chunk.uuid])return missedChunks[chunk.uuid]||(missedChunks[chunk.uuid]=[]),void missedChunks[chunk.uuid].push(chunk);-1==packets[chunk.uuid].indexOf(chunk.buffer)&&packets[chunk.uuid].push(chunk.buffer)}if(chunk.end){for(var _packets=packets[chunk.uuid],finalArray=[],length=_packets.length,i=0;length>i;i++)_packets[i]&&finalArray.push(_packets[i]);var blob=new Blob(finalArray,{type:chunk.type});blob=merge(blob,chunk),blob.url=URL.createObjectURL(blob),blob.uuid=chunk.uuid||blob.extra.fileUniqueId,blob.name=blob.name||blob.extra.fileName,blob.size||console.error("Something went wrong. Blob Size is 0."),fbr.onEnd&&fbr.onEnd(blob)}chunk.buffer&&fbr.onProgress&&fbr.onProgress(chunk),chunk.end||callback(chunk.uuid)}function merge(mergein,mergeto){if(mergein||(mergein={}),!mergeto)return mergein;for(var item in mergeto)mergein[item]=mergeto[item];return mergein}var packets={},missedChunks=[];this.receive=receive}function merge(mergein,mergeto){if(mergein||(mergein={}),!mergeto)return mergein;for(var item in mergeto)mergein[item]=mergeto[item];return mergein}window.FileSelector=function(){function selectFile(callback,multiple){var file=document.createElement("input");file.type="file",multiple&&(file.multiple=!0),file.onchange=function(){return multiple?file.files.length?void callback(file.files):void console.error("No file selected."):file.files[0]?(callback(file.files[0]),void file.parentNode.removeChild(file)):void console.error("No file selected.")},file.style.display="none",(document.body||document.documentElement).appendChild(file),fireClickEvent(file)}function fireClickEvent(element){var evt=new window.MouseEvent("click",{view:window,bubbles:!0,cancelable:!0,button:0,buttons:0,mozInputSource:1});element.dispatchEvent(evt)}var selector=this;selector.selectSingleFile=selectFile,selector.selectMultipleFiles=function(callback){selectFile(callback,!0)}};var FileConverter={ConvertToArrayBuffer:function(object,callback){binarize.pack(object,function(dataView){callback(dataView.buffer)})},ConvertToObject:function(buffer,callback){binarize.unpack(buffer,callback)}};!function(root){var debug=!1,BIG_ENDIAN=!1,LITTLE_ENDIAN=!0,TYPE_LENGTH=Uint8Array.BYTES_PER_ELEMENT,LENGTH_LENGTH=Uint16Array.BYTES_PER_ELEMENT,BYTES_LENGTH=Uint32Array.BYTES_PER_ELEMENT,Types={NULL:0,UNDEFINED:1,STRING:2,NUMBER:3,BOOLEAN:4,ARRAY:5,OBJECT:6,INT8ARRAY:7,INT16ARRAY:8,INT32ARRAY:9,UINT8ARRAY:10,UINT16ARRAY:11,UINT32ARRAY:12,FLOAT32ARRAY:13,FLOAT64ARRAY:14,ARRAYBUFFER:15,BLOB:16,FILE:16,BUFFER:17};if(debug)var TypeNames=["NULL","UNDEFINED","STRING","NUMBER","BOOLEAN","ARRAY","OBJECT","INT8ARRAY","INT16ARRAY","INT32ARRAY","UINT8ARRAY","UINT16ARRAY","UINT32ARRAY","FLOAT32ARRAY","FLOAT64ARRAY","ARRAYBUFFER","BLOB","BUFFER"];var Length=[null,null,"Uint16","Float64","Uint8",null,null,"Int8","Int16","Int32","Uint8","Uint16","Uint32","Float32","Float64","Uint8","Uint8","Uint8"],binary_dump=function(view,start,length){var table=[],endianness=BIG_ENDIAN,ROW_LENGTH=40;table[0]=[];for(var i=0;ROW_LENGTH>i;i++)table[0][i]=10>i?"0"+i.toString(10):i.toString(10);for(i=0;length>i;i++){var code=view.getUint8(start+i,endianness),index=~~(i/ROW_LENGTH)+1;"undefined"==typeof table[index]&&(table[index]=[]),table[index][i%ROW_LENGTH]=16>code?"0"+code.toString(16):code.toString(16)}for(console.log("%c"+table[0].join(" "),"font-weight: bold;"),i=1;ij;j++,cursor+=unit)view.setUint16(cursor,value.charCodeAt(j),endianness);break;case Types.NUMBER:case Types.BOOLEAN:debug&&console.info("%c"+value.toString(),"font-weight:bold;"),view["set"+type_name](cursor,value,endianness),cursor+=unit;break;case Types.INT8ARRAY:case Types.INT16ARRAY:case Types.INT32ARRAY:case Types.UINT8ARRAY:case Types.UINT16ARRAY:case Types.UINT32ARRAY:case Types.FLOAT32ARRAY:case Types.FLOAT64ARRAY:var _view=new Uint8Array(view.buffer,cursor,byte_length);_view.set(new Uint8Array(value.buffer)),cursor+=byte_length;break;case Types.ARRAYBUFFER:case Types.BUFFER:var _view=new Uint8Array(view.buffer,cursor,byte_length);_view.set(new Uint8Array(value)),cursor+=byte_length;break;case Types.BLOB:case Types.ARRAY:case Types.OBJECT:break;default:throw"TypeError: Unexpected type found."}debug&&binary_dump(view,start,cursor-start)}return view},unpack=function(view,cursor){var type,length,byte_length,value,elem,i=0,endianness=BIG_ENDIAN,start=cursor;type=view.getUint8(cursor,endianness),cursor+=TYPE_LENGTH,debug&&console.info("Unpacking",type,TypeNames[type]),(type===Types.ARRAY||type===Types.OBJECT)&&(length=view.getUint16(cursor,endianness),cursor+=LENGTH_LENGTH,debug&&console.info("Content Length",length)),byte_length=view.getUint32(cursor,endianness),cursor+=BYTES_LENGTH,debug&&console.info("Byte Length",byte_length,"bytes");var type_name=Length[type],unit=null===type_name?0:root[type_name+"Array"].BYTES_PER_ELEMENT;switch(type){case Types.NULL:case Types.UNDEFINED:debug&&binary_dump(view,start,cursor-start),value=null;break;case Types.STRING:length=byte_length/unit;var string=[];for(i=0;length>i;i++){var code=view.getUint16(cursor,endianness);cursor+=unit,string.push(String.fromCharCode(code))}value=string.join(""),debug&&(console.info('Actual Content %c"'+value+'"',"font-weight:bold;"),binary_dump(view,start,cursor-start));break;case Types.NUMBER:value=view.getFloat64(cursor,endianness),cursor+=unit,debug&&(console.info('Actual Content %c"'+value.toString()+'"',"font-weight:bold;"),binary_dump(view,start,cursor-start));break;case Types.BOOLEAN:value=1===view.getUint8(cursor,endianness)?!0:!1,cursor+=unit,debug&&(console.info('Actual Content %c"'+value.toString()+'"',"font-weight:bold;"),binary_dump(view,start,cursor-start));break;case Types.INT8ARRAY:case Types.INT16ARRAY:case Types.INT32ARRAY:case Types.UINT8ARRAY:case Types.UINT16ARRAY:case Types.UINT32ARRAY:case Types.FLOAT32ARRAY:case Types.FLOAT64ARRAY:case Types.ARRAYBUFFER:elem=view.buffer.slice(cursor,cursor+byte_length),cursor+=byte_length,value=type===Types.ARRAYBUFFER?elem:new root[type_name+"Array"](elem),debug&&binary_dump(view,start,cursor-start);break;case Types.BLOB:if(debug&&binary_dump(view,start,cursor-start),root.Blob){var mime=unpack(view,cursor),buffer=unpack(view,mime.cursor);cursor=buffer.cursor,value=new Blob([buffer.value],{type:mime.value})}else elem=view.buffer.slice(cursor,cursor+byte_length),cursor+=byte_length,value=new Buffer(elem);break;case Types.ARRAY:for(debug&&binary_dump(view,start,cursor-start),value=[],i=0;length>i;i++)elem=unpack(view,cursor),cursor=elem.cursor,value.push(elem.value);break;case Types.OBJECT:for(debug&&binary_dump(view,start,cursor-start),value={},i=0;length>i;i++){var key=unpack(view,cursor),val=unpack(view,key.cursor);cursor=val.cursor,value[key.value]=val.value}break;default:throw"TypeError: Type not supported."}return{value:value,cursor:cursor}},deferredSerialize=function(array,callback){for(var length=array.length,results=[],count=0,byte_length=0,i=0;ii;i++){var start=i*chunkSize;chunks[currentPosition]=binarySlice.slice(start,Math.min(start+chunkSize,binarySlice.byteLength)),callback({uuid:file.uuid,buffer:chunks[currentPosition],currentPosition:currentPosition,maxChunks:maxChunks,size:file.size,name:file.name||options.extra.fileName,lastModifiedDate:file.lastModifiedDate?file.lastModifiedDate.toString():"",type:file.type,extra:options}),currentPosition++}currentPosition==maxChunks&&(hasEntireFile=!0),addChunkCallback()}callback=callback||function(chunk){postMessage(chunk)};var file=options.file;file.uuid||(file.uuid=options.fileUniqueId||(100*Math.random()).toString().replace(/\./g,""));var chunkSize=options.chunkSize||15e3,sliceId=0,cacheSize=chunkSize,chunksPerSlice=Math.floor(Math.min(1e8,cacheSize)/chunkSize),sliceSize=chunksPerSlice*chunkSize,maxChunks=Math.ceil(file.size/chunkSize);file.maxChunks=maxChunks;var numOfChunksInSlice,hasEntireFile,currentPosition=0,chunks=[];callback({currentPosition:currentPosition,uuid:file.uuid,maxChunks:maxChunks,size:file.size,name:file.name||options.extra.fileName,type:file.type,lastModifiedDate:file.lastModifiedDate?file.lastModifiedDate.toString():"",start:!0,extra:options});var blob,reader=new FileReader;reader.onloadend=function(evt){evt.target.readyState==FileReader.DONE&&addChunks(file.name,evt.target.result,function(){sliceId++,(sliceId+1)*sliceSize5&&5==chunk.currentPosition&&earlyCallback&&(earlyCallback(chunk.uuid),earlyCallback=null)}var earlyCallback=options.earlyCallback;if(delete options.earlyCallback,navigator.mozGetUserMedia&&(window.___Worker=window.Worker,delete window.Worker),window.Worker&&"function"==typeof Worker){var webWorker=processInWebWorker(fileReaderWrapper);webWorker.onmessage=function(event){processChunk(event.data)},webWorker.postMessage(options)}else fileReaderWrapper(options,processChunk),navigator.mozGetUserMedia&&(window.Worker=window.___Worker)}}function FileBufferReceiver(fbr){function receive(chunk,callback){if(!chunk.uuid)return void fbr.convertToObject(chunk,function(object){receive(object)});if(chunk.start&&!packets[chunk.uuid]&&(packets[chunk.uuid]=[],missedChunks[chunk.uuid]&&(packets[chunk.uuid].push(chunk.buffer),missedChunks[chunk.uuid].forEach(function(chunk){receive(chunk,callback)}),delete missedChunks[chunk.uuid]),fbr.onBegin&&fbr.onBegin(chunk)),!chunk.end&&chunk.buffer){if(!packets[chunk.uuid])return missedChunks[chunk.uuid]||(missedChunks[chunk.uuid]=[]),void missedChunks[chunk.uuid].push(chunk);-1==packets[chunk.uuid].indexOf(chunk.buffer)&&packets[chunk.uuid].push(chunk.buffer)}if(chunk.end){for(var _packets=packets[chunk.uuid],finalArray=[],length=_packets.length,i=0;length>i;i++)_packets[i]&&finalArray.push(_packets[i]);var blob=new Blob(finalArray,{type:chunk.type});blob=merge(blob,chunk),blob.url=URL.createObjectURL(blob),blob.uuid=chunk.uuid||blob.extra.fileUniqueId,blob.name=blob.name||blob.extra.fileName,blob.size||console.error("Something went wrong. Blob Size is 0."),fbr.onEnd&&fbr.onEnd(blob)}chunk.buffer&&fbr.onProgress&&fbr.onProgress(chunk),chunk.end||callback(chunk.uuid)}function merge(mergein,mergeto){if(mergein||(mergein={}),!mergeto)return mergein;for(var item in mergeto)mergein[item]=mergeto[item];return mergein}var packets={},missedChunks=[];this.receive=receive}function merge(mergein,mergeto){if(mergein||(mergein={}),!mergeto)return mergein;for(var item in mergeto)mergein[item]=mergeto[item];return mergein}window.FileSelector=function(){function selectFile(callback,multiple){var file=document.createElement("input");file.type="file",multiple&&(file.multiple=!0),file.onchange=function(){return multiple?file.files.length?void callback(file.files):void console.error("No file selected."):file.files[0]?(callback(file.files[0]),void file.parentNode.removeChild(file)):void console.error("No file selected.")},file.style.display="none",(document.body||document.documentElement).appendChild(file),fireClickEvent(file)}function fireClickEvent(element){var evt=new window.MouseEvent("click",{view:window,bubbles:!0,cancelable:!0,button:0,buttons:0,mozInputSource:1});element.dispatchEvent(evt)}var selector=this;selector.selectSingleFile=selectFile,selector.selectMultipleFiles=function(callback){selectFile(callback,!0)}};var FileConverter={ConvertToArrayBuffer:function(object,callback){binarize.pack(object,function(dataView){callback(dataView.buffer)})},ConvertToObject:function(buffer,callback){binarize.unpack(buffer,callback)}};!function(root){var debug=!1,BIG_ENDIAN=!1,LITTLE_ENDIAN=!0,TYPE_LENGTH=Uint8Array.BYTES_PER_ELEMENT,LENGTH_LENGTH=Uint16Array.BYTES_PER_ELEMENT,BYTES_LENGTH=Uint32Array.BYTES_PER_ELEMENT,Types={NULL:0,UNDEFINED:1,STRING:2,NUMBER:3,BOOLEAN:4,ARRAY:5,OBJECT:6,INT8ARRAY:7,INT16ARRAY:8,INT32ARRAY:9,UINT8ARRAY:10,UINT16ARRAY:11,UINT32ARRAY:12,FLOAT32ARRAY:13,FLOAT64ARRAY:14,ARRAYBUFFER:15,BLOB:16,FILE:16,BUFFER:17};if(debug)var TypeNames=["NULL","UNDEFINED","STRING","NUMBER","BOOLEAN","ARRAY","OBJECT","INT8ARRAY","INT16ARRAY","INT32ARRAY","UINT8ARRAY","UINT16ARRAY","UINT32ARRAY","FLOAT32ARRAY","FLOAT64ARRAY","ARRAYBUFFER","BLOB","BUFFER"];var Length=[null,null,"Uint16","Float64","Uint8",null,null,"Int8","Int16","Int32","Uint8","Uint16","Uint32","Float32","Float64","Uint8","Uint8","Uint8"],binary_dump=function(view,start,length){var table=[],endianness=BIG_ENDIAN,ROW_LENGTH=40;table[0]=[];for(var i=0;ROW_LENGTH>i;i++)table[0][i]=10>i?"0"+i.toString(10):i.toString(10);for(i=0;length>i;i++){var code=view.getUint8(start+i,endianness),index=~~(i/ROW_LENGTH)+1;"undefined"==typeof table[index]&&(table[index]=[]),table[index][i%ROW_LENGTH]=16>code?"0"+code.toString(16):code.toString(16)}for(console.log("%c"+table[0].join(" "),"font-weight: bold;"),i=1;ij;j++,cursor+=unit)view.setUint16(cursor,value.charCodeAt(j),endianness);break;case Types.NUMBER:case Types.BOOLEAN:debug&&console.info("%c"+value.toString(),"font-weight:bold;"),view["set"+type_name](cursor,value,endianness),cursor+=unit;break;case Types.INT8ARRAY:case Types.INT16ARRAY:case Types.INT32ARRAY:case Types.UINT8ARRAY:case Types.UINT16ARRAY:case Types.UINT32ARRAY:case Types.FLOAT32ARRAY:case Types.FLOAT64ARRAY:var _view=new Uint8Array(view.buffer,cursor,byte_length);_view.set(new Uint8Array(value.buffer)),cursor+=byte_length;break;case Types.ARRAYBUFFER:case Types.BUFFER:var _view=new Uint8Array(view.buffer,cursor,byte_length);_view.set(new Uint8Array(value)),cursor+=byte_length;break;case Types.BLOB:case Types.ARRAY:case Types.OBJECT:break;default:throw"TypeError: Unexpected type found."}debug&&binary_dump(view,start,cursor-start)}return view},unpack=function(view,cursor){var type,length,byte_length,value,elem,i=0,endianness=BIG_ENDIAN,start=cursor;type=view.getUint8(cursor,endianness),cursor+=TYPE_LENGTH,debug&&console.info("Unpacking",type,TypeNames[type]),(type===Types.ARRAY||type===Types.OBJECT)&&(length=view.getUint16(cursor,endianness),cursor+=LENGTH_LENGTH,debug&&console.info("Content Length",length)),byte_length=view.getUint32(cursor,endianness),cursor+=BYTES_LENGTH,debug&&console.info("Byte Length",byte_length,"bytes");var type_name=Length[type],unit=null===type_name?0:root[type_name+"Array"].BYTES_PER_ELEMENT;switch(type){case Types.NULL:case Types.UNDEFINED:debug&&binary_dump(view,start,cursor-start),value=null;break;case Types.STRING:length=byte_length/unit;var string=[];for(i=0;length>i;i++){var code=view.getUint16(cursor,endianness);cursor+=unit,string.push(String.fromCharCode(code))}value=string.join(""),debug&&(console.info('Actual Content %c"'+value+'"',"font-weight:bold;"),binary_dump(view,start,cursor-start));break;case Types.NUMBER:value=view.getFloat64(cursor,endianness),cursor+=unit,debug&&(console.info('Actual Content %c"'+value.toString()+'"',"font-weight:bold;"),binary_dump(view,start,cursor-start));break;case Types.BOOLEAN:value=1===view.getUint8(cursor,endianness)?!0:!1,cursor+=unit,debug&&(console.info('Actual Content %c"'+value.toString()+'"',"font-weight:bold;"),binary_dump(view,start,cursor-start));break;case Types.INT8ARRAY:case Types.INT16ARRAY:case Types.INT32ARRAY:case Types.UINT8ARRAY:case Types.UINT16ARRAY:case Types.UINT32ARRAY:case Types.FLOAT32ARRAY:case Types.FLOAT64ARRAY:case Types.ARRAYBUFFER:elem=view.buffer.slice(cursor,cursor+byte_length),cursor+=byte_length,value=type===Types.ARRAYBUFFER?elem:new root[type_name+"Array"](elem),debug&&binary_dump(view,start,cursor-start);break;case Types.BLOB:if(debug&&binary_dump(view,start,cursor-start),root.Blob){var mime=unpack(view,cursor),buffer=unpack(view,mime.cursor);cursor=buffer.cursor,value=new Blob([buffer.value],{type:mime.value})}else elem=view.buffer.slice(cursor,cursor+byte_length),cursor+=byte_length,value=new Buffer(elem);break;case Types.ARRAY:for(debug&&binary_dump(view,start,cursor-start),value=[],i=0;length>i;i++)elem=unpack(view,cursor),cursor=elem.cursor,value.push(elem.value);break;case Types.OBJECT:for(debug&&binary_dump(view,start,cursor-start),value={},i=0;length>i;i++){var key=unpack(view,cursor),val=unpack(view,key.cursor);cursor=val.cursor,value[key.value]=val.value}break;default:throw"TypeError: Type not supported."}return{value:value,cursor:cursor}},deferredSerialize=function(array,callback){for(var length=array.length,results=[],count=0,byte_length=0,i=0;ii;i++)token+=a[i].toString(36);return token}return(Math.random()*(new Date).getTime()).toString(36).replace(/\./g,"")}function getRMCMediaElement(stream,callback,connection){var isAudioOnly=!1;stream.getVideoTracks().length||(isAudioOnly=!0);var mediaElement=document.createElement(isAudioOnly?"audio":"video");return isPluginRTC?(connection.videosContainer.insertBefore(mediaElement,connection.videosContainer.firstChild),void setTimeout(function(){Plugin.attachMediaStream(mediaElement,stream),callback(mediaElement)},1e3)):(mediaElement[isFirefox?"mozSrcObject":"src"]=isFirefox?stream:window.URL.createObjectURL(stream),mediaElement.controls=!0,isFirefox&&mediaElement.addEventListener("ended",function(){if(fireEvent(stream,"ended",stream),currentUserMediaRequest.remove(stream.idInstance),"local"===stream.type){StreamsHandler.onSyncNeeded(stream.streamid,"ended"),connection.attachStreams.forEach(function(aStream,idx){stream.streamid===aStream.streamid&&delete connection.attachStreams[idx]});var newStreamsArray=[];connection.attachStreams.forEach(function(aStream){aStream&&newStreamsArray.push(aStream)}),connection.attachStreams=newStreamsArray,connection.observers.all();var streamEvent=connection.streamEvents[stream.streamid];if(streamEvent)return void connection.onstreamended(streamEvent);this.parentNode&&this.parentNode.removeChild(this)}},!1),mediaElement.play(),void callback(mediaElement))}function listenEventHandler(eventName,eventHandler){window.removeEventListener(eventName,eventHandler),window.addEventListener(eventName,eventHandler,!1)}function removeNullEntries(array){var newArray=[];return array.forEach(function(item){item&&newArray.push(item)}),newArray}function isData(session){return!session.audio&&!session.video&&!session.screen&&session.data}function isNull(obj){return"undefined"==typeof obj}function isString(obj){return"string"==typeof obj}function observeObject(obj,callback){Object.observe&&Object.observe(obj,function(changes){var jsonStringified=JSON.stringify(changes);lastChanges!=jsonStringified&&(lastChanges=jsonStringified,callback(changes))})}function setSdpConstraints(config){var sdpConstraints,sdpConstraints_mandatory={OfferToReceiveAudio:!!config.OfferToReceiveAudio,OfferToReceiveVideo:!!config.OfferToReceiveVideo};return sdpConstraints={mandatory:sdpConstraints_mandatory,optional:[{VoiceActivityDetection:!1}]},navigator.mozGetUserMedia&&firefoxVersion>34&&(sdpConstraints={OfferToReceiveAudio:!!config.OfferToReceiveAudio,OfferToReceiveVideo:!!config.OfferToReceiveVideo}),sdpConstraints}function onPluginRTCInitialized(pluginRTCObject){Plugin=pluginRTCObject,MediaStreamTrack=Plugin.MediaStreamTrack,RTCPeerConnection=Plugin.RTCPeerConnection,RTCIceCandidate=Plugin.RTCIceCandidate,RTCSessionDescription=Plugin.RTCSessionDescription}function PeerInitiator(config){function createDataChannel(){if(!isOfferer)return void(peer.ondatachannel=function(event){var channel=event.channel;setChannelEvents(channel)});var channel=peer.createDataChannel("RTCDataChannel",{});setChannelEvents(channel)}function setChannelEvents(channel){channel.binaryType="arraybuffer",channel.onmessage=function(event){config.onDataChannelMessage(event.data)},channel.onopen=function(){config.onDataChannelOpened(channel)},channel.onerror=function(error){config.onDataChannelError(error)},channel.onclose=function(event){config.onDataChannelClosed(event)},channel.internalSend=channel.send,channel.send=function(data){"open"===channel.readyState&&channel.internalSend(data)},peer.channel=channel}var connection=config.rtcMultiConnection;this.extra=config.remoteSdp?config.remoteSdp.extra:connection.extra,this.remoteUserId=config.remoteUserId,this.streams=[],this.channels=[],this.connectionDescription=config.connectionDescription;var that=this;config.remoteSdp&&(this.connectionDescription=config.remoteSdp.connectionDescription);var allRemoteStreams={};if(Object.observe){var that=this;Object.observe(this.channels,function(changes){changes.forEach(function(change){"add"===change.type&&change.object[change.name].addEventListener("close",function(){delete that.channels[that.channels.indexOf(change.object[change.name])],that.channels=removeNullEntries(that.channels)},!1),("remove"===change.type||"delete"===change.type)&&-1!==that.channels.indexOf(change.object[change.name])&&delete that.channels.indexOf(change.object[change.name]),that.channels=removeNullEntries(that.channels)})})}defaults.sdpConstraints=setSdpConstraints({OfferToReceiveAudio:!0,OfferToReceiveVideo:!0});var peer,renegotiatingPeer=!!config.renegotiatingPeer;config.remoteSdp&&(renegotiatingPeer=!!config.remoteSdp.renegotiatingPeer);var localStreams=[];config.localStreams.forEach(function(stream){stream&&localStreams.push(stream)}),renegotiatingPeer?(peer=config.peerRef,peer.getLocalStreams().forEach(function(stream){localStreams.forEach(function(localStream,index){stream==localStream&&delete localStreams[index]}),config.removeStreams.forEach(function(streamToRemove,index){stream===streamToRemove&&(stream=config.beforeRemovingStream(stream),stream&&peer.removeStream&&peer.removeStream(stream),localStreams.forEach(function(localStream,index){streamToRemove==localStream&&delete localStreams[index]}))})})):peer=new RTCPeerConnection(navigator.onLine?{iceServers:config.iceServers,iceTransports:"all"}:null,config.optionalArgument),"Firefox"===connection.DetectRTC.browser.name&&(peer.removeStream=function(stream){stream.mute(),connection.StreamsHandler.onSyncNeeded(stream.streamid,"stream-removed")}),peer.onicecandidate=function(event){event.candidate&&config.onLocalCandidate({candidate:event.candidate.candidate,sdpMid:event.candidate.sdpMid,sdpMLineIndex:event.candidate.sdpMLineIndex})};var isFirefoxOffered=!isFirefox;config.remoteSdp&&config.remoteSdp.remotePeerSdpConstraints&&config.remoteSdp.remotePeerSdpConstraints.isFirefoxOffered&&(isFirefoxOffered=!0),localStreams.forEach(function(localStream){config.remoteSdp&&config.remoteSdp.remotePeerSdpConstraints&&config.remoteSdp.remotePeerSdpConstraints.dontGetRemoteStream||config.dontAttachLocalStream||(localStream=config.beforeAddingStream(localStream),localStream&&peer.addStream(localStream))}),peer.oniceconnectionstatechange=peer.onsignalingstatechange=function(){var extra=that.extra;if(connection.peers[that.remoteUserId]&&(extra=connection.peers[that.remoteUserId].extra||extra),!peer)return void that.removeAllRemoteStreams();if(-1!==peer.iceConnectionState.search(/closed|failed/gi)){if(peer.firedOnce)return;if(peer.firedOnce=!0,that.removeAllRemoteStreams(),that.connectionDescription&&connection.userid==that.connectionDescription.sender&&connection.autoReDialOnFailure){if(connection.isInitiator)return;setTimeout(function(){connection.rejoin(that.connectionDescription),peer&&(peer.firedOnce=!1)},5e3)}}config.onPeerStateChanged({iceConnectionState:peer.iceConnectionState,iceGatheringState:peer.iceGatheringState,signalingState:peer.signalingState,extra:extra,userid:that.remoteUserId})};var sdpConstraints={OfferToReceiveAudio:!!localStreams.length,OfferToReceiveVideo:!!localStreams.length};config.localPeerSdpConstraints&&(sdpConstraints=config.localPeerSdpConstraints),defaults.sdpConstraints=setSdpConstraints(sdpConstraints),peer.onaddstream=function(event){var streamsToShare={};config.remoteSdp&&config.remoteSdp.streamsToShare?streamsToShare=config.remoteSdp.streamsToShare:config.streamsToShare&&(streamsToShare=config.streamsToShare);var streamToShare=streamsToShare[event.stream.id];streamToShare&&(event.stream.isAudio=streamToShare.isAudio,event.stream.isVideo=streamToShare.isVideo,event.stream.isScreen=streamToShare.isScreen),event.stream.streamid=event.stream.id,event.stream.stop||(event.stream.stop=function(){fireEvent(event.stream,"ended",event)}),allRemoteStreams[event.stream.id]=event.stream,config.onRemoteStream(event.stream)},peer.onremovestream=function(event){event.stream.streamid=event.stream.id,allRemoteStreams[event.stream.id]&&delete allRemoteStreams[event.stream.id],config.onRemoteStreamRemoved(event.stream)},this.addRemoteCandidate=function(remoteCandidate){peer.addIceCandidate(new RTCIceCandidate(remoteCandidate))},this.addRemoteSdp=function(remoteSdp){peer.setRemoteDescription(new RTCSessionDescription(remoteSdp),function(){},function(error){connection.enableLogs&&console.error(JSON.stringify(error,null," ")),connection.autoReDialOnFailure&&setTimeout(function(){connection.rejoin(that.connectionDescription)},2e3)})};var isOfferer=!0;config.remoteSdp&&(isOfferer=!1),config.enableDataChannels===!0&&createDataChannel(),config.remoteSdp&&(config.remoteSdp.remotePeerSdpConstraints&&(sdpConstraints=config.remoteSdp.remotePeerSdpConstraints),defaults.sdpConstraints=setSdpConstraints(sdpConstraints),this.addRemoteSdp(config.remoteSdp)),("two-way"==config.session.audio||"two-way"==config.session.video||"two-way"==config.session.screen)&&(defaults.sdpConstraints=setSdpConstraints({OfferToReceiveAudio:"two-way"==config.session.audio||config.remoteSdp&&config.remoteSdp.remotePeerSdpConstraints&&config.remoteSdp.remotePeerSdpConstraints.OfferToReceiveAudio,OfferToReceiveVideo:"two-way"==config.session.video||"two-way"==config.session.screen||config.remoteSdp&&config.remoteSdp.remotePeerSdpConstraints&&config.remoteSdp.remotePeerSdpConstraints.OfferToReceiveAudio}));var streamsToShare={};peer.getLocalStreams().forEach(function(stream){streamsToShare[stream.streamid]={isAudio:!!stream.isAudio,isVideo:!!stream.isVideo,isScreen:!!stream.isScreen}}),peer[isOfferer?"createOffer":"createAnswer"](function(localSdp){localSdp.sdp=config.processSdp(localSdp.sdp),peer.setLocalDescription(localSdp),config.onLocalSdp({type:localSdp.type,sdp:localSdp.sdp,remotePeerSdpConstraints:config.remotePeerSdpConstraints||!1,renegotiatingPeer:!!config.renegotiatingPeer||!1,connectionDescription:that.connectionDescription,dontGetRemoteStream:!!config.dontGetRemoteStream,extra:connection?connection.extra:{},streamsToShare:streamsToShare,isFirefoxOffered:isFirefox})},function(error){connection.enableLogs&&console.error("sdp-error",error),connection.autoReDialOnFailure&&connection.isInitiator&&isFirefox&&isFirefoxOffered&&setTimeout(function(){connection.rejoin(that.connectionDescription)},5e3)},defaults.sdpConstraints),peer.nativeClose=peer.close,peer.close=function(){if(!peer)return void that.removeAllRemoteStreams();connection.multiPeersHandler.onNegotiationNeeded({userLeft:!0,autoCloseEntireSession:!!connection.autoCloseEntireSession},that.remoteUserId);try{-1===peer.iceConnectionState.search(/closed|failed/gi)&&peer.getRemoteStreams().forEach(function(stream){stream.stop()}),peer.nativeClose()}catch(e){}peer=null},this.removeAllRemoteStreams=function(){for(var id in allRemoteStreams)config.onRemoteStreamRemoved(allRemoteStreams[id]);allRemoteStreams={},that.streams.forEach(function(stream){stream.stop()}),that.streams=[]},this.peer=peer}function loadIceFrame(callback,skip){if(!loadedIceFrame){if(!skip)return loadIceFrame(callback,!0);loadedIceFrame=!0;var iframe=document.createElement("iframe");iframe.onload=function(){function iFrameLoaderCallback(event){event.data&&event.data.iceServers&&(callback(event.data.iceServers),window.removeEventListener("message",iFrameLoaderCallback))}iframe.isLoaded=!0,listenEventHandler("message",iFrameLoaderCallback),iframe.contentWindow.postMessage("get-ice-servers","*")},iframe.src="https://cdn.webrtc-experiment.com/getIceServers/",iframe.style.display="none",(document.body||document.documentElement).appendChild(iframe)}}function requestUserMedia(constraints){return new Promise(function(resolve,reject){getUserMedia(constraints,resolve,reject)})}function setStreamType(constraints,stream){constraints.mandatory&&constraints.mandatory.chromeMediaSource?stream.isScreen=!0:constraints.mozMediaSource||constraints.mediaSource?stream.isScreen=!0:constraints.video?stream.isVideo=!0:constraints.audio&&(stream.isAudio=!0)}function getUserMediaHandler(options){function streaming(stream,returnBack){setStreamType(options.localMediaConstraints,stream),options.onGettingLocalMedia(stream,returnBack),stream.addEventListener("ended",function(){delete currentUserMediaRequest.streams[idInstance],currentUserMediaRequest.mutex=!1,currentUserMediaRequest.queueRequests.indexOf(options)&&(delete currentUserMediaRequest.queueRequests[currentUserMediaRequest.queueRequests.indexOf(options)],currentUserMediaRequest.queueRequests=removeNullEntries(currentUserMediaRequest.queueRequests))},!1),currentUserMediaRequest.streams[idInstance]={stream:stream},currentUserMediaRequest.mutex=!1,currentUserMediaRequest.queueRequests.length&&getUserMediaHandler(currentUserMediaRequest.queueRequests.shift())}if(currentUserMediaRequest.mutex===!0)return void currentUserMediaRequest.queueRequests.push(options);currentUserMediaRequest.mutex=!0;var idInstance=JSON.stringify(options.localMediaConstraints);if(currentUserMediaRequest.streams[idInstance])streaming(currentUserMediaRequest.streams[idInstance].stream,!0);else{if(isPluginRTC){document.createElement("video");return void Plugin.getUserMedia({audio:!0,video:!0},function(stream){stream.streamid=stream.id||getRandomString(),streaming(stream)},function(error){})}"undefined"!=typeof DetectRTC&&(DetectRTC.hasMicrophone||(options.localMediaConstraints.audio=!1),DetectRTC.hasWebcam||(options.localMediaConstraints.video=!1)),navigator.mediaDevices.getUserMedia(options.localMediaConstraints).then(function(stream){stream.streamid=stream.streamid||stream.id||getRandomString(),stream.idInstance=idInstance,streaming(stream)})["catch"](function(error){options.onLocalMediaError(error,options.localMediaConstraints)})}}function TextReceiver(connection){function receive(data,userid,extra){var uuid=data.uuid;if(content[uuid]||(content[uuid]=[]),content[uuid].push(data.message),data.last){var message=content[uuid].join("");data.isobject&&(message=JSON.parse(message));var receivingTime=(new Date).getTime(),latency=receivingTime-data.sendingTime,e={data:message,userid:userid,extra:extra,latency:latency};connection.autoTranslateText?(e.original=e.data,connection.Translator.TranslateText(e.data,function(translatedText){e.data=translatedText,connection.onmessage(e)})):connection.onmessage(e),delete content[uuid]}}var content={};return{receive:receive}}var isOpera=!!window.opera||navigator.userAgent.indexOf(" OPR/")>=0,isFirefox="undefined"!=typeof window.InstallTrigger,isSafari=Object.prototype.toString.call(window.HTMLElement).indexOf("Constructor")>0,isChrome=!!window.chrome&&!isOpera,isIE=!!document.documentMode,isPluginRTC=isSafari||isIE,chromeVersion=(!!navigator.userAgent.match(/Android|iPhone|iPad|iPod|BlackBerry|IEMobile/i),
+"use strict";!function(){function RTCMultiConnection(roomid){function onUserLeft(remoteUserId){connection.peers[remoteUserId]&&connection.peers[remoteUserId].peer&&(connection.peers[remoteUserId].streams.forEach(function(stream){stream.stop()}),connection.peers[remoteUserId]&&(connection.peers[remoteUserId].peer.close(),connection.peers[remoteUserId]&&(connection.peers[remoteUserId].peer=null)),connection.onleave({userid:remoteUserId,extra:connection.peers[remoteUserId]?connection.peers[remoteUserId].extra:{}})),delete connection.peers[remoteUserId]}function connectSocket(connectCallback){if(socket)return void(connectCallback&&connectCallback(socket));if("undefined"==typeof SocketConnection)if("undefined"!=typeof FirebaseConnection)window.SocketConnection=FirebaseConnection;else{if("undefined"==typeof PubNubConnection)throw"SocketConnection.js seems missed.";window.SocketConnection=PubNubConnection}socket=new SocketConnection(connection,function(s){socket=s,connectCallback&&connectCallback(socket)})}function beforeUnload(shiftModerationControlOnLeave){if(connection.closeBeforeUnload&&(connection.peers.getAllParticipants().forEach(function(participant){mPeer.onNegotiationNeeded({userLeft:!0,autoCloseEntireSession:!!connection.autoCloseEntireSession},participant),connection.peers[participant]&&connection.peers[participant].peer&&connection.peers[participant].peer.close()}),socket&&("undefined"!=typeof socket.disconnect&&(connection.autoReDialOnFailure=!1,socket.disconnect()),socket=null),connection.broadcasters.length&&!connection.autoCloseEntireSession)){var firstBroadcaster=connection.broadcasters[0],otherBroadcasters=[];connection.broadcasters.forEach(function(broadcaster){broadcaster!==firstBroadcaster&&otherBroadcasters.push(broadcaster)}),connection.shiftModerationControl(firstBroadcaster,otherBroadcasters,"undefined"!=typeof shiftModerationControlOnLeave?shiftModerationControlOnLeave:!0),connection.broadcasters=[],connection.isInitiator=!1}}function applyConstraints(stream,mediaConstraints){return stream?(mediaConstraints.audio&&stream.getAudioTracks().forEach(function(track){track.applyConstraints(mediaConstraints.audio)}),void(mediaConstraints.video&&stream.getVideoTracks().forEach(function(track){track.applyConstraints(mediaConstraints.video)}))):void(connection.enableLogs&&console.error("No stream to applyConstraints."))}function replaceTrack(track,remoteUserId,isVideoTrack){return remoteUserId?void mPeer.replaceTrack(track,remoteUserId,isVideoTrack):void connection.peers.getAllParticipants().forEach(function(participant){mPeer.replaceTrack(track,participant,isVideoTrack)})}function setStreamEndHandler(stream,isRemote){isRemote=!!isRemote,stream.alreadySetEndHandler||(stream.alreadySetEndHandler=!0,stream&&stream.addEventListener&&stream.addEventListener("ended",function(){stream.idInstance&¤tUserMediaRequest.remove(stream.idInstance),isRemote||(delete connection.attachStreams[connection.attachStreams.indexOf(stream)],-1===connection.removeStreams.indexOf(stream)&&connection.removeStreams.push(stream),connection.attachStreams=removeNullEntries(connection.attachStreams),connection.removeStreams=removeNullEntries(connection.removeStreams),connection.observers.all());var streamEvent=connection.streamEvents[stream.streamid];streamEvent||(streamEvent={stream:stream,streamid:stream.streamid,type:isRemote?"remote":"local",userid:connection.userid,extra:connection.extra,mediaElement:connection.streamEvents[stream.streamid]?connection.streamEvents[stream.streamid].mediaElement:null}),connection.onstreamended(streamEvent),delete connection.streamEvents[stream.streamid]},!1))}var connection=this;connection.channel=connection.sessionid=(roomid||location.href.replace(/\/|:|#|\?|\$|\^|%|\.|`|~|!|\+|@|\[|\||]|\|*. /g,"").split("\n").join("").split("\r").join(""))+"";var mPeer=new MultiPeers(connection);mPeer.onGettingLocalMedia=function(stream){stream.type="local",setStreamEndHandler(stream),getRMCMediaElement(stream,function(mediaElement){mediaElement.id=stream.streamid,mediaElement.muted=!0,mediaElement.volume=0,-1===connection.attachStreams.indexOf(stream)&&connection.attachStreams.push(stream),"undefined"!=typeof StreamsHandler&&StreamsHandler.setHandlers(stream,!0,connection),connection.streamEvents[stream.streamid]={stream:stream,type:"local",mediaElement:mediaElement,userid:connection.userid,extra:connection.extra,streamid:stream.streamid,blobURL:mediaElement.src||URL.createObjectURL(stream),isAudioMuted:!0},setHarkEvents(connection,connection.streamEvents[stream.streamid]),setMuteHandlers(connection,connection.streamEvents[stream.streamid]),connection.onstream(connection.streamEvents[stream.streamid])},connection),connection.observers.all()},mPeer.onGettingRemoteMedia=function(stream,remoteUserId){stream.type="remote",setStreamEndHandler(stream,"remote-stream"),getRMCMediaElement(stream,function(mediaElement){mediaElement.id=stream.streamid,"undefined"!=typeof StreamsHandler&&StreamsHandler.setHandlers(stream,!1,connection),connection.streamEvents[stream.streamid]={stream:stream,type:"remote",userid:remoteUserId,extra:connection.peers[remoteUserId]?connection.peers[remoteUserId].extra:{},mediaElement:mediaElement,streamid:stream.streamid,blobURL:mediaElement.src||URL.createObjectURL(stream)},setMuteHandlers(connection,connection.streamEvents[stream.streamid]),connection.onstream(connection.streamEvents[stream.streamid])},connection)},mPeer.onRemovingRemoteMedia=function(stream,remoteUserId){var streamEvent=connection.streamEvents[stream.streamid];streamEvent||(streamEvent={stream:stream,type:"remote",userid:remoteUserId,extra:connection.peers[remoteUserId]?connection.peers[remoteUserId].extra:{},streamid:stream.streamid,mediaElement:connection.streamEvents[stream.streamid]?connection.streamEvents[stream.streamid].mediaElement:null}),connection.onstreamended(streamEvent),delete connection.streamEvents[stream.streamid]},mPeer.onNegotiationNeeded=function(message,remoteUserId,callback){connectSocket(function(){socket.emit(connection.socketMessageEvent,"password"in message?message:{remoteUserId:message.remoteUserId||remoteUserId,message:message,sender:connection.userid},callback||function(){})})},mPeer.onUserLeft=onUserLeft,mPeer.disconnectWith=function(remoteUserId,callback){socket&&socket.emit("disconnect-with",remoteUserId,callback||function(){}),connection.peers[remoteUserId]&&(connection.peers[remoteUserId].peer&&connection.peers[remoteUserId].peer.close(),delete connection.peers[remoteUserId])},connection.broadcasters=[],connection.socketOptions={transport:"polling"};var socket;connection.openOrJoin=function(localUserid,password){connection.checkPresence(localUserid,function(isRoomExists,roomid){if("function"==typeof password&&(password(isRoomExists,roomid),password=null),isRoomExists){connection.sessionid=roomid;var localPeerSdpConstraints=!1,remotePeerSdpConstraints=!1,isOneWay=!!connection.session.oneway,isDataOnly=isData(connection.session);remotePeerSdpConstraints={OfferToReceiveAudio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.sdpConstraints.mandatory.OfferToReceiveVideo},localPeerSdpConstraints={OfferToReceiveAudio:isOneWay?!!connection.session.audio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:isOneWay?!!connection.session.video||!!connection.session.screen:connection.sdpConstraints.mandatory.OfferToReceiveVideo};var connectionDescription={remoteUserId:connection.sessionid,message:{newParticipationRequest:!0,isOneWay:isOneWay,isDataOnly:isDataOnly,localPeerSdpConstraints:localPeerSdpConstraints,remotePeerSdpConstraints:remotePeerSdpConstraints},sender:connection.userid,password:password||!1};return void mPeer.onNegotiationNeeded(connectionDescription)}connection.userid;connection.userid=connection.sessionid=localUserid||connection.sessionid,connection.userid+="",socket.emit("changed-uuid",connection.userid),password&&socket.emit("set-password",password),connection.isInitiator=!0,isData(connection.session)||connection.captureUserMedia()})},connection.open=function(localUserid,isPublicModerator){connection.userid;return connection.userid=connection.sessionid=localUserid||connection.sessionid,connection.userid+="",connection.isInitiator=!0,connectSocket(function(){socket.emit("changed-uuid",connection.userid),1==isPublicModerator&&connection.becomePublicModerator()}),isData(connection.session)?void("function"==typeof isPublicModerator&&isPublicModerator()):void connection.captureUserMedia("function"==typeof isPublicModerator?isPublicModerator:null)},connection.becomePublicModerator=function(){connection.isInitiator&&socket.emit("become-a-public-moderator")},connection.rejoin=function(connectionDescription){if(!connection.isInitiator&&connectionDescription&&Object.keys(connectionDescription).length){var extra={};connection.peers[connectionDescription.remoteUserId]&&(extra=connection.peers[connectionDescription.remoteUserId].extra,connection.peers[connectionDescription.remoteUserId].peer&&(connection.peers[connectionDescription.remoteUserId].peer=null),delete connection.peers[connectionDescription.remoteUserId]),connectionDescription&&connectionDescription.remoteUserId&&(connection.join(connectionDescription.remoteUserId),connection.onReConnecting({userid:connectionDescription.remoteUserId,extra:extra}))}},connection.join=connection.connect=function(remoteUserId,options){connection.sessionid=(remoteUserId?remoteUserId.sessionid||remoteUserId.remoteUserId||remoteUserId:!1)||connection.sessionid,connection.sessionid+="";var localPeerSdpConstraints=!1,remotePeerSdpConstraints=!1,isOneWay=!1,isDataOnly=!1;if(remoteUserId&&remoteUserId.session||!remoteUserId||"string"==typeof remoteUserId){var session=remoteUserId?remoteUserId.session||connection.session:connection.session;isOneWay=!!session.oneway,isDataOnly=isData(session),remotePeerSdpConstraints={OfferToReceiveAudio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.sdpConstraints.mandatory.OfferToReceiveVideo},localPeerSdpConstraints={OfferToReceiveAudio:isOneWay?!!connection.session.audio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:isOneWay?!!connection.session.video||!!connection.session.screen:connection.sdpConstraints.mandatory.OfferToReceiveVideo}}options=options||{},"undefined"!=typeof options.localPeerSdpConstraints&&(localPeerSdpConstraints=options.localPeerSdpConstraints),"undefined"!=typeof options.remotePeerSdpConstraints&&(remotePeerSdpConstraints=options.remotePeerSdpConstraints),"undefined"!=typeof options.isOneWay&&(isOneWay=options.isOneWay),"undefined"!=typeof options.isDataOnly&&(isDataOnly=options.isDataOnly);var connectionDescription={remoteUserId:connection.sessionid,message:{newParticipationRequest:!0,isOneWay:isOneWay,isDataOnly:isDataOnly,localPeerSdpConstraints:localPeerSdpConstraints,remotePeerSdpConstraints:remotePeerSdpConstraints},sender:connection.userid,password:!1};return connectSocket(function(){connection.peers[connection.sessionid]||mPeer.onNegotiationNeeded(connectionDescription)}),connectionDescription},connection.connectWithAllParticipants=function(remoteUserId){mPeer.onNegotiationNeeded("connectWithAllParticipants",remoteUserId||connection.sessionid)},connection.removeFromBroadcastersList=function(remoteUserId){mPeer.onNegotiationNeeded("removeFromBroadcastersList",remoteUserId||connection.sessionid),connection.peers.getAllParticipants(remoteUserId||connection.sessionid).forEach(function(participant){mPeer.onNegotiationNeeded("dropPeerConnection",participant),connection.peers[participant].peer.close(),connection.peers[participant].peer=null,delete connection.peers[participant]}),connection.attachStreams.forEach(function(stream){stream.addEventListener("ended",function(){connection.renegotiate(remoteUserId||connection.sessionid)},!1),stream.stop()})},connection.getUserMedia=connection.captureUserMedia=function(callback,session){function invokeGetUserMedia(localMediaConstraints,getUserMedia_callback){var isScreen=!1;localMediaConstraints&&(isScreen=localMediaConstraints.isScreen,delete localMediaConstraints.isScreen),getUserMediaHandler({onGettingLocalMedia:function(stream){return stream.isAudio=stream.isVideo=stream.isScreen=!1,isScreen?stream.isScreen=!0:session.audio&&session.video?stream.isVideo=!0:session.audio&&(stream.isAudio=!0),mPeer.onGettingLocalMedia(stream),getUserMedia_callback?getUserMedia_callback():void(callback&&callback(stream))},onLocalMediaError:function(error){mPeer.onLocalMediaError(error),callback&&callback()},localMediaConstraints:localMediaConstraints||{audio:session.audio?connection.mediaConstraints.audio:!1,video:session.video?connection.mediaConstraints.video:!1}})}return connection.observers.all(),session=session||connection.session,connection.dontCaptureUserMedia||isData(session)?void(callback&&callback()):void((session.audio||session.video||session.screen)&&(session.screen?connection.getScreenConstraints(function(error,screen_constraints){if(error)throw error;invokeGetUserMedia({video:screen_constraints,isScreen:!0},session.audio||session.video?invokeGetUserMedia:!1)}):(session.audio||session.video)&&invokeGetUserMedia()))},connection.closeBeforeUnload=!0,window.addEventListener("beforeunload",beforeUnload,!1),connection.userid=getRandomString(),connection.changeUserId=function(newUserId){connection.userid=newUserId||getRandomString(),socket.emit("changed-uuid",connection.userid)},connection.observers={extra:function(){observeObject(connection.extra,function(changes){socket.emit("extra-data-updated",connection.extra)})},attachStreams:function(){observeObject(connection.attachStreams,function(changes){changes.forEach(function(change){"add"===change.type&&setStreamEndHandler(change.object[change.name]),("remove"===change.type||"delete"===change.type)&&-1===connection.removeStreams.indexOf(change.object[change.name])&&connection.removeStreams.push(change.object[change.name]),connection.attachStreams=removeNullEntries(connection.attachStreams),connection.removeStreams=removeNullEntries(connection.removeStreams),connection.observers.all()})})},all:function(){this.extra(),this.attachStreams(),socket&&socket.emit("extra-data-updated",connection.extra)}},connection.extra={},connection.attachStreams=[],connection.removeStreams=[],connection.observers.all(),connection.session={audio:!0,video:!0},connection.enableFileSharing=!1,connection.mediaConstraints={audio:{mandatory:{},optional:[]},video:{mandatory:{},optional:[]}},DetectRTC.load(function(){DetectRTC.MediaDevices.forEach(function(device){"audioinput"===device.kind&&(connection.mediaConstraints.audio={optional:[{sourceId:device.id},{bandwidth:connection.bandwidth.audio||1024e3}],mandatory:{}},isFirefox&&(connection.mediaConstraints.audio={deviceId:device.id})),"videoinput"===device.kind&&(connection.mediaConstraints.video={optional:[{sourceId:device.id},{googLeakyBucket:!0},{bandwidth:connection.bandwidth.video||2048e3}],mandatory:{}},isFirefox&&(connection.mediaConstraints.video={deviceId:device.id}))})}),connection.sdpConstraints={mandatory:{OfferToReceiveAudio:!0,OfferToReceiveVideo:!0},optional:[{VoiceActivityDetection:!1}]},connection.optionalArgument={optional:[{DtlsSrtpKeyAgreement:!0},{googImprovedWifiBwe:!0},{googScreencastMinBitrate:300},{googIPv6:!0},{googDscp:!0},{googCpuUnderuseThreshold:55},{googCpuOveruseThreshold:85},{googSuspendBelowMinBitrate:!0},{googCpuOveruseDetection:!0}],mandatory:{}},connection.iceServers=IceServersHandler.getIceServers(connection),connection.candidates={host:!0,stun:!0,turn:!0},connection.iceProtocols={tcp:!0,udp:!0},connection.onopen=function(event){connection.enableLogs&&console.info("Data connection has been opened between you & ",event.userid)},connection.onclose=function(event){connection.enableLogs&&console.warn("Data connection has been closed between you & ",event.userid)},connection.onerror=function(error){connection.enableLogs&&console.error(error.userid,"data-error",error)},connection.onmessage=function(event){connection.enableLogs&&console.debug("data-message",event.userid,event.data)},connection.send=function(data,remoteUserId){connection.peers.send(data,remoteUserId)},connection.close=connection.disconnect=connection.leave=function(){beforeUnload(!1)},connection.onstream=function(e){var parentNode=connection.videosContainer;parentNode.insertBefore(e.mediaElement,parentNode.firstChild)},connection.onstreamended=function(e){e.mediaElement||(e.mediaElement=document.getElementById(e.streamid)),e.mediaElement&&e.mediaElement.parentNode&&e.mediaElement.parentNode.removeChild(e.mediaElement)},connection.direction="many-to-many",Array.prototype.getStreamById=function(streamid){var stream;return this.forEach(function(_stream){_stream.streamid==streamid&&(stream=_stream)}),stream},connection.removeStream=function(streamid){var stream;return connection.attachStreams.forEach(function(localStream){localStream.id===streamid&&(stream=localStream)}),stream?void(-1===connection.removeStreams.indexOf(stream)&&(connection.removeStreams.push(stream),connection.peers.getAllParticipants().forEach(function(participant){mPeer.renegotiatePeer(participant)}))):void console.warn("No such stream exists.",streamid)},connection.addStream=function(session){function invokeGetUserMedia(localMediaConstraints,callback){getUserMediaHandler({onGettingLocalMedia:function(stream){var videoConstraints=localMediaConstraints?localMediaConstraints.video:connection.mediaConstraints;return videoConstraints&&(videoConstraints.mediaSource||videoConstraints.mozMediaSource?stream.isScreen=!0:videoConstraints.mandatory&&videoConstraints.mandatory.chromeMediaSource&&(stream.isScreen=!0)),stream.isScreen||(stream.isVideo=stream.getVideoTracks().length,stream.isAudio=!stream.isVideo&&stream.getAudioTracks().length),mPeer.onGettingLocalMedia(stream),session.streamCallback&&session.streamCallback(stream),callback?callback():void connection.renegotiate()},onLocalMediaError:function(error){return mPeer.onLocalMediaError(error),callback?callback():void connection.renegotiate()},localMediaConstraints:localMediaConstraints||{audio:session.audio?connection.mediaConstraints.audio:!1,video:session.video?connection.mediaConstraints.video:!1}})}return isData(session)?void connection.renegotiate():void((!session.audio||session.video||session.screen)&&(session.screen?connection.getScreenConstraints(function(error,screen_constraints){return error?alert(error):void invokeGetUserMedia({video:screen_constraints},session.audio||session.video?invokeGetUserMedia:!1)}):(session.audio||session.video)&&invokeGetUserMedia()))},connection.applyConstraints=function(mediaConstraints,streamid){if(!MediaStreamTrack||!MediaStreamTrack.prototype.applyConstraints)return void alert("track.applyConstraints is NOT supported in your browser.");if(streamid){return connection.streamEvents[streamid]&&(stream=connection.streamEvents[streamid].stream),void applyConstraints(stream,mediaConstraints)}connection.attachStreams.forEach(function(stream){applyConstraints(stream,mediaConstraints)})},connection.replaceTrack=function(session,remoteUserId,isVideoTrack){function invokeGetUserMedia(localMediaConstraints,callback){getUserMediaHandler({onGettingLocalMedia:function(stream){return mPeer.onGettingLocalMedia(stream),callback?callback():void connection.replaceTrack(stream,remoteUserId,isVideoTrack||session.video||session.screen)},onLocalMediaError:function(error){mPeer.onLocalMediaError(error),callback&&callback()},localMediaConstraints:localMediaConstraints||{audio:session.audio?connection.mediaConstraints.audio:!1,video:session.video?connection.mediaConstraints.video:!1}})}if(session=session||{},!RTCPeerConnection.prototype.getSenders)return void this.addStream(session);if(session instanceof MediaStreamTrack)return void replaceTrack(session,remoteUserId,isVideoTrack);if(session instanceof MediaStream)return void replaceTrack(session.getVideoTracks()[0],remoteUserId,isVideoTrack);if(isData(session))throw"connection.replaceTrack requires audio and/or video and/or screen.";(!session.audio||session.video||session.screen)&&(session.screen?connection.getScreenConstraints(function(error,screen_constraints){return error?alert(error):void invokeGetUserMedia({video:screen_constraints},session.audio||session.video?invokeGetUserMedia:!1)}):(session.audio||session.video)&&invokeGetUserMedia())},connection.resetTrack=function(remoteUsersIds,isVideoTrack){remoteUsersIds||(remoteUsersIds=connection.getAllParticipants()),"string"==typeof remoteUsersIds&&(remoteUsersIds=[remoteUsersIds]),remoteUsersIds.forEach(function(participant){var peer=connection.peers[participant].peer;"undefined"!=typeof isVideoTrack&&isVideoTrack!==!0||!peer.lastVideoTrack||connection.replaceTrack(peer.lastVideoTrack,participant,!0),"undefined"!=typeof isVideoTrack&&isVideoTrack!==!1||!peer.lastAudioTrack||connection.replaceTrack(peer.lastAudioTrack,participant,!1)})},connection.renegotiate=function(remoteUserId){return remoteUserId?void mPeer.renegotiatePeer(remoteUserId):void connection.peers.getAllParticipants().forEach(function(participant){mPeer.renegotiatePeer(participant)})},connection.onMediaError=function(error){connection.enableLogs&&console.error(error)},connection.addNewBroadcaster=function(broadcasterId,userPreferences){connection.broadcasters.forEach(function(broadcaster){mPeer.onNegotiationNeeded({newParticipant:broadcasterId,userPreferences:userPreferences||!1},broadcaster)}),connection.session.oneway||"many-to-many"!==connection.direction||-1!==connection.broadcasters.indexOf(broadcasterId)||connection.broadcasters.push(broadcasterId)},connection.filesContainer=connection.videosContainer=document.body||document.documentElement,connection.isInitiator=!1,connection.shareFile=mPeer.shareFile,"undefined"!=typeof FileProgressBarHandler&&FileProgressBarHandler.handle(connection),connection.autoCloseEntireSession=!1,"undefined"!=typeof TranslationHandler&&TranslationHandler.handle(connection),connection.token=getRandomString,connection.onNewParticipant=function(participantId,userPreferences){connection.acceptParticipationRequest(participantId,userPreferences)},connection.acceptParticipationRequest=function(participantId,userPreferences){userPreferences.successCallback&&(userPreferences.successCallback(),delete userPreferences.successCallback),mPeer.createNewPeer(participantId,userPreferences)},connection.onShiftedModerationControl=function(sender,existingBroadcasters){connection.acceptModerationControl(sender,existingBroadcasters)},connection.acceptModerationControl=function(sender,existingBroadcasters){connection.isInitiator=!0,connection.broadcasters=existingBroadcasters,connection.peers.getAllParticipants().forEach(function(participant){mPeer.onNegotiationNeeded({changedUUID:sender,oldUUID:connection.userid,newUUID:sender},participant)}),connection.userid=sender,socket.emit("changed-uuid",connection.userid)},connection.shiftModerationControl=function(remoteUserId,existingBroadcasters,firedOnLeave){mPeer.onNegotiationNeeded({shiftedModerationControl:!0,broadcasters:existingBroadcasters,firedOnLeave:!!firedOnLeave},remoteUserId)},connection.processSdp=function(sdp){return sdp=BandwidthHandler.setApplicationSpecificBandwidth(sdp,connection.bandwidth,!!connection.session.screen),sdp=BandwidthHandler.setVideoBitrates(sdp,{min:connection.bandwidth.video,max:connection.bandwidth.video}),sdp=BandwidthHandler.setOpusAttributes(sdp)},"undefined"!=typeof BandwidthHandler&&(connection.BandwidthHandler=BandwidthHandler),"undefined"!=typeof StreamsHandler&&(connection.StreamsHandler=StreamsHandler),connection.bandwidth={screen:300,audio:50,video:256},connection.onleave=function(userid){},connection.invokeSelectFileDialog=function(callback){var selector=new FileSelector;selector.selectSingleFile(callback)},connection.getPublicModerators=function(userIdStartsWith,callback){"function"==typeof userIdStartsWith&&(callback=userIdStartsWith),connectSocket(function(socket){socket.emit("get-public-moderators","string"==typeof userIdStartsWith?userIdStartsWith:"",callback)})},connection.onmute=function(e){e.mediaElement&&("both"===e.muteType||"video"===e.muteType?(e.mediaElement.src=null,e.mediaElement.pause(),e.mediaElement.poster=e.snapshot||"https://cdn.webrtc-experiment.com/images/muted.png"):"audio"===e.muteType&&(e.mediaElement.muted=!0))},connection.onunmute=function(e){e.mediaElement&&("both"===e.unmuteType||"video"===e.unmuteType?(e.mediaElement.poster=null,e.mediaElement.src=URL.createObjectURL(e.stream),e.mediaElement.play()):"audio"===e.unmuteType&&(e.mediaElement.muted=!1))},connection.onExtraDataUpdated=function(event){event.status="online",connection.onUserStatusChanged(event,!0)},connection.onJoinWithPassword=function(remoteUserId){console.warn(remoteUserId,"is password protected. Please join with password.")},connection.onInvalidPassword=function(remoteUserId,oldPassword){console.warn(remoteUserId,"is password protected. Please join with valid password. Your old password",oldPassword,"is wrong.")},connection.onPasswordMaxTriesOver=function(remoteUserId){console.warn(remoteUserId,"is password protected. Your max password tries exceeded the limit.")},connection.getAllParticipants=function(){return connection.peers.getAllParticipants()},"undefined"!=typeof StreamsHandler&&(StreamsHandler.onSyncNeeded=function(streamid,action,type){connection.peers.getAllParticipants().forEach(function(participant){mPeer.onNegotiationNeeded({streamid:streamid,action:action,streamSyncNeeded:!0,type:type||"both"},participant)})}),connection.getAllVideos=function(remoteUserId){var videos=[];return Array.prototype.slice.call(document.querySelectorAll("video")).forEach(function(video){video.getAttribute("data-userid")===remoteUserId&&videos.push(video)}),videos},connection.connectSocket=function(callback){connectSocket(callback)},connection.getSocket=function(callback){return socket?callback&&callback(socket):connectSocket(callback),socket},connection.getRemoteStreams=mPeer.getRemoteStreams,connection.autoReDialOnFailure=!0;var skipStreams=["selectFirst","selectAll","forEach"];connection.streamEvents={selectFirst:function(options){if(!options){var firstStream;for(var str in connection.streamEvents)-1!==skipStreams.indexOf(str)||firstStream||(firstStream=connection.streamEvents[str]);return firstStream}},selectAll:function(){}},connection.socketURL="/",connection.socketMessageEvent="RTCMultiConnection-Message",connection.socketCustomEvent="RTCMultiConnection-Custom-Message",connection.DetectRTC=DetectRTC,connection.onUserStatusChanged=function(event,dontWriteLogs){connection.enableLogs&&!dontWriteLogs&&console.info(event.userid,event.status)},connection.getUserMediaHandler=getUserMediaHandler,connection.multiPeersHandler=mPeer,connection.enableLogs=!0,connection.setCustomSocketHandler=function(customSocketHandler){"undefined"!=typeof SocketConnection&&(SocketConnection=customSocketHandler)},connection.chunkSize=65e3,connection.maxParticipantsAllowed=1e3,connection.disconnectWith=mPeer.disconnectWith,connection.checkPresence=function(remoteUserId,callback){mPeer.onNegotiationNeeded({detectPresence:!0,userid:(remoteUserId||connection.sessionid)+""},"system",callback)},connection.onReadyForOffer=function(remoteUserId,userPreferences){connection.multiPeersHandler.createNewPeer(remoteUserId,userPreferences)},connection.setUserPreferences=function(userPreferences){return connection.dontAttachStream&&(userPreferences.dontAttachLocalStream=!0),connection.dontGetRemoteStream&&(userPreferences.dontGetRemoteStream=!0),userPreferences},connection.updateExtraData=function(){socket.emit("extra-data-updated",connection.extra)},connection.enableScalableBroadcast=!1,connection.singleBroadcastAttendees=3,connection.dontCaptureUserMedia=!1,connection.dontAttachStream=!1,connection.dontGetRemoteStream=!1,connection.onReConnecting=function(event){connection.enableLogs&&console.info("ReConnecting with",event.userid,"...")},connection.beforeAddingStream=function(stream){return stream},connection.beforeRemovingStream=function(stream){return stream},"undefined"!=typeof isChromeExtensionAvailable&&(connection.checkIfChromeExtensionAvailable=isChromeExtensionAvailable),"undefined"!=typeof isFirefoxExtensionAvailable&&(connection.checkIfChromeExtensionAvailable=isFirefoxExtensionAvailable),"undefined"!=typeof getChromeExtensionStatus&&(connection.getChromeExtensionStatus=getChromeExtensionStatus),connection.getScreenConstraints=function(callback){getScreenConstraints(function(error,screen_constraints){error||(screen_constraints=connection.modifyScreenConstraints(screen_constraints),callback(error,screen_constraints))})},connection.modifyScreenConstraints=function(screen_constraints){return screen_constraints},connection.onPeerStateChanged=function(state){connection.enableLogs&&-1!==state.iceConnectionState.search(/closed|failed/gi)&&console.error("Peer connection is closed between you & ",state.userid,state.extra,"state:",state.iceConnectionState)}}function SocketConnection(connection,connectCallback){var parameters="";parameters+="?userid="+connection.userid,parameters+="&msgEvent="+connection.socketMessageEvent,parameters+="&socketCustomEvent="+connection.socketCustomEvent,connection.enableScalableBroadcast&&(parameters+="&enableScalableBroadcast=true",parameters+="&singleBroadcastAttendees="+connection.singleBroadcastAttendees);var socket=io.connect((connection.socketURL||"/")+parameters,connection.socketOptions),mPeer=connection.multiPeersHandler;return socket.on("extra-data-updated",function(remoteUserId,extra){connection.peers[remoteUserId]&&(connection.peers[remoteUserId].extra=extra,connection.onExtraDataUpdated({userid:remoteUserId,extra:extra}))}),socket.on(connection.socketMessageEvent,function(message){if(message.remoteUserId==connection.userid){if(connection.peers[message.sender]&&connection.peers[message.sender].extra!=message.extra&&(connection.peers[message.sender].extra=message.extra,connection.onExtraDataUpdated({userid:message.sender,extra:message.extra})),message.message.streamSyncNeeded&&connection.peers[message.sender]){var stream=connection.streamEvents[message.message.streamid];if(!stream||!stream.stream)return;var action=message.message.action;if("ended"===action||"stream-removed"===action)return void connection.onstreamended(stream);var type="both"!=message.message.type?message.message.type:null;return void stream.stream[action](type)}if("connectWithAllParticipants"===message.message)return-1===connection.broadcasters.indexOf(message.sender)&&connection.broadcasters.push(message.sender),void mPeer.onNegotiationNeeded({allParticipants:connection.peers.getAllParticipants(message.sender)},message.sender);if("removeFromBroadcastersList"===message.message)return void(-1!==connection.broadcasters.indexOf(message.sender)&&(delete connection.broadcasters[connection.broadcasters.indexOf(message.sender)],connection.broadcasters=removeNullEntries(connection.broadcasters)));if("dropPeerConnection"===message.message)return void(connection.peers[message.sender]&&(connection.peers[message.sender].peer.close(),connection.peers[message.sender].peer=null,delete connection.peers[message.sender]));if(message.message.allParticipants)return-1===message.message.allParticipants.indexOf(message.sender)&&message.message.allParticipants.push(message.sender),void message.message.allParticipants.forEach(function(participant){mPeer[connection.peers[participant]?"renegotiatePeer":"createNewPeer"](participant,{localPeerSdpConstraints:{OfferToReceiveAudio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.sdpConstraints.mandatory.OfferToReceiveVideo},remotePeerSdpConstraints:{OfferToReceiveAudio:connection.session.oneway?!!connection.session.audio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.session.oneway?!!connection.session.video||!!connection.session.screen:connection.sdpConstraints.mandatory.OfferToReceiveVideo
+},isOneWay:!!connection.session.oneway||"one-way"===connection.direction,isDataOnly:isData(connection.session)})});if(message.message.newParticipant){if(message.message.newParticipant==connection.userid)return;if(connection.peers[message.message.newParticipant])return;return void mPeer.createNewPeer(message.message.newParticipant,message.message.userPreferences||{localPeerSdpConstraints:{OfferToReceiveAudio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.sdpConstraints.mandatory.OfferToReceiveVideo},remotePeerSdpConstraints:{OfferToReceiveAudio:connection.session.oneway?!!connection.session.audio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.session.oneway?!!connection.session.video||!!connection.session.screen:connection.sdpConstraints.mandatory.OfferToReceiveVideo},isOneWay:!!connection.session.oneway||"one-way"===connection.direction,isDataOnly:isData(connection.session)})}if((message.message.readyForOffer||message.message.addMeAsBroadcaster)&&connection.addNewBroadcaster(message.sender),message.message.newParticipationRequest&&message.sender!==connection.userid){connection.peers[message.sender]&&(connection.peers[message.sender].peer&&(connection.peers[message.sender].peer.close(),connection.peers[message.sender].peer=null),delete connection.peers[message.sender]);var userPreferences={extra:message.extra||{},localPeerSdpConstraints:message.message.remotePeerSdpConstraints||{OfferToReceiveAudio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.sdpConstraints.mandatory.OfferToReceiveVideo},remotePeerSdpConstraints:message.message.localPeerSdpConstraints||{OfferToReceiveAudio:connection.session.oneway?!!connection.session.audio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.session.oneway?!!connection.session.video||!!connection.session.screen:connection.sdpConstraints.mandatory.OfferToReceiveVideo},isOneWay:"undefined"!=typeof message.message.isOneWay?message.message.isOneWay:!!connection.session.oneway||"one-way"===connection.direction,isDataOnly:"undefined"!=typeof message.message.isDataOnly?message.message.isDataOnly:isData(connection.session),dontGetRemoteStream:"undefined"!=typeof message.message.isOneWay?message.message.isOneWay:!!connection.session.oneway||"one-way"===connection.direction,dontAttachLocalStream:!!message.message.dontGetRemoteStream,connectionDescription:message,successCallback:function(){("undefined"!=typeof message.message.isOneWay?message.message.isOneWay:!!connection.session.oneway||"one-way"===connection.direction)&&connection.addNewBroadcaster(message.sender,userPreferences),(connection.session.oneway||"one-way"===connection.direction||isData(connection.session))&&connection.addNewBroadcaster(message.sender,userPreferences)}};return void connection.onNewParticipant(message.sender,userPreferences)}return message.message.shiftedModerationControl?void connection.onShiftedModerationControl(message.sender,message.message.broadcasters):(message.message.changedUUID&&connection.peers[message.message.oldUUID]&&(connection.peers[message.message.newUUID]=connection.peers[message.message.oldUUID],delete connection.peers[message.message.oldUUID]),message.message.userLeft?(mPeer.onUserLeft(message.sender),void(message.message.autoCloseEntireSession&&connection.leave())):void mPeer.addNegotiatedMessage(message.message,message.sender))}}),socket.on("user-left",function(userid){onUserLeft(userid),connection.onUserStatusChanged({userid:userid,status:"offline",extra:connection.peers[userid]?connection.peers[userid].extra||{}:{}}),connection.onleave({userid:userid,extra:{}})}),socket.on("connect",function(){connection.enableLogs&&console.info("socket.io connection is opened."),socket.emit("extra-data-updated",connection.extra),connectCallback&&connectCallback(socket)}),socket.on("disconnect",function(){connection.enableLogs&&(console.info("socket.io connection is closed"),console.warn("socket.io reconnecting"))}),socket.on("join-with-password",function(remoteUserId){connection.onJoinWithPassword(remoteUserId)}),socket.on("invalid-password",function(remoteUserId,oldPassword){connection.onInvalidPassword(remoteUserId,oldPassword)}),socket.on("password-max-tries-over",function(remoteUserId){connection.onPasswordMaxTriesOver(remoteUserId)}),socket.on("user-disconnected",function(remoteUserId){remoteUserId!==connection.userid&&(connection.onUserStatusChanged({userid:remoteUserId,status:"offline",extra:connection.peers[remoteUserId]?connection.peers[remoteUserId].extra||{}:{}}),connection.peers[remoteUserId]&&connection.peers[remoteUserId].peer&&(connection.peers[remoteUserId].peer.close(),delete connection.peers[remoteUserId]))}),socket.on("user-connected",function(userid){userid!==connection.userid&&connection.onUserStatusChanged({userid:userid,status:"online",extra:connection.peers[userid]?connection.peers[userid].extra||{}:{}})}),socket.on("logs",function(log){connection.enableLogs&&console.debug("server-logs",log)}),socket}function MultiPeers(connection){function initFileBufferReader(){fbr=new FileBufferReader,fbr.onProgress=function(chunk){connection.onFileProgress(chunk)},fbr.onBegin=function(file){connection.onFileStart(file)},fbr.onEnd=function(file){connection.onFileEnd(file)}}var self=this,skipPeers=["getAllParticipants","getLength","selectFirst","streams","send","forEach"];connection.peers={getLength:function(){var numberOfPeers=0;for(var peer in this)-1==skipPeers.indexOf(peer)&&numberOfPeers++;return numberOfPeers},selectFirst:function(){var firstPeer;for(var peer in this)-1==skipPeers.indexOf(peer)&&(firstPeer=this[peer]);return firstPeer},getAllParticipants:function(sender){var allPeers=[];for(var peer in this)-1==skipPeers.indexOf(peer)&&peer!=sender&&allPeers.push(peer);return allPeers},forEach:function(callbcak){this.getAllParticipants().forEach(function(participant){callbcak(connection.peers[participant])})},send:function(data,remoteUserId){var that=this;if(!isNull(data.size)&&!isNull(data.type))return void self.shareFile(data,remoteUserId);if(!("text"===data.type||data instanceof ArrayBuffer||data instanceof DataView))return void TextSender.send({text:data,channel:this,connection:connection,remoteUserId:remoteUserId});if("text"===data.type&&(data=JSON.stringify(data)),remoteUserId){var remoteUser=connection.peers[remoteUserId];if(remoteUser)return void remoteUser.channels.forEach(function(channel){channel.send(data)})}this.getAllParticipants().forEach(function(participant){that[participant].channels.forEach(function(channel){channel.send(data)})})}},this.uuid=connection.userid,this.getLocalConfig=function(remoteSdp,remoteUserId,userPreferences){return userPreferences||(userPreferences={}),{streamsToShare:userPreferences.streamsToShare||{},session:connection.session,rtcMultiConnection:connection,connectionDescription:userPreferences.connectionDescription,remoteUserId:remoteUserId,localPeerSdpConstraints:userPreferences.localPeerSdpConstraints,remotePeerSdpConstraints:userPreferences.remotePeerSdpConstraints,dontGetRemoteStream:!!userPreferences.dontGetRemoteStream,dontAttachLocalStream:!!userPreferences.dontAttachLocalStream,optionalArgument:connection.optionalArgument,iceServers:connection.iceServers,renegotiatingPeer:!!userPreferences.renegotiatingPeer,peerRef:userPreferences.peerRef,enableDataChannels:!!connection.session.data,localStreams:connection.attachStreams,removeStreams:connection.removeStreams,onLocalSdp:function(localSdp){self.onNegotiationNeeded(localSdp,remoteUserId)},onLocalCandidate:function(localCandidate){localCandidate=OnIceCandidateHandler.processCandidates(connection,localCandidate),localCandidate&&self.onNegotiationNeeded(localCandidate,remoteUserId)},remoteSdp:remoteSdp,onDataChannelMessage:function(message){if(!fbr&&connection.enableFileSharing&&initFileBufferReader(),"string"==typeof message||!connection.enableFileSharing)return void self.onDataChannelMessage(message,remoteUserId);var that=this;return message instanceof ArrayBuffer||message instanceof DataView?void fbr.convertToObject(message,function(object){that.onDataChannelMessage(object)}):message.readyForNextChunk?void fbr.getNextChunk(message.uuid,function(nextChunk,isLastChunk){connection.peers[remoteUserId].channels.forEach(function(channel){channel.send(nextChunk)})},remoteUserId):void fbr.addChunk(message,function(promptNextChunk){connection.peers[remoteUserId].peer.channel.send(promptNextChunk)})},onDataChannelError:function(error){self.onDataChannelError(error,remoteUserId)},onDataChannelOpened:function(channel){self.onDataChannelOpened(channel,remoteUserId)},onDataChannelClosed:function(event){self.onDataChannelClosed(event,remoteUserId)},onRemoteStream:function(stream){if(connection.peers[remoteUserId].streams.push(stream),isPluginRTC){var mediaElement=document.createElement("video"),body=document.body||document.documentElement;return body.insertBefore(mediaElement,body.firstChild),void setTimeout(function(){Plugin.attachMediaStream(mediaElement,stream),self.onGettingRemoteMedia(mediaElement,remoteUserId)},3e3)}self.onGettingRemoteMedia(stream,remoteUserId)},onRemoteStreamRemoved:function(stream){self.onRemovingRemoteMedia(stream,remoteUserId)},onPeerStateChanged:function(states){self.onPeerStateChanged(states),"new"===states.iceConnectionState&&self.onNegotiationStarted(remoteUserId,states),"connected"===states.iceConnectionState&&self.onNegotiationCompleted(remoteUserId,states),-1!==states.iceConnectionState.search(/closed|failed/gi)&&(self.onUserLeft(remoteUserId),self.disconnectWith(remoteUserId))},processSdp:connection.processSdp,beforeAddingStream:connection.beforeAddingStream,beforeRemovingStream:connection.beforeRemovingStream}},this.createNewPeer=function(remoteUserId,userPreferences){if(!(connection.maxParticipantsAllowed<=connection.getAllParticipants().length)){if(userPreferences=userPreferences||{},!userPreferences.isOneWay&&!userPreferences.isDataOnly)return userPreferences.isOneWay=!0,void this.onNegotiationNeeded({enableMedia:!0,userPreferences:userPreferences},remoteUserId);userPreferences=connection.setUserPreferences(userPreferences,remoteUserId);var localConfig=this.getLocalConfig(null,remoteUserId,userPreferences);connection.peers[remoteUserId]=new PeerInitiator(localConfig)}},this.createAnsweringPeer=function(remoteSdp,remoteUserId,userPreferences){userPreferences=connection.setUserPreferences(userPreferences||{},remoteUserId);var localConfig=this.getLocalConfig(remoteSdp,remoteUserId,userPreferences);connection.peers[remoteUserId]=new PeerInitiator(localConfig)},this.renegotiatePeer=function(remoteUserId,userPreferences,remoteSdp){if(!connection.peers[remoteUserId])throw"This peer ("+remoteUserId+") does not exists.";userPreferences||(userPreferences={}),userPreferences.renegotiatingPeer=!0,userPreferences.peerRef=connection.peers[remoteUserId].peer;var localConfig=this.getLocalConfig(remoteSdp,remoteUserId,userPreferences);connection.peers[remoteUserId]=new PeerInitiator(localConfig)},this.replaceTrack=function(track,remoteUserId,isVideoTrack){if(!connection.peers[remoteUserId])throw"This peer ("+remoteUserId+") does not exists.";var peer=connection.peers[remoteUserId].peer;return peer.getSenders&&"function"==typeof peer.getSenders&&peer.getSenders().length?void peer.getSenders().forEach(function(rtpSender){isVideoTrack&&rtpSender.track instanceof VideoStreamTrack&&(connection.peers[remoteUserId].peer.lastVideoTrack=rtpSender.track,rtpSender.replaceTrack(track)),!isVideoTrack&&rtpSender.track instanceof AudioStreamTrack&&(connection.peers[remoteUserId].peer.lastAudioTrack=rtpSender.track,rtpSender.replaceTrack(track))}):(console.warn("RTPSender.replaceTrack is NOT supported."),void this.renegotiatePeer(remoteUserId))},this.onNegotiationNeeded=function(message,remoteUserId){},this.addNegotiatedMessage=function(message,remoteUserId){if(message.type&&message.sdp)return"answer"==message.type&&connection.peers[remoteUserId]&&connection.peers[remoteUserId].addRemoteSdp(message),"offer"==message.type&&(message.renegotiatingPeer?this.renegotiatePeer(remoteUserId,null,message):this.createAnsweringPeer(message,remoteUserId)),void(connection.enableLogs&&console.log("Remote peer's sdp:",message.sdp));if(message.candidate)return connection.peers[remoteUserId]&&connection.peers[remoteUserId].addRemoteCandidate(message),void(connection.enableLogs&&console.log("Remote peer's candidate pairs:",message.candidate));if(message.enableMedia){if(connection.attachStreams.length){var streamsToShare={};return connection.attachStreams.forEach(function(stream){streamsToShare[stream.streamid]={isAudio:!!stream.isAudio,isVideo:!!stream.isVideo,isScreen:!!stream.isScreen}}),message.userPreferences.streamsToShare=streamsToShare,void self.onNegotiationNeeded({readyForOffer:!0,userPreferences:message.userPreferences},remoteUserId)}var localMediaConstraints={},userPreferences=message.userPreferences;userPreferences.localPeerSdpConstraints.OfferToReceiveAudio&&(localMediaConstraints.audio=connection.mediaConstraints.audio),userPreferences.localPeerSdpConstraints.OfferToReceiveVideo&&(localMediaConstraints.video=connection.mediaConstraints.video),getUserMediaHandler({onGettingLocalMedia:function(localStream){self.onGettingLocalMedia(localStream);var streamsToShare={};connection.attachStreams.forEach(function(stream){streamsToShare[stream.streamid]={isAudio:!!stream.isAudio,isVideo:!!stream.isVideo,isScreen:!!stream.isScreen}}),message.userPreferences.streamsToShare=streamsToShare,self.onNegotiationNeeded({readyForOffer:!0,userPreferences:message.userPreferences},remoteUserId)},onLocalMediaError:function(error){self.onLocalMediaError(error),self.onNegotiationNeeded({readyForOffer:!0,userPreferences:message.userPreferences},remoteUserId)},localMediaConstraints:localMediaConstraints})}message.readyForOffer&&connection.onReadyForOffer(remoteUserId,message.userPreferences)},this.onGettingRemoteMedia=function(stream,remoteUserId){},this.onRemovingRemoteMedia=function(stream,remoteUserId){},this.onGettingLocalMedia=function(localStream){},this.onLocalMediaError=function(error){connection.enableLogs&&console.error("onLocalMediaError",JSON.stringify(error,null," ")),connection.onMediaError(error)};var fbr;this.shareFile=function(file,remoteUserId){if(!connection.enableFileSharing)throw'"connection.enableFileSharing" is false.';initFileBufferReader(),fbr.readAsArrayBuffer(file,function(uuid){var arrayOfUsers=connection.getAllParticipants();remoteUserId&&(arrayOfUsers=[remoteUserId]),arrayOfUsers.forEach(function(participant){fbr.getNextChunk(uuid,function(nextChunk){connection.peers[participant].channels.forEach(function(channel){channel.send(nextChunk)})},participant)})},{userid:connection.userid,chunkSize:isFirefox?15e3:connection.chunkSize||0})};var textReceiver=new TextReceiver(connection);this.onDataChannelMessage=function(message,remoteUserId){textReceiver.receive(JSON.parse(message),remoteUserId,connection.peers[remoteUserId]?connection.peers[remoteUserId].extra:{})},this.onDataChannelClosed=function(event,remoteUserId){event.userid=remoteUserId,event.extra=connection.peers[remoteUserId]?connection.peers[remoteUserId].extra:{},connection.onclose(event)},this.onDataChannelError=function(error,remoteUserId){error.userid=remoteUserId,event.extra=connection.peers[remoteUserId]?connection.peers[remoteUserId].extra:{},connection.onerror(error)},this.onDataChannelOpened=function(channel,remoteUserId){connection.peers[remoteUserId].channels.length||(connection.peers[remoteUserId].channels.push(channel),connection.onopen({userid:remoteUserId,extra:connection.peers[remoteUserId]?connection.peers[remoteUserId].extra:{},channel:channel}),connection.observers.all())},this.onPeerStateChanged=function(state){connection.onPeerStateChanged(state)},this.onNegotiationStarted=function(remoteUserId,states){},this.onNegotiationCompleted=function(remoteUserId,states){},this.getRemoteStreams=function(remoteUserId){return remoteUserId=remoteUserId||connection.peers.getAllParticipants()[0],connection.peers[remoteUserId]?connection.peers[remoteUserId].streams:[]},this.isPluginRTC=connection.isPluginRTC=isPluginRTC}function fireEvent(obj,eventName,args){if("undefined"!=typeof CustomEvent){var eventDetail={arguments:args,__exposedProps__:args},event=new CustomEvent(eventName,eventDetail);obj.dispatchEvent(event)}}function setHarkEvents(connection,streamEvent){if(!connection||!streamEvent)throw"Both arguments are required.";if(connection.onspeaking&&connection.onsilence){if("undefined"==typeof hark)throw"hark.js not found.";hark(streamEvent.stream,{onspeaking:function(){connection.onspeaking(streamEvent)},onsilence:function(){connection.onsilence(streamEvent)},onvolumechange:function(volume,threshold){connection.onvolumechange&&connection.onvolumechange(merge({volume:volume,threshold:threshold},streamEvent))}})}}function setMuteHandlers(connection,streamEvent){streamEvent.stream.addEventListener("mute",function(event){event=connection.streamEvents[event.target.streamid],event.session={audio:"audio"===event.muteType,video:"video"===event.muteType},connection.onmute(event)},!1),streamEvent.stream.addEventListener("unmute",function(event){event=connection.streamEvents[event.target.streamid],event.session={audio:"audio"===event.unmuteType,video:"video"===event.unmuteType},connection.onunmute(event)},!1)}function getRandomString(){if(window.crypto&&window.crypto.getRandomValues&&-1===navigator.userAgent.indexOf("Safari")){for(var a=window.crypto.getRandomValues(new Uint32Array(3)),token="",i=0,l=a.length;l>i;i++)token+=a[i].toString(36);return token}return(Math.random()*(new Date).getTime()).toString(36).replace(/\./g,"")}function getRMCMediaElement(stream,callback,connection){var isAudioOnly=!1;stream.getVideoTracks().length||(isAudioOnly=!0);var mediaElement=document.createElement(isAudioOnly?"audio":"video");return isPluginRTC?(connection.videosContainer.insertBefore(mediaElement,connection.videosContainer.firstChild),void setTimeout(function(){Plugin.attachMediaStream(mediaElement,stream),callback(mediaElement)},1e3)):(mediaElement[isFirefox?"mozSrcObject":"src"]=isFirefox?stream:window.URL.createObjectURL(stream),mediaElement.controls=!0,isFirefox&&mediaElement.addEventListener("ended",function(){if(fireEvent(stream,"ended",stream),currentUserMediaRequest.remove(stream.idInstance),"local"===stream.type){StreamsHandler.onSyncNeeded(stream.streamid,"ended"),connection.attachStreams.forEach(function(aStream,idx){stream.streamid===aStream.streamid&&delete connection.attachStreams[idx]});var newStreamsArray=[];connection.attachStreams.forEach(function(aStream){aStream&&newStreamsArray.push(aStream)}),connection.attachStreams=newStreamsArray,connection.observers.all();var streamEvent=connection.streamEvents[stream.streamid];if(streamEvent)return void connection.onstreamended(streamEvent);this.parentNode&&this.parentNode.removeChild(this)}},!1),mediaElement.play(),void callback(mediaElement))}function listenEventHandler(eventName,eventHandler){window.removeEventListener(eventName,eventHandler),window.addEventListener(eventName,eventHandler,!1)}function removeNullEntries(array){var newArray=[];return array.forEach(function(item){item&&newArray.push(item)}),newArray}function isData(session){return!session.audio&&!session.video&&!session.screen&&session.data}function isNull(obj){return"undefined"==typeof obj}function isString(obj){return"string"==typeof obj}function observeObject(obj,callback){Object.observe&&Object.observe(obj,function(changes){var jsonStringified=JSON.stringify(changes);lastChanges!=jsonStringified&&(lastChanges=jsonStringified,callback(changes))})}function setSdpConstraints(config){var sdpConstraints,sdpConstraints_mandatory={OfferToReceiveAudio:!!config.OfferToReceiveAudio,OfferToReceiveVideo:!!config.OfferToReceiveVideo};return sdpConstraints={mandatory:sdpConstraints_mandatory,optional:[{VoiceActivityDetection:!1}]},navigator.mozGetUserMedia&&firefoxVersion>34&&(sdpConstraints={OfferToReceiveAudio:!!config.OfferToReceiveAudio,OfferToReceiveVideo:!!config.OfferToReceiveVideo}),sdpConstraints}function onPluginRTCInitialized(pluginRTCObject){Plugin=pluginRTCObject,MediaStreamTrack=Plugin.MediaStreamTrack,RTCPeerConnection=Plugin.RTCPeerConnection,RTCIceCandidate=Plugin.RTCIceCandidate,RTCSessionDescription=Plugin.RTCSessionDescription}function PeerInitiator(config){function createDataChannel(){if(!isOfferer)return void(peer.ondatachannel=function(event){var channel=event.channel;setChannelEvents(channel)});var channel=peer.createDataChannel("RTCDataChannel",{});setChannelEvents(channel)}function setChannelEvents(channel){channel.binaryType="arraybuffer",channel.onmessage=function(event){config.onDataChannelMessage(event.data)},channel.onopen=function(){config.onDataChannelOpened(channel)},channel.onerror=function(error){config.onDataChannelError(error)},channel.onclose=function(event){config.onDataChannelClosed(event)},channel.internalSend=channel.send,channel.send=function(data){"open"===channel.readyState&&channel.internalSend(data)},peer.channel=channel}var connection=config.rtcMultiConnection;this.extra=config.remoteSdp?config.remoteSdp.extra:connection.extra,this.remoteUserId=config.remoteUserId,this.streams=[],this.channels=[],this.connectionDescription=config.connectionDescription;var that=this;config.remoteSdp&&(this.connectionDescription=config.remoteSdp.connectionDescription);var allRemoteStreams={};if(Object.observe){var that=this;Object.observe(this.channels,function(changes){changes.forEach(function(change){"add"===change.type&&change.object[change.name].addEventListener("close",function(){delete that.channels[that.channels.indexOf(change.object[change.name])],that.channels=removeNullEntries(that.channels)},!1),("remove"===change.type||"delete"===change.type)&&-1!==that.channels.indexOf(change.object[change.name])&&delete that.channels.indexOf(change.object[change.name]),that.channels=removeNullEntries(that.channels)})})}defaults.sdpConstraints=setSdpConstraints({OfferToReceiveAudio:!0,OfferToReceiveVideo:!0});var peer,renegotiatingPeer=!!config.renegotiatingPeer;config.remoteSdp&&(renegotiatingPeer=!!config.remoteSdp.renegotiatingPeer);var localStreams=[];config.localStreams.forEach(function(stream){stream&&localStreams.push(stream)}),renegotiatingPeer?(peer=config.peerRef,peer.getLocalStreams().forEach(function(stream){localStreams.forEach(function(localStream,index){stream==localStream&&delete localStreams[index]}),config.removeStreams.forEach(function(streamToRemove,index){stream===streamToRemove&&(stream=config.beforeRemovingStream(stream),stream&&peer.removeStream&&peer.removeStream(stream),localStreams.forEach(function(localStream,index){streamToRemove==localStream&&delete localStreams[index]}))})})):peer=new RTCPeerConnection(navigator.onLine?{iceServers:config.iceServers,iceTransports:"all"}:null,config.optionalArgument),"Firefox"===connection.DetectRTC.browser.name&&(peer.removeStream=function(stream){stream.mute(),connection.StreamsHandler.onSyncNeeded(stream.streamid,"stream-removed")}),peer.onicecandidate=function(event){event.candidate&&config.onLocalCandidate({candidate:event.candidate.candidate,sdpMid:event.candidate.sdpMid,sdpMLineIndex:event.candidate.sdpMLineIndex})};var isFirefoxOffered=!isFirefox;config.remoteSdp&&config.remoteSdp.remotePeerSdpConstraints&&config.remoteSdp.remotePeerSdpConstraints.isFirefoxOffered&&(isFirefoxOffered=!0),localStreams.forEach(function(localStream){config.remoteSdp&&config.remoteSdp.remotePeerSdpConstraints&&config.remoteSdp.remotePeerSdpConstraints.dontGetRemoteStream||config.dontAttachLocalStream||(localStream=config.beforeAddingStream(localStream),localStream&&peer.addStream(localStream))}),peer.oniceconnectionstatechange=peer.onsignalingstatechange=function(){var extra=that.extra;if(connection.peers[that.remoteUserId]&&(extra=connection.peers[that.remoteUserId].extra||extra),!peer)return void that.removeAllRemoteStreams();if(-1!==peer.iceConnectionState.search(/closed|failed/gi)){if(peer.firedOnce)return;if(peer.firedOnce=!0,that.removeAllRemoteStreams(),that.connectionDescription&&connection.userid==that.connectionDescription.sender&&connection.autoReDialOnFailure){if(connection.isInitiator)return;setTimeout(function(){connection.rejoin(that.connectionDescription),peer&&(peer.firedOnce=!1)},5e3)}}config.onPeerStateChanged({iceConnectionState:peer.iceConnectionState,iceGatheringState:peer.iceGatheringState,signalingState:peer.signalingState,extra:extra,userid:that.remoteUserId})};var sdpConstraints={OfferToReceiveAudio:!!localStreams.length,OfferToReceiveVideo:!!localStreams.length};config.localPeerSdpConstraints&&(sdpConstraints=config.localPeerSdpConstraints),defaults.sdpConstraints=setSdpConstraints(sdpConstraints),peer.onaddstream=function(event){var streamsToShare={};config.remoteSdp&&config.remoteSdp.streamsToShare?streamsToShare=config.remoteSdp.streamsToShare:config.streamsToShare&&(streamsToShare=config.streamsToShare);var streamToShare=streamsToShare[event.stream.id];streamToShare&&(event.stream.isAudio=streamToShare.isAudio,event.stream.isVideo=streamToShare.isVideo,event.stream.isScreen=streamToShare.isScreen),event.stream.streamid=event.stream.id,event.stream.stop||(event.stream.stop=function(){fireEvent(event.stream,"ended",event)}),allRemoteStreams[event.stream.id]=event.stream,config.onRemoteStream(event.stream)},peer.onremovestream=function(event){event.stream.streamid=event.stream.id,allRemoteStreams[event.stream.id]&&delete allRemoteStreams[event.stream.id],config.onRemoteStreamRemoved(event.stream)},this.addRemoteCandidate=function(remoteCandidate){peer.addIceCandidate(new RTCIceCandidate(remoteCandidate))},this.addRemoteSdp=function(remoteSdp){peer.setRemoteDescription(new RTCSessionDescription(remoteSdp),function(){},function(error){connection.enableLogs&&console.error(JSON.stringify(error,null," ")),connection.autoReDialOnFailure&&setTimeout(function(){connection.rejoin(that.connectionDescription)},2e3)})};var isOfferer=!0;config.remoteSdp&&(isOfferer=!1),config.enableDataChannels===!0&&createDataChannel(),config.remoteSdp&&(config.remoteSdp.remotePeerSdpConstraints&&(sdpConstraints=config.remoteSdp.remotePeerSdpConstraints),defaults.sdpConstraints=setSdpConstraints(sdpConstraints),this.addRemoteSdp(config.remoteSdp)),("two-way"==config.session.audio||"two-way"==config.session.video||"two-way"==config.session.screen)&&(defaults.sdpConstraints=setSdpConstraints({OfferToReceiveAudio:"two-way"==config.session.audio||config.remoteSdp&&config.remoteSdp.remotePeerSdpConstraints&&config.remoteSdp.remotePeerSdpConstraints.OfferToReceiveAudio,OfferToReceiveVideo:"two-way"==config.session.video||"two-way"==config.session.screen||config.remoteSdp&&config.remoteSdp.remotePeerSdpConstraints&&config.remoteSdp.remotePeerSdpConstraints.OfferToReceiveAudio}));var streamsToShare={};peer.getLocalStreams().forEach(function(stream){streamsToShare[stream.streamid]={isAudio:!!stream.isAudio,isVideo:!!stream.isVideo,isScreen:!!stream.isScreen}}),peer[isOfferer?"createOffer":"createAnswer"](function(localSdp){localSdp.sdp=config.processSdp(localSdp.sdp),peer.setLocalDescription(localSdp),config.onLocalSdp({type:localSdp.type,sdp:localSdp.sdp,remotePeerSdpConstraints:config.remotePeerSdpConstraints||!1,renegotiatingPeer:!!config.renegotiatingPeer||!1,connectionDescription:that.connectionDescription,dontGetRemoteStream:!!config.dontGetRemoteStream,extra:connection?connection.extra:{},streamsToShare:streamsToShare,isFirefoxOffered:isFirefox})},function(error){connection.enableLogs&&console.error("sdp-error",error),connection.autoReDialOnFailure&&connection.isInitiator&&isFirefox&&isFirefoxOffered&&setTimeout(function(){connection.rejoin(that.connectionDescription)},5e3)},defaults.sdpConstraints),peer.nativeClose=peer.close,peer.close=function(){if(!peer)return void that.removeAllRemoteStreams();connection.multiPeersHandler.onNegotiationNeeded({userLeft:!0,autoCloseEntireSession:!!connection.autoCloseEntireSession},that.remoteUserId);try{-1===peer.iceConnectionState.search(/closed|failed/gi)&&peer.getRemoteStreams().forEach(function(stream){stream.stop()}),peer.nativeClose()}catch(e){}peer=null},this.removeAllRemoteStreams=function(){for(var id in allRemoteStreams)config.onRemoteStreamRemoved(allRemoteStreams[id]);allRemoteStreams={},that.streams.forEach(function(stream){stream.stop()}),that.streams=[]},this.peer=peer}function loadIceFrame(callback,skip){if(!loadedIceFrame){if(!skip)return loadIceFrame(callback,!0);loadedIceFrame=!0;var iframe=document.createElement("iframe");iframe.onload=function(){function iFrameLoaderCallback(event){event.data&&event.data.iceServers&&(callback(event.data.iceServers),window.removeEventListener("message",iFrameLoaderCallback))}iframe.isLoaded=!0,listenEventHandler("message",iFrameLoaderCallback),iframe.contentWindow.postMessage("get-ice-servers","*")},iframe.src="https://cdn.webrtc-experiment.com/getIceServers/",iframe.style.display="none",(document.body||document.documentElement).appendChild(iframe)}}function requestUserMedia(constraints){return new Promise(function(resolve,reject){getUserMedia(constraints,resolve,reject)})}function setStreamType(constraints,stream){constraints.mandatory&&constraints.mandatory.chromeMediaSource?stream.isScreen=!0:constraints.mozMediaSource||constraints.mediaSource?stream.isScreen=!0:constraints.video?stream.isVideo=!0:constraints.audio&&(stream.isAudio=!0)}function getUserMediaHandler(options){function streaming(stream,returnBack){setStreamType(options.localMediaConstraints,stream),options.onGettingLocalMedia(stream,returnBack),stream.addEventListener("ended",function(){delete currentUserMediaRequest.streams[idInstance],currentUserMediaRequest.mutex=!1,currentUserMediaRequest.queueRequests.indexOf(options)&&(delete currentUserMediaRequest.queueRequests[currentUserMediaRequest.queueRequests.indexOf(options)],currentUserMediaRequest.queueRequests=removeNullEntries(currentUserMediaRequest.queueRequests))},!1),currentUserMediaRequest.streams[idInstance]={stream:stream},currentUserMediaRequest.mutex=!1,currentUserMediaRequest.queueRequests.length&&getUserMediaHandler(currentUserMediaRequest.queueRequests.shift())}if(currentUserMediaRequest.mutex===!0)return void currentUserMediaRequest.queueRequests.push(options);currentUserMediaRequest.mutex=!0;var idInstance=JSON.stringify(options.localMediaConstraints);if(currentUserMediaRequest.streams[idInstance])streaming(currentUserMediaRequest.streams[idInstance].stream,!0);else{if(isPluginRTC){document.createElement("video");return void Plugin.getUserMedia({audio:!0,video:!0},function(stream){stream.streamid=stream.id||getRandomString(),streaming(stream)},function(error){})}"undefined"!=typeof DetectRTC&&(DetectRTC.hasMicrophone||(options.localMediaConstraints.audio=!1),DetectRTC.hasWebcam||(options.localMediaConstraints.video=!1)),navigator.mediaDevices.getUserMedia(options.localMediaConstraints).then(function(stream){stream.streamid=stream.streamid||stream.id||getRandomString(),stream.idInstance=idInstance,streaming(stream)})["catch"](function(error){options.onLocalMediaError(error,options.localMediaConstraints)})}}function TextReceiver(connection){function receive(data,userid,extra){var uuid=data.uuid;if(content[uuid]||(content[uuid]=[]),content[uuid].push(data.message),data.last){var message=content[uuid].join("");data.isobject&&(message=JSON.parse(message));var receivingTime=(new Date).getTime(),latency=receivingTime-data.sendingTime,e={data:message,userid:userid,extra:extra,latency:latency};connection.autoTranslateText?(e.original=e.data,connection.Translator.TranslateText(e.data,function(translatedText){e.data=translatedText,connection.onmessage(e)})):connection.onmessage(e),delete content[uuid]}}var content={};return{receive:receive}}var isOpera=!!window.opera||navigator.userAgent.indexOf(" OPR/")>=0,isFirefox="undefined"!=typeof window.InstallTrigger,isSafari=Object.prototype.toString.call(window.HTMLElement).indexOf("Constructor")>0,isChrome=!!window.chrome&&!isOpera,isIE=!!document.documentMode,isPluginRTC=isSafari||isIE,chromeVersion=(!!navigator.userAgent.match(/Android|iPhone|iPad|iPod|BlackBerry|IEMobile/i),
!!(window.process&&"object"==typeof window.process&&window.process.versions&&window.process.versions["node-webkit"]),50),matchArray=navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./);isChrome&&matchArray&&matchArray[2]&&(chromeVersion=parseInt(matchArray[2],10));var firefoxVersion=50;matchArray=navigator.userAgent.match(/Firefox\/(.*)/),isFirefox&&matchArray&&matchArray[1]&&(firefoxVersion=parseInt(matchArray[1],10)),window.addEventListener||(window.addEventListener=function(el,eventName,eventHandler){el.attachEvent&&el.attachEvent("on"+eventName,eventHandler)}),window.attachEventListener=function(video,type,listener,useCapture){video.addEventListener(type,listener,useCapture)};var MediaStream=window.MediaStream;"undefined"==typeof MediaStream&&"undefined"!=typeof webkitMediaStream&&(MediaStream=webkitMediaStream),"undefined"==typeof MediaStream||"stop"in MediaStream.prototype||(MediaStream.prototype.stop=function(){this.getAudioTracks().forEach(function(track){track.stop()}),this.getVideoTracks().forEach(function(track){track.stop()}),fireEvent(this,"ended")}),"undefined"!=typeof MediaStream&&("getAudioTracks"in MediaStream.prototype&&"function"==typeof MediaStream.prototype.getAudioTracks||(MediaStream.prototype.getAudioTracks=function(){}),"getVideoTracks"in MediaStream.prototype&&"function"==typeof MediaStream.prototype.getVideoTracks||(MediaStream.prototype.getVideoTracks=function(){}));var lastChanges="";!function(){function LoadPluginRTC(){function getPlugin(){return document.getElementById("WebrtcEverywherePluginId")}window.PluginRTC={};var extractPluginObj=function(elt){return elt.isWebRtcPlugin?elt:elt.pluginObj},attachEventListener=function(elt,type,listener,useCapture){var _pluginObj=extractPluginObj(elt);_pluginObj?_pluginObj.bindEventListener(type,listener,useCapture):"undefined"!=typeof elt.addEventListener?elt.addEventListener(type,listener,useCapture):"undefined"!=typeof elt.addEvent&&elt.addEventListener("on"+type,listener,useCapture)},installPlugin=function(){if(!document.getElementById("WebrtcEverywherePluginId")){var pluginObj=document.createElement("object");isIE?pluginObj.setAttribute("classid","CLSID:7FD49E23-C8D7-4C4F-93A1-F7EACFA1EC53"):pluginObj.setAttribute("type","application/webrtc-everywhere"),pluginObj.setAttribute("id","WebrtcEverywherePluginId"),(document.body||document.documentElement).appendChild(pluginObj),pluginObj.setAttribute("width","0"),pluginObj.setAttribute("height","0")}};document.body?installPlugin():(attachEventListener(window,"load",function(){installPlugin()}),attachEventListener(document,"readystatechange",function(){"complete"==document.readyState&&installPlugin()}));var getUserMediaDelayed;window.PluginRTC.getUserMedia=navigator.getUserMedia=function(constraints,successCallback,errorCallback){"complete"!==document.readyState?getUserMediaDelayed||(getUserMediaDelayed=!0,attachEventListener(document,"readystatechange",function(){getUserMediaDelayed&&"complete"==document.readyState&&(getUserMediaDelayed=!1,getPlugin().getUserMedia(constraints,successCallback,errorCallback))})):getPlugin().getUserMedia(constraints,successCallback,errorCallback)},window.PluginRTC.attachMediaStream=function(element,stream){if(element.isWebRtcPlugin)return element.src=stream,element;if("video"===element.nodeName.toLowerCase()){if(!element.pluginObj&&stream){var _pluginObj=document.createElement("object"),_isIE=Object.getOwnPropertyDescriptor&&Object.getOwnPropertyDescriptor(window,"ActiveXObject")||"ActiveXObject"in window;_isIE?_pluginObj.setAttribute("classid","CLSID:7FD49E23-C8D7-4C4F-93A1-F7EACFA1EC53"):_pluginObj.setAttribute("type","application/webrtc-everywhere"),element.pluginObj=_pluginObj,_pluginObj.setAttribute("className",element.className),_pluginObj.setAttribute("innerHTML",element.innerHTML);var width=element.getAttribute("width"),height=element.getAttribute("height"),bounds=element.getBoundingClientRect();if(width||(width=bounds.right-bounds.left),height||(height=bounds.bottom-bounds.top),"getComputedStyle"in window){var computedStyle=window.getComputedStyle(element,null);width||"auto"==computedStyle.width||"0px"==computedStyle.width||(width=computedStyle.width),height||"auto"==computedStyle.height||"0px"==computedStyle.height||(height=computedStyle.height)}width?_pluginObj.setAttribute("width",width):_pluginObj.setAttribute("autowidth",!0),height?_pluginObj.setAttribute("height",height):_pluginObj.setAttribute("autoheight",!0),(document.body||document.documentElement).appendChild(_pluginObj),element.parentNode&&(element.parentNode.replaceChild(_pluginObj,element),document.body.appendChild(element),element.style.visibility="hidden")}return element.pluginObj&&(element.pluginObj.bindEventListener("play",function(objvid){element.pluginObj&&(element.pluginObj.getAttribute("autowidth")&&objvid.videoWidth&&element.pluginObj.setAttribute("width",objvid.videoWidth),element.pluginObj.getAttribute("autoheight")&&objvid.videoHeight&&element.pluginObj.setAttribute("height",objvid.videoHeight))}),element.pluginObj.src=stream),element.pluginObj}return"audio"===element.nodeName.toLowerCase()?element:void 0},window.PluginRTC.MediaStreamTrack={};var getSourcesDelayed;window.PluginRTC.MediaStreamTrack.getSources=function(gotSources){"complete"!==document.readyState?getSourcesDelayed||(getSourcesDelayed=!0,attachEventListener(document,"readystatechange",function(){getSourcesDelayed&&"complete"==document.readyState&&(getSourcesDelayed=!1,getPlugin().getSources(gotSources))})):getPlugin().getSources(gotSources)},window.PluginRTC.RTCPeerConnection=function(configuration,constraints){return getPlugin().createPeerConnection(configuration,constraints)},window.PluginRTC.RTCIceCandidate=function(RTCIceCandidateInit){return getPlugin().createIceCandidate(RTCIceCandidateInit)},window.PluginRTC.RTCSessionDescription=function(RTCSessionDescriptionInit){return getPlugin().createSessionDescription(RTCSessionDescriptionInit)},window.onPluginRTCInitialized&&window.onPluginRTCInitialized(window.PluginRTC)}var ua=navigator.userAgent.toLowerCase(),isSafari=-1!=ua.indexOf("safari")&&-1==ua.indexOf("chrome"),isIE=!!(Object.getOwnPropertyDescriptor&&Object.getOwnPropertyDescriptor(window,"ActiveXObject")||"ActiveXObject"in window);(isSafari||isIE)&&window.addEventListener("load",LoadPluginRTC,!1)}();var RTCPeerConnection,defaults={};"undefined"!=typeof mozRTCPeerConnection?RTCPeerConnection=mozRTCPeerConnection:"undefined"!=typeof webkitRTCPeerConnection?RTCPeerConnection=webkitRTCPeerConnection:"undefined"!=typeof window.RTCPeerConnection?RTCPeerConnection=window.RTCPeerConnection:(console.error("WebRTC 1.0 (RTCPeerConnection) API are NOT available in this browser."),RTCPeerConnection=window.RTCSessionDescription=window.RTCIceCandidate=function(){});var RTCSessionDescription=window.RTCSessionDescription||window.mozRTCSessionDescription,RTCIceCandidate=window.RTCIceCandidate||window.mozRTCIceCandidate,MediaStreamTrack=window.MediaStreamTrack,Plugin={};"undefined"!=typeof PluginRTC&&onPluginRTCInitialized(PluginRTC);var loadedIceFrame,isSafari=Object.prototype.toString.call(window.HTMLElement).indexOf("Constructor")>0,isIE=!!document.documentMode,isPluginRTC=isSafari||isIE,OnIceCandidateHandler=function(){function processCandidates(connection,icePair){var candidate=icePair.candidate,iceRestrictions=connection.candidates,stun=iceRestrictions.stun,turn=iceRestrictions.turn;if(isNull(iceRestrictions.reflexive)||(stun=iceRestrictions.reflexive),isNull(iceRestrictions.relay)||(turn=iceRestrictions.relay),(iceRestrictions.host||!candidate.match(/typ host/g))&&(turn||!candidate.match(/typ relay/g))&&(stun||!candidate.match(/typ srflx/g))){var protocol=connection.iceProtocols;if((protocol.udp||!candidate.match(/ udp /g))&&(protocol.tcp||!candidate.match(/ tcp /g)))return connection.enableLogs&&console.debug("Your candidate pairs:",candidate),{candidate:candidate,sdpMid:icePair.sdpMid,sdpMLineIndex:icePair.sdpMLineIndex}}}return{processCandidates:processCandidates}}();("undefined"==typeof window.getExternalIceServers||1==window.getExternalIceServers)&&loadIceFrame(function(externalIceServers){externalIceServers&&externalIceServers.length&&(window.RMCExternalIceServers=externalIceServers,window.iceServersLoadCallback&&"function"==typeof window.iceServersLoadCallback&&window.iceServersLoadCallback(externalIceServers))});var IceServersHandler=function(){function getIceServers(connection){var iceServers=[];return iceServers.push({urls:"stun:stun.l.google.com:19302"}),iceServers.push({urls:"stun:stun.anyfirewall.com:3478"}),iceServers.push({urls:"turn:turn.bistri.com:80",credential:"homeo",username:"homeo"}),iceServers.push({urls:"turn:turn.anyfirewall.com:443?transport=tcp",credential:"webrtc",username:"webrtc"}),window.RMCExternalIceServers?(iceServers=window.RMCExternalIceServers.concat(iceServers),connection.iceServers=iceServers):"undefined"==typeof window.getExternalIceServers||1==window.getExternalIceServers?window.iceServersLoadCallback=function(){iceServers=window.RMCExternalIceServers.concat(iceServers),connection.iceServers=iceServers}:iceServers.push({urls:"turn:turn.anyfirewall.com:443?transport=udp",credential:"webrtc",username:"webrtc"}),iceServers}return{getIceServers:getIceServers}}(),BandwidthHandler=function(){function setBAS(sdp,bandwidth,isScreen){return bandwidth?"undefined"!=typeof isFirefox&&isFirefox?sdp:(isScreen&&(bandwidth.screen?bandwidth.screen<300&&console.warn("It seems that you are using wrong bandwidth value for screen. Screen sharing is expected to fail."):console.warn("It seems that you are not using bandwidth for screen. Screen sharing is expected to fail.")),bandwidth.screen&&isScreen&&(sdp=sdp.replace(/b=AS([^\r\n]+\r\n)/g,""),sdp=sdp.replace(/a=mid:video\r\n/g,"a=mid:video\r\nb=AS:"+bandwidth.screen+"\r\n")),(bandwidth.audio||bandwidth.video||bandwidth.data)&&(sdp=sdp.replace(/b=AS([^\r\n]+\r\n)/g,"")),bandwidth.audio&&(sdp=sdp.replace(/a=mid:audio\r\n/g,"a=mid:audio\r\nb=AS:"+bandwidth.audio+"\r\n")),bandwidth.video&&(sdp=sdp.replace(/a=mid:video\r\n/g,"a=mid:video\r\nb=AS:"+(isScreen?bandwidth.screen:bandwidth.video)+"\r\n")),sdp):sdp}function findLine(sdpLines,prefix,substr){return findLineInRange(sdpLines,0,-1,prefix,substr)}function findLineInRange(sdpLines,startLine,endLine,prefix,substr){for(var realEndLine=-1!==endLine?endLine:sdpLines.length,i=startLine;realEndLine>i;++i)if(0===sdpLines[i].indexOf(prefix)&&(!substr||-1!==sdpLines[i].toLowerCase().indexOf(substr.toLowerCase())))return i;return null}function getCodecPayloadType(sdpLine){var pattern=new RegExp("a=rtpmap:(\\d+) \\w+\\/\\d+"),result=sdpLine.match(pattern);return result&&2===result.length?result[1]:null}function setVideoBitrates(sdp,params){params=params||{};var vp8Payload,xgoogle_min_bitrate=params.min,xgoogle_max_bitrate=params.max,sdpLines=sdp.split("\r\n"),vp8Index=findLine(sdpLines,"a=rtpmap","VP8/90000");if(vp8Index&&(vp8Payload=getCodecPayloadType(sdpLines[vp8Index])),!vp8Payload)return sdp;var rtxPayload,rtxIndex=findLine(sdpLines,"a=rtpmap","rtx/90000");if(rtxIndex&&(rtxPayload=getCodecPayloadType(sdpLines[rtxIndex])),!rtxIndex)return sdp;var rtxFmtpLineIndex=findLine(sdpLines,"a=fmtp:"+rtxPayload.toString());if(null!==rtxFmtpLineIndex){var appendrtxNext="\r\n";appendrtxNext+="a=fmtp:"+vp8Payload+" x-google-min-bitrate="+(xgoogle_min_bitrate||"228")+"; x-google-max-bitrate="+(xgoogle_max_bitrate||"228"),sdpLines[rtxFmtpLineIndex]=sdpLines[rtxFmtpLineIndex].concat(appendrtxNext),sdp=sdpLines.join("\r\n")}return sdp}function setOpusAttributes(sdp,params){params=params||{};var opusPayload,sdpLines=sdp.split("\r\n"),opusIndex=findLine(sdpLines,"a=rtpmap","opus/48000");if(opusIndex&&(opusPayload=getCodecPayloadType(sdpLines[opusIndex])),!opusPayload)return sdp;var opusFmtpLineIndex=findLine(sdpLines,"a=fmtp:"+opusPayload.toString());if(null===opusFmtpLineIndex)return sdp;var appendOpusNext="";return appendOpusNext+="; stereo="+("undefined"!=typeof params.stereo?params.stereo:"1"),appendOpusNext+="; sprop-stereo="+("undefined"!=typeof params["sprop-stereo"]?params["sprop-stereo"]:"1"),"undefined"!=typeof params.maxaveragebitrate&&(appendOpusNext+="; maxaveragebitrate="+(params.maxaveragebitrate||1048576)),"undefined"!=typeof params.maxplaybackrate&&(appendOpusNext+="; maxplaybackrate="+(params.maxplaybackrate||1048576)),"undefined"!=typeof params.cbr&&(appendOpusNext+="; cbr="+("undefined"!=typeof params.cbr?params.cbr:"1")),"undefined"!=typeof params.useinbandfec&&(appendOpusNext+="; useinbandfec="+params.useinbandfec),"undefined"!=typeof params.usedtx&&(appendOpusNext+="; usedtx="+params.usedtx),"undefined"!=typeof params.maxptime&&(appendOpusNext+="\r\na=maxptime:"+params.maxptime),sdpLines[opusFmtpLineIndex]=sdpLines[opusFmtpLineIndex].concat(appendOpusNext),sdp=sdpLines.join("\r\n")}return{setApplicationSpecificBandwidth:function(sdp,bandwidth,isScreen){return setBAS(sdp,bandwidth,isScreen)},setVideoBitrates:function(sdp,params){return setVideoBitrates(sdp,params)},setOpusAttributes:function(sdp,params){return setOpusAttributes(sdp,params)}}}(),getUserMedia=null,webrtcDetectedBrowser=null,webrtcDetectedVersion=null,webrtcMinimumVersion=null,webrtcUtils=window.webrtcUtils||{};if(webrtcUtils.enableLogs||(webrtcUtils.enableLogs=!0),webrtcUtils.log||(webrtcUtils.log=function(){webrtcUtils.enableLogs&&("undefined"!=typeof module||"function"==typeof require&&"function"==typeof define||console.log.apply(console,arguments))}),webrtcUtils.extractVersion||(webrtcUtils.extractVersion=function(uastring,expr,pos){var match=uastring.match(expr);return match&&match.length>=pos&&parseInt(match[pos],10)}),"object"==typeof window&&(!window.HTMLMediaElement||"srcObject"in window.HTMLMediaElement.prototype||Object.defineProperty(window.HTMLMediaElement.prototype,"srcObject",{get:function(){return"mozSrcObject"in this?this.mozSrcObject:this._srcObject},set:function(stream){"mozSrcObject"in this?this.mozSrcObject=stream:(this._srcObject=stream,this.src=stream?URL.createObjectURL(stream):null)}}),getUserMedia=window.navigator&&window.navigator.getUserMedia),"undefined"!=typeof window&&window.navigator)if(navigator.mozGetUserMedia&&window.mozRTCPeerConnection){if(webrtcDetectedBrowser="firefox",webrtcDetectedVersion=webrtcUtils.extractVersion(navigator.userAgent,/Firefox\/([0-9]+)\./,1),webrtcMinimumVersion=31,getUserMedia=function(constraints,onSuccess,onError){var constraintsToFF37=function(c){if("object"!=typeof c||c.require)return c;var require=[];return Object.keys(c).forEach(function(key){if("require"!==key&&"advanced"!==key&&"mediaSource"!==key){var r=c[key]="object"==typeof c[key]?c[key]:{ideal:c[key]};if((void 0!==r.min||void 0!==r.max||void 0!==r.exact)&&require.push(key),void 0!==r.exact&&("number"==typeof r.exact?r.min=r.max=r.exact:c[key]=r.exact,delete r.exact),void 0!==r.ideal){c.advanced=c.advanced||[];var oc={};"number"==typeof r.ideal?oc[key]={min:r.ideal,max:r.ideal}:oc[key]=r.ideal,c.advanced.push(oc),delete r.ideal,Object.keys(r).length||delete c[key]}}}),require.length&&(c.require=require),c};return 38>webrtcDetectedVersion&&(webrtcUtils.log("spec: "+JSON.stringify(constraints)),constraints.audio&&(constraints.audio=constraintsToFF37(constraints.audio)),constraints.video&&(constraints.video=constraintsToFF37(constraints.video)),webrtcUtils.log("ff37: "+JSON.stringify(constraints))),navigator.mozGetUserMedia(constraints,onSuccess,onError)},navigator.getUserMedia=getUserMedia,navigator.mediaDevices||(navigator.mediaDevices={getUserMedia:requestUserMedia,addEventListener:function(){},removeEventListener:function(){}}),navigator.mediaDevices.enumerateDevices=navigator.mediaDevices.enumerateDevices||function(){return new Promise(function(resolve){var infos=[{kind:"audioinput",deviceId:"default",label:"",groupId:""},{kind:"videoinput",deviceId:"default",label:"",groupId:""}];resolve(infos)})},41>webrtcDetectedVersion){var orgEnumerateDevices=navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices);navigator.mediaDevices.enumerateDevices=function(){return orgEnumerateDevices().then(void 0,function(e){if("NotFoundError"===e.name)return[];throw e})}}}else if(navigator.webkitGetUserMedia&&window.webkitRTCPeerConnection){webrtcDetectedBrowser="chrome",webrtcDetectedVersion=webrtcUtils.extractVersion(navigator.userAgent,/Chrom(e|ium)\/([0-9]+)\./,2),webrtcMinimumVersion=38;var constraintsToChrome=function(c){if("object"!=typeof c||c.mandatory||c.optional)return c;var cc={};return Object.keys(c).forEach(function(key){if("require"!==key&&"advanced"!==key&&"mediaSource"!==key){var r="object"==typeof c[key]?c[key]:{ideal:c[key]};void 0!==r.exact&&"number"==typeof r.exact&&(r.min=r.max=r.exact);var oldname=function(prefix,name){return prefix?prefix+name.charAt(0).toUpperCase()+name.slice(1):"deviceId"===name?"sourceId":name};if(void 0!==r.ideal){cc.optional=cc.optional||[];var oc={};"number"==typeof r.ideal?(oc[oldname("min",key)]=r.ideal,cc.optional.push(oc),oc={},oc[oldname("max",key)]=r.ideal,cc.optional.push(oc)):(oc[oldname("",key)]=r.ideal,cc.optional.push(oc))}void 0!==r.exact&&"number"!=typeof r.exact?(cc.mandatory=cc.mandatory||{},cc.mandatory[oldname("",key)]=r.exact):["min","max"].forEach(function(mix){void 0!==r[mix]&&(cc.mandatory=cc.mandatory||{},cc.mandatory[oldname(mix,key)]=r[mix])})}}),c.advanced&&(cc.optional=(cc.optional||[]).concat(c.advanced)),cc};if(getUserMedia=function(constraints,onSuccess,onError){return constraints.audio&&(constraints.audio=constraintsToChrome(constraints.audio)),constraints.video&&(constraints.video=constraintsToChrome(constraints.video)),webrtcUtils.log("chrome: "+JSON.stringify(constraints)),navigator.webkitGetUserMedia(constraints,onSuccess,onError)},navigator.getUserMedia=getUserMedia,navigator.mediaDevices||(navigator.mediaDevices={getUserMedia:requestUserMedia}),navigator.mediaDevices.getUserMedia){var origGetUserMedia=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getUserMedia=function(c){return webrtcUtils.log("spec: "+JSON.stringify(c)),c.audio=constraintsToChrome(c.audio),c.video=constraintsToChrome(c.video),webrtcUtils.log("chrome: "+JSON.stringify(c)),origGetUserMedia(c)}}else navigator.mediaDevices.getUserMedia=function(constraints){return requestUserMedia(constraints)};"undefined"==typeof navigator.mediaDevices.addEventListener&&(navigator.mediaDevices.addEventListener=function(){webrtcUtils.log("Dummy mediaDevices.addEventListener called.")}),"undefined"==typeof navigator.mediaDevices.removeEventListener&&(navigator.mediaDevices.removeEventListener=function(){webrtcUtils.log("Dummy mediaDevices.removeEventListener called.")})}else navigator.mediaDevices&&navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)?(webrtcUtils.log("This appears to be Edge"),webrtcDetectedBrowser="edge",webrtcDetectedVersion=webrtcUtils.extractVersion(navigator.userAgent,/Edge\/(\d+).(\d+)$/,2),webrtcMinimumVersion=12):webrtcUtils.log("Browser does not appear to be WebRTC-capable");else webrtcDetectedBrowser="not a browser";"undefined"!=typeof module?module.exports={getUserMedia:getUserMedia,webrtcDetectedBrowser:webrtcDetectedBrowser,webrtcDetectedVersion:webrtcDetectedVersion,webrtcMinimumVersion:webrtcMinimumVersion,webrtcUtils:webrtcUtils}:"function"==typeof require&&"function"==typeof define&&define([],function(){return{getUserMedia:getUserMedia,webrtcDetectedBrowser:webrtcDetectedBrowser,webrtcDetectedVersion:webrtcDetectedVersion,webrtcMinimumVersion:webrtcMinimumVersion,webrtcUtils:webrtcUtils}}),"undefined"!=typeof webrtcUtils&&(webrtcUtils.enableLogs=!1);var currentUserMediaRequest={streams:[],mutex:!1,queueRequests:[],remove:function(idInstance){this.mutex=!1;var stream=this.streams[idInstance];if(stream){stream=stream.stream;var options=stream.currentUserMediaRequestOptions;this.queueRequests.indexOf(options)&&(delete this.queueRequests[this.queueRequests.indexOf(options)],this.queueRequests=removeNullEntries(this.queueRequests)),this.streams[idInstance].stream=null,delete this.streams[idInstance]}}},StreamsHandler=function(){function handleType(type){return type?"string"==typeof type||"undefined"==typeof type?type:type.audio&&type.video?null:type.audio?"audio":type.video?"video":void 0:void 0}function setHandlers(stream,syncAction,connection){function graduallyIncreaseVolume(){if(connection.streamEvents[stream.streamid].mediaElement){var mediaElement=connection.streamEvents[stream.streamid].mediaElement;mediaElement.volume=0,afterEach(200,5,function(){mediaElement.volume+=.2})}}("undefined"==typeof syncAction||1==syncAction)&&stream.addEventListener("ended",function(){StreamsHandler.onSyncNeeded(stream.streamid,"ended")},!1),stream.mute=function(type,isSyncAction){type=handleType(type),"undefined"!=typeof isSyncAction&&(syncAction=isSyncAction),("undefined"==typeof type||"audio"==type)&&stream.getAudioTracks().forEach(function(track){track.enabled=!1,connection.streamEvents[stream.streamid].isAudioMuted=!0}),("undefined"==typeof type||"video"==type)&&stream.getVideoTracks().forEach(function(track){track.enabled=!1}),("undefined"==typeof syncAction||1==syncAction)&&StreamsHandler.onSyncNeeded(stream.streamid,"mute",type),connection.streamEvents[stream.streamid].muteType=type||"both",fireEvent(stream,"mute",type)},stream.unmute=function(type,isSyncAction){type=handleType(type),"undefined"!=typeof isSyncAction&&(syncAction=isSyncAction),graduallyIncreaseVolume(),("undefined"==typeof type||"audio"==type)&&stream.getAudioTracks().forEach(function(track){track.enabled=!0,connection.streamEvents[stream.streamid].isAudioMuted=!1}),("undefined"==typeof type||"video"==type)&&(stream.getVideoTracks().forEach(function(track){track.enabled=!0}),"undefined"!=typeof type&&"video"==type&&connection.streamEvents[stream.streamid].isAudioMuted&&!function looper(times){times||(times=0),times++,100>times&&connection.streamEvents[stream.streamid].isAudioMuted&&(stream.mute("audio"),setTimeout(function(){looper(times)},50))}()),("undefined"==typeof syncAction||1==syncAction)&&StreamsHandler.onSyncNeeded(stream.streamid,"unmute",type),connection.streamEvents[stream.streamid].unmuteType=type||"both",fireEvent(stream,"unmute",type)}}function afterEach(setTimeoutInteval,numberOfTimes,callback,startedTimes){startedTimes=(startedTimes||0)+1,startedTimes>=numberOfTimes||setTimeout(function(){callback(),afterEach(setTimeoutInteval,numberOfTimes,callback,startedTimes)},setTimeoutInteval)}return{setHandlers:setHandlers,onSyncNeeded:function(streamid,action,type){}}}();!function(){function getBrowserInfo(){var nameOffset,verOffset,ix,nAgt=(navigator.appVersion,navigator.userAgent),browserName=navigator.appName,fullVersion=""+parseFloat(navigator.appVersion),majorVersion=parseInt(navigator.appVersion,10);if(isOpera){browserName="Opera";try{fullVersion=navigator.userAgent.split("OPR/")[1].split(" ")[0],majorVersion=fullVersion.split(".")[0]}catch(e){fullVersion="0.0.0.0",majorVersion=0}}else isIE?(verOffset=nAgt.indexOf("MSIE"),browserName="IE",fullVersion=nAgt.substring(verOffset+5)):isChrome?(verOffset=nAgt.indexOf("Chrome"),browserName="Chrome",fullVersion=nAgt.substring(verOffset+7)):isSafari?(verOffset=nAgt.indexOf("Safari"),browserName="Safari",fullVersion=nAgt.substring(verOffset+7),-1!==(verOffset=nAgt.indexOf("Version"))&&(fullVersion=nAgt.substring(verOffset+8))):isFirefox?(verOffset=nAgt.indexOf("Firefox"),browserName="Firefox",fullVersion=nAgt.substring(verOffset+8)):(nameOffset=nAgt.lastIndexOf(" ")+1)<(verOffset=nAgt.lastIndexOf("/"))&&(browserName=nAgt.substring(nameOffset,verOffset),fullVersion=nAgt.substring(verOffset+1),browserName.toLowerCase()===browserName.toUpperCase()&&(browserName=navigator.appName));return isEdge&&(browserName="Edge",fullVersion=parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2],10).toString()),-1!==(ix=fullVersion.indexOf(";"))&&(fullVersion=fullVersion.substring(0,ix)),-1!==(ix=fullVersion.indexOf(" "))&&(fullVersion=fullVersion.substring(0,ix)),majorVersion=parseInt(""+fullVersion,10),isNaN(majorVersion)&&(fullVersion=""+parseFloat(navigator.appVersion),majorVersion=parseInt(navigator.appVersion,10)),{fullVersion:fullVersion,version:majorVersion,name:browserName,isPrivateBrowsing:!1}}function retry(isDone,next){var currentTrial=0,maxRetry=50,isTimeout=!1,id=window.setInterval(function(){isDone()&&(window.clearInterval(id),next(isTimeout)),currentTrial++>maxRetry&&(window.clearInterval(id),isTimeout=!0,next(isTimeout))},10)}function isIE10OrLater(userAgent){var ua=userAgent.toLowerCase();if(0===ua.indexOf("msie")&&0===ua.indexOf("trident"))return!1;var match=/(?:msie|rv:)\s?([\d\.]+)/.exec(ua);return match&&parseInt(match[1],10)>=10?!0:!1}function detectPrivateMode(callback){var isPrivate;if(window.webkitRequestFileSystem)window.webkitRequestFileSystem(window.TEMPORARY,1,function(){isPrivate=!1},function(e){console.log(e),isPrivate=!0});else if(window.indexedDB&&/Firefox/.test(window.navigator.userAgent)){var db;try{db=window.indexedDB.open("test")}catch(e){isPrivate=!0}"undefined"==typeof isPrivate&&retry(function(){return"done"===db.readyState?!0:!1},function(isTimeout){isTimeout||(isPrivate=db.result?!1:!0)})}else if(isIE10OrLater(window.navigator.userAgent)){isPrivate=!1;try{window.indexedDB||(isPrivate=!0)}catch(e){isPrivate=!0}}else if(window.localStorage&&/Safari/.test(window.navigator.userAgent)){try{window.localStorage.setItem("test",1)}catch(e){isPrivate=!0}"undefined"==typeof isPrivate&&(isPrivate=!1,window.localStorage.removeItem("test"))}retry(function(){return"undefined"!=typeof isPrivate?!0:!1},function(isTimeout){callback(isPrivate)})}function detectDesktopOS(){var unknown="-",nVer=navigator.appVersion,nAgt=navigator.userAgent,os=unknown,clientStrings=[{s:"Windows 10",r:/(Windows 10.0|Windows NT 10.0)/},{s:"Windows 8.1",r:/(Windows 8.1|Windows NT 6.3)/},{s:"Windows 8",r:/(Windows 8|Windows NT 6.2)/},{s:"Windows 7",r:/(Windows 7|Windows NT 6.1)/},{s:"Windows Vista",r:/Windows NT 6.0/},{s:"Windows Server 2003",r:/Windows NT 5.2/},{s:"Windows XP",r:/(Windows NT 5.1|Windows XP)/},{s:"Windows 2000",r:/(Windows NT 5.0|Windows 2000)/},{s:"Windows ME",r:/(Win 9x 4.90|Windows ME)/},{s:"Windows 98",r:/(Windows 98|Win98)/},{s:"Windows 95",r:/(Windows 95|Win95|Windows_95)/},{s:"Windows NT 4.0",r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},{s:"Windows CE",r:/Windows CE/},{s:"Windows 3.11",r:/Win16/},{s:"Android",r:/Android/},{s:"Open BSD",r:/OpenBSD/},{s:"Sun OS",r:/SunOS/},{s:"Linux",r:/(Linux|X11)/},{s:"iOS",r:/(iPhone|iPad|iPod)/},{s:"Mac OS X",r:/Mac OS X/},{s:"Mac OS",r:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},{s:"QNX",r:/QNX/},{s:"UNIX",r:/UNIX/},{s:"BeOS",r:/BeOS/},{s:"OS/2",r:/OS\/2/},{s:"Search Bot",r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}];for(var id in clientStrings){var cs=clientStrings[id];if(cs.r.test(nAgt)){os=cs.s;break}}var osVersion=unknown;switch(/Windows/.test(os)&&(osVersion=/Windows (.*)/.exec(os)[1],os="Windows"),os){case"Mac OS X":osVersion=/Mac OS X (10[\.\_\d]+)/.exec(nAgt)[1];break;case"Android":osVersion=/Android ([\.\_\d]+)/.exec(nAgt)[1];break;case"iOS":osVersion=/OS (\d+)_(\d+)_?(\d+)?/.exec(nVer),osVersion=osVersion[1]+"."+osVersion[2]+"."+(0|osVersion[3])}return{osName:os,osVersion:osVersion}}function DetectLocalIPAddress(callback){DetectRTC.isWebRTCSupported&&(DetectRTC.isORTCSupported||getIPs(function(ip){callback(ip.match(/^(192\.168\.|169\.254\.|10\.|172\.(1[6-9]|2\d|3[01]))/)?"Local: "+ip:"Public: "+ip)}))}function getIPs(callback){function handleCandidate(candidate){var ipRegex=/([0-9]{1,3}(\.[0-9]{1,3}){3})/,match=ipRegex.exec(candidate);if(!match)return void console.warn("Could not match IP address in",candidate);var ipAddress=match[1];void 0===ipDuplicates[ipAddress]&&callback(ipAddress),ipDuplicates[ipAddress]=!0}var ipDuplicates={},RTCPeerConnection=window.RTCPeerConnection||window.mozRTCPeerConnection||window.webkitRTCPeerConnection,useWebKit=!!window.webkitRTCPeerConnection;if(!RTCPeerConnection){var iframe=document.getElementById("iframe");if(!iframe)throw"NOTE: you need to have an iframe in the page right above the script tag.";var win=iframe.contentWindow;RTCPeerConnection=win.RTCPeerConnection||win.mozRTCPeerConnection||win.webkitRTCPeerConnection,useWebKit=!!win.webkitRTCPeerConnection}if(RTCPeerConnection){var servers,mediaConstraints={optional:[{RtpDataChannels:!0}]};useWebKit&&(servers={iceServers:[{urls:"stun:stun.services.mozilla.com"}]},"undefined"!=typeof DetectRTC&&DetectRTC.browser.isFirefox&&DetectRTC.browser.version<=38&&(servers[0]={url:servers[0].urls}));var pc=new RTCPeerConnection(servers,mediaConstraints);pc.onicecandidate=function(ice){ice.candidate&&handleCandidate(ice.candidate.candidate)},pc.createDataChannel(""),pc.createOffer(function(result){pc.setLocalDescription(result,function(){},function(){})},function(){}),setTimeout(function(){var lines=pc.localDescription.sdp.split("\n");lines.forEach(function(line){0===line.indexOf("a=candidate:")&&handleCandidate(line)})},1e3)}}function checkDeviceSupport(callback){if(canEnumerate){if(!navigator.enumerateDevices&&window.MediaStreamTrack&&window.MediaStreamTrack.getSources&&(navigator.enumerateDevices=window.MediaStreamTrack.getSources.bind(window.MediaStreamTrack)),!navigator.enumerateDevices&&navigator.enumerateDevices&&(navigator.enumerateDevices=navigator.enumerateDevices.bind(navigator)),!navigator.enumerateDevices)return void(callback&&callback());MediaDevices=[],audioInputDevices=[],audioOutputDevices=[],videoInputDevices=[],navigator.enumerateDevices(function(devices){devices.forEach(function(_device){var device={};for(var d in _device)device[d]=_device[d];"audio"===device.kind&&(device.kind="audioinput"),"video"===device.kind&&(device.kind="videoinput");var skip;MediaDevices.forEach(function(d){d.id===device.id&&d.kind===device.kind&&(skip=!0)}),skip||(device.deviceId||(device.deviceId=device.id),device.id||(device.id=device.deviceId),device.label?("videoinput"!==device.kind||isWebsiteHasWebcamPermissions||(isWebsiteHasWebcamPermissions=!0),"audioinput"!==device.kind||isWebsiteHasMicrophonePermissions||(isWebsiteHasMicrophonePermissions=!0)):(device.label="Please invoke getUserMedia once.","https:"!==location.protocol&&(device.label="HTTPs is required to get label of this "+device.kind+" device.")),"audioinput"===device.kind&&(hasMicrophone=!0,-1===audioInputDevices.indexOf(device)&&audioInputDevices.push(device)),"audiooutput"===device.kind&&(hasSpeakers=!0,-1===audioOutputDevices.indexOf(device)&&audioOutputDevices.push(device)),"videoinput"===device.kind&&(hasWebcam=!0,-1===videoInputDevices.indexOf(device)&&videoInputDevices.push(device)),-1===MediaDevices.indexOf(device)&&MediaDevices.push(device))}),"undefined"!=typeof DetectRTC&&(DetectRTC.MediaDevices=MediaDevices,DetectRTC.hasMicrophone=hasMicrophone,DetectRTC.hasSpeakers=hasSpeakers,DetectRTC.hasWebcam=hasWebcam,DetectRTC.isWebsiteHasWebcamPermissions=isWebsiteHasWebcamPermissions,DetectRTC.isWebsiteHasMicrophonePermissions=isWebsiteHasMicrophonePermissions,DetectRTC.audioInputDevices=audioInputDevices,DetectRTC.audioOutputDevices=audioOutputDevices,DetectRTC.videoInputDevices=videoInputDevices),callback&&callback()})}}var navigator=window.navigator;"undefined"!=typeof navigator?("undefined"!=typeof navigator.webkitGetUserMedia&&(navigator.getUserMedia=navigator.webkitGetUserMedia),"undefined"!=typeof navigator.mozGetUserMedia&&(navigator.getUserMedia=navigator.mozGetUserMedia)):navigator={getUserMedia:function(){},userAgent:"Fake/5.0 (FakeOS) AppleWebKit/123 (KHTML, like Gecko) Fake/12.3.4567.89 Fake/123.45"};var isMobileDevice=!!navigator.userAgent.match(/Android|iPhone|iPad|iPod|BlackBerry|IEMobile/i),isEdge=!(-1===navigator.userAgent.indexOf("Edge")||!navigator.msSaveOrOpenBlob&&!navigator.msSaveBlob),isOpera=!!window.opera||navigator.userAgent.indexOf(" OPR/")>=0,isFirefox="undefined"!=typeof window.InstallTrigger,isSafari=Object.prototype.toString.call(window.HTMLElement).indexOf("Constructor")>0,isChrome=!!window.chrome&&!isOpera,isIE=!!document.documentMode&&!isEdge,isMobile={
Android:function(){return navigator.userAgent.match(/Android/i)},BlackBerry:function(){return navigator.userAgent.match(/BlackBerry/i)},iOS:function(){return navigator.userAgent.match(/iPhone|iPad|iPod/i)},Opera:function(){return navigator.userAgent.match(/Opera Mini/i)},Windows:function(){return navigator.userAgent.match(/IEMobile/i)},any:function(){return isMobile.Android()||isMobile.BlackBerry()||isMobile.iOS()||isMobile.Opera()||isMobile.Windows()},getOsName:function(){var osName="Unknown OS";return isMobile.Android()&&(osName="Android"),isMobile.BlackBerry()&&(osName="BlackBerry"),isMobile.iOS()&&(osName="iOS"),isMobile.Opera()&&(osName="Opera Mini"),isMobile.Windows()&&(osName="Windows"),osName}},osName="Unknown OS",osVersion="Unknown OS Version";if(isMobile.any())osName=isMobile.getOsName();else{var osInfo=detectDesktopOS();osName=osInfo.osName,osVersion=osInfo.osVersion}var isCanvasSupportsStreamCapturing=!1,isVideoSupportsStreamCapturing=!1;["captureStream","mozCaptureStream","webkitCaptureStream"].forEach(function(item){!isCanvasSupportsStreamCapturing&&item in document.createElement("canvas")&&(isCanvasSupportsStreamCapturing=!0),!isVideoSupportsStreamCapturing&&item in document.createElement("video")&&(isVideoSupportsStreamCapturing=!0)});var MediaDevices=[],audioInputDevices=[],audioOutputDevices=[],videoInputDevices=[];navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices&&(navigator.enumerateDevices=function(callback){navigator.mediaDevices.enumerateDevices().then(callback)});var canEnumerate=!1;"undefined"!=typeof MediaStreamTrack&&"getSources"in MediaStreamTrack?canEnumerate=!0:navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices&&(canEnumerate=!0);var hasMicrophone=!1,hasSpeakers=!1,hasWebcam=!1,isWebsiteHasMicrophonePermissions=!1,isWebsiteHasWebcamPermissions=!1;checkDeviceSupport();var DetectRTC=window.DetectRTC||{};DetectRTC.browser=getBrowserInfo(),detectPrivateMode(function(isPrivateBrowsing){DetectRTC.browser.isPrivateBrowsing=!!isPrivateBrowsing}),DetectRTC.browser["is"+DetectRTC.browser.name]=!0;var isWebRTCSupported=(!!(window.process&&"object"==typeof window.process&&window.process.versions&&window.process.versions["node-webkit"]),!1);["RTCPeerConnection","webkitRTCPeerConnection","mozRTCPeerConnection","RTCIceGatherer"].forEach(function(item){isWebRTCSupported||item in window&&(isWebRTCSupported=!0)}),DetectRTC.isWebRTCSupported=isWebRTCSupported,DetectRTC.isORTCSupported="undefined"!=typeof RTCIceGatherer;var isScreenCapturingSupported=!1;DetectRTC.browser.isChrome&&DetectRTC.browser.version>=35?isScreenCapturingSupported=!0:DetectRTC.browser.isFirefox&&DetectRTC.browser.version>=34&&(isScreenCapturingSupported=!0),"https:"!==location.protocol&&(isScreenCapturingSupported=!1),DetectRTC.isScreenCapturingSupported=isScreenCapturingSupported;var webAudio={isSupported:!1,isCreateMediaStreamSourceSupported:!1};["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"].forEach(function(item){webAudio.isSupported||item in window&&(webAudio.isSupported=!0,"createMediaStreamSource"in window[item].prototype&&(webAudio.isCreateMediaStreamSourceSupported=!0))}),DetectRTC.isAudioContextSupported=webAudio.isSupported,DetectRTC.isCreateMediaStreamSourceSupported=webAudio.isCreateMediaStreamSourceSupported;var isRtpDataChannelsSupported=!1;DetectRTC.browser.isChrome&&DetectRTC.browser.version>31&&(isRtpDataChannelsSupported=!0),DetectRTC.isRtpDataChannelsSupported=isRtpDataChannelsSupported;var isSCTPSupportd=!1;DetectRTC.browser.isFirefox&&DetectRTC.browser.version>28?isSCTPSupportd=!0:DetectRTC.browser.isChrome&&DetectRTC.browser.version>25?isSCTPSupportd=!0:DetectRTC.browser.isOpera&&DetectRTC.browser.version>=11&&(isSCTPSupportd=!0),DetectRTC.isSctpDataChannelsSupported=isSCTPSupportd,DetectRTC.isMobileDevice=isMobileDevice;var isGetUserMediaSupported=!1;navigator.getUserMedia?isGetUserMediaSupported=!0:navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&(isGetUserMediaSupported=!0),DetectRTC.browser.isChrome&&DetectRTC.browser.version>=46&&"https:"!==location.protocol&&(DetectRTC.isGetUserMediaSupported="Requires HTTPs"),DetectRTC.isGetUserMediaSupported=isGetUserMediaSupported,DetectRTC.osName=osName,DetectRTC.osVersion=osVersion;var displayResolution="";if(screen.width){var width=screen.width?screen.width:"",height=screen.height?screen.height:"";displayResolution+=""+width+" x "+height}DetectRTC.displayResolution=displayResolution,DetectRTC.isCanvasSupportsStreamCapturing=isCanvasSupportsStreamCapturing,DetectRTC.isVideoSupportsStreamCapturing=isVideoSupportsStreamCapturing,DetectRTC.DetectLocalIPAddress=DetectLocalIPAddress,DetectRTC.isWebSocketsSupported="WebSocket"in window&&2===window.WebSocket.CLOSING,DetectRTC.isWebSocketsBlocked=!DetectRTC.isWebSocketsSupported,DetectRTC.checkWebSocketsSupport=function(callback){callback=callback||function(){};try{var websocket=new WebSocket("wss://echo.websocket.org:443/");websocket.onopen=function(){DetectRTC.isWebSocketsBlocked=!1,callback(),websocket.close(),websocket=null},websocket.onerror=function(){DetectRTC.isWebSocketsBlocked=!0,callback()}}catch(e){DetectRTC.isWebSocketsBlocked=!0,callback()}},DetectRTC.load=function(callback){callback=callback||function(){},checkDeviceSupport(callback)},DetectRTC.MediaDevices=MediaDevices,DetectRTC.hasMicrophone=hasMicrophone,DetectRTC.hasSpeakers=hasSpeakers,DetectRTC.hasWebcam=hasWebcam,DetectRTC.isWebsiteHasWebcamPermissions=isWebsiteHasWebcamPermissions,DetectRTC.isWebsiteHasMicrophonePermissions=isWebsiteHasMicrophonePermissions,DetectRTC.audioInputDevices=audioInputDevices,DetectRTC.audioOutputDevices=audioOutputDevices,DetectRTC.videoInputDevices=videoInputDevices;var isSetSinkIdSupported=!1;"setSinkId"in document.createElement("video")&&(isSetSinkIdSupported=!0),DetectRTC.isSetSinkIdSupported=isSetSinkIdSupported;var isRTPSenderReplaceTracksSupported=!1;DetectRTC.browser.isFirefox?"getSenders"in mozRTCPeerConnection.prototype&&(isRTPSenderReplaceTracksSupported=!0):DetectRTC.browser.isChrome&&"getSenders"in webkitRTCPeerConnection.prototype&&(isRTPSenderReplaceTracksSupported=!0),DetectRTC.isRTPSenderReplaceTracksSupported=isRTPSenderReplaceTracksSupported;var isRemoteStreamProcessingSupported=!1;DetectRTC.browser.isFirefox&&DetectRTC.browser.version>38&&(isRemoteStreamProcessingSupported=!0),DetectRTC.isRemoteStreamProcessingSupported=isRemoteStreamProcessingSupported;var isApplyConstraintsSupported=!1;"undefined"!=typeof MediaStreamTrack&&"applyConstraints"in MediaStreamTrack.prototype&&(isApplyConstraintsSupported=!0),DetectRTC.isApplyConstraintsSupported=isApplyConstraintsSupported;var isMultiMonitorScreenCapturingSupported=!1;DetectRTC.browser.isFirefox&&DetectRTC.browser.version>=43&&(isMultiMonitorScreenCapturingSupported=!0),DetectRTC.isMultiMonitorScreenCapturingSupported=isMultiMonitorScreenCapturingSupported,window.DetectRTC=DetectRTC}(),function(){function getScreenConstraints(error,sourceId){var screen_constraints={audio:!1,video:{mandatory:{chromeMediaSource:error?"screen":"desktop",maxWidth:15360,maxHeight:8640,minFrameRate:30,maxFrameRate:64,minAspectRatio:1.77,googLeakyBucket:!0,googTemporalLayeredScreencast:!0},optional:[]}};return sourceId&&(screen_constraints.video.mandatory.chromeMediaSourceId=sourceId),screen_constraints}function postMessage(){return iframe?iframe.isLoaded?void iframe.contentWindow.postMessage({captureSourceId:!0},"*"):void setTimeout(postMessage,100):void loadIFrame(postMessage)}function loadIFrame(loadCallback){return iframe?void loadCallback():(iframe=document.createElement("iframe"),iframe.onload=function(){iframe.isLoaded=!0,loadCallback()},iframe.src="https://www.webrtc-experiment.com/getSourceId/",iframe.style.display="none",void(document.body||document.documentElement).appendChild(iframe))}window.getScreenId=function(callback){function onIFrameCallback(event){event.data&&(event.data.chromeMediaSourceId&&("PermissionDeniedError"===event.data.chromeMediaSourceId?callback("permission-denied"):callback(null,event.data.chromeMediaSourceId,getScreenConstraints(null,event.data.chromeMediaSourceId))),event.data.chromeExtensionStatus&&callback(event.data.chromeExtensionStatus,null,getScreenConstraints(event.data.chromeExtensionStatus)),window.removeEventListener("message",onIFrameCallback))}return navigator.mozGetUserMedia?void callback(null,"firefox",{video:{mozMediaSource:"window",mediaSource:"window",width:15360,height:8640}}):(postMessage(),void window.addEventListener("message",onIFrameCallback))};var iframe;window.getScreenConstraints=function(callback){loadIFrame(function(){getScreenId(function(error,sourceId,screen_constraints){callback(error,screen_constraints.video)})})}}(),function(){function getScreenConstraints(error,sourceId){var screen_constraints={audio:!1,video:{mandatory:{chromeMediaSource:error?"screen":"desktop",maxWidth:15360,maxHeight:8640,minFrameRate:30,maxFrameRate:64,minAspectRatio:1.77,googLeakyBucket:!0,googTemporalLayeredScreencast:!0},optional:[]}};return sourceId&&(screen_constraints.video.mandatory.chromeMediaSourceId=sourceId),screen_constraints}function postMessage(){return iframe?iframe.isLoaded?void iframe.contentWindow.postMessage({captureSourceId:!0},"*"):void setTimeout(postMessage,100):void loadIFrame(postMessage)}function loadIFrame(loadCallback){return iframe?void loadCallback():(iframe=document.createElement("iframe"),iframe.onload=function(){iframe.isLoaded=!0,loadCallback()},iframe.src="https://www.webrtc-experiment.com/getSourceId/",iframe.style.display="none",void(document.body||document.documentElement).appendChild(iframe))}if(-1!==document.domain.indexOf("webrtc-experiment.com")){window.getScreenId=function(callback){function onIFrameCallback(event){event.data&&(event.data.chromeMediaSourceId&&("PermissionDeniedError"===event.data.chromeMediaSourceId?callback("permission-denied"):callback(null,event.data.chromeMediaSourceId,getScreenConstraints(null,event.data.chromeMediaSourceId))),event.data.chromeExtensionStatus&&callback(event.data.chromeExtensionStatus,null,getScreenConstraints(event.data.chromeExtensionStatus)),window.removeEventListener("message",onIFrameCallback))}return navigator.mozGetUserMedia?void callback(null,"firefox",{video:{mozMediaSource:"window",mediaSource:"window",width:15360,height:8640}}):(postMessage(),void window.addEventListener("message",onIFrameCallback))};var iframe;window.getScreenConstraints=function(callback){loadIFrame(function(){getScreenId(function(error,sourceId,screen_constraints){callback(error,screen_constraints.video)})})}}}();var TextSender={send:function(config){function sendText(textMessage,text){var data={type:"text",uuid:uuid,sendingTime:sendingTime};textMessage&&(text=textMessage,data.packets=parseInt(text.length/packetSize)),text.length>packetSize?data.message=text.slice(0,packetSize):(data.message=text,data.last=!0,data.isobject=isobject),channel.send(data,remoteUserId),textToTransfer=text.slice(data.message.length),textToTransfer.length&&setTimeout(function(){sendText(null,textToTransfer)},connection.chunkInterval||100)}var connection=config.connection,channel=config.channel,remoteUserId=config.remoteUserId,initialText=config.text,packetSize=connection.chunkSize||1e3,textToTransfer="",isobject=!1;isString(initialText)||(isobject=!0,initialText=JSON.stringify(initialText));var uuid=getRandomString(),sendingTime=(new Date).getTime();sendText(initialText)}},FileProgressBarHandler=function(){function handle(connection){function updateLabel(progress,label){if(-1!==progress.position){var position=+progress.position.toFixed(2).split(".")[1]||100;label.innerHTML=position+"%"}}var progressHelper={};connection.onFileStart=function(file){var div=document.createElement("div");return div.title=file.name,div.innerHTML=" ",file.remoteUserId&&(div.innerHTML+=" (Sharing with:"+file.remoteUserId+")"),connection.filesContainer||(connection.filesContainer=document.body||document.documentElement),connection.filesContainer.insertBefore(div,connection.filesContainer.firstChild),file.remoteUserId?(progressHelper[file.uuid]||(progressHelper[file.uuid]={}),progressHelper[file.uuid][file.remoteUserId]={div:div,progress:div.querySelector("progress"),label:div.querySelector("label")},void(progressHelper[file.uuid][file.remoteUserId].progress.max=file.maxChunks)):(progressHelper[file.uuid]={div:div,progress:div.querySelector("progress"),label:div.querySelector("label")},void(progressHelper[file.uuid].progress.max=file.maxChunks))},connection.onFileProgress=function(chunk){var helper=progressHelper[chunk.uuid];helper&&(!chunk.remoteUserId||(helper=progressHelper[chunk.uuid][chunk.remoteUserId]))&&(helper.progress.value=chunk.currentPosition||chunk.maxChunks||helper.progress.max,updateLabel(helper.progress,helper.label))},connection.onFileEnd=function(file){var helper=progressHelper[file.uuid];if(!helper)return void console.error("No such progress-helper element exists.",file);if(!file.remoteUserId||(helper=progressHelper[file.uuid][file.remoteUserId])){var div=helper.div;-1!=file.type.indexOf("image")?div.innerHTML='Download '+file.name+'
':div.innerHTML='Download '+file.name+'
'}}}return{handle:handle}}(),TranslationHandler=function(){function handle(connection){connection.autoTranslateText=!1,connection.language="en",connection.googKey="AIzaSyCgB5hmFY74WYB-EoWkhr9cAGr6TiTHrEE",connection.Translator={TranslateText:function(text,callback){var newScript=document.createElement("script");newScript.type="text/javascript";var sourceText=encodeURIComponent(text),randomNumber="method"+connection.token();window[randomNumber]=function(response){response.data&&response.data.translations[0]&&callback&&callback(response.data.translations[0].translatedText),response.error&&"Daily Limit Exceeded"===response.error.message&&(warn('Text translation failed. Error message: "Daily Limit Exceeded."'),callback(text))};var source="https://www.googleapis.com/language/translate/v2?key="+connection.googKey+"&target="+(connection.language||"en-US")+"&callback=window."+randomNumber+"&q="+sourceText;newScript.src=source,document.getElementsByTagName("head")[0].appendChild(newScript)}}}return{handle:handle}}();window.RTCMultiConnection=RTCMultiConnection}();
\ No newline at end of file
diff --git a/package.json b/package.json
index 72b6efb5..5bb373a0 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "rtcmulticonnection-v3",
"preferGlobal": false,
- "version": "3.2.86",
+ "version": "3.2.87",
"author": {
"name": "Muaz Khan",
"email": "muazkh@gmail.com",
@@ -49,15 +49,16 @@
"homepage": "https://rtcmulticonnection.herokuapp.com/",
"_from": "rtcmulticonnection-v3@",
"devDependencies": {
- "grunt": "latest",
- "grunt-bump": "latest",
- "grunt-cli": "latest",
- "grunt-contrib-clean": "latest",
- "grunt-contrib-concat": "latest",
- "grunt-contrib-copy": "latest",
- "grunt-contrib-uglify": "latest",
- "grunt-jsbeautifier": "latest",
- "grunt-replace": "latest",
- "load-grunt-tasks": "latest"
+ "grunt": "0.4.5",
+ "grunt-cli": "0.1.13",
+ "load-grunt-tasks": "3.4.0",
+ "grunt-contrib-concat": "0.5.1",
+ "grunt-contrib-jshint": "0.11.3",
+ "grunt-contrib-uglify": "0.11.0",
+ "grunt-jsbeautifier": "0.2.10",
+ "grunt-bump": "0.7.0",
+ "grunt-contrib-clean": "0.6.0",
+ "grunt-contrib-copy": "0.8.2",
+ "grunt-replace": "0.11.0"
}
}