forked from simplewebrtc/SimpleWebRTC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimplewebrtc.bundle.js
1214 lines (1026 loc) · 35.3 KB
/
simplewebrtc.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(e){if("function"==typeof bootstrap)bootstrap("simplewebrtc",e);else if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else if("undefined"!=typeof ses){if(!ses.ok())return;ses.makeSimpleWebRTC=e}else"undefined"!=typeof window?window.SimpleWebRTC=e():global.SimpleWebRTC=e()})(function(){var define,ses,bootstrap,module,exports;
return (function(e,t,n){function i(n,s){if(!t[n]){if(!e[n]){var o=typeof require=="function"&&require;if(!s&&o)return o(n,!0);if(r)return r(n,!0);throw new Error("Cannot find module '"+n+"'")}var u=t[n]={exports:{}};e[n][0].call(u.exports,function(t){var r=e[n][1][t];return i(r?r:t)},u,u.exports)}return t[n].exports}var r=typeof require=="function"&&require;for(var s=0;s<n.length;s++)i(n[s]);return i})({1:[function(require,module,exports){
var WebRTC = require('webrtc');
var WildEmitter = require('wildemitter');
var webrtcSupport = require('webrtcsupport');
var attachMediaStream = require('attachmediastream');
var getScreenMedia = require('getscreenmedia');
function SimpleWebRTC(opts) {
var self = this;
var options = opts || {};
var config = this.config = {
url: 'http://signaling.simplewebrtc.com:8888',
log: options.log,
localVideoEl: '',
remoteVideosEl: '',
autoRequestMedia: false,
autoRemoveVideos: true
};
var item, connection;
// set options
for (item in options) {
this.config[item] = options[item];
}
// attach detected support for convenience
this.capabilities = webrtcSupport;
// call WildEmitter constructor
WildEmitter.call(this);
// our socket.io connection
connection = this.connection = io.connect(this.config.url);
connection.on('connect', function () {
self.emit('ready', connection.socket.sessionid);
self.sessionReady = true;
self.testReadiness();
});
connection.on('message', function (message) {
var peers = self.webrtc.getPeers(message.from, message.roomType);
var peer;
if (message.type === 'offer') {
peer = self.webrtc.createPeer({
id: message.from,
type: message.roomType,
sharemyscreen: message.roomType === 'screen' && !message.broadcaster
});
peer.handleMessage(message);
} else if (peers.length) {
peers.forEach(function (peer) {
peer.handleMessage(message);
});
}
});
connection.on('remove', function (room) {
if (room.id !== self.connection.socket.sessionid) {
self.webrtc.removePeers(room.id, room.type);
}
});
// instantiate our main WebRTC helper
this.webrtc = new WebRTC(opts);
// attach a few methods from underlying lib to simple.
['mute', 'unmute', 'pause', 'resume'].forEach(function (method) {
self[method] = self.webrtc[method].bind(self.webrtc);
});
// proxy events from WebRTC
this.webrtc.on('*', function (eventname, event) {
var args = [].splice.call(arguments, 0, 0, eventname);
//self.emit.apply(self, args);
});
// check for readiness
this.webrtc.on('localStream', function () {
self.testReadiness();
});
this.webrtc.on('message', function (payload) {
self.connection.emit('message', payload);
});
this.webrtc.on('peerStreamAdded', this.handlePeerStreamAdded.bind(this));
this.webrtc.on('peerStreamRemoved', this.handlePeerStreamRemoved.bind(this));
if (this.config.autoRequestMedia) this.startLocalVideo();
}
SimpleWebRTC.prototype = Object.create(WildEmitter.prototype, {
constructor: {
value: SimpleWebRTC
}
});
SimpleWebRTC.prototype.leaveRoom = function () {
if (this.roomName) {
this.connection.emit('leave', this.roomName);
this.peers.forEach(function (peer) {
peer.end();
});
}
};
SimpleWebRTC.prototype.handlePeerStreamAdded = function (peer) {
var container = this.getRemoteVideoContainer();
var video = attachMediaStream(peer.stream);
// store video element as part of peer for easy removal
peer.videoEl = video;
video.id = this.getDomId(peer);
if (container) container.appendChild(video);
this.emit('videoAdded', video, peer);
};
SimpleWebRTC.prototype.handlePeerStreamRemoved = function (peer) {
var container = this.getRemoteVideoContainer();
var videoEl = peer.videoEl;
if (this.config.autoRemoveVideos && container && videoEl) {
container.removeChild(videoEl);
}
if (videoEl) this.emit('videoRemoved', videoEl, peer);
};
SimpleWebRTC.prototype.getDomId = function (peer) {
return [peer.id, peer.type, peer.broadcaster ? 'broadcasting' : 'incoming'].join('_');
};
SimpleWebRTC.prototype.joinRoom = function (name, cb) {
var self = this;
this.roomName = name;
this.connection.emit('join', name, function (err, roomDescription) {
if (err) {
self.emit('error', err);
} else {
var id,
client,
type,
peer;
for (id in roomDescription.clients) {
client = roomDescription.clients[id];
for (type in client) {
if (client[type]) {
peer = self.webrtc.createPeer({
id: id,
type: type
});
peer.start();
}
}
}
}
if (cb) cb(err, roomDescription);
});
};
SimpleWebRTC.prototype.getEl = function (idOrEl) {
if (typeof idOrEl === 'string') {
return document.getElementById(idOrEl);
} else {
return idOrEl;
}
};
SimpleWebRTC.prototype.startLocalVideo = function () {
var self = this;
this.webrtc.startLocalMedia(null, function (err, stream) {
console.log('starting local media', err, stream);
if (err) {
self.emit(err);
} else {
attachMediaStream(stream, self.getLocalVideoContainer(), {muted: true, mirror: true});
}
});
};
// this accepts either element ID or element
// and either the video tag itself or a container
// that will be used to put the video tag into.
SimpleWebRTC.prototype.getLocalVideoContainer = function () {
var el = this.getEl(this.config.localVideoEl);
if (el && el.tagName === 'VIDEO') {
return el;
} else if (el) {
var video = document.createElement('video');
el.appendChild(video);
return video;
} else {
return;
}
};
SimpleWebRTC.prototype.getRemoteVideoContainer = function () {
return this.getEl(this.config.remoteVideosEl);
};
SimpleWebRTC.prototype.shareScreen = function (cb) {
var self = this,
peer;
getScreenMedia(function (err, stream) {
var item,
el = document.createElement('video'),
container = self.getRemoteVideoContainer();
if (!err) {
self.webrtc.localScreen = stream;
el.id = 'localScreen';
attachMediaStream(stream, el);
if (container) {
container.appendChild(el);
}
// TODO: Once this chrome bug is fixed:
// https://code.google.com/p/chromium/issues/detail?id=227485
// we need to listen for the screenshare stream ending and call
// the "stopScreenShare" method to clean things up.
self.emit('localScreenAdded', el);
self.connection.emit('shareScreen');
self.webrtc.peers.forEach(function (existingPeer) {
var peer;
if (existingPeer.type === 'video') {
peer = self.webrtc.createPeer({
id: existingPeer.id,
type: 'screen',
sharemyscreen: true,
broadcaster: self.connection.socket.sessionid
});
peer.start();
}
});
} else {
self.emit(err);
}
// enable the callback
if (cb) cb(err, stream);
});
};
SimpleWebRTC.prototype.getLocalScreen = function () {
return this.webrtc.localScreen;
};
SimpleWebRTC.prototype.stopScreenShare = function () {
this.connection.emit('unshareScreen');
var videoEl = document.getElementById('localScreen');
var container = this.getRemoteVideoContainer();
var stream = this.getLocalScreen();
if (this.config.autoRemoveVideos && container && videoEl) {
container.removeChild(videoEl);
}
// a hack to emit the event the removes the video
// element that we want
if (videoEl) this.emit('videoRemoved', videoEl);
if (stream) stream.stop();
this.webrtc.peers.forEach(function (peer) {
if (peer.broadcaster) {
peer.end();
}
});
delete this.webrtc.localScreen;
};
SimpleWebRTC.prototype.testReadiness = function () {
var self = this;
if (this.webrtc.localStream && this.sessionReady) {
// This timeout is a workaround for the strange no-audio bug
// as described here: https://code.google.com/p/webrtc/issues/detail?id=1525
// remove timeout when this is fixed.
setTimeout(function () {
self.emit('readyToCall', self.connection.socket.sessionid);
}, 1000);
}
};
SimpleWebRTC.prototype.createRoom = function (name, cb) {
if (arguments.length === 2) {
this.connection.emit('create', name, cb);
} else {
this.connection.emit('create', name);
}
};
module.exports = SimpleWebRTC;
},{"attachmediastream":5,"getscreenmedia":6,"webrtc":2,"webrtcsupport":4,"wildemitter":3}],3:[function(require,module,exports){
/*
WildEmitter.js is a slim little event emitter by @henrikjoreteg largely based
on @visionmedia's Emitter from UI Kit.
Why? I wanted it standalone.
I also wanted support for wildcard emitters like this:
emitter.on('*', function (eventName, other, event, payloads) {
});
emitter.on('somenamespace*', function (eventName, payloads) {
});
Please note that callbacks triggered by wildcard registered events also get
the event name as the first argument.
*/
module.exports = WildEmitter;
function WildEmitter() {
this.callbacks = {};
}
// Listen on the given `event` with `fn`. Store a group name if present.
WildEmitter.prototype.on = function (event, groupName, fn) {
var hasGroup = (arguments.length === 3),
group = hasGroup ? arguments[1] : undefined,
func = hasGroup ? arguments[2] : arguments[1];
func._groupName = group;
(this.callbacks[event] = this.callbacks[event] || []).push(func);
return this;
};
// Adds an `event` listener that will be invoked a single
// time then automatically removed.
WildEmitter.prototype.once = function (event, groupName, fn) {
var self = this,
hasGroup = (arguments.length === 3),
group = hasGroup ? arguments[1] : undefined,
func = hasGroup ? arguments[2] : arguments[1];
function on() {
self.off(event, on);
func.apply(this, arguments);
}
this.on(event, group, on);
return this;
};
// Unbinds an entire group
WildEmitter.prototype.releaseGroup = function (groupName) {
var item, i, len, handlers;
for (item in this.callbacks) {
handlers = this.callbacks[item];
for (i = 0, len = handlers.length; i < len; i++) {
if (handlers[i]._groupName === groupName) {
//console.log('removing');
// remove it and shorten the array we're looping through
handlers.splice(i, 1);
i--;
len--;
}
}
}
return this;
};
// Remove the given callback for `event` or all
// registered callbacks.
WildEmitter.prototype.off = function (event, fn) {
var callbacks = this.callbacks[event],
i;
if (!callbacks) return this;
// remove all handlers
if (arguments.length === 1) {
delete this.callbacks[event];
return this;
}
// remove specific handler
i = callbacks.indexOf(fn);
callbacks.splice(i, 1);
return this;
};
// Emit `event` with the given args.
// also calls any `*` handlers
WildEmitter.prototype.emit = function (event) {
var args = [].slice.call(arguments, 1),
callbacks = this.callbacks[event],
specialCallbacks = this.getWildcardCallbacks(event),
i,
len,
item;
if (callbacks) {
for (i = 0, len = callbacks.length; i < len; ++i) {
if (callbacks[i]) {
callbacks[i].apply(this, args);
} else {
break;
}
}
}
if (specialCallbacks) {
for (i = 0, len = specialCallbacks.length; i < len; ++i) {
if (specialCallbacks[i]) {
specialCallbacks[i].apply(this, [event].concat(args));
} else {
break;
}
}
}
return this;
};
// Helper for for finding special wildcard event handlers that match the event
WildEmitter.prototype.getWildcardCallbacks = function (eventName) {
var item,
split,
result = [];
for (item in this.callbacks) {
split = item.split('*');
if (item === '*' || (split.length === 2 && eventName.slice(0, split[1].length) === split[1])) {
result = result.concat(this.callbacks[item]);
}
}
return result;
};
},{}],4:[function(require,module,exports){
// created by @HenrikJoreteg
var PC = window.mozRTCPeerConnection || window.webkitRTCPeerConnection || window.RTCPeerConnection;
var IceCandidate = window.mozRTCIceCandidate || window.RTCIceCandidate;
var SessionDescription = window.mozRTCSessionDescription || window.RTCSessionDescription;
var prefix = function () {
if (window.mozRTCPeerConnection) {
return 'moz';
} else if (window.webkitRTCPeerConnection) {
return 'webkit';
}
}();
var screenSharing = navigator.userAgent.match('Chrome') && parseInt(navigator.userAgent.match(/Chrome\/(.*) /)[1], 10) >= 26;
var webAudio = !!window.webkitAudioContext;
// export support flags and constructors.prototype && PC
module.exports = {
support: !!PC,
dataChannel: !!(PC && PC.prototype && PC.prototype.createDataChannel),
prefix: prefix,
webAudio: webAudio,
screenSharing: screenSharing,
PeerConnection: PC,
SessionDescription: SessionDescription,
IceCandidate: IceCandidate
};
},{}],5:[function(require,module,exports){
module.exports = function (stream, el, options) {
var URL = window.URL;
var opts = {
autoplay: true,
mirror: false,
muted: false
};
var element = el || document.createElement('video');
var item;
if (options) {
for (item in options) {
opts[item] = options[item];
}
}
if (opts.autoplay) element.autoplay = 'autoplay';
if (opts.muted) element.muted = true;
if (opts.mirror) {
['', 'moz', 'webkit', 'o', 'ms'].forEach(function (prefix) {
var styleName = prefix ? prefix + 'Transform' : 'transform';
element.style[styleName] = 'scaleX(-1)';
});
}
// this first one should work most everywhere now
// but we have a few fallbacks just in case.
if (URL && URL.createObjectURL) {
element.src = URL.createObjectURL(stream);
} else if (element.srcObject) {
element.srcObject = stream;
} else if (element.mozSrcObject) {
element.mozSrcObject = stream;
} else {
return false;
}
return element;
};
},{}],6:[function(require,module,exports){
// getScreenMedia helper by @HenrikJoreteg
var getUserMedia = require('getusermedia');
module.exports = function (cb) {
var constraints = {
video: {
mandatory: {
chromeMediaSource: 'screen'
}
}
};
var error;
if (window.location.protocol === 'http:') {
error = new Error('NavigatorUserMediaError');
error.name = 'HTTPS_REQUIRED';
return cb(error);
}
getUserMedia(constraints, cb);
};
},{"getusermedia":7}],8:[function(require,module,exports){
// getUserMedia helper by @HenrikJoreteg
var func = (navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
module.exports = function (constraints, cb) {
var options;
var haveOpts = arguments.length === 2;
var defaultOpts = {video: true, audio: true};
var error;
var denied = 'PERMISSION_DENIED';
var notSatified = 'CONSTRAINT_NOT_SATISFIED';
// make constraints optional
if (!haveOpts) {
cb = constraints;
constraints = defaultOpts;
}
// treat lack of browser support like an error
if (!func) {
// throw proper error per spec
error = new Error('NavigatorUserMediaError');
error.name = 'NOT_SUPPORTED_ERROR';
return cb(error);
}
func.call(navigator, constraints, function (stream) {
cb(null, stream);
}, function (err) {
var error;
// coerce into an error object since FF gives us a string
// there are only two valid names according to the spec
// we coerce all non-denied to "constraint not satisfied".
if (typeof err === 'string') {
error = new Error('NavigatorUserMediaError');
if (err === denied) {
error.name = denied;
} else {
error.name = notSatified;
}
} else {
// if we get an error object make sure '.name' property is set
// according to spec: http://dev.w3.org/2011/webrtc/editor/getusermedia.html#navigatorusermediaerror-and-navigatorusermediaerrorcallback
error = err;
if (!error.name) {
// this is likely chrome which
// sets a property called "ERROR_DENIED" on the error object
// if so we make sure to set a name
if (error[denied]) {
err.name = denied;
} else {
err.name = notSatified;
}
}
}
cb(error);
});
};
},{}],7:[function(require,module,exports){
// getUserMedia helper by @HenrikJoreteg
var func = (navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
module.exports = function (constraints, cb) {
var options;
var haveOpts = arguments.length === 2;
var defaultOpts = {video: true, audio: true};
var error;
var denied = 'PERMISSION_DENIED';
var notSatified = 'CONSTRAINT_NOT_SATISFIED';
// make constraints optional
if (!haveOpts) {
cb = constraints;
constraints = defaultOpts;
}
// treat lack of browser support like an error
if (!func) {
// throw proper error per spec
error = new Error('NavigatorUserMediaError');
error.name = 'NOT_SUPPORTED_ERROR';
return cb(error);
}
func.call(navigator, constraints, function (stream) {
cb(null, stream);
}, function (err) {
var error;
// coerce into an error object since FF gives us a string
// there are only two valid names according to the spec
// we coerce all non-denied to "constraint not satisfied".
if (typeof err === 'string') {
error = new Error('NavigatorUserMediaError');
if (err === denied) {
error.name = denied;
} else {
error.name = notSatified;
}
} else {
// if we get an error object make sure '.name' property is set
// according to spec: http://dev.w3.org/2011/webrtc/editor/getusermedia.html#navigatorusermediaerror-and-navigatorusermediaerrorcallback
error = err;
if (!error.name) {
// this is likely chrome which
// sets a property called "ERROR_DENIED" on the error object
// if so we make sure to set a name
if (error[denied]) {
err.name = denied;
} else {
err.name = notSatified;
}
}
}
cb(error);
});
};
},{}],2:[function(require,module,exports){
var webrtc = require('webrtcsupport');
var getUserMedia = require('getusermedia');
var PeerConnection = require('rtcpeerconnection');
var WildEmitter = require('wildemitter');
var hark = require('hark');
var log;
function WebRTC(opts) {
var self = this;
var options = opts || {};
var config = this.config = {
log: false,
localVideoEl: '',
remoteVideosEl: '',
autoRequestMedia: false,
// makes the entire PC config overridable
peerConnectionConfig: {
iceServers: [{"url": "stun:stun.l.google.com:19302"}]
},
peerConnectionContraints: {
optional: [
{DtlsSrtpKeyAgreement: true},
{RtpDataChannels: true}
]
},
media: {
audio: true,
video: true
}
};
var item, connection;
// check for support
if (!webrtc.support) {
console.error('Your browser doesn\'t seem to support WebRTC');
}
// expose screensharing check
this.screenSharingSupport = webrtc.screenSharing;
// set options
for (item in options) {
this.config[item] = options[item];
}
// log if configured to
log = (this.config.log) ? console.log.bind(console) : function () {};
// where we'll store our peer connections
this.peers = [];
WildEmitter.call(this);
// log events
if (this.config.log) {
this.on('*', function (event, val1, val2) {
log('event:', event, val1, val2);
});
}
}
WebRTC.prototype = Object.create(WildEmitter.prototype, {
constructor: {
value: WebRTC
}
});
WebRTC.prototype.createPeer = function (opts) {
var peer;
opts.parent = this;
peer = new Peer(opts);
this.peers.push(peer);
return peer;
};
WebRTC.prototype.startLocalMedia = function (mediaConstraints, cb) {
var self = this;
var constraints = mediaConstraints || {video: true, audio: true};
getUserMedia(constraints, function (err, stream) {
if (!err) {
if (constraints.audio) {
self.setupAudioMonitor(stream);
}
self.localStream = self.setupMicVolumeControl(stream);
// start out somewhat muted if we can track audio
self.setMicVolume(0.5);
self.emit('localStream', stream);
}
if (cb) cb(err, stream);
});
};
// Audio controls
WebRTC.prototype.mute = function () {
this._audioEnabled(false);
this.hardMuted = true;
this.emit('audioOff');
};
WebRTC.prototype.unmute = function () {
this._audioEnabled(true);
this.hardMuted = false;
this.emit('audioOn');
};
// Audio monitor
WebRTC.prototype.setupAudioMonitor = function (stream) {
log('Setup audio');
var audio = hark(stream);
var self = this;
var timeout;
audio.on('speaking', function() {
if (self.hardMuted) return;
self.setMicVolume(1);
self.sendToAll('speaking', {});
});
audio.on('stopped_speaking', function() {
if (self.hardMuted) return;
if (timeout) clearTimeout(timeout);
timeout = setTimeout(function () {
self.setMicVolume(0.5);
self.sendToAll('stopped_speaking', {});
}, 1000);
});
};
WebRTC.prototype.setupMicVolumeControl = function (stream) {
if (!webrtc.webAudio) return stream;
var context = new webkitAudioContext();
var microphone = context.createMediaStreamSource(stream);
var gainFilter = this.gainFilter = context.createGainNode();
var destination = context.createMediaStreamDestination();
var outputStream = destination.stream;
microphone.connect(gainFilter);
gainFilter.connect(destination);
stream.removeTrack(stream.getAudioTracks()[0]);
stream.addTrack(outputStream.getAudioTracks()[0]);
return stream;
};
WebRTC.prototype.setMicVolume = function (volume) {
if (!webrtc.webAudio) return;
this.gainFilter.gain.value = volume;
};
// Video controls
WebRTC.prototype.pauseVideo = function () {
this._videoEnabled(false);
this.emit('videoOff');
};
WebRTC.prototype.resumeVideo = function () {
this._videoEnabled(true);
this.emit('videoOn');
};
// Combined controls
WebRTC.prototype.pause = function () {
this._audioEnabled(false);
this.pauseVideo();
};
WebRTC.prototype.resume = function () {
this._audioEnabled(true);
this.resumeVideo();
};
// Internal methods for enabling/disabling audio/video
WebRTC.prototype._audioEnabled = function (bool) {
// work around for chrome 27 bug where disabling tracks
// doesn't seem to work (works in canary, remove when working)
this.setMicVolume(bool ? 1 : 0);
this.localStream.getAudioTracks().forEach(function (track) {
track.enabled = !!bool;
});
};
WebRTC.prototype._videoEnabled = function (bool) {
this.localStream.getVideoTracks().forEach(function (track) {
track.enabled = !!bool;
});
};
// removes peers
WebRTC.prototype.removePeers = function (id, type) {
this.getPeers(id, type).forEach(function (peer) {
peer.end();
});
};
// fetches all Peer objects by session id and/or type
WebRTC.prototype.getPeers = function (sessionId, type) {
return this.peers.filter(function (peer) {
return (!sessionId || peer.id === sessionId) && (!type || peer.type === type);
});
};
// sends message to all
WebRTC.prototype.sendToAll = function (message, payload) {
this.peers.forEach(function (peer) {
peer.send(message, payload);
});
};
function Peer(options) {
var self = this;
this.id = options.id;
this.parent = options.parent;
this.type = options.type || 'video';
this.oneway = options.oneway || false;
this.sharemyscreen = options.sharemyscreen || false;
this.browserPrefix = options.prefix;
this.stream = options.stream;
// Create an RTCPeerConnection via the polyfill
this.pc = new PeerConnection(this.parent.config.peerConnectionConfig, this.parent.config.peerConnectionContraints);
this.pc.on('ice', this.onIceCandidate.bind(this));
this.pc.on('addStream', this.handleRemoteStreamAdded.bind(this));
this.pc.on('removeStream', this.handleStreamRemoved.bind(this));
// handle screensharing/broadcast mode
if (options.type === 'screen') {
if (this.parent.localScreen && this.sharemyscreen) {
log('adding local screen stream to peer connection');
this.pc.addStream(this.parent.localScreen);
this.broadcaster = options.broadcaster;
}
} else {
this.pc.addStream(this.parent.localStream);
}
// call emitter constructor
WildEmitter.call(this);
// proxy events to parent
this.on('*', function (name, value) {
self.parent.emit(name, value, self);
});
}
Peer.prototype = Object.create(WildEmitter.prototype, {
constructor: {
value: Peer
}
});
Peer.prototype.handleMessage = function (message) {
var self = this;
log('getting', message.type, message);
if (message.prefix) this.browserPrefix = message.prefix;
if (message.type === 'offer') {
this.pc.answer(message.payload, function (err, sessionDesc) {
self.send('answer', sessionDesc);
});
} else if (message.type === 'answer') {
this.pc.handleAnswer(message.payload);
} else if (message.type === 'candidate') {
this.pc.processIce(message.payload);
} else if (message.type === 'speaking') {
this.parent.emit('speaking', {id: message.from});
} else if (message.type === 'stopped_speaking') {
this.parent.emit('stopped_speaking', {id: message.from});
}
};
Peer.prototype.send = function (messageType, payload) {
var message = {
to: this.id,
broadcaster: this.broadcaster,
roomType: this.type,
type: messageType,
payload: payload,
prefix: webrtc.prefix
};
log('sending', messageType, message);
this.parent.emit('message', message);
};
Peer.prototype.onIceCandidate = function (candidate) {
if (this.closed) return;
if (candidate) {
this.send('candidate', candidate);
} else {
log("End of candidates.");
}
};
Peer.prototype.start = function () {
var self = this;
this.pc.offer(function (err, sessionDescription) {
self.send('offer', sessionDescription);
});
};
Peer.prototype.end = function () {
this.pc.close();
this.handleStreamRemoved();
};
Peer.prototype.handleRemoteStreamAdded = function (event) {
this.stream = event.stream;
this.parent.emit('peerStreamAdded', this);
};
Peer.prototype.handleStreamRemoved = function () {
this.parent.peers.splice(this.parent.peers.indexOf(this), 1);
this.closed = true;
this.parent.emit('peerStreamRemoved', this);
};
module.exports = WebRTC;
},{"getusermedia":8,"hark":10,"rtcpeerconnection":9,"webrtcsupport":4,"wildemitter":3}],9:[function(require,module,exports){
var WildEmitter = require('wildemitter');
var webrtc = require('webrtcsupport');
function PeerConnection(config, constraints) {
this.pc = new webrtc.PeerConnection(config, constraints);
WildEmitter.call(this);
this.pc.onicecandidate = this._onIce.bind(this);
this.pc.onaddstream = this._onAddStream.bind(this);
this.pc.onremovestream = this._onRemoveStream.bind(this);
if (config.debug) {
this.on('*', function (eventName, event) {
console.log('PeerConnection event:', eventName, event);
});
}
}
PeerConnection.prototype = Object.create(WildEmitter.prototype, {