Jitsi Meet - Secure, Simple and Scalable Video Conferences that you use as a standalone app or embed in your web application.
TypeScript debiandeep-videojitsijitsi-meetscalable-video-conferencessfuvideovideo-communicationvideo-conferencingwebrtc
Updates app.bundle.js.
Boris Grozeve90d8f553174
diff --git a/libs/app.bundle.js b/libs/app.bundle.jsindex e4515e4281..57783c0b45 100644--- a/libs/app.bundle.js+++ b/libs/app.bundle.js@@ -1,2107 +1,1712 @@-(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.APP = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){-// Copyright Joyent, Inc. and other Node contributors.-//-// Permission is hereby granted, free of charge, to any person obtaining a-// copy of this software and associated documentation files (the-// "Software"), to deal in the Software without restriction, including-// without limitation the rights to use, copy, modify, merge, publish,-// distribute, sublicense, and/or sell copies of the Software, and to permit-// persons to whom the Software is furnished to do so, subject to the-// following conditions:-//-// The above copyright notice and this permission notice shall be included-// in all copies or substantial portions of the Software.-//-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE-// USE OR OTHER DEALINGS IN THE SOFTWARE.--function EventEmitter() {- this._events = this._events || {};- this._maxListeners = this._maxListeners || undefined;-}-module.exports = EventEmitter;--// Backwards-compat with node 0.10.x-EventEmitter.EventEmitter = EventEmitter;--EventEmitter.prototype._events = undefined;-EventEmitter.prototype._maxListeners = undefined;--// By default EventEmitters will print a warning if more than 10 listeners are-// added to it. This is a useful default which helps finding memory leaks.-EventEmitter.defaultMaxListeners = 10;+!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.APP=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){+/* jshint -W117 */+/* application specific logic */-// Obviously not all Emitters should be limited to 10. This function allows-// that to be increased. Set to zero for unlimited.-EventEmitter.prototype.setMaxListeners = function(n) {- if (!isNumber(n) || n < 0 || isNaN(n))- throw TypeError('n must be a positive number');- this._maxListeners = n;- return this;+var APP =+{+ init: function () {+ this.UI = require("./modules/UI/UI");+ this.API = require("./modules/API/API");+ this.connectionquality = require("./modules/connectionquality/connectionquality");+ this.statistics = require("./modules/statistics/statistics");+ this.RTC = require("./modules/RTC/RTC");+ this.desktopsharing = require("./modules/desktopsharing/desktopsharing");+ this.xmpp = require("./modules/xmpp/xmpp");+ this.keyboardshortcut = require("./modules/keyboardshortcut/keyboardshortcut");+ this.translation = require("./modules/translation/translation");+ this.settings = require("./modules/settings/Settings");+ this.DTMF = require("./modules/DTMF/DTMF");+ this.members = require("./modules/members/MemberList");+ }};-EventEmitter.prototype.emit = function(type) {- var er, handler, len, args, i, listeners;-- if (!this._events)- this._events = {};+function init() {- // If there is no 'error' event listener then throw.- if (type === 'error') {- if (!this._events.error ||- (isObject(this._events.error) && !this._events.error.length)) {- er = arguments[1];- if (er instanceof Error) {- throw er; // Unhandled 'error' event- }- throw TypeError('Uncaught, unspecified "error" event.');- }- }+ APP.desktopsharing.init();+ APP.RTC.start();+ APP.xmpp.start();+ APP.statistics.start();+ APP.connectionquality.init();+ APP.keyboardshortcut.init();+ APP.members.start();+}- handler = this._events[type];- if (isUndefined(handler))- return false;+$(document).ready(function () {- if (isFunction(handler)) {- switch (arguments.length) {- // fast cases- case 1:- handler.call(this);- break;- case 2:- handler.call(this, arguments[1]);- break;- case 3:- handler.call(this, arguments[1], arguments[2]);- break;- // slower- default:- len = arguments.length;- args = new Array(len - 1);- for (i = 1; i < len; i++)- args[i - 1] = arguments[i];- handler.apply(this, args);- }- } else if (isObject(handler)) {- len = arguments.length;- args = new Array(len - 1);- for (i = 1; i < len; i++)- args[i - 1] = arguments[i];+ var URLProcessor = require("./modules/URLProcessor/URLProcessor");+ URLProcessor.setConfigParametersFromUrl();+ APP.init();- listeners = handler.slice();- len = listeners.length;- for (i = 0; i < len; i++)- listeners[i].apply(this, args);- }+ APP.translation.init();- return true;-};+ if(APP.API.isEnabled())+ APP.API.init();-EventEmitter.prototype.addListener = function(type, listener) {- var m;+ APP.UI.start(init);- if (!isFunction(listener))- throw TypeError('listener must be a function');+});- if (!this._events)- this._events = {};+$(window).bind('beforeunload', function () {+ if(APP.API.isEnabled())+ APP.API.dispose();+});- // To avoid recursion in the case that type === "newListener"! Before- // adding it to the listeners, first emit "newListener".- if (this._events.newListener)- this.emit('newListener', type,- isFunction(listener.listener) ?- listener.listener : listener);+module.exports = APP;- if (!this._events[type])- // Optimize the case of one listener. Don't need the extra array object.- this._events[type] = listener;- else if (isObject(this._events[type]))- // If we've already got an array, just append.- this._events[type].push(listener);- else- // Adding the second element, need to change to array.- this._events[type] = [this._events[type], listener];- // Check for listener leak- if (isObject(this._events[type]) && !this._events[type].warned) {- var m;- if (!isUndefined(this._maxListeners)) {- m = this._maxListeners;- } else {- m = EventEmitter.defaultMaxListeners;- }+},{"./modules/API/API":2,"./modules/DTMF/DTMF":3,"./modules/RTC/RTC":7,"./modules/UI/UI":11,"./modules/URLProcessor/URLProcessor":42,"./modules/connectionquality/connectionquality":43,"./modules/desktopsharing/desktopsharing":44,"./modules/keyboardshortcut/keyboardshortcut":45,"./modules/members/MemberList":46,"./modules/settings/Settings":47,"./modules/statistics/statistics":51,"./modules/translation/translation":52,"./modules/xmpp/xmpp":68}],2:[function(require,module,exports){+/* global APP */+/**+ * Implements API class that communicates with external api class+ * and provides interface to access Jitsi Meet features by external+ * applications that embed Jitsi Meet+ */- if (m && m > 0 && this._events[type].length > m) {- this._events[type].warned = true;- console.error('(node) warning: possible EventEmitter memory ' +- 'leak detected. %d listeners added. ' +- 'Use emitter.setMaxListeners() to increase limit.',- this._events[type].length);- if (typeof console.trace === 'function') {- // not supported in IE 10- console.trace();- }- }- }+var XMPPEvents = require("../../service/xmpp/XMPPEvents");- return this;-};+/**+ * List of the available commands.+ * @type {{+ * displayName: inputDisplayNameHandler,+ * toggleAudio: toggleAudio,+ * toggleVideo: toggleVideo,+ * toggleFilmStrip: toggleFilmStrip,+ * toggleChat: toggleChat,+ * toggleContactList: toggleContactList+ * }}+ */+var commands = {};-EventEmitter.prototype.on = EventEmitter.prototype.addListener;+function initCommands() {+ commands = {+ displayName: APP.UI.inputDisplayNameHandler,+ toggleAudio: APP.UI.toggleAudio,+ toggleVideo: APP.UI.toggleVideo,+ toggleFilmStrip: APP.UI.toggleFilmStrip,+ toggleChat: APP.UI.toggleChat,+ toggleContactList: APP.UI.toggleContactList+ };+}-EventEmitter.prototype.once = function(type, listener) {- if (!isFunction(listener))- throw TypeError('listener must be a function');- var fired = false;+/**+ * Maps the supported events and their status+ * (true it the event is enabled and false if it is disabled)+ * @type {{+ * incomingMessage: boolean,+ * outgoingMessage: boolean,+ * displayNameChange: boolean,+ * participantJoined: boolean,+ * participantLeft: boolean+ * }}+ */+var events = {+ incomingMessage: false,+ outgoingMessage:false,+ displayNameChange: false,+ participantJoined: false,+ participantLeft: false+};- function g() {- this.removeListener(type, g);+var displayName = {};- if (!fired) {- fired = true;- listener.apply(this, arguments);+/**+ * Processes commands from external application.+ * @param message the object with the command+ */+function processCommand(message) {+ if (message.action != "execute") {+ console.error("Unknown action of the message");+ return;}- }-- g.listener = listener;- this.on(type, g);-- return this;-};+ for (var key in message) {+ if(commands[key])+ commands[key].apply(null, message[key]);+ }+}-// emits a 'removeListener' event iff the listener was removed-EventEmitter.prototype.removeListener = function(type, listener) {- var list, position, length, i;-- if (!isFunction(listener))- throw TypeError('listener must be a function');+/**+ * Processes events objects from external applications+ * @param event the event+ */+function processEvent(event) {+ if (!event.action) {+ console.error("Event with no action is received.");+ return;+ }- if (!this._events || !this._events[type])- return this;+ var i = 0;+ switch(event.action) {+ case "add":+ for (; i < event.events.length; i++) {+ events[event.events[i]] = true;+ }+ break;+ case "remove":+ for (; i < event.events.length; i++) {+ events[event.events[i]] = false;+ }+ break;+ default:+ console.error("Unknown action for event.");+ }+}- list = this._events[type];- length = list.length;- position = -1;+/**+ * Sends message to the external application.+ * @param object+ */+function sendMessage(object) {+ window.parent.postMessage(JSON.stringify(object), "*");+}- if (list === listener ||- (isFunction(list.listener) && list.listener === listener)) {- delete this._events[type];- if (this._events.removeListener)- this.emit('removeListener', type, listener);+/**+ * Processes a message event from the external application+ * @param event the message event+ */+function processMessage(event) {+ var message;+ try {+ message = JSON.parse(event.data);+ } catch (e) {}- } else if (isObject(list)) {- for (i = length; i-- > 0;) {- if (list[i] === listener ||- (list[i].listener && list[i].listener === listener)) {- position = i;- break;- }+ if(!message.type)+ return;+ switch (message.type) {+ case "command":+ processCommand(message);+ break;+ case "event":+ processEvent(message);+ break;+ default:+ console.error("Unknown type of the message");+ return;}+}- if (position < 0)- return this;+function setupListeners() {+ APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, function (from) {+ API.triggerEvent("participantJoined", {jid: from});+ });+ APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid, stamp) {+ if (from != myjid)+ API.triggerEvent("incomingMessage",+ {"from": from, "nick": nick, "message": txt, "stamp": stamp});+ });+ APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, function (jid) {+ API.triggerEvent("participantLeft", {jid: jid});+ });+ APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {+ var name = displayName[jid];+ if(!name || name != newDisplayName) {+ API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});+ displayName[jid] = newDisplayName;+ }+ });+ APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {+ APP.API.triggerEvent("outgoingMessage", {"message": body});+ });+}- if (list.length === 1) {- list.length = 0;- delete this._events[type];- } else {- list.splice(position, 1);- }+var API = {+ /**+ * Check whether the API should be enabled or not.+ * @returns {boolean}+ */+ isEnabled: function () {+ var hash = location.hash;+ if (hash && hash.indexOf("external") > -1 && window.postMessage)+ return true;+ return false;+ },+ /**+ * Initializes the APIConnector. Setups message event listeners that will+ * receive information from external applications that embed Jitsi Meet.+ * It also sends a message to the external application that APIConnector+ * is initialized.+ */+ init: function () {+ initCommands();+ if (window.addEventListener) {+ window.addEventListener('message',+ processMessage, false);+ }+ else {+ window.attachEvent('onmessage', processMessage);+ }+ sendMessage({type: "system", loaded: true});+ setupListeners();+ },+ /**+ * Checks whether the event is enabled ot not.+ * @param name the name of the event.+ * @returns {*}+ */+ isEventEnabled: function (name) {+ return events[name];+ },- if (this._events.removeListener)- this.emit('removeListener', type, listener);- }+ /**+ * Sends event object to the external application that has been subscribed+ * for that event.+ * @param name the name event+ * @param object data associated with the event+ */+ triggerEvent: function (name, object) {+ if(this.isEnabled() && this.isEventEnabled(name))+ sendMessage({+ type: "event", action: "result", event: name, result: object});+ },- return this;+ /**+ * Removes the listeners.+ */+ dispose: function () {+ if(window.removeEventListener) {+ window.removeEventListener("message",+ processMessage, false);+ }+ else {+ window.detachEvent('onmessage', processMessage);+ }+ }};-EventEmitter.prototype.removeAllListeners = function(type) {- var key, listeners;-- if (!this._events)- return this;+module.exports = API;+},{"../../service/xmpp/XMPPEvents":161}],3:[function(require,module,exports){+/* global APP */- // not listening for removeListener, no need to emit- if (!this._events.removeListener) {- if (arguments.length === 0)- this._events = {};- else if (this._events[type])- delete this._events[type];- return this;- }+/**+ * A module for sending DTMF tones.+ */+var DTMFSender;+var initDtmfSender = function() {+ // TODO: This needs to reset this if the peerconnection changes+ // (e.g. the call is re-made)+ if (DTMFSender)+ return;- // emit removeListener for all listeners on all events- if (arguments.length === 0) {- for (key in this._events) {- if (key === 'removeListener') continue;- this.removeAllListeners(key);+ var localAudio = APP.RTC.localAudio;+ if (localAudio && localAudio.getTracks().length > 0)+ {+ var peerconnection+ = APP.xmpp.getConnection().jingle.activecall.peerconnection;+ if (peerconnection) {+ DTMFSender =+ peerconnection.peerconnection+ .createDTMFSender(localAudio.getTracks()[0]);+ console.log("Initialized DTMFSender");+ }+ else {+ console.log("Failed to initialize DTMFSender: no PeerConnection.");+ }}- this.removeAllListeners('removeListener');- this._events = {};- return this;- }-- listeners = this._events[type];+ else {+ console.log("Failed to initialize DTMFSender: no audio track.");+ }+};- if (isFunction(listeners)) {- this.removeListener(type, listeners);- } else {- // LIFO order- while (listeners.length)- this.removeListener(type, listeners[listeners.length - 1]);- }- delete this._events[type];+var DTMF = {+ sendTones: function (tones, duration, pause) {+ if (!DTMFSender)+ initDtmfSender();- return this;+ if (DTMFSender){+ DTMFSender.insertDTMF(tones,+ (duration || 200),+ (pause || 200));+ }+ }};-EventEmitter.prototype.listeners = function(type) {- var ret;- if (!this._events || !this._events[type])- ret = [];- else if (isFunction(this._events[type]))- ret = [this._events[type]];- else- ret = this._events[type].slice();- return ret;-};+module.exports = DTMF;-EventEmitter.listenerCount = function(emitter, type) {- var ret;- if (!emitter._events || !emitter._events[type])- ret = 0;- else if (isFunction(emitter._events[type]))- ret = 1;- else- ret = emitter._events[type].length;- return ret;-};-function isFunction(arg) {- return typeof arg === 'function';-}+},{}],4:[function(require,module,exports){+/* global config, APP, Strophe */-function isNumber(arg) {- return typeof arg === 'number';-}+// cache datachannels to avoid garbage collection+// https://code.google.com/p/chromium/issues/detail?id=405545+var RTCEvents = require("../../service/RTC/RTCEvents");-function isObject(arg) {- return typeof arg === 'object' && arg !== null;-}+var _dataChannels = [];+var eventEmitter = null;-function isUndefined(arg) {- return arg === void 0;-}-},{}],2:[function(require,module,exports){-// shim for using process in browser+var DataChannels = {+ /**+ * Callback triggered by PeerConnection when new data channel is opened+ * on the bridge.+ * @param event the event info object.+ */+ onDataChannel: function (event) {+ var dataChannel = event.channel;-var process = module.exports = {};-var queue = [];-var draining = false;-var currentQueue;-var queueIndex = -1;+ dataChannel.onopen = function () {+ console.info("Data channel opened by the Videobridge!", dataChannel);-function cleanUpNextTick() {- draining = false;- if (currentQueue.length) {- queue = currentQueue.concat(queue);- } else {- queueIndex = -1;- }- if (queue.length) {- drainQueue();- }-}+ // Code sample for sending string and/or binary data+ // Sends String message to the bridge+ //dataChannel.send("Hello bridge!");+ // Sends 12 bytes binary message to the bridge+ //dataChannel.send(new ArrayBuffer(12));-function drainQueue() {- if (draining) {- return;- }- var timeout = setTimeout(cleanUpNextTick);- draining = true;+ eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);+ };- var len = queue.length;- while(len) {- currentQueue = queue;- queue = [];- while (++queueIndex < len) {- currentQueue[queueIndex].run();- }- queueIndex = -1;- len = queue.length;- }- currentQueue = null;- draining = false;- clearTimeout(timeout);-}+ dataChannel.onerror = function (error) {+ console.error("Data Channel Error:", error, dataChannel);+ };-process.nextTick = function (fun) {- var args = new Array(arguments.length - 1);- if (arguments.length > 1) {- for (var i = 1; i < arguments.length; i++) {- args[i - 1] = arguments[i];- }- }- queue.push(new Item(fun, args));- if (queue.length === 1 && !draining) {- setTimeout(drainQueue, 0);- }-};+ dataChannel.onmessage = function (event) {+ var data = event.data;+ // JSON+ var obj;-// v8 likes predictible objects-function Item(fun, array) {- this.fun = fun;- this.array = array;-}-Item.prototype.run = function () {- this.fun.apply(null, this.array);-};-process.title = 'browser';-process.browser = true;-process.env = {};-process.argv = [];-process.version = ''; // empty string to avoid regexp issues-process.versions = {};+ try {+ obj = JSON.parse(data);+ }+ catch (e) {+ console.error(+ "Failed to parse data channel message as JSON: ",+ data,+ dataChannel);+ }+ if (('undefined' !== typeof(obj)) && (null !== obj)) {+ var colibriClass = obj.colibriClass;-function noop() {}+ if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {+ // Endpoint ID from the Videobridge.+ var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;-process.on = noop;-process.addListener = noop;-process.once = noop;-process.off = noop;-process.removeListener = noop;-process.removeAllListeners = noop;-process.emit = noop;+ console.info(+ "Data channel new dominant speaker event: ",+ dominantSpeakerEndpoint);+ eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);+ }+ else if ("InLastNChangeEvent" === colibriClass) {+ var oldValue = obj.oldValue;+ var newValue = obj.newValue;+ // Make sure that oldValue and newValue are of type boolean.+ var type;-process.binding = function (name) {- throw new Error('process.binding is not supported');-};+ if ((type = typeof oldValue) !== 'boolean') {+ if (type === 'string') {+ oldValue = (oldValue == "true");+ } else {+ oldValue = new Boolean(oldValue).valueOf();+ }+ }+ if ((type = typeof newValue) !== 'boolean') {+ if (type === 'string') {+ newValue = (newValue == "true");+ } else {+ newValue = new Boolean(newValue).valueOf();+ }+ }-// TODO(shtylman)-process.cwd = function () { return '/' };-process.chdir = function (dir) {- throw new Error('process.chdir is not supported');-};-process.umask = function() { return 0; };+ eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);+ }+ else if ("LastNEndpointsChangeEvent" === colibriClass) {+ // The new/latest list of last-n endpoint IDs.+ var lastNEndpoints = obj.lastNEndpoints;+ // The list of endpoint IDs which are entering the list of+ // last-n at this time i.e. were not in the old list of last-n+ // endpoint IDs.+ var endpointsEnteringLastN = obj.endpointsEnteringLastN;-},{}],3:[function(require,module,exports){-/* jshint -W117 */-/* application specific logic */+ console.log(+ "Data channel new last-n event: ",+ lastNEndpoints, endpointsEnteringLastN, obj);+ eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,+ lastNEndpoints, endpointsEnteringLastN, obj);+ }+ else {+ console.debug("Data channel JSON-formatted message: ", obj);+ }+ }+ };-var APP =-{- init: function () {- this.UI = require("./modules/UI/UI");- this.API = require("./modules/API/API");- this.connectionquality = require("./modules/connectionquality/connectionquality");- this.statistics = require("./modules/statistics/statistics");- this.RTC = require("./modules/RTC/RTC");- this.desktopsharing = require("./modules/desktopsharing/desktopsharing");- this.xmpp = require("./modules/xmpp/xmpp");- this.keyboardshortcut = require("./modules/keyboardshortcut/keyboardshortcut");- this.translation = require("./modules/translation/translation");- this.settings = require("./modules/settings/Settings");- this.DTMF = require("./modules/DTMF/DTMF");- this.members = require("./modules/members/MemberList");- }-};+ dataChannel.onclose = function () {+ console.info("The Data Channel closed", dataChannel);+ var idx = _dataChannels.indexOf(dataChannel);+ if (idx > -1)+ _dataChannels = _dataChannels.splice(idx, 1);+ };+ _dataChannels.push(dataChannel);+ },-function init() {+ /**+ * Binds "ondatachannel" event listener to given PeerConnection instance.+ * @param peerConnection WebRTC peer connection instance.+ */+ init: function (peerConnection, emitter) {+ if(!config.openSctp)+ return;- APP.desktopsharing.init();- APP.RTC.start();- APP.xmpp.start();- APP.statistics.start();- APP.connectionquality.init();- APP.keyboardshortcut.init();- APP.members.start();-}+ peerConnection.ondatachannel = this.onDataChannel;+ eventEmitter = emitter;+ // Sample code for opening new data channel from Jitsi Meet to the bridge.+ // Although it's not a requirement to open separate channels from both bridge+ // and peer as single channel can be used for sending and receiving data.+ // So either channel opened by the bridge or the one opened here is enough+ // for communication with the bridge.+ /*var dataChannelOptions =+ {+ reliable: true+ };+ var dataChannel+ = peerConnection.createDataChannel("myChannel", dataChannelOptions);-$(document).ready(function () {+ // Can be used only when is in open state+ dataChannel.onopen = function ()+ {+ dataChannel.send("My channel !!!");+ };+ dataChannel.onmessage = function (event)+ {+ var msgData = event.data;+ console.info("Got My Data Channel Message:", msgData, dataChannel);+ };*/+ },+ handleSelectedEndpointEvent: onSelectedEndpointChanged,+ handlePinnedEndpointEvent: onPinnedEndpointChanged+};- var URLProcessor = require("./modules/URLProcessor/URLProcessor");- URLProcessor.setConfigParametersFromUrl();- APP.init();+function onSelectedEndpointChanged(userResource) {+ console.log('selected endpoint changed: ', userResource);+ if (_dataChannels && _dataChannels.length != 0) {+ _dataChannels.some(function (dataChannel) {+ if (dataChannel.readyState == 'open') {+ console.log('sending selected endpoint changed ' ++ 'notification to the bridge: ', userResource);+ dataChannel.send(JSON.stringify({+ 'colibriClass': 'SelectedEndpointChangedEvent',+ 'selectedEndpoint':+ (!userResource || userResource === null)?+ null : userResource+ }));- APP.translation.init();+ return true;+ }+ });+ }+}- if(APP.API.isEnabled())- APP.API.init();-- APP.UI.start(init);--});+function onPinnedEndpointChanged(userResource) {+ console.log('pinned endpoint changed: ', userResource);+ if (_dataChannels && _dataChannels.length != 0) {+ _dataChannels.some(function (dataChannel) {+ if (dataChannel.readyState == 'open') {+ dataChannel.send(JSON.stringify({+ 'colibriClass': 'PinnedEndpointChangedEvent',+ 'pinnedEndpoint':+ (!userResource || userResource == null)?+ null : userResource+ }));-$(window).bind('beforeunload', function () {- if(APP.API.isEnabled())- APP.API.dispose();-});+ return true;+ }+ });+ }+}-module.exports = APP;+module.exports = DataChannels;-},{"./modules/API/API":4,"./modules/DTMF/DTMF":5,"./modules/RTC/RTC":9,"./modules/UI/UI":13,"./modules/URLProcessor/URLProcessor":44,"./modules/connectionquality/connectionquality":45,"./modules/desktopsharing/desktopsharing":46,"./modules/keyboardshortcut/keyboardshortcut":47,"./modules/members/MemberList":48,"./modules/settings/Settings":49,"./modules/statistics/statistics":53,"./modules/translation/translation":54,"./modules/xmpp/xmpp":70}],4:[function(require,module,exports){+},{"../../service/RTC/RTCEvents":152}],5:[function(require,module,exports){/* global APP */-/**- * Implements API class that communicates with external api class- * and provides interface to access Jitsi Meet features by external- * applications that embed Jitsi Meet- */--var XMPPEvents = require("../../service/xmpp/XMPPEvents");+var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");+var RTCEvents = require("../../service/RTC/RTCEvents");+var RTCBrowserType = require("./RTCBrowserType");/**- * List of the available commands.- * @type {{- * displayName: inputDisplayNameHandler,- * toggleAudio: toggleAudio,- * toggleVideo: toggleVideo,- * toggleFilmStrip: toggleFilmStrip,- * toggleChat: toggleChat,- * toggleContactList: toggleContactList- * }}+ * This implements 'onended' callback normally fired by WebRTC after the stream+ * is stopped. There is no such behaviour yet in FF, so we have to add it.+ * @param stream original WebRTC stream object to which 'onended' handling+ * will be added.*/-var commands = {};+function implementOnEndedHandling(stream) {+ var originalStop = stream.stop;+ stream.stop = function () {+ originalStop.apply(stream);+ if (!stream.ended) {+ stream.ended = true;+ stream.onended();+ }+ };+}-function initCommands() {- commands = {- displayName: APP.UI.inputDisplayNameHandler,- toggleAudio: APP.UI.toggleAudio,- toggleVideo: APP.UI.toggleVideo,- toggleFilmStrip: APP.UI.toggleFilmStrip,- toggleChat: APP.UI.toggleChat,- toggleContactList: APP.UI.toggleContactList+function LocalStream(stream, type, eventEmitter, videoType, isGUMStream) {+ this.stream = stream;+ this.eventEmitter = eventEmitter;+ this.type = type;+ this.videoType = videoType;+ this.isGUMStream = true;+ if(isGUMStream === false)+ this.isGUMStream = isGUMStream;+ var self = this;+ if(type == "audio") {+ this.getTracks = function () {+ return self.stream.getAudioTracks();+ };+ } else {+ this.getTracks = function () {+ return self.stream.getVideoTracks();+ };+ }++ this.stream.onended = function () {+ self.streamEnded();};+ if (RTCBrowserType.isFirefox()) {+ implementOnEndedHandling(this.stream);+ }}+LocalStream.prototype.streamEnded = function () {+ this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);+};-/**- * Maps the supported events and their status- * (true it the event is enabled and false if it is disabled)- * @type {{- * incomingMessage: boolean,- * outgoingMessage: boolean,- * displayNameChange: boolean,- * participantJoined: boolean,- * participantLeft: boolean- * }}- */-var events = {- incomingMessage: false,- outgoingMessage:false,- displayNameChange: false,- participantJoined: false,- participantLeft: false+LocalStream.prototype.getOriginalStream = function()+{+ return this.stream;};-var displayName = {};+LocalStream.prototype.isAudioStream = function () {+ return this.type === "audio";+};-/**- * Processes commands from external application.- * @param message the object with the command- */-function processCommand(message) {- if (message.action != "execute") {- console.error("Unknown action of the message");- return;- }- for (var key in message) {- if(commands[key])- commands[key].apply(null, message[key]);- }-}+LocalStream.prototype.setMute = function (mute)+{+ var isAudio = this.isAudioStream();+ var eventType = isAudio ? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE;-/**- * Processes events objects from external applications- * @param event the event- */-function processEvent(event) {- if (!event.action) {- console.error("Event with no action is received.");- return;+ if ((window.location.protocol != "https:" && this.isGUMStream) ||+ (isAudio && this.isGUMStream) || this.videoType === "screen" ||+ // FIXME FF does not support 'removeStream' method used to mute+ RTCBrowserType.isFirefox()) {++ var tracks = this.getTracks();+ for (var idx = 0; idx < tracks.length; idx++) {+ tracks[idx].enabled = !mute;+ }+ this.eventEmitter.emit(eventType, mute);+ } else {+ if (mute) {+ APP.xmpp.removeStream(this.stream);+ this.stream.stop();+ this.eventEmitter.emit(eventType, true);+ } else {+ var self = this;+ APP.RTC.rtcUtils.obtainAudioAndVideoPermissions(+ (this.isAudioStream() ? ["audio"] : ["video"]),+ function (stream) {+ if (isAudio) {+ APP.RTC.changeLocalAudio(stream,+ function () {+ self.eventEmitter.emit(eventType, false);+ });+ } else {+ APP.RTC.changeLocalVideo(stream, false,+ function () {+ self.eventEmitter.emit(eventType, false);+ });+ }+ });+ }}+};- var i = 0;- switch(event.action) {- case "add":- for (; i < event.events.length; i++) {- events[event.events[i]] = true;- }- break;- case "remove":- for (; i < event.events.length; i++) {- events[event.events[i]] = false;- }- break;- default:- console.error("Unknown action for event.");+LocalStream.prototype.isMuted = function () {+ var tracks = [];+ if (this.isAudioStream()) {+ tracks = this.stream.getAudioTracks();+ } else {+ if (this.stream.ended)+ return true;+ tracks = this.stream.getVideoTracks();}-}+ for (var idx = 0; idx < tracks.length; idx++) {+ if(tracks[idx].enabled)+ return false;+ }+ return true;+};-/**- * Sends message to the external application.- * @param object- */-function sendMessage(object) {- window.parent.postMessage(JSON.stringify(object), "*");-}+LocalStream.prototype.getId = function () {+ return this.stream.getTracks()[0].id;+};++module.exports = LocalStream;++},{"../../service/RTC/RTCEvents":152,"../../service/RTC/StreamEventTypes.js":154,"./RTCBrowserType":8}],6:[function(require,module,exports){+var MediaStreamType = require("../../service/RTC/MediaStreamTypes");/**- * Processes a message event from the external application- * @param event the message event+ * Creates a MediaStream object for the given data, session id and ssrc.+ * It is a wrapper class for the MediaStream.+ *+ * @param data the data object from which we obtain the stream,+ * the peerjid, etc.+ * @param sid the session id+ * @param ssrc the ssrc corresponding to this MediaStream+ *+ * @constructor*/-function processMessage(event) {- var message;- try {- message = JSON.parse(event.data);- } catch (e) {}-- if(!message.type)- return;- switch (message.type) {- case "command":- processCommand(message);- break;- case "event":- processEvent(message);- break;- default:- console.error("Unknown type of the message");- return;- }-}+function MediaStream(data, sid, ssrc, browser, eventEmitter) {-function setupListeners() {- APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, function (from) {- API.triggerEvent("participantJoined", {jid: from});- });- APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid, stamp) {- if (from != myjid)- API.triggerEvent("incomingMessage",- {"from": from, "nick": nick, "message": txt, "stamp": stamp});- });- APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, function (jid) {- API.triggerEvent("participantLeft", {jid: jid});- });- APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {- var name = displayName[jid];- if(!name || name != newDisplayName) {- API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});- displayName[jid] = newDisplayName;- }- });- APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {- APP.API.triggerEvent("outgoingMessage", {"message": body});- });-}+ // XXX(gp) to minimize headaches in the future, we should build our+ // abstractions around tracks and not streams. ORTC is track based API.+ // Mozilla expects m-lines to represent media tracks.+ //+ // Practically, what I'm saying is that we should have a MediaTrack class+ // and not a MediaStream class.+ //+ // Also, we should be able to associate multiple SSRCs with a MediaTrack as+ // a track might have an associated RTX and FEC sources.-var API = {- /**- * Check whether the API should be enabled or not.- * @returns {boolean}- */- isEnabled: function () {- var hash = location.hash;- if (hash && hash.indexOf("external") > -1 && window.postMessage)- return true;- return false;- },- /**- * Initializes the APIConnector. Setups message event listeners that will- * receive information from external applications that embed Jitsi Meet.- * It also sends a message to the external application that APIConnector- * is initialized.- */- init: function () {- initCommands();- if (window.addEventListener) {- window.addEventListener('message',- processMessage, false);- }- else {- window.attachEvent('onmessage', processMessage);- }- sendMessage({type: "system", loaded: true});- setupListeners();- },- /**- * Checks whether the event is enabled ot not.- * @param name the name of the event.- * @returns {*}- */- isEventEnabled: function (name) {- return events[name];- },+ this.sid = sid;+ this.stream = data.stream;+ this.peerjid = data.peerjid;+ this.videoType = data.videoType;+ this.ssrc = ssrc;+ this.type = (this.stream.getVideoTracks().length > 0)?+ MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;+ this.muted = false;+ this.eventEmitter = eventEmitter;+}- /**- * Sends event object to the external application that has been subscribed- * for that event.- * @param name the name event- * @param object data associated with the event- */- triggerEvent: function (name, object) {- if(this.isEnabled() && this.isEventEnabled(name))- sendMessage({- type: "event", action: "result", event: name, result: object});- },- /**- * Removes the listeners.- */- dispose: function () {- if(window.removeEventListener) {- window.removeEventListener("message",- processMessage, false);- }- else {- window.detachEvent('onmessage', processMessage);- }- }+MediaStream.prototype.getOriginalStream = function() {+ return this.stream;};-module.exports = API;-},{"../../service/xmpp/XMPPEvents":120}],5:[function(require,module,exports){-/* global APP */--/**- * A module for sending DTMF tones.- */-var DTMFSender;-var initDtmfSender = function() {- // TODO: This needs to reset this if the peerconnection changes- // (e.g. the call is re-made)- if (DTMFSender)- return;-- var localAudio = APP.RTC.localAudio;- if (localAudio && localAudio.getTracks().length > 0)- {- var peerconnection- = APP.xmpp.getConnection().jingle.activecall.peerconnection;- if (peerconnection) {- DTMFSender =- peerconnection.peerconnection- .createDTMFSender(localAudio.getTracks()[0]);- console.log("Initialized DTMFSender");- }- else {- console.log("Failed to initialize DTMFSender: no PeerConnection.");- }- }- else {- console.log("Failed to initialize DTMFSender: no audio track.");- }+MediaStream.prototype.setMute = function (value) {+ this.stream.muted = value;+ this.muted = value;};-var DTMF = {- sendTones: function (tones, duration, pause) {- if (!DTMFSender)- initDtmfSender();+module.exports = MediaStream;- if (DTMFSender){- DTMFSender.insertDTMF(tones,- (duration || 200),- (pause || 200));- }- }-};+},{"../../service/RTC/MediaStreamTypes":151}],7:[function(require,module,exports){+/* global APP */+var EventEmitter = require("events");+var RTCBrowserType = require("./RTCBrowserType");+var RTCUtils = require("./RTCUtils.js");+var LocalStream = require("./LocalStream.js");+var DataChannels = require("./DataChannels");+var MediaStream = require("./MediaStream.js");+var DesktopSharingEventTypes+ = require("../../service/desktopsharing/DesktopSharingEventTypes");+var MediaStreamType = require("../../service/RTC/MediaStreamTypes");+var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");+var RTCEvents = require("../../service/RTC/RTCEvents.js");+var XMPPEvents = require("../../service/xmpp/XMPPEvents");+var UIEvents = require("../../service/UI/UIEvents");-module.exports = DTMF;+var eventEmitter = new EventEmitter();-},{}],6:[function(require,module,exports){-/* global config, APP, Strophe */+function getMediaStreamUsage()+{+ var result = {+ audio: true,+ video: true+ };-// cache datachannels to avoid garbage collection-// https://code.google.com/p/chromium/issues/detail?id=405545-var RTCEvents = require("../../service/RTC/RTCEvents");+ /** There are some issues with the desktop sharing+ * when this property is enabled.+ * WARNING: We must change the implementation to start video/audio if we+ * receive from the focus that the peer is not muted.-var _dataChannels = [];-var eventEmitter = null;+ var isSecureConnection = window.location.protocol == "https:";+ if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)+ {+ result = {+ audio: false,+ video: false+ };-var DataChannels = {- /**- * Callback triggered by PeerConnection when new data channel is opened- * on the bridge.- * @param event the event info object.- */- onDataChannel: function (event) {- var dataChannel = event.channel;+ }+ **/- dataChannel.onopen = function () {- console.info("Data channel opened by the Videobridge!", dataChannel);+ return result;+}- // Code sample for sending string and/or binary data- // Sends String message to the bridge- //dataChannel.send("Hello bridge!");- // Sends 12 bytes binary message to the bridge- //dataChannel.send(new ArrayBuffer(12));+var RTC = {+ rtcUtils: null,+ devices: {+ audio: true,+ video: true+ },+ localStreams: [],+ remoteStreams: {},+ localAudio: null,+ localVideo: null,+ addStreamListener: function (listener, eventType) {+ eventEmitter.on(eventType, listener);+ },+ addListener: function (type, listener) {+ eventEmitter.on(type, listener);+ },+ removeStreamListener: function (listener, eventType) {+ if(!(eventType instanceof StreamEventTypes))+ throw "Illegal argument";- eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);- };+ eventEmitter.removeListener(eventType, listener);+ },+ createLocalStream: function (stream, type, change, videoType, isMuted, isGUMStream) {- dataChannel.onerror = function (error) {- console.error("Data Channel Error:", error, dataChannel);- };+ var localStream = new LocalStream(stream, type, eventEmitter, videoType, isGUMStream);+ //in firefox we have only one stream object+ if(this.localStreams.length == 0 ||+ this.localStreams[0].getOriginalStream() != stream)+ this.localStreams.push(localStream);+ if(isMuted === true)+ localStream.setMute(true);- dataChannel.onmessage = function (event) {- var data = event.data;- // JSON- var obj;+ if(type == "audio") {+ this.localAudio = localStream;+ } else {+ this.localVideo = localStream;+ }+ var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;+ if(change)+ eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;- try {- obj = JSON.parse(data);- }- catch (e) {- console.error(- "Failed to parse data channel message as JSON: ",- data,- dataChannel);+ eventEmitter.emit(eventType, localStream, isMuted);+ return localStream;+ },+ removeLocalStream: function (stream) {+ for(var i = 0; i < this.localStreams.length; i++) {+ if(this.localStreams[i].getOriginalStream() === stream) {+ delete this.localStreams[i];+ return;}- if (('undefined' !== typeof(obj)) && (null !== obj)) {- var colibriClass = obj.colibriClass;+ }+ },+ createRemoteStream: function (data, sid, thessrc) {+ var remoteStream = new MediaStream(data, sid, thessrc,+ RTCBrowserType.getBrowserType(), eventEmitter);+ var jid = data.peerjid || APP.xmpp.myJid();+ if(!this.remoteStreams[jid]) {+ this.remoteStreams[jid] = {};+ }+ this.remoteStreams[jid][remoteStream.type]= remoteStream;+ eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);+ return remoteStream;+ },+ getPCConstraints: function () {+ return this.rtcUtils.pc_constraints;+ },+ getUserMediaWithConstraints:function(um, success_callback,+ failure_callback, resolution,+ bandwidth, fps, desktopStream)+ {+ return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,+ failure_callback, resolution, bandwidth, fps, desktopStream);+ },+ attachMediaStream: function (elSelector, stream) {+ this.rtcUtils.attachMediaStream(elSelector, stream);+ },+ getStreamID: function (stream) {+ return this.rtcUtils.getStreamID(stream);+ },+ getVideoSrc: function (element) {+ return this.rtcUtils.getVideoSrc(element);+ },+ setVideoSrc: function (element, src) {+ this.rtcUtils.setVideoSrc(element, src);+ },+ getVideoElementName: function () {+ return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';+ },+ dispose: function() {+ if (this.rtcUtils) {+ this.rtcUtils = null;+ }+ },+ stop: function () {+ this.dispose();+ },+ start: function () {+ var self = this;+ APP.desktopsharing.addListener(+ function (stream, isUsingScreenStream, callback) {+ self.changeLocalVideo(stream, isUsingScreenStream, callback);+ }, DesktopSharingEventTypes.NEW_STREAM_CREATED);+ APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {+ DataChannels.init(event.peerconnection, eventEmitter);+ });+ APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,+ DataChannels.handleSelectedEndpointEvent);+ APP.UI.addListener(UIEvents.PINNED_ENDPOINT,+ DataChannels.handlePinnedEndpointEvent);- if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {- // Endpoint ID from the Videobridge.- var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;+ // In case of IE we continue from 'onReady' callback+ // passed to RTCUtils constructor. It will be invoked by Temasys plugin+ // once it is initialized.+ var onReady = function () {+ eventEmitter.emit(RTCEvents.RTC_READY, true);+ self.rtcUtils.obtainAudioAndVideoPermissions(+ null, null, getMediaStreamUsage());+ };- console.info(- "Data channel new dominant speaker event: ",- dominantSpeakerEndpoint);- eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);- }- else if ("InLastNChangeEvent" === colibriClass) {- var oldValue = obj.oldValue;- var newValue = obj.newValue;- // Make sure that oldValue and newValue are of type boolean.- var type;+ this.rtcUtils = new RTCUtils(this, onReady);- if ((type = typeof oldValue) !== 'boolean') {- if (type === 'string') {- oldValue = (oldValue == "true");- } else {- oldValue = new Boolean(oldValue).valueOf();- }- }- if ((type = typeof newValue) !== 'boolean') {- if (type === 'string') {- newValue = (newValue == "true");- } else {- newValue = new Boolean(newValue).valueOf();- }- }+ // Call onReady() if Temasys plugin is not used+ if (!RTCBrowserType.isTemasysPluginUsed()) {+ onReady();+ }+ },+ muteRemoteVideoStream: function (jid, value) {+ var stream;- eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);- }- else if ("LastNEndpointsChangeEvent" === colibriClass) {- // The new/latest list of last-n endpoint IDs.- var lastNEndpoints = obj.lastNEndpoints;- // The list of endpoint IDs which are entering the list of- // last-n at this time i.e. were not in the old list of last-n- // endpoint IDs.- var endpointsEnteringLastN = obj.endpointsEnteringLastN;+ if(this.remoteStreams[jid] &&+ this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {+ stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];+ }- console.log(- "Data channel new last-n event: ",- lastNEndpoints, endpointsEnteringLastN, obj);- eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,- lastNEndpoints, endpointsEnteringLastN, obj);- }- else {- console.debug("Data channel JSON-formatted message: ", obj);- }- }- };+ if(!stream)+ return true;- dataChannel.onclose = function () {- console.info("The Data Channel closed", dataChannel);- var idx = _dataChannels.indexOf(dataChannel);- if (idx > -1)- _dataChannels = _dataChannels.splice(idx, 1);- };- _dataChannels.push(dataChannel);+ if (value != stream.muted) {+ stream.setMute(value);+ return true;+ }+ return false;},+ switchVideoStreams: function (new_stream) {+ this.localVideo.stream = new_stream;- /**- * Binds "ondatachannel" event listener to given PeerConnection instance.- * @param peerConnection WebRTC peer connection instance.- */- init: function (peerConnection, emitter) {- if(!config.openSctp)- return;-- peerConnection.ondatachannel = this.onDataChannel;- eventEmitter = emitter;-- // Sample code for opening new data channel from Jitsi Meet to the bridge.- // Although it's not a requirement to open separate channels from both bridge- // and peer as single channel can be used for sending and receiving data.- // So either channel opened by the bridge or the one opened here is enough- // for communication with the bridge.- /*var dataChannelOptions =- {- reliable: true- };- var dataChannel- = peerConnection.createDataChannel("myChannel", dataChannelOptions);+ this.localStreams = [];- // Can be used only when is in open state- dataChannel.onopen = function ()- {- dataChannel.send("My channel !!!");- };- dataChannel.onmessage = function (event)- {- var msgData = event.data;- console.info("Got My Data Channel Message:", msgData, dataChannel);- };*/+ //in firefox we have only one stream object+ if (this.localAudio.getOriginalStream() != new_stream)+ this.localStreams.push(this.localAudio);+ this.localStreams.push(this.localVideo);},- handleSelectedEndpointEvent: onSelectedEndpointChanged,- handlePinnedEndpointEvent: onPinnedEndpointChanged-};+ changeLocalVideo: function (stream, isUsingScreenStream, callback) {+ var oldStream = this.localVideo.getOriginalStream();+ var type = (isUsingScreenStream ? "screen" : "camera");+ var localCallback = callback;+ if(this.localVideo.isMuted() && this.localVideo.videoType !== type) {+ localCallback = function() {+ APP.xmpp.setVideoMute(false, function(mute) {+ eventEmitter.emit(RTCEvents.VIDEO_MUTE, mute);+ });++ callback();+ };+ }+ // FIXME: Workaround for FF/IE/Safari+ if (stream && stream.videoStream) {+ stream = stream.videoStream;+ }+ var videoStream = this.rtcUtils.createStream(stream, true);+ this.localVideo = this.createLocalStream(videoStream, "video", true, type);+ // Stop the stream to trigger onended event for old stream+ oldStream.stop();-function onSelectedEndpointChanged(userResource) {- console.log('selected endpoint changed: ', userResource);- if (_dataChannels && _dataChannels.length != 0) {- _dataChannels.some(function (dataChannel) {- if (dataChannel.readyState == 'open') {- console.log('sending selected endpoint changed ' +- 'notification to the bridge: ', userResource);- dataChannel.send(JSON.stringify({- 'colibriClass': 'SelectedEndpointChangedEvent',- 'selectedEndpoint':- (!userResource || userResource === null)?- null : userResource- }));+ this.switchVideoStreams(videoStream, oldStream);- return true;+ APP.xmpp.switchStreams(videoStream, oldStream,localCallback);+ },+ changeLocalAudio: function (stream, callback) {+ var oldStream = this.localAudio.getOriginalStream();+ var newStream = this.rtcUtils.createStream(stream);+ this.localAudio = this.createLocalStream(newStream, "audio", true);+ // Stop the stream to trigger onended event for old stream+ oldStream.stop();+ APP.xmpp.switchStreams(newStream, oldStream, callback, true);+ },+ isVideoMuted: function (jid) {+ if (jid === APP.xmpp.myJid()) {+ var localVideo = APP.RTC.localVideo;+ return (!localVideo || localVideo.isMuted());+ } else {+ if (!APP.RTC.remoteStreams[jid] ||+ !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {+ return null;}- });- }-}--function onPinnedEndpointChanged(userResource) {- console.log('pinned endpoint changed: ', userResource);- if (_dataChannels && _dataChannels.length != 0) {- _dataChannels.some(function (dataChannel) {- if (dataChannel.readyState == 'open') {- dataChannel.send(JSON.stringify({- 'colibriClass': 'PinnedEndpointChangedEvent',- 'pinnedEndpoint':- (!userResource || userResource == null)?- null : userResource- }));+ return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;+ }+ },+ setVideoMute: function (mute, callback, options) {+ if (!this.localVideo)+ return;- return true;- }- });+ if (mute == APP.RTC.localVideo.isMuted())+ {+ APP.xmpp.sendVideoInfoPresence(mute);+ if (callback)+ callback(mute);+ }+ else+ {+ APP.RTC.localVideo.setMute(mute);+ APP.xmpp.setVideoMute(+ mute,+ callback,+ options);+ }+ },+ setDeviceAvailability: function (devices) {+ if(!devices)+ return;+ if(devices.audio === true || devices.audio === false)+ this.devices.audio = devices.audio;+ if(devices.video === true || devices.video === false)+ this.devices.video = devices.video;+ eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);}-}--module.exports = DataChannels;-+};-},{"../../service/RTC/RTCEvents":111}],7:[function(require,module,exports){-/* global APP */-var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");-var RTCEvents = require("../../service/RTC/RTCEvents");-var RTCBrowserType = require("./RTCBrowserType");+module.exports = RTC;-/**- * This implements 'onended' callback normally fired by WebRTC after the stream- * is stopped. There is no such behaviour yet in FF, so we have to add it.- * @param stream original WebRTC stream object to which 'onended' handling- * will be added.- */-function implementOnEndedHandling(stream) {- var originalStop = stream.stop;- stream.stop = function () {- originalStop.apply(stream);- if (!stream.ended) {- stream.ended = true;- stream.onended();- }- };-}+},{"../../service/RTC/MediaStreamTypes":151,"../../service/RTC/RTCEvents.js":152,"../../service/RTC/StreamEventTypes.js":154,"../../service/UI/UIEvents":155,"../../service/desktopsharing/DesktopSharingEventTypes":158,"../../service/xmpp/XMPPEvents":161,"./DataChannels":4,"./LocalStream.js":5,"./MediaStream.js":6,"./RTCBrowserType":8,"./RTCUtils.js":9,"events":162}],8:[function(require,module,exports){-function LocalStream(stream, type, eventEmitter, videoType, isGUMStream) {- this.stream = stream;- this.eventEmitter = eventEmitter;- this.type = type;- this.videoType = videoType;- this.isGUMStream = true;- if(isGUMStream === false)- this.isGUMStream = isGUMStream;- var self = this;- if(type == "audio") {- this.getTracks = function () {- return self.stream.getAudioTracks();- };- } else {- this.getTracks = function () {- return self.stream.getVideoTracks();- };- }+var currentBrowser;- this.stream.onended = function () {- self.streamEnded();- };- if (RTCBrowserType.isFirefox()) {- implementOnEndedHandling(this.stream);- }-}+var browserVersion;-LocalStream.prototype.streamEnded = function () {- this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);-};+var RTCBrowserType = {-LocalStream.prototype.getOriginalStream = function()-{- return this.stream;-};+ RTC_BROWSER_CHROME: "rtc_browser.chrome",-LocalStream.prototype.isAudioStream = function () {- return this.type === "audio";-};+ RTC_BROWSER_OPERA: "rtc_browser.opera",-LocalStream.prototype.setMute = function (mute)-{- var isAudio = this.isAudioStream();- var eventType = isAudio ? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE;+ RTC_BROWSER_FIREFOX: "rtc_browser.firefox",- if ((window.location.protocol != "https:" && this.isGUMStream) ||- (isAudio && this.isGUMStream) || this.videoType === "screen" ||- // FIXME FF does not support 'removeStream' method used to mute- RTCBrowserType.isFirefox()) {+ RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",- var tracks = this.getTracks();- for (var idx = 0; idx < tracks.length; idx++) {- tracks[idx].enabled = !mute;- }- this.eventEmitter.emit(eventType, mute);- } else {- if (mute) {- APP.xmpp.removeStream(this.stream);- this.stream.stop();- this.eventEmitter.emit(eventType, true);- } else {- var self = this;- APP.RTC.rtcUtils.obtainAudioAndVideoPermissions(- (this.isAudioStream() ? ["audio"] : ["video"]),- function (stream) {- if (isAudio) {- APP.RTC.changeLocalAudio(stream,- function () {- self.eventEmitter.emit(eventType, false);- });- } else {- APP.RTC.changeLocalVideo(stream, false,- function () {- self.eventEmitter.emit(eventType, false);- });- }- });- }- }-};+ RTC_BROWSER_SAFARI: "rtc_browser.safari",-LocalStream.prototype.isMuted = function () {- var tracks = [];- if (this.isAudioStream()) {- tracks = this.stream.getAudioTracks();- } else {- if (this.stream.ended)- return true;- tracks = this.stream.getVideoTracks();- }- for (var idx = 0; idx < tracks.length; idx++) {- if(tracks[idx].enabled)- return false;- }- return true;-};+ getBrowserType: function () {+ return currentBrowser;+ },-LocalStream.prototype.getId = function () {- return this.stream.getTracks()[0].id;-};+ isChrome: function () {+ return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;+ },-module.exports = LocalStream;+ isOpera: function () {+ return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;+ },+ isFirefox: function () {+ return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;+ },-},{"../../service/RTC/RTCEvents":111,"../../service/RTC/StreamEventTypes.js":113,"./RTCBrowserType":10}],8:[function(require,module,exports){-var MediaStreamType = require("../../service/RTC/MediaStreamTypes");+ isIExplorer: function () {+ return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;+ },-/**- * Creates a MediaStream object for the given data, session id and ssrc.- * It is a wrapper class for the MediaStream.- *- * @param data the data object from which we obtain the stream,- * the peerjid, etc.- * @param sid the session id- * @param ssrc the ssrc corresponding to this MediaStream- *- * @constructor- */-function MediaStream(data, sid, ssrc, browser, eventEmitter) {+ isSafari: function () {+ return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;+ },+ isTemasysPluginUsed: function () {+ return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();+ },+ getFirefoxVersion: function () {+ return RTCBrowserType.isFirefox() ? browserVersion : null;+ },- // XXX(gp) to minimize headaches in the future, we should build our- // abstractions around tracks and not streams. ORTC is track based API.- // Mozilla expects m-lines to represent media tracks.- //- // Practically, what I'm saying is that we should have a MediaTrack class- // and not a MediaStream class.- //- // Also, we should be able to associate multiple SSRCs with a MediaTrack as- // a track might have an associated RTX and FEC sources.+ getChromeVersion: function () {+ return RTCBrowserType.isChrome() ? browserVersion : null;+ },- this.sid = sid;- this.stream = data.stream;- this.peerjid = data.peerjid;- this.videoType = data.videoType;- this.ssrc = ssrc;- this.type = (this.stream.getVideoTracks().length > 0)?- MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;- this.muted = false;- this.eventEmitter = eventEmitter;-}+ usesPlanB: function() {+ return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||+ RTCBrowserType.isTemasysPluginUsed();+ },+ usesUnifiedPlan: function() {+ return RTCBrowserType.isFirefox();+ }-MediaStream.prototype.getOriginalStream = function() {- return this.stream;+ // Add version getters for other browsers when needed};-MediaStream.prototype.setMute = function (value) {- this.stream.muted = value;- this.muted = value;-};+// detectOpera() must be called before detectChrome() !!!+// otherwise Opera wil be detected as Chrome+function detectChrome() {+ if (navigator.webkitGetUserMedia) {+ currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;+ var userAgent = navigator.userAgent.toLowerCase();+ // We can assume that user agent is chrome, because it's+ // enforced when 'ext' streaming method is set+ var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);+ console.log("This appears to be Chrome, ver: " + ver);+ return ver;+ }+ return null;+}-module.exports = MediaStream;--},{"../../service/RTC/MediaStreamTypes":110}],9:[function(require,module,exports){-/* global APP */-var EventEmitter = require("events");-var RTCBrowserType = require("./RTCBrowserType");-var RTCUtils = require("./RTCUtils.js");-var LocalStream = require("./LocalStream.js");-var DataChannels = require("./DataChannels");-var MediaStream = require("./MediaStream.js");-var DesktopSharingEventTypes- = require("../../service/desktopsharing/DesktopSharingEventTypes");-var MediaStreamType = require("../../service/RTC/MediaStreamTypes");-var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");-var RTCEvents = require("../../service/RTC/RTCEvents.js");-var XMPPEvents = require("../../service/xmpp/XMPPEvents");-var UIEvents = require("../../service/UI/UIEvents");--var eventEmitter = new EventEmitter();+function detectOpera() {+ var userAgent = navigator.userAgent;+ if (userAgent.match(/Opera|OPR/)) {+ currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;+ var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];+ console.info("This appears to be Opera, ver: " + version);+ return version;+ }+ return null;+}+function detectFirefox() {+ if (navigator.mozGetUserMedia) {+ currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;+ var version = parseInt(+ navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);+ console.log('This appears to be Firefox, ver: ' + version);+ return version;+ }+ return null;+}-function getMediaStreamUsage()-{- var result = {- audio: true,- video: true- };+function detectSafari() {+ if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {+ currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;+ console.info("This appears to be Safari");+ // FIXME detect Safari version when needed+ return 1;+ }+ return null;+}- /** There are some issues with the desktop sharing- * when this property is enabled.- * WARNING: We must change the implementation to start video/audio if we- * receive from the focus that the peer is not muted.+function detectIE() {+ var version;+ var ua = window.navigator.userAgent;- var isSecureConnection = window.location.protocol == "https:";+ var msie = ua.indexOf('MSIE ');+ if (msie > 0) {+ // IE 10 or older => return version number+ version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);+ }- if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)- {- result = {- audio: false,- video: false- };+ var trident = ua.indexOf('Trident/');+ if (!version && trident > 0) {+ // IE 11 => return version number+ var rv = ua.indexOf('rv:');+ version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);+ }+ var edge = ua.indexOf('Edge/');+ if (!version && edge > 0) {+ // IE 12 => return version number+ version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);}- **/- return result;+ if (version) {+ currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;+ console.info("This appears to be IExplorer, ver: " + version);+ }+ return version;}-var RTC = {- rtcUtils: null,- devices: {- audio: true,- video: true- },- localStreams: [],- remoteStreams: {},- localAudio: null,- localVideo: null,- addStreamListener: function (listener, eventType) {- eventEmitter.on(eventType, listener);- },- addListener: function (type, listener) {- eventEmitter.on(type, listener);- },- removeStreamListener: function (listener, eventType) {- if(!(eventType instanceof StreamEventTypes))- throw "Illegal argument";+function detectBrowser() {+ var version;+ var detectors = [+ detectOpera,+ detectChrome,+ detectFirefox,+ detectIE,+ detectSafari+ ];+ // Try all browser detectors+ for (var i = 0; i < detectors.length; i++) {+ version = detectors[i]();+ if (version)+ return version;+ }+ console.error("Failed to detect browser type");+ return undefined;+}- eventEmitter.removeListener(eventType, listener);- },- createLocalStream: function (stream, type, change, videoType, isMuted, isGUMStream) {+browserVersion = detectBrowser();- var localStream = new LocalStream(stream, type, eventEmitter, videoType, isGUMStream);- //in firefox we have only one stream object- if(this.localStreams.length == 0 ||- this.localStreams[0].getOriginalStream() != stream)- this.localStreams.push(localStream);- if(isMuted === true)- localStream.setMute(true);+module.exports = RTCBrowserType;+},{}],9:[function(require,module,exports){+/* global config, require, attachMediaStream, getUserMedia */+var RTCBrowserType = require("./RTCBrowserType");+var Resolutions = require("../../service/RTC/Resolutions");+var AdapterJS = require("./adapter.screenshare");+var SDPUtil = require("../xmpp/SDPUtil");- if(type == "audio") {- this.localAudio = localStream;- } else {- this.localVideo = localStream;- }- var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;- if(change)- eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;+var currentResolution = null;- eventEmitter.emit(eventType, localStream, isMuted);- return localStream;- },- removeLocalStream: function (stream) {- for(var i = 0; i < this.localStreams.length; i++) {- if(this.localStreams[i].getOriginalStream() === stream) {- delete this.localStreams[i];- return;- }- }- },- createRemoteStream: function (data, sid, thessrc) {- var remoteStream = new MediaStream(data, sid, thessrc,- RTCBrowserType.getBrowserType(), eventEmitter);- var jid = data.peerjid || APP.xmpp.myJid();- if(!this.remoteStreams[jid]) {- this.remoteStreams[jid] = {};- }- this.remoteStreams[jid][remoteStream.type]= remoteStream;- eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);- return remoteStream;- },- getPCConstraints: function () {- return this.rtcUtils.pc_constraints;- },- getUserMediaWithConstraints:function(um, success_callback,- failure_callback, resolution,- bandwidth, fps, desktopStream)- {- return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,- failure_callback, resolution, bandwidth, fps, desktopStream);- },- attachMediaStream: function (elSelector, stream) {- this.rtcUtils.attachMediaStream(elSelector, stream);- },- getStreamID: function (stream) {- return this.rtcUtils.getStreamID(stream);- },- getVideoSrc: function (element) {- return this.rtcUtils.getVideoSrc(element);- },- setVideoSrc: function (element, src) {- this.rtcUtils.setVideoSrc(element, src);- },- getVideoElementName: function () {- return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';- },- dispose: function() {- if (this.rtcUtils) {- this.rtcUtils = null;+function getPreviousResolution(resolution) {+ if(!Resolutions[resolution])+ return null;+ var order = Resolutions[resolution].order;+ var res = null;+ var resName = null;+ for(var i in Resolutions) {+ var tmp = Resolutions[i];+ if(res == null || (res.order < tmp.order && tmp.order < order)) {+ resName = i;+ res = tmp;}- },- stop: function () {- this.dispose();- },- start: function () {- var self = this;- APP.desktopsharing.addListener(- function (stream, isUsingScreenStream, callback) {- self.changeLocalVideo(stream, isUsingScreenStream, callback);- }, DesktopSharingEventTypes.NEW_STREAM_CREATED);- APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {- DataChannels.init(event.peerconnection, eventEmitter);- });- APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,- DataChannels.handleSelectedEndpointEvent);- APP.UI.addListener(UIEvents.PINNED_ENDPOINT,- DataChannels.handlePinnedEndpointEvent);+ }+ return resName;+}- // In case of IE we continue from 'onReady' callback- // passed to RTCUtils constructor. It will be invoked by Temasys plugin- // once it is initialized.- var onReady = function () {- eventEmitter.emit(RTCEvents.RTC_READY, true);- self.rtcUtils.obtainAudioAndVideoPermissions(- null, null, getMediaStreamUsage());- };+function setResolutionConstraints(constraints, resolution, isAndroid) {- this.rtcUtils = new RTCUtils(this, onReady);+ if (Resolutions[resolution]) {+ constraints.video.mandatory.minWidth = Resolutions[resolution].width;+ constraints.video.mandatory.minHeight = Resolutions[resolution].height;+ }+ else if (isAndroid) {+ // FIXME can't remember if the purpose of this was to always request+ // low resolution on Android ? if yes it should be moved up front+ constraints.video.mandatory.minWidth = 320;+ constraints.video.mandatory.minHeight = 240;+ constraints.video.mandatory.maxFrameRate = 15;+ }- // Call onReady() if Temasys plugin is not used- if (!RTCBrowserType.isTemasysPluginUsed()) {- onReady();- }- },- muteRemoteVideoStream: function (jid, value) {- var stream;-- if(this.remoteStreams[jid] &&- this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {- stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];- }+ if (constraints.video.mandatory.minWidth)+ constraints.video.mandatory.maxWidth =+ constraints.video.mandatory.minWidth;+ if (constraints.video.mandatory.minHeight)+ constraints.video.mandatory.maxHeight =+ constraints.video.mandatory.minHeight;+}- if(!stream)- return true;+function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)+{+ var constraints = {audio: false, video: false};- if (value != stream.muted) {- stream.setMute(value);- return true;- }- return false;- },- switchVideoStreams: function (new_stream) {- this.localVideo.stream = new_stream;+ if (um.indexOf('video') >= 0) {+ // same behaviour as true+ constraints.video = { mandatory: {}, optional: [] };- this.localStreams = [];+ constraints.video.optional.push({ googLeakyBucket: true });- //in firefox we have only one stream object- if (this.localAudio.getOriginalStream() != new_stream)- this.localStreams.push(this.localAudio);- this.localStreams.push(this.localVideo);- },- changeLocalVideo: function (stream, isUsingScreenStream, callback) {- var oldStream = this.localVideo.getOriginalStream();- var type = (isUsingScreenStream ? "screen" : "camera");- var localCallback = callback;- if(this.localVideo.isMuted() && this.localVideo.videoType !== type) {- localCallback = function() {- APP.xmpp.setVideoMute(false, function(mute) {- eventEmitter.emit(RTCEvents.VIDEO_MUTE, mute);- });-- callback();- };- }- // FIXME: Workaround for FF/IE/Safari- if (stream && stream.videoStream) {- stream = stream.videoStream;+ setResolutionConstraints(constraints, resolution, isAndroid);+ }+ if (um.indexOf('audio') >= 0) {+ if (!RTCBrowserType.isFirefox()) {+ // same behaviour as true+ constraints.audio = { mandatory: {}, optional: []};+ // if it is good enough for hangouts...+ constraints.audio.optional.push(+ {googEchoCancellation: true},+ {googAutoGainControl: true},+ {googNoiseSupression: true},+ {googHighpassFilter: true},+ {googNoisesuppression2: true},+ {googEchoCancellation2: true},+ {googAutoGainControl2: true}+ );+ } else {+ constraints.audio = true;}- var videoStream = this.rtcUtils.createStream(stream, true);- this.localVideo = this.createLocalStream(videoStream, "video", true, type);- // Stop the stream to trigger onended event for old stream- oldStream.stop();-- this.switchVideoStreams(videoStream, oldStream);-- APP.xmpp.switchStreams(videoStream, oldStream,localCallback);- },- changeLocalAudio: function (stream, callback) {- var oldStream = this.localAudio.getOriginalStream();- var newStream = this.rtcUtils.createStream(stream);- this.localAudio = this.createLocalStream(newStream, "audio", true);- // Stop the stream to trigger onended event for old stream- oldStream.stop();- APP.xmpp.switchStreams(newStream, oldStream, callback, true);- },- isVideoMuted: function (jid) {- if (jid === APP.xmpp.myJid()) {- var localVideo = APP.RTC.localVideo;- return (!localVideo || localVideo.isMuted());+ }+ if (um.indexOf('screen') >= 0) {+ if (RTCBrowserType.isChrome()) {+ constraints.video = {+ mandatory: {+ chromeMediaSource: "screen",+ googLeakyBucket: true,+ maxWidth: window.screen.width,+ maxHeight: window.screen.height,+ maxFrameRate: 3+ },+ optional: []+ };+ } else if (RTCBrowserType.isTemasysPluginUsed()) {+ constraints.video = {+ optional: [+ {+ sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey+ }+ ]+ };} else {- if (!APP.RTC.remoteStreams[jid] ||- !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {- return null;- }- return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;+ console.error(+ "'screen' WebRTC media source is supported only in Chrome" ++ " and with Temasys plugin");}- },- setVideoMute: function (mute, callback, options) {- if (!this.localVideo)- return;+ }+ if (um.indexOf('desktop') >= 0) {+ constraints.video = {+ mandatory: {+ chromeMediaSource: "desktop",+ chromeMediaSourceId: desktopStream,+ googLeakyBucket: true,+ maxWidth: window.screen.width,+ maxHeight: window.screen.height,+ maxFrameRate: 3+ },+ optional: []+ };+ }- if (mute == APP.RTC.localVideo.isMuted())- {- APP.xmpp.sendVideoInfoPresence(mute);- if (callback)- callback(mute);+ if (bandwidth) {+ if (!constraints.video) {+ //same behaviour as true+ constraints.video = {mandatory: {}, optional: []};}- else- {- APP.RTC.localVideo.setMute(mute);- APP.xmpp.setVideoMute(- mute,- callback,- options);+ constraints.video.optional.push({bandwidth: bandwidth});+ }+ if (fps) {+ // for some cameras it might be necessary to request 30fps+ // so they choose 30fps mjpg over 10fps yuy2+ if (!constraints.video) {+ // same behaviour as true;+ constraints.video = {mandatory: {}, optional: []};}- },- setDeviceAvailability: function (devices) {- if(!devices)- return;- if(devices.audio === true || devices.audio === false)- this.devices.audio = devices.audio;- if(devices.video === true || devices.video === false)- this.devices.video = devices.video;- eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);+ constraints.video.mandatory.minFrameRate = fps;}-};--module.exports = RTC;--},{"../../service/RTC/MediaStreamTypes":110,"../../service/RTC/RTCEvents.js":111,"../../service/RTC/StreamEventTypes.js":113,"../../service/UI/UIEvents":114,"../../service/desktopsharing/DesktopSharingEventTypes":117,"../../service/xmpp/XMPPEvents":120,"./DataChannels":6,"./LocalStream.js":7,"./MediaStream.js":8,"./RTCBrowserType":10,"./RTCUtils.js":11,"events":1}],10:[function(require,module,exports){--var currentBrowser;--var browserVersion;--var RTCBrowserType = {-- RTC_BROWSER_CHROME: "rtc_browser.chrome",-- RTC_BROWSER_OPERA: "rtc_browser.opera",-- RTC_BROWSER_FIREFOX: "rtc_browser.firefox",- RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",-- RTC_BROWSER_SAFARI: "rtc_browser.safari",+ return constraints;+}- getBrowserType: function () {- return currentBrowser;- },- isChrome: function () {- return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;- },+function RTCUtils(RTCService, onTemasysPluginReady)+{+ var self = this;+ this.service = RTCService;+ if (RTCBrowserType.isFirefox()) {+ var FFversion = RTCBrowserType.getFirefoxVersion();+ if (FFversion >= 40) {+ this.peerconnection = mozRTCPeerConnection;+ this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);+ this.pc_constraints = {};+ this.attachMediaStream = function (element, stream) {+ // srcObject is being standardized and FF will eventually+ // support that unprefixed. FF also supports the+ // "element.src = URL.createObjectURL(...)" combo, but that+ // will be deprecated in favour of srcObject.+ //+ // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg+ // https://github.com/webrtc/samples/issues/302+ if(!element[0])+ return;+ element[0].mozSrcObject = stream;+ element[0].play();+ };+ this.getStreamID = function (stream) {+ var id = stream.id;+ if (!id) {+ var tracks = stream.getVideoTracks();+ if (!tracks || tracks.length === 0) {+ tracks = stream.getAudioTracks();+ }+ id = tracks[0].id;+ }+ return SDPUtil.filter_special_chars(id);+ };+ this.getVideoSrc = function (element) {+ if(!element)+ return null;+ return element.mozSrcObject;+ };+ this.setVideoSrc = function (element, src) {+ if(element)+ element.mozSrcObject = src;+ };+ RTCSessionDescription = mozRTCSessionDescription;+ RTCIceCandidate = mozRTCIceCandidate;+ } else {+ console.error(+ "Firefox version too old: " + FFversion + ". Required >= 40.");+ window.location.href = 'unsupported_browser.html';+ return;+ }- isOpera: function () {- return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;- },- isFirefox: function () {- return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;- },-- isIExplorer: function () {- return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;- },+ } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {+ this.peerconnection = webkitRTCPeerConnection;+ this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);+ this.attachMediaStream = function (element, stream) {+ element.attr('src', webkitURL.createObjectURL(stream));+ };+ this.getStreamID = function (stream) {+ // streams from FF endpoints have the characters '{' and '}'+ // that make jQuery choke.+ return SDPUtil.filter_special_chars(stream.id);+ };+ this.getVideoSrc = function (element) {+ if(!element)+ return null;+ return element.getAttribute("src");+ };+ this.setVideoSrc = function (element, src) {+ if(element)+ element.setAttribute("src", src);+ };+ // DTLS should now be enabled by default but..+ this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};+ if (navigator.userAgent.indexOf('Android') != -1) {+ this.pc_constraints = {}; // disable DTLS on Android+ }+ if (!webkitMediaStream.prototype.getVideoTracks) {+ webkitMediaStream.prototype.getVideoTracks = function () {+ return this.videoTracks;+ };+ }+ if (!webkitMediaStream.prototype.getAudioTracks) {+ webkitMediaStream.prototype.getAudioTracks = function () {+ return this.audioTracks;+ };+ }+ }+ // Detect IE/Safari+ else if (RTCBrowserType.isTemasysPluginUsed()) {- isSafari: function () {- return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;- },- isTemasysPluginUsed: function () {- return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();- },- getFirefoxVersion: function () {- return RTCBrowserType.isFirefox() ? browserVersion : null;- },+ //AdapterJS.WebRTCPlugin.setLogLevel(+ // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);- getChromeVersion: function () {- return RTCBrowserType.isChrome() ? browserVersion : null;- },+ AdapterJS.webRTCReady(function (isPlugin) {- usesPlanB: function() {- return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||- RTCBrowserType.isTemasysPluginUsed();- },+ self.peerconnection = RTCPeerConnection;+ self.getUserMedia = getUserMedia;+ self.attachMediaStream = function (elSel, stream) {- usesUnifiedPlan: function() {- return RTCBrowserType.isFirefox();- }+ if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {+ return;+ }- // Add version getters for other browsers when needed-};+ attachMediaStream(elSel[0], stream);+ };+ self.getStreamID = function (stream) {+ var id = SDPUtil.filter_special_chars(stream.label);+ return id;+ };+ self.getVideoSrc = function (element) {+ if (!element) {+ console.warn("Attempt to get video SRC of null element");+ return null;+ }+ var children = element.children;+ for (var i = 0; i !== children.length; ++i) {+ if (children[i].name === 'streamId') {+ return children[i].value;+ }+ }+ //console.info(element.id + " SRC: " + src);+ return null;+ };+ self.setVideoSrc = function (element, src) {+ //console.info("Set video src: ", element, src);+ if (!src) {+ console.warn("Not attaching video stream, 'src' is null");+ return;+ }+ AdapterJS.WebRTCPlugin.WaitForPluginReady();+ var stream = AdapterJS.WebRTCPlugin.plugin+ .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);+ attachMediaStream(element, stream);+ };-// detectOpera() must be called before detectChrome() !!!-// otherwise Opera wil be detected as Chrome-function detectChrome() {- if (navigator.webkitGetUserMedia) {- currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;- var userAgent = navigator.userAgent.toLowerCase();- // We can assume that user agent is chrome, because it's- // enforced when 'ext' streaming method is set- var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);- console.log("This appears to be Chrome, ver: " + ver);- return ver;+ onTemasysPluginReady(isPlugin);+ });+ } else {+ try {+ console.log('Browser does not appear to be WebRTC-capable');+ } catch (e) { }+ window.location.href = 'unsupported_browser.html';}- return null;}-function detectOpera() {- var userAgent = navigator.userAgent;- if (userAgent.match(/Opera|OPR/)) {- currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;- var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];- console.info("This appears to be Opera, ver: " + version);- return version;- }- return null;-}-function detectFirefox() {- if (navigator.mozGetUserMedia) {- currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;- var version = parseInt(- navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);- console.log('This appears to be Firefox, ver: ' + version);- return version;- }- return null;-}+RTCUtils.prototype.getUserMediaWithConstraints = function(+ um, success_callback, failure_callback, resolution,bandwidth, fps,+ desktopStream) {+ currentResolution = resolution;+ // Check if we are running on Android device+ var isAndroid = navigator.userAgent.indexOf('Android') != -1;-function detectSafari() {- if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {- currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;- console.info("This appears to be Safari");- // FIXME detect Safari version when needed- return 1;- }- return null;-}+ var constraints = getConstraints(+ um, resolution, bandwidth, fps, desktopStream, isAndroid);-function detectIE() {- var version;- var ua = window.navigator.userAgent;+ console.info("Get media constraints", constraints);- var msie = ua.indexOf('MSIE ');- if (msie > 0) {- // IE 10 or older => return version number- version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);- }+ var self = this;- var trident = ua.indexOf('Trident/');- if (!version && trident > 0) {- // IE 11 => return version number- var rv = ua.indexOf('rv:');- version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);+ try {+ this.getUserMedia(constraints,+ function (stream) {+ console.log('onUserMediaSuccess');+ self.setAvailableDevices(um, true);+ success_callback(stream);+ },+ function (error) {+ self.setAvailableDevices(um, false);+ console.warn('Failed to get access to local media. Error ',+ error, constraints);+ if (failure_callback) {+ failure_callback(error);+ }+ });+ } catch (e) {+ console.error('GUM failed: ', e);+ if(failure_callback) {+ failure_callback(e);+ }}+};- var edge = ua.indexOf('Edge/');- if (!version && edge > 0) {- // IE 12 => return version number- version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);+RTCUtils.prototype.setAvailableDevices = function (um, available) {+ var devices = {};+ if(um.indexOf("video") != -1) {+ devices.video = available;}-- if (version) {- currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;- console.info("This appears to be IExplorer, ver: " + version);+ if(um.indexOf("audio") != -1) {+ devices.audio = available;}- return version;-}+ this.service.setDeviceAvailability(devices);+};-function detectBrowser() {- var version;- var detectors = [- detectOpera,- detectChrome,- detectFirefox,- detectIE,- detectSafari- ];- // Try all browser detectors- for (var i = 0; i < detectors.length; i++) {- version = detectors[i]();- if (version)- return version;- }- console.error("Failed to detect browser type");- return undefined;-}+/**+ * We ask for audio and video combined stream in order to get permissions and+ * not to ask twice.+ */+RTCUtils.prototype.obtainAudioAndVideoPermissions =+ function(devices, callback, usageOptions)+{+ var self = this;+ // Get AV-browserVersion = detectBrowser();+ var successCallback = function (stream) {+ if(callback)+ callback(stream, usageOptions);+ else+ self.successCallback(stream, usageOptions);+ };-module.exports = RTCBrowserType;-},{}],11:[function(require,module,exports){-/* global config, require, attachMediaStream, getUserMedia */-var RTCBrowserType = require("./RTCBrowserType");-var Resolutions = require("../../service/RTC/Resolutions");-var AdapterJS = require("./adapter.screenshare");-var SDPUtil = require("../xmpp/SDPUtil");+ if(!devices)+ devices = ['audio', 'video'];-var currentResolution = null;+ var newDevices = [];-function getPreviousResolution(resolution) {- if(!Resolutions[resolution])- return null;- var order = Resolutions[resolution].order;- var res = null;- var resName = null;- for(var i in Resolutions) {- var tmp = Resolutions[i];- if(res == null || (res.order < tmp.order && tmp.order < order)) {- resName = i;- res = tmp;- }- }- return resName;-}-function setResolutionConstraints(constraints, resolution, isAndroid) {+ if(usageOptions)+ for(var i = 0; i < devices.length; i++) {+ var device = devices[i];+ if(usageOptions[device] === true)+ newDevices.push(device);+ }+ else+ newDevices = devices;- if (Resolutions[resolution]) {- constraints.video.mandatory.minWidth = Resolutions[resolution].width;- constraints.video.mandatory.minHeight = Resolutions[resolution].height;- }- else if (isAndroid) {- // FIXME can't remember if the purpose of this was to always request- // low resolution on Android ? if yes it should be moved up front- constraints.video.mandatory.minWidth = 320;- constraints.video.mandatory.minHeight = 240;- constraints.video.mandatory.maxFrameRate = 15;+ if(newDevices.length === 0) {+ successCallback();+ return;}- if (constraints.video.mandatory.minWidth)- constraints.video.mandatory.maxWidth =- constraints.video.mandatory.minWidth;- if (constraints.video.mandatory.minHeight)- constraints.video.mandatory.maxHeight =- constraints.video.mandatory.minHeight;-}--function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)-{- var constraints = {audio: false, video: false};-- if (um.indexOf('video') >= 0) {- // same behaviour as true- constraints.video = { mandatory: {}, optional: [] };-- constraints.video.optional.push({ googLeakyBucket: true });+ if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {- setResolutionConstraints(constraints, resolution, isAndroid);- }- if (um.indexOf('audio') >= 0) {- if (!RTCBrowserType.isFirefox()) {- // same behaviour as true- constraints.audio = { mandatory: {}, optional: []};- // if it is good enough for hangouts...- constraints.audio.optional.push(- {googEchoCancellation: true},- {googAutoGainControl: true},- {googNoiseSupression: true},- {googHighpassFilter: true},- {googNoisesuppression2: true},- {googEchoCancellation2: true},- {googAutoGainControl2: true}+ // With FF/IE we can't split the stream into audio and video because FF+ // doesn't support media stream constructors. So, we need to get the+ // audio stream separately from the video stream using two distinct GUM+ // calls. Not very user friendly :-( but we don't have many other+ // options neither.+ //+ // Note that we pack those 2 streams in a single object and pass it to+ // the successCallback method.+ var obtainVideo = function (audioStream) {+ self.getUserMediaWithConstraints(+ ['video'],+ function (videoStream) {+ return successCallback({+ audioStream: audioStream,+ videoStream: videoStream+ });+ },+ function (error) {+ console.error(+ 'failed to obtain video stream - stop', error);+ self.errorCallback(error);+ },+ config.resolution || '360');+ };+ var obtainAudio = function () {+ self.getUserMediaWithConstraints(+ ['audio'],+ function (audioStream) {+ if (newDevices.indexOf('video') !== -1)+ obtainVideo(audioStream);+ },+ function (error) {+ console.error(+ 'failed to obtain audio stream - stop', error);+ self.errorCallback(error);+ });+ };+ if (newDevices.indexOf('audio') !== -1) {+ obtainAudio();} else {- constraints.audio = true;+ obtainVideo(null);}+ } else {+ this.getUserMediaWithConstraints(+ newDevices,+ function (stream) {+ successCallback(stream);+ },+ function (error) {+ self.errorCallback(error);+ },+ config.resolution || '360');}- if (um.indexOf('screen') >= 0) {- if (RTCBrowserType.isChrome()) {- constraints.video = {- mandatory: {- chromeMediaSource: "screen",- googLeakyBucket: true,- maxWidth: window.screen.width,- maxHeight: window.screen.height,- maxFrameRate: 3- },- optional: []- };- } else if (RTCBrowserType.isTemasysPluginUsed()) {- constraints.video = {- optional: [- {- sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey- }- ]- };- } else {- console.error(- "'screen' WebRTC media source is supported only in Chrome" +- " and with Temasys plugin");- }+};++RTCUtils.prototype.successCallback = function (stream, usageOptions) {+ // If this is FF or IE, the stream parameter is *not* a MediaStream object,+ // it's an object with two properties: audioStream, videoStream.+ if (stream && stream.getAudioTracks && stream.getVideoTracks)+ console.log('got', stream, stream.getAudioTracks().length,+ stream.getVideoTracks().length);+ this.handleLocalStream(stream, usageOptions);+};++RTCUtils.prototype.errorCallback = function (error) {+ var self = this;+ console.error('failed to obtain audio/video stream - trying audio only', error);+ var resolution = getPreviousResolution(currentResolution);+ if(typeof error == "object" && error.constraintName && error.name+ && (error.name == "ConstraintNotSatisfiedError" ||+ error.name == "OverconstrainedError") &&+ (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||+ error.constraintName == "minHeight" || error.constraintName == "maxHeight")+ && resolution != null)+ {+ self.getUserMediaWithConstraints(['audio', 'video'],+ function (stream) {+ return self.successCallback(stream);+ }, function (error) {+ return self.errorCallback(error);+ }, resolution);}- if (um.indexOf('desktop') >= 0) {- constraints.video = {- mandatory: {- chromeMediaSource: "desktop",- chromeMediaSourceId: desktopStream,- googLeakyBucket: true,- maxWidth: window.screen.width,- maxHeight: window.screen.height,- maxFrameRate: 3+ else {+ self.getUserMediaWithConstraints(+ ['audio'],+ function (stream) {+ return self.successCallback(stream);},- optional: []- };+ function (error) {+ console.error('failed to obtain audio/video stream - stop',+ error);+ return self.successCallback(null);+ }+ );}+};- if (bandwidth) {- if (!constraints.video) {- //same behaviour as true- constraints.video = {mandatory: {}, optional: []};+RTCUtils.prototype.handleLocalStream = function(stream, usageOptions) {+ // If this is FF, the stream parameter is *not* a MediaStream object, it's+ // an object with two properties: audioStream, videoStream.+ var audioStream, videoStream;+ if(window.webkitMediaStream)+ {+ audioStream = new webkitMediaStream();+ videoStream = new webkitMediaStream();+ if(stream) {+ var audioTracks = stream.getAudioTracks();++ for (var i = 0; i < audioTracks.length; i++) {+ audioStream.addTrack(audioTracks[i]);+ }++ var videoTracks = stream.getVideoTracks();++ for (i = 0; i < videoTracks.length; i++) {+ videoStream.addTrack(videoTracks[i]);+ }}- constraints.video.optional.push({bandwidth: bandwidth});}- if (fps) {- // for some cameras it might be necessary to request 30fps- // so they choose 30fps mjpg over 10fps yuy2- if (!constraints.video) {- // same behaviour as true;- constraints.video = {mandatory: {}, optional: []};- }- constraints.video.mandatory.minFrameRate = fps;+ else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed())+ { // Firefox and Temasys plugin+ if (stream && stream.audioStream)+ audioStream = stream.audioStream;+ else+ audioStream = new DummyMediaStream("dummyAudio");++ if (stream && stream.videoStream)+ videoStream = stream.videoStream;+ else+ videoStream = new DummyMediaStream("dummyVideo");}- return constraints;-}+ var audioMuted = (usageOptions && usageOptions.audio === false),+ videoMuted = (usageOptions && usageOptions.video === false);+ var audioGUM = (!usageOptions || usageOptions.audio !== false),+ videoGUM = (!usageOptions || usageOptions.video !== false);-function RTCUtils(RTCService, onTemasysPluginReady)-{- var self = this;- this.service = RTCService;- if (RTCBrowserType.isFirefox()) {- var FFversion = RTCBrowserType.getFirefoxVersion();- if (FFversion >= 40) {- this.peerconnection = mozRTCPeerConnection;- this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);- this.pc_constraints = {};- this.attachMediaStream = function (element, stream) {- // srcObject is being standardized and FF will eventually- // support that unprefixed. FF also supports the- // "element.src = URL.createObjectURL(...)" combo, but that- // will be deprecated in favour of srcObject.- //- // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg- // https://github.com/webrtc/samples/issues/302- if(!element[0])- return;- element[0].mozSrcObject = stream;- element[0].play();- };- this.getStreamID = function (stream) {- var id = stream.id;- if (!id) {- var tracks = stream.getVideoTracks();- if (!tracks || tracks.length === 0) {- tracks = stream.getAudioTracks();- }- id = tracks[0].id;- }- return SDPUtil.filter_special_chars(id);- };- this.getVideoSrc = function (element) {- if(!element)- return null;- return element.mozSrcObject;- };- this.setVideoSrc = function (element, src) {- if(element)- element.mozSrcObject = src;- };- RTCSessionDescription = mozRTCSessionDescription;- RTCIceCandidate = mozRTCIceCandidate;- } else {- console.error(- "Firefox version too old: " + FFversion + ". Required >= 40.");- window.location.href = 'unsupported_browser.html';- return;- }-- } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {- this.peerconnection = webkitRTCPeerConnection;- this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);- this.attachMediaStream = function (element, stream) {- element.attr('src', webkitURL.createObjectURL(stream));- };- this.getStreamID = function (stream) {- // streams from FF endpoints have the characters '{' and '}'- // that make jQuery choke.- return SDPUtil.filter_special_chars(stream.id);- };- this.getVideoSrc = function (element) {- if(!element)- return null;- return element.getAttribute("src");- };- this.setVideoSrc = function (element, src) {- if(element)- element.setAttribute("src", src);- };- // DTLS should now be enabled by default but..- this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};- if (navigator.userAgent.indexOf('Android') != -1) {- this.pc_constraints = {}; // disable DTLS on Android- }- if (!webkitMediaStream.prototype.getVideoTracks) {- webkitMediaStream.prototype.getVideoTracks = function () {- return this.videoTracks;- };- }- if (!webkitMediaStream.prototype.getAudioTracks) {- webkitMediaStream.prototype.getAudioTracks = function () {- return this.audioTracks;- };- }- }- // Detect IE/Safari- else if (RTCBrowserType.isTemasysPluginUsed()) {-- //AdapterJS.WebRTCPlugin.setLogLevel(- // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);-- AdapterJS.webRTCReady(function (isPlugin) {-- self.peerconnection = RTCPeerConnection;- self.getUserMedia = getUserMedia;- self.attachMediaStream = function (elSel, stream) {- if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {- return;- }+ this.service.createLocalStream(audioStream, "audio", null, null,+ audioMuted, audioGUM);- attachMediaStream(elSel[0], stream);- };- self.getStreamID = function (stream) {- var id = SDPUtil.filter_special_chars(stream.label);- return id;- };- self.getVideoSrc = function (element) {- if (!element) {- console.warn("Attempt to get video SRC of null element");- return null;- }- var children = element.children;- for (var i = 0; i !== children.length; ++i) {- if (children[i].name === 'streamId') {- return children[i].value;- }- }- //console.info(element.id + " SRC: " + src);- return null;- };- self.setVideoSrc = function (element, src) {- //console.info("Set video src: ", element, src);- if (!src) {- console.warn("Not attaching video stream, 'src' is null");- return;- }- AdapterJS.WebRTCPlugin.WaitForPluginReady();- var stream = AdapterJS.WebRTCPlugin.plugin- .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);- attachMediaStream(element, stream);- };+ this.service.createLocalStream(videoStream, "video", null, 'camera',+ videoMuted, videoGUM);+};- onTemasysPluginReady(isPlugin);- });- } else {- try {- console.log('Browser does not appear to be WebRTC-capable');- } catch (e) { }- window.location.href = 'unsupported_browser.html';- }+function DummyMediaStream(id) {+ this.id = id;+ this.label = id;+ this.stop = function() { };+ this.getAudioTracks = function() { return []; };+ this.getVideoTracks = function() { return []; };}+RTCUtils.prototype.createStream = function(stream, isVideo) {+ var newStream = null;+ if (window.webkitMediaStream) {+ newStream = new webkitMediaStream();+ if (newStream) {+ var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());-RTCUtils.prototype.getUserMediaWithConstraints = function(- um, success_callback, failure_callback, resolution,bandwidth, fps,- desktopStream) {- currentResolution = resolution;- // Check if we are running on Android device- var isAndroid = navigator.userAgent.indexOf('Android') != -1;-- var constraints = getConstraints(- um, resolution, bandwidth, fps, desktopStream, isAndroid);-- console.info("Get media constraints", constraints);-- var self = this;-- try {- this.getUserMedia(constraints,- function (stream) {- console.log('onUserMediaSuccess');- self.setAvailableDevices(um, true);- success_callback(stream);- },- function (error) {- self.setAvailableDevices(um, false);- console.warn('Failed to get access to local media. Error ',- error, constraints);- if (failure_callback) {- failure_callback(error);- }- });- } catch (e) {- console.error('GUM failed: ', e);- if(failure_callback) {- failure_callback(e);+ for (var i = 0; i < tracks.length; i++) {+ newStream.addTrack(tracks[i]);+ }}- }-};-RTCUtils.prototype.setAvailableDevices = function (um, available) {- var devices = {};- if(um.indexOf("video") != -1) {- devices.video = available;}- if(um.indexOf("audio") != -1) {- devices.audio = available;+ else {+ // FIXME: this is duplicated with 'handleLocalStream' !!!+ if (stream) {+ newStream = stream;+ } else {+ newStream =+ new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");+ }}- this.service.setDeviceAvailability(devices);++ return newStream;};-/**- * We ask for audio and video combined stream in order to get permissions and- * not to ask twice.- */-RTCUtils.prototype.obtainAudioAndVideoPermissions =- function(devices, callback, usageOptions)-{- var self = this;- // Get AV+module.exports = RTCUtils;- var successCallback = function (stream) {- if(callback)- callback(stream, usageOptions);- else- self.successCallback(stream, usageOptions);- };+},{"../../service/RTC/Resolutions":153,"../xmpp/SDPUtil":58,"./RTCBrowserType":8,"./adapter.screenshare":10}],10:[function(require,module,exports){+/*! adapterjs - custom version from - 2015-08-12 */- if(!devices)- devices = ['audio', 'video'];+// Adapter's interface.+var AdapterJS = AdapterJS || {};- var newDevices = [];+// Browserify compatibility+if(typeof exports !== 'undefined') {+ module.exports = AdapterJS;+}+AdapterJS.options = AdapterJS.options || {};- if(usageOptions)- for(var i = 0; i < devices.length; i++) {- var device = devices[i];- if(usageOptions[device] === true)- newDevices.push(device);- }- else- newDevices = devices;+// uncomment to get virtual webcams+// AdapterJS.options.getAllCams = true;- if(newDevices.length === 0) {- successCallback();- return;- }+// uncomment to prevent the install prompt when the plugin in not yet installed+// AdapterJS.options.hidePluginInstallPrompt = true;- if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {-- // With FF/IE we can't split the stream into audio and video because FF- // doesn't support media stream constructors. So, we need to get the- // audio stream separately from the video stream using two distinct GUM- // calls. Not very user friendly :-( but we don't have many other- // options neither.- //- // Note that we pack those 2 streams in a single object and pass it to- // the successCallback method.- var obtainVideo = function (audioStream) {- self.getUserMediaWithConstraints(- ['video'],- function (videoStream) {- return successCallback({- audioStream: audioStream,- videoStream: videoStream- });- },- function (error) {- console.error(- 'failed to obtain video stream - stop', error);- self.errorCallback(error);- },- config.resolution || '360');- };- var obtainAudio = function () {- self.getUserMediaWithConstraints(- ['audio'],- function (audioStream) {- if (newDevices.indexOf('video') !== -1)- obtainVideo(audioStream);- },- function (error) {- console.error(- 'failed to obtain audio stream - stop', error);- self.errorCallback(error);- }- );- };- if (newDevices.indexOf('audio') !== -1) {- obtainAudio();- } else {- obtainVideo(null);- }- } else {- this.getUserMediaWithConstraints(- newDevices,- function (stream) {- successCallback(stream);- },- function (error) {- self.errorCallback(error);- },- config.resolution || '360');- }-};--RTCUtils.prototype.successCallback = function (stream, usageOptions) {- // If this is FF or IE, the stream parameter is *not* a MediaStream object,- // it's an object with two properties: audioStream, videoStream.- if (stream && stream.getAudioTracks && stream.getVideoTracks)- console.log('got', stream, stream.getAudioTracks().length,- stream.getVideoTracks().length);- this.handleLocalStream(stream, usageOptions);-};--RTCUtils.prototype.errorCallback = function (error) {- var self = this;- console.error('failed to obtain audio/video stream - trying audio only', error);- var resolution = getPreviousResolution(currentResolution);- if(typeof error == "object" && error.constraintName && error.name- && (error.name == "ConstraintNotSatisfiedError" ||- error.name == "OverconstrainedError") &&- (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||- error.constraintName == "minHeight" || error.constraintName == "maxHeight")- && resolution != null)- {- self.getUserMediaWithConstraints(['audio', 'video'],- function (stream) {- return self.successCallback(stream);- }, function (error) {- return self.errorCallback(error);- }, resolution);- }- else {- self.getUserMediaWithConstraints(- ['audio'],- function (stream) {- return self.successCallback(stream);- },- function (error) {- console.error('failed to obtain audio/video stream - stop',- error);- return self.successCallback(null);- }- );- }-};--RTCUtils.prototype.handleLocalStream = function(stream, usageOptions) {- // If this is FF, the stream parameter is *not* a MediaStream object, it's- // an object with two properties: audioStream, videoStream.- var audioStream, videoStream;- if(window.webkitMediaStream)- {- audioStream = new webkitMediaStream();- videoStream = new webkitMediaStream();- if(stream) {- var audioTracks = stream.getAudioTracks();-- for (var i = 0; i < audioTracks.length; i++) {- audioStream.addTrack(audioTracks[i]);- }-- var videoTracks = stream.getVideoTracks();-- for (i = 0; i < videoTracks.length; i++) {- videoStream.addTrack(videoTracks[i]);- }- }- }- else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed())- { // Firefox and Temasys plugin- if (stream && stream.audioStream)- audioStream = stream.audioStream;- else- audioStream = new DummyMediaStream("dummyAudio");-- if (stream && stream.videoStream)- videoStream = stream.videoStream;- else- videoStream = new DummyMediaStream("dummyVideo");- }-- var audioMuted = (usageOptions && usageOptions.audio === false),- videoMuted = (usageOptions && usageOptions.video === false);-- var audioGUM = (!usageOptions || usageOptions.audio !== false),- videoGUM = (!usageOptions || usageOptions.video !== false);--- this.service.createLocalStream(audioStream, "audio", null, null,- audioMuted, audioGUM);-- this.service.createLocalStream(videoStream, "video", null, 'camera',- videoMuted, videoGUM);-};--function DummyMediaStream(id) {- this.id = id;- this.label = id;- this.stop = function() { };- this.getAudioTracks = function() { return []; };- this.getVideoTracks = function() { return []; };-}--RTCUtils.prototype.createStream = function(stream, isVideo) {- var newStream = null;- if (window.webkitMediaStream) {- newStream = new webkitMediaStream();- if (newStream) {- var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());-- for (var i = 0; i < tracks.length; i++) {- newStream.addTrack(tracks[i]);- }- }-- }- else {- // FIXME: this is duplicated with 'handleLocalStream' !!!- if (stream) {- newStream = stream;- } else {- newStream =- new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");- }- }-- return newStream;-};--module.exports = RTCUtils;--},{"../../service/RTC/Resolutions":112,"../xmpp/SDPUtil":60,"./RTCBrowserType":10,"./adapter.screenshare":12}],12:[function(require,module,exports){-/*! adapterjs - custom version from - 2015-08-12 */--// Adapter's interface.-var AdapterJS = AdapterJS || {};--// Browserify compatibility-if(typeof exports !== 'undefined') {- module.exports = AdapterJS;-}--AdapterJS.options = AdapterJS.options || {};--// uncomment to get virtual webcams-// AdapterJS.options.getAllCams = true;--// uncomment to prevent the install prompt when the plugin in not yet installed-// AdapterJS.options.hidePluginInstallPrompt = true;--// AdapterJS version-AdapterJS.VERSION = '0.11.1';+// AdapterJS version+AdapterJS.VERSION = '0.11.1';// This function will be called when the WebRTC API is ready to be used// Whether it is the native implementation (Chrome, Firefox, Opera) or@@ -3412,7 +3017,7 @@ if (navigator.mozGetUserMedia) {};}})();-},{}],13:[function(require,module,exports){+},{}],11:[function(require,module,exports){/* global Strophe, APP, $, config, interfaceConfig, toastr */var UI = {};@@ -4291,7 +3896,7 @@ UI.setVideoMute = setVideoMute;module.exports = UI;-},{"../../service/RTC/RTCEvents":111,"../../service/RTC/StreamEventTypes":113,"../../service/UI/UIEvents":114,"../../service/connectionquality/CQEvents":116,"../../service/desktopsharing/DesktopSharingEventTypes":117,"../../service/members/Events":118,"../../service/xmpp/XMPPEvents":120,"../RTC/RTCBrowserType":10,"./../settings/Settings":49,"./audio_levels/AudioLevels.js":14,"./authentication/Authentication":16,"./avatar/Avatar":18,"./etherpad/Etherpad.js":19,"./prezi/Prezi.js":20,"./side_pannels/SidePanelToggler":22,"./side_pannels/chat/Chat.js":23,"./side_pannels/contactlist/ContactList":27,"./side_pannels/settings/SettingsMenu":28,"./toolbars/BottomToolbar":29,"./toolbars/Toolbar":30,"./toolbars/ToolbarToggler":31,"./util/JitsiPopover":32,"./util/MessageHandler":33,"./util/NicknameHandler":34,"./util/UIUtil":35,"./videolayout/VideoLayout.js":41,"./welcome_page/RoomnameGenerator":42,"./welcome_page/WelcomePage":43,"events":1}],14:[function(require,module,exports){+},{"../../service/RTC/RTCEvents":152,"../../service/RTC/StreamEventTypes":154,"../../service/UI/UIEvents":155,"../../service/connectionquality/CQEvents":157,"../../service/desktopsharing/DesktopSharingEventTypes":158,"../../service/members/Events":159,"../../service/xmpp/XMPPEvents":161,"../RTC/RTCBrowserType":8,"./../settings/Settings":47,"./audio_levels/AudioLevels.js":12,"./authentication/Authentication":14,"./avatar/Avatar":16,"./etherpad/Etherpad.js":17,"./prezi/Prezi.js":18,"./side_pannels/SidePanelToggler":20,"./side_pannels/chat/Chat.js":21,"./side_pannels/contactlist/ContactList":25,"./side_pannels/settings/SettingsMenu":26,"./toolbars/BottomToolbar":27,"./toolbars/Toolbar":28,"./toolbars/ToolbarToggler":29,"./util/JitsiPopover":30,"./util/MessageHandler":31,"./util/NicknameHandler":32,"./util/UIUtil":33,"./videolayout/VideoLayout.js":39,"./welcome_page/RoomnameGenerator":40,"./welcome_page/WelcomePage":41,"events":162}],12:[function(require,module,exports){/* global APP, interfaceConfig, $, Strophe */var CanvasUtil = require("./CanvasUtils");@@ -4557,7 +4162,7 @@ var AudioLevels = (function(my) {})(AudioLevels || {});module.exports = AudioLevels;-},{"./CanvasUtils":15}],15:[function(require,module,exports){+},{"./CanvasUtils":13}],13:[function(require,module,exports){/*** Utility class for drawing canvas shapes.*/@@ -4669,7 +4274,7 @@ var CanvasUtil = (function(my) {})(CanvasUtil || {});module.exports = CanvasUtil;-},{}],16:[function(require,module,exports){+},{}],14:[function(require,module,exports){/* global $, APP*/var LoginDialog = require('./LoginDialog');@@ -4794,7 +4399,7 @@ var Authentication = {};module.exports = Authentication;-},{"../../xmpp/moderator":62,"./LoginDialog":17}],17:[function(require,module,exports){+},{"../../xmpp/moderator":60,"./LoginDialog":15}],15:[function(require,module,exports){/* global $, APP, config*/var XMPP = require('../../xmpp/xmpp');@@ -5023,7 +4628,7 @@ var LoginDialog = {};module.exports = LoginDialog;-},{"../../xmpp/moderator":62,"../../xmpp/xmpp":70}],18:[function(require,module,exports){+},{"../../xmpp/moderator":60,"../../xmpp/xmpp":68}],16:[function(require,module,exports){var Settings = require("../../settings/Settings");var users = {};@@ -5091,7 +4696,7 @@ var Avatar = {module.exports = Avatar;-},{"../../settings/Settings":49}],19:[function(require,module,exports){+},{"../../settings/Settings":47}],17:[function(require,module,exports){/* global $, config,setLargeVideoVisible, Util */@@ -5223,7 +4828,7 @@ var Etherpad = {module.exports = Etherpad;-},{"../prezi/Prezi":20,"../util/UIUtil":35,"../videolayout/VideoLayout":41}],20:[function(require,module,exports){+},{"../prezi/Prezi":18,"../util/UIUtil":33,"../videolayout/VideoLayout":39}],18:[function(require,module,exports){var ToolbarToggler = require("../toolbars/ToolbarToggler");var UIUtil = require("../util/UIUtil");var VideoLayout = require("../videolayout/VideoLayout");@@ -5568,7 +5173,7 @@ $(window).resize(function () {module.exports = Prezi;-},{"../toolbars/ToolbarToggler":31,"../util/MessageHandler":33,"../util/UIUtil":35,"../videolayout/VideoLayout":41,"./PreziPlayer":21}],21:[function(require,module,exports){+},{"../toolbars/ToolbarToggler":29,"../util/MessageHandler":31,"../util/UIUtil":33,"../videolayout/VideoLayout":39,"./PreziPlayer":19}],19:[function(require,module,exports){(function() {"use strict";var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };@@ -5864,7 +5469,7 @@ module.exports = Prezi;module.exports = PreziPlayer;-},{}],22:[function(require,module,exports){+},{}],20:[function(require,module,exports){/* global require, $ */var Chat = require("./chat/Chat");var ContactList = require("./contactlist/ContactList");@@ -6039,7 +5644,7 @@ var PanelToggler = (function(my) {}(PanelToggler || {}));module.exports = PanelToggler;-},{"../toolbars/ToolbarToggler":31,"../util/UIUtil":35,"../videolayout/LargeVideo":37,"../videolayout/VideoLayout":41,"./../../settings/Settings":49,"./chat/Chat":23,"./contactlist/ContactList":27,"./settings/SettingsMenu":28}],23:[function(require,module,exports){+},{"../toolbars/ToolbarToggler":29,"../util/UIUtil":33,"../videolayout/LargeVideo":35,"../videolayout/VideoLayout":39,"./../../settings/Settings":47,"./chat/Chat":21,"./contactlist/ContactList":25,"./settings/SettingsMenu":26}],21:[function(require,module,exports){/* global APP, $, Util, nickname:true */var Replacement = require("./Replacement");var CommandsProcessor = require("./Commands");@@ -6390,7 +5995,7 @@ var Chat = (function (my) {return my;}(Chat || {}));module.exports = Chat;-},{"../../../../service/UI/UIEvents":114,"../../toolbars/ToolbarToggler":31,"../../util/NicknameHandler":34,"../../util/UIUtil":35,"../SidePanelToggler":22,"./Commands":24,"./Replacement":25,"./smileys.json":26}],24:[function(require,module,exports){+},{"../../../../service/UI/UIEvents":155,"../../toolbars/ToolbarToggler":29,"../../util/NicknameHandler":32,"../../util/UIUtil":33,"../SidePanelToggler":20,"./Commands":22,"./Replacement":23,"./smileys.json":24}],22:[function(require,module,exports){/* global APP, require */var UIUtil = require("../../util/UIUtil");@@ -6477,7 +6082,7 @@ CommandsProcessor.prototype.processCommand = function() {};module.exports = CommandsProcessor;-},{"../../util/UIUtil":35}],25:[function(require,module,exports){+},{"../../util/UIUtil":33}],23:[function(require,module,exports){var Smileys = require("./smileys.json");/*** Processes links and smileys in "body"@@ -6541,7 +6146,7 @@ module.exports = {linkify: linkify};-},{"./smileys.json":26}],26:[function(require,module,exports){+},{"./smileys.json":24}],24:[function(require,module,exports){module.exports={"smileys": {"smiley1": ":)",@@ -6591,7 +6196,7 @@ module.exports={}}-},{}],27:[function(require,module,exports){+},{}],25:[function(require,module,exports){/* global $, APP, Strophe */var Avatar = require('../../avatar/Avatar');@@ -6786,7 +6391,7 @@ var ContactList = {};module.exports = ContactList;-},{"../../avatar/Avatar":18}],28:[function(require,module,exports){+},{"../../avatar/Avatar":16}],26:[function(require,module,exports){/* global APP, $ */var Avatar = require("../../avatar/Avatar");var Settings = require("./../../../settings/Settings");@@ -6895,7 +6500,7 @@ var SettingsMenu = {module.exports = SettingsMenu;-},{"../../../../service/translation/languages":119,"../../avatar/Avatar":18,"../../util/UIUtil":35,"./../../../settings/Settings":49}],29:[function(require,module,exports){+},{"../../../../service/translation/languages":160,"../../avatar/Avatar":16,"../../util/UIUtil":33,"./../../../settings/Settings":47}],27:[function(require,module,exports){/* global $ */var PanelToggler = require("../side_pannels/SidePanelToggler");@@ -6941,7 +6546,7 @@ var BottomToolbar = (function (my) {module.exports = BottomToolbar;-},{"../side_pannels/SidePanelToggler":22}],30:[function(require,module,exports){+},{"../side_pannels/SidePanelToggler":20}],28:[function(require,module,exports){/* global APP, $, buttonClick, config, lockRoom, interfaceConfig, setSharedKey,Util */var messageHandler = require("../util/MessageHandler");@@ -7620,7 +7225,7 @@ var Toolbar = (function (my) {}(Toolbar || {}));module.exports = Toolbar;-},{"../../../service/authentication/AuthenticationEvents":115,"../authentication/Authentication":16,"../etherpad/Etherpad":19,"../prezi/Prezi":20,"../side_pannels/SidePanelToggler":22,"../util/MessageHandler":33,"../util/UIUtil":35,"./BottomToolbar":29}],31:[function(require,module,exports){+},{"../../../service/authentication/AuthenticationEvents":156,"../authentication/Authentication":14,"../etherpad/Etherpad":17,"../prezi/Prezi":18,"../side_pannels/SidePanelToggler":20,"../util/MessageHandler":31,"../util/UIUtil":33,"./BottomToolbar":27}],29:[function(require,module,exports){/* global APP, config, $, interfaceConfig, Moderator,DesktopStreaming.showDesktopSharingButton */@@ -7742,7 +7347,7 @@ var ToolbarToggler = {};module.exports = ToolbarToggler;-},{}],32:[function(require,module,exports){+},{}],30:[function(require,module,exports){/* global $ */var JitsiPopover = (function () {/**@@ -7871,7 +7476,7 @@ var JitsiPopover = (function () {})();module.exports = JitsiPopover;-},{}],33:[function(require,module,exports){+},{}],31:[function(require,module,exports){/* global $, APP, jQuery, toastr *//**@@ -8114,7 +7719,7 @@ module.exports = messageHandler;-},{}],34:[function(require,module,exports){+},{}],32:[function(require,module,exports){var UIEvents = require("../../../service/UI/UIEvents");var nickname = null;@@ -8145,7 +7750,7 @@ var NicknameHandler = {};module.exports = NicknameHandler;-},{"../../../service/UI/UIEvents":114}],35:[function(require,module,exports){+},{"../../../service/UI/UIEvents":155}],33:[function(require,module,exports){/* global $ *//*** Created by hristo on 12/22/14.@@ -8242,7 +7847,7 @@ module.exports = {}}};-},{"../side_pannels/SidePanelToggler":22}],36:[function(require,module,exports){+},{"../side_pannels/SidePanelToggler":20}],34:[function(require,module,exports){/* global APP, $ */var JitsiPopover = require("../util/JitsiPopover");@@ -8625,7 +8230,7 @@ ConnectionIndicator.prototype.hideIndicator = function () {};module.exports = ConnectionIndicator;-},{"../util/JitsiPopover":32}],37:[function(require,module,exports){+},{"../util/JitsiPopover":30}],35:[function(require,module,exports){/* global $, APP, Strophe, interfaceConfig */var Avatar = require("../avatar/Avatar");var RTCBrowserType = require("../../RTC/RTCBrowserType");@@ -9298,7 +8903,7 @@ var LargeVideo = {};module.exports = LargeVideo;-},{"../../../service/UI/UIEvents":114,"../../RTC/RTCBrowserType":10,"../../xmpp/xmpp":70,"../avatar/Avatar":18,"../toolbars/ToolbarToggler":31,"../util/UIUtil":35}],38:[function(require,module,exports){+},{"../../../service/UI/UIEvents":155,"../../RTC/RTCBrowserType":8,"../../xmpp/xmpp":68,"../avatar/Avatar":16,"../toolbars/ToolbarToggler":29,"../util/UIUtil":33}],36:[function(require,module,exports){/* global $, interfaceConfig, APP */var SmallVideo = require("./SmallVideo");var ConnectionIndicator = require("./ConnectionIndicator");@@ -9543,7 +9148,7 @@ LocalVideo.prototype.getResourceJid = function () {};module.exports = LocalVideo;-},{"../../RTC/RTCBrowserType":10,"../util/NicknameHandler":34,"../util/UIUtil":35,"./ConnectionIndicator":36,"./LargeVideo":37,"./SmallVideo":40}],39:[function(require,module,exports){+},{"../../RTC/RTCBrowserType":8,"../util/NicknameHandler":32,"../util/UIUtil":33,"./ConnectionIndicator":34,"./LargeVideo":35,"./SmallVideo":38}],37:[function(require,module,exports){/* global $, APP, require, Strophe, interfaceConfig */var ConnectionIndicator = require("./ConnectionIndicator");var SmallVideo = require("./SmallVideo");@@ -9961,7 +9566,7 @@ RemoteVideo.createContainer = function (spanId) {module.exports = RemoteVideo;-},{"../../RTC/RTCBrowserType":10,"../audio_levels/AudioLevels":14,"../avatar/Avatar":18,"../util/UIUtil":35,"./ConnectionIndicator":36,"./LargeVideo":37,"./SmallVideo":40}],40:[function(require,module,exports){+},{"../../RTC/RTCBrowserType":8,"../audio_levels/AudioLevels":12,"../avatar/Avatar":16,"../util/UIUtil":33,"./ConnectionIndicator":34,"./LargeVideo":35,"./SmallVideo":38}],38:[function(require,module,exports){/* global $, APP, require */var Avatar = require("../avatar/Avatar");var UIUtil = require("../util/UIUtil");@@ -10331,7 +9936,7 @@ SmallVideo.prototype.avatarChanged = function (thumbUrl) {};module.exports = SmallVideo;-},{"../../RTC/RTCBrowserType":10,"../avatar/Avatar":18,"../util/UIUtil":35,"./LargeVideo":37}],41:[function(require,module,exports){+},{"../../RTC/RTCBrowserType":8,"../avatar/Avatar":16,"../util/UIUtil":33,"./LargeVideo":35}],39:[function(require,module,exports){/* global config, APP, $, Strophe, require, interfaceConfig */var AudioLevels = require("../audio_levels/AudioLevels");var ContactList = require("../side_pannels/contactlist/ContactList");@@ -11321,7 +10926,7 @@ var VideoLayout = (function (my) {}(VideoLayout || {}));module.exports = VideoLayout;-},{"../../../service/RTC/MediaStreamTypes":110,"../../../service/UI/UIEvents":114,"../../RTC/RTC":9,"../../RTC/RTCBrowserType":10,"../audio_levels/AudioLevels":14,"../prezi/Prezi":20,"../side_pannels/contactlist/ContactList":27,"../util/UIUtil":35,"./LargeVideo":37,"./LocalVideo":38,"./RemoteVideo":39}],42:[function(require,module,exports){+},{"../../../service/RTC/MediaStreamTypes":151,"../../../service/UI/UIEvents":155,"../../RTC/RTC":7,"../../RTC/RTCBrowserType":8,"../audio_levels/AudioLevels":12,"../prezi/Prezi":18,"../side_pannels/contactlist/ContactList":25,"../util/UIUtil":33,"./LargeVideo":35,"./LocalVideo":36,"./RemoteVideo":37}],40:[function(require,module,exports){//var nouns = [//];var pluralNouns = [@@ -11502,7 +11107,7 @@ var RoomNameGenerator = {module.exports = RoomNameGenerator;-},{}],43:[function(require,module,exports){+},{}],41:[function(require,module,exports){/* global $, interfaceConfig */var animateTimeout, updateTimeout;@@ -11599,7 +11204,7 @@ function setupWelcomePage() {}module.exports = setupWelcomePage;-},{"./RoomnameGenerator":42}],44:[function(require,module,exports){+},{"./RoomnameGenerator":40}],42:[function(require,module,exports){/* global $, $iq, config, interfaceConfig */var params = {};function getConfigParamsFromUrl() {@@ -11650,7 +11255,7 @@ var URLProcessor = {};module.exports = URLProcessor;-},{}],45:[function(require,module,exports){+},{}],43:[function(require,module,exports){/* global APP, require */var EventEmitter = require("events");var eventEmitter = new EventEmitter();@@ -11785,7 +11390,7 @@ var ConnectionQuality = {};module.exports = ConnectionQuality;-},{"../../service/connectionquality/CQEvents":116,"../../service/xmpp/XMPPEvents":120,"events":1}],46:[function(require,module,exports){+},{"../../service/connectionquality/CQEvents":157,"../../service/xmpp/XMPPEvents":161,"events":162}],44:[function(require,module,exports){/* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,getUserMediaWithConstraints *//**@@ -12174,7 +11779,7 @@ module.exports = {};-},{"../../service/RTC/RTCEvents":111,"../../service/desktopsharing/DesktopSharingEventTypes":117,"../RTC/RTCBrowserType":10,"../RTC/adapter.screenshare":12,"events":1}],47:[function(require,module,exports){+},{"../../service/RTC/RTCEvents":152,"../../service/desktopsharing/DesktopSharingEventTypes":158,"../RTC/RTCBrowserType":8,"../RTC/adapter.screenshare":10,"events":162}],45:[function(require,module,exports){/* global APP, $ *///maps keycode to character, id of popover for given function and functionvar shortcuts = {};@@ -12272,7 +11877,7 @@ var KeyboardShortcut = {module.exports = KeyboardShortcut;-},{}],48:[function(require,module,exports){+},{}],46:[function(require,module,exports){/* global APP, require, $ *//**@@ -12402,7 +12007,7 @@ var Members = {module.exports = Members;-},{"../../service/members/Events":118,"../../service/xmpp/XMPPEvents":120,"events":1}],49:[function(require,module,exports){+},{"../../service/members/Events":159,"../../service/xmpp/XMPPEvents":161,"events":162}],47:[function(require,module,exports){var email = '';var displayName = '';var userId;@@ -12467,8 +12072,10 @@ var Settings = {module.exports = Settings;-},{}],50:[function(require,module,exports){+},{}],48:[function(require,module,exports){/* global config, $, APP, Strophe, callstats */+var jsSHA = require('jssha');+var io = require('socket.io-client');var callStats = null;function initCallback (err, msg) {@@ -12481,7 +12088,7 @@ var CallStats = {if(!config.callStatsID || !config.callStatsSecret || callStats !== null)return;- callStats = new callstats($,io,jsSHA);+ callStats = new callstats($, io, jsSHA);this.session = jingleSession;this.peerconnection = jingleSession.peerconnection.peerconnection;@@ -12544,7 +12151,7 @@ var CallStats = {};module.exports = CallStats;-},{}],51:[function(require,module,exports){+},{"jssha":71,"socket.io-client":101}],49:[function(require,module,exports){/* global config *//*** Provides statistics for the local stream.@@ -12671,7 +12278,7 @@ LocalStatsCollector.prototype.stop = function () {};module.exports = LocalStatsCollector;-},{"../RTC/RTCBrowserType":10}],52:[function(require,module,exports){+},{"../RTC/RTCBrowserType":8}],50:[function(require,module,exports){/* global require, ssrc2jid *//* jshint -W117 */var RTCBrowserType = require("../RTC/RTCBrowserType");@@ -13406,7 +13013,7 @@ StatsCollector.prototype.processAudioLevelReport = function () {}};-},{"../RTC/RTCBrowserType":10}],53:[function(require,module,exports){+},{"../RTC/RTCBrowserType":8}],51:[function(require,module,exports){/* global require, APP *//*** Created by hristo on 8/4/14.@@ -13548,7 +13155,7 @@ var statistics = {module.exports = statistics;-},{"../../service/RTC/RTCEvents":111,"../../service/RTC/StreamEventTypes.js":113,"../../service/xmpp/XMPPEvents":120,"./CallStats":50,"./LocalStatsCollector.js":51,"./RTPStatsCollector.js":52,"events":1}],54:[function(require,module,exports){+},{"../../service/RTC/RTCEvents":152,"../../service/RTC/StreamEventTypes.js":154,"../../service/xmpp/XMPPEvents":161,"./CallStats":48,"./LocalStatsCollector.js":49,"./RTPStatsCollector.js":50,"events":162}],52:[function(require,module,exports){/* global $, require, config, interfaceConfig */var i18n = require("i18next-client");var languages = require("../../service/translation/languages");@@ -13686,7 +13293,7 @@ module.exports = {}};-},{"../../service/translation/languages":119,"../settings/Settings":49,"i18next-client":72}],55:[function(require,module,exports){+},{"../../service/translation/languages":160,"../settings/Settings":47,"i18next-client":70}],53:[function(require,module,exports){/** JingleSession provides an API to manage a single Jingle session. We will* have different implementations depending on the underlying interface used@@ -13815,7 +13422,7 @@ JingleSession.prototype.setAnswer = function(jingle) {};module.exports = JingleSession;-},{}],56:[function(require,module,exports){+},{}],54:[function(require,module,exports){/* jshint -W117 */var JingleSession = require("./JingleSession");var TraceablePeerConnection = require("./TraceablePeerConnection");@@ -15261,7 +14868,7 @@ JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {module.exports = JingleSessionPC;-},{"../../service/xmpp/XMPPEvents":120,"../RTC/RTCBrowserType":10,"./JingleSession":55,"./LocalSSRCReplacement":57,"./SDP":58,"./SDPDiffer":59,"./SDPUtil":60,"./TraceablePeerConnection":61,"async":71,"sdp-transform":107}],57:[function(require,module,exports){+},{"../../service/xmpp/XMPPEvents":161,"../RTC/RTCBrowserType":8,"./JingleSession":53,"./LocalSSRCReplacement":55,"./SDP":56,"./SDPDiffer":57,"./SDPUtil":58,"./TraceablePeerConnection":59,"async":69,"sdp-transform":98}],55:[function(require,module,exports){/* global $ *//*@@ -15531,7 +15138,7 @@ var LocalSSRCReplacement = {module.exports = LocalSSRCReplacement;-},{"../RTC/RTCBrowserType":10,"./SDP":58}],58:[function(require,module,exports){+},{"../RTC/RTCBrowserType":8,"./SDP":56}],56:[function(require,module,exports){/* jshint -W117 */var SDPUtil = require("./SDPUtil");@@ -16157,7 +15764,7 @@ SDP.prototype.jingle2media = function (content) {module.exports = SDP;-},{"./SDPUtil":60}],59:[function(require,module,exports){+},{"./SDPUtil":58}],57:[function(require,module,exports){var SDPUtil = require("./SDPUtil");@@ -16329,7 +15936,7 @@ SDPDiffer.prototype.toJingle = function(modify) {};module.exports = SDPDiffer;-},{"./SDPUtil":60}],60:[function(require,module,exports){+},{"./SDPUtil":58}],58:[function(require,module,exports){SDPUtil = {filter_special_chars: function (text) {return text.replace(/[\\\/\{,\}\+]/g, "");@@ -16682,7 +16289,7 @@ SDPUtil = {}};module.exports = SDPUtil;-},{}],61:[function(require,module,exports){+},{}],59:[function(require,module,exports){var RTC = require('../RTC/RTC');var RTCBrowserType = require("../RTC/RTCBrowserType.js");var XMPPEvents = require("../../service/xmpp/XMPPEvents");@@ -17137,7 +16744,7 @@ TraceablePeerConnection.prototype.getStats = function(callback, errback) {module.exports = TraceablePeerConnection;-},{"../../service/xmpp/XMPPEvents":120,"../RTC/RTC":9,"../RTC/RTCBrowserType.js":10,"./LocalSSRCReplacement":57,"sdp-interop":93,"sdp-simulcast":100,"sdp-transform":107}],62:[function(require,module,exports){+},{"../../service/xmpp/XMPPEvents":161,"../RTC/RTC":7,"../RTC/RTCBrowserType.js":8,"./LocalSSRCReplacement":55,"sdp-interop":92,"sdp-simulcast":95,"sdp-transform":98}],60:[function(require,module,exports){/* global $, $iq, APP, config, messageHandler,roomName, sessionTerminated, Strophe, Util */var XMPPEvents = require("../../service/xmpp/XMPPEvents");@@ -17570,7 +17177,7 @@ module.exports = Moderator;-},{"../../service/authentication/AuthenticationEvents":115,"../../service/xmpp/XMPPEvents":120,"../settings/Settings":49}],63:[function(require,module,exports){+},{"../../service/authentication/AuthenticationEvents":156,"../../service/xmpp/XMPPEvents":161,"../settings/Settings":47}],61:[function(require,module,exports){/* global $, $iq, config, connection, focusMucJid, messageHandler,Toolbar, Util */var Moderator = require("./moderator");@@ -17740,7 +17347,7 @@ var Recording = {};module.exports = Recording;-},{"./moderator":62}],64:[function(require,module,exports){+},{"./moderator":60}],62:[function(require,module,exports){/* jshint -W117 *//* a simple MUC connection plugin* can only handle a single MUC room@@ -18382,7 +17989,7 @@ module.exports = function(XMPP, eventEmitter) {};-},{"../../service/xmpp/XMPPEvents":120,"./moderator":62}],65:[function(require,module,exports){+},{"../../service/xmpp/XMPPEvents":161,"./moderator":60}],63:[function(require,module,exports){/* jshint -W117 */var JingleSession = require("./JingleSessionPC");@@ -18725,7 +18332,7 @@ module.exports = function(XMPP, eventEmitter) {};-},{"../../service/xmpp/XMPPEvents":120,"../RTC/RTCBrowserType":10,"./JingleSessionPC":56}],66:[function(require,module,exports){+},{"../../service/xmpp/XMPPEvents":161,"../RTC/RTCBrowserType":8,"./JingleSessionPC":54}],64:[function(require,module,exports){/* global Strophe */module.exports = function () {@@ -18746,7 +18353,7 @@ module.exports = function () {}});};-},{}],67:[function(require,module,exports){+},{}],65:[function(require,module,exports){/* global $, $iq, config, connection, focusMucJid, forceMuted,setAudioMuted, Strophe *//**@@ -18807,7 +18414,7 @@ module.exports = function (XMPP, eventEmitter) {}});}-},{"../../service/xmpp/XMPPEvents":120}],68:[function(require,module,exports){+},{"../../service/xmpp/XMPPEvents":161}],66:[function(require,module,exports){/* jshint -W117 */module.exports = function() {Strophe.addConnectionPlugin('rayo',@@ -18904,7 +18511,7 @@ module.exports = function() {);};-},{}],69:[function(require,module,exports){+},{}],67:[function(require,module,exports){/*** Strophe logger implementation. Logs from level WARN and above.*/@@ -18948,7 +18555,7 @@ module.exports = function () {};};-},{}],70:[function(require,module,exports){+},{}],68:[function(require,module,exports){/* global $, APP, config, Strophe*/var Moderator = require("./moderator");var EventEmitter = require("events");@@ -19518,7 +19125,7 @@ var XMPP = {module.exports = XMPP;-},{"../../service/RTC/RTCEvents":111,"../../service/RTC/StreamEventTypes":113,"../../service/xmpp/XMPPEvents":120,"../settings/Settings":49,"./SDP":58,"./moderator":62,"./recording":63,"./strophe.emuc":64,"./strophe.jingle":65,"./strophe.logger":66,"./strophe.moderate":67,"./strophe.rayo":68,"./strophe.util":69,"events":1,"pako":73,"retry":89}],71:[function(require,module,exports){+},{"../../service/RTC/RTCEvents":152,"../../service/RTC/StreamEventTypes":154,"../../service/xmpp/XMPPEvents":161,"../settings/Settings":47,"./SDP":56,"./moderator":60,"./recording":61,"./strophe.emuc":62,"./strophe.jingle":63,"./strophe.logger":64,"./strophe.moderate":65,"./strophe.rayo":66,"./strophe.util":67,"events":162,"pako":72,"retry":88}],69:[function(require,module,exports){(function (process){/*!* async@@ -20645,7 +20252,7 @@ module.exports = XMPP;}());}).call(this,require('_process'))-},{"_process":2}],72:[function(require,module,exports){+},{"_process":163}],70:[function(require,module,exports){// i18next, v1.7.7// Copyright (c)2014 Jan Mühlemann (jamuhl).// Distributed under MIT license@@ -22768,7 +22375,43 @@ module.exports = XMPP;i18n.options = o;})();-},{"jquery":"jquery"}],73:[function(require,module,exports){+},{"jquery":"jquery"}],71:[function(require,module,exports){+/*+ A JavaScript implementation of the SHA family of hashes, as+ defined in FIPS PUB 180-2 as well as the corresponding HMAC implementation+ as defined in FIPS PUB 198a++ Copyright Brian Turek 2008-2013+ Distributed under the BSD License+ See http://caligatio.github.com/jsSHA/ for more information++ Several functions taken from Paul Johnston+*/+(function(T){function z(a,c,b){var g=0,f=[0],h="",l=null,h=b||"UTF8";if("UTF8"!==h&&"UTF16"!==h)throw"encoding must be UTF8 or UTF16";if("HEX"===c){if(0!==a.length%2)throw"srcString of HEX type must be in byte increments";l=B(a);g=l.binLen;f=l.value}else if("ASCII"===c||"TEXT"===c)l=J(a,h),g=l.binLen,f=l.value;else if("B64"===c)l=K(a),g=l.binLen,f=l.value;else throw"inputFormat must be HEX, TEXT, ASCII, or B64";this.getHash=function(a,c,b,h){var l=null,d=f.slice(),n=g,p;3===arguments.length?"number"!==+typeof b&&(h=b,b=1):2===arguments.length&&(b=1);if(b!==parseInt(b,10)||1>b)throw"numRounds must a integer >= 1";switch(c){case "HEX":l=L;break;case "B64":l=M;break;default:throw"format must be HEX or B64";}if("SHA-1"===a)for(p=0;p<b;p++)d=y(d,n),n=160;else if("SHA-224"===a)for(p=0;p<b;p++)d=v(d,n,a),n=224;else if("SHA-256"===a)for(p=0;p<b;p++)d=v(d,n,a),n=256;else if("SHA-384"===a)for(p=0;p<b;p++)d=v(d,n,a),n=384;else if("SHA-512"===a)for(p=0;p<b;p++)d=v(d,n,a),n=512;else throw"Chosen SHA variant is not supported";+return l(d,N(h))};this.getHMAC=function(a,b,c,l,s){var d,n,p,m,w=[],x=[];d=null;switch(l){case "HEX":l=L;break;case "B64":l=M;break;default:throw"outputFormat must be HEX or B64";}if("SHA-1"===c)n=64,m=160;else if("SHA-224"===c)n=64,m=224;else if("SHA-256"===c)n=64,m=256;else if("SHA-384"===c)n=128,m=384;else if("SHA-512"===c)n=128,m=512;else throw"Chosen SHA variant is not supported";if("HEX"===b)d=B(a),p=d.binLen,d=d.value;else if("ASCII"===b||"TEXT"===b)d=J(a,h),p=d.binLen,d=d.value;else if("B64"===+b)d=K(a),p=d.binLen,d=d.value;else throw"inputFormat must be HEX, TEXT, ASCII, or B64";a=8*n;b=n/4-1;n<p/8?(d="SHA-1"===c?y(d,p):v(d,p,c),d[b]&=4294967040):n>p/8&&(d[b]&=4294967040);for(n=0;n<=b;n+=1)w[n]=d[n]^909522486,x[n]=d[n]^1549556828;c="SHA-1"===c?y(x.concat(y(w.concat(f),a+g)),a+m):v(x.concat(v(w.concat(f),a+g,c)),a+m,c);return l(c,N(s))}}function s(a,c){this.a=a;this.b=c}function J(a,c){var b=[],g,f=[],h=0,l;if("UTF8"===c)for(l=0;l<a.length;l+=1)for(g=a.charCodeAt(l),f=[],2048<g?(f[0]=224|+(g&61440)>>>12,f[1]=128|(g&4032)>>>6,f[2]=128|g&63):128<g?(f[0]=192|(g&1984)>>>6,f[1]=128|g&63):f[0]=g,g=0;g<f.length;g+=1)b[h>>>2]|=f[g]<<24-h%4*8,h+=1;else if("UTF16"===c)for(l=0;l<a.length;l+=1)b[h>>>2]|=a.charCodeAt(l)<<16-h%4*8,h+=2;return{value:b,binLen:8*h}}function B(a){var c=[],b=a.length,g,f;if(0!==b%2)throw"String of HEX type must be in byte increments";for(g=0;g<b;g+=2){f=parseInt(a.substr(g,2),16);if(isNaN(f))throw"String of HEX type contains invalid characters";c[g>>>3]|=f<<24-g%8*4}return{value:c,+binLen:4*b}}function K(a){var c=[],b=0,g,f,h,l,r;if(-1===a.search(/^[a-zA-Z0-9=+\/]+$/))throw"Invalid character in base-64 string";g=a.indexOf("=");a=a.replace(/\=/g,"");if(-1!==g&&g<a.length)throw"Invalid '=' found in base-64 string";for(f=0;f<a.length;f+=4){r=a.substr(f,4);for(h=l=0;h<r.length;h+=1)g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(r[h]),l|=g<<18-6*h;for(h=0;h<r.length-1;h+=1)c[b>>2]|=(l>>>16-8*h&255)<<24-b%4*8,b+=1}return{value:c,binLen:8*b}}function L(a,+c){var b="",g=4*a.length,f,h;for(f=0;f<g;f+=1)h=a[f>>>2]>>>8*(3-f%4),b+="0123456789abcdef".charAt(h>>>4&15)+"0123456789abcdef".charAt(h&15);return c.outputUpper?b.toUpperCase():b}function M(a,c){var b="",g=4*a.length,f,h,l;for(f=0;f<g;f+=3)for(l=(a[f>>>2]>>>8*(3-f%4)&255)<<16|(a[f+1>>>2]>>>8*(3-(f+1)%4)&255)<<8|a[f+2>>>2]>>>8*(3-(f+2)%4)&255,h=0;4>h;h+=1)b=8*f+6*h<=32*a.length?b+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(l>>>6*(3-h)&63):b+c.b64Pad;return b}function N(a){var c=+{outputUpper:!1,b64Pad:"="};try{a.hasOwnProperty("outputUpper")&&(c.outputUpper=a.outputUpper),a.hasOwnProperty("b64Pad")&&(c.b64Pad=a.b64Pad)}catch(b){}if("boolean"!==typeof c.outputUpper)throw"Invalid outputUpper formatting option";if("string"!==typeof c.b64Pad)throw"Invalid b64Pad formatting option";return c}function U(a,c){return a<<c|a>>>32-c}function u(a,c){return a>>>c|a<<32-c}function t(a,c){var b=null,b=new s(a.a,a.b);return b=32>=c?new s(b.a>>>c|b.b<<32-c&4294967295,b.b>>>c|b.a<<32-c&4294967295):+new s(b.b>>>c-32|b.a<<64-c&4294967295,b.a>>>c-32|b.b<<64-c&4294967295)}function O(a,c){var b=null;return b=32>=c?new s(a.a>>>c,a.b>>>c|a.a<<32-c&4294967295):new s(0,a.a>>>c-32)}function V(a,c,b){return a^c^b}function P(a,c,b){return a&c^~a&b}function W(a,c,b){return new s(a.a&c.a^~a.a&b.a,a.b&c.b^~a.b&b.b)}function Q(a,c,b){return a&c^a&b^c&b}function X(a,c,b){return new s(a.a&c.a^a.a&b.a^c.a&b.a,a.b&c.b^a.b&b.b^c.b&b.b)}function Y(a){return u(a,2)^u(a,13)^u(a,22)}function Z(a){var c=t(a,28),b=t(a,+34);a=t(a,39);return new s(c.a^b.a^a.a,c.b^b.b^a.b)}function $(a){return u(a,6)^u(a,11)^u(a,25)}function aa(a){var c=t(a,14),b=t(a,18);a=t(a,41);return new s(c.a^b.a^a.a,c.b^b.b^a.b)}function ba(a){return u(a,7)^u(a,18)^a>>>3}function ca(a){var c=t(a,1),b=t(a,8);a=O(a,7);return new s(c.a^b.a^a.a,c.b^b.b^a.b)}function da(a){return u(a,17)^u(a,19)^a>>>10}function ea(a){var c=t(a,19),b=t(a,61);a=O(a,6);return new s(c.a^b.a^a.a,c.b^b.b^a.b)}function R(a,c){var b=(a&65535)+(c&65535);return((a>>>16)+(c>>>+16)+(b>>>16)&65535)<<16|b&65535}function fa(a,c,b,g){var f=(a&65535)+(c&65535)+(b&65535)+(g&65535);return((a>>>16)+(c>>>16)+(b>>>16)+(g>>>16)+(f>>>16)&65535)<<16|f&65535}function S(a,c,b,g,f){var h=(a&65535)+(c&65535)+(b&65535)+(g&65535)+(f&65535);return((a>>>16)+(c>>>16)+(b>>>16)+(g>>>16)+(f>>>16)+(h>>>16)&65535)<<16|h&65535}function ga(a,c){var b,g,f;b=(a.b&65535)+(c.b&65535);g=(a.b>>>16)+(c.b>>>16)+(b>>>16);f=(g&65535)<<16|b&65535;b=(a.a&65535)+(c.a&65535)+(g>>>16);g=(a.a>>>16)+(c.a>>>16)+(b>>>+16);return new s((g&65535)<<16|b&65535,f)}function ha(a,c,b,g){var f,h,l;f=(a.b&65535)+(c.b&65535)+(b.b&65535)+(g.b&65535);h=(a.b>>>16)+(c.b>>>16)+(b.b>>>16)+(g.b>>>16)+(f>>>16);l=(h&65535)<<16|f&65535;f=(a.a&65535)+(c.a&65535)+(b.a&65535)+(g.a&65535)+(h>>>16);h=(a.a>>>16)+(c.a>>>16)+(b.a>>>16)+(g.a>>>16)+(f>>>16);return new s((h&65535)<<16|f&65535,l)}function ia(a,c,b,g,f){var h,l,r;h=(a.b&65535)+(c.b&65535)+(b.b&65535)+(g.b&65535)+(f.b&65535);l=(a.b>>>16)+(c.b>>>16)+(b.b>>>16)+(g.b>>>16)+(f.b>>>+16)+(h>>>16);r=(l&65535)<<16|h&65535;h=(a.a&65535)+(c.a&65535)+(b.a&65535)+(g.a&65535)+(f.a&65535)+(l>>>16);l=(a.a>>>16)+(c.a>>>16)+(b.a>>>16)+(g.a>>>16)+(f.a>>>16)+(h>>>16);return new s((l&65535)<<16|h&65535,r)}function y(a,c){var b=[],g,f,h,l,r,s,u=P,t=V,v=Q,d=U,n=R,p,m,w=S,x,q=[1732584193,4023233417,2562383102,271733878,3285377520];a[c>>>5]|=128<<24-c%32;a[(c+65>>>9<<4)+15]=c;x=a.length;for(p=0;p<x;p+=16){g=q[0];f=q[1];h=q[2];l=q[3];r=q[4];for(m=0;80>m;m+=1)b[m]=16>m?a[m+p]:d(b[m-3]^b[m-8]^b[m-+14]^b[m-16],1),s=20>m?w(d(g,5),u(f,h,l),r,1518500249,b[m]):40>m?w(d(g,5),t(f,h,l),r,1859775393,b[m]):60>m?w(d(g,5),v(f,h,l),r,2400959708,b[m]):w(d(g,5),t(f,h,l),r,3395469782,b[m]),r=l,l=h,h=d(f,30),f=g,g=s;q[0]=n(g,q[0]);q[1]=n(f,q[1]);q[2]=n(h,q[2]);q[3]=n(l,q[3]);q[4]=n(r,q[4])}return q}function v(a,c,b){var g,f,h,l,r,t,u,v,z,d,n,p,m,w,x,q,y,C,D,E,F,G,H,I,e,A=[],B,k=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,+1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,+2361852424,2428436474,2756734187,3204031479,3329325298];d=[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428];f=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];if("SHA-224"===b||"SHA-256"===b)n=64,g=(c+65>>>9<<4)+15,w=16,x=1,e=Number,q=R,y=fa,C=S,D=ba,E=da,F=Y,G=$,I=Q,H=P,d="SHA-224"===b?d:f;else if("SHA-384"===b||"SHA-512"===b)n=80,g=(c+128>>>10<<5)+31,w=32,x=2,e=s,q=ga,y=ha,C=ia,D=ca,E=ea,F=Z,G=aa,I=X,H=W,k=[new e(k[0],+3609767458),new e(k[1],602891725),new e(k[2],3964484399),new e(k[3],2173295548),new e(k[4],4081628472),new e(k[5],3053834265),new e(k[6],2937671579),new e(k[7],3664609560),new e(k[8],2734883394),new e(k[9],1164996542),new e(k[10],1323610764),new e(k[11],3590304994),new e(k[12],4068182383),new e(k[13],991336113),new e(k[14],633803317),new e(k[15],3479774868),new e(k[16],2666613458),new e(k[17],944711139),new e(k[18],2341262773),new e(k[19],2007800933),new e(k[20],1495990901),new e(k[21],1856431235),+new e(k[22],3175218132),new e(k[23],2198950837),new e(k[24],3999719339),new e(k[25],766784016),new e(k[26],2566594879),new e(k[27],3203337956),new e(k[28],1034457026),new e(k[29],2466948901),new e(k[30],3758326383),new e(k[31],168717936),new e(k[32],1188179964),new e(k[33],1546045734),new e(k[34],1522805485),new e(k[35],2643833823),new e(k[36],2343527390),new e(k[37],1014477480),new e(k[38],1206759142),new e(k[39],344077627),new e(k[40],1290863460),new e(k[41],3158454273),new e(k[42],3505952657),+new e(k[43],106217008),new e(k[44],3606008344),new e(k[45],1432725776),new e(k[46],1467031594),new e(k[47],851169720),new e(k[48],3100823752),new e(k[49],1363258195),new e(k[50],3750685593),new e(k[51],3785050280),new e(k[52],3318307427),new e(k[53],3812723403),new e(k[54],2003034995),new e(k[55],3602036899),new e(k[56],1575990012),new e(k[57],1125592928),new e(k[58],2716904306),new e(k[59],442776044),new e(k[60],593698344),new e(k[61],3733110249),new e(k[62],2999351573),new e(k[63],3815920427),new e(3391569614,+3928383900),new e(3515267271,566280711),new e(3940187606,3454069534),new e(4118630271,4000239992),new e(116418474,1914138554),new e(174292421,2731055270),new e(289380356,3203993006),new e(460393269,320620315),new e(685471733,587496836),new e(852142971,1086792851),new e(1017036298,365543100),new e(1126000580,2618297676),new e(1288033470,3409855158),new e(1501505948,4234509866),new e(1607167915,987167468),new e(1816402316,1246189591)],d="SHA-384"===b?[new e(3418070365,d[0]),new e(1654270250,d[1]),new e(2438529370,+d[2]),new e(355462360,d[3]),new e(1731405415,d[4]),new e(41048885895,d[5]),new e(3675008525,d[6]),new e(1203062813,d[7])]:[new e(f[0],4089235720),new e(f[1],2227873595),new e(f[2],4271175723),new e(f[3],1595750129),new e(f[4],2917565137),new e(f[5],725511199),new e(f[6],4215389547),new e(f[7],327033209)];else throw"Unexpected error in SHA-2 implementation";a[c>>>5]|=128<<24-c%32;a[g]=c;B=a.length;for(p=0;p<B;p+=w){c=d[0];g=d[1];f=d[2];h=d[3];l=d[4];r=d[5];t=d[6];u=d[7];for(m=0;m<n;m+=1)A[m]=16>m?+new e(a[m*x+p],a[m*x+p+1]):y(E(A[m-2]),A[m-7],D(A[m-15]),A[m-16]),v=C(u,G(l),H(l,r,t),k[m],A[m]),z=q(F(c),I(c,g,f)),u=t,t=r,r=l,l=q(h,v),h=f,f=g,g=c,c=q(v,z);d[0]=q(c,d[0]);d[1]=q(g,d[1]);d[2]=q(f,d[2]);d[3]=q(h,d[3]);d[4]=q(l,d[4]);d[5]=q(r,d[5]);d[6]=q(t,d[6]);d[7]=q(u,d[7])}if("SHA-224"===b)a=[d[0],d[1],d[2],d[3],d[4],d[5],d[6]];else if("SHA-256"===b)a=d;else if("SHA-384"===b)a=[d[0].a,d[0].b,d[1].a,d[1].b,d[2].a,d[2].b,d[3].a,d[3].b,d[4].a,d[4].b,d[5].a,d[5].b];else if("SHA-512"===b)a=[d[0].a,+d[0].b,d[1].a,d[1].b,d[2].a,d[2].b,d[3].a,d[3].b,d[4].a,d[4].b,d[5].a,d[5].b,d[6].a,d[6].b,d[7].a,d[7].b];else throw"Unexpected error in SHA-2 implementation";return a}"function"===typeof define&&typeof define.amd?define(function(){return z}):"undefined"!==typeof exports?"undefined"!==typeof module&&module.exports?module.exports=exports=z:exports=z:T.jsSHA=z})(this);++},{}],72:[function(require,module,exports){// Top level file is just a mixin of submodules & constants'use strict';@@ -22784,7 +22427,7 @@ assign(pako, deflate, inflate, constants);module.exports = pako;-},{"./lib/deflate":74,"./lib/inflate":75,"./lib/utils/common":76,"./lib/zlib/constants":79}],74:[function(require,module,exports){+},{"./lib/deflate":73,"./lib/inflate":74,"./lib/utils/common":75,"./lib/zlib/constants":78}],73:[function(require,module,exports){'use strict';@@ -23162,7 +22805,7 @@ exports.deflate = deflate;exports.deflateRaw = deflateRaw;exports.gzip = gzip;-},{"./utils/common":76,"./utils/strings":77,"./zlib/deflate.js":81,"./zlib/messages":86,"./zlib/zstream":88}],75:[function(require,module,exports){+},{"./utils/common":75,"./utils/strings":76,"./zlib/deflate.js":80,"./zlib/messages":85,"./zlib/zstream":87}],74:[function(require,module,exports){'use strict';@@ -23543,7 +23186,7 @@ exports.inflate = inflate;exports.inflateRaw = inflateRaw;exports.ungzip = inflate;-},{"./utils/common":76,"./utils/strings":77,"./zlib/constants":79,"./zlib/gzheader":82,"./zlib/inflate.js":84,"./zlib/messages":86,"./zlib/zstream":88}],76:[function(require,module,exports){+},{"./utils/common":75,"./utils/strings":76,"./zlib/constants":78,"./zlib/gzheader":81,"./zlib/inflate.js":83,"./zlib/messages":85,"./zlib/zstream":87}],75:[function(require,module,exports){'use strict';@@ -23647,7 +23290,7 @@ exports.setTyped = function (on) {exports.setTyped(TYPED_OK);-},{}],77:[function(require,module,exports){+},{}],76:[function(require,module,exports){// String encode/decode helpers'use strict';@@ -23834,7 +23477,7 @@ exports.utf8border = function(buf, max) {return (pos + _utf8len[buf[pos]] > max) ? pos : max;};-},{"./common":76}],78:[function(require,module,exports){+},{"./common":75}],77:[function(require,module,exports){'use strict';// Note: adler32 takes 12% for level 0 and 2% for level 6.@@ -23868,7 +23511,7 @@ function adler32(adler, buf, len, pos) {module.exports = adler32;-},{}],79:[function(require,module,exports){+},{}],78:[function(require,module,exports){module.exports = {/* Allowed flush values; see deflate() and inflate() below for details */@@ -23917,7 +23560,7 @@ module.exports = {//Z_NULL: null // Use -1 or null inline, depending on var type};-},{}],80:[function(require,module,exports){+},{}],79:[function(require,module,exports){'use strict';// Note: we can't get significant speed boost here.@@ -23960,7 +23603,7 @@ function crc32(crc, buf, len, pos) {module.exports = crc32;-},{}],81:[function(require,module,exports){+},{}],80:[function(require,module,exports){'use strict';var utils = require('../utils/common');@@ -25727,7 +25370,7 @@ exports.deflatePrime = deflatePrime;exports.deflateTune = deflateTune;*/-},{"../utils/common":76,"./adler32":78,"./crc32":80,"./messages":86,"./trees":87}],82:[function(require,module,exports){+},{"../utils/common":75,"./adler32":77,"./crc32":79,"./messages":85,"./trees":86}],81:[function(require,module,exports){'use strict';@@ -25769,7 +25412,7 @@ function GZheader() {module.exports = GZheader;-},{}],83:[function(require,module,exports){+},{}],82:[function(require,module,exports){'use strict';// See state defs from inflate.js@@ -26096,7 +25739,7 @@ module.exports = function inflate_fast(strm, start) {return;};-},{}],84:[function(require,module,exports){+},{}],83:[function(require,module,exports){'use strict';@@ -27601,7 +27244,7 @@ exports.inflateSyncPoint = inflateSyncPoint;exports.inflateUndermine = inflateUndermine;*/-},{"../utils/common":76,"./adler32":78,"./crc32":80,"./inffast":83,"./inftrees":85}],85:[function(require,module,exports){+},{"../utils/common":75,"./adler32":77,"./crc32":79,"./inffast":82,"./inftrees":84}],84:[function(require,module,exports){'use strict';@@ -27930,7 +27573,7 @@ module.exports = function inflate_table(type, lens, lens_index, codes, table, tareturn 0;};-},{"../utils/common":76}],86:[function(require,module,exports){+},{"../utils/common":75}],85:[function(require,module,exports){'use strict';module.exports = {@@ -27945,7 +27588,7 @@ module.exports = {'-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */};-},{}],87:[function(require,module,exports){+},{}],86:[function(require,module,exports){'use strict';@@ -29146,7 +28789,7 @@ exports._tr_flush_block = _tr_flush_block;exports._tr_tally = _tr_tally;exports._tr_align = _tr_align;-},{"../utils/common":76}],88:[function(require,module,exports){+},{"../utils/common":75}],87:[function(require,module,exports){'use strict';@@ -29177,9 +28820,9 @@ function ZStream() {module.exports = ZStream;-},{}],89:[function(require,module,exports){+},{}],88:[function(require,module,exports){module.exports = require('./lib/retry');-},{"./lib/retry":90}],90:[function(require,module,exports){+},{"./lib/retry":89}],89:[function(require,module,exports){var RetryOperation = require('./retry_operation');exports.operation = function(options) {@@ -29230,7 +28873,7 @@ exports._createTimeout = function(attempt, opts) {return timeout;};-},{"./retry_operation":91}],91:[function(require,module,exports){+},{"./retry_operation":90}],90:[function(require,module,exports){function RetryOperation(timeouts) {this._timeouts = timeouts;this._fn = null;@@ -29340,7 +28983,7 @@ RetryOperation.prototype.mainError = function() {return mainError;};-},{}],92:[function(require,module,exports){+},{}],91:[function(require,module,exports){module.exports = function arrayEquals(array) {// if the other array is a falsy value, returnif (!array)@@ -29366,10 +29009,10 @@ module.exports = function arrayEquals(array) {}-},{}],93:[function(require,module,exports){+},{}],92:[function(require,module,exports){exports.Interop = require('./interop');-},{"./interop":94}],94:[function(require,module,exports){+},{"./interop":93}],93:[function(require,module,exports){"use strict";var transform = require('./transform');@@ -29951,7 +29594,7 @@ Interop.prototype.toUnifiedPlan = function(desc) {//#endregion};-},{"./array-equals":92,"./transform":95}],95:[function(require,module,exports){+},{"./array-equals":91,"./transform":94}],94:[function(require,module,exports){var transform = require('sdp-transform');exports.write = function(session, opts) {@@ -30050,38 +29693,491 @@ exports.parse = function(sdp) {};-},{"sdp-transform":97}],96:[function(require,module,exports){-var grammar = module.exports = {- v: [{- name: 'version',- reg: /^(\d*)$/- }],- o: [{ //o=- 20518 0 IN IP4 203.0.113.1- // NB: sessionId will be a String in most cases because it is huge- name: 'origin',- reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,- names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],- format: "%s %s %d %s IP%d %s"- }],- // default parsing of these only (though some of these feel outdated)- s: [{ name: 'name' }],- i: [{ name: 'description' }],- u: [{ name: 'uri' }],- e: [{ name: 'email' }],- p: [{ name: 'phone' }],- z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..- r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly- //k: [{}], // outdated thing ignored- t: [{ //t=0 0- name: 'timing',- reg: /^(\d*) (\d*)/,- names: ['start', 'stop'],- format: "%d %d"- }],- c: [{ //c=IN IP4 10.47.197.26- name: 'connection',- reg: /^IN IP(\d) (\S*)/,- names: ['version', 'ip'],+},{"sdp-transform":98}],95:[function(require,module,exports){+var transform = require('sdp-transform');+var transformUtils = require('./transform-utils');+var parseSsrcs = transformUtils.parseSsrcs;+var writeSsrcs = transformUtils.writeSsrcs;++//region Constants++var DEFAULT_NUM_OF_LAYERS = 3;++//endregion++//region Ctor++function Simulcast(options) {++ this.options = options ? options : {};++ if (!this.options.numOfLayers) {+ this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;+ }++ this.layers = [];+}++//endregion++//region Stateless private utility functions++/**+ * Returns a random integer between min (included) and max (excluded)+ * Using Math.round() gives a non-uniform distribution!+ * @returns {number}+ */+function generateSSRC() {+ var min = 0, max = 0xffffffff;+ return Math.floor(Math.random() * (max - min)) + min;+};++function processVideo(session, action) {+ if (session == null || !Array.isArray(session.media)) {+ return;+ }++ session.media.forEach(function (mLine) {+ if (mLine.type === 'video') {+ action(mLine);+ }+ });+}++function validateDescription(desc)+{+ return desc && desc != null+ && desc.type && desc.type != ''+ && desc.sdp && desc.sdp != '';+}++function explodeRemoteSimulcast(mLine) {++ if (!mLine || !Array.isArray(mLine.ssrcGroups)) {+ return;+ }++ var sources = parseSsrcs(mLine);+ var order = [];++ // Find the SIM group and explode its sources.+ var j = mLine.ssrcGroups.length;+ while (j--) {++ if (mLine.ssrcGroups[j].semantics !== 'SIM') {+ continue;+ }++ var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');++ for (var i = 0; i < simulcastSsrcs.length; i++) {++ var ssrc = simulcastSsrcs[i];+ order.push(ssrc);++ var parts = sources[ssrc].msid.split(' ');+ sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');+ sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');++ // Remove all the groups that this SSRC participates in.+ mLine.ssrcGroups.forEach(function (relatedGroup) {+ if (relatedGroup.semantics === 'SIM') {+ return;+ }++ var relatedSsrcs = relatedGroup.ssrcs.split(' ');+ if (relatedSsrcs.indexOf(ssrc) === -1) {+ return;+ }++ // Nuke all the related SSRCs.+ relatedSsrcs.forEach(function (relatedSSRC) {+ sources[relatedSSRC].msid = sources[ssrc].msid;+ sources[relatedSSRC].cname = sources[ssrc].cname;+ if (relatedSSRC !== ssrc) {+ order.push(relatedSSRC);+ }+ });++ // Schedule the related group for nuking.+ })+ }++ mLine.ssrcs = writeSsrcs(sources, order);+ mLine.ssrcGroups.splice(j, 1);+ };+}++function squeezeRemoteSimulcast(mLine) {++ if (!mLine || !Array.isArray(mLine.ssrcGroups)) {+ return;+ }++ var sources = parseSsrcs(mLine);++ // Find the SIM group and nuke it.+ mLine.ssrcGroups.some(function (simulcastGroup) {+ if (simulcastGroup.semantics !== 'SIM') {+ return false;+ }++ // Schedule the SIM group for nuking.+ simulcastGroup.nuke = true;++ var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');++ // Nuke all the higher layer SSRCs.+ for (var i = 1; i < simulcastSsrcs.length; i++) {++ var ssrc = simulcastSsrcs[i];+ delete sources[ssrc];++ // Remove all the groups that this SSRC participates in.+ mLine.ssrcGroups.forEach(function (relatedGroup) {+ if (relatedGroup.semantics === 'SIM') {+ return;+ }++ var relatedSsrcs = relatedGroup.ssrcs.split(' ');+ if (relatedSsrcs.indexOf(ssrc) === -1) {+ return;+ }++ // Nuke all the related SSRCs.+ relatedSsrcs.forEach(function (relatedSSRC) {+ delete sources[relatedSSRC];+ });++ // Schedule the related group for nuking.+ relatedGroup.nuke = true;+ })+ }++ return true;+ });++ mLine.ssrcs = writeSsrcs(sources);++ // Nuke all the scheduled groups.+ var i = mLine.ssrcGroups.length;+ while (i--) {+ if (mLine.ssrcGroups[i].nuke) {+ mLine.ssrcGroups.splice(i, 1);+ }+ }+}++function removeGoogConference(mLine) {+ if (!mLine || !Array.isArray(mLine.invalid)) {+ return;+ }++ var i = mLine.invalid.length;+ while (i--) {+ if (mLine.invalid[i].value == 'x-google-flag:conference') {+ mLine.invalid.splice(i, 1);+ }+ }+}++function assertGoogConference(mLine) {+ if (!mLine) {+ return;+ }++ if (!Array.isArray(mLine.invalid)) {+ mLine.invalid = [];+ }++ if (!mLine.invalid.some(+ function (i) { return i.value === 'x-google-flag:conference' })) {+ mLine.invalid.push({'value': 'x-google-flag:conference'});+ }+}++//endregion++//region "Private" functions++/**+ *+ * @param mLine+ * @private+ */+Simulcast.prototype._maybeInitializeLayers = function(mLine) {++ if (!mLine || mLine.type !== 'video') {+ return;+ }++ var sources = parseSsrcs(mLine);++ if (Object.keys(sources).length === 0) {++ // no sources, disable simulcast.+ if (this.layers.length !== 0) {+ this.layers = [];+ }++ return;+ }++ // find the base layer (we'll reuse its msid and cname).+ var baseLayerSSRC = Object.keys(sources)[0];+ var baseLayer = sources[baseLayerSSRC];++ // todo(gp) handle screen sharing.++ // check if base CNAME has changed and reinitialise layers.+ if (this.layers.length > 0+ && sources[baseLayerSSRC].cname !== this.layers[0].cname) {+ this.layers = [];+ }++ // (re)initialise layers+ if (this.layers.length < 1) {++ // first push the base layer.+ this.layers.push({+ ssrc: baseLayerSSRC,+ msid: baseLayer.msid,+ cname: baseLayer.cname+ });++ var rtx = false; // RFC 4588+ if (Array.isArray(mLine.rtp)) {+ rtx = mLine.rtp.some(+ function (rtpmap) { return rtpmap.codec === 'rtx'; });+ }++ if (rtx) {+ this.layers[0].rtx = generateSSRC();+ }++ // now push additional layers.+ for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {++ var layer = { ssrc: generateSSRC() };+ if (rtx) {+ layer.rtx = generateSSRC();+ }++ this.layers.push(layer);+ }+ }+};++/**+ *+ * @param mLine+ * @private+ */+Simulcast.prototype._restoreSimulcastView = function(mLine) {+ if (mLine && mLine.type === 'video' && this.layers.length !== 0) {++ var sources = {};++ var msid = this.layers[0].msid;+ var cname = this.layers[0].cname;+ var simulcastSsrcs = [];+ var ssrcGroups = [];++ for (var i = 0; i < this.layers.length; i++) {+ var layer = this.layers[i];++ sources[layer.ssrc] = { msid: msid, cname: cname };+ simulcastSsrcs.push(layer.ssrc);++ if (layer.rtx) {++ sources[layer.rtx] = {+ msid: msid,+ cname: cname+ }++ ssrcGroups.push({+ semantics: 'FID',+ ssrcs: [layer.ssrc, layer.rtx].join(' ')+ });+ }+ }++ ssrcGroups.push({+ semantics: 'SIM',+ ssrcs: simulcastSsrcs.join(' ')+ });++ mLine.ssrcGroups = ssrcGroups;+ mLine.ssrcs = writeSsrcs(sources);+ }+}++//endregion++//region "Public" functions++Simulcast.prototype.isSupported = function () {+ return window.chrome;++ // TODO this needs improvements. For example I doubt that Chrome in Android+ // has simulcast support. Also, only recent versions of Chromium have native+ // simulcast support.+}++/**+ *+ * @param desc+ * @returns {RTCSessionDescription}+ */+Simulcast.prototype.mungeRemoteDescription = function (desc) {++ if (!validateDescription(desc)) {+ return desc;+ }++ var session = transform.parse(desc.sdp);++ var self = this;+ processVideo(session, function (mLine) {++ // Handle simulcast reception.+ if (self.options.explodeRemoteSimulcast) {+ explodeRemoteSimulcast(mLine);+ } else {+ squeezeRemoteSimulcast(mLine);+ }++ // If native simulcast is enabled, we must append the x-goog-conference+ // attribute to the SDP.+ if (self.layers.length < 1) {+ removeGoogConference(mLine);+ } else {+ assertGoogConference(mLine);+ }+ });++ return new RTCSessionDescription({+ type: desc.type,+ sdp: transform.write(session)+ });+};++/**+ *+ * @param desc+ * @returns {RTCSessionDescription}+ */+Simulcast.prototype.mungeLocalDescription = function (desc) {++ if (!validateDescription(desc) || !this.isSupported()) {+ return desc;+ }++ var session = transform.parse(desc.sdp);++ var self = this;+ processVideo(session, function (mLine) {+ // Initialize native simulcast layers, if not already done.+ self._maybeInitializeLayers(mLine);++ // Update the SDP with the simulcast layers.+ self._restoreSimulcastView(mLine);+ });++ return new RTCSessionDescription({+ type: desc.type,+ sdp: transform.write(session)+ });+};++//endregion++module.exports = Simulcast;++},{"./transform-utils":96,"sdp-transform":98}],96:[function(require,module,exports){+exports.writeSsrcs = function(sources, order) {+ var ssrcs = [];++ // expand sources to ssrcs+ if (typeof sources !== 'undefined' &&+ Object.keys(sources).length !== 0) {++ if (Array.isArray(order)) {+ for (var i = 0; i < order.length; i++) {+ var ssrc = order[i];+ var source = sources[ssrc];+ Object.keys(source).forEach(function (attribute) {+ ssrcs.push({+ id: ssrc,+ attribute: attribute,+ value: source[attribute]+ });+ });+ }+ } else {+ Object.keys(sources).forEach(function (ssrc) {+ var source = sources[ssrc];+ Object.keys(source).forEach(function (attribute) {+ ssrcs.push({+ id: ssrc,+ attribute: attribute,+ value: source[attribute]+ });+ });+ });+ }+ }++ return ssrcs;+};++exports.parseSsrcs = function (mLine) {+ var sources = {};+ // group sources attributes by ssrc.+ if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {+ mLine.ssrcs.forEach(function (ssrc) {+ if (!sources[ssrc.id])+ sources[ssrc.id] = {};+ sources[ssrc.id][ssrc.attribute] = ssrc.value;+ });+ }+ return sources;+};+++},{}],97:[function(require,module,exports){+var grammar = module.exports = {+ v: [{+ name: 'version',+ reg: /^(\d*)$/+ }],+ o: [{ //o=- 20518 0 IN IP4 203.0.113.1+ // NB: sessionId will be a String in most cases because it is huge+ name: 'origin',+ reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,+ names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],+ format: "%s %s %d %s IP%d %s"+ }],+ // default parsing of these only (though some of these feel outdated)+ s: [{ name: 'name' }],+ i: [{ name: 'description' }],+ u: [{ name: 'uri' }],+ e: [{ name: 'email' }],+ p: [{ name: 'phone' }],+ z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..+ r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly+ //k: [{}], // outdated thing ignored+ t: [{ //t=0 0+ name: 'timing',+ reg: /^(\d*) (\d*)/,+ names: ['start', 'stop'],+ format: "%d %d"+ }],+ c: [{ //c=IN IP4 10.47.197.26+ name: 'connection',+ reg: /^IN IP(\d) (\S*)/,+ names: ['version', 'ip'],format: "IN IP%d %s"}],b: [{ //b=AS:4000@@ -30107,1094 +30203,7984 @@ var grammar = module.exports = {"rtpmap:%d %s/%s/%s":"rtpmap:%d %s/%s";}- },- { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000- push: 'fmtp',- reg: /^fmtp:(\d*) (\S*)/,- names: ['payload', 'config'],- format: "fmtp:%d %s"- },- { //a=control:streamid=0- name: 'control',- reg: /^control:(.*)/,- format: "control:%s"- },- { //a=rtcp:65179 IN IP4 193.84.77.194- name: 'rtcp',- reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,- names: ['port', 'netType', 'ipVer', 'address'],- format: function (o) {- return (o.address != null) ?- "rtcp:%d %s IP%d %s":- "rtcp:%d";+ },+ { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000+ push: 'fmtp',+ reg: /^fmtp:(\d*) (\S*)/,+ names: ['payload', 'config'],+ format: "fmtp:%d %s"+ },+ { //a=control:streamid=0+ name: 'control',+ reg: /^control:(.*)/,+ format: "control:%s"+ },+ { //a=rtcp:65179 IN IP4 193.84.77.194+ name: 'rtcp',+ reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,+ names: ['port', 'netType', 'ipVer', 'address'],+ format: function (o) {+ return (o.address != null) ?+ "rtcp:%d %s IP%d %s":+ "rtcp:%d";+ }+ },+ { //a=rtcp-fb:98 trr-int 100+ push: 'rtcpFbTrrInt',+ reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,+ names: ['payload', 'value'],+ format: "rtcp-fb:%d trr-int %d"+ },+ { //a=rtcp-fb:98 nack rpsi+ push: 'rtcpFb',+ reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,+ names: ['payload', 'type', 'subtype'],+ format: function (o) {+ return (o.subtype != null) ?+ "rtcp-fb:%s %s %s":+ "rtcp-fb:%s %s";+ }+ },+ { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset+ //a=extmap:1/recvonly URI-gps-string+ push: 'ext',+ reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,+ names: ['value', 'uri', 'config'], // value may include "/direction" suffix+ format: function (o) {+ return (o.config != null) ?+ "extmap:%s %s %s":+ "extmap:%s %s";+ }+ },+ {+ //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32+ push: 'crypto',+ reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,+ names: ['id', 'suite', 'config', 'sessionConfig'],+ format: function (o) {+ return (o.sessionConfig != null) ?+ "crypto:%d %s %s %s":+ "crypto:%d %s %s";+ }+ },+ { //a=setup:actpass+ name: 'setup',+ reg: /^setup:(\w*)/,+ format: "setup:%s"+ },+ { //a=mid:1+ name: 'mid',+ reg: /^mid:([^\s]*)/,+ format: "mid:%s"+ },+ { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a+ name: 'msid',+ reg: /^msid:(.*)/,+ format: "msid:%s"+ },+ { //a=ptime:20+ name: 'ptime',+ reg: /^ptime:(\d*)/,+ format: "ptime:%d"+ },+ { //a=maxptime:60+ name: 'maxptime',+ reg: /^maxptime:(\d*)/,+ format: "maxptime:%d"+ },+ { //a=sendrecv+ name: 'direction',+ reg: /^(sendrecv|recvonly|sendonly|inactive)/+ },+ { //a=ice-lite+ name: 'icelite',+ reg: /^(ice-lite)/+ },+ { //a=ice-ufrag:F7gI+ name: 'iceUfrag',+ reg: /^ice-ufrag:(\S*)/,+ format: "ice-ufrag:%s"+ },+ { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g+ name: 'icePwd',+ reg: /^ice-pwd:(\S*)/,+ format: "ice-pwd:%s"+ },+ { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33+ name: 'fingerprint',+ reg: /^fingerprint:(\S*) (\S*)/,+ names: ['type', 'hash'],+ format: "fingerprint:%s %s"+ },+ {+ //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host+ //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0+ //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0+ push:'candidates',+ reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,+ names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],+ format: function (o) {+ var str = "candidate:%s %d %s %d %s %d typ %s";+ // NB: candidate has two optional chunks, so %void middle one if it's missing+ str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";+ if (o.generation != null) {+ str += " generation %d";+ }+ return str;+ }+ },+ { //a=end-of-candidates (keep after the candidates line for readability)+ name: 'endOfCandidates',+ reg: /^(end-of-candidates)/+ },+ { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...+ name: 'remoteCandidates',+ reg: /^remote-candidates:(.*)/,+ format: "remote-candidates:%s"+ },+ { //a=ice-options:google-ice+ name: 'iceOptions',+ reg: /^ice-options:(\S*)/,+ format: "ice-options:%s"+ },+ { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1+ push: "ssrcs",+ reg: /^ssrc:(\d*) ([\w_]*):(.*)/,+ names: ['id', 'attribute', 'value'],+ format: "ssrc:%d %s:%s"+ },+ { //a=ssrc-group:FEC 1 2+ push: "ssrcGroups",+ reg: /^ssrc-group:(\w*) (.*)/,+ names: ['semantics', 'ssrcs'],+ format: "ssrc-group:%s %s"+ },+ { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV+ name: "msidSemantic",+ reg: /^msid-semantic:\s?(\w*) (\S*)/,+ names: ['semantic', 'token'],+ format: "msid-semantic: %s %s" // space after ":" is not accidental+ },+ { //a=group:BUNDLE audio video+ push: 'groups',+ reg: /^group:(\w*) (.*)/,+ names: ['type', 'mids'],+ format: "group:%s %s"+ },+ { //a=rtcp-mux+ name: 'rtcpMux',+ reg: /^(rtcp-mux)/+ },+ { //a=rtcp-rsize+ name: 'rtcpRsize',+ reg: /^(rtcp-rsize)/+ },+ { // any a= that we don't understand is kepts verbatim on media.invalid+ push: 'invalid',+ names: ["value"]+ }+ ]+};++// set sensible defaults to avoid polluting the grammar with boring details+Object.keys(grammar).forEach(function (key) {+ var objs = grammar[key];+ objs.forEach(function (obj) {+ if (!obj.reg) {+ obj.reg = /(.*)/;+ }+ if (!obj.format) {+ obj.format = "%s";+ }+ });+});++},{}],98:[function(require,module,exports){+var parser = require('./parser');+var writer = require('./writer');++exports.write = writer;+exports.parse = parser.parse;+exports.parseFmtpConfig = parser.parseFmtpConfig;+exports.parsePayloads = parser.parsePayloads;+exports.parseRemoteCandidates = parser.parseRemoteCandidates;++},{"./parser":99,"./writer":100}],99:[function(require,module,exports){+var toIntIfInt = function (v) {+ return String(Number(v)) === v ? Number(v) : v;+};++var attachProperties = function (match, location, names, rawName) {+ if (rawName && !names) {+ location[rawName] = toIntIfInt(match[1]);+ }+ else {+ for (var i = 0; i < names.length; i += 1) {+ if (match[i+1] != null) {+ location[names[i]] = toIntIfInt(match[i+1]);+ }+ }+ }+};++var parseReg = function (obj, location, content) {+ var needsBlank = obj.name && obj.names;+ if (obj.push && !location[obj.push]) {+ location[obj.push] = [];+ }+ else if (needsBlank && !location[obj.name]) {+ location[obj.name] = {};+ }+ var keyLocation = obj.push ?+ {} : // blank object that will be pushed+ needsBlank ? location[obj.name] : location; // otherwise, named location or root++ attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);++ if (obj.push) {+ location[obj.push].push(keyLocation);+ }+};++var grammar = require('./grammar');+var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);++exports.parse = function (sdp) {+ var session = {}+ , media = []+ , location = session; // points at where properties go under (one of the above)++ // parse lines we understand+ sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {+ var type = l[0];+ var content = l.slice(2);+ if (type === 'm') {+ media.push({rtp: [], fmtp: []});+ location = media[media.length-1]; // point at latest media line+ }++ for (var j = 0; j < (grammar[type] || []).length; j += 1) {+ var obj = grammar[type][j];+ if (obj.reg.test(content)) {+ return parseReg(obj, location, content);+ }+ }+ });++ session.media = media; // link it up+ return session;+};++var fmtpReducer = function (acc, expr) {+ var s = expr.split('=');+ if (s.length === 2) {+ acc[s[0]] = toIntIfInt(s[1]);+ }+ return acc;+};++exports.parseFmtpConfig = function (str) {+ return str.split(';').reduce(fmtpReducer, {});+};++exports.parsePayloads = function (str) {+ return str.split(' ').map(Number);+};++exports.parseRemoteCandidates = function (str) {+ var candidates = [];+ var parts = str.split(' ').map(toIntIfInt);+ for (var i = 0; i < parts.length; i += 3) {+ candidates.push({+ component: parts[i],+ ip: parts[i + 1],+ port: parts[i + 2]+ });+ }+ return candidates;+};++},{"./grammar":97}],100:[function(require,module,exports){+var grammar = require('./grammar');++// customized util.format - discards excess arguments and can void middle ones+var formatRegExp = /%[sdv%]/g;+var format = function (formatStr) {+ var i = 1;+ var args = arguments;+ var len = args.length;+ return formatStr.replace(formatRegExp, function (x) {+ if (i >= len) {+ return x; // missing argument+ }+ var arg = args[i];+ i += 1;+ switch (x) {+ case '%%':+ return '%';+ case '%s':+ return String(arg);+ case '%d':+ return Number(arg);+ case '%v':+ return '';+ }+ });+ // NB: we discard excess arguments - they are typically undefined from makeLine+};++var makeLine = function (type, obj, location) {+ var str = obj.format instanceof Function ?+ (obj.format(obj.push ? location : location[obj.name])) :+ obj.format;++ var args = [type + '=' + str];+ if (obj.names) {+ for (var i = 0; i < obj.names.length; i += 1) {+ var n = obj.names[i];+ if (obj.name) {+ args.push(location[obj.name][n]);+ }+ else { // for mLine and push attributes+ args.push(location[obj.names[i]]);+ }+ }+ }+ else {+ args.push(location[obj.name]);+ }+ return format.apply(null, args);+};++// RFC specified order+// TODO: extend this with all the rest+var defaultOuterOrder = [+ 'v', 'o', 's', 'i',+ 'u', 'e', 'p', 'c',+ 'b', 't', 'r', 'z', 'a'+];+var defaultInnerOrder = ['i', 'c', 'b', 'a'];+++module.exports = function (session, opts) {+ opts = opts || {};+ // ensure certain properties exist+ if (session.version == null) {+ session.version = 0; // "v=0" must be there (only defined version atm)+ }+ if (session.name == null) {+ session.name = " "; // "s= " must be there if no meaningful name set+ }+ session.media.forEach(function (mLine) {+ if (mLine.payloads == null) {+ mLine.payloads = "";+ }+ });++ var outerOrder = opts.outerOrder || defaultOuterOrder;+ var innerOrder = opts.innerOrder || defaultInnerOrder;+ var sdp = [];++ // loop through outerOrder for matching properties on session+ outerOrder.forEach(function (type) {+ grammar[type].forEach(function (obj) {+ if (obj.name in session && session[obj.name] != null) {+ sdp.push(makeLine(type, obj, session));+ }+ else if (obj.push in session && session[obj.push] != null) {+ session[obj.push].forEach(function (el) {+ sdp.push(makeLine(type, obj, el));+ });+ }+ });+ });++ // then for each media line, follow the innerOrder+ session.media.forEach(function (mLine) {+ sdp.push(makeLine('m', grammar.m[0], mLine));++ innerOrder.forEach(function (type) {+ grammar[type].forEach(function (obj) {+ if (obj.name in mLine && mLine[obj.name] != null) {+ sdp.push(makeLine(type, obj, mLine));+ }+ else if (obj.push in mLine && mLine[obj.push] != null) {+ mLine[obj.push].forEach(function (el) {+ sdp.push(makeLine(type, obj, el));+ });+ }+ });+ });+ });++ return sdp.join('\r\n') + '\r\n';+};++},{"./grammar":97}],101:[function(require,module,exports){++module.exports = require('./lib/');++},{"./lib/":102}],102:[function(require,module,exports){++/**+ * Module dependencies.+ */++var url = require('./url');+var parser = require('socket.io-parser');+var Manager = require('./manager');+var debug = require('debug')('socket.io-client');++/**+ * Module exports.+ */++module.exports = exports = lookup;++/**+ * Managers cache.+ */++var cache = exports.managers = {};++/**+ * Looks up an existing `Manager` for multiplexing.+ * If the user summons:+ *+ * `io('http://localhost/a');`+ * `io('http://localhost/b');`+ *+ * We reuse the existing instance based on same scheme/port/host,+ * and we initialize sockets for each namespace.+ *+ * @api public+ */++function lookup(uri, opts) {+ if (typeof uri == 'object') {+ opts = uri;+ uri = undefined;+ }++ opts = opts || {};++ var parsed = url(uri);+ var source = parsed.source;+ var id = parsed.id;+ var io;++ if (opts.forceNew || opts['force new connection'] || false === opts.multiplex) {+ debug('ignoring socket cache for %s', source);+ io = Manager(source, opts);+ } else {+ if (!cache[id]) {+ debug('new io instance for %s', source);+ cache[id] = Manager(source, opts);+ }+ io = cache[id];+ }++ return io.socket(parsed.path);+}++/**+ * Protocol version.+ *+ * @api public+ */++exports.protocol = parser.protocol;++/**+ * `connect`.+ *+ * @param {String} uri+ * @api public+ */++exports.connect = lookup;++/**+ * Expose constructors for standalone build.+ *+ * @api public+ */++exports.Manager = require('./manager');+exports.Socket = require('./socket');++},{"./manager":103,"./socket":105,"./url":106,"debug":110,"socket.io-parser":146}],103:[function(require,module,exports){++/**+ * Module dependencies.+ */++var url = require('./url');+var eio = require('engine.io-client');+var Socket = require('./socket');+var Emitter = require('component-emitter');+var parser = require('socket.io-parser');+var on = require('./on');+var bind = require('component-bind');+var object = require('object-component');+var debug = require('debug')('socket.io-client:manager');+var indexOf = require('indexof');+var Backoff = require('backo2');++/**+ * Module exports+ */++module.exports = Manager;++/**+ * `Manager` constructor.+ *+ * @param {String} engine instance or engine uri/opts+ * @param {Object} options+ * @api public+ */++function Manager(uri, opts){+ if (!(this instanceof Manager)) return new Manager(uri, opts);+ if (uri && ('object' == typeof uri)) {+ opts = uri;+ uri = undefined;+ }+ opts = opts || {};++ opts.path = opts.path || '/socket.io';+ this.nsps = {};+ this.subs = [];+ this.opts = opts;+ this.reconnection(opts.reconnection !== false);+ this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);+ this.reconnectionDelay(opts.reconnectionDelay || 1000);+ this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);+ this.randomizationFactor(opts.randomizationFactor || 0.5);+ this.backoff = new Backoff({+ min: this.reconnectionDelay(),+ max: this.reconnectionDelayMax(),+ jitter: this.randomizationFactor()+ });+ this.timeout(null == opts.timeout ? 20000 : opts.timeout);+ this.readyState = 'closed';+ this.uri = uri;+ this.connected = [];+ this.encoding = false;+ this.packetBuffer = [];+ this.encoder = new parser.Encoder();+ this.decoder = new parser.Decoder();+ this.autoConnect = opts.autoConnect !== false;+ if (this.autoConnect) this.open();+}++/**+ * Propagate given event to sockets and emit on `this`+ *+ * @api private+ */++Manager.prototype.emitAll = function() {+ this.emit.apply(this, arguments);+ for (var nsp in this.nsps) {+ this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);+ }+};++/**+ * Update `socket.id` of all sockets+ *+ * @api private+ */++Manager.prototype.updateSocketIds = function(){+ for (var nsp in this.nsps) {+ this.nsps[nsp].id = this.engine.id;+ }+};++/**+ * Mix in `Emitter`.+ */++Emitter(Manager.prototype);++/**+ * Sets the `reconnection` config.+ *+ * @param {Boolean} true/false if it should automatically reconnect+ * @return {Manager} self or value+ * @api public+ */++Manager.prototype.reconnection = function(v){+ if (!arguments.length) return this._reconnection;+ this._reconnection = !!v;+ return this;+};++/**+ * Sets the reconnection attempts config.+ *+ * @param {Number} max reconnection attempts before giving up+ * @return {Manager} self or value+ * @api public+ */++Manager.prototype.reconnectionAttempts = function(v){+ if (!arguments.length) return this._reconnectionAttempts;+ this._reconnectionAttempts = v;+ return this;+};++/**+ * Sets the delay between reconnections.+ *+ * @param {Number} delay+ * @return {Manager} self or value+ * @api public+ */++Manager.prototype.reconnectionDelay = function(v){+ if (!arguments.length) return this._reconnectionDelay;+ this._reconnectionDelay = v;+ this.backoff && this.backoff.setMin(v);+ return this;+};++Manager.prototype.randomizationFactor = function(v){+ if (!arguments.length) return this._randomizationFactor;+ this._randomizationFactor = v;+ this.backoff && this.backoff.setJitter(v);+ return this;+};++/**+ * Sets the maximum delay between reconnections.+ *+ * @param {Number} delay+ * @return {Manager} self or value+ * @api public+ */++Manager.prototype.reconnectionDelayMax = function(v){+ if (!arguments.length) return this._reconnectionDelayMax;+ this._reconnectionDelayMax = v;+ this.backoff && this.backoff.setMax(v);+ return this;+};++/**+ * Sets the connection timeout. `false` to disable+ *+ * @return {Manager} self or value+ * @api public+ */++Manager.prototype.timeout = function(v){+ if (!arguments.length) return this._timeout;+ this._timeout = v;+ return this;+};++/**+ * Starts trying to reconnect if reconnection is enabled and we have not+ * started reconnecting yet+ *+ * @api private+ */++Manager.prototype.maybeReconnectOnOpen = function() {+ // Only try to reconnect if it's the first time we're connecting+ if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {+ // keeps reconnection from firing twice for the same reconnection loop+ this.reconnect();+ }+};+++/**+ * Sets the current transport `socket`.+ *+ * @param {Function} optional, callback+ * @return {Manager} self+ * @api public+ */++Manager.prototype.open =+Manager.prototype.connect = function(fn){+ debug('readyState %s', this.readyState);+ if (~this.readyState.indexOf('open')) return this;++ debug('opening %s', this.uri);+ this.engine = eio(this.uri, this.opts);+ var socket = this.engine;+ var self = this;+ this.readyState = 'opening';+ this.skipReconnect = false;++ // emit `open`+ var openSub = on(socket, 'open', function() {+ self.onopen();+ fn && fn();+ });++ // emit `connect_error`+ var errorSub = on(socket, 'error', function(data){+ debug('connect_error');+ self.cleanup();+ self.readyState = 'closed';+ self.emitAll('connect_error', data);+ if (fn) {+ var err = new Error('Connection error');+ err.data = data;+ fn(err);+ } else {+ // Only do this if there is no fn to handle the error+ self.maybeReconnectOnOpen();+ }+ });++ // emit `connect_timeout`+ if (false !== this._timeout) {+ var timeout = this._timeout;+ debug('connect attempt will timeout after %d', timeout);++ // set timer+ var timer = setTimeout(function(){+ debug('connect attempt timed out after %d', timeout);+ openSub.destroy();+ socket.close();+ socket.emit('error', 'timeout');+ self.emitAll('connect_timeout', timeout);+ }, timeout);++ this.subs.push({+ destroy: function(){+ clearTimeout(timer);+ }+ });+ }++ this.subs.push(openSub);+ this.subs.push(errorSub);++ return this;+};++/**+ * Called upon transport open.+ *+ * @api private+ */++Manager.prototype.onopen = function(){+ debug('open');++ // clear old subs+ this.cleanup();++ // mark as open+ this.readyState = 'open';+ this.emit('open');++ // add new subs+ var socket = this.engine;+ this.subs.push(on(socket, 'data', bind(this, 'ondata')));+ this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));+ this.subs.push(on(socket, 'error', bind(this, 'onerror')));+ this.subs.push(on(socket, 'close', bind(this, 'onclose')));+};++/**+ * Called with data.+ *+ * @api private+ */++Manager.prototype.ondata = function(data){+ this.decoder.add(data);+};++/**+ * Called when parser fully decodes a packet.+ *+ * @api private+ */++Manager.prototype.ondecoded = function(packet) {+ this.emit('packet', packet);+};++/**+ * Called upon socket error.+ *+ * @api private+ */++Manager.prototype.onerror = function(err){+ debug('error', err);+ this.emitAll('error', err);+};++/**+ * Creates a new socket for the given `nsp`.+ *+ * @return {Socket}+ * @api public+ */++Manager.prototype.socket = function(nsp){+ var socket = this.nsps[nsp];+ if (!socket) {+ socket = new Socket(this, nsp);+ this.nsps[nsp] = socket;+ var self = this;+ socket.on('connect', function(){+ socket.id = self.engine.id;+ if (!~indexOf(self.connected, socket)) {+ self.connected.push(socket);+ }+ });+ }+ return socket;+};++/**+ * Called upon a socket close.+ *+ * @param {Socket} socket+ */++Manager.prototype.destroy = function(socket){+ var index = indexOf(this.connected, socket);+ if (~index) this.connected.splice(index, 1);+ if (this.connected.length) return;++ this.close();+};++/**+ * Writes a packet.+ *+ * @param {Object} packet+ * @api private+ */++Manager.prototype.packet = function(packet){+ debug('writing packet %j', packet);+ var self = this;++ if (!self.encoding) {+ // encode, then write to engine with result+ self.encoding = true;+ this.encoder.encode(packet, function(encodedPackets) {+ for (var i = 0; i < encodedPackets.length; i++) {+ self.engine.write(encodedPackets[i]);+ }+ self.encoding = false;+ self.processPacketQueue();+ });+ } else { // add packet to the queue+ self.packetBuffer.push(packet);+ }+};++/**+ * If packet buffer is non-empty, begins encoding the+ * next packet in line.+ *+ * @api private+ */++Manager.prototype.processPacketQueue = function() {+ if (this.packetBuffer.length > 0 && !this.encoding) {+ var pack = this.packetBuffer.shift();+ this.packet(pack);+ }+};++/**+ * Clean up transport subscriptions and packet buffer.+ *+ * @api private+ */++Manager.prototype.cleanup = function(){+ var sub;+ while (sub = this.subs.shift()) sub.destroy();++ this.packetBuffer = [];+ this.encoding = false;++ this.decoder.destroy();+};++/**+ * Close the current socket.+ *+ * @api private+ */++Manager.prototype.close =+Manager.prototype.disconnect = function(){+ this.skipReconnect = true;+ this.backoff.reset();+ this.readyState = 'closed';+ this.engine && this.engine.close();+};++/**+ * Called upon engine close.+ *+ * @api private+ */++Manager.prototype.onclose = function(reason){+ debug('close');+ this.cleanup();+ this.backoff.reset();+ this.readyState = 'closed';+ this.emit('close', reason);+ if (this._reconnection && !this.skipReconnect) {+ this.reconnect();+ }+};++/**+ * Attempt a reconnection.+ *+ * @api private+ */++Manager.prototype.reconnect = function(){+ if (this.reconnecting || this.skipReconnect) return this;++ var self = this;++ if (this.backoff.attempts >= this._reconnectionAttempts) {+ debug('reconnect failed');+ this.backoff.reset();+ this.emitAll('reconnect_failed');+ this.reconnecting = false;+ } else {+ var delay = this.backoff.duration();+ debug('will wait %dms before reconnect attempt', delay);++ this.reconnecting = true;+ var timer = setTimeout(function(){+ if (self.skipReconnect) return;++ debug('attempting reconnect');+ self.emitAll('reconnect_attempt', self.backoff.attempts);+ self.emitAll('reconnecting', self.backoff.attempts);++ // check again for the case socket closed in above events+ if (self.skipReconnect) return;++ self.open(function(err){+ if (err) {+ debug('reconnect attempt error');+ self.reconnecting = false;+ self.reconnect();+ self.emitAll('reconnect_error', err.data);+ } else {+ debug('reconnect success');+ self.onreconnect();+ }+ });+ }, delay);++ this.subs.push({+ destroy: function(){+ clearTimeout(timer);+ }+ });+ }+};++/**+ * Called upon successful reconnect.+ *+ * @api private+ */++Manager.prototype.onreconnect = function(){+ var attempt = this.backoff.attempts;+ this.reconnecting = false;+ this.backoff.reset();+ this.updateSocketIds();+ this.emitAll('reconnect', attempt);+};++},{"./on":104,"./socket":105,"./url":106,"backo2":107,"component-bind":108,"component-emitter":109,"debug":110,"engine.io-client":111,"indexof":142,"object-component":143,"socket.io-parser":146}],104:[function(require,module,exports){++/**+ * Module exports.+ */++module.exports = on;++/**+ * Helper for subscriptions.+ *+ * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`+ * @param {String} event name+ * @param {Function} callback+ * @api public+ */++function on(obj, ev, fn) {+ obj.on(ev, fn);+ return {+ destroy: function(){+ obj.removeListener(ev, fn);+ }+ };+}++},{}],105:[function(require,module,exports){++/**+ * Module dependencies.+ */++var parser = require('socket.io-parser');+var Emitter = require('component-emitter');+var toArray = require('to-array');+var on = require('./on');+var bind = require('component-bind');+var debug = require('debug')('socket.io-client:socket');+var hasBin = require('has-binary');++/**+ * Module exports.+ */++module.exports = exports = Socket;++/**+ * Internal events (blacklisted).+ * These events can't be emitted by the user.+ *+ * @api private+ */++var events = {+ connect: 1,+ connect_error: 1,+ connect_timeout: 1,+ disconnect: 1,+ error: 1,+ reconnect: 1,+ reconnect_attempt: 1,+ reconnect_failed: 1,+ reconnect_error: 1,+ reconnecting: 1+};++/**+ * Shortcut to `Emitter#emit`.+ */++var emit = Emitter.prototype.emit;++/**+ * `Socket` constructor.+ *+ * @api public+ */++function Socket(io, nsp){+ this.io = io;+ this.nsp = nsp;+ this.json = this; // compat+ this.ids = 0;+ this.acks = {};+ if (this.io.autoConnect) this.open();+ this.receiveBuffer = [];+ this.sendBuffer = [];+ this.connected = false;+ this.disconnected = true;+}++/**+ * Mix in `Emitter`.+ */++Emitter(Socket.prototype);++/**+ * Subscribe to open, close and packet events+ *+ * @api private+ */++Socket.prototype.subEvents = function() {+ if (this.subs) return;++ var io = this.io;+ this.subs = [+ on(io, 'open', bind(this, 'onopen')),+ on(io, 'packet', bind(this, 'onpacket')),+ on(io, 'close', bind(this, 'onclose'))+ ];+};++/**+ * "Opens" the socket.+ *+ * @api public+ */++Socket.prototype.open =+Socket.prototype.connect = function(){+ if (this.connected) return this;++ this.subEvents();+ this.io.open(); // ensure open+ if ('open' == this.io.readyState) this.onopen();+ return this;+};++/**+ * Sends a `message` event.+ *+ * @return {Socket} self+ * @api public+ */++Socket.prototype.send = function(){+ var args = toArray(arguments);+ args.unshift('message');+ this.emit.apply(this, args);+ return this;+};++/**+ * Override `emit`.+ * If the event is in `events`, it's emitted normally.+ *+ * @param {String} event name+ * @return {Socket} self+ * @api public+ */++Socket.prototype.emit = function(ev){+ if (events.hasOwnProperty(ev)) {+ emit.apply(this, arguments);+ return this;+ }++ var args = toArray(arguments);+ var parserType = parser.EVENT; // default+ if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary+ var packet = { type: parserType, data: args };++ // event ack callback+ if ('function' == typeof args[args.length - 1]) {+ debug('emitting packet with ack id %d', this.ids);+ this.acks[this.ids] = args.pop();+ packet.id = this.ids++;+ }++ if (this.connected) {+ this.packet(packet);+ } else {+ this.sendBuffer.push(packet);+ }++ return this;+};++/**+ * Sends a packet.+ *+ * @param {Object} packet+ * @api private+ */++Socket.prototype.packet = function(packet){+ packet.nsp = this.nsp;+ this.io.packet(packet);+};++/**+ * Called upon engine `open`.+ *+ * @api private+ */++Socket.prototype.onopen = function(){+ debug('transport is open - connecting');++ // write connect packet if necessary+ if ('/' != this.nsp) {+ this.packet({ type: parser.CONNECT });+ }+};++/**+ * Called upon engine `close`.+ *+ * @param {String} reason+ * @api private+ */++Socket.prototype.onclose = function(reason){+ debug('close (%s)', reason);+ this.connected = false;+ this.disconnected = true;+ delete this.id;+ this.emit('disconnect', reason);+};++/**+ * Called with socket packet.+ *+ * @param {Object} packet+ * @api private+ */++Socket.prototype.onpacket = function(packet){+ if (packet.nsp != this.nsp) return;++ switch (packet.type) {+ case parser.CONNECT:+ this.onconnect();+ break;++ case parser.EVENT:+ this.onevent(packet);+ break;++ case parser.BINARY_EVENT:+ this.onevent(packet);+ break;++ case parser.ACK:+ this.onack(packet);+ break;++ case parser.BINARY_ACK:+ this.onack(packet);+ break;++ case parser.DISCONNECT:+ this.ondisconnect();+ break;++ case parser.ERROR:+ this.emit('error', packet.data);+ break;+ }+};++/**+ * Called upon a server event.+ *+ * @param {Object} packet+ * @api private+ */++Socket.prototype.onevent = function(packet){+ var args = packet.data || [];+ debug('emitting event %j', args);++ if (null != packet.id) {+ debug('attaching ack callback to event');+ args.push(this.ack(packet.id));+ }++ if (this.connected) {+ emit.apply(this, args);+ } else {+ this.receiveBuffer.push(args);+ }+};++/**+ * Produces an ack callback to emit with an event.+ *+ * @api private+ */++Socket.prototype.ack = function(id){+ var self = this;+ var sent = false;+ return function(){+ // prevent double callbacks+ if (sent) return;+ sent = true;+ var args = toArray(arguments);+ debug('sending ack %j', args);++ var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;+ self.packet({+ type: type,+ id: id,+ data: args+ });+ };+};++/**+ * Called upon a server acknowlegement.+ *+ * @param {Object} packet+ * @api private+ */++Socket.prototype.onack = function(packet){+ debug('calling ack %s with %j', packet.id, packet.data);+ var fn = this.acks[packet.id];+ fn.apply(this, packet.data);+ delete this.acks[packet.id];+};++/**+ * Called upon server connect.+ *+ * @api private+ */++Socket.prototype.onconnect = function(){+ this.connected = true;+ this.disconnected = false;+ this.emit('connect');+ this.emitBuffered();+};++/**+ * Emit buffered events (received and emitted).+ *+ * @api private+ */++Socket.prototype.emitBuffered = function(){+ var i;+ for (i = 0; i < this.receiveBuffer.length; i++) {+ emit.apply(this, this.receiveBuffer[i]);+ }+ this.receiveBuffer = [];++ for (i = 0; i < this.sendBuffer.length; i++) {+ this.packet(this.sendBuffer[i]);+ }+ this.sendBuffer = [];+};++/**+ * Called upon server disconnect.+ *+ * @api private+ */++Socket.prototype.ondisconnect = function(){+ debug('server disconnect (%s)', this.nsp);+ this.destroy();+ this.onclose('io server disconnect');+};++/**+ * Called upon forced client/server side disconnections,+ * this method ensures the manager stops tracking us and+ * that reconnections don't get triggered for this.+ *+ * @api private.+ */++Socket.prototype.destroy = function(){+ if (this.subs) {+ // clean subscriptions to avoid reconnections+ for (var i = 0; i < this.subs.length; i++) {+ this.subs[i].destroy();+ }+ this.subs = null;+ }++ this.io.destroy(this);+};++/**+ * Disconnects the socket manually.+ *+ * @return {Socket} self+ * @api public+ */++Socket.prototype.close =+Socket.prototype.disconnect = function(){+ if (this.connected) {+ debug('performing disconnect (%s)', this.nsp);+ this.packet({ type: parser.DISCONNECT });+ }++ // remove socket from pool+ this.destroy();++ if (this.connected) {+ // fire events+ this.onclose('io client disconnect');+ }+ return this;+};++},{"./on":104,"component-bind":108,"component-emitter":109,"debug":110,"has-binary":140,"socket.io-parser":146,"to-array":150}],106:[function(require,module,exports){+(function (global){++/**+ * Module dependencies.+ */++var parseuri = require('parseuri');+var debug = require('debug')('socket.io-client:url');++/**+ * Module exports.+ */++module.exports = url;++/**+ * URL parser.+ *+ * @param {String} url+ * @param {Object} An object meant to mimic window.location.+ * Defaults to window.location.+ * @api public+ */++function url(uri, loc){+ var obj = uri;++ // default to window.location+ var loc = loc || global.location;+ if (null == uri) uri = loc.protocol + '//' + loc.host;++ // relative path support+ if ('string' == typeof uri) {+ if ('/' == uri.charAt(0)) {+ if ('/' == uri.charAt(1)) {+ uri = loc.protocol + uri;+ } else {+ uri = loc.hostname + uri;+ }+ }++ if (!/^(https?|wss?):\/\//.test(uri)) {+ debug('protocol-less url %s', uri);+ if ('undefined' != typeof loc) {+ uri = loc.protocol + '//' + uri;+ } else {+ uri = 'https://' + uri;+ }+ }++ // parse+ debug('parse %s', uri);+ obj = parseuri(uri);+ }++ // make sure we treat `localhost:80` and `localhost` equally+ if (!obj.port) {+ if (/^(http|ws)$/.test(obj.protocol)) {+ obj.port = '80';+ }+ else if (/^(http|ws)s$/.test(obj.protocol)) {+ obj.port = '443';+ }+ }++ obj.path = obj.path || '/';++ // define unique id+ obj.id = obj.protocol + '://' + obj.host + ':' + obj.port;+ // define href+ obj.href = obj.protocol + '://' + obj.host + (loc && loc.port == obj.port ? '' : (':' + obj.port));++ return obj;+}++}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})+},{"debug":110,"parseuri":144}],107:[function(require,module,exports){++/**+ * Expose `Backoff`.+ */++module.exports = Backoff;++/**+ * Initialize backoff timer with `opts`.+ *+ * - `min` initial timeout in milliseconds [100]+ * - `max` max timeout [10000]+ * - `jitter` [0]+ * - `factor` [2]+ *+ * @param {Object} opts+ * @api public+ */++function Backoff(opts) {+ opts = opts || {};+ this.ms = opts.min || 100;+ this.max = opts.max || 10000;+ this.factor = opts.factor || 2;+ this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;+ this.attempts = 0;+}++/**+ * Return the backoff duration.+ *+ * @return {Number}+ * @api public+ */++Backoff.prototype.duration = function(){+ var ms = this.ms * Math.pow(this.factor, this.attempts++);+ if (this.jitter) {+ var rand = Math.random();+ var deviation = Math.floor(rand * this.jitter * ms);+ ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;+ }+ return Math.min(ms, this.max) | 0;+};++/**+ * Reset the number of attempts.+ *+ * @api public+ */++Backoff.prototype.reset = function(){+ this.attempts = 0;+};++/**+ * Set the minimum duration+ *+ * @api public+ */++Backoff.prototype.setMin = function(min){+ this.ms = min;+};++/**+ * Set the maximum duration+ *+ * @api public+ */++Backoff.prototype.setMax = function(max){+ this.max = max;+};++/**+ * Set the jitter+ *+ * @api public+ */++Backoff.prototype.setJitter = function(jitter){+ this.jitter = jitter;+};+++},{}],108:[function(require,module,exports){+/**+ * Slice reference.+ */++var slice = [].slice;++/**+ * Bind `obj` to `fn`.+ *+ * @param {Object} obj+ * @param {Function|String} fn or string+ * @return {Function}+ * @api public+ */++module.exports = function(obj, fn){+ if ('string' == typeof fn) fn = obj[fn];+ if ('function' != typeof fn) throw new Error('bind() requires a function');+ var args = slice.call(arguments, 2);+ return function(){+ return fn.apply(obj, args.concat(slice.call(arguments)));+ }+};++},{}],109:[function(require,module,exports){++/**+ * Expose `Emitter`.+ */++module.exports = Emitter;++/**+ * Initialize a new `Emitter`.+ *+ * @api public+ */++function Emitter(obj) {+ if (obj) return mixin(obj);+};++/**+ * Mixin the emitter properties.+ *+ * @param {Object} obj+ * @return {Object}+ * @api private+ */++function mixin(obj) {+ for (var key in Emitter.prototype) {+ obj[key] = Emitter.prototype[key];+ }+ return obj;+}++/**+ * Listen on the given `event` with `fn`.+ *+ * @param {String} event+ * @param {Function} fn+ * @return {Emitter}+ * @api public+ */++Emitter.prototype.on =+Emitter.prototype.addEventListener = function(event, fn){+ this._callbacks = this._callbacks || {};+ (this._callbacks[event] = this._callbacks[event] || [])+ .push(fn);+ return this;+};++/**+ * Adds an `event` listener that will be invoked a single+ * time then automatically removed.+ *+ * @param {String} event+ * @param {Function} fn+ * @return {Emitter}+ * @api public+ */++Emitter.prototype.once = function(event, fn){+ var self = this;+ this._callbacks = this._callbacks || {};++ function on() {+ self.off(event, on);+ fn.apply(this, arguments);+ }++ on.fn = fn;+ this.on(event, on);+ return this;+};++/**+ * Remove the given callback for `event` or all+ * registered callbacks.+ *+ * @param {String} event+ * @param {Function} fn+ * @return {Emitter}+ * @api public+ */++Emitter.prototype.off =+Emitter.prototype.removeListener =+Emitter.prototype.removeAllListeners =+Emitter.prototype.removeEventListener = function(event, fn){+ this._callbacks = this._callbacks || {};++ // all+ if (0 == arguments.length) {+ this._callbacks = {};+ return this;+ }++ // specific event+ var callbacks = this._callbacks[event];+ if (!callbacks) return this;++ // remove all handlers+ if (1 == arguments.length) {+ delete this._callbacks[event];+ return this;+ }++ // remove specific handler+ var cb;+ for (var i = 0; i < callbacks.length; i++) {+ cb = callbacks[i];+ if (cb === fn || cb.fn === fn) {+ callbacks.splice(i, 1);+ break;+ }+ }+ return this;+};++/**+ * Emit `event` with the given args.+ *+ * @param {String} event+ * @param {Mixed} ...+ * @return {Emitter}+ */++Emitter.prototype.emit = function(event){+ this._callbacks = this._callbacks || {};+ var args = [].slice.call(arguments, 1)+ , callbacks = this._callbacks[event];++ if (callbacks) {+ callbacks = callbacks.slice(0);+ for (var i = 0, len = callbacks.length; i < len; ++i) {+ callbacks[i].apply(this, args);+ }+ }++ return this;+};++/**+ * Return array of callbacks for `event`.+ *+ * @param {String} event+ * @return {Array}+ * @api public+ */++Emitter.prototype.listeners = function(event){+ this._callbacks = this._callbacks || {};+ return this._callbacks[event] || [];+};++/**+ * Check if this emitter has `event` handlers.+ *+ * @param {String} event+ * @return {Boolean}+ * @api public+ */++Emitter.prototype.hasListeners = function(event){+ return !! this.listeners(event).length;+};++},{}],110:[function(require,module,exports){++/**+ * Expose `debug()` as the module.+ */++module.exports = debug;++/**+ * Create a debugger with the given `name`.+ *+ * @param {String} name+ * @return {Type}+ * @api public+ */++function debug(name) {+ if (!debug.enabled(name)) return function(){};++ return function(fmt){+ fmt = coerce(fmt);++ var curr = new Date;+ var ms = curr - (debug[name] || curr);+ debug[name] = curr;++ fmt = name+ + ' '+ + fmt+ + ' +' + debug.humanize(ms);++ // This hackery is required for IE8+ // where `console.log` doesn't have 'apply'+ window.console+ && console.log+ && Function.prototype.apply.call(console.log, console, arguments);+ }+}++/**+ * The currently active debug mode names.+ */++debug.names = [];+debug.skips = [];++/**+ * Enables a debug mode by name. This can include modes+ * separated by a colon and wildcards.+ *+ * @param {String} name+ * @api public+ */++debug.enable = function(name) {+ try {+ localStorage.debug = name;+ } catch(e){}++ var split = (name || '').split(/[\s,]+/)+ , len = split.length;++ for (var i = 0; i < len; i++) {+ name = split[i].replace('*', '.*?');+ if (name[0] === '-') {+ debug.skips.push(new RegExp('^' + name.substr(1) + '$'));+ }+ else {+ debug.names.push(new RegExp('^' + name + '$'));+ }+ }+};++/**+ * Disable debug output.+ *+ * @api public+ */++debug.disable = function(){+ debug.enable('');+};++/**+ * Humanize the given `ms`.+ *+ * @param {Number} m+ * @return {String}+ * @api private+ */++debug.humanize = function(ms) {+ var sec = 1000+ , min = 60 * 1000+ , hour = 60 * min;++ if (ms >= hour) return (ms / hour).toFixed(1) + 'h';+ if (ms >= min) return (ms / min).toFixed(1) + 'm';+ if (ms >= sec) return (ms / sec | 0) + 's';+ return ms + 'ms';+};++/**+ * Returns true if the given mode name is enabled, false otherwise.+ *+ * @param {String} name+ * @return {Boolean}+ * @api public+ */++debug.enabled = function(name) {+ for (var i = 0, len = debug.skips.length; i < len; i++) {+ if (debug.skips[i].test(name)) {+ return false;+ }+ }+ for (var i = 0, len = debug.names.length; i < len; i++) {+ if (debug.names[i].test(name)) {+ return true;+ }+ }+ return false;+};++/**+ * Coerce `val`.+ */++function coerce(val) {+ if (val instanceof Error) return val.stack || val.message;+ return val;+}++// persist++try {+ if (window.localStorage) debug.enable(localStorage.debug);+} catch(e){}++},{}],111:[function(require,module,exports){++module.exports = require('./lib/');++},{"./lib/":112}],112:[function(require,module,exports){++module.exports = require('./socket');++/**+ * Exports parser+ *+ * @api public+ *+ */+module.exports.parser = require('engine.io-parser');++},{"./socket":113,"engine.io-parser":125}],113:[function(require,module,exports){+(function (global){+/**+ * Module dependencies.+ */++var transports = require('./transports');+var Emitter = require('component-emitter');+var debug = require('debug')('engine.io-client:socket');+var index = require('indexof');+var parser = require('engine.io-parser');+var parseuri = require('parseuri');+var parsejson = require('parsejson');+var parseqs = require('parseqs');++/**+ * Module exports.+ */++module.exports = Socket;++/**+ * Noop function.+ *+ * @api private+ */++function noop(){}++/**+ * Socket constructor.+ *+ * @param {String|Object} uri or options+ * @param {Object} options+ * @api public+ */++function Socket(uri, opts){+ if (!(this instanceof Socket)) return new Socket(uri, opts);++ opts = opts || {};++ if (uri && 'object' == typeof uri) {+ opts = uri;+ uri = null;+ }++ if (uri) {+ uri = parseuri(uri);+ opts.host = uri.host;+ opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';+ opts.port = uri.port;+ if (uri.query) opts.query = uri.query;+ }++ this.secure = null != opts.secure ? opts.secure :+ (global.location && 'https:' == location.protocol);++ if (opts.host) {+ var pieces = opts.host.split(':');+ opts.hostname = pieces.shift();+ if (pieces.length) {+ opts.port = pieces.pop();+ } else if (!opts.port) {+ // if no port is specified manually, use the protocol default+ opts.port = this.secure ? '443' : '80';+ }+ }++ this.agent = opts.agent || false;+ this.hostname = opts.hostname ||+ (global.location ? location.hostname : 'localhost');+ this.port = opts.port || (global.location && location.port ?+ location.port :+ (this.secure ? 443 : 80));+ this.query = opts.query || {};+ if ('string' == typeof this.query) this.query = parseqs.decode(this.query);+ this.upgrade = false !== opts.upgrade;+ this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';+ this.forceJSONP = !!opts.forceJSONP;+ this.jsonp = false !== opts.jsonp;+ this.forceBase64 = !!opts.forceBase64;+ this.enablesXDR = !!opts.enablesXDR;+ this.timestampParam = opts.timestampParam || 't';+ this.timestampRequests = opts.timestampRequests;+ this.transports = opts.transports || ['polling', 'websocket'];+ this.readyState = '';+ this.writeBuffer = [];+ this.callbackBuffer = [];+ this.policyPort = opts.policyPort || 843;+ this.rememberUpgrade = opts.rememberUpgrade || false;+ this.binaryType = null;+ this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;++ // SSL options for Node.js client+ this.pfx = opts.pfx || null;+ this.key = opts.key || null;+ this.passphrase = opts.passphrase || null;+ this.cert = opts.cert || null;+ this.ca = opts.ca || null;+ this.ciphers = opts.ciphers || null;+ this.rejectUnauthorized = opts.rejectUnauthorized || null;++ this.open();+}++Socket.priorWebsocketSuccess = false;++/**+ * Mix in `Emitter`.+ */++Emitter(Socket.prototype);++/**+ * Protocol version.+ *+ * @api public+ */++Socket.protocol = parser.protocol; // this is an int++/**+ * Expose deps for legacy compatibility+ * and standalone browser access.+ */++Socket.Socket = Socket;+Socket.Transport = require('./transport');+Socket.transports = require('./transports');+Socket.parser = require('engine.io-parser');++/**+ * Creates transport of the given type.+ *+ * @param {String} transport name+ * @return {Transport}+ * @api private+ */++Socket.prototype.createTransport = function (name) {+ debug('creating transport "%s"', name);+ var query = clone(this.query);++ // append engine.io protocol identifier+ query.EIO = parser.protocol;++ // transport name+ query.transport = name;++ // session id if we already have one+ if (this.id) query.sid = this.id;++ var transport = new transports[name]({+ agent: this.agent,+ hostname: this.hostname,+ port: this.port,+ secure: this.secure,+ path: this.path,+ query: query,+ forceJSONP: this.forceJSONP,+ jsonp: this.jsonp,+ forceBase64: this.forceBase64,+ enablesXDR: this.enablesXDR,+ timestampRequests: this.timestampRequests,+ timestampParam: this.timestampParam,+ policyPort: this.policyPort,+ socket: this,+ pfx: this.pfx,+ key: this.key,+ passphrase: this.passphrase,+ cert: this.cert,+ ca: this.ca,+ ciphers: this.ciphers,+ rejectUnauthorized: this.rejectUnauthorized+ });++ return transport;+};++function clone (obj) {+ var o = {};+ for (var i in obj) {+ if (obj.hasOwnProperty(i)) {+ o[i] = obj[i];+ }+ }+ return o;+}++/**+ * Initializes transport to use and starts probe.+ *+ * @api private+ */+Socket.prototype.open = function () {+ var transport;+ if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) {+ transport = 'websocket';+ } else if (0 == this.transports.length) {+ // Emit error on next tick so it can be listened to+ var self = this;+ setTimeout(function() {+ self.emit('error', 'No transports available');+ }, 0);+ return;+ } else {+ transport = this.transports[0];+ }+ this.readyState = 'opening';++ // Retry with the next transport if the transport is disabled (jsonp: false)+ var transport;+ try {+ transport = this.createTransport(transport);+ } catch (e) {+ this.transports.shift();+ this.open();+ return;+ }++ transport.open();+ this.setTransport(transport);+};++/**+ * Sets the current transport. Disables the existing one (if any).+ *+ * @api private+ */++Socket.prototype.setTransport = function(transport){+ debug('setting transport %s', transport.name);+ var self = this;++ if (this.transport) {+ debug('clearing existing transport %s', this.transport.name);+ this.transport.removeAllListeners();+ }++ // set up transport+ this.transport = transport;++ // set up transport listeners+ transport+ .on('drain', function(){+ self.onDrain();+ })+ .on('packet', function(packet){+ self.onPacket(packet);+ })+ .on('error', function(e){+ self.onError(e);+ })+ .on('close', function(){+ self.onClose('transport close');+ });+};++/**+ * Probes a transport.+ *+ * @param {String} transport name+ * @api private+ */++Socket.prototype.probe = function (name) {+ debug('probing transport "%s"', name);+ var transport = this.createTransport(name, { probe: 1 })+ , failed = false+ , self = this;++ Socket.priorWebsocketSuccess = false;++ function onTransportOpen(){+ if (self.onlyBinaryUpgrades) {+ var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;+ failed = failed || upgradeLosesBinary;+ }+ if (failed) return;++ debug('probe transport "%s" opened', name);+ transport.send([{ type: 'ping', data: 'probe' }]);+ transport.once('packet', function (msg) {+ if (failed) return;+ if ('pong' == msg.type && 'probe' == msg.data) {+ debug('probe transport "%s" pong', name);+ self.upgrading = true;+ self.emit('upgrading', transport);+ if (!transport) return;+ Socket.priorWebsocketSuccess = 'websocket' == transport.name;++ debug('pausing current transport "%s"', self.transport.name);+ self.transport.pause(function () {+ if (failed) return;+ if ('closed' == self.readyState) return;+ debug('changing transport and sending upgrade packet');++ cleanup();++ self.setTransport(transport);+ transport.send([{ type: 'upgrade' }]);+ self.emit('upgrade', transport);+ transport = null;+ self.upgrading = false;+ self.flush();+ });+ } else {+ debug('probe transport "%s" failed', name);+ var err = new Error('probe error');+ err.transport = transport.name;+ self.emit('upgradeError', err);+ }+ });+ }++ function freezeTransport() {+ if (failed) return;++ // Any callback called by transport should be ignored since now+ failed = true;++ cleanup();++ transport.close();+ transport = null;+ }++ //Handle any error that happens while probing+ function onerror(err) {+ var error = new Error('probe error: ' + err);+ error.transport = transport.name;++ freezeTransport();++ debug('probe transport "%s" failed because of error: %s', name, err);++ self.emit('upgradeError', error);+ }++ function onTransportClose(){+ onerror("transport closed");+ }++ //When the socket is closed while we're probing+ function onclose(){+ onerror("socket closed");+ }++ //When the socket is upgraded while we're probing+ function onupgrade(to){+ if (transport && to.name != transport.name) {+ debug('"%s" works - aborting "%s"', to.name, transport.name);+ freezeTransport();+ }+ }++ //Remove all listeners on the transport and on self+ function cleanup(){+ transport.removeListener('open', onTransportOpen);+ transport.removeListener('error', onerror);+ transport.removeListener('close', onTransportClose);+ self.removeListener('close', onclose);+ self.removeListener('upgrading', onupgrade);+ }++ transport.once('open', onTransportOpen);+ transport.once('error', onerror);+ transport.once('close', onTransportClose);++ this.once('close', onclose);+ this.once('upgrading', onupgrade);++ transport.open();++};++/**+ * Called when connection is deemed open.+ *+ * @api public+ */++Socket.prototype.onOpen = function () {+ debug('socket open');+ this.readyState = 'open';+ Socket.priorWebsocketSuccess = 'websocket' == this.transport.name;+ this.emit('open');+ this.flush();++ // we check for `readyState` in case an `open`+ // listener already closed the socket+ if ('open' == this.readyState && this.upgrade && this.transport.pause) {+ debug('starting upgrade probes');+ for (var i = 0, l = this.upgrades.length; i < l; i++) {+ this.probe(this.upgrades[i]);+ }+ }+};++/**+ * Handles a packet.+ *+ * @api private+ */++Socket.prototype.onPacket = function (packet) {+ if ('opening' == this.readyState || 'open' == this.readyState) {+ debug('socket receive: type "%s", data "%s"', packet.type, packet.data);++ this.emit('packet', packet);++ // Socket is live - any packet counts+ this.emit('heartbeat');++ switch (packet.type) {+ case 'open':+ this.onHandshake(parsejson(packet.data));+ break;++ case 'pong':+ this.setPing();+ break;++ case 'error':+ var err = new Error('server error');+ err.code = packet.data;+ this.emit('error', err);+ break;++ case 'message':+ this.emit('data', packet.data);+ this.emit('message', packet.data);+ break;+ }+ } else {+ debug('packet received with socket readyState "%s"', this.readyState);+ }+};++/**+ * Called upon handshake completion.+ *+ * @param {Object} handshake obj+ * @api private+ */++Socket.prototype.onHandshake = function (data) {+ this.emit('handshake', data);+ this.id = data.sid;+ this.transport.query.sid = data.sid;+ this.upgrades = this.filterUpgrades(data.upgrades);+ this.pingInterval = data.pingInterval;+ this.pingTimeout = data.pingTimeout;+ this.onOpen();+ // In case open handler closes socket+ if ('closed' == this.readyState) return;+ this.setPing();++ // Prolong liveness of socket on heartbeat+ this.removeListener('heartbeat', this.onHeartbeat);+ this.on('heartbeat', this.onHeartbeat);+};++/**+ * Resets ping timeout.+ *+ * @api private+ */++Socket.prototype.onHeartbeat = function (timeout) {+ clearTimeout(this.pingTimeoutTimer);+ var self = this;+ self.pingTimeoutTimer = setTimeout(function () {+ if ('closed' == self.readyState) return;+ self.onClose('ping timeout');+ }, timeout || (self.pingInterval + self.pingTimeout));+};++/**+ * Pings server every `this.pingInterval` and expects response+ * within `this.pingTimeout` or closes connection.+ *+ * @api private+ */++Socket.prototype.setPing = function () {+ var self = this;+ clearTimeout(self.pingIntervalTimer);+ self.pingIntervalTimer = setTimeout(function () {+ debug('writing ping packet - expecting pong within %sms', self.pingTimeout);+ self.ping();+ self.onHeartbeat(self.pingTimeout);+ }, self.pingInterval);+};++/**+* Sends a ping packet.+*+* @api public+*/++Socket.prototype.ping = function () {+ this.sendPacket('ping');+};++/**+ * Called on `drain` event+ *+ * @api private+ */++Socket.prototype.onDrain = function() {+ for (var i = 0; i < this.prevBufferLen; i++) {+ if (this.callbackBuffer[i]) {+ this.callbackBuffer[i]();+ }+ }++ this.writeBuffer.splice(0, this.prevBufferLen);+ this.callbackBuffer.splice(0, this.prevBufferLen);++ // setting prevBufferLen = 0 is very important+ // for example, when upgrading, upgrade packet is sent over,+ // and a nonzero prevBufferLen could cause problems on `drain`+ this.prevBufferLen = 0;++ if (this.writeBuffer.length == 0) {+ this.emit('drain');+ } else {+ this.flush();+ }+};++/**+ * Flush write buffers.+ *+ * @api private+ */++Socket.prototype.flush = function () {+ if ('closed' != this.readyState && this.transport.writable &&+ !this.upgrading && this.writeBuffer.length) {+ debug('flushing %d packets in socket', this.writeBuffer.length);+ this.transport.send(this.writeBuffer);+ // keep track of current length of writeBuffer+ // splice writeBuffer and callbackBuffer on `drain`+ this.prevBufferLen = this.writeBuffer.length;+ this.emit('flush');+ }+};++/**+ * Sends a message.+ *+ * @param {String} message.+ * @param {Function} callback function.+ * @return {Socket} for chaining.+ * @api public+ */++Socket.prototype.write =+Socket.prototype.send = function (msg, fn) {+ this.sendPacket('message', msg, fn);+ return this;+};++/**+ * Sends a packet.+ *+ * @param {String} packet type.+ * @param {String} data.+ * @param {Function} callback function.+ * @api private+ */++Socket.prototype.sendPacket = function (type, data, fn) {+ if ('closing' == this.readyState || 'closed' == this.readyState) {+ return;+ }++ var packet = { type: type, data: data };+ this.emit('packetCreate', packet);+ this.writeBuffer.push(packet);+ this.callbackBuffer.push(fn);+ this.flush();+};++/**+ * Closes the connection.+ *+ * @api private+ */++Socket.prototype.close = function () {+ if ('opening' == this.readyState || 'open' == this.readyState) {+ this.readyState = 'closing';++ var self = this;++ function close() {+ self.onClose('forced close');+ debug('socket closing - telling transport to close');+ self.transport.close();+ }++ function cleanupAndClose() {+ self.removeListener('upgrade', cleanupAndClose);+ self.removeListener('upgradeError', cleanupAndClose);+ close();+ }++ function waitForUpgrade() {+ // wait for upgrade to finish since we can't send packets while pausing a transport+ self.once('upgrade', cleanupAndClose);+ self.once('upgradeError', cleanupAndClose);+ }++ if (this.writeBuffer.length) {+ this.once('drain', function() {+ if (this.upgrading) {+ waitForUpgrade();+ } else {+ close();+ }+ });+ } else if (this.upgrading) {+ waitForUpgrade();+ } else {+ close();+ }+ }++ return this;+};++/**+ * Called upon transport error+ *+ * @api private+ */++Socket.prototype.onError = function (err) {+ debug('socket error %j', err);+ Socket.priorWebsocketSuccess = false;+ this.emit('error', err);+ this.onClose('transport error', err);+};++/**+ * Called upon transport close.+ *+ * @api private+ */++Socket.prototype.onClose = function (reason, desc) {+ if ('opening' == this.readyState || 'open' == this.readyState || 'closing' == this.readyState) {+ debug('socket close with reason: "%s"', reason);+ var self = this;++ // clear timers+ clearTimeout(this.pingIntervalTimer);+ clearTimeout(this.pingTimeoutTimer);++ // clean buffers in next tick, so developers can still+ // grab the buffers on `close` event+ setTimeout(function() {+ self.writeBuffer = [];+ self.callbackBuffer = [];+ self.prevBufferLen = 0;+ }, 0);++ // stop event from firing again for transport+ this.transport.removeAllListeners('close');++ // ensure transport won't stay open+ this.transport.close();++ // ignore further transport communication+ this.transport.removeAllListeners();++ // set ready state+ this.readyState = 'closed';++ // clear session id+ this.id = null;++ // emit close event+ this.emit('close', reason, desc);+ }+};++/**+ * Filters upgrades, returning only those matching client transports.+ *+ * @param {Array} server upgrades+ * @api private+ *+ */++Socket.prototype.filterUpgrades = function (upgrades) {+ var filteredUpgrades = [];+ for (var i = 0, j = upgrades.length; i<j; i++) {+ if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);+ }+ return filteredUpgrades;+};++}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})+},{"./transport":114,"./transports":115,"component-emitter":109,"debug":122,"engine.io-parser":125,"indexof":142,"parsejson":136,"parseqs":137,"parseuri":138}],114:[function(require,module,exports){+/**+ * Module dependencies.+ */++var parser = require('engine.io-parser');+var Emitter = require('component-emitter');++/**+ * Module exports.+ */++module.exports = Transport;++/**+ * Transport abstract constructor.+ *+ * @param {Object} options.+ * @api private+ */++function Transport (opts) {+ this.path = opts.path;+ this.hostname = opts.hostname;+ this.port = opts.port;+ this.secure = opts.secure;+ this.query = opts.query;+ this.timestampParam = opts.timestampParam;+ this.timestampRequests = opts.timestampRequests;+ this.readyState = '';+ this.agent = opts.agent || false;+ this.socket = opts.socket;+ this.enablesXDR = opts.enablesXDR;++ // SSL options for Node.js client+ this.pfx = opts.pfx;+ this.key = opts.key;+ this.passphrase = opts.passphrase;+ this.cert = opts.cert;+ this.ca = opts.ca;+ this.ciphers = opts.ciphers;+ this.rejectUnauthorized = opts.rejectUnauthorized;+}++/**+ * Mix in `Emitter`.+ */++Emitter(Transport.prototype);++/**+ * A counter used to prevent collisions in the timestamps used+ * for cache busting.+ */++Transport.timestamps = 0;++/**+ * Emits an error.+ *+ * @param {String} str+ * @return {Transport} for chaining+ * @api public+ */++Transport.prototype.onError = function (msg, desc) {+ var err = new Error(msg);+ err.type = 'TransportError';+ err.description = desc;+ this.emit('error', err);+ return this;+};++/**+ * Opens the transport.+ *+ * @api public+ */++Transport.prototype.open = function () {+ if ('closed' == this.readyState || '' == this.readyState) {+ this.readyState = 'opening';+ this.doOpen();+ }++ return this;+};++/**+ * Closes the transport.+ *+ * @api private+ */++Transport.prototype.close = function () {+ if ('opening' == this.readyState || 'open' == this.readyState) {+ this.doClose();+ this.onClose();+ }++ return this;+};++/**+ * Sends multiple packets.+ *+ * @param {Array} packets+ * @api private+ */++Transport.prototype.send = function(packets){+ if ('open' == this.readyState) {+ this.write(packets);+ } else {+ throw new Error('Transport not open');+ }+};++/**+ * Called upon open+ *+ * @api private+ */++Transport.prototype.onOpen = function () {+ this.readyState = 'open';+ this.writable = true;+ this.emit('open');+};++/**+ * Called with data.+ *+ * @param {String} data+ * @api private+ */++Transport.prototype.onData = function(data){+ var packet = parser.decodePacket(data, this.socket.binaryType);+ this.onPacket(packet);+};++/**+ * Called with a decoded packet.+ */++Transport.prototype.onPacket = function (packet) {+ this.emit('packet', packet);+};++/**+ * Called upon close.+ *+ * @api private+ */++Transport.prototype.onClose = function () {+ this.readyState = 'closed';+ this.emit('close');+};++},{"component-emitter":109,"engine.io-parser":125}],115:[function(require,module,exports){+(function (global){+/**+ * Module dependencies+ */++var XMLHttpRequest = require('xmlhttprequest');+var XHR = require('./polling-xhr');+var JSONP = require('./polling-jsonp');+var websocket = require('./websocket');++/**+ * Export transports.+ */++exports.polling = polling;+exports.websocket = websocket;++/**+ * Polling transport polymorphic constructor.+ * Decides on xhr vs jsonp based on feature detection.+ *+ * @api private+ */++function polling(opts){+ var xhr;+ var xd = false;+ var xs = false;+ var jsonp = false !== opts.jsonp;++ if (global.location) {+ var isSSL = 'https:' == location.protocol;+ var port = location.port;++ // some user agents have empty `location.port`+ if (!port) {+ port = isSSL ? 443 : 80;+ }++ xd = opts.hostname != location.hostname || port != opts.port;+ xs = opts.secure != isSSL;+ }++ opts.xdomain = xd;+ opts.xscheme = xs;+ xhr = new XMLHttpRequest(opts);++ if ('open' in xhr && !opts.forceJSONP) {+ return new XHR(opts);+ } else {+ if (!jsonp) throw new Error('JSONP disabled');+ return new JSONP(opts);+ }+}++}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})+},{"./polling-jsonp":116,"./polling-xhr":117,"./websocket":119,"xmlhttprequest":120}],116:[function(require,module,exports){+(function (global){++/**+ * Module requirements.+ */++var Polling = require('./polling');+var inherit = require('component-inherit');++/**+ * Module exports.+ */++module.exports = JSONPPolling;++/**+ * Cached regular expressions.+ */++var rNewline = /\n/g;+var rEscapedNewline = /\\n/g;++/**+ * Global JSONP callbacks.+ */++var callbacks;++/**+ * Callbacks count.+ */++var index = 0;++/**+ * Noop.+ */++function empty () { }++/**+ * JSONP Polling constructor.+ *+ * @param {Object} opts.+ * @api public+ */++function JSONPPolling (opts) {+ Polling.call(this, opts);++ this.query = this.query || {};++ // define global callbacks array if not present+ // we do this here (lazily) to avoid unneeded global pollution+ if (!callbacks) {+ // we need to consider multiple engines in the same page+ if (!global.___eio) global.___eio = [];+ callbacks = global.___eio;+ }++ // callback identifier+ this.index = callbacks.length;++ // add callback to jsonp global+ var self = this;+ callbacks.push(function (msg) {+ self.onData(msg);+ });++ // append to query string+ this.query.j = this.index;++ // prevent spurious errors from being emitted when the window is unloaded+ if (global.document && global.addEventListener) {+ global.addEventListener('beforeunload', function () {+ if (self.script) self.script.onerror = empty;+ }, false);+ }+}++/**+ * Inherits from Polling.+ */++inherit(JSONPPolling, Polling);++/*+ * JSONP only supports binary as base64 encoded strings+ */++JSONPPolling.prototype.supportsBinary = false;++/**+ * Closes the socket.+ *+ * @api private+ */++JSONPPolling.prototype.doClose = function () {+ if (this.script) {+ this.script.parentNode.removeChild(this.script);+ this.script = null;+ }++ if (this.form) {+ this.form.parentNode.removeChild(this.form);+ this.form = null;+ this.iframe = null;+ }++ Polling.prototype.doClose.call(this);+};++/**+ * Starts a poll cycle.+ *+ * @api private+ */++JSONPPolling.prototype.doPoll = function () {+ var self = this;+ var script = document.createElement('script');++ if (this.script) {+ this.script.parentNode.removeChild(this.script);+ this.script = null;+ }++ script.async = true;+ script.src = this.uri();+ script.onerror = function(e){+ self.onError('jsonp poll error',e);+ };++ var insertAt = document.getElementsByTagName('script')[0];+ insertAt.parentNode.insertBefore(script, insertAt);+ this.script = script;++ var isUAgecko = 'undefined' != typeof navigator && /gecko/i.test(navigator.userAgent);++ if (isUAgecko) {+ setTimeout(function () {+ var iframe = document.createElement('iframe');+ document.body.appendChild(iframe);+ document.body.removeChild(iframe);+ }, 100);+ }+};++/**+ * Writes with a hidden iframe.+ *+ * @param {String} data to send+ * @param {Function} called upon flush.+ * @api private+ */++JSONPPolling.prototype.doWrite = function (data, fn) {+ var self = this;++ if (!this.form) {+ var form = document.createElement('form');+ var area = document.createElement('textarea');+ var id = this.iframeId = 'eio_iframe_' + this.index;+ var iframe;++ form.className = 'socketio';+ form.style.position = 'absolute';+ form.style.top = '-1000px';+ form.style.left = '-1000px';+ form.target = id;+ form.method = 'POST';+ form.setAttribute('accept-charset', 'utf-8');+ area.name = 'd';+ form.appendChild(area);+ document.body.appendChild(form);++ this.form = form;+ this.area = area;+ }++ this.form.action = this.uri();++ function complete () {+ initIframe();+ fn();+ }++ function initIframe () {+ if (self.iframe) {+ try {+ self.form.removeChild(self.iframe);+ } catch (e) {+ self.onError('jsonp polling iframe removal error', e);+ }+ }++ try {+ // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)+ var html = '<iframe src="javascript:0" name="'+ self.iframeId +'">';+ iframe = document.createElement(html);+ } catch (e) {+ iframe = document.createElement('iframe');+ iframe.name = self.iframeId;+ iframe.src = 'javascript:0';+ }++ iframe.id = self.iframeId;++ self.form.appendChild(iframe);+ self.iframe = iframe;+ }++ initIframe();++ // escape \n to prevent it from being converted into \r\n by some UAs+ // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side+ data = data.replace(rEscapedNewline, '\\\n');+ this.area.value = data.replace(rNewline, '\\n');++ try {+ this.form.submit();+ } catch(e) {}++ if (this.iframe.attachEvent) {+ this.iframe.onreadystatechange = function(){+ if (self.iframe.readyState == 'complete') {+ complete();+ }+ };+ } else {+ this.iframe.onload = complete;+ }+};++}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})+},{"./polling":118,"component-inherit":121}],117:[function(require,module,exports){+(function (global){+/**+ * Module requirements.+ */++var XMLHttpRequest = require('xmlhttprequest');+var Polling = require('./polling');+var Emitter = require('component-emitter');+var inherit = require('component-inherit');+var debug = require('debug')('engine.io-client:polling-xhr');++/**+ * Module exports.+ */++module.exports = XHR;+module.exports.Request = Request;++/**+ * Empty function+ */++function empty(){}++/**+ * XHR Polling constructor.+ *+ * @param {Object} opts+ * @api public+ */++function XHR(opts){+ Polling.call(this, opts);++ if (global.location) {+ var isSSL = 'https:' == location.protocol;+ var port = location.port;++ // some user agents have empty `location.port`+ if (!port) {+ port = isSSL ? 443 : 80;+ }++ this.xd = opts.hostname != global.location.hostname ||+ port != opts.port;+ this.xs = opts.secure != isSSL;+ }+}++/**+ * Inherits from Polling.+ */++inherit(XHR, Polling);++/**+ * XHR supports binary+ */++XHR.prototype.supportsBinary = true;++/**+ * Creates a request.+ *+ * @param {String} method+ * @api private+ */++XHR.prototype.request = function(opts){+ opts = opts || {};+ opts.uri = this.uri();+ opts.xd = this.xd;+ opts.xs = this.xs;+ opts.agent = this.agent || false;+ opts.supportsBinary = this.supportsBinary;+ opts.enablesXDR = this.enablesXDR;++ // SSL options for Node.js client+ opts.pfx = this.pfx;+ opts.key = this.key;+ opts.passphrase = this.passphrase;+ opts.cert = this.cert;+ opts.ca = this.ca;+ opts.ciphers = this.ciphers;+ opts.rejectUnauthorized = this.rejectUnauthorized;++ return new Request(opts);+};++/**+ * Sends data.+ *+ * @param {String} data to send.+ * @param {Function} called upon flush.+ * @api private+ */++XHR.prototype.doWrite = function(data, fn){+ var isBinary = typeof data !== 'string' && data !== undefined;+ var req = this.request({ method: 'POST', data: data, isBinary: isBinary });+ var self = this;+ req.on('success', fn);+ req.on('error', function(err){+ self.onError('xhr post error', err);+ });+ this.sendXhr = req;+};++/**+ * Starts a poll cycle.+ *+ * @api private+ */++XHR.prototype.doPoll = function(){+ debug('xhr poll');+ var req = this.request();+ var self = this;+ req.on('data', function(data){+ self.onData(data);+ });+ req.on('error', function(err){+ self.onError('xhr poll error', err);+ });+ this.pollXhr = req;+};++/**+ * Request constructor+ *+ * @param {Object} options+ * @api public+ */++function Request(opts){+ this.method = opts.method || 'GET';+ this.uri = opts.uri;+ this.xd = !!opts.xd;+ this.xs = !!opts.xs;+ this.async = false !== opts.async;+ this.data = undefined != opts.data ? opts.data : null;+ this.agent = opts.agent;+ this.isBinary = opts.isBinary;+ this.supportsBinary = opts.supportsBinary;+ this.enablesXDR = opts.enablesXDR;++ // SSL options for Node.js client+ this.pfx = opts.pfx;+ this.key = opts.key;+ this.passphrase = opts.passphrase;+ this.cert = opts.cert;+ this.ca = opts.ca;+ this.ciphers = opts.ciphers;+ this.rejectUnauthorized = opts.rejectUnauthorized;++ this.create();+}++/**+ * Mix in `Emitter`.+ */++Emitter(Request.prototype);++/**+ * Creates the XHR object and sends the request.+ *+ * @api private+ */++Request.prototype.create = function(){+ var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };++ // SSL options for Node.js client+ opts.pfx = this.pfx;+ opts.key = this.key;+ opts.passphrase = this.passphrase;+ opts.cert = this.cert;+ opts.ca = this.ca;+ opts.ciphers = this.ciphers;+ opts.rejectUnauthorized = this.rejectUnauthorized;++ var xhr = this.xhr = new XMLHttpRequest(opts);+ var self = this;++ try {+ debug('xhr open %s: %s', this.method, this.uri);+ xhr.open(this.method, this.uri, this.async);+ if (this.supportsBinary) {+ // This has to be done after open because Firefox is stupid+ // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension+ xhr.responseType = 'arraybuffer';+ }++ if ('POST' == this.method) {+ try {+ if (this.isBinary) {+ xhr.setRequestHeader('Content-type', 'application/octet-stream');+ } else {+ xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');+ }+ } catch (e) {}+ }++ // ie6 check+ if ('withCredentials' in xhr) {+ xhr.withCredentials = true;+ }++ if (this.hasXDR()) {+ xhr.onload = function(){+ self.onLoad();+ };+ xhr.onerror = function(){+ self.onError(xhr.responseText);+ };+ } else {+ xhr.onreadystatechange = function(){+ if (4 != xhr.readyState) return;+ if (200 == xhr.status || 1223 == xhr.status) {+ self.onLoad();+ } else {+ // make sure the `error` event handler that's user-set+ // does not throw in the same tick and gets caught here+ setTimeout(function(){+ self.onError(xhr.status);+ }, 0);+ }+ };+ }++ debug('xhr data %s', this.data);+ xhr.send(this.data);+ } catch (e) {+ // Need to defer since .create() is called directly fhrom the constructor+ // and thus the 'error' event can only be only bound *after* this exception+ // occurs. Therefore, also, we cannot throw here at all.+ setTimeout(function() {+ self.onError(e);+ }, 0);+ return;+ }++ if (global.document) {+ this.index = Request.requestsCount++;+ Request.requests[this.index] = this;+ }+};++/**+ * Called upon successful response.+ *+ * @api private+ */++Request.prototype.onSuccess = function(){+ this.emit('success');+ this.cleanup();+};++/**+ * Called if we have data.+ *+ * @api private+ */++Request.prototype.onData = function(data){+ this.emit('data', data);+ this.onSuccess();+};++/**+ * Called upon error.+ *+ * @api private+ */++Request.prototype.onError = function(err){+ this.emit('error', err);+ this.cleanup(true);+};++/**+ * Cleans up house.+ *+ * @api private+ */++Request.prototype.cleanup = function(fromError){+ if ('undefined' == typeof this.xhr || null === this.xhr) {+ return;+ }+ // xmlhttprequest+ if (this.hasXDR()) {+ this.xhr.onload = this.xhr.onerror = empty;+ } else {+ this.xhr.onreadystatechange = empty;+ }++ if (fromError) {+ try {+ this.xhr.abort();+ } catch(e) {}+ }++ if (global.document) {+ delete Request.requests[this.index];+ }++ this.xhr = null;+};++/**+ * Called upon load.+ *+ * @api private+ */++Request.prototype.onLoad = function(){+ var data;+ try {+ var contentType;+ try {+ contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0];+ } catch (e) {}+ if (contentType === 'application/octet-stream') {+ data = this.xhr.response;+ } else {+ if (!this.supportsBinary) {+ data = this.xhr.responseText;+ } else {+ data = 'ok';+ }+ }+ } catch (e) {+ this.onError(e);+ }+ if (null != data) {+ this.onData(data);+ }+};++/**+ * Check if it has XDomainRequest.+ *+ * @api private+ */++Request.prototype.hasXDR = function(){+ return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR;+};++/**+ * Aborts the request.+ *+ * @api public+ */++Request.prototype.abort = function(){+ this.cleanup();+};++/**+ * Aborts pending requests when unloading the window. This is needed to prevent+ * memory leaks (e.g. when using IE) and to ensure that no spurious error is+ * emitted.+ */++if (global.document) {+ Request.requestsCount = 0;+ Request.requests = {};+ if (global.attachEvent) {+ global.attachEvent('onunload', unloadHandler);+ } else if (global.addEventListener) {+ global.addEventListener('beforeunload', unloadHandler, false);+ }+}++function unloadHandler() {+ for (var i in Request.requests) {+ if (Request.requests.hasOwnProperty(i)) {+ Request.requests[i].abort();+ }+ }+}++}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})+},{"./polling":118,"component-emitter":109,"component-inherit":121,"debug":122,"xmlhttprequest":120}],118:[function(require,module,exports){+/**+ * Module dependencies.+ */++var Transport = require('../transport');+var parseqs = require('parseqs');+var parser = require('engine.io-parser');+var inherit = require('component-inherit');+var debug = require('debug')('engine.io-client:polling');++/**+ * Module exports.+ */++module.exports = Polling;++/**+ * Is XHR2 supported?+ */++var hasXHR2 = (function() {+ var XMLHttpRequest = require('xmlhttprequest');+ var xhr = new XMLHttpRequest({ xdomain: false });+ return null != xhr.responseType;+})();++/**+ * Polling interface.+ *+ * @param {Object} opts+ * @api private+ */++function Polling(opts){+ var forceBase64 = (opts && opts.forceBase64);+ if (!hasXHR2 || forceBase64) {+ this.supportsBinary = false;+ }+ Transport.call(this, opts);+}++/**+ * Inherits from Transport.+ */++inherit(Polling, Transport);++/**+ * Transport name.+ */++Polling.prototype.name = 'polling';++/**+ * Opens the socket (triggers polling). We write a PING message to determine+ * when the transport is open.+ *+ * @api private+ */++Polling.prototype.doOpen = function(){+ this.poll();+};++/**+ * Pauses polling.+ *+ * @param {Function} callback upon buffers are flushed and transport is paused+ * @api private+ */++Polling.prototype.pause = function(onPause){+ var pending = 0;+ var self = this;++ this.readyState = 'pausing';++ function pause(){+ debug('paused');+ self.readyState = 'paused';+ onPause();+ }++ if (this.polling || !this.writable) {+ var total = 0;++ if (this.polling) {+ debug('we are currently polling - waiting to pause');+ total++;+ this.once('pollComplete', function(){+ debug('pre-pause polling complete');+ --total || pause();+ });+ }++ if (!this.writable) {+ debug('we are currently writing - waiting to pause');+ total++;+ this.once('drain', function(){+ debug('pre-pause writing complete');+ --total || pause();+ });+ }+ } else {+ pause();+ }+};++/**+ * Starts polling cycle.+ *+ * @api public+ */++Polling.prototype.poll = function(){+ debug('polling');+ this.polling = true;+ this.doPoll();+ this.emit('poll');+};++/**+ * Overloads onData to detect payloads.+ *+ * @api private+ */++Polling.prototype.onData = function(data){+ var self = this;+ debug('polling got data %s', data);+ var callback = function(packet, index, total) {+ // if its the first message we consider the transport open+ if ('opening' == self.readyState) {+ self.onOpen();+ }++ // if its a close packet, we close the ongoing requests+ if ('close' == packet.type) {+ self.onClose();+ return false;+ }++ // otherwise bypass onData and handle the message+ self.onPacket(packet);+ };++ // decode payload+ parser.decodePayload(data, this.socket.binaryType, callback);++ // if an event did not trigger closing+ if ('closed' != this.readyState) {+ // if we got data we're not polling+ this.polling = false;+ this.emit('pollComplete');++ if ('open' == this.readyState) {+ this.poll();+ } else {+ debug('ignoring poll - transport state "%s"', this.readyState);+ }+ }+};++/**+ * For polling, send a close packet.+ *+ * @api private+ */++Polling.prototype.doClose = function(){+ var self = this;++ function close(){+ debug('writing close packet');+ self.write([{ type: 'close' }]);+ }++ if ('open' == this.readyState) {+ debug('transport open - closing');+ close();+ } else {+ // in case we're trying to close while+ // handshaking is in progress (GH-164)+ debug('transport not open - deferring close');+ this.once('open', close);+ }+};++/**+ * Writes a packets payload.+ *+ * @param {Array} data packets+ * @param {Function} drain callback+ * @api private+ */++Polling.prototype.write = function(packets){+ var self = this;+ this.writable = false;+ var callbackfn = function() {+ self.writable = true;+ self.emit('drain');+ };++ var self = this;+ parser.encodePayload(packets, this.supportsBinary, function(data) {+ self.doWrite(data, callbackfn);+ });+};++/**+ * Generates uri for connection.+ *+ * @api private+ */++Polling.prototype.uri = function(){+ var query = this.query || {};+ var schema = this.secure ? 'https' : 'http';+ var port = '';++ // cache busting is forced+ if (false !== this.timestampRequests) {+ query[this.timestampParam] = +new Date + '-' + Transport.timestamps++;+ }++ if (!this.supportsBinary && !query.sid) {+ query.b64 = 1;+ }++ query = parseqs.encode(query);++ // avoid port if default for schema+ if (this.port && (('https' == schema && this.port != 443) ||+ ('http' == schema && this.port != 80))) {+ port = ':' + this.port;+ }++ // prepend ? to query+ if (query.length) {+ query = '?' + query;+ }++ return schema + '://' + this.hostname + port + this.path + query;+};++},{"../transport":114,"component-inherit":121,"debug":122,"engine.io-parser":125,"parseqs":137,"xmlhttprequest":120}],119:[function(require,module,exports){+/**+ * Module dependencies.+ */++var Transport = require('../transport');+var parser = require('engine.io-parser');+var parseqs = require('parseqs');+var inherit = require('component-inherit');+var debug = require('debug')('engine.io-client:websocket');++/**+ * `ws` exposes a WebSocket-compatible interface in+ * Node, or the `WebSocket` or `MozWebSocket` globals+ * in the browser.+ */++var WebSocket = require('ws');++/**+ * Module exports.+ */++module.exports = WS;++/**+ * WebSocket transport constructor.+ *+ * @api {Object} connection options+ * @api public+ */++function WS(opts){+ var forceBase64 = (opts && opts.forceBase64);+ if (forceBase64) {+ this.supportsBinary = false;+ }+ Transport.call(this, opts);+}++/**+ * Inherits from Transport.+ */++inherit(WS, Transport);++/**+ * Transport name.+ *+ * @api public+ */++WS.prototype.name = 'websocket';++/*+ * WebSockets support binary+ */++WS.prototype.supportsBinary = true;++/**+ * Opens socket.+ *+ * @api private+ */++WS.prototype.doOpen = function(){+ if (!this.check()) {+ // let probe timeout+ return;+ }++ var self = this;+ var uri = this.uri();+ var protocols = void(0);+ var opts = { agent: this.agent };++ // SSL options for Node.js client+ opts.pfx = this.pfx;+ opts.key = this.key;+ opts.passphrase = this.passphrase;+ opts.cert = this.cert;+ opts.ca = this.ca;+ opts.ciphers = this.ciphers;+ opts.rejectUnauthorized = this.rejectUnauthorized;++ this.ws = new WebSocket(uri, protocols, opts);++ if (this.ws.binaryType === undefined) {+ this.supportsBinary = false;+ }++ this.ws.binaryType = 'arraybuffer';+ this.addEventListeners();+};++/**+ * Adds event listeners to the socket+ *+ * @api private+ */++WS.prototype.addEventListeners = function(){+ var self = this;++ this.ws.onopen = function(){+ self.onOpen();+ };+ this.ws.onclose = function(){+ self.onClose();+ };+ this.ws.onmessage = function(ev){+ self.onData(ev.data);+ };+ this.ws.onerror = function(e){+ self.onError('websocket error', e);+ };+};++/**+ * Override `onData` to use a timer on iOS.+ * See: https://gist.github.com/mloughran/2052006+ *+ * @api private+ */++if ('undefined' != typeof navigator+ && /iPad|iPhone|iPod/i.test(navigator.userAgent)) {+ WS.prototype.onData = function(data){+ var self = this;+ setTimeout(function(){+ Transport.prototype.onData.call(self, data);+ }, 0);+ };+}++/**+ * Writes data to socket.+ *+ * @param {Array} array of packets.+ * @api private+ */++WS.prototype.write = function(packets){+ var self = this;+ this.writable = false;+ // encodePacket efficient as it uses WS framing+ // no need for encodePayload+ for (var i = 0, l = packets.length; i < l; i++) {+ parser.encodePacket(packets[i], this.supportsBinary, function(data) {+ //Sometimes the websocket has already been closed but the browser didn't+ //have a chance of informing us about it yet, in that case send will+ //throw an error+ try {+ self.ws.send(data);+ } catch (e){+ debug('websocket closed before onclose event');+ }+ });+ }++ function ondrain() {+ self.writable = true;+ self.emit('drain');+ }+ // fake drain+ // defer to next tick to allow Socket to clear writeBuffer+ setTimeout(ondrain, 0);+};++/**+ * Called upon close+ *+ * @api private+ */++WS.prototype.onClose = function(){+ Transport.prototype.onClose.call(this);+};++/**+ * Closes socket.+ *+ * @api private+ */++WS.prototype.doClose = function(){+ if (typeof this.ws !== 'undefined') {+ this.ws.close();+ }+};++/**+ * Generates uri for connection.+ *+ * @api private+ */++WS.prototype.uri = function(){+ var query = this.query || {};+ var schema = this.secure ? 'wss' : 'ws';+ var port = '';++ // avoid port if default for schema+ if (this.port && (('wss' == schema && this.port != 443)+ || ('ws' == schema && this.port != 80))) {+ port = ':' + this.port;+ }++ // append timestamp to URI+ if (this.timestampRequests) {+ query[this.timestampParam] = +new Date;+ }++ // communicate binary support capabilities+ if (!this.supportsBinary) {+ query.b64 = 1;+ }++ query = parseqs.encode(query);++ // prepend ? to query+ if (query.length) {+ query = '?' + query;+ }++ return schema + '://' + this.hostname + port + this.path + query;+};++/**+ * Feature detection for WebSocket.+ *+ * @return {Boolean} whether this transport is available.+ * @api public+ */++WS.prototype.check = function(){+ return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);+};++},{"../transport":114,"component-inherit":121,"debug":122,"engine.io-parser":125,"parseqs":137,"ws":139}],120:[function(require,module,exports){+// browser shim for xmlhttprequest module+var hasCORS = require('has-cors');++module.exports = function(opts) {+ var xdomain = opts.xdomain;++ // scheme must be same when usign XDomainRequest+ // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx+ var xscheme = opts.xscheme;++ // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.+ // https://github.com/Automattic/engine.io-client/pull/217+ var enablesXDR = opts.enablesXDR;++ // XMLHttpRequest can be disabled on IE+ try {+ if ('undefined' != typeof XMLHttpRequest && (!xdomain || hasCORS)) {+ return new XMLHttpRequest();+ }+ } catch (e) { }++ // Use XDomainRequest for IE8 if enablesXDR is true+ // because loading bar keeps flashing when using jsonp-polling+ // https://github.com/yujiosaka/socke.io-ie8-loading-example+ try {+ if ('undefined' != typeof XDomainRequest && !xscheme && enablesXDR) {+ return new XDomainRequest();+ }+ } catch (e) { }++ if (!xdomain) {+ try {+ return new ActiveXObject('Microsoft.XMLHTTP');+ } catch(e) { }+ }+}++},{"has-cors":134}],121:[function(require,module,exports){++module.exports = function(a, b){+ var fn = function(){};+ fn.prototype = b.prototype;+ a.prototype = new fn;+ a.prototype.constructor = a;+};+},{}],122:[function(require,module,exports){++/**+ * This is the web browser implementation of `debug()`.+ *+ * Expose `debug()` as the module.+ */++exports = module.exports = require('./debug');+exports.log = log;+exports.formatArgs = formatArgs;+exports.save = save;+exports.load = load;+exports.useColors = useColors;++/**+ * Colors.+ */++exports.colors = [+ 'lightseagreen',+ 'forestgreen',+ 'goldenrod',+ 'dodgerblue',+ 'darkorchid',+ 'crimson'+];++/**+ * Currently only WebKit-based Web Inspectors, Firefox >= v31,+ * and the Firebug extension (any Firefox version) are known+ * to support "%c" CSS customizations.+ *+ * TODO: add a `localStorage` variable to explicitly enable/disable colors+ */++function useColors() {+ // is webkit? http://stackoverflow.com/a/16459606/376773+ return ('WebkitAppearance' in document.documentElement.style) ||+ // is firebug? http://stackoverflow.com/a/398120/376773+ (window.console && (console.firebug || (console.exception && console.table))) ||+ // is firefox >= v31?+ // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages+ (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);+}++/**+ * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.+ */++exports.formatters.j = function(v) {+ return JSON.stringify(v);+};+++/**+ * Colorize log arguments if enabled.+ *+ * @api public+ */++function formatArgs() {+ var args = arguments;+ var useColors = this.useColors;++ args[0] = (useColors ? '%c' : '')+ + this.namespace+ + (useColors ? ' %c' : ' ')+ + args[0]+ + (useColors ? '%c ' : ' ')+ + '+' + exports.humanize(this.diff);++ if (!useColors) return args;++ var c = 'color: ' + this.color;+ args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));++ // the final "%c" is somewhat tricky, because there could be other+ // arguments passed either before or after the %c, so we need to+ // figure out the correct index to insert the CSS into+ var index = 0;+ var lastC = 0;+ args[0].replace(/%[a-z%]/g, function(match) {+ if ('%%' === match) return;+ index++;+ if ('%c' === match) {+ // we only are interested in the *last* %c+ // (the user may have provided their own)+ lastC = index;+ }+ });++ args.splice(lastC, 0, c);+ return args;+}++/**+ * Invokes `console.log()` when available.+ * No-op when `console.log` is not a "function".+ *+ * @api public+ */++function log() {+ // This hackery is required for IE8,+ // where the `console.log` function doesn't have 'apply'+ return 'object' == typeof console+ && 'function' == typeof console.log+ && Function.prototype.apply.call(console.log, console, arguments);+}++/**+ * Save `namespaces`.+ *+ * @param {String} namespaces+ * @api private+ */++function save(namespaces) {+ try {+ if (null == namespaces) {+ localStorage.removeItem('debug');+ } else {+ localStorage.debug = namespaces;+ }+ } catch(e) {}+}++/**+ * Load `namespaces`.+ *+ * @return {String} returns the previously persisted debug modes+ * @api private+ */++function load() {+ var r;+ try {+ r = localStorage.debug;+ } catch(e) {}+ return r;+}++/**+ * Enable namespaces listed in `localStorage.debug` initially.+ */++exports.enable(load());++},{"./debug":123}],123:[function(require,module,exports){++/**+ * This is the common logic for both the Node.js and web browser+ * implementations of `debug()`.+ *+ * Expose `debug()` as the module.+ */++exports = module.exports = debug;+exports.coerce = coerce;+exports.disable = disable;+exports.enable = enable;+exports.enabled = enabled;+exports.humanize = require('ms');++/**+ * The currently active debug mode names, and names to skip.+ */++exports.names = [];+exports.skips = [];++/**+ * Map of special "%n" handling functions, for the debug "format" argument.+ *+ * Valid key names are a single, lowercased letter, i.e. "n".+ */++exports.formatters = {};++/**+ * Previously assigned color.+ */++var prevColor = 0;++/**+ * Previous log timestamp.+ */++var prevTime;++/**+ * Select a color.+ *+ * @return {Number}+ * @api private+ */++function selectColor() {+ return exports.colors[prevColor++ % exports.colors.length];+}++/**+ * Create a debugger with the given `namespace`.+ *+ * @param {String} namespace+ * @return {Function}+ * @api public+ */++function debug(namespace) {++ // define the `disabled` version+ function disabled() {+ }+ disabled.enabled = false;++ // define the `enabled` version+ function enabled() {++ var self = enabled;++ // set `diff` timestamp+ var curr = +new Date();+ var ms = curr - (prevTime || curr);+ self.diff = ms;+ self.prev = prevTime;+ self.curr = curr;+ prevTime = curr;++ // add the `color` if not set+ if (null == self.useColors) self.useColors = exports.useColors();+ if (null == self.color && self.useColors) self.color = selectColor();++ var args = Array.prototype.slice.call(arguments);++ args[0] = exports.coerce(args[0]);++ if ('string' !== typeof args[0]) {+ // anything else let's inspect with %o+ args = ['%o'].concat(args);+ }++ // apply any `formatters` transformations+ var index = 0;+ args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {+ // if we encounter an escaped % then don't increase the array index+ if (match === '%%') return match;+ index++;+ var formatter = exports.formatters[format];+ if ('function' === typeof formatter) {+ var val = args[index];+ match = formatter.call(self, val);++ // now we need to remove `args[index]` since it's inlined in the `format`+ args.splice(index, 1);+ index--;+ }+ return match;+ });++ if ('function' === typeof exports.formatArgs) {+ args = exports.formatArgs.apply(self, args);+ }+ var logFn = enabled.log || exports.log || console.log.bind(console);+ logFn.apply(self, args);+ }+ enabled.enabled = true;++ var fn = exports.enabled(namespace) ? enabled : disabled;++ fn.namespace = namespace;++ return fn;+}++/**+ * Enables a debug mode by namespaces. This can include modes+ * separated by a colon and wildcards.+ *+ * @param {String} namespaces+ * @api public+ */++function enable(namespaces) {+ exports.save(namespaces);++ var split = (namespaces || '').split(/[\s,]+/);+ var len = split.length;++ for (var i = 0; i < len; i++) {+ if (!split[i]) continue; // ignore empty strings+ namespaces = split[i].replace(/\*/g, '.*?');+ if (namespaces[0] === '-') {+ exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));+ } else {+ exports.names.push(new RegExp('^' + namespaces + '$'));+ }+ }+}++/**+ * Disable debug output.+ *+ * @api public+ */++function disable() {+ exports.enable('');+}++/**+ * Returns true if the given mode name is enabled, false otherwise.+ *+ * @param {String} name+ * @return {Boolean}+ * @api public+ */++function enabled(name) {+ var i, len;+ for (i = 0, len = exports.skips.length; i < len; i++) {+ if (exports.skips[i].test(name)) {+ return false;+ }+ }+ for (i = 0, len = exports.names.length; i < len; i++) {+ if (exports.names[i].test(name)) {+ return true;+ }+ }+ return false;+}++/**+ * Coerce `val`.+ *+ * @param {Mixed} val+ * @return {Mixed}+ * @api private+ */++function coerce(val) {+ if (val instanceof Error) return val.stack || val.message;+ return val;+}++},{"ms":124}],124:[function(require,module,exports){+/**+ * Helpers.+ */++var s = 1000;+var m = s * 60;+var h = m * 60;+var d = h * 24;+var y = d * 365.25;++/**+ * Parse or format the given `val`.+ *+ * Options:+ *+ * - `long` verbose formatting [false]+ *+ * @param {String|Number} val+ * @param {Object} options+ * @return {String|Number}+ * @api public+ */++module.exports = function(val, options){+ options = options || {};+ if ('string' == typeof val) return parse(val);+ return options.long+ ? long(val)+ : short(val);+};++/**+ * Parse the given `str` and return milliseconds.+ *+ * @param {String} str+ * @return {Number}+ * @api private+ */++function parse(str) {+ var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);+ if (!match) return;+ var n = parseFloat(match[1]);+ var type = (match[2] || 'ms').toLowerCase();+ switch (type) {+ case 'years':+ case 'year':+ case 'y':+ return n * y;+ case 'days':+ case 'day':+ case 'd':+ return n * d;+ case 'hours':+ case 'hour':+ case 'h':+ return n * h;+ case 'minutes':+ case 'minute':+ case 'm':+ return n * m;+ case 'seconds':+ case 'second':+ case 's':+ return n * s;+ case 'ms':+ return n;+ }+}++/**+ * Short format for `ms`.+ *+ * @param {Number} ms+ * @return {String}+ * @api private+ */++function short(ms) {+ if (ms >= d) return Math.round(ms / d) + 'd';+ if (ms >= h) return Math.round(ms / h) + 'h';+ if (ms >= m) return Math.round(ms / m) + 'm';+ if (ms >= s) return Math.round(ms / s) + 's';+ return ms + 'ms';+}++/**+ * Long format for `ms`.+ *+ * @param {Number} ms+ * @return {String}+ * @api private+ */++function long(ms) {+ return plural(ms, d, 'day')+ || plural(ms, h, 'hour')+ || plural(ms, m, 'minute')+ || plural(ms, s, 'second')+ || ms + ' ms';+}++/**+ * Pluralization helper.+ */++function plural(ms, n, name) {+ if (ms < n) return;+ if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;+ return Math.ceil(ms / n) + ' ' + name + 's';+}++},{}],125:[function(require,module,exports){+(function (global){+/**+ * Module dependencies.+ */++var keys = require('./keys');+var hasBinary = require('has-binary');+var sliceBuffer = require('arraybuffer.slice');+var base64encoder = require('base64-arraybuffer');+var after = require('after');+var utf8 = require('utf8');++/**+ * Check if we are running an android browser. That requires us to use+ * ArrayBuffer with polling transports...+ *+ * http://ghinda.net/jpeg-blob-ajax-android/+ */++var isAndroid = navigator.userAgent.match(/Android/i);++/**+ * Check if we are running in PhantomJS.+ * Uploading a Blob with PhantomJS does not work correctly, as reported here:+ * https://github.com/ariya/phantomjs/issues/11395+ * @type boolean+ */+var isPhantomJS = /PhantomJS/i.test(navigator.userAgent);++/**+ * When true, avoids using Blobs to encode payloads.+ * @type boolean+ */+var dontSendBlobs = isAndroid || isPhantomJS;++/**+ * Current protocol version.+ */++exports.protocol = 3;++/**+ * Packet types.+ */++var packets = exports.packets = {+ open: 0 // non-ws+ , close: 1 // non-ws+ , ping: 2+ , pong: 3+ , message: 4+ , upgrade: 5+ , noop: 6+};++var packetslist = keys(packets);++/**+ * Premade error packet.+ */++var err = { type: 'error', data: 'parser error' };++/**+ * Create a blob api even for blob builder when vendor prefixes exist+ */++var Blob = require('blob');++/**+ * Encodes a packet.+ *+ * <packet type id> [ <data> ]+ *+ * Example:+ *+ * 5hello world+ * 3+ * 4+ *+ * Binary is encoded in an identical principle+ *+ * @api private+ */++exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {+ if ('function' == typeof supportsBinary) {+ callback = supportsBinary;+ supportsBinary = false;+ }++ if ('function' == typeof utf8encode) {+ callback = utf8encode;+ utf8encode = null;+ }++ var data = (packet.data === undefined)+ ? undefined+ : packet.data.buffer || packet.data;++ if (global.ArrayBuffer && data instanceof ArrayBuffer) {+ return encodeArrayBuffer(packet, supportsBinary, callback);+ } else if (Blob && data instanceof global.Blob) {+ return encodeBlob(packet, supportsBinary, callback);+ }++ // might be an object with { base64: true, data: dataAsBase64String }+ if (data && data.base64) {+ return encodeBase64Object(packet, callback);+ }++ // Sending data as a utf-8 string+ var encoded = packets[packet.type];++ // data fragment is optional+ if (undefined !== packet.data) {+ encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data);+ }++ return callback('' + encoded);++};++function encodeBase64Object(packet, callback) {+ // packet data is an object { base64: true, data: dataAsBase64String }+ var message = 'b' + exports.packets[packet.type] + packet.data.data;+ return callback(message);+}++/**+ * Encode packet helpers for binary types+ */++function encodeArrayBuffer(packet, supportsBinary, callback) {+ if (!supportsBinary) {+ return exports.encodeBase64Packet(packet, callback);+ }++ var data = packet.data;+ var contentArray = new Uint8Array(data);+ var resultBuffer = new Uint8Array(1 + data.byteLength);++ resultBuffer[0] = packets[packet.type];+ for (var i = 0; i < contentArray.length; i++) {+ resultBuffer[i+1] = contentArray[i];+ }++ return callback(resultBuffer.buffer);+}++function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {+ if (!supportsBinary) {+ return exports.encodeBase64Packet(packet, callback);+ }++ var fr = new FileReader();+ fr.onload = function() {+ packet.data = fr.result;+ exports.encodePacket(packet, supportsBinary, true, callback);+ };+ return fr.readAsArrayBuffer(packet.data);+}++function encodeBlob(packet, supportsBinary, callback) {+ if (!supportsBinary) {+ return exports.encodeBase64Packet(packet, callback);+ }++ if (dontSendBlobs) {+ return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);+ }++ var length = new Uint8Array(1);+ length[0] = packets[packet.type];+ var blob = new Blob([length.buffer, packet.data]);++ return callback(blob);+}++/**+ * Encodes a packet with binary data in a base64 string+ *+ * @param {Object} packet, has `type` and `data`+ * @return {String} base64 encoded message+ */++exports.encodeBase64Packet = function(packet, callback) {+ var message = 'b' + exports.packets[packet.type];+ if (Blob && packet.data instanceof Blob) {+ var fr = new FileReader();+ fr.onload = function() {+ var b64 = fr.result.split(',')[1];+ callback(message + b64);+ };+ return fr.readAsDataURL(packet.data);+ }++ var b64data;+ try {+ b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));+ } catch (e) {+ // iPhone Safari doesn't let you apply with typed arrays+ var typed = new Uint8Array(packet.data);+ var basic = new Array(typed.length);+ for (var i = 0; i < typed.length; i++) {+ basic[i] = typed[i];+ }+ b64data = String.fromCharCode.apply(null, basic);+ }+ message += global.btoa(b64data);+ return callback(message);+};++/**+ * Decodes a packet. Changes format to Blob if requested.+ *+ * @return {Object} with `type` and `data` (if any)+ * @api private+ */++exports.decodePacket = function (data, binaryType, utf8decode) {+ // String data+ if (typeof data == 'string' || data === undefined) {+ if (data.charAt(0) == 'b') {+ return exports.decodeBase64Packet(data.substr(1), binaryType);+ }++ if (utf8decode) {+ try {+ data = utf8.decode(data);+ } catch (e) {+ return err;+ }+ }+ var type = data.charAt(0);++ if (Number(type) != type || !packetslist[type]) {+ return err;+ }++ if (data.length > 1) {+ return { type: packetslist[type], data: data.substring(1) };+ } else {+ return { type: packetslist[type] };+ }+ }++ var asArray = new Uint8Array(data);+ var type = asArray[0];+ var rest = sliceBuffer(data, 1);+ if (Blob && binaryType === 'blob') {+ rest = new Blob([rest]);+ }+ return { type: packetslist[type], data: rest };+};++/**+ * Decodes a packet encoded in a base64 string+ *+ * @param {String} base64 encoded message+ * @return {Object} with `type` and `data` (if any)+ */++exports.decodeBase64Packet = function(msg, binaryType) {+ var type = packetslist[msg.charAt(0)];+ if (!global.ArrayBuffer) {+ return { type: type, data: { base64: true, data: msg.substr(1) } };+ }++ var data = base64encoder.decode(msg.substr(1));++ if (binaryType === 'blob' && Blob) {+ data = new Blob([data]);+ }++ return { type: type, data: data };+};++/**+ * Encodes multiple messages (payload).+ *+ * <length>:data+ *+ * Example:+ *+ * 11:hello world2:hi+ *+ * If any contents are binary, they will be encoded as base64 strings. Base64+ * encoded strings are marked with a b before the length specifier+ *+ * @param {Array} packets+ * @api private+ */++exports.encodePayload = function (packets, supportsBinary, callback) {+ if (typeof supportsBinary == 'function') {+ callback = supportsBinary;+ supportsBinary = null;+ }++ var isBinary = hasBinary(packets);++ if (supportsBinary && isBinary) {+ if (Blob && !dontSendBlobs) {+ return exports.encodePayloadAsBlob(packets, callback);+ }++ return exports.encodePayloadAsArrayBuffer(packets, callback);+ }++ if (!packets.length) {+ return callback('0:');+ }++ function setLengthHeader(message) {+ return message.length + ':' + message;+ }++ function encodeOne(packet, doneCallback) {+ exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) {+ doneCallback(null, setLengthHeader(message));+ });+ }++ map(packets, encodeOne, function(err, results) {+ return callback(results.join(''));+ });+};++/**+ * Async array map using after+ */++function map(ary, each, done) {+ var result = new Array(ary.length);+ var next = after(ary.length, done);++ var eachWithIndex = function(i, el, cb) {+ each(el, function(error, msg) {+ result[i] = msg;+ cb(error, result);+ });+ };++ for (var i = 0; i < ary.length; i++) {+ eachWithIndex(i, ary[i], next);+ }+}++/*+ * Decodes data when a payload is maybe expected. Possible binary contents are+ * decoded from their base64 representation+ *+ * @param {String} data, callback method+ * @api public+ */++exports.decodePayload = function (data, binaryType, callback) {+ if (typeof data != 'string') {+ return exports.decodePayloadAsBinary(data, binaryType, callback);+ }++ if (typeof binaryType === 'function') {+ callback = binaryType;+ binaryType = null;+ }++ var packet;+ if (data == '') {+ // parser error - ignoring payload+ return callback(err, 0, 1);+ }++ var length = ''+ , n, msg;++ for (var i = 0, l = data.length; i < l; i++) {+ var chr = data.charAt(i);++ if (':' != chr) {+ length += chr;+ } else {+ if ('' == length || (length != (n = Number(length)))) {+ // parser error - ignoring payload+ return callback(err, 0, 1);+ }++ msg = data.substr(i + 1, n);++ if (length != msg.length) {+ // parser error - ignoring payload+ return callback(err, 0, 1);}- },- { //a=rtcp-fb:98 trr-int 100- push: 'rtcpFbTrrInt',- reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,- names: ['payload', 'value'],- format: "rtcp-fb:%d trr-int %d"- },- { //a=rtcp-fb:98 nack rpsi- push: 'rtcpFb',- reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,- names: ['payload', 'type', 'subtype'],- format: function (o) {- return (o.subtype != null) ?- "rtcp-fb:%s %s %s":- "rtcp-fb:%s %s";++ if (msg.length) {+ packet = exports.decodePacket(msg, binaryType, true);++ if (err.type == packet.type && err.data == packet.data) {+ // parser error in individual packet - ignoring payload+ return callback(err, 0, 1);+ }++ var ret = callback(packet, i + n, l);+ if (false === ret) return;}- },- { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset- //a=extmap:1/recvonly URI-gps-string- push: 'ext',- reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,- names: ['value', 'uri', 'config'], // value may include "/direction" suffix- format: function (o) {- return (o.config != null) ?- "extmap:%s %s %s":- "extmap:%s %s";++ // advance cursor+ i += n;+ length = '';+ }+ }++ if (length != '') {+ // parser error - ignoring payload+ return callback(err, 0, 1);+ }++};++/**+ * Encodes multiple messages (payload) as binary.+ *+ * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number+ * 255><data>+ *+ * Example:+ * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers+ *+ * @param {Array} packets+ * @return {ArrayBuffer} encoded payload+ * @api private+ */++exports.encodePayloadAsArrayBuffer = function(packets, callback) {+ if (!packets.length) {+ return callback(new ArrayBuffer(0));+ }++ function encodeOne(packet, doneCallback) {+ exports.encodePacket(packet, true, true, function(data) {+ return doneCallback(null, data);+ });+ }++ map(packets, encodeOne, function(err, encodedPackets) {+ var totalLength = encodedPackets.reduce(function(acc, p) {+ var len;+ if (typeof p === 'string'){+ len = p.length;+ } else {+ len = p.byteLength;+ }+ return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2+ }, 0);++ var resultArray = new Uint8Array(totalLength);++ var bufferIndex = 0;+ encodedPackets.forEach(function(p) {+ var isString = typeof p === 'string';+ var ab = p;+ if (isString) {+ var view = new Uint8Array(p.length);+ for (var i = 0; i < p.length; i++) {+ view[i] = p.charCodeAt(i);+ }+ ab = view.buffer;+ }++ if (isString) { // not true binary+ resultArray[bufferIndex++] = 0;+ } else { // true binary+ resultArray[bufferIndex++] = 1;+ }++ var lenStr = ab.byteLength.toString();+ for (var i = 0; i < lenStr.length; i++) {+ resultArray[bufferIndex++] = parseInt(lenStr[i]);+ }+ resultArray[bufferIndex++] = 255;++ var view = new Uint8Array(ab);+ for (var i = 0; i < view.length; i++) {+ resultArray[bufferIndex++] = view[i];+ }+ });++ return callback(resultArray.buffer);+ });+};++/**+ * Encode as Blob+ */++exports.encodePayloadAsBlob = function(packets, callback) {+ function encodeOne(packet, doneCallback) {+ exports.encodePacket(packet, true, true, function(encoded) {+ var binaryIdentifier = new Uint8Array(1);+ binaryIdentifier[0] = 1;+ if (typeof encoded === 'string') {+ var view = new Uint8Array(encoded.length);+ for (var i = 0; i < encoded.length; i++) {+ view[i] = encoded.charCodeAt(i);+ }+ encoded = view.buffer;+ binaryIdentifier[0] = 0;+ }++ var len = (encoded instanceof ArrayBuffer)+ ? encoded.byteLength+ : encoded.size;++ var lenStr = len.toString();+ var lengthAry = new Uint8Array(lenStr.length + 1);+ for (var i = 0; i < lenStr.length; i++) {+ lengthAry[i] = parseInt(lenStr[i]);+ }+ lengthAry[lenStr.length] = 255;++ if (Blob) {+ var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);+ doneCallback(null, blob);+ }+ });+ }++ map(packets, encodeOne, function(err, results) {+ return callback(new Blob(results));+ });+};++/*+ * Decodes data when a payload is maybe expected. Strings are decoded by+ * interpreting each byte as a key code for entries marked to start with 0. See+ * description of encodePayloadAsBinary+ *+ * @param {ArrayBuffer} data, callback method+ * @api public+ */++exports.decodePayloadAsBinary = function (data, binaryType, callback) {+ if (typeof binaryType === 'function') {+ callback = binaryType;+ binaryType = null;+ }++ var bufferTail = data;+ var buffers = [];++ var numberTooLong = false;+ while (bufferTail.byteLength > 0) {+ var tailArray = new Uint8Array(bufferTail);+ var isString = tailArray[0] === 0;+ var msgLength = '';++ for (var i = 1; ; i++) {+ if (tailArray[i] == 255) break;++ if (msgLength.length > 310) {+ numberTooLong = true;+ break;+ }++ msgLength += tailArray[i];+ }++ if(numberTooLong) return callback(err, 0, 1);++ bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);+ msgLength = parseInt(msgLength);++ var msg = sliceBuffer(bufferTail, 0, msgLength);+ if (isString) {+ try {+ msg = String.fromCharCode.apply(null, new Uint8Array(msg));+ } catch (e) {+ // iPhone Safari doesn't let you apply to typed arrays+ var typed = new Uint8Array(msg);+ msg = '';+ for (var i = 0; i < typed.length; i++) {+ msg += String.fromCharCode(typed[i]);+ }+ }+ }++ buffers.push(msg);+ bufferTail = sliceBuffer(bufferTail, msgLength);+ }++ var total = buffers.length;+ buffers.forEach(function(buffer, i) {+ callback(exports.decodePacket(buffer, binaryType, true), i, total);+ });+};++}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})+},{"./keys":126,"after":127,"arraybuffer.slice":128,"base64-arraybuffer":129,"blob":130,"has-binary":131,"utf8":133}],126:[function(require,module,exports){++/**+ * Gets the keys for an object.+ *+ * @return {Array} keys+ * @api private+ */++module.exports = Object.keys || function keys (obj){+ var arr = [];+ var has = Object.prototype.hasOwnProperty;++ for (var i in obj) {+ if (has.call(obj, i)) {+ arr.push(i);+ }+ }+ return arr;+};++},{}],127:[function(require,module,exports){+module.exports = after++function after(count, callback, err_cb) {+ var bail = false+ err_cb = err_cb || noop+ proxy.count = count++ return (count === 0) ? callback() : proxy++ function proxy(err, result) {+ if (proxy.count <= 0) {+ throw new Error('after called too many times')+ }+ --proxy.count++ // after first error, rest are passed to err_cb+ if (err) {+ bail = true+ callback(err)+ // future error callbacks will go to error handler+ callback = err_cb+ } else if (proxy.count === 0 && !bail) {+ callback(null, result)+ }+ }+}++function noop() {}++},{}],128:[function(require,module,exports){+/**+ * An abstraction for slicing an arraybuffer even when+ * ArrayBuffer.prototype.slice is not supported+ *+ * @api public+ */++module.exports = function(arraybuffer, start, end) {+ var bytes = arraybuffer.byteLength;+ start = start || 0;+ end = end || bytes;++ if (arraybuffer.slice) { return arraybuffer.slice(start, end); }++ if (start < 0) { start += bytes; }+ if (end < 0) { end += bytes; }+ if (end > bytes) { end = bytes; }++ if (start >= bytes || start >= end || bytes === 0) {+ return new ArrayBuffer(0);+ }++ var abv = new Uint8Array(arraybuffer);+ var result = new Uint8Array(end - start);+ for (var i = start, ii = 0; i < end; i++, ii++) {+ result[ii] = abv[i];+ }+ return result.buffer;+};++},{}],129:[function(require,module,exports){+/*+ * base64-arraybuffer+ * https://github.com/niklasvh/base64-arraybuffer+ *+ * Copyright (c) 2012 Niklas von Hertzen+ * Licensed under the MIT license.+ */+(function(chars){+ "use strict";++ exports.encode = function(arraybuffer) {+ var bytes = new Uint8Array(arraybuffer),+ i, len = bytes.length, base64 = "";++ for (i = 0; i < len; i+=3) {+ base64 += chars[bytes[i] >> 2];+ base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];+ base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];+ base64 += chars[bytes[i + 2] & 63];+ }++ if ((len % 3) === 2) {+ base64 = base64.substring(0, base64.length - 1) + "=";+ } else if (len % 3 === 1) {+ base64 = base64.substring(0, base64.length - 2) + "==";+ }++ return base64;+ };++ exports.decode = function(base64) {+ var bufferLength = base64.length * 0.75,+ len = base64.length, i, p = 0,+ encoded1, encoded2, encoded3, encoded4;++ if (base64[base64.length - 1] === "=") {+ bufferLength--;+ if (base64[base64.length - 2] === "=") {+ bufferLength--;+ }+ }++ var arraybuffer = new ArrayBuffer(bufferLength),+ bytes = new Uint8Array(arraybuffer);++ for (i = 0; i < len; i+=4) {+ encoded1 = chars.indexOf(base64[i]);+ encoded2 = chars.indexOf(base64[i+1]);+ encoded3 = chars.indexOf(base64[i+2]);+ encoded4 = chars.indexOf(base64[i+3]);++ bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);+ bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);+ bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);+ }++ return arraybuffer;+ };+})("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");++},{}],130:[function(require,module,exports){+(function (global){+/**+ * Create a blob builder even when vendor prefixes exist+ */++var BlobBuilder = global.BlobBuilder+ || global.WebKitBlobBuilder+ || global.MSBlobBuilder+ || global.MozBlobBuilder;++/**+ * Check if Blob constructor is supported+ */++var blobSupported = (function() {+ try {+ var b = new Blob(['hi']);+ return b.size == 2;+ } catch(e) {+ return false;+ }+})();++/**+ * Check if BlobBuilder is supported+ */++var blobBuilderSupported = BlobBuilder+ && BlobBuilder.prototype.append+ && BlobBuilder.prototype.getBlob;++function BlobBuilderConstructor(ary, options) {+ options = options || {};++ var bb = new BlobBuilder();+ for (var i = 0; i < ary.length; i++) {+ bb.append(ary[i]);+ }+ return (options.type) ? bb.getBlob(options.type) : bb.getBlob();+};++module.exports = (function() {+ if (blobSupported) {+ return global.Blob;+ } else if (blobBuilderSupported) {+ return BlobBuilderConstructor;+ } else {+ return undefined;+ }+})();++}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})+},{}],131:[function(require,module,exports){+(function (global){++/*+ * Module requirements.+ */++var isArray = require('isarray');++/**+ * Module exports.+ */++module.exports = hasBinary;++/**+ * Checks for binary data.+ *+ * Right now only Buffer and ArrayBuffer are supported..+ *+ * @param {Object} anything+ * @api public+ */++function hasBinary(data) {++ function _hasBinary(obj) {+ if (!obj) return false;++ if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||+ (global.ArrayBuffer && obj instanceof ArrayBuffer) ||+ (global.Blob && obj instanceof Blob) ||+ (global.File && obj instanceof File)+ ) {+ return true;+ }++ if (isArray(obj)) {+ for (var i = 0; i < obj.length; i++) {+ if (_hasBinary(obj[i])) {+ return true;+ }}- },- {- //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32- push: 'crypto',- reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,- names: ['id', 'suite', 'config', 'sessionConfig'],- format: function (o) {- return (o.sessionConfig != null) ?- "crypto:%d %s %s %s":- "crypto:%d %s %s";+ } else if (obj && 'object' == typeof obj) {+ if (obj.toJSON) {+ obj = obj.toJSON();}- },- { //a=setup:actpass- name: 'setup',- reg: /^setup:(\w*)/,- format: "setup:%s"- },- { //a=mid:1- name: 'mid',- reg: /^mid:([^\s]*)/,- format: "mid:%s"- },- { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a- name: 'msid',- reg: /^msid:(.*)/,- format: "msid:%s"- },- { //a=ptime:20- name: 'ptime',- reg: /^ptime:(\d*)/,- format: "ptime:%d"- },- { //a=maxptime:60- name: 'maxptime',- reg: /^maxptime:(\d*)/,- format: "maxptime:%d"- },- { //a=sendrecv- name: 'direction',- reg: /^(sendrecv|recvonly|sendonly|inactive)/- },- { //a=ice-lite- name: 'icelite',- reg: /^(ice-lite)/- },- { //a=ice-ufrag:F7gI- name: 'iceUfrag',- reg: /^ice-ufrag:(\S*)/,- format: "ice-ufrag:%s"- },- { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g- name: 'icePwd',- reg: /^ice-pwd:(\S*)/,- format: "ice-pwd:%s"- },- { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33- name: 'fingerprint',- reg: /^fingerprint:(\S*) (\S*)/,- names: ['type', 'hash'],- format: "fingerprint:%s %s"- },- {- //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host- //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0- //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0- push:'candidates',- reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,- names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],- format: function (o) {- var str = "candidate:%s %d %s %d %s %d typ %s";- // NB: candidate has two optional chunks, so %void middle one if it's missing- str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";- if (o.generation != null) {- str += " generation %d";++ for (var key in obj) {+ if (obj.hasOwnProperty(key) && _hasBinary(obj[key])) {+ return true;}- return str;}- },- { //a=end-of-candidates (keep after the candidates line for readability)- name: 'endOfCandidates',- reg: /^(end-of-candidates)/- },- { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...- name: 'remoteCandidates',- reg: /^remote-candidates:(.*)/,- format: "remote-candidates:%s"- },- { //a=ice-options:google-ice- name: 'iceOptions',- reg: /^ice-options:(\S*)/,- format: "ice-options:%s"- },- { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1- push: "ssrcs",- reg: /^ssrc:(\d*) ([\w_]*):(.*)/,- names: ['id', 'attribute', 'value'],- format: "ssrc:%d %s:%s"- },- { //a=ssrc-group:FEC 1 2- push: "ssrcGroups",- reg: /^ssrc-group:(\w*) (.*)/,- names: ['semantics', 'ssrcs'],- format: "ssrc-group:%s %s"- },- { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV- name: "msidSemantic",- reg: /^msid-semantic:\s?(\w*) (\S*)/,- names: ['semantic', 'token'],- format: "msid-semantic: %s %s" // space after ":" is not accidental- },- { //a=group:BUNDLE audio video- push: 'groups',- reg: /^group:(\w*) (.*)/,- names: ['type', 'mids'],- format: "group:%s %s"- },- { //a=rtcp-mux- name: 'rtcpMux',- reg: /^(rtcp-mux)/- },- { //a=rtcp-rsize- name: 'rtcpRsize',- reg: /^(rtcp-rsize)/- },- { // any a= that we don't understand is kepts verbatim on media.invalid- push: 'invalid',- names: ["value"]}- ]++ return false;+ }++ return _hasBinary(data);+}++}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})+},{"isarray":132}],132:[function(require,module,exports){+module.exports = Array.isArray || function (arr) {+ return Object.prototype.toString.call(arr) == '[object Array]';+};++},{}],133:[function(require,module,exports){+(function (global){+/*! http://mths.be/utf8js v2.0.0 by @mathias */+;(function(root) {++ // Detect free variables `exports`+ var freeExports = typeof exports == 'object' && exports;++ // Detect free variable `module`+ var freeModule = typeof module == 'object' && module &&+ module.exports == freeExports && module;++ // Detect free variable `global`, from Node.js or Browserified code,+ // and use it as `root`+ var freeGlobal = typeof global == 'object' && global;+ if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {+ root = freeGlobal;+ }++ /*--------------------------------------------------------------------------*/++ var stringFromCharCode = String.fromCharCode;++ // Taken from http://mths.be/punycode+ function ucs2decode(string) {+ var output = [];+ var counter = 0;+ var length = string.length;+ var value;+ var extra;+ while (counter < length) {+ value = string.charCodeAt(counter++);+ if (value >= 0xD800 && value <= 0xDBFF && counter < length) {+ // high surrogate, and there is a next character+ extra = string.charCodeAt(counter++);+ if ((extra & 0xFC00) == 0xDC00) { // low surrogate+ output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);+ } else {+ // unmatched surrogate; only append this code unit, in case the next+ // code unit is the high surrogate of a surrogate pair+ output.push(value);+ counter--;+ }+ } else {+ output.push(value);+ }+ }+ return output;+ }++ // Taken from http://mths.be/punycode+ function ucs2encode(array) {+ var length = array.length;+ var index = -1;+ var value;+ var output = '';+ while (++index < length) {+ value = array[index];+ if (value > 0xFFFF) {+ value -= 0x10000;+ output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);+ value = 0xDC00 | value & 0x3FF;+ }+ output += stringFromCharCode(value);+ }+ return output;+ }++ /*--------------------------------------------------------------------------*/++ function createByte(codePoint, shift) {+ return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);+ }++ function encodeCodePoint(codePoint) {+ if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence+ return stringFromCharCode(codePoint);+ }+ var symbol = '';+ if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence+ symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);+ }+ else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence+ symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);+ symbol += createByte(codePoint, 6);+ }+ else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence+ symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);+ symbol += createByte(codePoint, 12);+ symbol += createByte(codePoint, 6);+ }+ symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);+ return symbol;+ }++ function utf8encode(string) {+ var codePoints = ucs2decode(string);++ // console.log(JSON.stringify(codePoints.map(function(x) {+ // return 'U+' + x.toString(16).toUpperCase();+ // })));++ var length = codePoints.length;+ var index = -1;+ var codePoint;+ var byteString = '';+ while (++index < length) {+ codePoint = codePoints[index];+ byteString += encodeCodePoint(codePoint);+ }+ return byteString;+ }++ /*--------------------------------------------------------------------------*/++ function readContinuationByte() {+ if (byteIndex >= byteCount) {+ throw Error('Invalid byte index');+ }++ var continuationByte = byteArray[byteIndex] & 0xFF;+ byteIndex++;++ if ((continuationByte & 0xC0) == 0x80) {+ return continuationByte & 0x3F;+ }++ // If we end up here, it’s not a continuation byte+ throw Error('Invalid continuation byte');+ }++ function decodeSymbol() {+ var byte1;+ var byte2;+ var byte3;+ var byte4;+ var codePoint;++ if (byteIndex > byteCount) {+ throw Error('Invalid byte index');+ }++ if (byteIndex == byteCount) {+ return false;+ }++ // Read first byte+ byte1 = byteArray[byteIndex] & 0xFF;+ byteIndex++;++ // 1-byte sequence (no continuation bytes)+ if ((byte1 & 0x80) == 0) {+ return byte1;+ }++ // 2-byte sequence+ if ((byte1 & 0xE0) == 0xC0) {+ var byte2 = readContinuationByte();+ codePoint = ((byte1 & 0x1F) << 6) | byte2;+ if (codePoint >= 0x80) {+ return codePoint;+ } else {+ throw Error('Invalid continuation byte');+ }+ }++ // 3-byte sequence (may include unpaired surrogates)+ if ((byte1 & 0xF0) == 0xE0) {+ byte2 = readContinuationByte();+ byte3 = readContinuationByte();+ codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;+ if (codePoint >= 0x0800) {+ return codePoint;+ } else {+ throw Error('Invalid continuation byte');+ }+ }++ // 4-byte sequence+ if ((byte1 & 0xF8) == 0xF0) {+ byte2 = readContinuationByte();+ byte3 = readContinuationByte();+ byte4 = readContinuationByte();+ codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) |+ (byte3 << 0x06) | byte4;+ if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {+ return codePoint;+ }+ }++ throw Error('Invalid UTF-8 detected');+ }++ var byteArray;+ var byteCount;+ var byteIndex;+ function utf8decode(byteString) {+ byteArray = ucs2decode(byteString);+ byteCount = byteArray.length;+ byteIndex = 0;+ var codePoints = [];+ var tmp;+ while ((tmp = decodeSymbol()) !== false) {+ codePoints.push(tmp);+ }+ return ucs2encode(codePoints);+ }++ /*--------------------------------------------------------------------------*/++ var utf8 = {+ 'version': '2.0.0',+ 'encode': utf8encode,+ 'decode': utf8decode+ };++ // Some AMD build optimizers, like r.js, check for specific condition patterns+ // like the following:+ if (+ typeof define == 'function' &&+ typeof define.amd == 'object' &&+ define.amd+ ) {+ define(function() {+ return utf8;+ });+ } else if (freeExports && !freeExports.nodeType) {+ if (freeModule) { // in Node.js or RingoJS v0.8.0++ freeModule.exports = utf8;+ } else { // in Narwhal or RingoJS v0.7.0-+ var object = {};+ var hasOwnProperty = object.hasOwnProperty;+ for (var key in utf8) {+ hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]);+ }+ }+ } else { // in Rhino or a web browser+ root.utf8 = utf8;+ }++}(this));++}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})+},{}],134:[function(require,module,exports){++/**+ * Module dependencies.+ */++var global = require('global');++/**+ * Module exports.+ *+ * Logic borrowed from Modernizr:+ *+ * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js+ */++try {+ module.exports = 'XMLHttpRequest' in global &&+ 'withCredentials' in new global.XMLHttpRequest();+} catch (err) {+ // if XMLHttp support is disabled in IE then it will throw+ // when trying to create+ module.exports = false;+}++},{"global":135}],135:[function(require,module,exports){++/**+ * Returns `this`. Execute this without a "context" (i.e. without it being+ * attached to an object of the left-hand side), and `this` points to the+ * "global" scope of the current JS execution.+ */++module.exports = (function () { return this; })();++},{}],136:[function(require,module,exports){+(function (global){+/**+ * JSON parse.+ *+ * @see Based on jQuery#parseJSON (MIT) and JSON2+ * @api private+ */++var rvalidchars = /^[\],:{}\s]*$/;+var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;+var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;+var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;+var rtrimLeft = /^\s+/;+var rtrimRight = /\s+$/;++module.exports = function parsejson(data) {+ if ('string' != typeof data || !data) {+ return null;+ }++ data = data.replace(rtrimLeft, '').replace(rtrimRight, '');++ // Attempt to parse using the native JSON parser first+ if (global.JSON && JSON.parse) {+ return JSON.parse(data);+ }++ if (rvalidchars.test(data.replace(rvalidescape, '@')+ .replace(rvalidtokens, ']')+ .replace(rvalidbraces, ''))) {+ return (new Function('return ' + data))();+ }+};+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})+},{}],137:[function(require,module,exports){+/**+ * Compiles a querystring+ * Returns string representation of the object+ *+ * @param {Object}+ * @api private+ */++exports.encode = function (obj) {+ var str = '';++ for (var i in obj) {+ if (obj.hasOwnProperty(i)) {+ if (str.length) str += '&';+ str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);+ }+ }++ return str;+};++/**+ * Parses a simple querystring into an object+ *+ * @param {String} qs+ * @api private+ */++exports.decode = function(qs){+ var qry = {};+ var pairs = qs.split('&');+ for (var i = 0, l = pairs.length; i < l; i++) {+ var pair = pairs[i].split('=');+ qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);+ }+ return qry;+};++},{}],138:[function(require,module,exports){+/**+ * Parses an URI+ *+ * @author Steven Levithan <stevenlevithan.com> (MIT license)+ * @api private+ */++var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;++var parts = [+ 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'+];++module.exports = function parseuri(str) {+ var src = str,+ b = str.indexOf('['),+ e = str.indexOf(']');++ if (b != -1 && e != -1) {+ str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);+ }++ var m = re.exec(str || ''),+ uri = {},+ i = 14;++ while (i--) {+ uri[parts[i]] = m[i] || '';+ }++ if (b != -1 && e != -1) {+ uri.source = src;+ uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');+ uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');+ uri.ipv6uri = true;+ }++ return uri;};-// set sensible defaults to avoid polluting the grammar with boring details-Object.keys(grammar).forEach(function (key) {- var objs = grammar[key];- objs.forEach(function (obj) {- if (!obj.reg) {- obj.reg = /(.*)/;+},{}],139:[function(require,module,exports){++/**+ * Module dependencies.+ */++var global = (function() { return this; })();++/**+ * WebSocket constructor.+ */++var WebSocket = global.WebSocket || global.MozWebSocket;++/**+ * Module exports.+ */++module.exports = WebSocket ? ws : null;++/**+ * WebSocket constructor.+ *+ * The third `opts` options object gets ignored in web browsers, since it's+ * non-standard, and throws a TypeError if passed to the constructor.+ * See: https://github.com/einaros/ws/issues/227+ *+ * @param {String} uri+ * @param {Array} protocols (optional)+ * @param {Object) opts (optional)+ * @api public+ */++function ws(uri, protocols, opts) {+ var instance;+ if (protocols) {+ instance = new WebSocket(uri, protocols);+ } else {+ instance = new WebSocket(uri);+ }+ return instance;+}++if (WebSocket) ws.prototype = WebSocket.prototype;++},{}],140:[function(require,module,exports){+(function (global){++/*+ * Module requirements.+ */++var isArray = require('isarray');++/**+ * Module exports.+ */++module.exports = hasBinary;++/**+ * Checks for binary data.+ *+ * Right now only Buffer and ArrayBuffer are supported..+ *+ * @param {Object} anything+ * @api public+ */++function hasBinary(data) {++ function _hasBinary(obj) {+ if (!obj) return false;++ if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||+ (global.ArrayBuffer && obj instanceof ArrayBuffer) ||+ (global.Blob && obj instanceof Blob) ||+ (global.File && obj instanceof File)+ ) {+ return true;}- if (!obj.format) {- obj.format = "%s";++ if (isArray(obj)) {+ for (var i = 0; i < obj.length; i++) {+ if (_hasBinary(obj[i])) {+ return true;+ }+ }+ } else if (obj && 'object' == typeof obj) {+ if (obj.toJSON) {+ obj = obj.toJSON();+ }++ for (var key in obj) {+ if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {+ return true;+ }+ }}- });-});-},{}],97:[function(require,module,exports){-var parser = require('./parser');-var writer = require('./writer');+ return false;+ }-exports.write = writer;-exports.parse = parser.parse;-exports.parseFmtpConfig = parser.parseFmtpConfig;-exports.parsePayloads = parser.parsePayloads;-exports.parseRemoteCandidates = parser.parseRemoteCandidates;+ return _hasBinary(data);+}-},{"./parser":98,"./writer":99}],98:[function(require,module,exports){-var toIntIfInt = function (v) {- return String(Number(v)) === v ? Number(v) : v;-};+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})+},{"isarray":141}],141:[function(require,module,exports){+arguments[4][132][0].apply(exports,arguments)+},{"dup":132}],142:[function(require,module,exports){-var attachProperties = function (match, location, names, rawName) {- if (rawName && !names) {- location[rawName] = toIntIfInt(match[1]);+var indexOf = [].indexOf;++module.exports = function(arr, obj){+ if (indexOf) return arr.indexOf(obj);+ for (var i = 0; i < arr.length; ++i) {+ if (arr[i] === obj) return i;}- else {- for (var i = 0; i < names.length; i += 1) {- if (match[i+1] != null) {- location[names[i]] = toIntIfInt(match[i+1]);- }+ return -1;+};+},{}],143:[function(require,module,exports){++/**+ * HOP ref.+ */++var has = Object.prototype.hasOwnProperty;++/**+ * Return own keys in `obj`.+ *+ * @param {Object} obj+ * @return {Array}+ * @api public+ */++exports.keys = Object.keys || function(obj){+ var keys = [];+ for (var key in obj) {+ if (has.call(obj, key)) {+ keys.push(key);}}+ return keys;};-var parseReg = function (obj, location, content) {- var needsBlank = obj.name && obj.names;- if (obj.push && !location[obj.push]) {- location[obj.push] = [];+/**+ * Return own values in `obj`.+ *+ * @param {Object} obj+ * @return {Array}+ * @api public+ */++exports.values = function(obj){+ var vals = [];+ for (var key in obj) {+ if (has.call(obj, key)) {+ vals.push(obj[key]);+ }}- else if (needsBlank && !location[obj.name]) {- location[obj.name] = {};+ return vals;+};++/**+ * Merge `b` into `a`.+ *+ * @param {Object} a+ * @param {Object} b+ * @return {Object} a+ * @api public+ */++exports.merge = function(a, b){+ for (var key in b) {+ if (has.call(b, key)) {+ a[key] = b[key];+ }}- var keyLocation = obj.push ?- {} : // blank object that will be pushed- needsBlank ? location[obj.name] : location; // otherwise, named location or root+ return a;+};- attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);+/**+ * Return length of `obj`.+ *+ * @param {Object} obj+ * @return {Number}+ * @api public+ */- if (obj.push) {- location[obj.push].push(keyLocation);+exports.length = function(obj){+ return exports.keys(obj).length;+};++/**+ * Check if `obj` is empty.+ *+ * @param {Object} obj+ * @return {Boolean}+ * @api public+ */++exports.isEmpty = function(obj){+ return 0 == exports.length(obj);+};+},{}],144:[function(require,module,exports){+/**+ * Parses an URI+ *+ * @author Steven Levithan <stevenlevithan.com> (MIT license)+ * @api private+ */++var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;++var parts = [+ 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host'+ , 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'+];++module.exports = function parseuri(str) {+ var m = re.exec(str || '')+ , uri = {}+ , i = 14;++ while (i--) {+ uri[parts[i]] = m[i] || '';}++ return uri;};-var grammar = require('./grammar');-var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);+},{}],145:[function(require,module,exports){+(function (global){+/*global Blob,File*/-exports.parse = function (sdp) {- var session = {}- , media = []- , location = session; // points at where properties go under (one of the above)+/**+ * Module requirements+ */- // parse lines we understand- sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {- var type = l[0];- var content = l.slice(2);- if (type === 'm') {- media.push({rtp: [], fmtp: []});- location = media[media.length-1]; // point at latest media line- }+var isArray = require('isarray');+var isBuf = require('./is-buffer');- for (var j = 0; j < (grammar[type] || []).length; j += 1) {- var obj = grammar[type][j];- if (obj.reg.test(content)) {- return parseReg(obj, location, content);+/**+ * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder.+ * Anything with blobs or files should be fed through removeBlobs before coming+ * here.+ *+ * @param {Object} packet - socket.io event packet+ * @return {Object} with deconstructed packet and list of buffers+ * @api public+ */++exports.deconstructPacket = function(packet){+ var buffers = [];+ var packetData = packet.data;++ function _deconstructPacket(data) {+ if (!data) return data;++ if (isBuf(data)) {+ var placeholder = { _placeholder: true, num: buffers.length };+ buffers.push(data);+ return placeholder;+ } else if (isArray(data)) {+ var newData = new Array(data.length);+ for (var i = 0; i < data.length; i++) {+ newData[i] = _deconstructPacket(data[i]);+ }+ return newData;+ } else if ('object' == typeof data && !(data instanceof Date)) {+ var newData = {};+ for (var key in data) {+ newData[key] = _deconstructPacket(data[key]);}+ return newData;}- });+ return data;+ }- session.media = media; // link it up- return session;+ var pack = packet;+ pack.data = _deconstructPacket(packetData);+ pack.attachments = buffers.length; // number of binary 'attachments'+ return {packet: pack, buffers: buffers};};-var fmtpReducer = function (acc, expr) {- var s = expr.split('=');- if (s.length === 2) {- acc[s[0]] = toIntIfInt(s[1]);+/**+ * Reconstructs a binary packet from its placeholder packet and buffers+ *+ * @param {Object} packet - event packet with placeholders+ * @param {Array} buffers - binary buffers to put in placeholder positions+ * @return {Object} reconstructed packet+ * @api public+ */++exports.reconstructPacket = function(packet, buffers) {+ var curPlaceHolder = 0;++ function _reconstructPacket(data) {+ if (data && data._placeholder) {+ var buf = buffers[data.num]; // appropriate buffer (should be natural order anyway)+ return buf;+ } else if (isArray(data)) {+ for (var i = 0; i < data.length; i++) {+ data[i] = _reconstructPacket(data[i]);+ }+ return data;+ } else if (data && 'object' == typeof data) {+ for (var key in data) {+ data[key] = _reconstructPacket(data[key]);+ }+ return data;+ }+ return data;}- return acc;-};-exports.parseFmtpConfig = function (str) {- return str.split(';').reduce(fmtpReducer, {});+ packet.data = _reconstructPacket(packet.data);+ packet.attachments = undefined; // no longer useful+ return packet;};-exports.parsePayloads = function (str) {- return str.split(' ').map(Number);-};+/**+ * Asynchronously removes Blobs or Files from data via+ * FileReader's readAsArrayBuffer method. Used before encoding+ * data as msgpack. Calls callback with the blobless data.+ *+ * @param {Object} data+ * @param {Function} callback+ * @api private+ */-exports.parseRemoteCandidates = function (str) {- var candidates = [];- var parts = str.split(' ').map(toIntIfInt);- for (var i = 0; i < parts.length; i += 3) {- candidates.push({- component: parts[i],- ip: parts[i + 1],- port: parts[i + 2]- });- }- return candidates;-};+exports.removeBlobs = function(data, callback) {+ function _removeBlobs(obj, curKey, containingObject) {+ if (!obj) return obj;-},{"./grammar":96}],99:[function(require,module,exports){-var grammar = require('./grammar');+ // convert any blob+ if ((global.Blob && obj instanceof Blob) ||+ (global.File && obj instanceof File)) {+ pendingBlobs++;-// customized util.format - discards excess arguments and can void middle ones-var formatRegExp = /%[sdv%]/g;-var format = function (formatStr) {- var i = 1;- var args = arguments;- var len = args.length;- return formatStr.replace(formatRegExp, function (x) {- if (i >= len) {- return x; // missing argument- }- var arg = args[i];- i += 1;- switch (x) {- case '%%':- return '%';- case '%s':- return String(arg);- case '%d':- return Number(arg);- case '%v':- return '';+ // async filereader+ var fileReader = new FileReader();+ fileReader.onload = function() { // this.result == arraybuffer+ if (containingObject) {+ containingObject[curKey] = this.result;+ }+ else {+ bloblessData = this.result;+ }++ // if nothing pending its callback time+ if(! --pendingBlobs) {+ callback(bloblessData);+ }+ };++ fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer+ } else if (isArray(obj)) { // handle array+ for (var i = 0; i < obj.length; i++) {+ _removeBlobs(obj[i], i, obj);+ }+ } else if (obj && 'object' == typeof obj && !isBuf(obj)) { // and object+ for (var key in obj) {+ _removeBlobs(obj[key], key, obj);+ }}- });- // NB: we discard excess arguments - they are typically undefined from makeLine+ }++ var pendingBlobs = 0;+ var bloblessData = data;+ _removeBlobs(bloblessData);+ if (!pendingBlobs) {+ callback(bloblessData);+ }};-var makeLine = function (type, obj, location) {- var str = obj.format instanceof Function ?- (obj.format(obj.push ? location : location[obj.name])) :- obj.format;+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})+},{"./is-buffer":147,"isarray":148}],146:[function(require,module,exports){++/**+ * Module dependencies.+ */++var debug = require('debug')('socket.io-parser');+var json = require('json3');+var isArray = require('isarray');+var Emitter = require('component-emitter');+var binary = require('./binary');+var isBuf = require('./is-buffer');++/**+ * Protocol version.+ *+ * @api public+ */++exports.protocol = 4;++/**+ * Packet types.+ *+ * @api public+ */++exports.types = [+ 'CONNECT',+ 'DISCONNECT',+ 'EVENT',+ 'BINARY_EVENT',+ 'ACK',+ 'BINARY_ACK',+ 'ERROR'+];++/**+ * Packet type `connect`.+ *+ * @api public+ */++exports.CONNECT = 0;++/**+ * Packet type `disconnect`.+ *+ * @api public+ */++exports.DISCONNECT = 1;++/**+ * Packet type `event`.+ *+ * @api public+ */++exports.EVENT = 2;++/**+ * Packet type `ack`.+ *+ * @api public+ */++exports.ACK = 3;++/**+ * Packet type `error`.+ *+ * @api public+ */++exports.ERROR = 4;++/**+ * Packet type 'binary event'+ *+ * @api public+ */++exports.BINARY_EVENT = 5;++/**+ * Packet type `binary ack`. For acks with binary arguments.+ *+ * @api public+ */++exports.BINARY_ACK = 6;++/**+ * Encoder constructor.+ *+ * @api public+ */++exports.Encoder = Encoder;++/**+ * Decoder constructor.+ *+ * @api public+ */++exports.Decoder = Decoder;- var args = [type + '=' + str];- if (obj.names) {- for (var i = 0; i < obj.names.length; i += 1) {- var n = obj.names[i];- if (obj.name) {- args.push(location[obj.name][n]);- }- else { // for mLine and push attributes- args.push(location[obj.names[i]]);- }- }+/**+ * A socket.io Encoder instance+ *+ * @api public+ */++function Encoder() {}++/**+ * Encode a packet as a single string if non-binary, or as a+ * buffer sequence, depending on packet type.+ *+ * @param {Object} obj - packet object+ * @param {Function} callback - function to handle encodings (likely engine.write)+ * @return Calls callback with Array of encodings+ * @api public+ */++Encoder.prototype.encode = function(obj, callback){+ debug('encoding packet %j', obj);++ if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {+ encodeAsBinary(obj, callback);}else {- args.push(location[obj.name]);+ var encoding = encodeAsString(obj);+ callback([encoding]);}- return format.apply(null, args);};-// RFC specified order-// TODO: extend this with all the rest-var defaultOuterOrder = [- 'v', 'o', 's', 'i',- 'u', 'e', 'p', 'c',- 'b', 't', 'r', 'z', 'a'-];-var defaultInnerOrder = ['i', 'c', 'b', 'a'];+/**+ * Encode packet as string.+ *+ * @param {Object} packet+ * @return {String} encoded+ * @api private+ */+function encodeAsString(obj) {+ var str = '';+ var nsp = false;-module.exports = function (session, opts) {- opts = opts || {};- // ensure certain properties exist- if (session.version == null) {- session.version = 0; // "v=0" must be there (only defined version atm)+ // first is type+ str += obj.type;++ // attachments if we have them+ if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {+ str += obj.attachments;+ str += '-';}- if (session.name == null) {- session.name = " "; // "s= " must be there if no meaningful name set++ // if we have a namespace other than `/`+ // we append it followed by a comma `,`+ if (obj.nsp && '/' != obj.nsp) {+ nsp = true;+ str += obj.nsp;}- session.media.forEach(function (mLine) {- if (mLine.payloads == null) {- mLine.payloads = "";++ // immediately followed by the id+ if (null != obj.id) {+ if (nsp) {+ str += ',';+ nsp = false;}- });+ str += obj.id;+ }- var outerOrder = opts.outerOrder || defaultOuterOrder;- var innerOrder = opts.innerOrder || defaultInnerOrder;- var sdp = [];+ // json data+ if (null != obj.data) {+ if (nsp) str += ',';+ str += json.stringify(obj.data);+ }- // loop through outerOrder for matching properties on session- outerOrder.forEach(function (type) {- grammar[type].forEach(function (obj) {- if (obj.name in session && session[obj.name] != null) {- sdp.push(makeLine(type, obj, session));- }- else if (obj.push in session && session[obj.push] != null) {- session[obj.push].forEach(function (el) {- sdp.push(makeLine(type, obj, el));- });- }- });- });+ debug('encoded %j as %s', obj, str);+ return str;+}- // then for each media line, follow the innerOrder- session.media.forEach(function (mLine) {- sdp.push(makeLine('m', grammar.m[0], mLine));+/**+ * Encode packet as 'buffer sequence' by removing blobs, and+ * deconstructing packet into object with placeholders and+ * a list of buffers.+ *+ * @param {Object} packet+ * @return {Buffer} encoded+ * @api private+ */- innerOrder.forEach(function (type) {- grammar[type].forEach(function (obj) {- if (obj.name in mLine && mLine[obj.name] != null) {- sdp.push(makeLine(type, obj, mLine));- }- else if (obj.push in mLine && mLine[obj.push] != null) {- mLine[obj.push].forEach(function (el) {- sdp.push(makeLine(type, obj, el));- });- }- });- });- });+function encodeAsBinary(obj, callback) {- return sdp.join('\r\n') + '\r\n';-};+ function writeEncoding(bloblessData) {+ var deconstruction = binary.deconstructPacket(bloblessData);+ var pack = encodeAsString(deconstruction.packet);+ var buffers = deconstruction.buffers;-},{"./grammar":96}],100:[function(require,module,exports){-var transform = require('sdp-transform');-var transformUtils = require('./transform-utils');-var parseSsrcs = transformUtils.parseSsrcs;-var writeSsrcs = transformUtils.writeSsrcs;+ buffers.unshift(pack); // add packet info to beginning of data list+ callback(buffers); // write all the buffers+ }-//region Constants+ binary.removeBlobs(obj, writeEncoding);+}-var DEFAULT_NUM_OF_LAYERS = 3;+/**+ * A socket.io Decoder instance+ *+ * @return {Object} decoder+ * @api public+ */-//endregion+function Decoder() {+ this.reconstructor = null;+}-//region Ctor+/**+ * Mix in `Emitter` with Decoder.+ */-function Simulcast(options) {+Emitter(Decoder.prototype);- this.options = options ? options : {};+/**+ * Decodes an ecoded packet string into packet JSON.+ *+ * @param {String} obj - encoded packet+ * @return {Object} packet+ * @api public+ */- if (!this.options.numOfLayers) {- this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;+Decoder.prototype.add = function(obj) {+ var packet;+ if ('string' == typeof obj) {+ packet = decodeString(obj);+ if (exports.BINARY_EVENT == packet.type || exports.BINARY_ACK == packet.type) { // binary packet's json+ this.reconstructor = new BinaryReconstructor(packet);++ // no attachments, labeled binary but no binary data to follow+ if (this.reconstructor.reconPack.attachments === 0) {+ this.emit('decoded', packet);+ }+ } else { // non-binary full packet+ this.emit('decoded', packet);+ }+ }+ else if (isBuf(obj) || obj.base64) { // raw binary data+ if (!this.reconstructor) {+ throw new Error('got binary data when not reconstructing a packet');+ } else {+ packet = this.reconstructor.takeBinaryData(obj);+ if (packet) { // received final buffer+ this.reconstructor = null;+ this.emit('decoded', packet);+ }}+ }+ else {+ throw new Error('Unknown type: ' + obj);+ }+};- this.layers = [];-}+/**+ * Decode a packet String (JSON data)+ *+ * @param {String} str+ * @return {Object} packet+ * @api private+ */-//endregion+function decodeString(str) {+ var p = {};+ var i = 0;-//region Stateless private utility functions+ // look up type+ p.type = Number(str.charAt(0));+ if (null == exports.types[p.type]) return error();-/**- * Returns a random integer between min (included) and max (excluded)- * Using Math.round() gives a non-uniform distribution!- * @returns {number}- */-function generateSSRC() {- var min = 0, max = 0xffffffff;- return Math.floor(Math.random() * (max - min)) + min;-};+ // look up attachments if type binary+ if (exports.BINARY_EVENT == p.type || exports.BINARY_ACK == p.type) {+ var buf = '';+ while (str.charAt(++i) != '-') {+ buf += str.charAt(i);+ if (i == str.length) break;+ }+ if (buf != Number(buf) || str.charAt(i) != '-') {+ throw new Error('Illegal attachments');+ }+ p.attachments = Number(buf);+ }-function processVideo(session, action) {- if (session == null || !Array.isArray(session.media)) {- return;+ // look up namespace (if any)+ if ('/' == str.charAt(i + 1)) {+ p.nsp = '';+ while (++i) {+ var c = str.charAt(i);+ if (',' == c) break;+ p.nsp += c;+ if (i == str.length) break;}+ } else {+ p.nsp = '/';+ }- session.media.forEach(function (mLine) {- if (mLine.type === 'video') {- action(mLine);- }- });-}+ // look up id+ var next = str.charAt(i + 1);+ if ('' !== next && Number(next) == next) {+ p.id = '';+ while (++i) {+ var c = str.charAt(i);+ if (null == c || Number(c) != c) {+ --i;+ break;+ }+ p.id += str.charAt(i);+ if (i == str.length) break;+ }+ p.id = Number(p.id);+ }-function validateDescription(desc)-{- return desc && desc != null- && desc.type && desc.type != ''- && desc.sdp && desc.sdp != '';-}+ // look up json data+ if (str.charAt(++i)) {+ try {+ p.data = json.parse(str.substr(i));+ } catch(e){+ return error();+ }+ }-function explodeRemoteSimulcast(mLine) {+ debug('decoded %s as %j', str, p);+ return p;+}- if (!mLine || !Array.isArray(mLine.ssrcGroups)) {- return;- }+/**+ * Deallocates a parser's resources+ *+ * @api public+ */- var sources = parseSsrcs(mLine);- var order = [];+Decoder.prototype.destroy = function() {+ if (this.reconstructor) {+ this.reconstructor.finishedReconstruction();+ }+};- // Find the SIM group and explode its sources.- var j = mLine.ssrcGroups.length;- while (j--) {+/**+ * A manager of a binary event's 'buffer sequence'. Should+ * be constructed whenever a packet of type BINARY_EVENT is+ * decoded.+ *+ * @param {Object} packet+ * @return {BinaryReconstructor} initialized reconstructor+ * @api private+ */- if (mLine.ssrcGroups[j].semantics !== 'SIM') {- continue;- }+function BinaryReconstructor(packet) {+ this.reconPack = packet;+ this.buffers = [];+}- var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');+/**+ * Method to be called when binary data received from connection+ * after a BINARY_EVENT packet.+ *+ * @param {Buffer | ArrayBuffer} binData - the raw binary data received+ * @return {null | Object} returns null if more binary data is expected or+ * a reconstructed packet object if all buffers have been received.+ * @api private+ */- for (var i = 0; i < simulcastSsrcs.length; i++) {+BinaryReconstructor.prototype.takeBinaryData = function(binData) {+ this.buffers.push(binData);+ if (this.buffers.length == this.reconPack.attachments) { // done with buffer list+ var packet = binary.reconstructPacket(this.reconPack, this.buffers);+ this.finishedReconstruction();+ return packet;+ }+ return null;+};- var ssrc = simulcastSsrcs[i];- order.push(ssrc);+/**+ * Cleans up binary packet reconstruction variables.+ *+ * @api private+ */- var parts = sources[ssrc].msid.split(' ');- sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');- sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');+BinaryReconstructor.prototype.finishedReconstruction = function() {+ this.reconPack = null;+ this.buffers = [];+};- // Remove all the groups that this SSRC participates in.- mLine.ssrcGroups.forEach(function (relatedGroup) {- if (relatedGroup.semantics === 'SIM') {- return;- }+function error(data){+ return {+ type: exports.ERROR,+ data: 'parser error'+ };+}- var relatedSsrcs = relatedGroup.ssrcs.split(' ');- if (relatedSsrcs.indexOf(ssrc) === -1) {- return;- }+},{"./binary":145,"./is-buffer":147,"component-emitter":109,"debug":110,"isarray":148,"json3":149}],147:[function(require,module,exports){+(function (global){- // Nuke all the related SSRCs.- relatedSsrcs.forEach(function (relatedSSRC) {- sources[relatedSSRC].msid = sources[ssrc].msid;- sources[relatedSSRC].cname = sources[ssrc].cname;- if (relatedSSRC !== ssrc) {- order.push(relatedSSRC);- }- });+module.exports = isBuf;- // Schedule the related group for nuking.- })- }+/**+ * Returns true if obj is a buffer or an arraybuffer.+ *+ * @api private+ */- mLine.ssrcs = writeSsrcs(sources, order);- mLine.ssrcGroups.splice(j, 1);- };+function isBuf(obj) {+ return (global.Buffer && global.Buffer.isBuffer(obj)) ||+ (global.ArrayBuffer && obj instanceof ArrayBuffer);}-function squeezeRemoteSimulcast(mLine) {+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})+},{}],148:[function(require,module,exports){+arguments[4][132][0].apply(exports,arguments)+},{"dup":132}],149:[function(require,module,exports){+/*! JSON v3.2.6 | http://bestiejs.github.io/json3 | Copyright 2012-2013, Kit Cambridge | http://kit.mit-license.org */+;(function (window) {+ // Convenience aliases.+ var getClass = {}.toString, isProperty, forEach, undef;- if (!mLine || !Array.isArray(mLine.ssrcGroups)) {- return;+ // Detect the `define` function exposed by asynchronous module loaders. The+ // strict `define` check is necessary for compatibility with `r.js`.+ var isLoader = typeof define === "function" && define.amd;++ // Detect native implementations.+ var nativeJSON = typeof JSON == "object" && JSON;++ // Set up the JSON 3 namespace, preferring the CommonJS `exports` object if+ // available.+ var JSON3 = typeof exports == "object" && exports && !exports.nodeType && exports;++ if (JSON3 && nativeJSON) {+ // Explicitly delegate to the native `stringify` and `parse`+ // implementations in CommonJS environments.+ JSON3.stringify = nativeJSON.stringify;+ JSON3.parse = nativeJSON.parse;+ } else {+ // Export for web browsers, JavaScript engines, and asynchronous module+ // loaders, using the global `JSON` object if available.+ JSON3 = window.JSON = nativeJSON || {};+ }++ // Test the `Date#getUTC*` methods. Based on work by @Yaffle.+ var isExtended = new Date(-3509827334573292);+ try {+ // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical+ // results for certain dates in Opera >= 10.53.+ isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&+ // Safari < 2.0.2 stores the internal millisecond time value correctly,+ // but clips the values returned by the date methods to the range of+ // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).+ isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;+ } catch (exception) {}++ // Internal: Determines whether the native `JSON.stringify` and `parse`+ // implementations are spec-compliant. Based on work by Ken Snyder.+ function has(name) {+ if (has[name] !== undef) {+ // Return cached feature test result.+ return has[name];+ }++ var isSupported;+ if (name == "bug-string-char-index") {+ // IE <= 7 doesn't support accessing string characters using square+ // bracket notation. IE 8 only supports this for primitives.+ isSupported = "a"[0] != "a";+ } else if (name == "json") {+ // Indicates whether both `JSON.stringify` and `JSON.parse` are+ // supported.+ isSupported = has("json-stringify") && has("json-parse");+ } else {+ var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';+ // Test `JSON.stringify`.+ if (name == "json-stringify") {+ var stringify = JSON3.stringify, stringifySupported = typeof stringify == "function" && isExtended;+ if (stringifySupported) {+ // A test function object with a custom `toJSON` method.+ (value = function () {+ return 1;+ }).toJSON = value;+ try {+ stringifySupported =+ // Firefox 3.1b1 and b2 serialize string, number, and boolean+ // primitives as object literals.+ stringify(0) === "0" &&+ // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object+ // literals.+ stringify(new Number()) === "0" &&+ stringify(new String()) == '""' &&+ // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or+ // does not define a canonical JSON representation (this applies to+ // objects with `toJSON` properties as well, *unless* they are nested+ // within an object or array).+ stringify(getClass) === undef &&+ // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and+ // FF 3.1b3 pass this test.+ stringify(undef) === undef &&+ // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,+ // respectively, if the value is omitted entirely.+ stringify() === undef &&+ // FF 3.1b1, 2 throw an error if the given value is not a number,+ // string, array, object, Boolean, or `null` literal. This applies to+ // objects with custom `toJSON` methods as well, unless they are nested+ // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`+ // methods entirely.+ stringify(value) === "1" &&+ stringify([value]) == "[1]" &&+ // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of+ // `"[null]"`.+ stringify([undef]) == "[null]" &&+ // YUI 3.0.0b1 fails to serialize `null` literals.+ stringify(null) == "null" &&+ // FF 3.1b1, 2 halts serialization if an array contains a function:+ // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3+ // elides non-JSON values from objects and arrays, unless they+ // define custom `toJSON` methods.+ stringify([undef, getClass, null]) == "[null,null,null]" &&+ // Simple serialization test. FF 3.1b1 uses Unicode escape sequences+ // where character escape codes are expected (e.g., `\b` => `\u0008`).+ stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&+ // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.+ stringify(null, value) === "1" &&+ stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&+ // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly+ // serialize extended years.+ stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&+ // The milliseconds are optional in ES 5, but required in 5.1.+ stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&+ // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative+ // four-digit years instead of six-digit years. Credits: @Yaffle.+ stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&+ // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond+ // values less than 1000. Credits: @Yaffle.+ stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';+ } catch (exception) {+ stringifySupported = false;+ }+ }+ isSupported = stringifySupported;+ }+ // Test `JSON.parse`.+ if (name == "json-parse") {+ var parse = JSON3.parse;+ if (typeof parse == "function") {+ try {+ // FF 3.1b1, b2 will throw an exception if a bare literal is provided.+ // Conforming implementations should also coerce the initial argument to+ // a string prior to parsing.+ if (parse("0") === 0 && !parse(false)) {+ // Simple parsing test.+ value = parse(serialized);+ var parseSupported = value["a"].length == 5 && value["a"][0] === 1;+ if (parseSupported) {+ try {+ // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.+ parseSupported = !parse('"\t"');+ } catch (exception) {}+ if (parseSupported) {+ try {+ // FF 4.0 and 4.0.1 allow leading `+` signs and leading+ // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow+ // certain octal literals.+ parseSupported = parse("01") !== 1;+ } catch (exception) {}+ }+ if (parseSupported) {+ try {+ // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal+ // points. These environments, along with FF 3.1b1 and 2,+ // also allow trailing commas in JSON objects and arrays.+ parseSupported = parse("1.") !== 1;+ } catch (exception) {}+ }+ }+ }+ } catch (exception) {+ parseSupported = false;+ }+ }+ isSupported = parseSupported;+ }}+ return has[name] = !!isSupported;+ }- var sources = parseSsrcs(mLine);+ if (!has("json")) {+ // Common `[[Class]]` name aliases.+ var functionClass = "[object Function]";+ var dateClass = "[object Date]";+ var numberClass = "[object Number]";+ var stringClass = "[object String]";+ var arrayClass = "[object Array]";+ var booleanClass = "[object Boolean]";++ // Detect incomplete support for accessing string characters by index.+ var charIndexBuggy = has("bug-string-char-index");++ // Define additional utility methods if the `Date` methods are buggy.+ if (!isExtended) {+ var floor = Math.floor;+ // A mapping between the months of the year and the number of days between+ // January 1st and the first of the respective month.+ var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];+ // Internal: Calculates the number of days between the Unix epoch and the+ // first day of the given month.+ var getDay = function (year, month) {+ return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);+ };+ }- // Find the SIM group and nuke it.- mLine.ssrcGroups.some(function (simulcastGroup) {- if (simulcastGroup.semantics !== 'SIM') {- return false;+ // Internal: Determines if a property is a direct property of the given+ // object. Delegates to the native `Object#hasOwnProperty` method.+ if (!(isProperty = {}.hasOwnProperty)) {+ isProperty = function (property) {+ var members = {}, constructor;+ if ((members.__proto__ = null, members.__proto__ = {+ // The *proto* property cannot be set multiple times in recent+ // versions of Firefox and SeaMonkey.+ "toString": 1+ }, members).toString != getClass) {+ // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but+ // supports the mutable *proto* property.+ isProperty = function (property) {+ // Capture and break the object's prototype chain (see section 8.6.2+ // of the ES 5.1 spec). The parenthesized expression prevents an+ // unsafe transformation by the Closure Compiler.+ var original = this.__proto__, result = property in (this.__proto__ = null, this);+ // Restore the original prototype chain.+ this.__proto__ = original;+ return result;+ };+ } else {+ // Capture a reference to the top-level `Object` constructor.+ constructor = members.constructor;+ // Use the `constructor` property to simulate `Object#hasOwnProperty` in+ // other environments.+ isProperty = function (property) {+ var parent = (this.constructor || constructor).prototype;+ return property in this && !(property in parent && this[property] === parent[property]);+ };}+ members = null;+ return isProperty.call(this, property);+ };+ }- // Schedule the SIM group for nuking.- simulcastGroup.nuke = true;+ // Internal: A set of primitive types used by `isHostType`.+ var PrimitiveTypes = {+ 'boolean': 1,+ 'number': 1,+ 'string': 1,+ 'undefined': 1+ };- var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');+ // Internal: Determines if the given object `property` value is a+ // non-primitive.+ var isHostType = function (object, property) {+ var type = typeof object[property];+ return type == 'object' ? !!object[property] : !PrimitiveTypes[type];+ };- // Nuke all the higher layer SSRCs.- for (var i = 1; i < simulcastSsrcs.length; i++) {+ // Internal: Normalizes the `for...in` iteration algorithm across+ // environments. Each enumerated key is yielded to a `callback` function.+ forEach = function (object, callback) {+ var size = 0, Properties, members, property;++ // Tests for bugs in the current environment's `for...in` algorithm. The+ // `valueOf` property inherits the non-enumerable flag from+ // `Object.prototype` in older versions of IE, Netscape, and Mozilla.+ (Properties = function () {+ this.valueOf = 0;+ }).prototype.valueOf = 0;++ // Iterate over a new instance of the `Properties` class.+ members = new Properties();+ for (property in members) {+ // Ignore all properties inherited from `Object.prototype`.+ if (isProperty.call(members, property)) {+ size++;+ }+ }+ Properties = members = null;++ // Normalize the iteration algorithm.+ if (!size) {+ // A list of non-enumerable properties inherited from `Object.prototype`.+ members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];+ // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable+ // properties.+ forEach = function (object, callback) {+ var isFunction = getClass.call(object) == functionClass, property, length;+ var hasProperty = !isFunction && typeof object.constructor != 'function' && isHostType(object, 'hasOwnProperty') ? object.hasOwnProperty : isProperty;+ for (property in object) {+ // Gecko <= 1.0 enumerates the `prototype` property of functions under+ // certain conditions; IE does not.+ if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {+ callback(property);+ }+ }+ // Manually invoke the callback for each non-enumerable property.+ for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));+ };+ } else if (size == 2) {+ // Safari <= 2.0.4 enumerates shadowed properties twice.+ forEach = function (object, callback) {+ // Create a set of iterated properties.+ var members = {}, isFunction = getClass.call(object) == functionClass, property;+ for (property in object) {+ // Store each property name to prevent double enumeration. The+ // `prototype` property of functions is not enumerated due to cross-+ // environment inconsistencies.+ if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {+ callback(property);+ }+ }+ };+ } else {+ // No bugs detected; use the standard `for...in` algorithm.+ forEach = function (object, callback) {+ var isFunction = getClass.call(object) == functionClass, property, isConstructor;+ for (property in object) {+ if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {+ callback(property);+ }+ }+ // Manually invoke the callback for the `constructor` property due to+ // cross-environment inconsistencies.+ if (isConstructor || isProperty.call(object, (property = "constructor"))) {+ callback(property);+ }+ };+ }+ return forEach(object, callback);+ };- var ssrc = simulcastSsrcs[i];- delete sources[ssrc];+ // Public: Serializes a JavaScript `value` as a JSON string. The optional+ // `filter` argument may specify either a function that alters how object and+ // array members are serialized, or an array of strings and numbers that+ // indicates which properties should be serialized. The optional `width`+ // argument may be either a string or number that specifies the indentation+ // level of the output.+ if (!has("json-stringify")) {+ // Internal: A map of control characters and their escaped equivalents.+ var Escapes = {+ 92: "\\\\",+ 34: '\\"',+ 8: "\\b",+ 12: "\\f",+ 10: "\\n",+ 13: "\\r",+ 9: "\\t"+ };- // Remove all the groups that this SSRC participates in.- mLine.ssrcGroups.forEach(function (relatedGroup) {- if (relatedGroup.semantics === 'SIM') {- return;- }+ // Internal: Converts `value` into a zero-padded string such that its+ // length is at least equal to `width`. The `width` must be <= 6.+ var leadingZeroes = "000000";+ var toPaddedString = function (width, value) {+ // The `|| 0` expression is necessary to work around a bug in+ // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.+ return (leadingZeroes + (value || 0)).slice(-width);+ };- var relatedSsrcs = relatedGroup.ssrcs.split(' ');- if (relatedSsrcs.indexOf(ssrc) === -1) {- return;- }+ // Internal: Double-quotes a string `value`, replacing all ASCII control+ // characters (characters with code unit values between 0 and 31) with+ // their escaped equivalents. This is an implementation of the+ // `Quote(value)` operation defined in ES 5.1 section 15.12.3.+ var unicodePrefix = "\\u00";+ var quote = function (value) {+ var result = '"', index = 0, length = value.length, isLarge = length > 10 && charIndexBuggy, symbols;+ if (isLarge) {+ symbols = value.split("");+ }+ for (; index < length; index++) {+ var charCode = value.charCodeAt(index);+ // If the character is a control character, append its Unicode or+ // shorthand escape sequence; otherwise, append the character as-is.+ switch (charCode) {+ case 8: case 9: case 10: case 12: case 13: case 34: case 92:+ result += Escapes[charCode];+ break;+ default:+ if (charCode < 32) {+ result += unicodePrefix + toPaddedString(2, charCode.toString(16));+ break;+ }+ result += isLarge ? symbols[index] : charIndexBuggy ? value.charAt(index) : value[index];+ }+ }+ return result + '"';+ };- // Nuke all the related SSRCs.- relatedSsrcs.forEach(function (relatedSSRC) {- delete sources[relatedSSRC];- });+ // Internal: Recursively serializes an object. Implements the+ // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.+ var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {+ var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;+ try {+ // Necessary for host object support.+ value = object[property];+ } catch (exception) {}+ if (typeof value == "object" && value) {+ className = getClass.call(value);+ if (className == dateClass && !isProperty.call(value, "toJSON")) {+ if (value > -1 / 0 && value < 1 / 0) {+ // Dates are serialized according to the `Date#toJSON` method+ // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15+ // for the ISO 8601 date time string format.+ if (getDay) {+ // Manually compute the year, month, date, hours, minutes,+ // seconds, and milliseconds if the `getUTC*` methods are+ // buggy. Adapted from @Yaffle's `date-shim` project.+ date = floor(value / 864e5);+ for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);+ for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);+ date = 1 + date - getDay(year, month);+ // The `time` value specifies the time within the day (see ES+ // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used+ // to compute `A modulo B`, as the `%` operator does not+ // correspond to the `modulo` operation for negative numbers.+ time = (value % 864e5 + 864e5) % 864e5;+ // The hours, minutes, seconds, and milliseconds are obtained by+ // decomposing the time within the day. See section 15.9.1.10.+ hours = floor(time / 36e5) % 24;+ minutes = floor(time / 6e4) % 60;+ seconds = floor(time / 1e3) % 60;+ milliseconds = time % 1e3;+ } else {+ year = value.getUTCFullYear();+ month = value.getUTCMonth();+ date = value.getUTCDate();+ hours = value.getUTCHours();+ minutes = value.getUTCMinutes();+ seconds = value.getUTCSeconds();+ milliseconds = value.getUTCMilliseconds();+ }+ // Serialize extended years correctly.+ value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) ++ "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) ++ // Months, dates, hours, minutes, and seconds should have two+ // digits; milliseconds should have three.+ "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) ++ // Milliseconds are optional in ES 5.0, but required in 5.1.+ "." + toPaddedString(3, milliseconds) + "Z";+ } else {+ value = null;+ }+ } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {+ // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the+ // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3+ // ignores all `toJSON` methods on these objects unless they are+ // defined directly on an instance.+ value = value.toJSON(property);+ }+ }+ if (callback) {+ // If a replacement function was provided, call it to obtain the value+ // for serialization.+ value = callback.call(object, property, value);+ }+ if (value === null) {+ return "null";+ }+ className = getClass.call(value);+ if (className == booleanClass) {+ // Booleans are represented literally.+ return "" + value;+ } else if (className == numberClass) {+ // JSON numbers must be finite. `Infinity` and `NaN` are serialized as+ // `"null"`.+ return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";+ } else if (className == stringClass) {+ // Strings are double-quoted and escaped.+ return quote("" + value);+ }+ // Recursively serialize objects and arrays.+ if (typeof value == "object") {+ // Check for cyclic structures. This is a linear search; performance+ // is inversely proportional to the number of unique nested objects.+ for (length = stack.length; length--;) {+ if (stack[length] === value) {+ // Cyclic structures cannot be serialized by `JSON.stringify`.+ throw TypeError();+ }+ }+ // Add the object to the stack of traversed objects.+ stack.push(value);+ results = [];+ // Save the current indentation level and indent one additional level.+ prefix = indentation;+ indentation += whitespace;+ if (className == arrayClass) {+ // Recursively serialize array elements.+ for (index = 0, length = value.length; index < length; index++) {+ element = serialize(index, value, callback, properties, whitespace, indentation, stack);+ results.push(element === undef ? "null" : element);+ }+ result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";+ } else {+ // Recursively serialize object members. Members are selected from+ // either a user-specified list of property names, or the object+ // itself.+ forEach(properties || value, function (property) {+ var element = serialize(property, value, callback, properties, whitespace, indentation, stack);+ if (element !== undef) {+ // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}+ // is not the empty string, let `member` {quote(property) + ":"}+ // be the concatenation of `member` and the `space` character."+ // The "`space` character" refers to the literal space+ // character, not the `space` {width} argument provided to+ // `JSON.stringify`.+ results.push(quote(property) + ":" + (whitespace ? " " : "") + element);+ }+ });+ result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";+ }+ // Remove the object from the traversed object stack.+ stack.pop();+ return result;+ }+ };- // Schedule the related group for nuking.- relatedGroup.nuke = true;- })+ // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.+ JSON3.stringify = function (source, filter, width) {+ var whitespace, callback, properties, className;+ if (typeof filter == "function" || typeof filter == "object" && filter) {+ if ((className = getClass.call(filter)) == functionClass) {+ callback = filter;+ } else if (className == arrayClass) {+ // Convert the property names array into a makeshift set.+ properties = {};+ for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));+ }+ }+ if (width) {+ if ((className = getClass.call(width)) == numberClass) {+ // Convert the `width` to an integer and create a string containing+ // `width` number of space characters.+ if ((width -= width % 1) > 0) {+ for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");+ }+ } else if (className == stringClass) {+ whitespace = width.length <= 10 ? width : width.slice(0, 10);+ }}+ // Opera <= 7.54u2 discards the values associated with empty string keys+ // (`""`) only if they are used directly within an object member list+ // (e.g., `!("" in { "": 1})`).+ return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);+ };+ }- return true;- });+ // Public: Parses a JSON source string.+ if (!has("json-parse")) {+ var fromCharCode = String.fromCharCode;++ // Internal: A map of escaped control characters and their unescaped+ // equivalents.+ var Unescapes = {+ 92: "\\",+ 34: '"',+ 47: "/",+ 98: "\b",+ 116: "\t",+ 110: "\n",+ 102: "\f",+ 114: "\r"+ };- mLine.ssrcs = writeSsrcs(sources);+ // Internal: Stores the parser state.+ var Index, Source;- // Nuke all the scheduled groups.- var i = mLine.ssrcGroups.length;- while (i--) {- if (mLine.ssrcGroups[i].nuke) {- mLine.ssrcGroups.splice(i, 1);+ // Internal: Resets the parser state and throws a `SyntaxError`.+ var abort = function() {+ Index = Source = null;+ throw SyntaxError();+ };++ // Internal: Returns the next token, or `"$"` if the parser has reached+ // the end of the source string. A token may be a string, number, `null`+ // literal, or Boolean literal.+ var lex = function () {+ var source = Source, length = source.length, value, begin, position, isSigned, charCode;+ while (Index < length) {+ charCode = source.charCodeAt(Index);+ switch (charCode) {+ case 9: case 10: case 13: case 32:+ // Skip whitespace tokens, including tabs, carriage returns, line+ // feeds, and space characters.+ Index++;+ break;+ case 123: case 125: case 91: case 93: case 58: case 44:+ // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at+ // the current position.+ value = charIndexBuggy ? source.charAt(Index) : source[Index];+ Index++;+ return value;+ case 34:+ // `"` delimits a JSON string; advance to the next character and+ // begin parsing the string. String tokens are prefixed with the+ // sentinel `@` character to distinguish them from punctuators and+ // end-of-string tokens.+ for (value = "@", Index++; Index < length;) {+ charCode = source.charCodeAt(Index);+ if (charCode < 32) {+ // Unescaped ASCII control characters (those with a code unit+ // less than the space character) are not permitted.+ abort();+ } else if (charCode == 92) {+ // A reverse solidus (`\`) marks the beginning of an escaped+ // control character (including `"`, `\`, and `/`) or Unicode+ // escape sequence.+ charCode = source.charCodeAt(++Index);+ switch (charCode) {+ case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:+ // Revive escaped control characters.+ value += Unescapes[charCode];+ Index++;+ break;+ case 117:+ // `\u` marks the beginning of a Unicode escape sequence.+ // Advance to the first character and validate the+ // four-digit code point.+ begin = ++Index;+ for (position = Index + 4; Index < position; Index++) {+ charCode = source.charCodeAt(Index);+ // A valid sequence comprises four hexdigits (case-+ // insensitive) that form a single hexadecimal value.+ if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {+ // Invalid Unicode escape sequence.+ abort();+ }+ }+ // Revive the escaped character.+ value += fromCharCode("0x" + source.slice(begin, Index));+ break;+ default:+ // Invalid escape sequence.+ abort();+ }+ } else {+ if (charCode == 34) {+ // An unescaped double-quote character marks the end of the+ // string.+ break;+ }+ charCode = source.charCodeAt(Index);+ begin = Index;+ // Optimize for the common case where a string is valid.+ while (charCode >= 32 && charCode != 92 && charCode != 34) {+ charCode = source.charCodeAt(++Index);+ }+ // Append the string as-is.+ value += source.slice(begin, Index);+ }+ }+ if (source.charCodeAt(Index) == 34) {+ // Advance to the next character and return the revived string.+ Index++;+ return value;+ }+ // Unterminated string.+ abort();+ default:+ // Parse numbers and literals.+ begin = Index;+ // Advance past the negative sign, if one is specified.+ if (charCode == 45) {+ isSigned = true;+ charCode = source.charCodeAt(++Index);+ }+ // Parse an integer or floating-point value.+ if (charCode >= 48 && charCode <= 57) {+ // Leading zeroes are interpreted as octal literals.+ if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {+ // Illegal octal literal.+ abort();+ }+ isSigned = false;+ // Parse the integer component.+ for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);+ // Floats cannot contain a leading decimal point; however, this+ // case is already accounted for by the parser.+ if (source.charCodeAt(Index) == 46) {+ position = ++Index;+ // Parse the decimal component.+ for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);+ if (position == Index) {+ // Illegal trailing decimal.+ abort();+ }+ Index = position;+ }+ // Parse exponents. The `e` denoting the exponent is+ // case-insensitive.+ charCode = source.charCodeAt(Index);+ if (charCode == 101 || charCode == 69) {+ charCode = source.charCodeAt(++Index);+ // Skip past the sign following the exponent, if one is+ // specified.+ if (charCode == 43 || charCode == 45) {+ Index++;+ }+ // Parse the exponential component.+ for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);+ if (position == Index) {+ // Illegal empty exponent.+ abort();+ }+ Index = position;+ }+ // Coerce the parsed value to a JavaScript number.+ return +source.slice(begin, Index);+ }+ // A negative sign may only precede numbers.+ if (isSigned) {+ abort();+ }+ // `true`, `false`, and `null` literals.+ if (source.slice(Index, Index + 4) == "true") {+ Index += 4;+ return true;+ } else if (source.slice(Index, Index + 5) == "false") {+ Index += 5;+ return false;+ } else if (source.slice(Index, Index + 4) == "null") {+ Index += 4;+ return null;+ }+ // Unrecognized token.+ abort();+ }}- }-}+ // Return the sentinel `$` character if the parser has reached the end+ // of the source string.+ return "$";+ };-function removeGoogConference(mLine) {- if (!mLine || !Array.isArray(mLine.invalid)) {- return;- }+ // Internal: Parses a JSON `value` token.+ var get = function (value) {+ var results, hasMembers;+ if (value == "$") {+ // Unexpected end of input.+ abort();+ }+ if (typeof value == "string") {+ if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {+ // Remove the sentinel `@` character.+ return value.slice(1);+ }+ // Parse object and array literals.+ if (value == "[") {+ // Parses a JSON array, returning a new JavaScript array.+ results = [];+ for (;; hasMembers || (hasMembers = true)) {+ value = lex();+ // A closing square bracket marks the end of the array literal.+ if (value == "]") {+ break;+ }+ // If the array literal contains elements, the current token+ // should be a comma separating the previous element from the+ // next.+ if (hasMembers) {+ if (value == ",") {+ value = lex();+ if (value == "]") {+ // Unexpected trailing `,` in array literal.+ abort();+ }+ } else {+ // A `,` must separate each array element.+ abort();+ }+ }+ // Elisions and leading commas are not permitted.+ if (value == ",") {+ abort();+ }+ results.push(get(value));+ }+ return results;+ } else if (value == "{") {+ // Parses a JSON object, returning a new JavaScript object.+ results = {};+ for (;; hasMembers || (hasMembers = true)) {+ value = lex();+ // A closing curly brace marks the end of the object literal.+ if (value == "}") {+ break;+ }+ // If the object literal contains members, the current token+ // should be a comma separator.+ if (hasMembers) {+ if (value == ",") {+ value = lex();+ if (value == "}") {+ // Unexpected trailing `,` in object literal.+ abort();+ }+ } else {+ // A `,` must separate each object member.+ abort();+ }+ }+ // Leading commas are not permitted, object property names must be+ // double-quoted strings, and a `:` must separate each property+ // name and value.+ if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {+ abort();+ }+ results[value.slice(1)] = get(lex());+ }+ return results;+ }+ // Unexpected token encountered.+ abort();+ }+ return value;+ };- var i = mLine.invalid.length;- while (i--) {- if (mLine.invalid[i].value == 'x-google-flag:conference') {- mLine.invalid.splice(i, 1);+ // Internal: Updates a traversed object member.+ var update = function(source, property, callback) {+ var element = walk(source, property, callback);+ if (element === undef) {+ delete source[property];+ } else {+ source[property] = element;}- }-}+ };-function assertGoogConference(mLine) {- if (!mLine) {- return;- }+ // Internal: Recursively traverses a parsed JSON object, invoking the+ // `callback` function for each value. This is an implementation of the+ // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.+ var walk = function (source, property, callback) {+ var value = source[property], length;+ if (typeof value == "object" && value) {+ // `forEach` can't be used to traverse an array in Opera <= 8.54+ // because its `Object#hasOwnProperty` implementation returns `false`+ // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).+ if (getClass.call(value) == arrayClass) {+ for (length = value.length; length--;) {+ update(value, length, callback);+ }+ } else {+ forEach(value, function (property) {+ update(value, property, callback);+ });+ }+ }+ return callback.call(source, property, value);+ };- if (!Array.isArray(mLine.invalid)) {- mLine.invalid = [];+ // Public: `JSON.parse`. See ES 5.1 section 15.12.2.+ JSON3.parse = function (source, callback) {+ var result, value;+ Index = 0;+ Source = "" + source;+ result = get(lex());+ // If a JSON string contains multiple tokens, it is invalid.+ if (lex() != "$") {+ abort();+ }+ // Reset the parser state.+ Index = Source = null;+ return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;+ };}+ }- if (!mLine.invalid.some(- function (i) { return i.value === 'x-google-flag:conference' })) {- mLine.invalid.push({'value': 'x-google-flag:conference'});- }-}+ // Export for asynchronous module loaders.+ if (isLoader) {+ define(function () {+ return JSON3;+ });+ }+}(this));-//endregion+},{}],150:[function(require,module,exports){+module.exports = toArray-//region "Private" functions+function toArray(list, index) {+ var array = []-/**- *- * @param mLine- * @private- */-Simulcast.prototype._maybeInitializeLayers = function(mLine) {+ index = index || 0- if (!mLine || mLine.type !== 'video') {- return;+ for (var i = index || 0; i < list.length; i++) {+ array[i - index] = list[i]}- var sources = parseSsrcs(mLine);-- if (Object.keys(sources).length === 0) {-- // no sources, disable simulcast.- if (this.layers.length !== 0) {- this.layers = [];- }-- return;- }+ return array+}- // find the base layer (we'll reuse its msid and cname).- var baseLayerSSRC = Object.keys(sources)[0];- var baseLayer = sources[baseLayerSSRC];+},{}],151:[function(require,module,exports){+var MediaStreamType = {+ VIDEO_TYPE: "Video",- // todo(gp) handle screen sharing.+ AUDIO_TYPE: "Audio"+};+module.exports = MediaStreamType;+},{}],152:[function(require,module,exports){+var RTCEvents = {+ RTC_READY: "rtc.ready",+ DATA_CHANNEL_OPEN: "rtc.data_channel_open",+ LASTN_CHANGED: "rtc.lastn_changed",+ DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",+ LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",+ AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",+ AUDIO_MUTE: "rtc.audio_mute",+ VIDEO_MUTE: "rtc.video_mute"+};- // check if base CNAME has changed and reinitialise layers.- if (this.layers.length > 0- && sources[baseLayerSSRC].cname !== this.layers[0].cname) {- this.layers = [];+module.exports = RTCEvents;+},{}],153:[function(require,module,exports){+var Resolutions = {+ "1080": {+ width: 1920,+ height: 1080,+ order: 7+ },+ "fullhd": {+ width: 1920,+ height: 1080,+ order: 7+ },+ "720": {+ width: 1280,+ height: 720,+ order: 6+ },+ "hd": {+ width: 1280,+ height: 720,+ order: 6+ },+ "960": {+ width: 960,+ height: 720,+ order: 5+ },+ "640": {+ width: 640,+ height: 480,+ order: 4+ },+ "vga": {+ width: 640,+ height: 480,+ order: 4+ },+ "360": {+ width: 640,+ height: 360,+ order: 3+ },+ "320": {+ width: 320,+ height: 240,+ order: 2+ },+ "180": {+ width: 320,+ height: 180,+ order: 1}+};+module.exports = Resolutions;+},{}],154:[function(require,module,exports){+var StreamEventTypes = {+ EVENT_TYPE_LOCAL_CREATED: "stream.local_created",- // (re)initialise layers- if (this.layers.length < 1) {-- // first push the base layer.- this.layers.push({- ssrc: baseLayerSSRC,- msid: baseLayer.msid,- cname: baseLayer.cname- });-- var rtx = false; // RFC 4588- if (Array.isArray(mLine.rtp)) {- rtx = mLine.rtp.some(- function (rtpmap) { return rtpmap.codec === 'rtx'; });- }-- if (rtx) {- this.layers[0].rtx = generateSSRC();- }+ EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",- // now push additional layers.- for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {+ EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",- var layer = { ssrc: generateSSRC() };- if (rtx) {- layer.rtx = generateSSRC();- }+ EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",- this.layers.push(layer);- }- }+ EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended"};-/**- *- * @param mLine- * @private- */-Simulcast.prototype._restoreSimulcastView = function(mLine) {- if (mLine && mLine.type === 'video' && this.layers.length !== 0) {+module.exports = StreamEventTypes;+},{}],155:[function(require,module,exports){+var UIEvents = {+ NICKNAME_CHANGED: "UI.nickname_changed",+ SELECTED_ENDPOINT: "UI.selected_endpoint",+ PINNED_ENDPOINT: "UI.pinned_endpoint",+ LARGEVIDEO_INIT: "UI.largevideo_init"+};+module.exports = UIEvents;+},{}],156:[function(require,module,exports){+var AuthenticationEvents = {+ /**+ * Event callback arguments:+ * function(authenticationEnabled, userIdentity)+ * authenticationEnabled - indicates whether authentication has been enabled+ * in this session+ * userIdentity - if user has been logged in then it contains user name. If+ * contains 'null' or 'undefined' then user is not logged in.+ */+ IDENTITY_UPDATED: "authentication.identity_updated"+};+module.exports = AuthenticationEvents;- var sources = {};+},{}],157:[function(require,module,exports){+var CQEvents = {+ LOCALSTATS_UPDATED: "cq.localstats_updated",+ REMOTESTATS_UPDATED: "cq.remotestats_updated",+ STOP: "cq.stop"+};- var msid = this.layers[0].msid;- var cname = this.layers[0].cname;- var simulcastSsrcs = [];- var ssrcGroups = [];+module.exports = CQEvents;+},{}],158:[function(require,module,exports){+var DesktopSharingEventTypes = {+ INIT: "ds.init",- for (var i = 0; i < this.layers.length; i++) {- var layer = this.layers[i];+ SWITCHING_DONE: "ds.switching_done",- sources[layer.ssrc] = { msid: msid, cname: cname };- simulcastSsrcs.push(layer.ssrc);+ NEW_STREAM_CREATED: "ds.new_stream_created"+};- if (layer.rtx) {+module.exports = DesktopSharingEventTypes;+},{}],159:[function(require,module,exports){+var Events = {+ DTMF_SUPPORT_CHANGED: "members.dtmf_support_changed"+};- sources[layer.rtx] = {- msid: msid,- cname: cname- }+module.exports = Events;- ssrcGroups.push({- semantics: 'FID',- ssrcs: [layer.ssrc, layer.rtx].join(' ')- });- }+},{}],160:[function(require,module,exports){+module.exports = {+ getLanguages : function () {+ var languages = [];+ for(var lang in this)+ {+ if(typeof this[lang] === "string")+ languages.push(this[lang]);}+ return languages;+ },+ EN: "en",+ BG: "bg",+ DE: "de",+ TR: "tr",+ FR: "fr"+}+},{}],161:[function(require,module,exports){+var XMPPEvents = {+ CONNECTION_FAILED: "xmpp.connection.failed",+ // Indicates an interrupted connection event.+ CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",+ // Indicates a restored connection event.+ CONNECTION_RESTORED: "xmpp.connection.restored",+ CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",+ CALL_INCOMING: "xmpp.callincoming.jingle",+ DISPOSE_CONFERENCE: "xmpp.dispose_conference",+ GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",+ KICKED: "xmpp.kicked",+ BRIDGE_DOWN: "xmpp.bridge_down",+ USER_ID_CHANGED: "xmpp.user_id_changed",+ // We joined the MUC+ MUC_JOINED: "xmpp.muc_joined",+ // A member joined the MUC+ MUC_MEMBER_JOINED: "xmpp.muc_member_joined",+ // A member left the MUC+ MUC_MEMBER_LEFT: "xmpp.muc_member_left",+ MUC_ROLE_CHANGED: "xmpp.muc_role_changed",+ MUC_DESTROYED: "xmpp.muc_destroyed",+ DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",+ REMOTE_STATS: "xmpp.remote_stats",+ LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",+ PRESENCE_STATUS: "xmpp.presence_status",+ RESERVATION_ERROR: "xmpp.room_reservation_error",+ SUBJECT_CHANGED: "xmpp.subject_changed",+ MESSAGE_RECEIVED: "xmpp.message_received",+ SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",+ PASSWORD_REQUIRED: "xmpp.password_required",+ AUTHENTICATION_REQUIRED: "xmpp.authentication_required",+ CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",+ ETHERPAD: "xmpp.etherpad",+ DEVICE_AVAILABLE: "xmpp.device_available",+ VIDEO_TYPE: "xmpp.video_type",+ PEERCONNECTION_READY: "xmpp.peerconnection_ready",+ CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",+ AUDIO_MUTED: "xmpp.audio_muted",+ VIDEO_MUTED: "xmpp.video_muted",+ AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",+ START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",+ START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",+ SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',+ SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',+ CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',+ JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',+ PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',+ FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',+ ROOM_JOIN_ERROR: 'xmpp.room_join_error',+ ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',+ // xmpp is connected and obtained user media+ READY_TO_JOIN: 'xmpp.ready_to_join'+};+module.exports = XMPPEvents;+},{}],162:[function(require,module,exports){+// Copyright Joyent, Inc. and other Node contributors.+//+// Permission is hereby granted, free of charge, to any person obtaining a+// copy of this software and associated documentation files (the+// "Software"), to deal in the Software without restriction, including+// without limitation the rights to use, copy, modify, merge, publish,+// distribute, sublicense, and/or sell copies of the Software, and to permit+// persons to whom the Software is furnished to do so, subject to the+// following conditions:+//+// The above copyright notice and this permission notice shall be included+// in all copies or substantial portions of the Software.+//+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE+// USE OR OTHER DEALINGS IN THE SOFTWARE.- ssrcGroups.push({- semantics: 'SIM',- ssrcs: simulcastSsrcs.join(' ')- });-- mLine.ssrcGroups = ssrcGroups;- mLine.ssrcs = writeSsrcs(sources);- }+function EventEmitter() {+ this._events = this._events || {};+ this._maxListeners = this._maxListeners || undefined;}+module.exports = EventEmitter;-//endregion+// Backwards-compat with node 0.10.x+EventEmitter.EventEmitter = EventEmitter;-//region "Public" functions+EventEmitter.prototype._events = undefined;+EventEmitter.prototype._maxListeners = undefined;-Simulcast.prototype.isSupported = function () {- return window.chrome;+// By default EventEmitters will print a warning if more than 10 listeners are+// added to it. This is a useful default which helps finding memory leaks.+EventEmitter.defaultMaxListeners = 10;- // TODO this needs improvements. For example I doubt that Chrome in Android- // has simulcast support. Also, only recent versions of Chromium have native- // simulcast support.-}+// Obviously not all Emitters should be limited to 10. This function allows+// that to be increased. Set to zero for unlimited.+EventEmitter.prototype.setMaxListeners = function(n) {+ if (!isNumber(n) || n < 0 || isNaN(n))+ throw TypeError('n must be a positive number');+ this._maxListeners = n;+ return this;+};-/**- *- * @param desc- * @returns {RTCSessionDescription}- */-Simulcast.prototype.mungeRemoteDescription = function (desc) {+EventEmitter.prototype.emit = function(type) {+ var er, handler, len, args, i, listeners;- if (!validateDescription(desc)) {- return desc;+ if (!this._events)+ this._events = {};++ // If there is no 'error' event listener then throw.+ if (type === 'error') {+ if (!this._events.error ||+ (isObject(this._events.error) && !this._events.error.length)) {+ er = arguments[1];+ if (er instanceof Error) {+ throw er; // Unhandled 'error' event+ }+ throw TypeError('Uncaught, unspecified "error" event.');}+ }- var session = transform.parse(desc.sdp);+ handler = this._events[type];- var self = this;- processVideo(session, function (mLine) {+ if (isUndefined(handler))+ return false;- // Handle simulcast reception.- if (self.options.explodeRemoteSimulcast) {- explodeRemoteSimulcast(mLine);- } else {- squeezeRemoteSimulcast(mLine);- }+ if (isFunction(handler)) {+ switch (arguments.length) {+ // fast cases+ case 1:+ handler.call(this);+ break;+ case 2:+ handler.call(this, arguments[1]);+ break;+ case 3:+ handler.call(this, arguments[1], arguments[2]);+ break;+ // slower+ default:+ len = arguments.length;+ args = new Array(len - 1);+ for (i = 1; i < len; i++)+ args[i - 1] = arguments[i];+ handler.apply(this, args);+ }+ } else if (isObject(handler)) {+ len = arguments.length;+ args = new Array(len - 1);+ for (i = 1; i < len; i++)+ args[i - 1] = arguments[i];- // If native simulcast is enabled, we must append the x-goog-conference- // attribute to the SDP.- if (self.layers.length < 1) {- removeGoogConference(mLine);- } else {- assertGoogConference(mLine);- }- });+ listeners = handler.slice();+ len = listeners.length;+ for (i = 0; i < len; i++)+ listeners[i].apply(this, args);+ }- return new RTCSessionDescription({- type: desc.type,- sdp: transform.write(session)- });+ return true;};-/**- *- * @param desc- * @returns {RTCSessionDescription}- */-Simulcast.prototype.mungeLocalDescription = function (desc) {+EventEmitter.prototype.addListener = function(type, listener) {+ var m;- if (!validateDescription(desc) || !this.isSupported()) {- return desc;- }+ if (!isFunction(listener))+ throw TypeError('listener must be a function');- var session = transform.parse(desc.sdp);+ if (!this._events)+ this._events = {};- var self = this;- processVideo(session, function (mLine) {- // Initialize native simulcast layers, if not already done.- self._maybeInitializeLayers(mLine);+ // To avoid recursion in the case that type === "newListener"! Before+ // adding it to the listeners, first emit "newListener".+ if (this._events.newListener)+ this.emit('newListener', type,+ isFunction(listener.listener) ?+ listener.listener : listener);- // Update the SDP with the simulcast layers.- self._restoreSimulcastView(mLine);- });+ if (!this._events[type])+ // Optimize the case of one listener. Don't need the extra array object.+ this._events[type] = listener;+ else if (isObject(this._events[type]))+ // If we've already got an array, just append.+ this._events[type].push(listener);+ else+ // Adding the second element, need to change to array.+ this._events[type] = [this._events[type], listener];- return new RTCSessionDescription({- type: desc.type,- sdp: transform.write(session)- });+ // Check for listener leak+ if (isObject(this._events[type]) && !this._events[type].warned) {+ var m;+ if (!isUndefined(this._maxListeners)) {+ m = this._maxListeners;+ } else {+ m = EventEmitter.defaultMaxListeners;+ }++ if (m && m > 0 && this._events[type].length > m) {+ this._events[type].warned = true;+ console.error('(node) warning: possible EventEmitter memory ' ++ 'leak detected. %d listeners added. ' ++ 'Use emitter.setMaxListeners() to increase limit.',+ this._events[type].length);+ if (typeof console.trace === 'function') {+ // not supported in IE 10+ console.trace();+ }+ }+ }++ return this;};-//endregion+EventEmitter.prototype.on = EventEmitter.prototype.addListener;-module.exports = Simulcast;+EventEmitter.prototype.once = function(type, listener) {+ if (!isFunction(listener))+ throw TypeError('listener must be a function');-},{"./transform-utils":101,"sdp-transform":103}],101:[function(require,module,exports){-exports.writeSsrcs = function(sources, order) {- var ssrcs = [];+ var fired = false;- // expand sources to ssrcs- if (typeof sources !== 'undefined' &&- Object.keys(sources).length !== 0) {+ function g() {+ this.removeListener(type, g);- if (Array.isArray(order)) {- for (var i = 0; i < order.length; i++) {- var ssrc = order[i];- var source = sources[ssrc];- Object.keys(source).forEach(function (attribute) {- ssrcs.push({- id: ssrc,- attribute: attribute,- value: source[attribute]- });- });- }- } else {- Object.keys(sources).forEach(function (ssrc) {- var source = sources[ssrc];- Object.keys(source).forEach(function (attribute) {- ssrcs.push({- id: ssrc,- attribute: attribute,- value: source[attribute]- });- });- });+ if (!fired) {+ fired = true;+ listener.apply(this, arguments);}}- return ssrcs;-};+ g.listener = listener;+ this.on(type, g);-exports.parseSsrcs = function (mLine) {- var sources = {};- // group sources attributes by ssrc.- if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {- mLine.ssrcs.forEach(function (ssrc) {- if (!sources[ssrc.id])- sources[ssrc.id] = {};- sources[ssrc.id][ssrc.attribute] = ssrc.value;- });- }- return sources;+ return this;};+// emits a 'removeListener' event iff the listener was removed+EventEmitter.prototype.removeListener = function(type, listener) {+ var list, position, length, i;-},{}],102:[function(require,module,exports){-arguments[4][96][0].apply(exports,arguments)-},{"dup":96}],103:[function(require,module,exports){-arguments[4][97][0].apply(exports,arguments)-},{"./parser":104,"./writer":105,"dup":97}],104:[function(require,module,exports){-arguments[4][98][0].apply(exports,arguments)-},{"./grammar":102,"dup":98}],105:[function(require,module,exports){-arguments[4][99][0].apply(exports,arguments)-},{"./grammar":102,"dup":99}],106:[function(require,module,exports){-arguments[4][96][0].apply(exports,arguments)-},{"dup":96}],107:[function(require,module,exports){-arguments[4][97][0].apply(exports,arguments)-},{"./parser":108,"./writer":109,"dup":97}],108:[function(require,module,exports){-arguments[4][98][0].apply(exports,arguments)-},{"./grammar":106,"dup":98}],109:[function(require,module,exports){-arguments[4][99][0].apply(exports,arguments)-},{"./grammar":106,"dup":99}],110:[function(require,module,exports){-var MediaStreamType = {- VIDEO_TYPE: "Video",-- AUDIO_TYPE: "Audio"-};-module.exports = MediaStreamType;-},{}],111:[function(require,module,exports){-var RTCEvents = {- RTC_READY: "rtc.ready",- DATA_CHANNEL_OPEN: "rtc.data_channel_open",- LASTN_CHANGED: "rtc.lastn_changed",- DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",- LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",- AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",- AUDIO_MUTE: "rtc.audio_mute",- VIDEO_MUTE: "rtc.video_mute"-};+ if (!isFunction(listener))+ throw TypeError('listener must be a function');-module.exports = RTCEvents;-},{}],112:[function(require,module,exports){-var Resolutions = {- "1080": {- width: 1920,- height: 1080,- order: 7- },- "fullhd": {- width: 1920,- height: 1080,- order: 7- },- "720": {- width: 1280,- height: 720,- order: 6- },- "hd": {- width: 1280,- height: 720,- order: 6- },- "960": {- width: 960,- height: 720,- order: 5- },- "640": {- width: 640,- height: 480,- order: 4- },- "vga": {- width: 640,- height: 480,- order: 4- },- "360": {- width: 640,- height: 360,- order: 3- },- "320": {- width: 320,- height: 240,- order: 2- },- "180": {- width: 320,- height: 180,- order: 1+ if (!this._events || !this._events[type])+ return this;++ list = this._events[type];+ length = list.length;+ position = -1;++ if (list === listener ||+ (isFunction(list.listener) && list.listener === listener)) {+ delete this._events[type];+ if (this._events.removeListener)+ this.emit('removeListener', type, listener);++ } else if (isObject(list)) {+ for (i = length; i-- > 0;) {+ if (list[i] === listener ||+ (list[i].listener && list[i].listener === listener)) {+ position = i;+ break;+ }}-};-module.exports = Resolutions;-},{}],113:[function(require,module,exports){-var StreamEventTypes = {- EVENT_TYPE_LOCAL_CREATED: "stream.local_created",- EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",+ if (position < 0)+ return this;- EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",+ if (list.length === 1) {+ list.length = 0;+ delete this._events[type];+ } else {+ list.splice(position, 1);+ }- EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",+ if (this._events.removeListener)+ this.emit('removeListener', type, listener);+ }- EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended"+ return this;};-module.exports = StreamEventTypes;-},{}],114:[function(require,module,exports){-var UIEvents = {- NICKNAME_CHANGED: "UI.nickname_changed",- SELECTED_ENDPOINT: "UI.selected_endpoint",- PINNED_ENDPOINT: "UI.pinned_endpoint",- LARGEVIDEO_INIT: "UI.largevideo_init"+EventEmitter.prototype.removeAllListeners = function(type) {+ var key, listeners;++ if (!this._events)+ return this;++ // not listening for removeListener, no need to emit+ if (!this._events.removeListener) {+ if (arguments.length === 0)+ this._events = {};+ else if (this._events[type])+ delete this._events[type];+ return this;+ }++ // emit removeListener for all listeners on all events+ if (arguments.length === 0) {+ for (key in this._events) {+ if (key === 'removeListener') continue;+ this.removeAllListeners(key);+ }+ this.removeAllListeners('removeListener');+ this._events = {};+ return this;+ }++ listeners = this._events[type];++ if (isFunction(listeners)) {+ this.removeListener(type, listeners);+ } else {+ // LIFO order+ while (listeners.length)+ this.removeListener(type, listeners[listeners.length - 1]);+ }+ delete this._events[type];++ return this;};-module.exports = UIEvents;-},{}],115:[function(require,module,exports){-var AuthenticationEvents = {- /**- * Event callback arguments:- * function(authenticationEnabled, userIdentity)- * authenticationEnabled - indicates whether authentication has been enabled- * in this session- * userIdentity - if user has been logged in then it contains user name. If- * contains 'null' or 'undefined' then user is not logged in.- */- IDENTITY_UPDATED: "authentication.identity_updated"++EventEmitter.prototype.listeners = function(type) {+ var ret;+ if (!this._events || !this._events[type])+ ret = [];+ else if (isFunction(this._events[type]))+ ret = [this._events[type]];+ else+ ret = this._events[type].slice();+ return ret;};-module.exports = AuthenticationEvents;-},{}],116:[function(require,module,exports){-var CQEvents = {- LOCALSTATS_UPDATED: "cq.localstats_updated",- REMOTESTATS_UPDATED: "cq.remotestats_updated",- STOP: "cq.stop"+EventEmitter.listenerCount = function(emitter, type) {+ var ret;+ if (!emitter._events || !emitter._events[type])+ ret = 0;+ else if (isFunction(emitter._events[type]))+ ret = 1;+ else+ ret = emitter._events[type].length;+ return ret;};-module.exports = CQEvents;-},{}],117:[function(require,module,exports){-var DesktopSharingEventTypes = {- INIT: "ds.init",+function isFunction(arg) {+ return typeof arg === 'function';+}- SWITCHING_DONE: "ds.switching_done",+function isNumber(arg) {+ return typeof arg === 'number';+}- NEW_STREAM_CREATED: "ds.new_stream_created"-};+function isObject(arg) {+ return typeof arg === 'object' && arg !== null;+}-module.exports = DesktopSharingEventTypes;-},{}],118:[function(require,module,exports){-var Events = {- DTMF_SUPPORT_CHANGED: "members.dtmf_support_changed"-};+function isUndefined(arg) {+ return arg === void 0;+}-module.exports = Events;+},{}],163:[function(require,module,exports){+// shim for using process in browser-},{}],119:[function(require,module,exports){-module.exports = {- getLanguages : function () {- var languages = [];- for(var lang in this)- {- if(typeof this[lang] === "string")- languages.push(this[lang]);+var process = module.exports = {};+var queue = [];+var draining = false;++function drainQueue() {+ if (draining) {+ return;+ }+ draining = true;+ var currentQueue;+ var len = queue.length;+ while(len) {+ currentQueue = queue;+ queue = [];+ var i = -1;+ while (++i < len) {+ currentQueue[i]();}- return languages;- },- EN: "en",- BG: "bg",- DE: "de",- TR: "tr",- FR: "fr"+ len = queue.length;+ }+ draining = false;}-},{}],120:[function(require,module,exports){-var XMPPEvents = {- CONNECTION_FAILED: "xmpp.connection.failed",- // Indicates an interrupted connection event.- CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",- // Indicates a restored connection event.- CONNECTION_RESTORED: "xmpp.connection.restored",- CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",- CALL_INCOMING: "xmpp.callincoming.jingle",- DISPOSE_CONFERENCE: "xmpp.dispose_conference",- GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",- KICKED: "xmpp.kicked",- BRIDGE_DOWN: "xmpp.bridge_down",- USER_ID_CHANGED: "xmpp.user_id_changed",- // We joined the MUC- MUC_JOINED: "xmpp.muc_joined",- // A member joined the MUC- MUC_MEMBER_JOINED: "xmpp.muc_member_joined",- // A member left the MUC- MUC_MEMBER_LEFT: "xmpp.muc_member_left",- MUC_ROLE_CHANGED: "xmpp.muc_role_changed",- MUC_DESTROYED: "xmpp.muc_destroyed",- DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",- REMOTE_STATS: "xmpp.remote_stats",- LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",- PRESENCE_STATUS: "xmpp.presence_status",- RESERVATION_ERROR: "xmpp.room_reservation_error",- SUBJECT_CHANGED: "xmpp.subject_changed",- MESSAGE_RECEIVED: "xmpp.message_received",- SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",- PASSWORD_REQUIRED: "xmpp.password_required",- AUTHENTICATION_REQUIRED: "xmpp.authentication_required",- CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",- ETHERPAD: "xmpp.etherpad",- DEVICE_AVAILABLE: "xmpp.device_available",- VIDEO_TYPE: "xmpp.video_type",- PEERCONNECTION_READY: "xmpp.peerconnection_ready",- CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",- AUDIO_MUTED: "xmpp.audio_muted",- VIDEO_MUTED: "xmpp.video_muted",- AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",- START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",- START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",- SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',- SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',- CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',- JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',- PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',- FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',- ROOM_JOIN_ERROR: 'xmpp.room_join_error',- ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',- // xmpp is connected and obtained user media- READY_TO_JOIN: 'xmpp.ready_to_join'+process.nextTick = function (fun) {+ queue.push(fun);+ if (!draining) {+ setTimeout(drainQueue, 0);+ }};-module.exports = XMPPEvents;-},{}]},{},[3])(3)++process.title = 'browser';+process.browser = true;+process.env = {};+process.argv = [];+process.version = ''; // empty string to avoid regexp issues++function noop() {}++process.on = noop;+process.addListener = noop;+process.once = noop;+process.off = noop;+process.removeListener = noop;+process.removeAllListeners = noop;+process.emit = noop;++process.binding = function (name) {+ throw new Error('process.binding is not supported');+};++// TODO(shtylman)+process.cwd = function () { return '/' };+process.chdir = function (dir) {+ throw new Error('process.chdir is not supported');+};+process.umask = function() { return 0; };++},{}]},{},[1])(1)});\ No newline at end of file