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