-
Notifications
You must be signed in to change notification settings - Fork 100
/
adapter.screenshare.js
3212 lines (2890 loc) · 116 KB
/
adapter.screenshare.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*! adapterjs - v0.13.3 - 2016-04-13 */
// Adapter's interface.
var AdapterJS = AdapterJS || {};
// Browserify compatibility
if(typeof exports !== 'undefined') {
module.exports = AdapterJS;
}
AdapterJS.options = AdapterJS.options || {};
// uncomment to get virtual webcams
// AdapterJS.options.getAllCams = true;
// uncomment to prevent the install prompt when the plugin in not yet installed
// AdapterJS.options.hidePluginInstallPrompt = true;
// AdapterJS version
AdapterJS.VERSION = '0.13.3';
// This function will be called when the WebRTC API is ready to be used
// Whether it is the native implementation (Chrome, Firefox, Opera) or
// the plugin
// You may Override this function to synchronise the start of your application
// with the WebRTC API being ready.
// If you decide not to override use this synchronisation, it may result in
// an extensive CPU usage on the plugin start (once per tab loaded)
// Params:
// - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
//
AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
// The WebRTC API is ready.
// Override me and do whatever you want here
};
// New interface to store multiple callbacks, private
AdapterJS._onwebrtcreadies = [];
// Sets a callback function to be called when the WebRTC interface is ready.
// The first argument is the function to callback.\
// Throws an error if the first argument is not a function
AdapterJS.webRTCReady = function (callback) {
if (typeof callback !== 'function') {
throw new Error('Callback provided is not a function');
}
if (true === AdapterJS.onwebrtcreadyDone) {
// All WebRTC interfaces are ready, just call the callback
callback(null !== AdapterJS.WebRTCPlugin.plugin);
} else {
// will be triggered automatically when your browser/plugin is ready.
AdapterJS._onwebrtcreadies.push(callback);
}
};
// Plugin namespace
AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
// The object to store plugin information
/* jshint ignore:start */
AdapterJS.WebRTCPlugin.pluginInfo = {
prefix : 'Tem',
plugName : 'TemWebRTCPlugin',
pluginId : 'plugin0',
type : 'application/x-temwebrtcplugin',
onload : '__TemWebRTCReady0',
portalLink : 'http://skylink.io/plugin/',
downloadLink : null, //set below
companyName: 'Temasys'
};
if(!!navigator.platform.match(/^Mac/i)) {
AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
}
else if(!!navigator.platform.match(/^Win/i)) {
AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
}
/* jshint ignore:end */
AdapterJS.WebRTCPlugin.TAGS = {
NONE : 'none',
AUDIO : 'audio',
VIDEO : 'video'
};
// Unique identifier of each opened page
AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
// Use this whenever you want to call the plugin.
AdapterJS.WebRTCPlugin.plugin = null;
// Set log level for the plugin once it is ready.
// The different values are
// This is an asynchronous function that will run when the plugin is ready
AdapterJS.WebRTCPlugin.setLogLevel = null;
// Defines webrtc's JS interface according to the plugin's implementation.
// Define plugin Browsers as WebRTC Interface.
AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
// This function detects whether or not a plugin is installed.
// Checks if Not IE (firefox, for example), else if it's IE,
// we're running IE and do something. If not it is not supported.
AdapterJS.WebRTCPlugin.isPluginInstalled = null;
// Lets adapter.js wait until the the document is ready before injecting the plugin
AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
// Inject the HTML DOM object element into the page.
AdapterJS.WebRTCPlugin.injectPlugin = null;
// States of readiness that the plugin goes through when
// being injected and stated
AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
NONE : 0, // no plugin use
INITIALIZING : 1, // Detected need for plugin
INJECTING : 2, // Injecting plugin
INJECTED: 3, // Plugin element injected but not usable yet
READY: 4 // Plugin ready to be used
};
// Current state of the plugin. You cannot use the plugin before this is
// equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
// True is AdapterJS.onwebrtcready was already called, false otherwise
// Used to make sure AdapterJS.onwebrtcready is only called once
AdapterJS.onwebrtcreadyDone = false;
// Log levels for the plugin.
// To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
/*
Log outputs are prefixed in some cases.
INFO: Information reported by the plugin.
ERROR: Errors originating from within the plugin.
WEBRTC: Error originating from within the libWebRTC library
*/
// From the least verbose to the most verbose
AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
NONE : 'NONE',
ERROR : 'ERROR',
WARNING : 'WARNING',
INFO: 'INFO',
VERBOSE: 'VERBOSE',
SENSITIVE: 'SENSITIVE'
};
// Does a waiting check before proceeding to load the plugin.
AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
// This methid will use an interval to wait for the plugin to be ready.
AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
// !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
// This function will be called when plugin is ready. It sends necessary
// details to the plugin.
// The function will wait for the document to be ready and the set the
// plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
// indicating that it can start being requested.
// This function is not in the IE/Safari condition brackets so that
// TemPluginLoaded function might be called on Chrome/Firefox.
// This function is the only private function that is not encapsulated to
// allow the plugin method to be called.
__TemWebRTCReady0 = function () {
if (document.readyState === 'complete') {
AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
AdapterJS.maybeThroughWebRTCReady();
} else {
var timer = setInterval(function () {
if (document.readyState === 'complete') {
// TODO: update comments, we wait for the document to be ready
clearInterval(timer);
AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
AdapterJS.maybeThroughWebRTCReady();
}
}, 100);
}
};
AdapterJS.maybeThroughWebRTCReady = function() {
if (!AdapterJS.onwebrtcreadyDone) {
AdapterJS.onwebrtcreadyDone = true;
// If new interface for multiple callbacks used
if (AdapterJS._onwebrtcreadies.length) {
AdapterJS._onwebrtcreadies.forEach(function (callback) {
if (typeof(callback) === 'function') {
callback(AdapterJS.WebRTCPlugin.plugin !== null);
}
});
// Else if no callbacks on new interface assuming user used old(deprecated) way to set callback through AdapterJS.onwebrtcready = ...
} else if (typeof(AdapterJS.onwebrtcready) === 'function') {
AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
}
}
};
// Text namespace
AdapterJS.TEXT = {
PLUGIN: {
REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
'to work on this browser.',
NOT_SUPPORTED: 'Your browser does not support WebRTC.',
BUTTON: 'Install Now'
},
REFRESH: {
REQUIRE_REFRESH: 'Please refresh page',
BUTTON: 'Refresh Page'
}
};
// The result of ice connection states.
// - starting: Ice connection is starting.
// - checking: Ice connection is checking.
// - connected Ice connection is connected.
// - completed Ice connection is connected.
// - done Ice connection has been completed.
// - disconnected Ice connection has been disconnected.
// - failed Ice connection has failed.
// - closed Ice connection is closed.
AdapterJS._iceConnectionStates = {
starting : 'starting',
checking : 'checking',
connected : 'connected',
completed : 'connected',
done : 'completed',
disconnected : 'disconnected',
failed : 'failed',
closed : 'closed'
};
//The IceConnection states that has been fired for each peer.
AdapterJS._iceConnectionFiredStates = [];
// Check if WebRTC Interface is defined.
AdapterJS.isDefined = null;
// This function helps to retrieve the webrtc detected browser information.
// This sets:
// - webrtcDetectedBrowser: The browser agent name.
// - webrtcDetectedVersion: The browser version.
// - webrtcMinimumVersion: The minimum browser version still supported by AJS.
// - webrtcDetectedType: The types of webRTC support.
// - 'moz': Mozilla implementation of webRTC.
// - 'webkit': WebKit implementation of webRTC.
// - 'plugin': Using the plugin implementation.
AdapterJS.parseWebrtcDetectedBrowser = function () {
var hasMatch = null;
if ((!!window.opr && !!opr.addons) ||
!!window.opera ||
navigator.userAgent.indexOf(' OPR/') >= 0) {
// Opera 8.0+
webrtcDetectedBrowser = 'opera';
webrtcDetectedType = 'webkit';
webrtcMinimumVersion = 26;
hasMatch = /OPR\/(\d+)/i.exec(navigator.userAgent) || [];
webrtcDetectedVersion = parseInt(hasMatch[1], 10);
} else if (typeof InstallTrigger !== 'undefined') {
// Firefox 1.0+
// Bowser and Version set in Google's adapter
webrtcDetectedType = 'moz';
} else if (Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
// Safari
webrtcDetectedBrowser = 'safari';
webrtcDetectedType = 'plugin';
webrtcMinimumVersion = 7;
hasMatch = /version\/(\d+)/i.exec(navigator.userAgent) || [];
webrtcDetectedVersion = parseInt(hasMatch[1], 10);
} else if (/*@cc_on!@*/false || !!document.documentMode) {
// Internet Explorer 6-11
webrtcDetectedBrowser = 'IE';
webrtcDetectedType = 'plugin';
webrtcMinimumVersion = 9;
hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
if (!webrtcDetectedVersion) {
hasMatch = /\bMSIE[ :]+(\d+)/g.exec(navigator.userAgent) || [];
webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
}
} else if (!!window.StyleMedia) {
// Edge 20+
// Bowser and Version set in Google's adapter
webrtcDetectedType = '';
} else if (!!window.chrome && !!window.chrome.webstore) {
// Chrome 1+
// Bowser and Version set in Google's adapter
webrtcDetectedType = 'webkit';
} else if ((webrtcDetectedBrowser === 'chrome'|| webrtcDetectedBrowser === 'opera') &&
!!window.CSS) {
// Blink engine detection
webrtcDetectedBrowser = 'blink';
// TODO: detected WebRTC version
}
window.webrtcDetectedBrowser = webrtcDetectedBrowser;
window.webrtcDetectedVersion = webrtcDetectedVersion;
window.webrtcMinimumVersion = webrtcMinimumVersion;
};
AdapterJS.addEvent = function(elem, evnt, func) {
if (elem.addEventListener) { // W3C DOM
elem.addEventListener(evnt, func, false);
} else if (elem.attachEvent) {// OLD IE DOM
elem.attachEvent('on'+evnt, func);
} else { // No much to do
elem[evnt] = func;
}
};
AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
// only inject once the page is ready
if (document.readyState !== 'complete') {
return;
}
var w = window;
var i = document.createElement('iframe');
i.name = 'adapterjs-alert';
i.style.position = 'fixed';
i.style.top = '-41px';
i.style.left = 0;
i.style.right = 0;
i.style.width = '100%';
i.style.height = '40px';
i.style.backgroundColor = '#ffffe1';
i.style.border = 'none';
i.style.borderBottom = '1px solid #888888';
i.style.zIndex = '9999999';
if(typeof i.style.webkitTransition === 'string') {
i.style.webkitTransition = 'all .5s ease-out';
} else if(typeof i.style.transition === 'string') {
i.style.transition = 'all .5s ease-out';
}
document.body.appendChild(i);
var c = (i.contentWindow) ? i.contentWindow :
(i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
c.document.open();
c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
'middle; cursor: default;">' + text + '</span>');
if(buttonText && buttonLink) {
c.document.write('<button id="okay">' + buttonText + '</button><button id="cancel">Cancel</button>');
c.document.close();
// On click on okay
AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
if (!!displayRefreshBar) {
AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()'); // jshint ignore:line
}
window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
e.preventDefault();
try {
e.cancelBubble = true;
} catch(error) { }
var pluginInstallInterval = setInterval(function(){
if(! isIE) {
navigator.plugins.refresh(false);
}
AdapterJS.WebRTCPlugin.isPluginInstalled(
AdapterJS.WebRTCPlugin.pluginInfo.prefix,
AdapterJS.WebRTCPlugin.pluginInfo.plugName,
function() { // plugin now installed
clearInterval(pluginInstallInterval);
AdapterJS.WebRTCPlugin.defineWebRTCInterface();
},
function() {
// still no plugin detected, nothing to do
});
} , 500);
});
// On click on Cancel
AdapterJS.addEvent(c.document.getElementById('cancel'), 'click', function(e) {
w.document.body.removeChild(i);
});
} else {
c.document.close();
}
setTimeout(function() {
if(typeof i.style.webkitTransform === 'string') {
i.style.webkitTransform = 'translateY(40px)';
} else if(typeof i.style.transform === 'string') {
i.style.transform = 'translateY(40px)';
} else {
i.style.top = '0px';
}
}, 300);
};
// -----------------------------------------------------------
// Detected webrtc implementation. Types are:
// - 'moz': Mozilla implementation of webRTC.
// - 'webkit': WebKit implementation of webRTC.
// - 'plugin': Using the plugin implementation.
webrtcDetectedType = null;
// Set the settings for creating DataChannels, MediaStream for
// Cross-browser compability.
// - This is only for SCTP based support browsers.
// the 'urls' attribute.
checkMediaDataChannelSettings =
function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
if (typeof callback !== 'function') {
return;
}
var beOfferer = true;
var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
// Nightly version does not require MozDontOfferDataChannel for interop
var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
var isPeerFirefox = peerBrowserAgent === 'firefox';
var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
// Resends an updated version of constraints for MozDataChannel to work
// If other userAgent is firefox and user is firefox, remove MozDataChannel
if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
try {
delete constraints.mandatory.MozDontOfferDataChannel;
} catch (error) {
console.error('Failed deleting MozDontOfferDataChannel');
console.error(error);
}
} else if ((isLocalFirefox && !isPeerFirefox)) {
constraints.mandatory.MozDontOfferDataChannel = true;
}
if (!isLocalFirefox) {
// temporary measure to remove Moz* constraints in non Firefox browsers
for (var prop in constraints.mandatory) {
if (constraints.mandatory.hasOwnProperty(prop)) {
if (prop.indexOf('Moz') !== -1) {
delete constraints.mandatory[prop];
}
}
}
}
// Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
// interopability of the media stream
if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
beOfferer = false;
}
callback(beOfferer, constraints);
};
// Handles the differences for all browsers ice connection state output.
// - Tested outcomes are:
// - Chrome (offerer) : 'checking' > 'completed' > 'completed'
// - Chrome (answerer) : 'checking' > 'connected'
// - Firefox (offerer) : 'checking' > 'connected'
// - Firefox (answerer): 'checking' > 'connected'
checkIceConnectionState = function (peerId, iceConnectionState, callback) {
if (typeof callback !== 'function') {
console.warn('No callback specified in checkIceConnectionState. Aborted.');
return;
}
peerId = (peerId) ? peerId : 'peer';
if (!AdapterJS._iceConnectionFiredStates[peerId] ||
iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
iceConnectionState === AdapterJS._iceConnectionStates.failed ||
iceConnectionState === AdapterJS._iceConnectionStates.closed) {
AdapterJS._iceConnectionFiredStates[peerId] = [];
}
iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
setTimeout(function () {
AdapterJS._iceConnectionFiredStates[peerId]
.push(AdapterJS._iceConnectionStates.done);
callback(AdapterJS._iceConnectionStates.done);
}, 1000);
}
callback(iceConnectionState);
}
return;
};
// Firefox:
// - Creates iceServer from the url for Firefox.
// - Create iceServer with stun url.
// - Create iceServer with turn url.
// - Ignore the transport parameter from TURN url for FF version <=27.
// - Return null for createIceServer if transport=tcp.
// - FF 27 and above supports transport parameters in TURN url,
// - So passing in the full url to create iceServer.
// Chrome:
// - Creates iceServer from the url for Chrome M33 and earlier.
// - Create iceServer with stun url.
// - Chrome M28 & above uses below TURN format.
// Plugin:
// - Creates Ice Server for Plugin Browsers
// - If Stun - Create iceServer with stun url.
// - Else - Create iceServer with turn url
// - This is a WebRTC Function
createIceServer = null;
// Firefox:
// - Creates IceServers for Firefox
// - Use .url for FireFox.
// - Multiple Urls support
// Chrome:
// - Creates iceServers from the urls for Chrome M34 and above.
// - .urls is supported since Chrome M34.
// - Multiple Urls support
// Plugin:
// - Creates Ice Servers for Plugin Browsers
// - Multiple Urls support
// - This is a WebRTC Function
createIceServers = null;
//------------------------------------------------------------
//The RTCPeerConnection object.
RTCPeerConnection = null;
// Creates RTCSessionDescription object for Plugin Browsers
RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
RTCSessionDescription : null;
// Creates RTCIceCandidate object for Plugin Browsers
RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
RTCIceCandidate : null;
// Get UserMedia (only difference is the prefix).
// Code from Adam Barth.
getUserMedia = null;
// Attach a media stream to an element.
attachMediaStream = null;
// Re-attach a media stream to an element.
reattachMediaStream = null;
// Detected browser agent name. Types are:
// - 'firefox': Firefox browser.
// - 'chrome': Chrome browser.
// - 'opera': Opera browser.
// - 'safari': Safari browser.
// - 'IE' - Internet Explorer browser.
webrtcDetectedBrowser = null;
// Detected browser version.
webrtcDetectedVersion = null;
// The minimum browser version still supported by AJS.
webrtcMinimumVersion = null;
// Check for browser types and react accordingly
if ( navigator.mozGetUserMedia ||
navigator.webkitGetUserMedia ||
(navigator.mediaDevices &&
navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)) ) {
///////////////////////////////////////////////////////////////////
// INJECTION OF GOOGLE'S ADAPTER.JS CONTENT
/* jshint ignore:start */
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* More information about these options at jshint.com/docs/options */
/* jshint browser: true, camelcase: true, curly: true, devel: true,
eqeqeq: true, forin: false, globalstrict: true, node: true,
quotmark: single, undef: true, unused: strict */
/* global mozRTCIceCandidate, mozRTCPeerConnection, Promise,
mozRTCSessionDescription, webkitRTCPeerConnection, MediaStreamTrack,
MediaStream, RTCIceGatherer, RTCIceTransport, RTCDtlsTransport,
RTCRtpSender, RTCRtpReceiver*/
/* exported trace,requestUserMedia */
'use strict';
var getUserMedia = null;
var attachMediaStream = null;
var reattachMediaStream = null;
var webrtcDetectedBrowser = null;
var webrtcDetectedVersion = null;
var webrtcMinimumVersion = null;
var webrtcUtils = {
log: function() {
// suppress console.log output when being included as a module.
if (typeof module !== 'undefined' ||
typeof require === 'function' && typeof define === 'function') {
return;
}
console.log.apply(console, arguments);
},
extractVersion: function(uastring, expr, pos) {
var match = uastring.match(expr);
return match && match.length >= pos && parseInt(match[pos], 10);
}
};
function trace(text) {
// This function is used for logging.
if (text[text.length - 1] === '\n') {
text = text.substring(0, text.length - 1);
}
if (window.performance) {
var now = (window.performance.now() / 1000).toFixed(3);
webrtcUtils.log(now + ': ' + text);
} else {
webrtcUtils.log(text);
}
}
if (typeof window === 'object') {
if (window.HTMLMediaElement &&
!('srcObject' in window.HTMLMediaElement.prototype)) {
// Shim the srcObject property, once, when HTMLMediaElement is found.
Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', {
get: function() {
// If prefixed srcObject property exists, return it.
// Otherwise use the shimmed property, _srcObject
return 'mozSrcObject' in this ? this.mozSrcObject : this._srcObject;
},
set: function(stream) {
if ('mozSrcObject' in this) {
this.mozSrcObject = stream;
} else {
// Use _srcObject as a private property for this shim
this._srcObject = stream;
// TODO: revokeObjectUrl(this.src) when !stream to release resources?
this.src = URL.createObjectURL(stream);
}
}
});
}
// Proxy existing globals
getUserMedia = window.navigator && window.navigator.getUserMedia;
}
// Attach a media stream to an element.
attachMediaStream = function(element, stream) {
element.srcObject = stream;
};
reattachMediaStream = function(to, from) {
to.srcObject = from.srcObject;
};
if (typeof window === 'undefined' || !window.navigator) {
webrtcUtils.log('This does not appear to be a browser');
webrtcDetectedBrowser = 'not a browser';
} else if (navigator.mozGetUserMedia) {
webrtcUtils.log('This appears to be Firefox');
webrtcDetectedBrowser = 'firefox';
// the detected firefox version.
webrtcDetectedVersion = webrtcUtils.extractVersion(navigator.userAgent,
/Firefox\/([0-9]+)\./, 1);
// the minimum firefox version still supported by adapter.
webrtcMinimumVersion = 31;
// Shim for RTCPeerConnection on older versions.
if (!window.RTCPeerConnection) {
window.RTCPeerConnection = function(pcConfig, pcConstraints) {
if (webrtcDetectedVersion < 38) {
// .urls is not supported in FF < 38.
// create RTCIceServers with a single url.
if (pcConfig && pcConfig.iceServers) {
var newIceServers = [];
for (var i = 0; i < pcConfig.iceServers.length; i++) {
var server = pcConfig.iceServers[i];
if (server.hasOwnProperty('urls')) {
for (var j = 0; j < server.urls.length; j++) {
var newServer = {
url: server.urls[j]
};
if (server.urls[j].indexOf('turn') === 0) {
newServer.username = server.username;
newServer.credential = server.credential;
}
newIceServers.push(newServer);
}
} else {
newIceServers.push(pcConfig.iceServers[i]);
}
}
pcConfig.iceServers = newIceServers;
}
}
return new mozRTCPeerConnection(pcConfig, pcConstraints); // jscs:ignore requireCapitalizedConstructors
};
// wrap static methods. Currently just generateCertificate.
if (mozRTCPeerConnection.generateCertificate) {
Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
get: function() {
if (arguments.length) {
return mozRTCPeerConnection.generateCertificate.apply(null,
arguments);
} else {
return mozRTCPeerConnection.generateCertificate;
}
}
});
}
window.RTCSessionDescription = mozRTCSessionDescription;
window.RTCIceCandidate = mozRTCIceCandidate;
}
// getUserMedia constraints shim.
getUserMedia = function(constraints, onSuccess, onError) {
var constraintsToFF37 = function(c) {
if (typeof c !== 'object' || c.require) {
return c;
}
var require = [];
Object.keys(c).forEach(function(key) {
if (key === 'require' || key === 'advanced' || key === 'mediaSource') {
return;
}
var r = c[key] = (typeof c[key] === 'object') ?
c[key] : {ideal: c[key]};
if (r.min !== undefined ||
r.max !== undefined || r.exact !== undefined) {
require.push(key);
}
if (r.exact !== undefined) {
if (typeof r.exact === 'number') {
r.min = r.max = r.exact;
} else {
c[key] = r.exact;
}
delete r.exact;
}
if (r.ideal !== undefined) {
c.advanced = c.advanced || [];
var oc = {};
if (typeof r.ideal === 'number') {
oc[key] = {min: r.ideal, max: r.ideal};
} else {
oc[key] = r.ideal;
}
c.advanced.push(oc);
delete r.ideal;
if (!Object.keys(r).length) {
delete c[key];
}
}
});
if (require.length) {
c.require = require;
}
return c;
};
if (webrtcDetectedVersion < 38) {
webrtcUtils.log('spec: ' + JSON.stringify(constraints));
if (constraints.audio) {
constraints.audio = constraintsToFF37(constraints.audio);
}
if (constraints.video) {
constraints.video = constraintsToFF37(constraints.video);
}
webrtcUtils.log('ff37: ' + JSON.stringify(constraints));
}
return navigator.mozGetUserMedia(constraints, onSuccess, onError);
};
navigator.getUserMedia = getUserMedia;
// Shim for mediaDevices on older versions.
if (!navigator.mediaDevices) {
navigator.mediaDevices = {getUserMedia: requestUserMedia,
addEventListener: function() { },
removeEventListener: function() { }
};
}
navigator.mediaDevices.enumerateDevices =
navigator.mediaDevices.enumerateDevices || function() {
return new Promise(function(resolve) {
var infos = [
{kind: 'audioinput', deviceId: 'default', label: '', groupId: ''},
{kind: 'videoinput', deviceId: 'default', label: '', groupId: ''}
];
resolve(infos);
});
};
if (webrtcDetectedVersion < 41) {
// Work around http://bugzil.la/1169665
var orgEnumerateDevices =
navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices);
navigator.mediaDevices.enumerateDevices = function() {
return orgEnumerateDevices().then(undefined, function(e) {
if (e.name === 'NotFoundError') {
return [];
}
throw e;
});
};
}
} else if (navigator.webkitGetUserMedia && window.webkitRTCPeerConnection) {
webrtcUtils.log('This appears to be Chrome');
webrtcDetectedBrowser = 'chrome';
// the detected chrome version.
webrtcDetectedVersion = webrtcUtils.extractVersion(navigator.userAgent,
/Chrom(e|ium)\/([0-9]+)\./, 2);
// the minimum chrome version still supported by adapter.
webrtcMinimumVersion = 38;
// The RTCPeerConnection object.
window.RTCPeerConnection = function(pcConfig, pcConstraints) {
// Translate iceTransportPolicy to iceTransports,
// see https://code.google.com/p/webrtc/issues/detail?id=4869
if (pcConfig && pcConfig.iceTransportPolicy) {
pcConfig.iceTransports = pcConfig.iceTransportPolicy;
}
var pc = new webkitRTCPeerConnection(pcConfig, pcConstraints); // jscs:ignore requireCapitalizedConstructors
var origGetStats = pc.getStats.bind(pc);
pc.getStats = function(selector, successCallback, errorCallback) { // jshint ignore: line
var self = this;
var args = arguments;
// If selector is a function then we are in the old style stats so just
// pass back the original getStats format to avoid breaking old users.
if (arguments.length > 0 && typeof selector === 'function') {
return origGetStats(selector, successCallback);
}
var fixChromeStats = function(response) {
var standardReport = {};
var reports = response.result();
reports.forEach(function(report) {
var standardStats = {
id: report.id,
timestamp: report.timestamp,
type: report.type
};
report.names().forEach(function(name) {
standardStats[name] = report.stat(name);
});
standardReport[standardStats.id] = standardStats;
});
return standardReport;
};
if (arguments.length >= 2) {
var successCallbackWrapper = function(response) {
args[1](fixChromeStats(response));
};
return origGetStats.apply(this, [successCallbackWrapper, arguments[0]]);
}
// promise-support
return new Promise(function(resolve, reject) {
if (args.length === 1 && selector === null) {
origGetStats.apply(self, [
function(response) {
resolve.apply(null, [fixChromeStats(response)]);
}, reject]);
} else {
origGetStats.apply(self, [resolve, reject]);
}
});
};
return pc;
};
// wrap static methods. Currently just generateCertificate.
if (webkitRTCPeerConnection.generateCertificate) {
Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
get: function() {
if (arguments.length) {
return webkitRTCPeerConnection.generateCertificate.apply(null,
arguments);
} else {
return webkitRTCPeerConnection.generateCertificate;
}
}
});
}
// add promise support
['createOffer', 'createAnswer'].forEach(function(method) {
var nativeMethod = webkitRTCPeerConnection.prototype[method];
webkitRTCPeerConnection.prototype[method] = function() {
var self = this;
if (arguments.length < 1 || (arguments.length === 1 &&
typeof(arguments[0]) === 'object')) {
var opts = arguments.length === 1 ? arguments[0] : undefined;
return new Promise(function(resolve, reject) {
nativeMethod.apply(self, [resolve, reject, opts]);
});
} else {
return nativeMethod.apply(this, arguments);
}
};
});
['setLocalDescription', 'setRemoteDescription',
'addIceCandidate'].forEach(function(method) {
var nativeMethod = webkitRTCPeerConnection.prototype[method];
webkitRTCPeerConnection.prototype[method] = function() {
var args = arguments;
var self = this;
return new Promise(function(resolve, reject) {
nativeMethod.apply(self, [args[0],
function() {
resolve();
if (args.length >= 2) {
args[1].apply(null, []);
}
},
function(err) {
reject(err);
if (args.length >= 3) {
args[2].apply(null, [err]);
}
}]
);
});
};
});
// getUserMedia constraints shim.
var constraintsToChrome = function(c) {
if (typeof c !== 'object' || c.mandatory || c.optional) {
return c;
}
var cc = {};
Object.keys(c).forEach(function(key) {
if (key === 'require' || key === 'advanced' || key === 'mediaSource') {
return;
}
var r = (typeof c[key] === 'object') ? c[key] : {ideal: c[key]};
if (r.exact !== undefined && typeof r.exact === 'number') {
r.min = r.max = r.exact;
}
var oldname = function(prefix, name) {
if (prefix) {
return prefix + name.charAt(0).toUpperCase() + name.slice(1);
}
return (name === 'deviceId') ? 'sourceId' : name;
};
if (r.ideal !== undefined) {
cc.optional = cc.optional || [];
var oc = {};
if (typeof r.ideal === 'number') {
oc[oldname('min', key)] = r.ideal;
cc.optional.push(oc);
oc = {};
oc[oldname('max', key)] = r.ideal;
cc.optional.push(oc);
} else {
oc[oldname('', key)] = r.ideal;
cc.optional.push(oc);
}
}
if (r.exact !== undefined && typeof r.exact !== 'number') {
cc.mandatory = cc.mandatory || {};
cc.mandatory[oldname('', key)] = r.exact;
} else {
['min', 'max'].forEach(function(mix) {
if (r[mix] !== undefined) {
cc.mandatory = cc.mandatory || {};
cc.mandatory[oldname(mix, key)] = r[mix];
}
});
}
});
if (c.advanced) {
cc.optional = (cc.optional || []).concat(c.advanced);
}
return cc;
};
getUserMedia = function(constraints, onSuccess, onError) {
if (constraints.audio) {
constraints.audio = constraintsToChrome(constraints.audio);
}
if (constraints.video) {
constraints.video = constraintsToChrome(constraints.video);
}
webrtcUtils.log('chrome: ' + JSON.stringify(constraints));
return navigator.webkitGetUserMedia(constraints, onSuccess, onError);
};
navigator.getUserMedia = getUserMedia;