matrix_components 2.0.300

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