ucservice 1.8.0 → 1.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/lib/janus.js DELETED
@@ -1,3413 +0,0 @@
1
- /*
2
- The MIT License (MIT)
3
-
4
- Copyright (c) 2016 Meetecho
5
-
6
- Permission is hereby granted, free of charge, to any person obtaining
7
- a copy of this software and associated documentation files (the "Software"),
8
- to deal in the Software without restriction, including without limitation
9
- the rights to use, copy, modify, merge, publish, distribute, sublicense,
10
- and/or sell copies of the Software, and to permit persons to whom the
11
- Software is furnished to do so, subject to the following conditions:
12
-
13
- The above copyright notice and this permission notice shall be included
14
- in all copies or substantial portions of the Software.
15
-
16
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17
- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19
- THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20
- OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21
- ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
- OTHER DEALINGS IN THE SOFTWARE.
23
- */
24
-
25
- // List of sessions
26
- Janus.sessions = {};
27
-
28
- Janus.isExtensionEnabled = function() {
29
- if(navigator.mediaDevices && navigator.mediaDevices.getDisplayMedia) {
30
- // No need for the extension, getDisplayMedia is supported
31
- return true;
32
- }
33
- if(window.navigator.userAgent.match('Chrome')) {
34
- var chromever = parseInt(window.navigator.userAgent.match(/Chrome\/(.*) /)[1], 10);
35
- var maxver = 33;
36
- if(window.navigator.userAgent.match('Linux'))
37
- maxver = 35; // "known" crash in chrome 34 and 35 on linux
38
- if(chromever >= 26 && chromever <= maxver) {
39
- // Older versions of Chrome don't support this extension-based approach, so lie
40
- return true;
41
- }
42
- return Janus.extension.isInstalled();
43
- } else {
44
- // Firefox of others, no need for the extension (but this doesn't mean it will work)
45
- return true;
46
- }
47
- };
48
-
49
- var defaultExtension = {
50
- // Screensharing Chrome Extension ID
51
- extensionId: 'hapfgfdkleiggjjpfpenajgdnfckjpaj',
52
- isInstalled: function() { return document.querySelector('#janus-extension-installed') !== null; },
53
- getScreen: function (callback) {
54
- var pending = window.setTimeout(function () {
55
- error = new Error('NavigatorUserMediaError');
56
- error.name = 'The required Chrome extension is not installed: click <a href="#">here</a> to install it. (NOTE: this will need you to refresh the page)';
57
- return callback(error);
58
- }, 1000);
59
- this.cache[pending] = callback;
60
- window.postMessage({ type: 'janusGetScreen', id: pending }, '*');
61
- },
62
- init: function () {
63
- var cache = {};
64
- this.cache = cache;
65
- // Wait for events from the Chrome Extension
66
- window.addEventListener('message', function (event) {
67
- if(event.origin != window.location.origin)
68
- return;
69
- if(event.data.type == 'janusGotScreen' && cache[event.data.id]) {
70
- var callback = cache[event.data.id];
71
- delete cache[event.data.id];
72
-
73
- if (event.data.sourceId === '') {
74
- // user canceled
75
- var error = new Error('NavigatorUserMediaError');
76
- error.name = 'You cancelled the request for permission, giving up...';
77
- callback(error);
78
- } else {
79
- callback(null, event.data.sourceId);
80
- }
81
- } else if (event.data.type == 'janusGetScreenPending') {
82
- console.log('clearing ', event.data.id);
83
- window.clearTimeout(event.data.id);
84
- }
85
- });
86
- }
87
- };
88
-
89
- Janus.useDefaultDependencies = function (deps) {
90
- var f = (deps && deps.fetch) || fetch;
91
- var p = (deps && deps.Promise) || Promise;
92
- var socketCls = (deps && deps.WebSocket) || WebSocket;
93
-
94
- return {
95
- newWebSocket: function(server, proto) { return new socketCls(server, proto); },
96
- extension: (deps && deps.extension) || defaultExtension,
97
- isArray: function(arr) { return Array.isArray(arr); },
98
- webRTCAdapter: (deps && deps.adapter) || adapter,
99
- httpAPICall: function(url, options) {
100
- var fetchOptions = {
101
- method: options.verb,
102
- headers: {
103
- 'Accept': 'application/json, text/plain, */*'
104
- },
105
- cache: 'no-cache'
106
- };
107
- if(options.verb === "POST") {
108
- fetchOptions.headers['Content-Type'] = 'application/json';
109
- }
110
- if(options.withCredentials !== undefined) {
111
- fetchOptions.credentials = options.withCredentials === true ? 'include' : (options.withCredentials ? options.withCredentials : 'omit');
112
- }
113
- if(options.body !== undefined) {
114
- fetchOptions.body = JSON.stringify(options.body);
115
- }
116
-
117
- var fetching = f(url, fetchOptions).catch(function(error) {
118
- return p.reject({message: 'Probably a network error, is the server down?', error: error});
119
- });
120
-
121
- /*
122
- * fetch() does not natively support timeouts.
123
- * Work around this by starting a timeout manually, and racing it agains the fetch() to see which thing resolves first.
124
- */
125
-
126
- if(options.timeout !== undefined) {
127
- var timeout = new p(function(resolve, reject) {
128
- var timerId = setTimeout(function() {
129
- clearTimeout(timerId);
130
- return reject({message: 'Request timed out', timeout: options.timeout});
131
- }, options.timeout);
132
- });
133
- fetching = p.race([fetching,timeout]);
134
- }
135
-
136
- fetching.then(function(response) {
137
- if(response.ok) {
138
- if(typeof(options.success) === typeof(Janus.noop)) {
139
- return response.json().then(function(parsed) {
140
- options.success(parsed);
141
- }).catch(function(error) {
142
- return p.reject({message: 'Failed to parse response body', error: error, response: response});
143
- });
144
- }
145
- }
146
- else {
147
- return p.reject({message: 'API call failed', response: response});
148
- }
149
- }).catch(function(error) {
150
- if(typeof(options.error) === typeof(Janus.noop)) {
151
- options.error(error.message || '<< internal error >>', error);
152
- }
153
- });
154
-
155
- return fetching;
156
- }
157
- }
158
- };
159
-
160
- Janus.useOldDependencies = function (deps) {
161
- var jq = (deps && deps.jQuery) || jQuery;
162
- var socketCls = (deps && deps.WebSocket) || WebSocket;
163
- return {
164
- newWebSocket: function(server, proto) { return new socketCls(server, proto); },
165
- isArray: function(arr) { return jq.isArray(arr); },
166
- extension: (deps && deps.extension) || defaultExtension,
167
- webRTCAdapter: (deps && deps.adapter) || adapter,
168
- httpAPICall: function(url, options) {
169
- var payload = options.body !== undefined ? {
170
- contentType: 'application/json',
171
- data: JSON.stringify(options.body)
172
- } : {};
173
- var credentials = options.withCredentials !== undefined ? {xhrFields: {withCredentials: options.withCredentials}} : {};
174
-
175
- return jq.ajax(jq.extend(payload, credentials, {
176
- url: url,
177
- type: options.verb,
178
- cache: false,
179
- dataType: 'json',
180
- async: options.async,
181
- timeout: options.timeout,
182
- success: function(result) {
183
- if(typeof(options.success) === typeof(Janus.noop)) {
184
- options.success(result);
185
- }
186
- },
187
- error: function(xhr, status, err) {
188
- if(typeof(options.error) === typeof(Janus.noop)) {
189
- options.error(status, err);
190
- }
191
- }
192
- }));
193
- },
194
- };
195
- };
196
-
197
- Janus.noop = function() {};
198
-
199
- Janus.dataChanDefaultLabel = "JanusDataChannel";
200
-
201
- // Initialization
202
- Janus.init = function(options) {
203
- options = options || {};
204
- options.callback = (typeof options.callback == "function") ? options.callback : Janus.noop;
205
- if(Janus.initDone === true) {
206
- // Already initialized
207
- options.callback();
208
- } else {
209
- if(typeof console == "undefined" || typeof console.log == "undefined")
210
- console = { log: function() {} };
211
- // Console logging (all debugging disabled by default)
212
- Janus.trace = Janus.noop;
213
- Janus.debug = Janus.noop;
214
- Janus.vdebug = Janus.noop;
215
- Janus.log = Janus.noop;
216
- Janus.warn = Janus.noop;
217
- Janus.error = Janus.noop;
218
- if(options.debug === true || options.debug === "all") {
219
- // Enable all debugging levels
220
- Janus.trace = console.trace.bind(console);
221
- Janus.debug = console.debug.bind(console);
222
- Janus.vdebug = console.debug.bind(console);
223
- Janus.log = console.log.bind(console);
224
- Janus.warn = console.warn.bind(console);
225
- Janus.error = console.error.bind(console);
226
- } else if(Array.isArray(options.debug)) {
227
- for(var i in options.debug) {
228
- var d = options.debug[i];
229
- switch(d) {
230
- case "trace":
231
- Janus.trace = console.trace.bind(console);
232
- break;
233
- case "debug":
234
- Janus.debug = console.debug.bind(console);
235
- break;
236
- case "vdebug":
237
- Janus.vdebug = console.debug.bind(console);
238
- break;
239
- case "log":
240
- Janus.log = console.log.bind(console);
241
- break;
242
- case "warn":
243
- Janus.warn = console.warn.bind(console);
244
- break;
245
- case "error":
246
- Janus.error = console.error.bind(console);
247
- break;
248
- default:
249
- console.error("Unknown debugging option '" + d + "' (supported: 'trace', 'debug', 'vdebug', 'log', warn', 'error')");
250
- break;
251
- }
252
- }
253
- }
254
- Janus.log("Initializing library");
255
-
256
- var usedDependencies = options.dependencies || Janus.useDefaultDependencies();
257
- Janus.isArray = usedDependencies.isArray;
258
- Janus.webRTCAdapter = usedDependencies.webRTCAdapter;
259
- Janus.httpAPICall = usedDependencies.httpAPICall;
260
- Janus.newWebSocket = usedDependencies.newWebSocket;
261
- Janus.extension = usedDependencies.extension;
262
- Janus.extension.init();
263
-
264
- // Helper method to enumerate devices
265
- Janus.listDevices = function(callback, config) {
266
- callback = (typeof callback == "function") ? callback : Janus.noop;
267
- if (config == null) config = { audio: true, video: true };
268
- if(Janus.isGetUserMediaAvailable()) {
269
- navigator.mediaDevices.getUserMedia(config)
270
- .then(function(stream) {
271
- navigator.mediaDevices.enumerateDevices().then(function(devices) {
272
- Janus.debug(devices);
273
- callback(devices);
274
- // Get rid of the now useless stream
275
- try {
276
- var tracks = stream.getTracks();
277
- for(var i in tracks) {
278
- var mst = tracks[i];
279
- if(mst !== null && mst !== undefined)
280
- mst.stop();
281
- }
282
- } catch(e) {}
283
- });
284
- })
285
- .catch(function(err) {
286
- Janus.error(err);
287
- callback([]);
288
- });
289
- } else {
290
- Janus.warn("navigator.mediaDevices unavailable");
291
- callback([]);
292
- }
293
- }
294
- // Helper methods to attach/reattach a stream to a video element (previously part of adapter.js)
295
- Janus.attachMediaStream = function(element, stream) {
296
- if(Janus.webRTCAdapter.browserDetails.browser === 'chrome') {
297
- var chromever = Janus.webRTCAdapter.browserDetails.version;
298
- if(chromever >= 52) {
299
- element.srcObject = stream;
300
- } else if(typeof element.src !== 'undefined') {
301
- element.src = URL.createObjectURL(stream);
302
- } else {
303
- Janus.error("Error attaching stream to element");
304
- }
305
- } else {
306
- element.srcObject = stream;
307
- }
308
- };
309
- Janus.reattachMediaStream = function(to, from) {
310
- if(Janus.webRTCAdapter.browserDetails.browser === 'chrome') {
311
- var chromever = Janus.webRTCAdapter.browserDetails.version;
312
- if(chromever >= 52) {
313
- to.srcObject = from.srcObject;
314
- } else if(typeof to.src !== 'undefined') {
315
- to.src = from.src;
316
- } else {
317
- Janus.error("Error reattaching stream to element");
318
- }
319
- } else {
320
- to.srcObject = from.srcObject;
321
- }
322
- };
323
- // Detect tab close: make sure we don't loose existing onbeforeunload handlers
324
- // (note: for iOS we need to subscribe to a different event, 'pagehide', see
325
- // https://gist.github.com/thehunmonkgroup/6bee8941a49b86be31a787fe8f4b8cfe)
326
- var iOS = ['iPad', 'iPhone', 'iPod'].indexOf(navigator.platform) >= 0;
327
- var eventName = iOS ? 'pagehide' : 'beforeunload';
328
- var oldOBF = window["on" + eventName];
329
- window.addEventListener(eventName, function(event) {
330
- Janus.log("Closing window");
331
- for(var s in Janus.sessions) {
332
- if(Janus.sessions[s] !== null && Janus.sessions[s] !== undefined &&
333
- Janus.sessions[s].destroyOnUnload) {
334
- Janus.log("Destroying session " + s);
335
- Janus.sessions[s].destroy({asyncRequest: false, notifyDestroyed: false});
336
- }
337
- }
338
- if(oldOBF && typeof oldOBF == "function")
339
- oldOBF();
340
- });
341
- // If this is a Safari Technology Preview, check if VP8 is supported
342
- Janus.safariVp8 = false;
343
- if(Janus.webRTCAdapter.browserDetails.browser === 'safari' &&
344
- Janus.webRTCAdapter.browserDetails.version >= 605) {
345
- // Let's see if RTCRtpSender.getCapabilities() is there
346
- if(RTCRtpSender && RTCRtpSender.getCapabilities && RTCRtpSender.getCapabilities("video") &&
347
- RTCRtpSender.getCapabilities("video").codecs && RTCRtpSender.getCapabilities("video").codecs.length) {
348
- for(var i in RTCRtpSender.getCapabilities("video").codecs) {
349
- var codec = RTCRtpSender.getCapabilities("video").codecs[i];
350
- if(codec && codec.mimeType && codec.mimeType.toLowerCase() === "video/vp8") {
351
- Janus.safariVp8 = true;
352
- break;
353
- }
354
- }
355
- if(Janus.safariVp8) {
356
- Janus.log("This version of Safari supports VP8");
357
- } else {
358
- Janus.warn("This version of Safari does NOT support VP8: if you're using a Technology Preview, " +
359
- "try enabling the 'WebRTC VP8 codec' setting in the 'Experimental Features' Develop menu");
360
- }
361
- } else {
362
- // We do it in a very ugly way, as there's no alternative...
363
- // We create a PeerConnection to see if VP8 is in an offer
364
- var testpc = new RTCPeerConnection({}, {});
365
- testpc.createOffer({offerToReceiveVideo: true}).then(function(offer) {
366
- Janus.safariVp8 = offer.sdp.indexOf("VP8") !== -1;
367
- if(Janus.safariVp8) {
368
- Janus.log("This version of Safari supports VP8");
369
- } else {
370
- Janus.warn("This version of Safari does NOT support VP8: if you're using a Technology Preview, " +
371
- "try enabling the 'WebRTC VP8 codec' setting in the 'Experimental Features' Develop menu");
372
- }
373
- testpc.close();
374
- testpc = null;
375
- });
376
- }
377
- }
378
- Janus.initDone = true;
379
- options.callback();
380
- }
381
- };
382
-
383
- // Helper method to check whether WebRTC is supported by this browser
384
- Janus.isWebrtcSupported = function() {
385
- return window.RTCPeerConnection !== undefined && window.RTCPeerConnection !== null;
386
- };
387
- // Helper method to check whether devices can be accessed by this browser (e.g., not possible via plain HTTP)
388
- Janus.isGetUserMediaAvailable = function() {
389
- return navigator.mediaDevices !== undefined && navigator.mediaDevices !== null &&
390
- navigator.mediaDevices.getUserMedia !== undefined && navigator.mediaDevices.getUserMedia !== null;
391
- };
392
-
393
- // Helper method to create random identifiers (e.g., transaction)
394
- Janus.randomString = function(len) {
395
- var charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
396
- var randomString = '';
397
- for (var i = 0; i < len; i++) {
398
- var randomPoz = Math.floor(Math.random() * charSet.length);
399
- randomString += charSet.substring(randomPoz,randomPoz+1);
400
- }
401
- return randomString;
402
- }
403
-
404
-
405
- function Janus(gatewayCallbacks) {
406
- if(Janus.initDone === undefined) {
407
- gatewayCallbacks.error("Library not initialized");
408
- return {};
409
- }
410
- if(!Janus.isWebrtcSupported()) {
411
- gatewayCallbacks.error("WebRTC not supported by this browser");
412
- return {};
413
- }
414
- Janus.log("Library initialized: " + Janus.initDone);
415
- gatewayCallbacks = gatewayCallbacks || {};
416
- gatewayCallbacks.success = (typeof gatewayCallbacks.success == "function") ? gatewayCallbacks.success : Janus.noop;
417
- gatewayCallbacks.error = (typeof gatewayCallbacks.error == "function") ? gatewayCallbacks.error : Janus.noop;
418
- gatewayCallbacks.destroyed = (typeof gatewayCallbacks.destroyed == "function") ? gatewayCallbacks.destroyed : Janus.noop;
419
- if(gatewayCallbacks.server === null || gatewayCallbacks.server === undefined) {
420
- gatewayCallbacks.error("Invalid server url");
421
- return {};
422
- }
423
- var websockets = false;
424
- var ws = null;
425
- var wsHandlers = {};
426
- var wsKeepaliveTimeoutId = null;
427
-
428
- var servers = null, serversIndex = 0;
429
- var server = gatewayCallbacks.server;
430
- if(Janus.isArray(server)) {
431
- Janus.log("Multiple servers provided (" + server.length + "), will use the first that works");
432
- server = null;
433
- servers = gatewayCallbacks.server;
434
- Janus.debug(servers);
435
- } else {
436
- if(server.indexOf("ws") === 0) {
437
- websockets = true;
438
- Janus.log("Using WebSockets to contact Janus: " + server);
439
- } else {
440
- websockets = false;
441
- Janus.log("Using REST API to contact Janus: " + server);
442
- }
443
- }
444
- var iceServers = gatewayCallbacks.iceServers;
445
- if(iceServers === undefined || iceServers === null)
446
- iceServers = [{urls: "stun:stun.l.google.com:19302"}];
447
- var iceTransportPolicy = gatewayCallbacks.iceTransportPolicy;
448
- var bundlePolicy = gatewayCallbacks.bundlePolicy;
449
- // Whether IPv6 candidates should be gathered
450
- var ipv6Support = gatewayCallbacks.ipv6;
451
- if(ipv6Support === undefined || ipv6Support === null)
452
- ipv6Support = false;
453
- // Whether we should enable the withCredentials flag for XHR requests
454
- var withCredentials = false;
455
- if(gatewayCallbacks.withCredentials !== undefined && gatewayCallbacks.withCredentials !== null)
456
- withCredentials = gatewayCallbacks.withCredentials === true;
457
- // Optional max events
458
- var maxev = 10;
459
- if(gatewayCallbacks.max_poll_events !== undefined && gatewayCallbacks.max_poll_events !== null)
460
- maxev = gatewayCallbacks.max_poll_events;
461
- if(maxev < 1)
462
- maxev = 1;
463
- // Token to use (only if the token based authentication mechanism is enabled)
464
- var token = null;
465
- if(gatewayCallbacks.token !== undefined && gatewayCallbacks.token !== null)
466
- token = gatewayCallbacks.token;
467
- // API secret to use (only if the shared API secret is enabled)
468
- var apisecret = null;
469
- if(gatewayCallbacks.apisecret !== undefined && gatewayCallbacks.apisecret !== null)
470
- apisecret = gatewayCallbacks.apisecret;
471
- // Whether we should destroy this session when onbeforeunload is called
472
- this.destroyOnUnload = true;
473
- if(gatewayCallbacks.destroyOnUnload !== undefined && gatewayCallbacks.destroyOnUnload !== null)
474
- this.destroyOnUnload = (gatewayCallbacks.destroyOnUnload === true);
475
- // Some timeout-related values
476
- var keepAlivePeriod = 25000;
477
- if(gatewayCallbacks.keepAlivePeriod !== undefined && gatewayCallbacks.keepAlivePeriod !== null)
478
- keepAlivePeriod = gatewayCallbacks.keepAlivePeriod;
479
- if(isNaN(keepAlivePeriod))
480
- keepAlivePeriod = 25000;
481
- var longPollTimeout = 60000;
482
- if(gatewayCallbacks.longPollTimeout !== undefined && gatewayCallbacks.longPollTimeout !== null)
483
- longPollTimeout = gatewayCallbacks.longPollTimeout;
484
- if(isNaN(longPollTimeout))
485
- longPollTimeout = 60000;
486
-
487
- var connected = false;
488
- var sessionId = null;
489
- var pluginHandles = {};
490
- var that = this;
491
- var retries = 0;
492
- var transactions = {};
493
- createSession(gatewayCallbacks);
494
-
495
- // Public methods
496
- this.getServer = function() { return server; };
497
- this.isConnected = function() { return connected; };
498
- this.reconnect = function(callbacks) {
499
- callbacks = callbacks || {};
500
- callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : Janus.noop;
501
- callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : Janus.noop;
502
- callbacks["reconnect"] = true;
503
- createSession(callbacks);
504
- };
505
- this.getSessionId = function() { return sessionId; };
506
- this.destroy = function(callbacks) { destroySession(callbacks); };
507
- this.attach = function(callbacks) { createHandle(callbacks); };
508
-
509
- function eventHandler() {
510
- if(sessionId == null)
511
- return;
512
- Janus.debug('Long poll...');
513
- if(!connected) {
514
- Janus.warn("Is the server down? (connected=false)");
515
- return;
516
- }
517
- var longpoll = server + "/" + sessionId + "?rid=" + new Date().getTime();
518
- if(maxev !== undefined && maxev !== null)
519
- longpoll = longpoll + "&maxev=" + maxev;
520
- if(token !== null && token !== undefined)
521
- longpoll = longpoll + "&token=" + encodeURIComponent(token);
522
- if(apisecret !== null && apisecret !== undefined)
523
- longpoll = longpoll + "&apisecret=" + encodeURIComponent(apisecret);
524
- Janus.httpAPICall(longpoll, {
525
- verb: 'GET',
526
- withCredentials: withCredentials,
527
- success: handleEvent,
528
- timeout: longPollTimeout,
529
- error: function(textStatus, errorThrown) {
530
- Janus.error(textStatus + ":", errorThrown);
531
- retries++;
532
- if(retries > 3) {
533
- // Did we just lose the server? :-(
534
- connected = false;
535
- gatewayCallbacks.error("Lost connection to the server (is it down?)");
536
- return;
537
- }
538
- eventHandler();
539
- }
540
- });
541
- }
542
-
543
- // Private event handler: this will trigger plugin callbacks, if set
544
- function handleEvent(json, skipTimeout) {
545
- retries = 0;
546
- if(!websockets && sessionId !== undefined && sessionId !== null && skipTimeout !== true)
547
- eventHandler();
548
- if(!websockets && Janus.isArray(json)) {
549
- // We got an array: it means we passed a maxev > 1, iterate on all objects
550
- for(var i=0; i<json.length; i++) {
551
- handleEvent(json[i], true);
552
- }
553
- return;
554
- }
555
- if(json["janus"] === "keepalive") {
556
- // Nothing happened
557
- Janus.vdebug("Got a keepalive on session " + sessionId);
558
- return;
559
- } else if(json["janus"] === "ack") {
560
- // Just an ack, we can probably ignore
561
- Janus.debug("Got an ack on session " + sessionId);
562
- Janus.debug(json);
563
- var transaction = json["transaction"];
564
- if(transaction !== null && transaction !== undefined) {
565
- var reportSuccess = transactions[transaction];
566
- if(reportSuccess !== null && reportSuccess !== undefined) {
567
- reportSuccess(json);
568
- }
569
- delete transactions[transaction];
570
- }
571
- return;
572
- } else if(json["janus"] === "success") {
573
- // Success!
574
- Janus.debug("Got a success on session " + sessionId);
575
- Janus.debug(json);
576
- var transaction = json["transaction"];
577
- if(transaction !== null && transaction !== undefined) {
578
- var reportSuccess = transactions[transaction];
579
- if(reportSuccess !== null && reportSuccess !== undefined) {
580
- reportSuccess(json);
581
- }
582
- delete transactions[transaction];
583
- }
584
- return;
585
- } else if(json["janus"] === "trickle") {
586
- // We got a trickle candidate from Janus
587
- var sender = json["sender"];
588
- if(sender === undefined || sender === null) {
589
- Janus.warn("Missing sender...");
590
- return;
591
- }
592
- var pluginHandle = pluginHandles[sender];
593
- if(pluginHandle === undefined || pluginHandle === null) {
594
- Janus.debug("This handle is not attached to this session");
595
- return;
596
- }
597
- var candidate = json["candidate"];
598
- Janus.debug("Got a trickled candidate on session " + sessionId);
599
- Janus.debug(candidate);
600
- var config = pluginHandle.webrtcStuff;
601
- if(config.pc && config.remoteSdp) {
602
- // Add candidate right now
603
- Janus.debug("Adding remote candidate:", candidate);
604
- if(!candidate || candidate.completed === true) {
605
- // end-of-candidates
606
- config.pc.addIceCandidate();
607
- } else {
608
- // New candidate
609
- config.pc.addIceCandidate(candidate);
610
- }
611
- } else {
612
- // We didn't do setRemoteDescription (trickle got here before the offer?)
613
- Janus.debug("We didn't do setRemoteDescription (trickle got here before the offer?), caching candidate");
614
- if(!config.candidates)
615
- config.candidates = [];
616
- config.candidates.push(candidate);
617
- Janus.debug(config.candidates);
618
- }
619
- } else if(json["janus"] === "webrtcup") {
620
- // The PeerConnection with the server is up! Notify this
621
- Janus.debug("Got a webrtcup event on session " + sessionId);
622
- Janus.debug(json);
623
- var sender = json["sender"];
624
- if(sender === undefined || sender === null) {
625
- Janus.warn("Missing sender...");
626
- return;
627
- }
628
- var pluginHandle = pluginHandles[sender];
629
- if(pluginHandle === undefined || pluginHandle === null) {
630
- Janus.debug("This handle is not attached to this session");
631
- return;
632
- }
633
- pluginHandle.webrtcState(true);
634
- return;
635
- } else if(json["janus"] === "hangup") {
636
- // A plugin asked the core to hangup a PeerConnection on one of our handles
637
- Janus.debug("Got a hangup event on session " + sessionId);
638
- Janus.debug(json);
639
- var sender = json["sender"];
640
- if(sender === undefined || sender === null) {
641
- Janus.warn("Missing sender...");
642
- return;
643
- }
644
- var pluginHandle = pluginHandles[sender];
645
- if(pluginHandle === undefined || pluginHandle === null) {
646
- Janus.debug("This handle is not attached to this session");
647
- return;
648
- }
649
- pluginHandle.webrtcState(false, json["reason"]);
650
- pluginHandle.hangup();
651
- } else if(json["janus"] === "detached") {
652
- // A plugin asked the core to detach one of our handles
653
- Janus.debug("Got a detached event on session " + sessionId);
654
- Janus.debug(json);
655
- var sender = json["sender"];
656
- if(sender === undefined || sender === null) {
657
- Janus.warn("Missing sender...");
658
- return;
659
- }
660
- var pluginHandle = pluginHandles[sender];
661
- if(pluginHandle === undefined || pluginHandle === null) {
662
- // Don't warn here because destroyHandle causes this situation.
663
- return;
664
- }
665
- pluginHandle.detached = true;
666
- pluginHandle.ondetached();
667
- pluginHandle.detach();
668
- } else if(json["janus"] === "media") {
669
- // Media started/stopped flowing
670
- Janus.debug("Got a media event on session " + sessionId);
671
- Janus.debug(json);
672
- var sender = json["sender"];
673
- if(sender === undefined || sender === null) {
674
- Janus.warn("Missing sender...");
675
- return;
676
- }
677
- var pluginHandle = pluginHandles[sender];
678
- if(pluginHandle === undefined || pluginHandle === null) {
679
- Janus.debug("This handle is not attached to this session");
680
- return;
681
- }
682
- pluginHandle.mediaState(json["type"], json["receiving"]);
683
- } else if(json["janus"] === "slowlink") {
684
- Janus.debug("Got a slowlink event on session " + sessionId);
685
- Janus.debug(json);
686
- // Trouble uplink or downlink
687
- var sender = json["sender"];
688
- if(sender === undefined || sender === null) {
689
- Janus.warn("Missing sender...");
690
- return;
691
- }
692
- var pluginHandle = pluginHandles[sender];
693
- if(pluginHandle === undefined || pluginHandle === null) {
694
- Janus.debug("This handle is not attached to this session");
695
- return;
696
- }
697
- pluginHandle.slowLink(json["uplink"], json["nacks"]);
698
- } else if(json["janus"] === "error") {
699
- // Oops, something wrong happened
700
- Janus.error("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
701
- Janus.debug(json);
702
- var transaction = json["transaction"];
703
- if(transaction !== null && transaction !== undefined) {
704
- var reportSuccess = transactions[transaction];
705
- if(reportSuccess !== null && reportSuccess !== undefined) {
706
- reportSuccess(json);
707
- }
708
- delete transactions[transaction];
709
- }
710
- return;
711
- } else if(json["janus"] === "event") {
712
- Janus.debug("Got a plugin event on session " + sessionId);
713
- Janus.debug(json);
714
- var sender = json["sender"];
715
- if(sender === undefined || sender === null) {
716
- Janus.warn("Missing sender...");
717
- return;
718
- }
719
- var plugindata = json["plugindata"];
720
- if(plugindata === undefined || plugindata === null) {
721
- Janus.warn("Missing plugindata...");
722
- return;
723
- }
724
- Janus.debug(" -- Event is coming from " + sender + " (" + plugindata["plugin"] + ")");
725
- var data = plugindata["data"];
726
- Janus.debug(data);
727
- var pluginHandle = pluginHandles[sender];
728
- if(pluginHandle === undefined || pluginHandle === null) {
729
- Janus.warn("This handle is not attached to this session");
730
- return;
731
- }
732
- var jsep = json["jsep"];
733
- if(jsep !== undefined && jsep !== null) {
734
- Janus.debug("Handling SDP as well...");
735
- Janus.debug(jsep);
736
- }
737
- var callback = pluginHandle.onmessage;
738
- if(callback !== null && callback !== undefined) {
739
- Janus.debug("Notifying application...");
740
- // Send to callback specified when attaching plugin handle
741
- callback(data, jsep);
742
- } else {
743
- // Send to generic callback (?)
744
- Janus.debug("No provided notification callback");
745
- }
746
- } else if(json["janus"] === "timeout") {
747
- Janus.error("Timeout on session " + sessionId);
748
- Janus.debug(json);
749
- if (websockets) {
750
- ws.close(3504, "Gateway timeout");
751
- }
752
- return;
753
- } else {
754
- Janus.warn("Unknown message/event '" + json["janus"] + "' on session " + sessionId);
755
- Janus.debug(json);
756
- }
757
- }
758
-
759
- // Private helper to send keep-alive messages on WebSockets
760
- function keepAlive() {
761
- if(server === null || !websockets || !connected)
762
- return;
763
- wsKeepaliveTimeoutId = setTimeout(keepAlive, keepAlivePeriod);
764
- var request = { "janus": "keepalive", "session_id": sessionId, "transaction": Janus.randomString(12) };
765
- if(token !== null && token !== undefined)
766
- request["token"] = token;
767
- if(apisecret !== null && apisecret !== undefined)
768
- request["apisecret"] = apisecret;
769
- ws.send(JSON.stringify(request));
770
- }
771
-
772
- // Private method to create a session
773
- function createSession(callbacks) {
774
- var transaction = Janus.randomString(12);
775
- var request = { "janus": "create", "transaction": transaction };
776
- if(callbacks["reconnect"]) {
777
- // We're reconnecting, claim the session
778
- connected = false;
779
- request["janus"] = "claim";
780
- request["session_id"] = sessionId;
781
- // If we were using websockets, ignore the old connection
782
- if(ws) {
783
- ws.onopen = null;
784
- ws.onerror = null;
785
- ws.onclose = null;
786
- if(wsKeepaliveTimeoutId) {
787
- clearTimeout(wsKeepaliveTimeoutId);
788
- wsKeepaliveTimeoutId = null;
789
- }
790
- }
791
- }
792
- if(token !== null && token !== undefined)
793
- request["token"] = token;
794
- if(apisecret !== null && apisecret !== undefined)
795
- request["apisecret"] = apisecret;
796
- if(server === null && Janus.isArray(servers)) {
797
- // We still need to find a working server from the list we were given
798
- server = servers[serversIndex];
799
- if(server.indexOf("ws") === 0) {
800
- websockets = true;
801
- Janus.log("Server #" + (serversIndex+1) + ": trying WebSockets to contact Janus (" + server + ")");
802
- } else {
803
- websockets = false;
804
- Janus.log("Server #" + (serversIndex+1) + ": trying REST API to contact Janus (" + server + ")");
805
- }
806
- }
807
- if(websockets) {
808
- ws = Janus.newWebSocket(server, 'janus-protocol');
809
- wsHandlers = {
810
- 'error': function() {
811
- Janus.error("Error connecting to the Janus WebSockets server... " + server);
812
- if (Janus.isArray(servers) && !callbacks["reconnect"]) {
813
- serversIndex++;
814
- if (serversIndex == servers.length) {
815
- // We tried all the servers the user gave us and they all failed
816
- callbacks.error("Error connecting to any of the provided Janus servers: Is the server down?");
817
- return;
818
- }
819
- // Let's try the next server
820
- server = null;
821
- setTimeout(function() {
822
- createSession(callbacks);
823
- }, 200);
824
- return;
825
- }
826
- callbacks.error("Error connecting to the Janus WebSockets server: Is the server down?");
827
- },
828
-
829
- 'open': function() {
830
- // We need to be notified about the success
831
- transactions[transaction] = function(json) {
832
- Janus.debug(json);
833
- if (json["janus"] !== "success") {
834
- Janus.error("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
835
- callbacks.error(json["error"].reason);
836
- return;
837
- }
838
- wsKeepaliveTimeoutId = setTimeout(keepAlive, keepAlivePeriod);
839
- connected = true;
840
- sessionId = json["session_id"] ? json["session_id"] : json.data["id"];
841
- if(callbacks["reconnect"]) {
842
- Janus.log("Claimed session: " + sessionId);
843
- } else {
844
- Janus.log("Created session: " + sessionId);
845
- }
846
- Janus.sessions[sessionId] = that;
847
- callbacks.success();
848
- };
849
- ws.send(JSON.stringify(request));
850
- },
851
-
852
- 'message': function(event) {
853
- handleEvent(JSON.parse(event.data));
854
- },
855
-
856
- 'close': function() {
857
- if (server === null || !connected) {
858
- return;
859
- }
860
- connected = false;
861
- // FIXME What if this is called when the page is closed?
862
- gatewayCallbacks.error("Lost connection to the server (is it down?)");
863
- }
864
- };
865
-
866
- for(var eventName in wsHandlers) {
867
- ws.addEventListener(eventName, wsHandlers[eventName]);
868
- }
869
-
870
- return;
871
- }
872
- Janus.httpAPICall(server, {
873
- verb: 'POST',
874
- withCredentials: withCredentials,
875
- body: request,
876
- success: function(json) {
877
- Janus.debug(json);
878
- if(json["janus"] !== "success") {
879
- Janus.error("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
880
- callbacks.error(json["error"].reason);
881
- return;
882
- }
883
- connected = true;
884
- sessionId = json["session_id"] ? json["session_id"] : json.data["id"];
885
- if(callbacks["reconnect"]) {
886
- Janus.log("Claimed session: " + sessionId);
887
- } else {
888
- Janus.log("Created session: " + sessionId);
889
- }
890
- Janus.sessions[sessionId] = that;
891
- eventHandler();
892
- callbacks.success();
893
- },
894
- error: function(textStatus, errorThrown) {
895
- Janus.error(textStatus + ":", errorThrown); // FIXME
896
- if(Janus.isArray(servers) && !callbacks["reconnect"]) {
897
- serversIndex++;
898
- if(serversIndex == servers.length) {
899
- // We tried all the servers the user gave us and they all failed
900
- callbacks.error("Error connecting to any of the provided Janus servers: Is the server down?");
901
- return;
902
- }
903
- // Let's try the next server
904
- server = null;
905
- setTimeout(function() { createSession(callbacks); }, 200);
906
- return;
907
- }
908
- if(errorThrown === "")
909
- callbacks.error(textStatus + ": Is the server down?");
910
- else
911
- callbacks.error(textStatus + ": " + errorThrown);
912
- }
913
- });
914
- }
915
-
916
- // Private method to destroy a session
917
- function destroySession(callbacks) {
918
- callbacks = callbacks || {};
919
- // FIXME This method triggers a success even when we fail
920
- callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : Janus.noop;
921
- var asyncRequest = true;
922
- if(callbacks.asyncRequest !== undefined && callbacks.asyncRequest !== null)
923
- asyncRequest = (callbacks.asyncRequest === true);
924
- var notifyDestroyed = true;
925
- if(callbacks.notifyDestroyed !== undefined && callbacks.notifyDestroyed !== null)
926
- notifyDestroyed = (callbacks.notifyDestroyed === true);
927
- Janus.log("Destroying session " + sessionId + " (async=" + asyncRequest + ")");
928
- if(!connected) {
929
- Janus.warn("Is the server down? (connected=false)");
930
- callbacks.success();
931
- return;
932
- }
933
- if(sessionId === undefined || sessionId === null) {
934
- Janus.warn("No session to destroy");
935
- callbacks.success();
936
- if(notifyDestroyed)
937
- gatewayCallbacks.destroyed();
938
- return;
939
- }
940
- delete Janus.sessions[sessionId];
941
- // No need to destroy all handles first, Janus will do that itself
942
- var request = { "janus": "destroy", "transaction": Janus.randomString(12) };
943
- if(token !== null && token !== undefined)
944
- request["token"] = token;
945
- if(apisecret !== null && apisecret !== undefined)
946
- request["apisecret"] = apisecret;
947
- if(websockets) {
948
- request["session_id"] = sessionId;
949
-
950
- var unbindWebSocket = function() {
951
- for(var eventName in wsHandlers) {
952
- ws.removeEventListener(eventName, wsHandlers[eventName]);
953
- }
954
- ws.removeEventListener('message', onUnbindMessage);
955
- ws.removeEventListener('error', onUnbindError);
956
- if(wsKeepaliveTimeoutId) {
957
- clearTimeout(wsKeepaliveTimeoutId);
958
- }
959
- ws.close();
960
- };
961
-
962
- var onUnbindMessage = function(event){
963
- var data = JSON.parse(event.data);
964
- if(data.session_id == request.session_id && data.transaction == request.transaction) {
965
- unbindWebSocket();
966
- callbacks.success();
967
- if(notifyDestroyed)
968
- gatewayCallbacks.destroyed();
969
- }
970
- };
971
- var onUnbindError = function(event) {
972
- unbindWebSocket();
973
- callbacks.error("Failed to destroy the server: Is the server down?");
974
- if(notifyDestroyed)
975
- gatewayCallbacks.destroyed();
976
- };
977
-
978
- ws.addEventListener('message', onUnbindMessage);
979
- ws.addEventListener('error', onUnbindError);
980
-
981
- ws.send(JSON.stringify(request));
982
- return;
983
- }
984
- Janus.httpAPICall(server + "/" + sessionId, {
985
- verb: 'POST',
986
- async: asyncRequest, // Sometimes we need false here, or destroying in onbeforeunload won't work
987
- withCredentials: withCredentials,
988
- body: request,
989
- success: function(json) {
990
- Janus.log("Destroyed session:");
991
- Janus.debug(json);
992
- sessionId = null;
993
- connected = false;
994
- if(json["janus"] !== "success") {
995
- Janus.error("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
996
- }
997
- callbacks.success();
998
- if(notifyDestroyed)
999
- gatewayCallbacks.destroyed();
1000
- },
1001
- error: function(textStatus, errorThrown) {
1002
- Janus.error(textStatus + ":", errorThrown); // FIXME
1003
- // Reset everything anyway
1004
- sessionId = null;
1005
- connected = false;
1006
- callbacks.success();
1007
- if(notifyDestroyed)
1008
- gatewayCallbacks.destroyed();
1009
- }
1010
- });
1011
- }
1012
-
1013
- // Private method to create a plugin handle
1014
- function createHandle(callbacks) {
1015
- callbacks = callbacks || {};
1016
- callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : Janus.noop;
1017
- callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : Janus.noop;
1018
- callbacks.consentDialog = (typeof callbacks.consentDialog == "function") ? callbacks.consentDialog : Janus.noop;
1019
- callbacks.iceState = (typeof callbacks.iceState == "function") ? callbacks.iceState : Janus.noop;
1020
- callbacks.mediaState = (typeof callbacks.mediaState == "function") ? callbacks.mediaState : Janus.noop;
1021
- callbacks.webrtcState = (typeof callbacks.webrtcState == "function") ? callbacks.webrtcState : Janus.noop;
1022
- callbacks.slowLink = (typeof callbacks.slowLink == "function") ? callbacks.slowLink : Janus.noop;
1023
- callbacks.onmessage = (typeof callbacks.onmessage == "function") ? callbacks.onmessage : Janus.noop;
1024
- callbacks.onlocalstream = (typeof callbacks.onlocalstream == "function") ? callbacks.onlocalstream : Janus.noop;
1025
- callbacks.onremotestream = (typeof callbacks.onremotestream == "function") ? callbacks.onremotestream : Janus.noop;
1026
- callbacks.ondata = (typeof callbacks.ondata == "function") ? callbacks.ondata : Janus.noop;
1027
- callbacks.ondataopen = (typeof callbacks.ondataopen == "function") ? callbacks.ondataopen : Janus.noop;
1028
- callbacks.oncleanup = (typeof callbacks.oncleanup == "function") ? callbacks.oncleanup : Janus.noop;
1029
- callbacks.ondetached = (typeof callbacks.ondetached == "function") ? callbacks.ondetached : Janus.noop;
1030
- if(!connected) {
1031
- Janus.warn("Is the server down? (connected=false)");
1032
- callbacks.error("Is the server down? (connected=false)");
1033
- return;
1034
- }
1035
- var plugin = callbacks.plugin;
1036
- if(plugin === undefined || plugin === null) {
1037
- Janus.error("Invalid plugin");
1038
- callbacks.error("Invalid plugin");
1039
- return;
1040
- }
1041
- var opaqueId = callbacks.opaqueId;
1042
- var handleToken = callbacks.token ? callbacks.token : token;
1043
- var transaction = Janus.randomString(12);
1044
- var request = { "janus": "attach", "plugin": plugin, "opaque_id": opaqueId, "transaction": transaction };
1045
- if(handleToken !== null && handleToken !== undefined)
1046
- request["token"] = handleToken;
1047
- if(apisecret !== null && apisecret !== undefined)
1048
- request["apisecret"] = apisecret;
1049
- if(websockets) {
1050
- transactions[transaction] = function(json) {
1051
- Janus.debug(json);
1052
- if(json["janus"] !== "success") {
1053
- Janus.error("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
1054
- callbacks.error("Ooops: " + json["error"].code + " " + json["error"].reason);
1055
- return;
1056
- }
1057
- var handleId = json.data["id"];
1058
- Janus.log("Created handle: " + handleId);
1059
- var pluginHandle =
1060
- {
1061
- session : that,
1062
- plugin : plugin,
1063
- id : handleId,
1064
- token : handleToken,
1065
- detached : false,
1066
- webrtcStuff : {
1067
- started : false,
1068
- myStream : null,
1069
- streamExternal : false,
1070
- remoteStream : null,
1071
- mySdp : null,
1072
- mediaConstraints : null,
1073
- pc : null,
1074
- dataChannel : {},
1075
- dtmfSender : null,
1076
- trickle : true,
1077
- iceDone : false,
1078
- volume : {
1079
- value : null,
1080
- timer : null
1081
- },
1082
- bitrate : {
1083
- value : null,
1084
- bsnow : null,
1085
- bsbefore : null,
1086
- tsnow : null,
1087
- tsbefore : null,
1088
- timer : null
1089
- }
1090
- },
1091
- getId : function() { return handleId; },
1092
- getPlugin : function() { return plugin; },
1093
- getVolume : function() { return getVolume(handleId, true); },
1094
- getRemoteVolume : function() { return getVolume(handleId, true); },
1095
- getLocalVolume : function() { return getVolume(handleId, false); },
1096
- isAudioMuted : function() { return isMuted(handleId, false); },
1097
- muteAudio : function() { return mute(handleId, false, true); },
1098
- unmuteAudio : function() { return mute(handleId, false, false); },
1099
- isVideoMuted : function() { return isMuted(handleId, true); },
1100
- muteVideo : function() { return mute(handleId, true, true); },
1101
- unmuteVideo : function() { return mute(handleId, true, false); },
1102
- getBitrate : function() { return getBitrate(handleId); },
1103
- send : function(callbacks) { sendMessage(handleId, callbacks); },
1104
- data : function(callbacks) { sendData(handleId, callbacks); },
1105
- dtmf : function(callbacks) { sendDtmf(handleId, callbacks); },
1106
- consentDialog : callbacks.consentDialog,
1107
- iceState : callbacks.iceState,
1108
- mediaState : callbacks.mediaState,
1109
- webrtcState : callbacks.webrtcState,
1110
- slowLink : callbacks.slowLink,
1111
- onmessage : callbacks.onmessage,
1112
- createOffer : function(callbacks) { prepareWebrtc(handleId, true, callbacks); },
1113
- createAnswer : function(callbacks) { prepareWebrtc(handleId, false, callbacks); },
1114
- handleRemoteJsep : function(callbacks) { prepareWebrtcPeer(handleId, callbacks); },
1115
- onlocalstream : callbacks.onlocalstream,
1116
- onremotestream : callbacks.onremotestream,
1117
- ondata : callbacks.ondata,
1118
- ondataopen : callbacks.ondataopen,
1119
- oncleanup : callbacks.oncleanup,
1120
- ondetached : callbacks.ondetached,
1121
- hangup : function(sendRequest) { cleanupWebrtc(handleId, sendRequest === true); },
1122
- detach : function(callbacks) { destroyHandle(handleId, callbacks); }
1123
- }
1124
- pluginHandles[handleId] = pluginHandle;
1125
- callbacks.success(pluginHandle);
1126
- };
1127
- request["session_id"] = sessionId;
1128
- ws.send(JSON.stringify(request));
1129
- return;
1130
- }
1131
- Janus.httpAPICall(server + "/" + sessionId, {
1132
- verb: 'POST',
1133
- withCredentials: withCredentials,
1134
- body: request,
1135
- success: function(json) {
1136
- Janus.debug(json);
1137
- if(json["janus"] !== "success") {
1138
- Janus.error("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
1139
- callbacks.error("Ooops: " + json["error"].code + " " + json["error"].reason);
1140
- return;
1141
- }
1142
- var handleId = json.data["id"];
1143
- Janus.log("Created handle: " + handleId);
1144
- var pluginHandle =
1145
- {
1146
- session : that,
1147
- plugin : plugin,
1148
- id : handleId,
1149
- token : handleToken,
1150
- detached : false,
1151
- webrtcStuff : {
1152
- started : false,
1153
- myStream : null,
1154
- streamExternal : false,
1155
- remoteStream : null,
1156
- mySdp : null,
1157
- mediaConstraints : null,
1158
- pc : null,
1159
- dataChannel : {},
1160
- dtmfSender : null,
1161
- trickle : true,
1162
- iceDone : false,
1163
- volume : {
1164
- value : null,
1165
- timer : null
1166
- },
1167
- bitrate : {
1168
- value : null,
1169
- bsnow : null,
1170
- bsbefore : null,
1171
- tsnow : null,
1172
- tsbefore : null,
1173
- timer : null
1174
- }
1175
- },
1176
- getId : function() { return handleId; },
1177
- getPlugin : function() { return plugin; },
1178
- getVolume : function() { return getVolume(handleId, true); },
1179
- getRemoteVolume : function() { return getVolume(handleId, true); },
1180
- getLocalVolume : function() { return getVolume(handleId, false); },
1181
- isAudioMuted : function() { return isMuted(handleId, false); },
1182
- muteAudio : function() { return mute(handleId, false, true); },
1183
- unmuteAudio : function() { return mute(handleId, false, false); },
1184
- isVideoMuted : function() { return isMuted(handleId, true); },
1185
- muteVideo : function() { return mute(handleId, true, true); },
1186
- unmuteVideo : function() { return mute(handleId, true, false); },
1187
- getBitrate : function() { return getBitrate(handleId); },
1188
- send : function(callbacks) { sendMessage(handleId, callbacks); },
1189
- data : function(callbacks) { sendData(handleId, callbacks); },
1190
- dtmf : function(callbacks) { sendDtmf(handleId, callbacks); },
1191
- consentDialog : callbacks.consentDialog,
1192
- iceState : callbacks.iceState,
1193
- mediaState : callbacks.mediaState,
1194
- webrtcState : callbacks.webrtcState,
1195
- slowLink : callbacks.slowLink,
1196
- onmessage : callbacks.onmessage,
1197
- createOffer : function(callbacks) { prepareWebrtc(handleId, true, callbacks); },
1198
- createAnswer : function(callbacks) { prepareWebrtc(handleId, false, callbacks); },
1199
- handleRemoteJsep : function(callbacks) { prepareWebrtcPeer(handleId, callbacks); },
1200
- onlocalstream : callbacks.onlocalstream,
1201
- onremotestream : callbacks.onremotestream,
1202
- ondata : callbacks.ondata,
1203
- ondataopen : callbacks.ondataopen,
1204
- oncleanup : callbacks.oncleanup,
1205
- ondetached : callbacks.ondetached,
1206
- hangup : function(sendRequest) { cleanupWebrtc(handleId, sendRequest === true); },
1207
- detach : function(callbacks) { destroyHandle(handleId, callbacks); }
1208
- }
1209
- pluginHandles[handleId] = pluginHandle;
1210
- callbacks.success(pluginHandle);
1211
- },
1212
- error: function(textStatus, errorThrown) {
1213
- Janus.error(textStatus + ":", errorThrown); // FIXME
1214
- }
1215
- });
1216
- }
1217
-
1218
- // Private method to send a message
1219
- function sendMessage(handleId, callbacks) {
1220
- callbacks = callbacks || {};
1221
- callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : Janus.noop;
1222
- callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : Janus.noop;
1223
- if(!connected) {
1224
- Janus.warn("Is the server down? (connected=false)");
1225
- callbacks.error("Is the server down? (connected=false)");
1226
- return;
1227
- }
1228
- var pluginHandle = pluginHandles[handleId];
1229
- if(pluginHandle === null || pluginHandle === undefined ||
1230
- pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
1231
- Janus.warn("Invalid handle");
1232
- callbacks.error("Invalid handle");
1233
- return;
1234
- }
1235
- var message = callbacks.message;
1236
- var jsep = callbacks.jsep;
1237
- var transaction = Janus.randomString(12);
1238
- var request = { "janus": "message", "body": message, "transaction": transaction };
1239
- if(pluginHandle.token !== null && pluginHandle.token !== undefined)
1240
- request["token"] = pluginHandle.token;
1241
- if(apisecret !== null && apisecret !== undefined)
1242
- request["apisecret"] = apisecret;
1243
- if(jsep !== null && jsep !== undefined)
1244
- request.jsep = jsep;
1245
- Janus.debug("Sending message to plugin (handle=" + handleId + "):");
1246
- Janus.debug(request);
1247
- if(websockets) {
1248
- request["session_id"] = sessionId;
1249
- request["handle_id"] = handleId;
1250
- transactions[transaction] = function(json) {
1251
- Janus.debug("Message sent!");
1252
- Janus.debug(json);
1253
- if(json["janus"] === "success") {
1254
- // We got a success, must have been a synchronous transaction
1255
- var plugindata = json["plugindata"];
1256
- if(plugindata === undefined || plugindata === null) {
1257
- Janus.warn("Request succeeded, but missing plugindata...");
1258
- callbacks.success();
1259
- return;
1260
- }
1261
- Janus.log("Synchronous transaction successful (" + plugindata["plugin"] + ")");
1262
- var data = plugindata["data"];
1263
- Janus.debug(data);
1264
- callbacks.success(data);
1265
- return;
1266
- } else if(json["janus"] !== "ack") {
1267
- // Not a success and not an ack, must be an error
1268
- if(json["error"] !== undefined && json["error"] !== null) {
1269
- Janus.error("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
1270
- callbacks.error(json["error"].code + " " + json["error"].reason);
1271
- } else {
1272
- Janus.error("Unknown error"); // FIXME
1273
- callbacks.error("Unknown error");
1274
- }
1275
- return;
1276
- }
1277
- // If we got here, the plugin decided to handle the request asynchronously
1278
- callbacks.success();
1279
- };
1280
- ws.send(JSON.stringify(request));
1281
- return;
1282
- }
1283
- Janus.httpAPICall(server + "/" + sessionId + "/" + handleId, {
1284
- verb: 'POST',
1285
- withCredentials: withCredentials,
1286
- body: request,
1287
- success: function(json) {
1288
- Janus.debug("Message sent!");
1289
- Janus.debug(json);
1290
- if(json["janus"] === "success") {
1291
- // We got a success, must have been a synchronous transaction
1292
- var plugindata = json["plugindata"];
1293
- if(plugindata === undefined || plugindata === null) {
1294
- Janus.warn("Request succeeded, but missing plugindata...");
1295
- callbacks.success();
1296
- return;
1297
- }
1298
- Janus.log("Synchronous transaction successful (" + plugindata["plugin"] + ")");
1299
- var data = plugindata["data"];
1300
- Janus.debug(data);
1301
- callbacks.success(data);
1302
- return;
1303
- } else if(json["janus"] !== "ack") {
1304
- // Not a success and not an ack, must be an error
1305
- if(json["error"] !== undefined && json["error"] !== null) {
1306
- Janus.error("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
1307
- callbacks.error(json["error"].code + " " + json["error"].reason);
1308
- } else {
1309
- Janus.error("Unknown error"); // FIXME
1310
- callbacks.error("Unknown error");
1311
- }
1312
- return;
1313
- }
1314
- // If we got here, the plugin decided to handle the request asynchronously
1315
- callbacks.success();
1316
- },
1317
- error: function(textStatus, errorThrown) {
1318
- Janus.error(textStatus + ":", errorThrown); // FIXME
1319
- callbacks.error(textStatus + ": " + errorThrown);
1320
- }
1321
- });
1322
- }
1323
-
1324
- // Private method to send a trickle candidate
1325
- function sendTrickleCandidate(handleId, candidate) {
1326
- if(!connected) {
1327
- Janus.warn("Is the server down? (connected=false)");
1328
- return;
1329
- }
1330
- var pluginHandle = pluginHandles[handleId];
1331
- if(pluginHandle === null || pluginHandle === undefined ||
1332
- pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
1333
- Janus.warn("Invalid handle");
1334
- return;
1335
- }
1336
- var request = { "janus": "trickle", "candidate": candidate, "transaction": Janus.randomString(12) };
1337
- if(pluginHandle.token !== null && pluginHandle.token !== undefined)
1338
- request["token"] = pluginHandle.token;
1339
- if(apisecret !== null && apisecret !== undefined)
1340
- request["apisecret"] = apisecret;
1341
- Janus.vdebug("Sending trickle candidate (handle=" + handleId + "):");
1342
- Janus.vdebug(request);
1343
- if(websockets) {
1344
- request["session_id"] = sessionId;
1345
- request["handle_id"] = handleId;
1346
- ws.send(JSON.stringify(request));
1347
- return;
1348
- }
1349
- Janus.httpAPICall(server + "/" + sessionId + "/" + handleId, {
1350
- verb: 'POST',
1351
- withCredentials: withCredentials,
1352
- body: request,
1353
- success: function(json) {
1354
- Janus.vdebug("Candidate sent!");
1355
- Janus.vdebug(json);
1356
- if(json["janus"] !== "ack") {
1357
- Janus.error("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
1358
- return;
1359
- }
1360
- },
1361
- error: function(textStatus, errorThrown) {
1362
- Janus.error(textStatus + ":", errorThrown); // FIXME
1363
- }
1364
- });
1365
- }
1366
-
1367
- // Private method to create a data channel
1368
- function createDataChannel(handleId, dclabel, incoming, pendingText) {
1369
- var pluginHandle = pluginHandles[handleId];
1370
- if(pluginHandle === null || pluginHandle === undefined ||
1371
- pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
1372
- Janus.warn("Invalid handle");
1373
- return;
1374
- }
1375
- var config = pluginHandle.webrtcStuff;
1376
- var onDataChannelMessage = function(event) {
1377
- Janus.log('Received message on data channel:', event);
1378
- var label = event.target.label;
1379
- pluginHandle.ondata(event.data, label);
1380
- }
1381
- var onDataChannelStateChange = function(event) {
1382
- Janus.log('Received state change on data channel:', event);
1383
- var label = event.target.label;
1384
- var dcState = config.dataChannel[label] !== null ? config.dataChannel[label].readyState : "null";
1385
- Janus.log('State change on <' + label + '> data channel: ' + dcState);
1386
- if(dcState === 'open') {
1387
- // Any pending messages to send?
1388
- if(config.dataChannel[label].pending && config.dataChannel[label].pending.length > 0) {
1389
- Janus.log("Sending pending messages on <' + label + '>:", config.dataChannel[label].pending.length);
1390
- for(var i in config.dataChannel[label].pending) {
1391
- var text = config.dataChannel[label].pending[i];
1392
- Janus.log("Sending string on data channel <" + label + ">: " + text);
1393
- config.dataChannel[label].send(text);
1394
- }
1395
- config.dataChannel[label].pending = [];
1396
- }
1397
- // Notify the open data channel
1398
- pluginHandle.ondataopen(label);
1399
- }
1400
- }
1401
- var onDataChannelError = function(error) {
1402
- Janus.error('Got error on data channel:', error);
1403
- // TODO
1404
- }
1405
- if(!incoming) {
1406
- // FIXME Add options (ordered, maxRetransmits, etc.)
1407
- config.dataChannel[dclabel] = config.pc.createDataChannel(dclabel, {ordered:false});
1408
- } else {
1409
- // The channel was created by Janus
1410
- config.dataChannel[dclabel] = incoming;
1411
- }
1412
- config.dataChannel[dclabel].onmessage = onDataChannelMessage;
1413
- config.dataChannel[dclabel].onopen = onDataChannelStateChange;
1414
- config.dataChannel[dclabel].onclose = onDataChannelStateChange;
1415
- config.dataChannel[dclabel].onerror = onDataChannelError;
1416
- config.dataChannel[dclabel].pending = [];
1417
- if(pendingText)
1418
- config.dataChannel[dclabel].pending.push(pendingText);
1419
- }
1420
-
1421
- // Private method to send a data channel message
1422
- function sendData(handleId, callbacks) {
1423
- callbacks = callbacks || {};
1424
- callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : Janus.noop;
1425
- callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : Janus.noop;
1426
- var pluginHandle = pluginHandles[handleId];
1427
- if(pluginHandle === null || pluginHandle === undefined ||
1428
- pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
1429
- Janus.warn("Invalid handle");
1430
- callbacks.error("Invalid handle");
1431
- return;
1432
- }
1433
- var config = pluginHandle.webrtcStuff;
1434
- var text = callbacks.text;
1435
- if(text === null || text === undefined) {
1436
- Janus.warn("Invalid text");
1437
- callbacks.error("Invalid text");
1438
- return;
1439
- }
1440
- var label = callbacks.label ? callbacks.label : Janus.dataChanDefaultLabel;
1441
- if(!config.dataChannel[label]) {
1442
- // Create new data channel and wait for it to open
1443
- createDataChannel(handleId, label, false, text);
1444
- callbacks.success();
1445
- return;
1446
- }
1447
- if(config.dataChannel[label].readyState !== "open") {
1448
- config.dataChannel[label].pending.push(text);
1449
- callbacks.success();
1450
- return;
1451
- }
1452
- Janus.log("Sending string on data channel <" + label + ">: " + text);
1453
- config.dataChannel[label].send(text);
1454
- callbacks.success();
1455
- }
1456
-
1457
- // Private method to send a DTMF tone
1458
- function sendDtmf(handleId, callbacks) {
1459
- callbacks = callbacks || {};
1460
- callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : Janus.noop;
1461
- callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : Janus.noop;
1462
- var pluginHandle = pluginHandles[handleId];
1463
- if(pluginHandle === null || pluginHandle === undefined ||
1464
- pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
1465
- Janus.warn("Invalid handle");
1466
- callbacks.error("Invalid handle");
1467
- return;
1468
- }
1469
- var config = pluginHandle.webrtcStuff;
1470
- if(config.dtmfSender === null || config.dtmfSender === undefined) {
1471
- // Create the DTMF sender the proper way, if possible
1472
- if(config.pc !== undefined && config.pc !== null) {
1473
- var senders = config.pc.getSenders();
1474
- var audioSender = senders.find(function(sender) {
1475
- return sender.track && sender.track.kind === 'audio';
1476
- });
1477
- if(!audioSender) {
1478
- Janus.warn("Invalid DTMF configuration (no audio track)");
1479
- callbacks.error("Invalid DTMF configuration (no audio track)");
1480
- return;
1481
- }
1482
- config.dtmfSender = audioSender.dtmf;
1483
- if(config.dtmfSender) {
1484
- Janus.log("Created DTMF Sender");
1485
- config.dtmfSender.ontonechange = function(tone) { Janus.debug("Sent DTMF tone: " + tone.tone); };
1486
- }
1487
- }
1488
- if(config.dtmfSender === null || config.dtmfSender === undefined) {
1489
- Janus.warn("Invalid DTMF configuration");
1490
- callbacks.error("Invalid DTMF configuration");
1491
- return;
1492
- }
1493
- }
1494
- var dtmf = callbacks.dtmf;
1495
- if(dtmf === null || dtmf === undefined) {
1496
- Janus.warn("Invalid DTMF parameters");
1497
- callbacks.error("Invalid DTMF parameters");
1498
- return;
1499
- }
1500
- var tones = dtmf.tones;
1501
- if(tones === null || tones === undefined) {
1502
- Janus.warn("Invalid DTMF string");
1503
- callbacks.error("Invalid DTMF string");
1504
- return;
1505
- }
1506
- var duration = dtmf.duration;
1507
- if(duration === null || duration === undefined)
1508
- duration = 500; // We choose 500ms as the default duration for a tone
1509
- var gap = dtmf.gap;
1510
- if(gap === null || gap === undefined)
1511
- gap = 50; // We choose 50ms as the default gap between tones
1512
- Janus.debug("Sending DTMF string " + tones + " (duration " + duration + "ms, gap " + gap + "ms)");
1513
- config.dtmfSender.insertDTMF(tones, duration, gap);
1514
- callbacks.success();
1515
- }
1516
-
1517
- // Private method to destroy a plugin handle
1518
- function destroyHandle(handleId, callbacks) {
1519
- callbacks = callbacks || {};
1520
- callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : Janus.noop;
1521
- callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : Janus.noop;
1522
- var asyncRequest = true;
1523
- if(callbacks.asyncRequest !== undefined && callbacks.asyncRequest !== null)
1524
- asyncRequest = (callbacks.asyncRequest === true);
1525
- Janus.log("Destroying handle " + handleId + " (async=" + asyncRequest + ")");
1526
- cleanupWebrtc(handleId);
1527
- var pluginHandle = pluginHandles[handleId];
1528
- if(pluginHandle === null || pluginHandle === undefined || pluginHandle.detached) {
1529
- // Plugin was already detached by Janus, calling detach again will return a handle not found error, so just exit here
1530
- delete pluginHandles[handleId];
1531
- callbacks.success();
1532
- return;
1533
- }
1534
- if(!connected) {
1535
- Janus.warn("Is the server down? (connected=false)");
1536
- callbacks.error("Is the server down? (connected=false)");
1537
- return;
1538
- }
1539
- var request = { "janus": "detach", "transaction": Janus.randomString(12) };
1540
- if(pluginHandle.token !== null && pluginHandle.token !== undefined)
1541
- request["token"] = pluginHandle.token;
1542
- if(apisecret !== null && apisecret !== undefined)
1543
- request["apisecret"] = apisecret;
1544
- if(websockets) {
1545
- request["session_id"] = sessionId;
1546
- request["handle_id"] = handleId;
1547
- ws.send(JSON.stringify(request));
1548
- delete pluginHandles[handleId];
1549
- callbacks.success();
1550
- return;
1551
- }
1552
- Janus.httpAPICall(server + "/" + sessionId + "/" + handleId, {
1553
- verb: 'POST',
1554
- async: asyncRequest, // Sometimes we need false here, or destroying in onbeforeunload won't work
1555
- withCredentials: withCredentials,
1556
- body: request,
1557
- success: function(json) {
1558
- Janus.log("Destroyed handle:");
1559
- Janus.debug(json);
1560
- if(json["janus"] !== "success") {
1561
- Janus.error("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
1562
- }
1563
- delete pluginHandles[handleId];
1564
- callbacks.success();
1565
- },
1566
- error: function(textStatus, errorThrown) {
1567
- Janus.error(textStatus + ":", errorThrown); // FIXME
1568
- // We cleanup anyway
1569
- delete pluginHandles[handleId];
1570
- callbacks.success();
1571
- }
1572
- });
1573
- }
1574
-
1575
- // WebRTC stuff
1576
- function streamsDone(handleId, jsep, media, callbacks, stream) {
1577
- var pluginHandle = pluginHandles[handleId];
1578
- if(pluginHandle === null || pluginHandle === undefined ||
1579
- pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
1580
- Janus.warn("Invalid handle");
1581
- callbacks.error("Invalid handle");
1582
- return;
1583
- }
1584
- var config = pluginHandle.webrtcStuff;
1585
- Janus.debug("streamsDone:", stream);
1586
- if(stream) {
1587
- Janus.debug(" -- Audio tracks:", stream.getAudioTracks());
1588
- Janus.debug(" -- Video tracks:", stream.getVideoTracks());
1589
- }
1590
- // We're now capturing the new stream: check if we're updating or if it's a new thing
1591
- var addTracks = false;
1592
- if(!config.myStream || !media.update || config.streamExternal) {
1593
- config.myStream = stream;
1594
- addTracks = true;
1595
- } else {
1596
- // We only need to update the existing stream
1597
- if(((!media.update && isAudioSendEnabled(media)) || (media.update && (media.addAudio || media.replaceAudio))) &&
1598
- stream.getAudioTracks() && stream.getAudioTracks().length) {
1599
- config.myStream.addTrack(stream.getAudioTracks()[0]);
1600
- if((Janus.webRTCAdapter.browserDetails.browser === "firefox" && Janus.webRTCAdapter.browserDetails.version >= 59) ||
1601
- (Janus.webRTCAdapter.browserDetails.browser === "safari" && window.RTCRtpSender.prototype.replaceTrack) ||
1602
- (Janus.webRTCAdapter.browserDetails.browser === "chrome" && Janus.webRTCAdapter.browserDetails.version >= 72)) {
1603
- // Use Transceivers
1604
- Janus.log((media.replaceAudio ? "Replacing" : "Adding") + " audio track:", stream.getAudioTracks()[0]);
1605
- var audioTransceiver = null;
1606
- var transceivers = config.pc.getTransceivers();
1607
- if(transceivers && transceivers.length > 0) {
1608
- for(var i in transceivers) {
1609
- var t = transceivers[i];
1610
- if((t.sender && t.sender.track && t.sender.track.kind === "audio") ||
1611
- (t.receiver && t.receiver.track && t.receiver.track.kind === "audio")) {
1612
- audioTransceiver = t;
1613
- break;
1614
- }
1615
- }
1616
- }
1617
- if(audioTransceiver && audioTransceiver.sender) {
1618
- audioTransceiver.sender.replaceTrack(stream.getAudioTracks()[0]);
1619
- } else {
1620
- config.pc.addTrack(stream.getAudioTracks()[0], stream);
1621
- }
1622
- } else {
1623
- Janus.log((media.replaceAudio ? "Replacing" : "Adding") + " audio track:", stream.getAudioTracks()[0]);
1624
- config.pc.addTrack(stream.getAudioTracks()[0], stream);
1625
- }
1626
- }
1627
- if(((!media.update && isVideoSendEnabled(media)) || (media.update && (media.addVideo || media.replaceVideo))) &&
1628
- stream.getVideoTracks() && stream.getVideoTracks().length) {
1629
- config.myStream.addTrack(stream.getVideoTracks()[0]);
1630
- if((Janus.webRTCAdapter.browserDetails.browser === "firefox" && Janus.webRTCAdapter.browserDetails.version >= 59) ||
1631
- (Janus.webRTCAdapter.browserDetails.browser === "safari" && window.RTCRtpSender.prototype.replaceTrack) ||
1632
- (Janus.webRTCAdapter.browserDetails.browser === "chrome" && Janus.webRTCAdapter.browserDetails.version >= 72)) {
1633
- // Use Transceivers
1634
- Janus.log((media.replaceVideo ? "Replacing" : "Adding") + " video track:", stream.getVideoTracks()[0]);
1635
- var videoTransceiver = null;
1636
- var transceivers = config.pc.getTransceivers();
1637
- if(transceivers && transceivers.length > 0) {
1638
- for(var i in transceivers) {
1639
- var t = transceivers[i];
1640
- if((t.sender && t.sender.track && t.sender.track.kind === "video") ||
1641
- (t.receiver && t.receiver.track && t.receiver.track.kind === "video")) {
1642
- videoTransceiver = t;
1643
- break;
1644
- }
1645
- }
1646
- }
1647
- if(videoTransceiver && videoTransceiver.sender) {
1648
- videoTransceiver.sender.replaceTrack(stream.getVideoTracks()[0]);
1649
- } else {
1650
- config.pc.addTrack(stream.getVideoTracks()[0], stream);
1651
- }
1652
- } else {
1653
- Janus.log((media.replaceVideo ? "Replacing" : "Adding") + " video track:", stream.getVideoTracks()[0]);
1654
- config.pc.addTrack(stream.getVideoTracks()[0], stream);
1655
- }
1656
- }
1657
- }
1658
- // If we still need to create a PeerConnection, let's do that
1659
- if(!config.pc) {
1660
- var pc_config = {"iceServers": iceServers, "iceTransportPolicy": iceTransportPolicy, "bundlePolicy": bundlePolicy};
1661
- if(Janus.webRTCAdapter.browserDetails.browser === "chrome") {
1662
- // For Chrome versions before 72, we force a plan-b semantic, and unified-plan otherwise
1663
- pc_config["sdpSemantics"] = (Janus.webRTCAdapter.browserDetails.version < 72) ? "plan-b" : "unified-plan";
1664
- }
1665
- var pc_constraints = {
1666
- "optional": [{"DtlsSrtpKeyAgreement": true}]
1667
- };
1668
- if(ipv6Support === true) {
1669
- pc_constraints.optional.push({"googIPv6":true});
1670
- }
1671
- // Any custom constraint to add?
1672
- if(callbacks.rtcConstraints && typeof callbacks.rtcConstraints === 'object') {
1673
- Janus.debug("Adding custom PeerConnection constraints:", callbacks.rtcConstraints);
1674
- for(var i in callbacks.rtcConstraints) {
1675
- pc_constraints.optional.push(callbacks.rtcConstraints[i]);
1676
- }
1677
- }
1678
- if(Janus.webRTCAdapter.browserDetails.browser === "edge") {
1679
- // This is Edge, enable BUNDLE explicitly
1680
- pc_config.bundlePolicy = "max-bundle";
1681
- }
1682
- Janus.log("Creating PeerConnection");
1683
- Janus.debug(pc_constraints);
1684
- config.pc = new RTCPeerConnection(pc_config, pc_constraints);
1685
- Janus.debug(config.pc);
1686
- if(config.pc.getStats) { // FIXME
1687
- config.volume = {};
1688
- config.bitrate.value = "0 kbits/sec";
1689
- }
1690
- Janus.log("Preparing local SDP and gathering candidates (trickle=" + config.trickle + ")");
1691
- config.pc.oniceconnectionstatechange = function(e) {
1692
- if(config.pc)
1693
- pluginHandle.iceState(config.pc.iceConnectionState);
1694
- };
1695
- config.pc.onicecandidate = function(event) {
1696
- if (event.candidate == null ||
1697
- (Janus.webRTCAdapter.browserDetails.browser === 'edge' && event.candidate.candidate.indexOf('endOfCandidates') > 0)) {
1698
- Janus.log("End of candidates.");
1699
- config.iceDone = true;
1700
- if(config.trickle === true) {
1701
- // Notify end of candidates
1702
- sendTrickleCandidate(handleId, {"completed": true});
1703
- } else {
1704
- // No trickle, time to send the complete SDP (including all candidates)
1705
- sendSDP(handleId, callbacks);
1706
- }
1707
- } else {
1708
- // JSON.stringify doesn't work on some WebRTC objects anymore
1709
- // See https://code.google.com/p/chromium/issues/detail?id=467366
1710
-
1711
- var myStr = event.candidate.candidate;
1712
- var arr1 = myStr.split(" ");
1713
-
1714
- //判断是否是IPV4
1715
- var exp = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
1716
- var flag = arr1[4].match(exp);
1717
- if(!flag || flag == ""){
1718
- arr1[4] = '127.0.0.1';
1719
- }
1720
- var String = arr1.join(' ');
1721
-
1722
- var candidate = {
1723
- "candidate": String,
1724
- "sdpMid": event.candidate.sdpMid,
1725
- "sdpMLineIndex": event.candidate.sdpMLineIndex
1726
- };
1727
- if(config.trickle === true) {
1728
- // Send candidate
1729
- sendTrickleCandidate(handleId, candidate);
1730
- }
1731
- }
1732
- };
1733
- config.pc.ontrack = function(event) {
1734
- Janus.log("Handling Remote Track");
1735
- Janus.debug(event);
1736
- if(!event.streams)
1737
- return;
1738
- config.remoteStream = event.streams[0];
1739
- pluginHandle.onremotestream(config.remoteStream);
1740
- if(event.track && !event.track.onended) {
1741
- Janus.log("Adding onended callback to track:", event.track);
1742
- event.track.onended = function(ev) {
1743
- Janus.log("Remote track removed:", ev);
1744
- if(config.remoteStream) {
1745
- config.remoteStream.removeTrack(ev.target);
1746
- pluginHandle.onremotestream(config.remoteStream);
1747
- }
1748
- }
1749
- }
1750
- };
1751
- }
1752
- if(addTracks && stream !== null && stream !== undefined) {
1753
- Janus.log('Adding local stream');
1754
- var simulcast2 = callbacks.simulcast2 === true ? true : false;
1755
- stream.getTracks().forEach(function(track) {
1756
- Janus.log('Adding local track:', track);
1757
- if(!simulcast2) {
1758
- config.pc.addTrack(track, stream);
1759
- } else {
1760
- if(track.kind === "audio") {
1761
- config.pc.addTrack(track, stream);
1762
- } else {
1763
- Janus.log('Enabling rid-based simulcasting:', track);
1764
- config.pc.addTransceiver(track, {
1765
- direction: "sendrecv",
1766
- streams: [stream],
1767
- sendEncodings: [
1768
- { rid: "h", active: true, maxBitrate: 900000 },
1769
- { rid: "m", active: true, maxBitrate: 300000, scaleResolutionDownBy: 2 },
1770
- { rid: "l", active: true, maxBitrate: 100000, scaleResolutionDownBy: 4 }
1771
- ]
1772
- });
1773
- }
1774
- }
1775
- });
1776
- }
1777
- // Any data channel to create?
1778
- if(isDataEnabled(media) && !config.dataChannel[Janus.dataChanDefaultLabel]) {
1779
- Janus.log("Creating data channel");
1780
- createDataChannel(handleId, Janus.dataChanDefaultLabel, false);
1781
- config.pc.ondatachannel = function(event) {
1782
- Janus.log("Data channel created by Janus:", event);
1783
- createDataChannel(handleId, event.channel.label, event.channel);
1784
- };
1785
- }
1786
- // If there's a new local stream, let's notify the application
1787
- if(config.myStream)
1788
- pluginHandle.onlocalstream(config.myStream);
1789
- // Create offer/answer now
1790
- if(jsep === null || jsep === undefined) {
1791
- createOffer(handleId, media, callbacks);
1792
- } else {
1793
- config.pc.setRemoteDescription(jsep)
1794
- .then(function() {
1795
- Janus.log("Remote description accepted!");
1796
- config.remoteSdp = jsep.sdp;
1797
- // Any trickle candidate we cached?
1798
- if(config.candidates && config.candidates.length > 0) {
1799
- for(var i in config.candidates) {
1800
- var candidate = config.candidates[i];
1801
- Janus.debug("Adding remote candidate:", candidate);
1802
- if(!candidate || candidate.completed === true) {
1803
- // end-of-candidates
1804
- config.pc.addIceCandidate();
1805
- } else {
1806
- // New candidate
1807
- config.pc.addIceCandidate(candidate);
1808
- }
1809
- }
1810
- config.candidates = [];
1811
- }
1812
- // Create the answer now
1813
- createAnswer(handleId, media, callbacks);
1814
- }, callbacks.error);
1815
- }
1816
- }
1817
-
1818
- function prepareWebrtc(handleId, offer, callbacks) {
1819
- callbacks = callbacks || {};
1820
- callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : Janus.noop;
1821
- callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : webrtcError;
1822
- var jsep = callbacks.jsep;
1823
- if(offer && jsep) {
1824
- Janus.error("Provided a JSEP to a createOffer");
1825
- callbacks.error("Provided a JSEP to a createOffer");
1826
- return;
1827
- } else if(!offer && (!jsep || !jsep.type || !jsep.sdp)) {
1828
- Janus.error("A valid JSEP is required for createAnswer");
1829
- callbacks.error("A valid JSEP is required for createAnswer");
1830
- return;
1831
- }
1832
- callbacks.media = callbacks.media || { audio: true, video: true };
1833
- var media = callbacks.media;
1834
- var pluginHandle = pluginHandles[handleId];
1835
- if(pluginHandle === null || pluginHandle === undefined ||
1836
- pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
1837
- Janus.warn("Invalid handle");
1838
- callbacks.error("Invalid handle");
1839
- return;
1840
- }
1841
- var config = pluginHandle.webrtcStuff;
1842
- config.trickle = isTrickleEnabled(callbacks.trickle);
1843
- // Are we updating a session?
1844
- if(config.pc === undefined || config.pc === null) {
1845
- // Nope, new PeerConnection
1846
- media.update = false;
1847
- media.keepAudio = false;
1848
- media.keepVideo = false;
1849
- } else if(config.pc !== undefined && config.pc !== null) {
1850
- Janus.log("Updating existing media session");
1851
- media.update = true;
1852
- // Check if there's anything to add/remove/replace, or if we
1853
- // can go directly to preparing the new SDP offer or answer
1854
- if(callbacks.stream !== null && callbacks.stream !== undefined) {
1855
- // External stream: is this the same as the one we were using before?
1856
- if(callbacks.stream !== config.myStream) {
1857
- Janus.log("Renegotiation involves a new external stream");
1858
- }
1859
- } else {
1860
- // Check if there are changes on audio
1861
- if(media.addAudio) {
1862
- media.keepAudio = false;
1863
- media.replaceAudio = false;
1864
- media.removeAudio = false;
1865
- media.audioSend = true;
1866
- if(config.myStream && config.myStream.getAudioTracks() && config.myStream.getAudioTracks().length) {
1867
- Janus.error("Can't add audio stream, there already is one");
1868
- callbacks.error("Can't add audio stream, there already is one");
1869
- return;
1870
- }
1871
- } else if(media.removeAudio) {
1872
- media.keepAudio = false;
1873
- media.replaceAudio = false;
1874
- media.addAudio = false;
1875
- media.audioSend = false;
1876
- } else if(media.replaceAudio) {
1877
- media.keepAudio = false;
1878
- media.addAudio = false;
1879
- media.removeAudio = false;
1880
- media.audioSend = true;
1881
- }
1882
- if(config.myStream === null || config.myStream === undefined) {
1883
- // No media stream: if we were asked to replace, it's actually an "add"
1884
- if(media.replaceAudio) {
1885
- media.keepAudio = false;
1886
- media.replaceAudio = false;
1887
- media.addAudio = true;
1888
- media.audioSend = true;
1889
- }
1890
- if(isAudioSendEnabled(media)) {
1891
- media.keepAudio = false;
1892
- media.addAudio = true;
1893
- }
1894
- } else {
1895
- if(config.myStream.getAudioTracks() === null
1896
- || config.myStream.getAudioTracks() === undefined
1897
- || config.myStream.getAudioTracks().length === 0) {
1898
- // No audio track: if we were asked to replace, it's actually an "add"
1899
- if(media.replaceAudio) {
1900
- media.keepAudio = false;
1901
- media.replaceAudio = false;
1902
- media.addAudio = true;
1903
- media.audioSend = true;
1904
- }
1905
- if(isAudioSendEnabled(media)) {
1906
- media.keepVideo = false;
1907
- media.addAudio = true;
1908
- }
1909
- } else {
1910
- // We have an audio track: should we keep it as it is?
1911
- if(isAudioSendEnabled(media) &&
1912
- !media.removeAudio && !media.replaceAudio) {
1913
- media.keepAudio = true;
1914
- }
1915
- }
1916
- }
1917
- // Check if there are changes on video
1918
- if(media.addVideo) {
1919
- media.keepVideo = false;
1920
- media.replaceVideo = false;
1921
- media.removeVideo = false;
1922
- media.videoSend = true;
1923
- if(config.myStream && config.myStream.getVideoTracks() && config.myStream.getVideoTracks().length) {
1924
- Janus.error("Can't add video stream, there already is one");
1925
- callbacks.error("Can't add video stream, there already is one");
1926
- return;
1927
- }
1928
- } else if(media.removeVideo) {
1929
- media.keepVideo = false;
1930
- media.replaceVideo = false;
1931
- media.addVideo = false;
1932
- media.videoSend = false;
1933
- } else if(media.replaceVideo) {
1934
- media.keepVideo = false;
1935
- media.addVideo = false;
1936
- media.removeVideo = false;
1937
- media.videoSend = true;
1938
- }
1939
- if(config.myStream === null || config.myStream === undefined) {
1940
- // No media stream: if we were asked to replace, it's actually an "add"
1941
- if(media.replaceVideo) {
1942
- media.keepVideo = false;
1943
- media.replaceVideo = false;
1944
- media.addVideo = true;
1945
- media.videoSend = true;
1946
- }
1947
- if(isVideoSendEnabled(media)) {
1948
- media.keepVideo = false;
1949
- media.addVideo = true;
1950
- }
1951
- } else {
1952
- if(config.myStream.getVideoTracks() === null
1953
- || config.myStream.getVideoTracks() === undefined
1954
- || config.myStream.getVideoTracks().length === 0) {
1955
- // No video track: if we were asked to replace, it's actually an "add"
1956
- if(media.replaceVideo) {
1957
- media.keepVideo = false;
1958
- media.replaceVideo = false;
1959
- media.addVideo = true;
1960
- media.videoSend = true;
1961
- }
1962
- if(isVideoSendEnabled(media)) {
1963
- media.keepVideo = false;
1964
- media.addVideo = true;
1965
- }
1966
- } else {
1967
- // We have a video track: should we keep it as it is?
1968
- if(isVideoSendEnabled(media) &&
1969
- !media.removeVideo && !media.replaceVideo) {
1970
- media.keepVideo = true;
1971
- }
1972
- }
1973
- }
1974
- // Data channels can only be added
1975
- if(media.addData)
1976
- media.data = true;
1977
- }
1978
- // If we're updating and keeping all tracks, let's skip the getUserMedia part
1979
- if((isAudioSendEnabled(media) && media.keepAudio) &&
1980
- (isVideoSendEnabled(media) && media.keepVideo)) {
1981
- pluginHandle.consentDialog(false);
1982
- streamsDone(handleId, jsep, media, callbacks, config.myStream);
1983
- return;
1984
- }
1985
- }
1986
- // If we're updating, check if we need to remove/replace one of the tracks
1987
- if(media.update && !config.streamExternal) {
1988
- if(media.removeAudio || media.replaceAudio) {
1989
- if(config.myStream && config.myStream.getAudioTracks() && config.myStream.getAudioTracks().length) {
1990
- var s = config.myStream.getAudioTracks()[0];
1991
- Janus.log("Removing audio track:", s);
1992
- config.myStream.removeTrack(s);
1993
- try {
1994
- s.stop();
1995
- } catch(e) {};
1996
- }
1997
- if(config.pc.getSenders() && config.pc.getSenders().length) {
1998
- var ra = true;
1999
- if(media.replaceAudio && (Janus.webRTCAdapter.browserDetails.browser === "firefox" ||
2000
- (Janus.webRTCAdapter.browserDetails.browser === "chrome" && Janus.webRTCAdapter.browserDetails.version >= 72))) {
2001
- // On Firefox we can use replaceTrack
2002
- ra = false;
2003
- }
2004
- if(ra) {
2005
- for(var index in config.pc.getSenders()) {
2006
- var s = config.pc.getSenders()[index];
2007
- if(s && s.track && s.track.kind === "audio") {
2008
- Janus.log("Removing audio sender:", s);
2009
- config.pc.removeTrack(s);
2010
- }
2011
- }
2012
- }
2013
- }
2014
- }
2015
- if(media.removeVideo || media.replaceVideo) {
2016
- if(config.myStream && config.myStream.getVideoTracks() && config.myStream.getVideoTracks().length) {
2017
- var s = config.myStream.getVideoTracks()[0];
2018
- Janus.log("Removing video track:", s);
2019
- config.myStream.removeTrack(s);
2020
- try {
2021
- s.stop();
2022
- } catch(e) {};
2023
- }
2024
- if(config.pc.getSenders() && config.pc.getSenders().length) {
2025
- var rv = true;
2026
- if(media.replaceVideo && (Janus.webRTCAdapter.browserDetails.browser === "firefox" ||
2027
- (Janus.webRTCAdapter.browserDetails.browser === "chrome" && Janus.webRTCAdapter.browserDetails.version >= 72))) {
2028
- // On Firefox we can use replaceTrack
2029
- rv = false;
2030
- }
2031
- if(rv) {
2032
- for(var index in config.pc.getSenders()) {
2033
- var s = config.pc.getSenders()[index];
2034
- if(s && s.track && s.track.kind === "video") {
2035
- Janus.log("Removing video sender:", s);
2036
- config.pc.removeTrack(s);
2037
- }
2038
- }
2039
- }
2040
- }
2041
- }
2042
- }
2043
- // Was a MediaStream object passed, or do we need to take care of that?
2044
- if(callbacks.stream !== null && callbacks.stream !== undefined) {
2045
- var stream = callbacks.stream;
2046
- Janus.log("MediaStream provided by the application");
2047
- Janus.debug(stream);
2048
- // If this is an update, let's check if we need to release the previous stream
2049
- if(media.update) {
2050
- if(config.myStream && config.myStream !== callbacks.stream && !config.streamExternal) {
2051
- // We're replacing a stream we captured ourselves with an external one
2052
- try {
2053
- // Try a MediaStreamTrack.stop() for each track
2054
- var tracks = config.myStream.getTracks();
2055
- for(var i in tracks) {
2056
- var mst = tracks[i];
2057
- Janus.log(mst);
2058
- if(mst !== null && mst !== undefined)
2059
- mst.stop();
2060
- }
2061
- } catch(e) {
2062
- // Do nothing if this fails
2063
- }
2064
- config.myStream = null;
2065
- }
2066
- }
2067
- // Skip the getUserMedia part
2068
- config.streamExternal = true;
2069
- pluginHandle.consentDialog(false);
2070
- streamsDone(handleId, jsep, media, callbacks, stream);
2071
- return;
2072
- }
2073
- if(isAudioSendEnabled(media) || isVideoSendEnabled(media)) {
2074
- if(!Janus.isGetUserMediaAvailable()) {
2075
- callbacks.error("getUserMedia not available");
2076
- return;
2077
- }
2078
- var constraints = { mandatory: {}, optional: []};
2079
- pluginHandle.consentDialog(true);
2080
- var audioSupport = isAudioSendEnabled(media);
2081
- if(audioSupport === true && media != undefined && media != null) {
2082
- if(typeof media.audio === 'object') {
2083
- audioSupport = media.audio;
2084
- }
2085
- }
2086
- var videoSupport = isVideoSendEnabled(media);
2087
- if(videoSupport === true && media != undefined && media != null) {
2088
- var simulcast = callbacks.simulcast === true ? true : false;
2089
- var simulcast2 = callbacks.simulcast2 === true ? true : false;
2090
- if((simulcast || simulcast2) && !jsep && (media.video === undefined || media.video === false))
2091
- media.video = "hires";
2092
- if(media.video && media.video != 'screen' && media.video != 'window') {
2093
- if(typeof media.video === 'object') {
2094
- videoSupport = media.video;
2095
- } else {
2096
- var width = 0;
2097
- var height = 0, maxHeight = 0;
2098
- if(media.video === 'lowres') {
2099
- // Small resolution, 4:3
2100
- height = 240;
2101
- maxHeight = 240;
2102
- width = 320;
2103
- } else if(media.video === 'lowres-16:9') {
2104
- // Small resolution, 16:9
2105
- height = 180;
2106
- maxHeight = 180;
2107
- width = 320;
2108
- } else if(media.video === 'hires' || media.video === 'hires-16:9' || media.video === 'hdres') {
2109
- // High(HD) resolution is only 16:9
2110
- height = 720;
2111
- maxHeight = 720;
2112
- width = 1280;
2113
- } else if(media.video === 'fhdres') {
2114
- // Full HD resolution is only 16:9
2115
- height = 1080;
2116
- maxHeight = 1080;
2117
- width = 1920;
2118
- } else if(media.video === '4kres') {
2119
- // 4K resolution is only 16:9
2120
- height = 2160;
2121
- maxHeight = 2160;
2122
- width = 3840;
2123
- } else if(media.video === 'stdres') {
2124
- // Normal resolution, 4:3
2125
- height = 480;
2126
- maxHeight = 480;
2127
- width = 640;
2128
- } else if(media.video === 'stdres-16:9') {
2129
- // Normal resolution, 16:9
2130
- height = 360;
2131
- maxHeight = 360;
2132
- width = 640;
2133
- } else {
2134
- Janus.log("Default video setting is stdres 4:3");
2135
- height = 480;
2136
- maxHeight = 480;
2137
- width = 640;
2138
- }
2139
- Janus.log("Adding media constraint:", media.video);
2140
- videoSupport = {
2141
- 'height': {'ideal': height},
2142
- 'width': {'ideal': width}
2143
- };
2144
- Janus.log("Adding video constraint:", videoSupport);
2145
- }
2146
- } else if(media.video === 'screen' || media.video === 'window') {
2147
- if(!media.screenshareFrameRate) {
2148
- media.screenshareFrameRate = 3;
2149
- }
2150
- if(navigator.mediaDevices && navigator.mediaDevices.getDisplayMedia) {
2151
- // The new experimental getDisplayMedia API is available, let's use that
2152
- // https://groups.google.com/forum/#!topic/discuss-webrtc/Uf0SrR4uxzk
2153
- // https://webrtchacks.com/chrome-screensharing-getdisplaymedia/
2154
- navigator.mediaDevices.getDisplayMedia({ video: true })
2155
- .then(function(stream) {
2156
- pluginHandle.consentDialog(false);
2157
- if(isAudioSendEnabled(media) && !media.keepAudio) {
2158
- navigator.mediaDevices.getUserMedia({ audio: true, video: false })
2159
- .then(function (audioStream) {
2160
- stream.addTrack(audioStream.getAudioTracks()[0]);
2161
- streamsDone(handleId, jsep, media, callbacks, stream);
2162
- })
2163
- } else {
2164
- streamsDone(handleId, jsep, media, callbacks, stream);
2165
- }
2166
- }, function (error) {
2167
- pluginHandle.consentDialog(false);
2168
- callbacks.error(error);
2169
- });
2170
- return;
2171
- }
2172
- // We're going to try and use the extension for Chrome 34+, the old approach
2173
- // for older versions of Chrome, or the experimental support in Firefox 33+
2174
- function callbackUserMedia (error, stream) {
2175
- pluginHandle.consentDialog(false);
2176
- if(error) {
2177
- callbacks.error(error);
2178
- } else {
2179
- streamsDone(handleId, jsep, media, callbacks, stream);
2180
- }
2181
- };
2182
- function getScreenMedia(constraints, gsmCallback, useAudio) {
2183
- Janus.log("Adding media constraint (screen capture)");
2184
- Janus.debug(constraints);
2185
- navigator.mediaDevices.getUserMedia(constraints)
2186
- .then(function(stream) {
2187
- if(useAudio) {
2188
- navigator.mediaDevices.getUserMedia({ audio: true, video: false })
2189
- .then(function (audioStream) {
2190
- stream.addTrack(audioStream.getAudioTracks()[0]);
2191
- gsmCallback(null, stream);
2192
- })
2193
- } else {
2194
- gsmCallback(null, stream);
2195
- }
2196
- })
2197
- .catch(function(error) { pluginHandle.consentDialog(false); gsmCallback(error); });
2198
- };
2199
- if(Janus.webRTCAdapter.browserDetails.browser === 'chrome') {
2200
- var chromever = Janus.webRTCAdapter.browserDetails.version;
2201
- var maxver = 33;
2202
- if(window.navigator.userAgent.match('Linux'))
2203
- maxver = 35; // "known" crash in chrome 34 and 35 on linux
2204
- if(chromever >= 26 && chromever <= maxver) {
2205
- // Chrome 26->33 requires some awkward chrome://flags manipulation
2206
- constraints = {
2207
- video: {
2208
- mandatory: {
2209
- googLeakyBucket: true,
2210
- maxWidth: window.screen.width,
2211
- maxHeight: window.screen.height,
2212
- minFrameRate: media.screenshareFrameRate,
2213
- maxFrameRate: media.screenshareFrameRate,
2214
- chromeMediaSource: 'screen'
2215
- }
2216
- },
2217
- audio: isAudioSendEnabled(media) && !media.keepAudio
2218
- };
2219
- getScreenMedia(constraints, callbackUserMedia);
2220
- } else {
2221
- // Chrome 34+ requires an extension
2222
- Janus.extension.getScreen(function (error, sourceId) {
2223
- if (error) {
2224
- pluginHandle.consentDialog(false);
2225
- return callbacks.error(error);
2226
- }
2227
- constraints = {
2228
- audio: false,
2229
- video: {
2230
- mandatory: {
2231
- chromeMediaSource: 'desktop',
2232
- maxWidth: window.screen.width,
2233
- maxHeight: window.screen.height,
2234
- minFrameRate: media.screenshareFrameRate,
2235
- maxFrameRate: media.screenshareFrameRate,
2236
- },
2237
- optional: [
2238
- {googLeakyBucket: true},
2239
- {googTemporalLayeredScreencast: true}
2240
- ]
2241
- }
2242
- };
2243
- constraints.video.mandatory.chromeMediaSourceId = sourceId;
2244
- getScreenMedia(constraints, callbackUserMedia,
2245
- isAudioSendEnabled(media) && !media.keepAudio);
2246
- });
2247
- }
2248
- } else if(Janus.webRTCAdapter.browserDetails.browser === 'firefox') {
2249
- if(Janus.webRTCAdapter.browserDetails.version >= 33) {
2250
- // Firefox 33+ has experimental support for screen sharing
2251
- constraints = {
2252
- video: {
2253
- mozMediaSource: media.video,
2254
- mediaSource: media.video
2255
- },
2256
- audio: isAudioSendEnabled(media) && !media.keepAudio
2257
- };
2258
- getScreenMedia(constraints, function (err, stream) {
2259
- callbackUserMedia(err, stream);
2260
- // Workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=1045810
2261
- if (!err) {
2262
- var lastTime = stream.currentTime;
2263
- var polly = window.setInterval(function () {
2264
- if(!stream)
2265
- window.clearInterval(polly);
2266
- if(stream.currentTime == lastTime) {
2267
- window.clearInterval(polly);
2268
- if(stream.onended) {
2269
- stream.onended();
2270
- }
2271
- }
2272
- lastTime = stream.currentTime;
2273
- }, 500);
2274
- }
2275
- });
2276
- } else {
2277
- var error = new Error('NavigatorUserMediaError');
2278
- error.name = 'Your version of Firefox does not support screen sharing, please install Firefox 33 (or more recent versions)';
2279
- pluginHandle.consentDialog(false);
2280
- callbacks.error(error);
2281
- return;
2282
- }
2283
- }
2284
- return;
2285
- }
2286
- }
2287
- // If we got here, we're not screensharing
2288
- if(media === null || media === undefined || media.video !== 'screen') {
2289
- // Check whether all media sources are actually available or not
2290
- navigator.mediaDevices.enumerateDevices().then(function(devices) {
2291
- var audioExist = devices.some(function(device) {
2292
- return device.kind === 'audioinput';
2293
- }),
2294
- videoExist = isScreenSendEnabled(media) || devices.some(function(device) {
2295
- return device.kind === 'videoinput';
2296
- });
2297
-
2298
- // Check whether a missing device is really a problem
2299
- var audioSend = isAudioSendEnabled(media);
2300
- var videoSend = isVideoSendEnabled(media);
2301
- var needAudioDevice = isAudioSendRequired(media);
2302
- var needVideoDevice = isVideoSendRequired(media);
2303
- if(audioSend || videoSend || needAudioDevice || needVideoDevice) {
2304
- // We need to send either audio or video
2305
- var haveAudioDevice = audioSend ? audioExist : false;
2306
- var haveVideoDevice = videoSend ? videoExist : false;
2307
- if(!haveAudioDevice && !haveVideoDevice) {
2308
- // FIXME Should we really give up, or just assume recvonly for both?
2309
- pluginHandle.consentDialog(false);
2310
- callbacks.error('No capture device found');
2311
- return false;
2312
- } else if(!haveAudioDevice && needAudioDevice) {
2313
- pluginHandle.consentDialog(false);
2314
- callbacks.error('Audio capture is required, but no capture device found');
2315
- return false;
2316
- } else if(!haveVideoDevice && needVideoDevice) {
2317
- pluginHandle.consentDialog(false);
2318
- callbacks.error('Video capture is required, but no capture device found');
2319
- return false;
2320
- }
2321
- }
2322
-
2323
- var gumConstraints = {
2324
- audio: (audioExist && !media.keepAudio) ? audioSupport : false,
2325
- video: (videoExist && !media.keepVideo) ? videoSupport : false
2326
- };
2327
- Janus.debug("getUserMedia constraints", gumConstraints);
2328
- if (!gumConstraints.audio && !gumConstraints.video) {
2329
- pluginHandle.consentDialog(false);
2330
- streamsDone(handleId, jsep, media, callbacks, stream);
2331
- } else {
2332
- navigator.mediaDevices.getUserMedia(gumConstraints)
2333
- .then(function(stream) {
2334
- pluginHandle.consentDialog(false);
2335
- streamsDone(handleId, jsep, media, callbacks, stream);
2336
- }).catch(function(error) {
2337
- pluginHandle.consentDialog(false);
2338
- callbacks.error({code: error.code, name: error.name, message: error.message});
2339
- });
2340
- }
2341
- })
2342
- .catch(function(error) {
2343
- pluginHandle.consentDialog(false);
2344
- callbacks.error('enumerateDevices error', error);
2345
- });
2346
- }
2347
- } else {
2348
- // No need to do a getUserMedia, create offer/answer right away
2349
- streamsDone(handleId, jsep, media, callbacks);
2350
- }
2351
- }
2352
-
2353
- function prepareWebrtcPeer(handleId, callbacks) {
2354
- callbacks = callbacks || {};
2355
- callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : Janus.noop;
2356
- callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : webrtcError;
2357
- var jsep = callbacks.jsep;
2358
- var pluginHandle = pluginHandles[handleId];
2359
- if(pluginHandle === null || pluginHandle === undefined ||
2360
- pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
2361
- Janus.warn("Invalid handle");
2362
- callbacks.error("Invalid handle");
2363
- return;
2364
- }
2365
- var config = pluginHandle.webrtcStuff;
2366
- if(jsep !== undefined && jsep !== null) {
2367
- if(config.pc === null) {
2368
- Janus.warn("Wait, no PeerConnection?? if this is an answer, use createAnswer and not handleRemoteJsep");
2369
- callbacks.error("No PeerConnection: if this is an answer, use createAnswer and not handleRemoteJsep");
2370
- return;
2371
- }
2372
- config.pc.setRemoteDescription(jsep)
2373
- .then(function() {
2374
- Janus.log("Remote description accepted!");
2375
- config.remoteSdp = jsep.sdp;
2376
- // Any trickle candidate we cached?
2377
- if(config.candidates && config.candidates.length > 0) {
2378
- for(var i in config.candidates) {
2379
- var candidate = config.candidates[i];
2380
- Janus.debug("Adding remote candidate:", candidate);
2381
- if(!candidate || candidate.completed === true) {
2382
- // end-of-candidates
2383
- config.pc.addIceCandidate();
2384
- } else {
2385
- // New candidate
2386
- config.pc.addIceCandidate(candidate);
2387
- }
2388
- }
2389
- config.candidates = [];
2390
- }
2391
- // Done
2392
- callbacks.success();
2393
- }, callbacks.error);
2394
- } else {
2395
- callbacks.error("Invalid JSEP");
2396
- }
2397
- }
2398
-
2399
- function createOffer(handleId, media, callbacks) {
2400
- callbacks = callbacks || {};
2401
- callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : Janus.noop;
2402
- callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : Janus.noop;
2403
- callbacks.customizeSdp = (typeof callbacks.customizeSdp == "function") ? callbacks.customizeSdp : Janus.noop;
2404
- var pluginHandle = pluginHandles[handleId];
2405
- if(pluginHandle === null || pluginHandle === undefined ||
2406
- pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
2407
- Janus.warn("Invalid handle");
2408
- callbacks.error("Invalid handle");
2409
- return;
2410
- }
2411
- var config = pluginHandle.webrtcStuff;
2412
- var simulcast = callbacks.simulcast === true ? true : false;
2413
- if(!simulcast) {
2414
- Janus.log("Creating offer (iceDone=" + config.iceDone + ")");
2415
- } else {
2416
- Janus.log("Creating offer (iceDone=" + config.iceDone + ", simulcast=" + simulcast + ")");
2417
- }
2418
- // https://code.google.com/p/webrtc/issues/detail?id=3508
2419
- var mediaConstraints = {};
2420
- if((Janus.webRTCAdapter.browserDetails.browser === "firefox" && Janus.webRTCAdapter.browserDetails.version >= 59) ||
2421
- (Janus.webRTCAdapter.browserDetails.browser === "safari" && window.RTCRtpSender.prototype.replaceTrack) ||
2422
- (Janus.webRTCAdapter.browserDetails.browser === "chrome" && Janus.webRTCAdapter.browserDetails.version >= 72)) {
2423
- // Firefox >= 59, Safari and Chrome >= 72 use Transceivers
2424
- var audioTransceiver = null, videoTransceiver = null;
2425
- var transceivers = config.pc.getTransceivers();
2426
- if(transceivers && transceivers.length > 0) {
2427
- for(var i in transceivers) {
2428
- var t = transceivers[i];
2429
- if((t.sender && t.sender.track && t.sender.track.kind === "audio") ||
2430
- (t.receiver && t.receiver.track && t.receiver.track.kind === "audio")) {
2431
- if(!audioTransceiver)
2432
- audioTransceiver = t;
2433
- continue;
2434
- }
2435
- if((t.sender && t.sender.track && t.sender.track.kind === "video") ||
2436
- (t.receiver && t.receiver.track && t.receiver.track.kind === "video")) {
2437
- if(!videoTransceiver)
2438
- videoTransceiver = t;
2439
- continue;
2440
- }
2441
- }
2442
- }
2443
- // Handle audio (and related changes, if any)
2444
- var audioSend = isAudioSendEnabled(media);
2445
- var audioRecv = isAudioRecvEnabled(media);
2446
- if(!audioSend && !audioRecv) {
2447
- // Audio disabled: have we removed it?
2448
- if(media.removeAudio && audioTransceiver) {
2449
- if (audioTransceiver.setDirection) {
2450
- audioTransceiver.setDirection("inactive");
2451
- } else {
2452
- audioTransceiver.direction = "inactive";
2453
- }
2454
- Janus.log("Setting audio transceiver to inactive:", audioTransceiver);
2455
- }
2456
- } else {
2457
- // Take care of audio m-line
2458
- if(audioSend && audioRecv) {
2459
- if(audioTransceiver) {
2460
- if (audioTransceiver.setDirection) {
2461
- audioTransceiver.setDirection("sendrecv");
2462
- } else {
2463
- audioTransceiver.direction = "sendrecv";
2464
- }
2465
- Janus.log("Setting audio transceiver to sendrecv:", audioTransceiver);
2466
- }
2467
- } else if(audioSend && !audioRecv) {
2468
- if(audioTransceiver) {
2469
- if (audioTransceiver.setDirection) {
2470
- audioTransceiver.setDirection("sendonly");
2471
- } else {
2472
- audioTransceiver.direction = "sendonly";
2473
- }
2474
- Janus.log("Setting audio transceiver to sendonly:", audioTransceiver);
2475
- }
2476
- } else if(!audioSend && audioRecv) {
2477
- if(audioTransceiver) {
2478
- if (audioTransceiver.setDirection) {
2479
- audioTransceiver.setDirection("recvonly");
2480
- } else {
2481
- audioTransceiver.direction = "recvonly";
2482
- }
2483
- Janus.log("Setting audio transceiver to recvonly:", audioTransceiver);
2484
- } else {
2485
- // In theory, this is the only case where we might not have a transceiver yet
2486
- audioTransceiver = config.pc.addTransceiver("audio", { direction: "recvonly" });
2487
- Janus.log("Adding recvonly audio transceiver:", audioTransceiver);
2488
- }
2489
- }
2490
- }
2491
- // Handle video (and related changes, if any)
2492
- var videoSend = isVideoSendEnabled(media);
2493
- var videoRecv = isVideoRecvEnabled(media);
2494
- if(!videoSend && !videoRecv) {
2495
- // Video disabled: have we removed it?
2496
- if(media.removeVideo && videoTransceiver) {
2497
- if (videoTransceiver.setDirection) {
2498
- videoTransceiver.setDirection("inactive");
2499
- } else {
2500
- videoTransceiver.direction = "inactive";
2501
- }
2502
- Janus.log("Setting video transceiver to inactive:", videoTransceiver);
2503
- }
2504
- } else {
2505
- // Take care of video m-line
2506
- if(videoSend && videoRecv) {
2507
- if(videoTransceiver) {
2508
- if (videoTransceiver.setDirection) {
2509
- videoTransceiver.setDirection("sendrecv");
2510
- } else {
2511
- videoTransceiver.direction = "sendrecv";
2512
- }
2513
- Janus.log("Setting video transceiver to sendrecv:", videoTransceiver);
2514
- }
2515
- } else if(videoSend && !videoRecv) {
2516
- if(videoTransceiver) {
2517
- if (videoTransceiver.setDirection) {
2518
- videoTransceiver.setDirection("sendonly");
2519
- } else {
2520
- videoTransceiver.direction = "sendonly";
2521
- }
2522
- Janus.log("Setting video transceiver to sendonly:", videoTransceiver);
2523
- }
2524
- } else if(!videoSend && videoRecv) {
2525
- if(videoTransceiver) {
2526
- if (videoTransceiver.setDirection) {
2527
- videoTransceiver.setDirection("recvonly");
2528
- } else {
2529
- videoTransceiver.direction = "recvonly";
2530
- }
2531
- Janus.log("Setting video transceiver to recvonly:", videoTransceiver);
2532
- } else {
2533
- // In theory, this is the only case where we might not have a transceiver yet
2534
- videoTransceiver = config.pc.addTransceiver("video", { direction: "recvonly" });
2535
- Janus.log("Adding recvonly video transceiver:", videoTransceiver);
2536
- }
2537
- }
2538
- }
2539
- } else {
2540
- mediaConstraints["offerToReceiveAudio"] = isAudioRecvEnabled(media);
2541
- mediaConstraints["offerToReceiveVideo"] = isVideoRecvEnabled(media);
2542
- }
2543
- var iceRestart = callbacks.iceRestart === true ? true : false;
2544
- if(iceRestart) {
2545
- mediaConstraints["iceRestart"] = true;
2546
- }
2547
- Janus.debug(mediaConstraints);
2548
- // Check if this is Firefox and we've been asked to do simulcasting
2549
- var sendVideo = isVideoSendEnabled(media);
2550
- if(sendVideo && simulcast && Janus.webRTCAdapter.browserDetails.browser === "firefox") {
2551
- // FIXME Based on https://gist.github.com/voluntas/088bc3cc62094730647b
2552
- Janus.log("Enabling Simulcasting for Firefox (RID)");
2553
- var sender = config.pc.getSenders().find(function(s) {return s.track.kind == "video"});
2554
- if(sender) {
2555
- var parameters = sender.getParameters();
2556
- if(!parameters)
2557
- parameters = {};
2558
- parameters.encodings = [
2559
- { rid: "h", active: true, maxBitrate: 900000 },
2560
- { rid: "m", active: true, maxBitrate: 300000, scaleResolutionDownBy: 2 },
2561
- { rid: "l", active: true, maxBitrate: 100000, scaleResolutionDownBy: 4 }
2562
- ];
2563
- sender.setParameters(parameters);
2564
- }
2565
- }
2566
- config.pc.createOffer(mediaConstraints)
2567
- .then(function(offer) {
2568
- Janus.debug(offer);
2569
- // JSON.stringify doesn't work on some WebRTC objects anymore
2570
- // See https://code.google.com/p/chromium/issues/detail?id=467366
2571
- var jsep = {
2572
- "type": offer.type,
2573
- "sdp": offer.sdp
2574
- };
2575
- callbacks.customizeSdp(jsep);
2576
- offer.sdp = jsep.sdp;
2577
- Janus.log("Setting local description");
2578
- if(sendVideo && simulcast) {
2579
- // This SDP munging only works with Chrome (Safari STP may support it too)
2580
- if(Janus.webRTCAdapter.browserDetails.browser === "chrome" ||
2581
- Janus.webRTCAdapter.browserDetails.browser === "safari") {
2582
- Janus.log("Enabling Simulcasting for Chrome (SDP munging)");
2583
- offer.sdp = mungeSdpForSimulcasting(offer.sdp);
2584
- } else if(Janus.webRTCAdapter.browserDetails.browser !== "firefox") {
2585
- Janus.warn("simulcast=true, but this is not Chrome nor Firefox, ignoring");
2586
- }
2587
- }
2588
- config.mySdp = offer.sdp;
2589
- config.pc.setLocalDescription(offer)
2590
- .catch(callbacks.error);
2591
- config.mediaConstraints = mediaConstraints;
2592
- if(!config.iceDone && !config.trickle) {
2593
- // Don't do anything until we have all candidates
2594
- Janus.log("Waiting for all candidates...");
2595
- return;
2596
- }
2597
- Janus.log("Offer ready");
2598
- Janus.debug(callbacks);
2599
- callbacks.success(offer);
2600
- }, callbacks.error);
2601
- }
2602
-
2603
- function createAnswer(handleId, media, callbacks) {
2604
- callbacks = callbacks || {};
2605
- callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : Janus.noop;
2606
- callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : Janus.noop;
2607
- callbacks.customizeSdp = (typeof callbacks.customizeSdp == "function") ? callbacks.customizeSdp : Janus.noop;
2608
- var pluginHandle = pluginHandles[handleId];
2609
- if(pluginHandle === null || pluginHandle === undefined ||
2610
- pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
2611
- Janus.warn("Invalid handle");
2612
- callbacks.error("Invalid handle");
2613
- return;
2614
- }
2615
- var config = pluginHandle.webrtcStuff;
2616
- var simulcast = callbacks.simulcast === true ? true : false;
2617
- if(!simulcast) {
2618
- Janus.log("Creating answer (iceDone=" + config.iceDone + ")");
2619
- } else {
2620
- Janus.log("Creating answer (iceDone=" + config.iceDone + ", simulcast=" + simulcast + ")");
2621
- }
2622
- var mediaConstraints = null;
2623
- if((Janus.webRTCAdapter.browserDetails.browser === "firefox" && Janus.webRTCAdapter.browserDetails.version >= 59) ||
2624
- (Janus.webRTCAdapter.browserDetails.browser === "safari" && window.RTCRtpSender.prototype.replaceTrack) ||
2625
- (Janus.webRTCAdapter.browserDetails.browser === "chrome" && Janus.webRTCAdapter.browserDetails.version >= 72)) {
2626
- // Firefox >= 59, Safari and Chrome >= 72 use Transceivers
2627
- mediaConstraints = {};
2628
- var audioTransceiver = null, videoTransceiver = null;
2629
- var transceivers = config.pc.getTransceivers();
2630
- if(transceivers && transceivers.length > 0) {
2631
- for(var i in transceivers) {
2632
- var t = transceivers[i];
2633
- if((t.sender && t.sender.track && t.sender.track.kind === "audio") ||
2634
- (t.receiver && t.receiver.track && t.receiver.track.kind === "audio")) {
2635
- if(!audioTransceiver)
2636
- audioTransceiver = t;
2637
- continue;
2638
- }
2639
- if((t.sender && t.sender.track && t.sender.track.kind === "video") ||
2640
- (t.receiver && t.receiver.track && t.receiver.track.kind === "video")) {
2641
- if(!videoTransceiver)
2642
- videoTransceiver = t;
2643
- continue;
2644
- }
2645
- }
2646
- }
2647
- // Handle audio (and related changes, if any)
2648
- var audioSend = isAudioSendEnabled(media);
2649
- var audioRecv = isAudioRecvEnabled(media);
2650
- if(!audioSend && !audioRecv) {
2651
- // Audio disabled: have we removed it?
2652
- if(media.removeAudio && audioTransceiver) {
2653
- if (audioTransceiver.setDirection) {
2654
- audioTransceiver.setDirection("inactive");
2655
- } else {
2656
- audioTransceiver.direction = "inactive";
2657
- }
2658
- Janus.log("Setting audio transceiver to inactive:", audioTransceiver);
2659
- }
2660
- } else {
2661
- // Take care of audio m-line
2662
- if(audioSend && audioRecv) {
2663
- if(audioTransceiver) {
2664
- if (audioTransceiver.setDirection) {
2665
- audioTransceiver.setDirection("sendrecv");
2666
- } else {
2667
- audioTransceiver.direction = "sendrecv";
2668
- }
2669
- Janus.log("Setting audio transceiver to sendrecv:", audioTransceiver);
2670
- }
2671
- } else if(audioSend && !audioRecv) {
2672
- if(audioTransceiver) {
2673
- if (audioTransceiver.setDirection) {
2674
- audioTransceiver.setDirection("sendonly");
2675
- } else {
2676
- audioTransceiver.direction = "sendonly";
2677
- }
2678
- Janus.log("Setting audio transceiver to sendonly:", audioTransceiver);
2679
- }
2680
- } else if(!audioSend && audioRecv) {
2681
- if(audioTransceiver) {
2682
- if (audioTransceiver.setDirection) {
2683
- audioTransceiver.setDirection("recvonly");
2684
- } else {
2685
- audioTransceiver.direction = "recvonly";
2686
- }
2687
- Janus.log("Setting audio transceiver to recvonly:", audioTransceiver);
2688
- } else {
2689
- // In theory, this is the only case where we might not have a transceiver yet
2690
- audioTransceiver = config.pc.addTransceiver("audio", { direction: "recvonly" });
2691
- Janus.log("Adding recvonly audio transceiver:", audioTransceiver);
2692
- }
2693
- }
2694
- }
2695
- // Handle video (and related changes, if any)
2696
- var videoSend = isVideoSendEnabled(media);
2697
- var videoRecv = isVideoRecvEnabled(media);
2698
- if(!videoSend && !videoRecv) {
2699
- // Video disabled: have we removed it?
2700
- if(media.removeVideo && videoTransceiver) {
2701
- if (videoTransceiver.setDirection) {
2702
- videoTransceiver.setDirection("inactive");
2703
- } else {
2704
- videoTransceiver.direction = "inactive";
2705
- }
2706
- Janus.log("Setting video transceiver to inactive:", videoTransceiver);
2707
- }
2708
- } else {
2709
- // Take care of video m-line
2710
- if(videoSend && videoRecv) {
2711
- if(videoTransceiver) {
2712
- if (videoTransceiver.setDirection) {
2713
- videoTransceiver.setDirection("sendrecv");
2714
- } else {
2715
- videoTransceiver.direction = "sendrecv";
2716
- }
2717
- Janus.log("Setting video transceiver to sendrecv:", videoTransceiver);
2718
- }
2719
- } else if(videoSend && !videoRecv) {
2720
- if(videoTransceiver) {
2721
- if (videoTransceiver.setDirection) {
2722
- videoTransceiver.setDirection("sendonly");
2723
- } else {
2724
- videoTransceiver.direction = "sendonly";
2725
- }
2726
- Janus.log("Setting video transceiver to sendonly:", videoTransceiver);
2727
- }
2728
- } else if(!videoSend && videoRecv) {
2729
- if(videoTransceiver) {
2730
- if (videoTransceiver.setDirection) {
2731
- videoTransceiver.setDirection("recvonly");
2732
- } else {
2733
- videoTransceiver.direction = "recvonly";
2734
- }
2735
- Janus.log("Setting video transceiver to recvonly:", videoTransceiver);
2736
- } else {
2737
- // In theory, this is the only case where we might not have a transceiver yet
2738
- videoTransceiver = config.pc.addTransceiver("video", { direction: "recvonly" });
2739
- Janus.log("Adding recvonly video transceiver:", videoTransceiver);
2740
- }
2741
- }
2742
- }
2743
- } else {
2744
- if(Janus.webRTCAdapter.browserDetails.browser == "firefox" || Janus.webRTCAdapter.browserDetails.browser == "edge") {
2745
- mediaConstraints = {
2746
- offerToReceiveAudio: isAudioRecvEnabled(media),
2747
- offerToReceiveVideo: isVideoRecvEnabled(media)
2748
- };
2749
- } else {
2750
- mediaConstraints = {
2751
- mandatory: {
2752
- OfferToReceiveAudio: isAudioRecvEnabled(media),
2753
- OfferToReceiveVideo: isVideoRecvEnabled(media)
2754
- }
2755
- };
2756
- }
2757
- }
2758
- Janus.debug(mediaConstraints);
2759
- // Check if this is Firefox and we've been asked to do simulcasting
2760
- var sendVideo = isVideoSendEnabled(media);
2761
- if(sendVideo && simulcast && Janus.webRTCAdapter.browserDetails.browser === "firefox") {
2762
- // FIXME Based on https://gist.github.com/voluntas/088bc3cc62094730647b
2763
- Janus.log("Enabling Simulcasting for Firefox (RID)");
2764
- var sender = config.pc.getSenders()[1];
2765
- Janus.log(sender);
2766
- var parameters = sender.getParameters();
2767
- Janus.log(parameters);
2768
- sender.setParameters({encodings: [
2769
- { rid: "high", active: true, priority: "high", maxBitrate: 1000000 },
2770
- { rid: "medium", active: true, priority: "medium", maxBitrate: 300000 },
2771
- { rid: "low", active: true, priority: "low", maxBitrate: 100000 }
2772
- ]});
2773
- }
2774
- config.pc.createAnswer(mediaConstraints)
2775
- .then(function(answer) {
2776
- Janus.debug(answer);
2777
- // JSON.stringify doesn't work on some WebRTC objects anymore
2778
- // See https://code.google.com/p/chromium/issues/detail?id=467366
2779
- var jsep = {
2780
- "type": answer.type,
2781
- "sdp": answer.sdp
2782
- };
2783
- callbacks.customizeSdp(jsep);
2784
- answer.sdp = jsep.sdp;
2785
- Janus.log("Setting local description");
2786
- if(sendVideo && simulcast) {
2787
- // This SDP munging only works with Chrome
2788
- if(Janus.webRTCAdapter.browserDetails.browser === "chrome") {
2789
- // FIXME Apparently trying to simulcast when answering breaks video in Chrome...
2790
- //~ Janus.log("Enabling Simulcasting for Chrome (SDP munging)");
2791
- //~ answer.sdp = mungeSdpForSimulcasting(answer.sdp);
2792
- Janus.warn("simulcast=true, but this is an answer, and video breaks in Chrome if we enable it");
2793
- } else if(Janus.webRTCAdapter.browserDetails.browser !== "firefox") {
2794
- Janus.warn("simulcast=true, but this is not Chrome nor Firefox, ignoring");
2795
- }
2796
- }
2797
- config.mySdp = answer.sdp;
2798
- config.pc.setLocalDescription(answer)
2799
- .catch(callbacks.error);
2800
- config.mediaConstraints = mediaConstraints;
2801
- if(!config.iceDone && !config.trickle) {
2802
- // Don't do anything until we have all candidates
2803
- Janus.log("Waiting for all candidates...");
2804
- return;
2805
- }
2806
- callbacks.success(answer);
2807
- }, callbacks.error);
2808
- }
2809
-
2810
- function sendSDP(handleId, callbacks) {
2811
- callbacks = callbacks || {};
2812
- callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : Janus.noop;
2813
- callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : Janus.noop;
2814
- var pluginHandle = pluginHandles[handleId];
2815
- if(pluginHandle === null || pluginHandle === undefined ||
2816
- pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
2817
- Janus.warn("Invalid handle, not sending anything");
2818
- return;
2819
- }
2820
- var config = pluginHandle.webrtcStuff;
2821
- Janus.log("Sending offer/answer SDP...");
2822
- if(config.mySdp === null || config.mySdp === undefined) {
2823
- Janus.warn("Local SDP instance is invalid, not sending anything...");
2824
- return;
2825
- }
2826
- config.mySdp = {
2827
- "type": config.pc.localDescription.type,
2828
- "sdp": config.pc.localDescription.sdp
2829
- };
2830
- if(config.trickle === false)
2831
- config.mySdp["trickle"] = false;
2832
- Janus.debug(callbacks);
2833
- config.sdpSent = true;
2834
- callbacks.success(config.mySdp);
2835
- }
2836
-
2837
- function getVolume(handleId, remote) {
2838
- var pluginHandle = pluginHandles[handleId];
2839
- if(pluginHandle === null || pluginHandle === undefined ||
2840
- pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
2841
- Janus.warn("Invalid handle");
2842
- return 0;
2843
- }
2844
- var stream = remote ? "remote" : "local";
2845
- var config = pluginHandle.webrtcStuff;
2846
- if(!config.volume[stream])
2847
- config.volume[stream] = { value: 0 };
2848
- // Start getting the volume, if getStats is supported
2849
- if(config.pc.getStats && Janus.webRTCAdapter.browserDetails.browser === "chrome") {
2850
- if(remote && (config.remoteStream === null || config.remoteStream === undefined)) {
2851
- Janus.warn("Remote stream unavailable");
2852
- return 0;
2853
- } else if(!remote && (config.myStream === null || config.myStream === undefined)) {
2854
- Janus.warn("Local stream unavailable");
2855
- return 0;
2856
- }
2857
- if(config.volume[stream].timer === null || config.volume[stream].timer === undefined) {
2858
- Janus.log("Starting " + stream + " volume monitor");
2859
- config.volume[stream].timer = setInterval(function() {
2860
- config.pc.getStats(function(stats) {
2861
- var results = stats.result();
2862
- for(var i=0; i<results.length; i++) {
2863
- var res = results[i];
2864
- if(res.type == 'ssrc') {
2865
- if(remote && res.stat('audioOutputLevel'))
2866
- config.volume[stream].value = parseInt(res.stat('audioOutputLevel'));
2867
- else if(!remote && res.stat('audioInputLevel'))
2868
- config.volume[stream].value = parseInt(res.stat('audioInputLevel'));
2869
- }
2870
- }
2871
- });
2872
- }, 200);
2873
- return 0; // We don't have a volume to return yet
2874
- }
2875
- return config.volume[stream].value;
2876
- } else {
2877
- // audioInputLevel and audioOutputLevel seem only available in Chrome? audioLevel
2878
- // seems to be available on Chrome and Firefox, but they don't seem to work
2879
- Janus.warn("Getting the " + stream + " volume unsupported by browser");
2880
- return 0;
2881
- }
2882
- }
2883
-
2884
- function isMuted(handleId, video) {
2885
- var pluginHandle = pluginHandles[handleId];
2886
- if(pluginHandle === null || pluginHandle === undefined ||
2887
- pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
2888
- Janus.warn("Invalid handle");
2889
- return true;
2890
- }
2891
- var config = pluginHandle.webrtcStuff;
2892
- if(config.pc === null || config.pc === undefined) {
2893
- Janus.warn("Invalid PeerConnection");
2894
- return true;
2895
- }
2896
- if(config.myStream === undefined || config.myStream === null) {
2897
- Janus.warn("Invalid local MediaStream");
2898
- return true;
2899
- }
2900
- if(video) {
2901
- // Check video track
2902
- if(config.myStream.getVideoTracks() === null
2903
- || config.myStream.getVideoTracks() === undefined
2904
- || config.myStream.getVideoTracks().length === 0) {
2905
- Janus.warn("No video track");
2906
- return true;
2907
- }
2908
- return !config.myStream.getVideoTracks()[0].enabled;
2909
- } else {
2910
- // Check audio track
2911
- if(config.myStream.getAudioTracks() === null
2912
- || config.myStream.getAudioTracks() === undefined
2913
- || config.myStream.getAudioTracks().length === 0) {
2914
- Janus.warn("No audio track");
2915
- return true;
2916
- }
2917
- return !config.myStream.getAudioTracks()[0].enabled;
2918
- }
2919
- }
2920
-
2921
- function mute(handleId, video, mute) {
2922
- var pluginHandle = pluginHandles[handleId];
2923
- if(pluginHandle === null || pluginHandle === undefined ||
2924
- pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
2925
- Janus.warn("Invalid handle");
2926
- return false;
2927
- }
2928
- var config = pluginHandle.webrtcStuff;
2929
- if(config.pc === null || config.pc === undefined) {
2930
- Janus.warn("Invalid PeerConnection");
2931
- return false;
2932
- }
2933
- if(config.myStream === undefined || config.myStream === null) {
2934
- Janus.warn("Invalid local MediaStream");
2935
- return false;
2936
- }
2937
- if(video) {
2938
- // Mute/unmute video track
2939
- if(config.myStream.getVideoTracks() === null
2940
- || config.myStream.getVideoTracks() === undefined
2941
- || config.myStream.getVideoTracks().length === 0) {
2942
- Janus.warn("No video track");
2943
- return false;
2944
- }
2945
- config.myStream.getVideoTracks()[0].enabled = mute ? false : true;
2946
- return true;
2947
- } else {
2948
- // Mute/unmute audio track
2949
- if(config.myStream.getAudioTracks() === null
2950
- || config.myStream.getAudioTracks() === undefined
2951
- || config.myStream.getAudioTracks().length === 0) {
2952
- Janus.warn("No audio track");
2953
- return false;
2954
- }
2955
- config.myStream.getAudioTracks()[0].enabled = mute ? false : true;
2956
- return true;
2957
- }
2958
- }
2959
-
2960
- function getBitrate(handleId) {
2961
- var pluginHandle = pluginHandles[handleId];
2962
- if(pluginHandle === null || pluginHandle === undefined ||
2963
- pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
2964
- Janus.warn("Invalid handle");
2965
- return "Invalid handle";
2966
- }
2967
- var config = pluginHandle.webrtcStuff;
2968
- if(config.pc === null || config.pc === undefined)
2969
- return "Invalid PeerConnection";
2970
- // Start getting the bitrate, if getStats is supported
2971
- if(config.pc.getStats) {
2972
- if(config.bitrate.timer === null || config.bitrate.timer === undefined) {
2973
- Janus.log("Starting bitrate timer (via getStats)");
2974
- config.bitrate.timer = setInterval(function() {
2975
- config.pc.getStats()
2976
- .then(function(stats) {
2977
- stats.forEach(function (res) {
2978
- if(!res)
2979
- return;
2980
- var inStats = false;
2981
- // Check if these are statistics on incoming media
2982
- if((res.mediaType === "video" || res.id.toLowerCase().indexOf("video") > -1) &&
2983
- res.type === "inbound-rtp" && res.id.indexOf("rtcp") < 0) {
2984
- // New stats
2985
- inStats = true;
2986
- } else if(res.type == 'ssrc' && res.bytesReceived &&
2987
- (res.googCodecName === "VP8" || res.googCodecName === "")) {
2988
- // Older Chromer versions
2989
- inStats = true;
2990
- }
2991
- // Parse stats now
2992
- if(inStats) {
2993
- config.bitrate.bsnow = res.bytesReceived;
2994
- config.bitrate.tsnow = res.timestamp;
2995
- if(config.bitrate.bsbefore === null || config.bitrate.tsbefore === null) {
2996
- // Skip this round
2997
- config.bitrate.bsbefore = config.bitrate.bsnow;
2998
- config.bitrate.tsbefore = config.bitrate.tsnow;
2999
- } else {
3000
- // Calculate bitrate
3001
- var timePassed = config.bitrate.tsnow - config.bitrate.tsbefore;
3002
- if(Janus.webRTCAdapter.browserDetails.browser == "safari")
3003
- timePassed = timePassed/1000; // Apparently the timestamp is in microseconds, in Safari
3004
- var bitRate = Math.round((config.bitrate.bsnow - config.bitrate.bsbefore) * 8 / timePassed);
3005
- if(Janus.webRTCAdapter.browserDetails.browser === 'safari')
3006
- bitRate = parseInt(bitRate/1000);
3007
- config.bitrate.value = bitRate + ' kbits/sec';
3008
- //~ Janus.log("Estimated bitrate is " + config.bitrate.value);
3009
- config.bitrate.bsbefore = config.bitrate.bsnow;
3010
- config.bitrate.tsbefore = config.bitrate.tsnow;
3011
- }
3012
- }
3013
- });
3014
- });
3015
- }, 1000);
3016
- return "0 kbits/sec"; // We don't have a bitrate value yet
3017
- }
3018
- return config.bitrate.value;
3019
- } else {
3020
- Janus.warn("Getting the video bitrate unsupported by browser");
3021
- return "Feature unsupported by browser";
3022
- }
3023
- }
3024
-
3025
- function webrtcError(error) {
3026
- Janus.error("WebRTC error:", error);
3027
- }
3028
-
3029
- function cleanupWebrtc(handleId, hangupRequest) {
3030
- Janus.log("Cleaning WebRTC stuff");
3031
- var pluginHandle = pluginHandles[handleId];
3032
- if(pluginHandle === null || pluginHandle === undefined) {
3033
- // Nothing to clean
3034
- return;
3035
- }
3036
- var config = pluginHandle.webrtcStuff;
3037
- if(config !== null && config !== undefined) {
3038
- if(hangupRequest === true) {
3039
- // Send a hangup request (we don't really care about the response)
3040
- var request = { "janus": "hangup", "transaction": Janus.randomString(12) };
3041
- if(pluginHandle.token !== null && pluginHandle.token !== undefined)
3042
- request["token"] = pluginHandle.token;
3043
- if(apisecret !== null && apisecret !== undefined)
3044
- request["apisecret"] = apisecret;
3045
- Janus.debug("Sending hangup request (handle=" + handleId + "):");
3046
- Janus.debug(request);
3047
- if(websockets) {
3048
- request["session_id"] = sessionId;
3049
- request["handle_id"] = handleId;
3050
- ws.send(JSON.stringify(request));
3051
- } else {
3052
- Janus.httpAPICall(server + "/" + sessionId + "/" + handleId, {
3053
- verb: 'POST',
3054
- withCredentials: withCredentials,
3055
- body: request
3056
- });
3057
- }
3058
- }
3059
- // Cleanup stack
3060
- config.remoteStream = null;
3061
- if(config.volume) {
3062
- if(config.volume["local"] && config.volume["local"].timer)
3063
- clearInterval(config.volume["local"].timer);
3064
- if(config.volume["remote"] && config.volume["remote"].timer)
3065
- clearInterval(config.volume["remote"].timer);
3066
- }
3067
- config.volume = {};
3068
- if(config.bitrate.timer)
3069
- clearInterval(config.bitrate.timer);
3070
- config.bitrate.timer = null;
3071
- config.bitrate.bsnow = null;
3072
- config.bitrate.bsbefore = null;
3073
- config.bitrate.tsnow = null;
3074
- config.bitrate.tsbefore = null;
3075
- config.bitrate.value = null;
3076
- try {
3077
- // Try a MediaStreamTrack.stop() for each track
3078
- if(!config.streamExternal && config.myStream !== null && config.myStream !== undefined) {
3079
- Janus.log("Stopping local stream tracks");
3080
- var tracks = config.myStream.getTracks();
3081
- for(var i in tracks) {
3082
- var mst = tracks[i];
3083
- Janus.log(mst);
3084
- if(mst !== null && mst !== undefined)
3085
- mst.stop();
3086
- }
3087
- }
3088
- } catch(e) {
3089
- // Do nothing if this fails
3090
- }
3091
- config.streamExternal = false;
3092
- config.myStream = null;
3093
- // Close PeerConnection
3094
- try {
3095
- config.pc.close();
3096
- } catch(e) {
3097
- // Do nothing
3098
- }
3099
- config.pc = null;
3100
- config.candidates = null;
3101
- config.mySdp = null;
3102
- config.remoteSdp = null;
3103
- config.iceDone = false;
3104
- config.dataChannel = {};
3105
- config.dtmfSender = null;
3106
- }
3107
- pluginHandle.oncleanup();
3108
- }
3109
-
3110
- // Helper method to munge an SDP to enable simulcasting (Chrome only)
3111
- function mungeSdpForSimulcasting(sdp) {
3112
- // Let's munge the SDP to add the attributes for enabling simulcasting
3113
- // (based on https://gist.github.com/ggarber/a19b4c33510028b9c657)
3114
- var lines = sdp.split("\r\n");
3115
- var video = false;
3116
- var ssrc = [ -1 ], ssrc_fid = [ -1 ];
3117
- var cname = null, msid = null, mslabel = null, label = null;
3118
- var insertAt = -1;
3119
- for(var i=0; i<lines.length; i++) {
3120
- var mline = lines[i].match(/m=(\w+) */);
3121
- if(mline) {
3122
- var medium = mline[1];
3123
- if(medium === "video") {
3124
- // New video m-line: make sure it's the first one
3125
- if(ssrc[0] < 0) {
3126
- video = true;
3127
- } else {
3128
- // We're done, let's add the new attributes here
3129
- insertAt = i;
3130
- break;
3131
- }
3132
- } else {
3133
- // New non-video m-line: do we have what we were looking for?
3134
- if(ssrc[0] > -1) {
3135
- // We're done, let's add the new attributes here
3136
- insertAt = i;
3137
- break;
3138
- }
3139
- }
3140
- continue;
3141
- }
3142
- if(!video)
3143
- continue;
3144
- var fid = lines[i].match(/a=ssrc-group:FID (\d+) (\d+)/);
3145
- if(fid) {
3146
- ssrc[0] = fid[1];
3147
- ssrc_fid[0] = fid[2];
3148
- lines.splice(i, 1); i--;
3149
- continue;
3150
- }
3151
- if(ssrc[0]) {
3152
- var match = lines[i].match('a=ssrc:' + ssrc[0] + ' cname:(.+)')
3153
- if(match) {
3154
- cname = match[1];
3155
- }
3156
- match = lines[i].match('a=ssrc:' + ssrc[0] + ' msid:(.+)')
3157
- if(match) {
3158
- msid = match[1];
3159
- }
3160
- match = lines[i].match('a=ssrc:' + ssrc[0] + ' mslabel:(.+)')
3161
- if(match) {
3162
- mslabel = match[1];
3163
- }
3164
- match = lines[i].match('a=ssrc:' + ssrc[0] + ' label:(.+)')
3165
- if(match) {
3166
- label = match[1];
3167
- }
3168
- if(lines[i].indexOf('a=ssrc:' + ssrc_fid[0]) === 0) {
3169
- lines.splice(i, 1); i--;
3170
- continue;
3171
- }
3172
- if(lines[i].indexOf('a=ssrc:' + ssrc[0]) === 0) {
3173
- lines.splice(i, 1); i--;
3174
- continue;
3175
- }
3176
- }
3177
- if(lines[i].length == 0) {
3178
- lines.splice(i, 1); i--;
3179
- continue;
3180
- }
3181
- }
3182
- if(ssrc[0] < 0) {
3183
- // Couldn't find a FID attribute, let's just take the first video SSRC we find
3184
- insertAt = -1;
3185
- video = false;
3186
- for(var i=0; i<lines.length; i++) {
3187
- var mline = lines[i].match(/m=(\w+) */);
3188
- if(mline) {
3189
- var medium = mline[1];
3190
- if(medium === "video") {
3191
- // New video m-line: make sure it's the first one
3192
- if(ssrc[0] < 0) {
3193
- video = true;
3194
- } else {
3195
- // We're done, let's add the new attributes here
3196
- insertAt = i;
3197
- break;
3198
- }
3199
- } else {
3200
- // New non-video m-line: do we have what we were looking for?
3201
- if(ssrc[0] > -1) {
3202
- // We're done, let's add the new attributes here
3203
- insertAt = i;
3204
- break;
3205
- }
3206
- }
3207
- continue;
3208
- }
3209
- if(!video)
3210
- continue;
3211
- if(ssrc[0] < 0) {
3212
- var value = lines[i].match(/a=ssrc:(\d+)/);
3213
- if(value) {
3214
- ssrc[0] = value[1];
3215
- lines.splice(i, 1); i--;
3216
- continue;
3217
- }
3218
- } else {
3219
- var match = lines[i].match('a=ssrc:' + ssrc[0] + ' cname:(.+)')
3220
- if(match) {
3221
- cname = match[1];
3222
- }
3223
- match = lines[i].match('a=ssrc:' + ssrc[0] + ' msid:(.+)')
3224
- if(match) {
3225
- msid = match[1];
3226
- }
3227
- match = lines[i].match('a=ssrc:' + ssrc[0] + ' mslabel:(.+)')
3228
- if(match) {
3229
- mslabel = match[1];
3230
- }
3231
- match = lines[i].match('a=ssrc:' + ssrc[0] + ' label:(.+)')
3232
- if(match) {
3233
- label = match[1];
3234
- }
3235
- if(lines[i].indexOf('a=ssrc:' + ssrc_fid[0]) === 0) {
3236
- lines.splice(i, 1); i--;
3237
- continue;
3238
- }
3239
- if(lines[i].indexOf('a=ssrc:' + ssrc[0]) === 0) {
3240
- lines.splice(i, 1); i--;
3241
- continue;
3242
- }
3243
- }
3244
- if(lines[i].length == 0) {
3245
- lines.splice(i, 1); i--;
3246
- continue;
3247
- }
3248
- }
3249
- }
3250
- if(ssrc[0] < 0) {
3251
- // Still nothing, let's just return the SDP we were asked to munge
3252
- Janus.warn("Couldn't find the video SSRC, simulcasting NOT enabled");
3253
- return sdp;
3254
- }
3255
- if(insertAt < 0) {
3256
- // Append at the end
3257
- insertAt = lines.length;
3258
- }
3259
- // Generate a couple of SSRCs (for retransmissions too)
3260
- // Note: should we check if there are conflicts, here?
3261
- ssrc[1] = Math.floor(Math.random()*0xFFFFFFFF);
3262
- ssrc[2] = Math.floor(Math.random()*0xFFFFFFFF);
3263
- ssrc_fid[1] = Math.floor(Math.random()*0xFFFFFFFF);
3264
- ssrc_fid[2] = Math.floor(Math.random()*0xFFFFFFFF);
3265
- // Add attributes to the SDP
3266
- for(var i=0; i<ssrc.length; i++) {
3267
- if(cname) {
3268
- lines.splice(insertAt, 0, 'a=ssrc:' + ssrc[i] + ' cname:' + cname);
3269
- insertAt++;
3270
- }
3271
- if(msid) {
3272
- lines.splice(insertAt, 0, 'a=ssrc:' + ssrc[i] + ' msid:' + msid);
3273
- insertAt++;
3274
- }
3275
- if(mslabel) {
3276
- lines.splice(insertAt, 0, 'a=ssrc:' + ssrc[i] + ' mslabel:' + mslabel);
3277
- insertAt++;
3278
- }
3279
- if(label) {
3280
- lines.splice(insertAt, 0, 'a=ssrc:' + ssrc[i] + ' label:' + label);
3281
- insertAt++;
3282
- }
3283
- // Add the same info for the retransmission SSRC
3284
- if(cname) {
3285
- lines.splice(insertAt, 0, 'a=ssrc:' + ssrc_fid[i] + ' cname:' + cname);
3286
- insertAt++;
3287
- }
3288
- if(msid) {
3289
- lines.splice(insertAt, 0, 'a=ssrc:' + ssrc_fid[i] + ' msid:' + msid);
3290
- insertAt++;
3291
- }
3292
- if(mslabel) {
3293
- lines.splice(insertAt, 0, 'a=ssrc:' + ssrc_fid[i] + ' mslabel:' + mslabel);
3294
- insertAt++;
3295
- }
3296
- if(label) {
3297
- lines.splice(insertAt, 0, 'a=ssrc:' + ssrc_fid[i] + ' label:' + label);
3298
- insertAt++;
3299
- }
3300
- }
3301
- lines.splice(insertAt, 0, 'a=ssrc-group:FID ' + ssrc[2] + ' ' + ssrc_fid[2]);
3302
- lines.splice(insertAt, 0, 'a=ssrc-group:FID ' + ssrc[1] + ' ' + ssrc_fid[1]);
3303
- lines.splice(insertAt, 0, 'a=ssrc-group:FID ' + ssrc[0] + ' ' + ssrc_fid[0]);
3304
- lines.splice(insertAt, 0, 'a=ssrc-group:SIM ' + ssrc[0] + ' ' + ssrc[1] + ' ' + ssrc[2]);
3305
- sdp = lines.join("\r\n");
3306
- if(!sdp.endsWith("\r\n"))
3307
- sdp += "\r\n";
3308
- return sdp;
3309
- }
3310
-
3311
- // Helper methods to parse a media object
3312
- function isAudioSendEnabled(media) {
3313
- Janus.debug("isAudioSendEnabled:", media);
3314
- if(media === undefined || media === null)
3315
- return true; // Default
3316
- if(media.audio === false)
3317
- return false; // Generic audio has precedence
3318
- if(media.audioSend === undefined || media.audioSend === null)
3319
- return true; // Default
3320
- return (media.audioSend === true);
3321
- }
3322
-
3323
- function isAudioSendRequired(media) {
3324
- Janus.debug("isAudioSendRequired:", media);
3325
- if(media === undefined || media === null)
3326
- return false; // Default
3327
- if(media.audio === false || media.audioSend === false)
3328
- return false; // If we're not asking to capture audio, it's not required
3329
- if(media.failIfNoAudio === undefined || media.failIfNoAudio === null)
3330
- return false; // Default
3331
- return (media.failIfNoAudio === true);
3332
- }
3333
-
3334
- function isAudioRecvEnabled(media) {
3335
- Janus.debug("isAudioRecvEnabled:", media);
3336
- if(media === undefined || media === null)
3337
- return true; // Default
3338
- if(media.audio === false)
3339
- return false; // Generic audio has precedence
3340
- if(media.audioRecv === undefined || media.audioRecv === null)
3341
- return true; // Default
3342
- return (media.audioRecv === true);
3343
- }
3344
-
3345
- function isVideoSendEnabled(media) {
3346
- Janus.debug("isVideoSendEnabled:", media);
3347
- if(media === undefined || media === null)
3348
- return true; // Default
3349
- if(media.video === false)
3350
- return false; // Generic video has precedence
3351
- if(media.videoSend === undefined || media.videoSend === null)
3352
- return true; // Default
3353
- return (media.videoSend === true);
3354
- }
3355
-
3356
- function isVideoSendRequired(media) {
3357
- Janus.debug("isVideoSendRequired:", media);
3358
- if(media === undefined || media === null)
3359
- return false; // Default
3360
- if(media.video === false || media.videoSend === false)
3361
- return false; // If we're not asking to capture video, it's not required
3362
- if(media.failIfNoVideo === undefined || media.failIfNoVideo === null)
3363
- return false; // Default
3364
- return (media.failIfNoVideo === true);
3365
- }
3366
-
3367
- function isVideoRecvEnabled(media) {
3368
- Janus.debug("isVideoRecvEnabled:", media);
3369
- if(media === undefined || media === null)
3370
- return true; // Default
3371
- if(media.video === false)
3372
- return false; // Generic video has precedence
3373
- if(media.videoRecv === undefined || media.videoRecv === null)
3374
- return true; // Default
3375
- return (media.videoRecv === true);
3376
- }
3377
-
3378
- function isScreenSendEnabled(media) {
3379
- Janus.debug("isScreenSendEnabled:", media);
3380
- if (media === undefined || media === null)
3381
- return false;
3382
- if (typeof media.video !== 'object' || typeof media.video.mandatory !== 'object')
3383
- return false;
3384
- var constraints = media.video.mandatory;
3385
- if (constraints.chromeMediaSource)
3386
- return constraints.chromeMediaSource === 'desktop' || constraints.chromeMediaSource === 'screen';
3387
- else if (constraints.mozMediaSource)
3388
- return constraints.mozMediaSource === 'window' || constraints.mozMediaSource === 'screen';
3389
- else if (constraints.mediaSource)
3390
- return constraints.mediaSource === 'window' || constraints.mediaSource === 'screen';
3391
- return false;
3392
- }
3393
-
3394
- function isDataEnabled(media) {
3395
- Janus.debug("isDataEnabled:", media);
3396
- if(Janus.webRTCAdapter.browserDetails.browser == "edge") {
3397
- Janus.warn("Edge doesn't support data channels yet");
3398
- return false;
3399
- }
3400
- if(media === undefined || media === null)
3401
- return false; // Default
3402
- return (media.data === true);
3403
- }
3404
-
3405
- function isTrickleEnabled(trickle) {
3406
- Janus.debug("isTrickleEnabled:", trickle);
3407
- if(trickle === undefined || trickle === null)
3408
- return true; // Default is true
3409
- return (trickle === true);
3410
- }
3411
- };
3412
-
3413
- exports.default = Janus