-
Notifications
You must be signed in to change notification settings - Fork 60
/
rtcpeerconnection.js
945 lines (865 loc) · 34.4 KB
/
rtcpeerconnection.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
var util = require('util');
var SJJ = require('sdp-jingle-json');
var WildEmitter = require('wildemitter');
var cloneDeep = require('lodash.clonedeep');
function PeerConnection(config, constraints) {
var self = this;
var item;
WildEmitter.call(this);
config = config || {};
config.iceServers = config.iceServers || [];
// make sure this only gets enabled in Google Chrome
// EXPERIMENTAL FLAG, might get removed without notice
this.enableChromeNativeSimulcast = false;
if (constraints && constraints.optional && window.chrome &&
navigator.appVersion.match(/Chromium\//) === null) {
constraints.optional.forEach(function (constraint) {
if (constraint.enableChromeNativeSimulcast) {
self.enableChromeNativeSimulcast = true;
}
});
}
// EXPERIMENTAL FLAG, might get removed without notice
this.enableMultiStreamHacks = false;
if (constraints && constraints.optional && window.chrome) {
constraints.optional.forEach(function (constraint) {
if (constraint.enableMultiStreamHacks) {
self.enableMultiStreamHacks = true;
}
});
}
// EXPERIMENTAL FLAG, might get removed without notice
this.restrictBandwidth = 0;
if (constraints && constraints.optional) {
constraints.optional.forEach(function (constraint) {
if (constraint.andyetRestrictBandwidth) {
self.restrictBandwidth = constraint.andyetRestrictBandwidth;
}
});
}
// EXPERIMENTAL FLAG, might get removed without notice
// bundle up ice candidates, only works for jingle mode
// number > 0 is the delay to wait for additional candidates
// ~20ms seems good
this.batchIceCandidates = 0;
if (constraints && constraints.optional) {
constraints.optional.forEach(function (constraint) {
if (constraint.andyetBatchIce) {
self.batchIceCandidates = constraint.andyetBatchIce;
}
});
}
this.batchedIceCandidates = [];
// EXPERIMENTAL FLAG, might get removed without notice
// this attemps to strip out candidates with an already known foundation
// and type -- i.e. those which are gathered via the same TURN server
// but different transports (TURN udp, tcp and tls respectively)
if (constraints && constraints.optional && window.chrome) {
constraints.optional.forEach(function (constraint) {
if (constraint.andyetFasterICE) {
self.eliminateDuplicateCandidates = constraint.andyetFasterICE;
}
});
}
// EXPERIMENTAL FLAG, might get removed without notice
// when using a server such as the jitsi videobridge we don't need to signal
// our candidates
if (constraints && constraints.optional) {
constraints.optional.forEach(function (constraint) {
if (constraint.andyetDontSignalCandidates) {
self.dontSignalCandidates = constraint.andyetDontSignalCandidates;
}
});
}
// EXPERIMENTAL FLAG, might get removed without notice
this.assumeSetLocalSuccess = false;
if (constraints && constraints.optional) {
constraints.optional.forEach(function (constraint) {
if (constraint.andyetAssumeSetLocalSuccess) {
self.assumeSetLocalSuccess = constraint.andyetAssumeSetLocalSuccess;
}
});
}
// EXPERIMENTAL FLAG, might get removed without notice
// working around https://bugzilla.mozilla.org/show_bug.cgi?id=1087551
// pass in a timeout for this
if (window.navigator.mozGetUserMedia) {
if (constraints && constraints.optional) {
this.wtFirefox = 0;
constraints.optional.forEach(function (constraint) {
if (constraint.andyetFirefoxMakesMeSad) {
self.wtFirefox = constraint.andyetFirefoxMakesMeSad;
if (self.wtFirefox > 0) {
self.firefoxcandidatebuffer = [];
}
}
});
}
}
this.pc = new RTCPeerConnection(config, constraints);
if (typeof this.pc.getLocalStreams === 'function') {
this.getLocalStreams = this.pc.getLocalStreams.bind(this.pc);
} else {
this.getLocalStreams = function () {
return [];
};
}
if (typeof this.pc.getSenders === 'function') {
this.getSenders = this.pc.getSenders.bind(this.pc);
} else {
this.getSenders = function () {
return [];
};
}
if (typeof this.pc.getRemoteStreams === 'function') {
this.getRemoteStreams = this.pc.getRemoteStreams.bind(this.pc);
} else {
this.getRemoteStreams = function () {
return [];
};
}
if (typeof this.pc.getReceivers === 'function') {
this.getReceivers = this.pc.getReceivers.bind(this.pc);
} else {
this.getReceivers = function () {
return [];
};
}
this.addStream = this.pc.addStream.bind(this.pc);
this.removeStream = function (stream) {
if (typeof self.pc.removeStream === 'function') {
self.pc.removeStream.apply(self.pc, arguments);
} else if (typeof self.pc.removeTrack === 'function') {
stream.getTracks().forEach(function (track) {
self.pc.removeTrack(track);
});
}
};
if (typeof this.pc.removeTrack === 'function') {
this.removeTrack = this.pc.removeTrack.bind(this.pc);
}
// proxy some events directly
this.pc.onremovestream = this.emit.bind(this, 'removeStream');
this.pc.onremovetrack = this.emit.bind(this, 'removeTrack');
this.pc.onaddstream = this.emit.bind(this, 'addStream');
this.pc.ontrack = this.emit.bind(this, 'addTrack');
this.pc.onnegotiationneeded = this.emit.bind(this, 'negotiationNeeded');
this.pc.oniceconnectionstatechange = this.emit.bind(this, 'iceConnectionStateChange');
this.pc.onsignalingstatechange = this.emit.bind(this, 'signalingStateChange');
// handle ice candidate and data channel events
this.pc.onicecandidate = this._onIce.bind(this);
this.pc.ondatachannel = this._onDataChannel.bind(this);
this.localDescription = {
contents: []
};
this.remoteDescription = {
contents: []
};
this.config = {
debug: false,
sid: '',
isInitiator: true,
sdpSessionID: Date.now(),
useJingle: false
};
this.iceCredentials = {
local: {},
remote: {}
};
// apply our config
for (item in config) {
this.config[item] = config[item];
}
if (this.config.debug) {
this.on('*', function () {
var logger = config.logger || console;
logger.log('PeerConnection event:', arguments);
});
}
this.hadLocalStunCandidate = false;
this.hadRemoteStunCandidate = false;
this.hadLocalRelayCandidate = false;
this.hadRemoteRelayCandidate = false;
this.hadLocalIPv6Candidate = false;
this.hadRemoteIPv6Candidate = false;
// keeping references for all our data channels
// so they dont get garbage collected
// can be removed once the following bugs have been fixed
// https://crbug.com/405545
// https://bugzilla.mozilla.org/show_bug.cgi?id=964092
// to be filed for opera
this._remoteDataChannels = [];
this._localDataChannels = [];
this._candidateBuffer = [];
}
util.inherits(PeerConnection, WildEmitter);
Object.defineProperty(PeerConnection.prototype, 'signalingState', {
get: function () {
return this.pc.signalingState;
}
});
Object.defineProperty(PeerConnection.prototype, 'iceConnectionState', {
get: function () {
return this.pc.iceConnectionState;
}
});
PeerConnection.prototype._role = function () {
return this.isInitiator ? 'initiator' : 'responder';
};
// Add a stream to the peer connection object
PeerConnection.prototype.addStream = function (stream) {
this.localStream = stream;
stream.getTracks().forEach(
function(track) {
this.pc.addTrack(
track,
stream
);
}
);
};
// helper function to check if a remote candidate is a stun/relay
// candidate or an ipv6 candidate
PeerConnection.prototype._checkLocalCandidate = function (candidate) {
var cand = SJJ.toCandidateJSON(candidate);
if (cand.type == 'srflx') {
this.hadLocalStunCandidate = true;
} else if (cand.type == 'relay') {
this.hadLocalRelayCandidate = true;
}
if (cand.ip.indexOf(':') != -1) {
this.hadLocalIPv6Candidate = true;
}
};
// helper function to check if a remote candidate is a stun/relay
// candidate or an ipv6 candidate
PeerConnection.prototype._checkRemoteCandidate = function (candidate) {
var cand = SJJ.toCandidateJSON(candidate);
if (cand.type == 'srflx') {
this.hadRemoteStunCandidate = true;
} else if (cand.type == 'relay') {
this.hadRemoteRelayCandidate = true;
}
if (cand.ip.indexOf(':') != -1) {
this.hadRemoteIPv6Candidate = true;
}
};
// Init and add ice candidate object with correct constructor
PeerConnection.prototype.processIce = function (update, cb) {
cb = cb || function () {};
var self = this;
// ignore any added ice candidates to avoid errors. why does the
// spec not do this?
if (this.pc.signalingState === 'closed') return cb();
if (update.contents || (update.jingle && update.jingle.contents)) {
var contentNames = this.remoteDescription.contents.map(function (c) { return c.name; });
var contents = update.contents || update.jingle.contents;
contents.forEach(function (content) {
var transport = content.transport || {};
var candidates = transport.candidates || [];
var mline = contentNames.indexOf(content.name);
var mid = content.name;
var remoteContent = self.remoteDescription.contents.find(function (c) {
return c.name === content.name;
});
// process candidates as a callback, in case we need to
// update ufrag and pwd with offer/answer
var processCandidates = function () {
candidates.forEach(
function (candidate) {
var iceCandidate = SJJ.toCandidateSDP(candidate);
self.pc.addIceCandidate(
new RTCIceCandidate({
candidate: iceCandidate,
sdpMLineIndex: mline,
sdpMid: mid
})
).then(
function () {
// well, this success callback is pretty meaningless
},
function (err) {
self.emit('error', err);
}
);
self._checkRemoteCandidate(iceCandidate);
});
cb();
};
if (self.iceCredentials.remote[content.name] && transport.ufrag &&
self.iceCredentials.remote[content.name].ufrag !== transport.ufrag) {
if (remoteContent) {
remoteContent.transport.ufrag = transport.ufrag;
remoteContent.transport.pwd = transport.pwd;
var offer = {
type: 'offer',
jingle: self.remoteDescription
};
offer.sdp = SJJ.toSessionSDP(offer.jingle, {
sid: self.config.sdpSessionID,
role: self._role(),
direction: 'incoming'
});
self.pc.setRemoteDescription(
new RTCSessionDescription(offer)
).then(
function () {
processCandidates();
},
function (err) {
self.emit('error', err);
}
);
} else {
self.emit('error', 'ice restart failed to find matching content');
}
} else {
processCandidates();
}
});
} else {
// working around https://code.google.com/p/webrtc/issues/detail?id=3669
if (update.candidate && update.candidate.candidate.indexOf('a=') !== 0) {
update.candidate.candidate = 'a=' + update.candidate.candidate;
}
if (this.wtFirefox && this.firefoxcandidatebuffer !== null) {
// we cant add this yet due to https://bugzilla.mozilla.org/show_bug.cgi?id=1087551
if (this.pc.localDescription && this.pc.localDescription.type === 'offer') {
this.firefoxcandidatebuffer.push(update.candidate);
return cb();
}
}
self.pc.addIceCandidate(
new RTCIceCandidate(update.candidate)
).then(
function () { },
function (err) {
self.emit('error', err);
}
);
self._checkRemoteCandidate(update.candidate.candidate);
cb();
}
};
// Generate and emit an offer with the given constraints
PeerConnection.prototype.offer = function (constraints, cb) {
var self = this;
var hasConstraints = arguments.length === 2;
var mediaConstraints = hasConstraints && constraints ? constraints : {
offerToReceiveAudio: 1,
offerToReceiveVideo: 1
};
cb = hasConstraints ? cb : constraints;
cb = cb || function () {};
if (this.pc.signalingState === 'closed') return cb('Already closed');
// Actually generate the offer
this.pc.createOffer(
mediaConstraints
).then(
function (offer) {
// does not work for jingle, but jingle.js doesn't need
// this hack...
var expandedOffer = {
type: 'offer',
sdp: offer.sdp
};
if (self.assumeSetLocalSuccess) {
self.emit('offer', expandedOffer);
cb(null, expandedOffer);
}
self._candidateBuffer = [];
self.pc.setLocalDescription(offer).then(
function () {
var jingle;
if (self.config.useJingle) {
jingle = SJJ.toSessionJSON(offer.sdp, {
role: self._role(),
direction: 'outgoing'
});
jingle.sid = self.config.sid;
self.localDescription = jingle;
// Save ICE credentials
jingle.contents.forEach(function (content) {
var transport = content.transport || {};
if (transport.ufrag) {
self.iceCredentials.local[content.name] = {
ufrag: transport.ufrag,
pwd: transport.pwd
};
}
});
expandedOffer.jingle = jingle;
}
expandedOffer.sdp.split(/\r?\n/).forEach(function (line) {
if (line.indexOf('a=candidate:') === 0) {
self._checkLocalCandidate(line);
}
});
if (!self.assumeSetLocalSuccess) {
self.emit('offer', expandedOffer);
cb(null, expandedOffer);
}
},
function (err) {
self.emit('error', err);
cb(err);
}
);
},
function (err) {
self.emit('error', err);
cb(err);
}
);
};
// Process an incoming offer so that ICE may proceed before deciding
// to answer the request.
PeerConnection.prototype.handleOffer = function (offer, cb) {
cb = cb || function () {};
var self = this;
offer.type = 'offer';
if (offer.jingle) {
if (this.enableChromeNativeSimulcast) {
offer.jingle.contents.forEach(function (content) {
if (content.name === 'video') {
content.application.googConferenceFlag = true;
}
});
}
if (this.enableMultiStreamHacks) {
// add a mixed video stream as first stream
offer.jingle.contents.forEach(function (content) {
if (content.name === 'video') {
var sources = content.application.sources || [];
if (sources.length === 0 || sources[0].ssrc !== "3735928559") {
sources.unshift({
ssrc: "3735928559", // 0xdeadbeef
parameters: [
{
key: "cname",
value: "deadbeef"
},
{
key: "msid",
value: "mixyourfecintothis please"
}
]
});
content.application.sources = sources;
}
}
});
}
if (self.restrictBandwidth > 0) {
if (offer.jingle.contents.length >= 2 && offer.jingle.contents[1].name === 'video') {
var content = offer.jingle.contents[1];
var hasBw = content.application && content.application.bandwidth && content.application.bandwidth.bandwidth;
if (!hasBw) {
offer.jingle.contents[1].application.bandwidth = { type: 'AS', bandwidth: self.restrictBandwidth.toString() };
offer.sdp = SJJ.toSessionSDP(offer.jingle, {
sid: self.config.sdpSessionID,
role: self._role(),
direction: 'outgoing'
});
}
}
}
// Save ICE credentials
offer.jingle.contents.forEach(function (content) {
var transport = content.transport || {};
if (transport.ufrag) {
self.iceCredentials.remote[content.name] = {
ufrag: transport.ufrag,
pwd: transport.pwd
};
}
});
offer.sdp = SJJ.toSessionSDP(offer.jingle, {
sid: self.config.sdpSessionID,
role: self._role(),
direction: 'incoming'
});
self.remoteDescription = offer.jingle;
}
offer.sdp.split(/\r?\n/).forEach(function (line) {
if (line.indexOf('a=candidate:') === 0) {
self._checkRemoteCandidate(line);
}
});
self.pc.setRemoteDescription(
new RTCSessionDescription(offer)
).then(
function () {
cb();
},
cb
);
};
// Answer an offer with audio only
PeerConnection.prototype.answerAudioOnly = function (cb) {
var mediaConstraints = {
mandatory: {
OfferToReceiveAudio: true,
OfferToReceiveVideo: false
}
};
this._answer(mediaConstraints, cb);
};
// Answer an offer without offering to recieve
PeerConnection.prototype.answerBroadcastOnly = function (cb) {
var mediaConstraints = {
mandatory: {
OfferToReceiveAudio: false,
OfferToReceiveVideo: false
}
};
this._answer(mediaConstraints, cb);
};
// Answer an offer with given constraints default is audio/video
PeerConnection.prototype.answer = function (constraints, cb) {
var hasConstraints = arguments.length === 2;
var callback = hasConstraints ? cb : constraints;
var mediaConstraints = hasConstraints && constraints ? constraints : {
mandatory: {
OfferToReceiveAudio: true,
OfferToReceiveVideo: true
}
};
this._answer(mediaConstraints, callback);
};
// Process an answer
PeerConnection.prototype.handleAnswer = function (answer, cb) {
cb = cb || function () {};
var self = this;
if (answer.jingle) {
answer.sdp = SJJ.toSessionSDP(answer.jingle, {
sid: self.config.sdpSessionID,
role: self._role(),
direction: 'incoming'
});
self.remoteDescription = answer.jingle;
// Save ICE credentials
answer.jingle.contents.forEach(function (content) {
var transport = content.transport || {};
if (transport.ufrag) {
self.iceCredentials.remote[content.name] = {
ufrag: transport.ufrag,
pwd: transport.pwd
};
}
});
}
answer.sdp.split(/\r?\n/).forEach(function (line) {
if (line.indexOf('a=candidate:') === 0) {
self._checkRemoteCandidate(line);
}
});
self.pc.setRemoteDescription(
new RTCSessionDescription(answer)
).then(
function () {
if (self.wtFirefox) {
window.setTimeout(function () {
self.firefoxcandidatebuffer.forEach(function (candidate) {
// add candidates later
self.pc.addIceCandidate(
new RTCIceCandidate(candidate)
).then(
function () { },
function (err) {
self.emit('error', err);
}
);
self._checkRemoteCandidate(candidate.candidate);
});
self.firefoxcandidatebuffer = null;
}, self.wtFirefox);
}
cb(null);
},
cb
);
};
// Close the peer connection
PeerConnection.prototype.close = function () {
this.pc.close();
this._localDataChannels = [];
this._remoteDataChannels = [];
this.emit('close');
};
// Internal code sharing for various types of answer methods
PeerConnection.prototype._answer = function (constraints, cb) {
cb = cb || function () {};
var self = this;
if (!this.pc.remoteDescription) {
// the old API is used, call handleOffer
throw new Error('remoteDescription not set');
}
if (this.pc.signalingState === 'closed') return cb('Already closed');
self.pc.createAnswer(
constraints
).then(
function (answer) {
var sim = [];
if (self.enableChromeNativeSimulcast) {
// native simulcast part 1: add another SSRC
answer.jingle = SJJ.toSessionJSON(answer.sdp, {
role: self._role(),
direction: 'outgoing'
});
if (answer.jingle.contents.length >= 2 && answer.jingle.contents[1].name === 'video') {
var groups = answer.jingle.contents[1].application.sourceGroups || [];
var hasSim = false;
groups.forEach(function (group) {
if (group.semantics == 'SIM') hasSim = true;
});
if (!hasSim &&
answer.jingle.contents[1].application.sources.length) {
var newssrc = JSON.parse(JSON.stringify(answer.jingle.contents[1].application.sources[0]));
newssrc.ssrc = '' + Math.floor(Math.random() * 0xffffffff); // FIXME: look for conflicts
answer.jingle.contents[1].application.sources.push(newssrc);
sim.push(answer.jingle.contents[1].application.sources[0].ssrc);
sim.push(newssrc.ssrc);
groups.push({
semantics: 'SIM',
sources: sim
});
// also create an RTX one for the SIM one
var rtxssrc = JSON.parse(JSON.stringify(newssrc));
rtxssrc.ssrc = '' + Math.floor(Math.random() * 0xffffffff); // FIXME: look for conflicts
answer.jingle.contents[1].application.sources.push(rtxssrc);
groups.push({
semantics: 'FID',
sources: [newssrc.ssrc, rtxssrc.ssrc]
});
answer.jingle.contents[1].application.sourceGroups = groups;
answer.sdp = SJJ.toSessionSDP(answer.jingle, {
sid: self.config.sdpSessionID,
role: self._role(),
direction: 'outgoing'
});
}
}
}
var expandedAnswer = {
type: 'answer',
sdp: answer.sdp
};
if (self.assumeSetLocalSuccess) {
// not safe to do when doing simulcast mangling
var copy = cloneDeep(expandedAnswer);
self.emit('answer', copy);
cb(null, copy);
}
self._candidateBuffer = [];
self.pc.setLocalDescription(answer).then(
function () {
if (self.config.useJingle) {
var jingle = SJJ.toSessionJSON(answer.sdp, {
role: self._role(),
direction: 'outgoing'
});
jingle.sid = self.config.sid;
self.localDescription = jingle;
expandedAnswer.jingle = jingle;
}
if (self.enableChromeNativeSimulcast) {
// native simulcast part 2:
// signal multiple tracks to the receiver
// for anything in the SIM group
if (!expandedAnswer.jingle) {
expandedAnswer.jingle = SJJ.toSessionJSON(answer.sdp, {
role: self._role(),
direction: 'outgoing'
});
}
expandedAnswer.jingle.contents[1].application.sources.forEach(function (source, idx) {
// the floor idx/2 is a hack that relies on a particular order
// of groups, alternating between sim and rtx
source.parameters = source.parameters.map(function (parameter) {
if (parameter.key === 'msid') {
parameter.value += '-' + Math.floor(idx / 2);
}
return parameter;
});
});
expandedAnswer.sdp = SJJ.toSessionSDP(expandedAnswer.jingle, {
sid: self.sdpSessionID,
role: self._role(),
direction: 'outgoing'
});
}
expandedAnswer.sdp.split(/\r?\n/).forEach(function (line) {
if (line.indexOf('a=candidate:') === 0) {
self._checkLocalCandidate(line);
}
});
if (!self.assumeSetLocalSuccess) {
var copy = cloneDeep(expandedAnswer);
self.emit('answer', copy);
cb(null, copy);
}
},
function (err) {
self.emit('error', err);
cb(err);
}
);
},
function (err) {
self.emit('error', err);
cb(err);
}
);
};
// Internal method for emitting ice candidates on our peer object
PeerConnection.prototype._onIce = function (event) {
var self = this;
if (event.candidate) {
if (this.dontSignalCandidates) return;
var ice = event.candidate;
var expandedCandidate = {
candidate: {
candidate: ice.candidate,
sdpMid: ice.sdpMid,
sdpMLineIndex: ice.sdpMLineIndex
}
};
this._checkLocalCandidate(ice.candidate);
var cand = SJJ.toCandidateJSON(ice.candidate);
var already;
var idx;
if (this.eliminateDuplicateCandidates && cand.type === 'relay') {
// drop candidates with same foundation, component
// take local type pref into account so we don't ignore udp
// ones when we know about a TCP one. unlikely but...
already = this._candidateBuffer.filter(
function (c) {
return c.type === 'relay';
}).map(function (c) {
return c.foundation + ':' + c.component;
}
);
idx = already.indexOf(cand.foundation + ':' + cand.component);
// remember: local type pref of udp is 0, tcp 1, tls 2
if (idx > -1 && ((cand.priority >> 24) >= (already[idx].priority >> 24))) {
// drop it, same foundation with higher (worse) type pref
return;
}
}
if (this.config.bundlePolicy === 'max-bundle') {
// drop candidates which are duplicate for audio/video/data
// duplicate means same host/port but different sdpMid
already = this._candidateBuffer.filter(
function (c) {
return cand.type === c.type;
}).map(function (cand) {
return cand.address + ':' + cand.port;
}
);
idx = already.indexOf(cand.address + ':' + cand.port);
if (idx > -1) return;
}
// also drop rtcp candidates since we know the peer supports RTCP-MUX
// this is a workaround until browsers implement this natively
if (this.config.rtcpMuxPolicy === 'require' && cand.component === '2') {
return;
}
this._candidateBuffer.push(cand);
if (self.config.useJingle) {
if (!ice.sdpMid) { // firefox doesn't set this
if (self.pc.remoteDescription && self.pc.remoteDescription.type === 'offer') {
// preserve name from remote
ice.sdpMid = self.remoteDescription.contents[ice.sdpMLineIndex].name;
} else {
ice.sdpMid = self.localDescription.contents[ice.sdpMLineIndex].name;
}
}
if (!self.iceCredentials.local[ice.sdpMid]) {
var jingle = SJJ.toSessionJSON(self.pc.localDescription.sdp, {
role: self._role(),
direction: 'outgoing'
});
jingle.contents.forEach(function (content) {
var transport = content.transport || {};
if (transport.ufrag) {
self.iceCredentials.local[content.name] = {
ufrag: transport.ufrag,
pwd: transport.pwd
};
}
});
}
expandedCandidate.jingle = {
contents: [{
name: ice.sdpMid,
creator: self._role(),
transport: {
transportType: 'iceUdp',
ufrag: self.iceCredentials.local[ice.sdpMid].ufrag,
pwd: self.iceCredentials.local[ice.sdpMid].pwd,
candidates: [
cand
]
}
}]
};
if (self.batchIceCandidates > 0) {
if (self.batchedIceCandidates.length === 0) {
window.setTimeout(function () {
var contents = {};
self.batchedIceCandidates.forEach(function (content) {
content = content.contents[0];
if (!contents[content.name]) contents[content.name] = content;
contents[content.name].transport.candidates.push(content.transport.candidates[0]);
});
var newCand = {
jingle: {
contents: []
}
};
Object.keys(contents).forEach(function (name) {
newCand.jingle.contents.push(contents[name]);
});
self.batchedIceCandidates = [];
self.emit('ice', newCand);
}, self.batchIceCandidates);
}
self.batchedIceCandidates.push(expandedCandidate.jingle);
return;
}
}
this.emit('ice', expandedCandidate);
} else {
this.emit('endOfCandidates');
}
};
// Internal method for processing a new data channel being added by the
// other peer.
PeerConnection.prototype._onDataChannel = function (event) {
// make sure we keep a reference so this doesn't get garbage collected
var channel = event.channel;
this._remoteDataChannels.push(channel);
this.emit('addChannel', channel);
};
// Create a data channel spec reference:
// http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCDataChannelInit
PeerConnection.prototype.createDataChannel = function (name, opts) {
var channel = this.pc.createDataChannel(name, opts);
// make sure we keep a reference so this doesn't get garbage collected
this._localDataChannels.push(channel);
return channel;
};
PeerConnection.prototype.getStats = function () {
if (typeof arguments[0] === 'function') {
var cb = arguments[0];
this.pc.getStats().then(function (res) {
cb(null, res);
}, function (err) {
cb(err);
});
} else {
return this.pc.getStats.apply(this.pc, arguments);
}
};
module.exports = PeerConnection;