-
Notifications
You must be signed in to change notification settings - Fork 19
/
localMedia.bundle.js
6951 lines (6294 loc) · 228 KB
/
localMedia.bundle.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
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.LocalMedia = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var util = require('util');
var hark = require('hark');
var getScreenMedia = require('getscreenmedia');
var WildEmitter = require('wildemitter');
var mockconsole = require('mockconsole');
function isAllTracksEnded(stream) {
var isAllTracksEnded = true;
stream.getTracks().forEach(function (t) {
isAllTracksEnded = t.readyState === 'ended' && isAllTracksEnded;
});
return isAllTracksEnded;
}
function LocalMedia(opts) {
WildEmitter.call(this);
var config = this.config = {
detectSpeakingEvents: false,
audioFallback: false,
media: {
audio: true,
video: true
},
harkOptions: null,
logger: mockconsole
};
var item;
for (item in opts) {
if (opts.hasOwnProperty(item)) {
this.config[item] = opts[item];
}
}
this.logger = config.logger;
this._log = this.logger.log.bind(this.logger, 'LocalMedia:');
this._logerror = this.logger.error.bind(this.logger, 'LocalMedia:');
this.localStreams = [];
this.localScreens = [];
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
this._logerror('Your browser does not support local media capture.');
}
this._audioMonitors = [];
this.on('localStreamStopped', this._stopAudioMonitor.bind(this));
this.on('localScreenStopped', this._stopAudioMonitor.bind(this));
}
util.inherits(LocalMedia, WildEmitter);
LocalMedia.prototype.start = function (mediaConstraints, cb) {
var self = this;
var constraints = mediaConstraints || this.config.media;
this.emit('localStreamRequested', constraints);
navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
if (constraints.audio && self.config.detectSpeakingEvents) {
self._setupAudioMonitor(stream, self.config.harkOptions);
}
self.localStreams.push(stream);
stream.getTracks().forEach(function (track) {
track.addEventListener('ended', function () {
if (isAllTracksEnded(stream)) {
self._removeStream(stream);
}
});
});
self.emit('localStream', stream);
if (cb) {
return cb(null, stream);
}
}).catch(function (err) {
// Fallback for users without a camera
if (self.config.audioFallback && err.name === 'NotFoundError' && constraints.video !== false) {
constraints.video = false;
self.start(constraints, cb);
return;
}
self.emit('localStreamRequestFailed', constraints);
if (cb) {
return cb(err, null);
}
});
};
LocalMedia.prototype.stop = function (stream) {
this.stopStream(stream);
this.stopScreenShare(stream);
};
LocalMedia.prototype.stopStream = function (stream) {
var self = this;
if (stream) {
var idx = this.localStreams.indexOf(stream);
if (idx > -1) {
stream.getTracks().forEach(function (track) { track.stop(); });
this._removeStream(stream);
}
} else {
this.localStreams.forEach(function (stream) {
stream.getTracks().forEach(function (track) { track.stop(); });
self._removeStream(stream);
});
}
};
LocalMedia.prototype.startScreenShare = function (constraints, cb) {
var self = this;
this.emit('localScreenRequested');
if (typeof constraints === 'function' && !cb) {
cb = constraints;
constraints = null;
}
getScreenMedia(constraints, function (err, stream) {
if (!err) {
self.localScreens.push(stream);
stream.getTracks().forEach(function (track) {
track.addEventListener('ended', function () {
var isAllTracksEnded = true;
stream.getTracks().forEach(function (t) {
isAllTracksEnded = t.readyState === 'ended' && isAllTracksEnded;
});
if (isAllTracksEnded) {
self._removeStream(stream);
}
});
});
self.emit('localScreen', stream);
} else {
self.emit('localScreenRequestFailed');
}
// enable the callback
if (cb) {
return cb(err, stream);
}
});
};
LocalMedia.prototype.stopScreenShare = function (stream) {
var self = this;
if (stream) {
var idx = this.localScreens.indexOf(stream);
if (idx > -1) {
stream.getTracks().forEach(function (track) { track.stop(); });
this._removeStream(stream);
}
} else {
this.localScreens.forEach(function (stream) {
stream.getTracks().forEach(function (track) { track.stop(); });
self._removeStream(stream);
});
}
};
// Audio controls
LocalMedia.prototype.mute = function () {
this._audioEnabled(false);
this.emit('audioOff');
};
LocalMedia.prototype.unmute = function () {
this._audioEnabled(true);
this.emit('audioOn');
};
// Video controls
LocalMedia.prototype.pauseVideo = function () {
this._videoEnabled(false);
this.emit('videoOff');
};
LocalMedia.prototype.resumeVideo = function () {
this._videoEnabled(true);
this.emit('videoOn');
};
// Combined controls
LocalMedia.prototype.pause = function () {
this.mute();
this.pauseVideo();
};
LocalMedia.prototype.resume = function () {
this.unmute();
this.resumeVideo();
};
// Internal methods for enabling/disabling audio/video
LocalMedia.prototype._audioEnabled = function (bool) {
this.localStreams.forEach(function (stream) {
stream.getAudioTracks().forEach(function (track) {
track.enabled = !!bool;
});
});
};
LocalMedia.prototype._videoEnabled = function (bool) {
this.localStreams.forEach(function (stream) {
stream.getVideoTracks().forEach(function (track) {
track.enabled = !!bool;
});
});
};
// check if all audio streams are enabled
LocalMedia.prototype.isAudioEnabled = function () {
var enabled = true;
this.localStreams.forEach(function (stream) {
stream.getAudioTracks().forEach(function (track) {
enabled = enabled && track.enabled;
});
});
return enabled;
};
// check if all video streams are enabled
LocalMedia.prototype.isVideoEnabled = function () {
var enabled = true;
this.localStreams.forEach(function (stream) {
stream.getVideoTracks().forEach(function (track) {
enabled = enabled && track.enabled;
});
});
return enabled;
};
LocalMedia.prototype._removeStream = function (stream) {
var idx = this.localStreams.indexOf(stream);
if (idx > -1) {
this.localStreams.splice(idx, 1);
this.emit('localStreamStopped', stream);
} else {
idx = this.localScreens.indexOf(stream);
if (idx > -1) {
this.localScreens.splice(idx, 1);
this.emit('localScreenStopped', stream);
}
}
};
LocalMedia.prototype._setupAudioMonitor = function (stream, harkOptions) {
this._log('Setup audio');
var audio = hark(stream, harkOptions);
var self = this;
var timeout;
audio.on('speaking', function () {
self.emit('speaking');
});
audio.on('stopped_speaking', function () {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function () {
self.emit('stoppedSpeaking');
}, 1000);
});
audio.on('volume_change', function (volume, threshold) {
self.emit('volumeChange', volume, threshold);
});
this._audioMonitors.push({audio: audio, stream: stream});
};
LocalMedia.prototype._stopAudioMonitor = function (stream) {
var idx = -1;
this._audioMonitors.forEach(function (monitors, i) {
if (monitors.stream === stream) {
idx = i;
}
});
if (idx > -1) {
this._audioMonitors[idx].audio.stop();
this._audioMonitors.splice(idx, 1);
}
};
module.exports = LocalMedia;
},{"getscreenmedia":2,"hark":3,"mockconsole":4,"util":10,"wildemitter":23}],2:[function(require,module,exports){
var adapter = require('webrtc-adapter');
module.exports = function (constraints, cb) {
var hasConstraints = arguments.length === 2;
var callback = hasConstraints ? cb : constraints;
var error;
if ('getDisplayMedia' in window.navigator.mediaDevices) { // prefer spec getDisplayMedia
window.navigator.mediaDevices.getDisplayMedia(constraints)
.then(function (stream) {
callback(null, stream);
}).catch(function (err) {
callback(err);
});
} else if (adapter.browserDetails.browser === 'chrome') {
if (sessionStorage.getScreenMediaJSExtensionId) {
// check that the extension is installed by looking for a
// sessionStorage variable that contains the extension id
// this has to be set after installation unless the content
// script does that
chrome.runtime.sendMessage(sessionStorage.getScreenMediaJSExtensionId,
{type:'getScreen', id: 1}, null,
function (data) {
if (!data || data.sourceId === '') { // user canceled
var error = new Error('NavigatorUserMediaError');
error.name = 'NotAllowedError';
callback(error);
} else {
constraints = (hasConstraints && constraints) || {audio: false, video: {
mandatory: {
chromeMediaSource: 'desktop',
maxWidth: window.screen.width,
maxHeight: window.screen.height,
maxFrameRate: 3
}
}};
constraints.video.mandatory.chromeMediaSourceId = data.sourceId;
window.navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
callback(null, stream);
}).catch(function (err) {
callback(err);
});
}
}
);
} else if (window.cefGetScreenMedia) {
//window.cefGetScreenMedia is experimental - may be removed without notice
window.cefGetScreenMedia(function(sourceId) {
if (!sourceId) {
var error = new Error('cefGetScreenMediaError');
error.name = 'CEF_GETSCREENMEDIA_CANCELED';
callback(error);
} else {
constraints = (hasConstraints && constraints) || {audio: false, video: {
mandatory: {
chromeMediaSource: 'desktop',
maxWidth: window.screen.width,
maxHeight: window.screen.height,
maxFrameRate: 3
}
}};
constraints.video.mandatory.chromeMediaSourceId = sourceId;
window.navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
callback(null, stream);
}).catch(function (err) {
callback(err);
});
}
});
} else {
error = new Error('Screensharing is not supported');
error.name = 'NotSupportedError';
callback(error);
}
} else if (adapter.browserDetails.browser === 'firefox' && adapter.browserDetails.version >= 33) {
constraints = (hasConstraints && constraints) || {
video: {
mediaSource: 'window'
}
};
window.navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
callback(null, stream);
}).catch(function (err) {
callback(err);
});
} else {
error = new Error('Screensharing is not supported');
error.name = 'NotSupportedError';
callback(error);
}
};
},{"webrtc-adapter":11}],3:[function(require,module,exports){
var WildEmitter = require('wildemitter');
function getMaxVolume (analyser, fftBins) {
var maxVolume = -Infinity;
analyser.getFloatFrequencyData(fftBins);
for(var i=4, ii=fftBins.length; i < ii; i++) {
if (fftBins[i] > maxVolume && fftBins[i] < 0) {
maxVolume = fftBins[i];
}
};
return maxVolume;
}
var audioContextType;
if (typeof window !== 'undefined') {
audioContextType = window.AudioContext || window.webkitAudioContext;
}
// use a single audio context due to hardware limits
var audioContext = null;
module.exports = function(stream, options) {
var harker = new WildEmitter();
// make it not break in non-supported browsers
if (!audioContextType) return harker;
//Config
var options = options || {},
smoothing = (options.smoothing || 0.1),
interval = (options.interval || 50),
threshold = options.threshold,
play = options.play,
history = options.history || 10,
running = true;
//Setup Audio Context
if (!audioContext) {
audioContext = new audioContextType();
}
var sourceNode, fftBins, analyser;
analyser = audioContext.createAnalyser();
analyser.fftSize = 512;
analyser.smoothingTimeConstant = smoothing;
fftBins = new Float32Array(analyser.frequencyBinCount);
if (stream.jquery) stream = stream[0];
if (stream instanceof HTMLAudioElement || stream instanceof HTMLVideoElement) {
//Audio Tag
sourceNode = audioContext.createMediaElementSource(stream);
if (typeof play === 'undefined') play = true;
threshold = threshold || -50;
} else {
//WebRTC Stream
sourceNode = audioContext.createMediaStreamSource(stream);
threshold = threshold || -50;
}
sourceNode.connect(analyser);
if (play) analyser.connect(audioContext.destination);
harker.speaking = false;
harker.setThreshold = function(t) {
threshold = t;
};
harker.setInterval = function(i) {
interval = i;
};
harker.stop = function() {
running = false;
harker.emit('volume_change', -100, threshold);
if (harker.speaking) {
harker.speaking = false;
harker.emit('stopped_speaking');
}
analyser.disconnect();
sourceNode.disconnect();
};
harker.speakingHistory = [];
for (var i = 0; i < history; i++) {
harker.speakingHistory.push(0);
}
// Poll the analyser node to determine if speaking
// and emit events if changed
var looper = function() {
setTimeout(function() {
//check if stop has been called
if(!running) {
return;
}
var currentVolume = getMaxVolume(analyser, fftBins);
harker.emit('volume_change', currentVolume, threshold);
var history = 0;
if (currentVolume > threshold && !harker.speaking) {
// trigger quickly, short history
for (var i = harker.speakingHistory.length - 3; i < harker.speakingHistory.length; i++) {
history += harker.speakingHistory[i];
}
if (history >= 2) {
harker.speaking = true;
harker.emit('speaking');
}
} else if (currentVolume < threshold && harker.speaking) {
for (var i = 0; i < harker.speakingHistory.length; i++) {
history += harker.speakingHistory[i];
}
if (history == 0) {
harker.speaking = false;
harker.emit('stopped_speaking');
}
}
harker.speakingHistory.shift();
harker.speakingHistory.push(0 + (currentVolume > threshold));
looper();
}, interval);
};
looper();
return harker;
}
},{"wildemitter":23}],4:[function(require,module,exports){
var methods = "assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(",");
var l = methods.length;
var fn = function () {};
var mockconsole = {};
while (l--) {
mockconsole[methods[l]] = fn;
}
module.exports = mockconsole;
},{}],5:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],6:[function(require,module,exports){
/*
* Copyright (c) 2017 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.
*/
/* eslint-env node */
'use strict';
var SDPUtils = require('sdp');
function fixStatsType(stat) {
return {
inboundrtp: 'inbound-rtp',
outboundrtp: 'outbound-rtp',
candidatepair: 'candidate-pair',
localcandidate: 'local-candidate',
remotecandidate: 'remote-candidate'
}[stat.type] || stat.type;
}
function writeMediaSection(transceiver, caps, type, stream, dtlsRole) {
var sdp = SDPUtils.writeRtpDescription(transceiver.kind, caps);
// Map ICE parameters (ufrag, pwd) to SDP.
sdp += SDPUtils.writeIceParameters(
transceiver.iceGatherer.getLocalParameters());
// Map DTLS parameters to SDP.
sdp += SDPUtils.writeDtlsParameters(
transceiver.dtlsTransport.getLocalParameters(),
type === 'offer' ? 'actpass' : dtlsRole || 'active');
sdp += 'a=mid:' + transceiver.mid + '\r\n';
if (transceiver.rtpSender && transceiver.rtpReceiver) {
sdp += 'a=sendrecv\r\n';
} else if (transceiver.rtpSender) {
sdp += 'a=sendonly\r\n';
} else if (transceiver.rtpReceiver) {
sdp += 'a=recvonly\r\n';
} else {
sdp += 'a=inactive\r\n';
}
if (transceiver.rtpSender) {
var trackId = transceiver.rtpSender._initialTrackId ||
transceiver.rtpSender.track.id;
transceiver.rtpSender._initialTrackId = trackId;
// spec.
var msid = 'msid:' + (stream ? stream.id : '-') + ' ' +
trackId + '\r\n';
sdp += 'a=' + msid;
// for Chrome. Legacy should no longer be required.
sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
' ' + msid;
// RTX
if (transceiver.sendEncodingParameters[0].rtx) {
sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
' ' + msid;
sdp += 'a=ssrc-group:FID ' +
transceiver.sendEncodingParameters[0].ssrc + ' ' +
transceiver.sendEncodingParameters[0].rtx.ssrc +
'\r\n';
}
}
// FIXME: this should be written by writeRtpDescription.
sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
' cname:' + SDPUtils.localCName + '\r\n';
if (transceiver.rtpSender && transceiver.sendEncodingParameters[0].rtx) {
sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
' cname:' + SDPUtils.localCName + '\r\n';
}
return sdp;
}
// Edge does not like
// 1) stun: filtered after 14393 unless ?transport=udp is present
// 2) turn: that does not have all of turn:host:port?transport=udp
// 3) turn: with ipv6 addresses
// 4) turn: occurring muliple times
function filterIceServers(iceServers, edgeVersion) {
var hasTurn = false;
iceServers = JSON.parse(JSON.stringify(iceServers));
return iceServers.filter(function(server) {
if (server && (server.urls || server.url)) {
var urls = server.urls || server.url;
if (server.url && !server.urls) {
console.warn('RTCIceServer.url is deprecated! Use urls instead.');
}
var isString = typeof urls === 'string';
if (isString) {
urls = [urls];
}
urls = urls.filter(function(url) {
var validTurn = url.indexOf('turn:') === 0 &&
url.indexOf('transport=udp') !== -1 &&
url.indexOf('turn:[') === -1 &&
!hasTurn;
if (validTurn) {
hasTurn = true;
return true;
}
return url.indexOf('stun:') === 0 && edgeVersion >= 14393 &&
url.indexOf('?transport=udp') === -1;
});
delete server.url;
server.urls = isString ? urls[0] : urls;
return !!urls.length;
}
});
}
// Determines the intersection of local and remote capabilities.
function getCommonCapabilities(localCapabilities, remoteCapabilities) {
var commonCapabilities = {
codecs: [],
headerExtensions: [],
fecMechanisms: []
};
var findCodecByPayloadType = function(pt, codecs) {
pt = parseInt(pt, 10);
for (var i = 0; i < codecs.length; i++) {
if (codecs[i].payloadType === pt ||
codecs[i].preferredPayloadType === pt) {
return codecs[i];
}
}
};
var rtxCapabilityMatches = function(lRtx, rRtx, lCodecs, rCodecs) {
var lCodec = findCodecByPayloadType(lRtx.parameters.apt, lCodecs);
var rCodec = findCodecByPayloadType(rRtx.parameters.apt, rCodecs);
return lCodec && rCodec &&
lCodec.name.toLowerCase() === rCodec.name.toLowerCase();
};
localCapabilities.codecs.forEach(function(lCodec) {
for (var i = 0; i < remoteCapabilities.codecs.length; i++) {
var rCodec = remoteCapabilities.codecs[i];
if (lCodec.name.toLowerCase() === rCodec.name.toLowerCase() &&
lCodec.clockRate === rCodec.clockRate) {
if (lCodec.name.toLowerCase() === 'rtx' &&
lCodec.parameters && rCodec.parameters.apt) {
// for RTX we need to find the local rtx that has a apt
// which points to the same local codec as the remote one.
if (!rtxCapabilityMatches(lCodec, rCodec,
localCapabilities.codecs, remoteCapabilities.codecs)) {
continue;
}
}
rCodec = JSON.parse(JSON.stringify(rCodec)); // deepcopy
// number of channels is the highest common number of channels
rCodec.numChannels = Math.min(lCodec.numChannels,
rCodec.numChannels);
// push rCodec so we reply with offerer payload type
commonCapabilities.codecs.push(rCodec);
// determine common feedback mechanisms
rCodec.rtcpFeedback = rCodec.rtcpFeedback.filter(function(fb) {
for (var j = 0; j < lCodec.rtcpFeedback.length; j++) {
if (lCodec.rtcpFeedback[j].type === fb.type &&
lCodec.rtcpFeedback[j].parameter === fb.parameter) {
return true;
}
}
return false;
});
// FIXME: also need to determine .parameters
// see https://github.com/openpeer/ortc/issues/569
break;
}
}
});
localCapabilities.headerExtensions.forEach(function(lHeaderExtension) {
for (var i = 0; i < remoteCapabilities.headerExtensions.length;
i++) {
var rHeaderExtension = remoteCapabilities.headerExtensions[i];
if (lHeaderExtension.uri === rHeaderExtension.uri) {
commonCapabilities.headerExtensions.push(rHeaderExtension);
break;
}
}
});
// FIXME: fecMechanisms
return commonCapabilities;
}
// is action=setLocalDescription with type allowed in signalingState
function isActionAllowedInSignalingState(action, type, signalingState) {
return {
offer: {
setLocalDescription: ['stable', 'have-local-offer'],
setRemoteDescription: ['stable', 'have-remote-offer']
},
answer: {
setLocalDescription: ['have-remote-offer', 'have-local-pranswer'],
setRemoteDescription: ['have-local-offer', 'have-remote-pranswer']
}
}[type][action].indexOf(signalingState) !== -1;
}
function maybeAddCandidate(iceTransport, candidate) {
// Edge's internal representation adds some fields therefore
// not all fieldѕ are taken into account.
var alreadyAdded = iceTransport.getRemoteCandidates()
.find(function(remoteCandidate) {
return candidate.foundation === remoteCandidate.foundation &&
candidate.ip === remoteCandidate.ip &&
candidate.port === remoteCandidate.port &&
candidate.priority === remoteCandidate.priority &&
candidate.protocol === remoteCandidate.protocol &&
candidate.type === remoteCandidate.type;
});
if (!alreadyAdded) {
iceTransport.addRemoteCandidate(candidate);
}
return !alreadyAdded;
}
function makeError(name, description) {
var e = new Error(description);
e.name = name;
// legacy error codes from https://heycam.github.io/webidl/#idl-DOMException-error-names
e.code = {
NotSupportedError: 9,
InvalidStateError: 11,
InvalidAccessError: 15,
TypeError: undefined,
OperationError: undefined
}[name];
return e;
}
module.exports = function(window, edgeVersion) {
// https://w3c.github.io/mediacapture-main/#mediastream
// Helper function to add the track to the stream and
// dispatch the event ourselves.
function addTrackToStreamAndFireEvent(track, stream) {
stream.addTrack(track);
stream.dispatchEvent(new window.MediaStreamTrackEvent('addtrack',
{track: track}));
}
function removeTrackFromStreamAndFireEvent(track, stream) {
stream.removeTrack(track);
stream.dispatchEvent(new window.MediaStreamTrackEvent('removetrack',
{track: track}));
}
function fireAddTrack(pc, track, receiver, streams) {
var trackEvent = new Event('track');
trackEvent.track = track;
trackEvent.receiver = receiver;
trackEvent.transceiver = {receiver: receiver};
trackEvent.streams = streams;
window.setTimeout(function() {
pc._dispatchEvent('track', trackEvent);
});
}
var RTCPeerConnection = function(config) {
var pc = this;
var _eventTarget = document.createDocumentFragment();
['addEventListener', 'removeEventListener', 'dispatchEvent']