forked from feross/simple-peer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
966 lines (819 loc) · 27.9 KB
/
index.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
module.exports = Peer
var debug = require('debug')('simple-peer')
var getBrowserRTC = require('get-browser-rtc')
var inherits = require('inherits')
var randombytes = require('randombytes')
var stream = require('readable-stream')
var MAX_BUFFERED_AMOUNT = 64 * 1024
inherits(Peer, stream.Duplex)
/**
* WebRTC peer connection. Same API as node core `net.Socket`, plus a few extra methods.
* Duplex stream.
* @param {Object} opts
*/
function Peer (opts) {
var self = this
if (!(self instanceof Peer)) return new Peer(opts)
self._id = randombytes(4).toString('hex').slice(0, 7)
self._debug('new peer %o', opts)
opts = Object.assign({
allowHalfOpen: false
}, opts)
stream.Duplex.call(self, opts)
self.channelName = opts.initiator
? opts.channelName || randombytes(20).toString('hex')
: null
// Needed by _transformConstraints, so set this early
self._isChromium = typeof window !== 'undefined' && !!window.webkitRTCPeerConnection
self.initiator = opts.initiator || false
self.channelConfig = opts.channelConfig || Peer.channelConfig
self.config = opts.config || Peer.config
self.constraints = self._transformConstraints(opts.constraints || Peer.constraints)
self.offerConstraints = self._transformConstraints(opts.offerConstraints || {})
self.answerConstraints = self._transformConstraints(opts.answerConstraints || {})
self.sdpTransform = opts.sdpTransform || function (sdp) { return sdp }
self.streams = opts.streams || (opts.stream ? [opts.stream] : []) // support old "stream" option
self.trickle = opts.trickle !== undefined ? opts.trickle : true
self.destroyed = false
self.connected = false
self.remoteAddress = undefined
self.remoteFamily = undefined
self.remotePort = undefined
self.localAddress = undefined
self.localPort = undefined
self._wrtc = (opts.wrtc && typeof opts.wrtc === 'object')
? opts.wrtc
: getBrowserRTC()
if (!self._wrtc) {
if (typeof window === 'undefined') {
throw makeError('No WebRTC support: Specify `opts.wrtc` option in this environment', 'ERR_WEBRTC_SUPPORT')
} else {
throw makeError('No WebRTC support: Not a supported browser', 'ERR_WEBRTC_SUPPORT')
}
}
self._pcReady = false
self._channelReady = false
self._iceComplete = false // ice candidate trickle done (got null candidate)
self._channel = null
self._pendingCandidates = []
self._isNegotiating = !self.initiator // is this peer waiting for negotiation to complete?
self._batchedNegotiation = false // batch synchronous negotiations
self._queuedNegotiation = false // is there a queued negotiation request?
self._sendersAwaitingStable = []
self._senderMap = new WeakMap()
self._remoteTracks = []
self._remoteStreams = []
self._chunk = null
self._cb = null
self._interval = null
self._pc = new (self._wrtc.RTCPeerConnection)(self.config, self.constraints)
if (self._isChromium || (self._wrtc && self._wrtc.electronDaemon)) { // HACK: Electron and Chromium need a promise shim
shimPromiseAPI(self._wrtc.RTCPeerConnection, self._pc)
}
// We prefer feature detection whenever possible, but sometimes that's not
// possible for certain implementations.
self._isReactNativeWebrtc = typeof self._pc._peerConnectionId === 'number'
self._pc.oniceconnectionstatechange = function () {
self._onIceStateChange()
}
self._pc.onicegatheringstatechange = function () {
self._onIceStateChange()
}
self._pc.onsignalingstatechange = function () {
self._onSignalingStateChange()
}
self._pc.onicecandidate = function (event) {
self._onIceCandidate(event)
}
// Other spec events, unused by this implementation:
// - onconnectionstatechange
// - onicecandidateerror
// - onfingerprintfailure
// - onnegotiationneeded
if (self.initiator) {
self._setupData({
channel: self._pc.createDataChannel(self.channelName, self.channelConfig)
})
} else {
self._pc.ondatachannel = function (event) {
self._setupData(event)
}
}
if ('addTrack' in self._pc) {
if (self.streams) {
self.streams.forEach(function (stream) {
self.addStream(stream)
})
}
self._pc.ontrack = function (event) {
self._onTrack(event)
}
}
if (self.initiator) {
self._needsNegotiation()
}
self._onFinishBound = function () {
self._onFinish()
}
self.once('finish', self._onFinishBound)
}
Peer.WEBRTC_SUPPORT = !!getBrowserRTC()
/**
* Expose config, constraints, and data channel config for overriding all Peer
* instances. Otherwise, just set opts.config, opts.constraints, or opts.channelConfig
* when constructing a Peer.
*/
Peer.config = {
iceServers: [
{
urls: 'stun:stun.l.google.com:19302'
},
{
urls: 'stun:global.stun.twilio.com:3478?transport=udp'
}
]
}
Peer.constraints = {}
Peer.channelConfig = {}
Object.defineProperty(Peer.prototype, 'bufferSize', {
get: function () {
var self = this
return (self._channel && self._channel.bufferedAmount) || 0
}
})
Peer.prototype.address = function () {
var self = this
return { port: self.localPort, family: 'IPv4', address: self.localAddress }
}
Peer.prototype.signal = function (data) {
var self = this
if (self.destroyed) throw makeError('cannot signal after peer is destroyed', 'ERR_SIGNALING')
if (typeof data === 'string') {
try {
data = JSON.parse(data)
} catch (err) {
data = {}
}
}
self._debug('signal()')
if (data.renegotiate) {
self._debug('got request to renegotiate')
self._needsNegotiation()
}
if (data.candidate) {
if (self._pc.remoteDescription && self._pc.remoteDescription.type) self._addIceCandidate(data.candidate)
else self._pendingCandidates.push(data.candidate)
}
if (data.sdp) {
self._pc.setRemoteDescription(new (self._wrtc.RTCSessionDescription)(data)).then(function () {
if (self.destroyed) return
self._pendingCandidates.forEach(function (candidate) {
self._addIceCandidate(candidate)
})
self._pendingCandidates = []
if (self._pc.remoteDescription.type === 'offer') self._createAnswer()
}).catch(function (err) { self.destroy(makeError(err, 'ERR_SET_REMOTE_DESCRIPTION')) })
}
if (!data.sdp && !data.candidate && !data.renegotiate) {
self.destroy(makeError('signal() called with invalid signal data', 'ERR_SIGNALING'))
}
}
Peer.prototype._addIceCandidate = function (candidate) {
var self = this
try {
self._pc.addIceCandidate(
new self._wrtc.RTCIceCandidate(candidate),
noop,
function (err) { self.destroy(makeError(err, 'ERR_ADD_ICE_CANDIDATE')) }
)
} catch (err) {
self.destroy(makeError('error adding candidate: ' + err.message, 'ERR_ADD_ICE_CANDIDATE'))
}
}
/**
* Send text/binary data to the remote peer.
* @param {ArrayBufferView|ArrayBuffer|Buffer|string|Blob} chunk
*/
Peer.prototype.send = function (chunk) {
var self = this
self._channel.send(chunk)
}
/**
* Add a MediaStream to the connection.
* @param {MediaStream} stream
*/
Peer.prototype.addStream = function (stream) {
var self = this
self._debug('addStream()')
stream.getTracks().forEach(function (track) {
self.addTrack(track, stream)
})
}
/**
* Add a MediaStreamTrack to the connection.
* @param {MediaStreamTrack} track
* @param {MediaStream} stream
*/
Peer.prototype.addTrack = function (track, stream) {
var self = this
self._debug('addTrack()')
var sender = self._pc.addTrack(track, stream)
var submap = self._senderMap.get(track) || new WeakMap() // nested WeakMaps map [track, stream] to sender
submap.set(stream, sender)
self._senderMap.set(track, submap)
self._needsNegotiation()
}
/**
* Remove a MediaStreamTrack from the connection.
* @param {MediaStreamTrack} track
* @param {MediaStream} stream
*/
Peer.prototype.removeTrack = function (track, stream) {
var self = this
self._debug('removeSender()')
var submap = self._senderMap.get(track)
var sender = submap ? submap.get(stream) : null
if (!sender) {
self.destroy(new Error('Cannot remove track that was never added.'))
}
try {
self._pc.removeTrack(sender)
} catch (err) {
if (err.name === 'NS_ERROR_UNEXPECTED') {
self._sendersAwaitingStable.push(sender) // HACK: Firefox must wait until (signalingState === stable) https://bugzilla.mozilla.org/show_bug.cgi?id=1133874
} else {
self.destroy(err)
}
}
}
/**
* Remove a MediaStream from the connection.
* @param {MediaStream} stream
*/
Peer.prototype.removeStream = function (stream) {
var self = this
self._debug('removeSenders()')
stream.getTracks().forEach(function (track) {
self.removeTrack(track, stream)
})
}
Peer.prototype._needsNegotiation = function () {
var self = this
self._debug('_needsNegotiation')
if (self._batchedNegotiation) return // batch synchronous renegotiations
self._batchedNegotiation = true
setTimeout(function () {
self._batchedNegotiation = false
self._debug('starting batched negotiation')
self.negotiate()
}, 0)
}
Peer.prototype.negotiate = function () {
var self = this
if (self.initiator) {
if (self._isNegotiating) {
self._queuedNegotiation = true
self._debug('already negotiating, queueing')
} else {
self._debug('start negotiation')
self._createOffer()
}
} else {
if (!self._isNegotiating) {
self._debug('requesting negotiation from initiator')
self.emit('signal', { // request initiator to renegotiate
renegotiate: true
})
}
}
self._isNegotiating = true
}
// TODO: Delete this method once readable-stream is updated to contain a default
// implementation of destroy() that automatically calls _destroy()
// See: https://github.com/nodejs/readable-stream/issues/283
Peer.prototype.destroy = function (err) {
var self = this
self._destroy(err, function () {})
}
Peer.prototype._destroy = function (err, cb) {
var self = this
if (self.destroyed) return
self._debug('destroy (error: %s)', err && (err.message || err))
self.readable = self.writable = false
if (!self._readableState.ended) self.push(null)
if (!self._writableState.finished) self.end()
self.destroyed = true
self.connected = false
self._pcReady = false
self._channelReady = false
self._remoteTracks = null
self._remoteStreams = null
self._senderMap = null
clearInterval(self._interval)
self._interval = null
self._chunk = null
self._cb = null
if (self._onFinishBound) self.removeListener('finish', self._onFinishBound)
self._onFinishBound = null
if (self._channel) {
try {
self._channel.close()
} catch (err) {}
self._channel.onmessage = null
self._channel.onopen = null
self._channel.onclose = null
self._channel.onerror = null
}
if (self._pc) {
try {
self._pc.close()
} catch (err) {}
self._pc.oniceconnectionstatechange = null
self._pc.onicegatheringstatechange = null
self._pc.onsignalingstatechange = null
self._pc.onicecandidate = null
if ('addTrack' in self._pc) {
self._pc.ontrack = null
}
self._pc.ondatachannel = null
}
self._pc = null
self._channel = null
if (err) self.emit('error', err)
self.emit('close')
cb()
}
Peer.prototype._setupData = function (event) {
var self = this
if (!event.channel) {
// In some situations `pc.createDataChannel()` returns `undefined` (in wrtc),
// which is invalid behavior. Handle it gracefully.
// See: https://github.com/feross/simple-peer/issues/163
return self.destroy(makeError('Data channel event is missing `channel` property', 'ERR_DATA_CHANNEL'))
}
self._channel = event.channel
self._channel.binaryType = 'arraybuffer'
if (typeof self._channel.bufferedAmountLowThreshold === 'number') {
self._channel.bufferedAmountLowThreshold = MAX_BUFFERED_AMOUNT
}
self.channelName = self._channel.label
self._channel.onmessage = function (event) {
self._onChannelMessage(event)
}
self._channel.onbufferedamountlow = function () {
self._onChannelBufferedAmountLow()
}
self._channel.onopen = function () {
self._onChannelOpen()
}
self._channel.onclose = function () {
self._onChannelClose()
}
self._channel.onerror = function (err) {
self.destroy(makeError(err, 'ERR_DATA_CHANNEL'))
}
}
Peer.prototype._read = function () {}
Peer.prototype._write = function (chunk, encoding, cb) {
var self = this
if (self.destroyed) return cb(makeError('cannot write after peer is destroyed', 'ERR_DATA_CHANNEL'))
if (self.connected) {
try {
self.send(chunk)
} catch (err) {
return self.destroy(makeError(err, 'ERR_DATA_CHANNEL'))
}
if (self._channel.bufferedAmount > MAX_BUFFERED_AMOUNT) {
self._debug('start backpressure: bufferedAmount %d', self._channel.bufferedAmount)
self._cb = cb
} else {
cb(null)
}
} else {
self._debug('write before connect')
self._chunk = chunk
self._cb = cb
}
}
// When stream finishes writing, close socket. Half open connections are not
// supported.
Peer.prototype._onFinish = function () {
var self = this
if (self.destroyed) return
if (self.connected) {
destroySoon()
} else {
self.once('connect', destroySoon)
}
// Wait a bit before destroying so the socket flushes.
// TODO: is there a more reliable way to accomplish this?
function destroySoon () {
setTimeout(function () {
self.destroy()
}, 1000)
}
}
Peer.prototype._createOffer = function () {
var self = this
if (self.destroyed) return
self._pc.createOffer(self.offerConstraints).then(function (offer) {
if (self.destroyed) return
offer.sdp = self.sdpTransform(offer.sdp)
self._pc.setLocalDescription(offer).then(onSuccess).catch(onError)
function onSuccess () {
self._debug('createOffer success')
if (self.destroyed) return
if (self.trickle || self._iceComplete) sendOffer()
else self.once('_iceComplete', sendOffer) // wait for candidates
}
function onError (err) {
self.destroy(makeError(err, 'ERR_SET_LOCAL_DESCRIPTION'))
}
function sendOffer () {
var signal = self._pc.localDescription || offer
self._debug('signal')
self.emit('signal', {
type: signal.type,
sdp: signal.sdp
})
}
}).catch(function (err) { self.destroy(makeError(err, 'ERR_CREATE_OFFER')) })
}
Peer.prototype._createAnswer = function () {
var self = this
if (self.destroyed) return
self._pc.createAnswer(self.answerConstraints).then(function (answer) {
if (self.destroyed) return
answer.sdp = self.sdpTransform(answer.sdp)
self._pc.setLocalDescription(answer).then(onSuccess).catch(onError)
function onSuccess () {
if (self.destroyed) return
if (self.trickle || self._iceComplete) sendAnswer()
else self.once('_iceComplete', sendAnswer)
}
function onError (err) {
self.destroy(makeError(err, 'ERR_SET_LOCAL_DESCRIPTION'))
}
function sendAnswer () {
var signal = self._pc.localDescription || answer
self._debug('signal')
self.emit('signal', {
type: signal.type,
sdp: signal.sdp
})
}
}).catch(function (err) { self.destroy(makeError(err, 'ERR_CREATE_ANSWER')) })
}
Peer.prototype._onIceStateChange = function () {
var self = this
if (self.destroyed) return
var iceConnectionState = self._pc.iceConnectionState
var iceGatheringState = self._pc.iceGatheringState
self._debug(
'iceStateChange (connection: %s) (gathering: %s)',
iceConnectionState,
iceGatheringState
)
self.emit('iceStateChange', iceConnectionState, iceGatheringState)
if (iceConnectionState === 'connected' || iceConnectionState === 'completed') {
self._pcReady = true
self._maybeReady()
}
if (iceConnectionState === 'failed') {
self.destroy(makeError('Ice connection failed.', 'ERR_ICE_CONNECTION_FAILURE'))
}
if (iceConnectionState === 'closed') {
self.destroy(new Error('Ice connection closed.'))
}
}
Peer.prototype.getStats = function (cb) {
var self = this
// Promise-based getStats() (standard)
if (self._pc.getStats.length === 0) {
self._pc.getStats().then(function (res) {
var reports = []
res.forEach(function (report) {
reports.push(report)
})
cb(null, reports)
}, function (err) { cb(err) })
// Two-parameter callback-based getStats() (deprecated, former standard)
} else if (self._isReactNativeWebrtc) {
self._pc.getStats(null, function (res) {
var reports = []
res.forEach(function (report) {
reports.push(report)
})
cb(null, reports)
}, function (err) { cb(err) })
// Single-parameter callback-based getStats() (non-standard)
} else if (self._pc.getStats.length > 0) {
self._pc.getStats(function (res) {
// If we destroy connection in `connect` callback this code might happen to run when actual connection is already closed
if (self.destroyed) return
var reports = []
res.result().forEach(function (result) {
var report = {}
result.names().forEach(function (name) {
report[name] = result.stat(name)
})
report.id = result.id
report.type = result.type
report.timestamp = result.timestamp
reports.push(report)
})
cb(null, reports)
}, function (err) { cb(err) })
// Unknown browser, skip getStats() since it's anyone's guess which style of
// getStats() they implement.
} else {
cb(null, [])
}
}
Peer.prototype._maybeReady = function () {
var self = this
self._debug('maybeReady pc %s channel %s', self._pcReady, self._channelReady)
if (self.connected || self._connecting || !self._pcReady || !self._channelReady) return
self._connecting = true
// HACK: We can't rely on order here, for details see https://github.com/js-platform/node-webrtc/issues/339
function findCandidatePair () {
if (self.destroyed) return
self.getStats(function (err, items) {
if (self.destroyed) return
// Treat getStats error as non-fatal. It's not essential.
if (err) items = []
var remoteCandidates = {}
var localCandidates = {}
var candidatePairs = {}
var foundSelectedCandidatePair = false
items.forEach(function (item) {
// TODO: Once all browsers support the hyphenated stats report types, remove
// the non-hypenated ones
if (item.type === 'remotecandidate' || item.type === 'remote-candidate') {
remoteCandidates[item.id] = item
}
if (item.type === 'localcandidate' || item.type === 'local-candidate') {
localCandidates[item.id] = item
}
if (item.type === 'candidatepair' || item.type === 'candidate-pair') {
candidatePairs[item.id] = item
}
})
items.forEach(function (item) {
// Spec-compliant
if (item.type === 'transport' && item.selectedCandidatePairId) {
setSelectedCandidatePair(candidatePairs[item.selectedCandidatePairId])
}
// Old implementations
if (
(item.type === 'googCandidatePair' && item.googActiveConnection === 'true') ||
((item.type === 'candidatepair' || item.type === 'candidate-pair') && item.selected)
) {
setSelectedCandidatePair(item)
}
})
function setSelectedCandidatePair (selectedCandidatePair) {
foundSelectedCandidatePair = true
var local = localCandidates[selectedCandidatePair.localCandidateId]
if (local && local.ip) {
// Spec
self.localAddress = local.ip
self.localPort = Number(local.port)
} else if (local && local.ipAddress) {
// Firefox
self.localAddress = local.ipAddress
self.localPort = Number(local.portNumber)
} else if (typeof selectedCandidatePair.googLocalAddress === 'string') {
// TODO: remove this once Chrome 58 is released
local = selectedCandidatePair.googLocalAddress.split(':')
self.localAddress = local[0]
self.localPort = Number(local[1])
}
var remote = remoteCandidates[selectedCandidatePair.remoteCandidateId]
if (remote && remote.ip) {
// Spec
self.remoteAddress = remote.ip
self.remotePort = Number(remote.port)
} else if (remote && remote.ipAddress) {
// Firefox
self.remoteAddress = remote.ipAddress
self.remotePort = Number(remote.portNumber)
} else if (typeof selectedCandidatePair.googRemoteAddress === 'string') {
// TODO: remove this once Chrome 58 is released
remote = selectedCandidatePair.googRemoteAddress.split(':')
self.remoteAddress = remote[0]
self.remotePort = Number(remote[1])
}
self.remoteFamily = 'IPv4'
self._debug(
'connect local: %s:%s remote: %s:%s',
self.localAddress, self.localPort, self.remoteAddress, self.remotePort
)
}
// Ignore candidate pair selection in browsers like Safari 11 that do not have any local or remote candidates
// But wait until at least 1 candidate pair is available
if (!foundSelectedCandidatePair && (!Object.keys(candidatePairs).length || Object.keys(localCandidates).length)) {
setTimeout(findCandidatePair, 100)
return
} else {
self._connecting = false
self.connected = true
}
if (self._chunk) {
try {
self.send(self._chunk)
} catch (err) {
return self.destroy(makeError(err, 'ERR_DATA_CHANNEL'))
}
self._chunk = null
self._debug('sent chunk from "write before connect"')
var cb = self._cb
self._cb = null
cb(null)
}
// If `bufferedAmountLowThreshold` and 'onbufferedamountlow' are unsupported,
// fallback to using setInterval to implement backpressure.
if (typeof self._channel.bufferedAmountLowThreshold !== 'number') {
self._interval = setInterval(function () { self._onInterval() }, 150)
if (self._interval.unref) self._interval.unref()
}
self._debug('connect')
self.emit('connect')
})
}
findCandidatePair()
}
Peer.prototype._onInterval = function () {
var self = this
if (!self._cb || !self._channel || self._channel.bufferedAmount > MAX_BUFFERED_AMOUNT) {
return
}
self._onChannelBufferedAmountLow()
}
Peer.prototype._onSignalingStateChange = function () {
var self = this
if (self.destroyed) return
if (self._pc.signalingState === 'stable') {
self._isNegotiating = false
// HACK: Firefox doesn't yet support removing tracks when signalingState !== 'stable'
self._debug('flushing sender queue', self._sendersAwaitingStable)
self._sendersAwaitingStable.forEach(function (sender) {
self.removeTrack(sender)
self._queuedNegotiation = true
})
self._sendersAwaitingStable = []
if (self._queuedNegotiation) {
self._debug('flushing negotiation queue')
self._queuedNegotiation = false
self._needsNegotiation() // negotiate again
}
self._debug('negotiate')
self.emit('negotiate')
}
self._debug('signalingStateChange %s', self._pc.signalingState)
self.emit('signalingStateChange', self._pc.signalingState)
}
Peer.prototype._onIceCandidate = function (event) {
var self = this
if (self.destroyed) return
if (event.candidate && self.trickle) {
self.emit('signal', {
candidate: {
candidate: event.candidate.candidate,
sdpMLineIndex: event.candidate.sdpMLineIndex,
sdpMid: event.candidate.sdpMid
}
})
} else if (!event.candidate) {
self._iceComplete = true
self.emit('_iceComplete')
}
}
Peer.prototype._onChannelMessage = function (event) {
var self = this
if (self.destroyed) return
var data = event.data
if (data instanceof ArrayBuffer) data = Buffer.from(data)
self.push(data)
}
Peer.prototype._onChannelBufferedAmountLow = function () {
var self = this
if (self.destroyed || !self._cb) return
self._debug('ending backpressure: bufferedAmount %d', self._channel.bufferedAmount)
var cb = self._cb
self._cb = null
cb(null)
}
Peer.prototype._onChannelOpen = function () {
var self = this
if (self.connected || self.destroyed) return
self._debug('on channel open')
self._channelReady = true
self._maybeReady()
}
Peer.prototype._onChannelClose = function () {
var self = this
if (self.destroyed) return
self._debug('on channel close')
self.destroy()
}
Peer.prototype._onTrack = function (event) {
var self = this
if (self.destroyed) return
event.streams.forEach(function (eventStream) {
self._debug('on track')
self.emit('track', event.track, eventStream)
self._remoteTracks.push({
track: event.track,
stream: eventStream
})
if (self._remoteStreams.some(function (remoteStream) {
return remoteStream.id === eventStream.id
})) return // Only fire one 'stream' event, even though there may be multiple tracks per stream
self._remoteStreams.push(eventStream)
setTimeout(function () {
self.emit('stream', eventStream) // ensure all tracks have been added
}, 0)
})
}
Peer.prototype.setConstraints = function (constraints) {
var self = this
if (self.initiator) {
self.offerConstraints = self._transformConstraints(constraints)
} else {
self.answerConstraints = self._transformConstraints(constraints)
}
}
Peer.prototype._debug = function () {
var self = this
var args = [].slice.call(arguments)
args[0] = '[' + self._id + '] ' + args[0]
debug.apply(null, args)
}
// Transform constraints objects into the new format (unless Chromium)
// TODO: This can be removed when Chromium supports the new format
Peer.prototype._transformConstraints = function (constraints) {
var self = this
if (Object.keys(constraints).length === 0) {
return constraints
}
if ((constraints.mandatory || constraints.optional) && !self._isChromium) {
// convert to new format
// Merge mandatory and optional objects, prioritizing mandatory
var newConstraints = Object.assign({}, constraints.optional, constraints.mandatory)
// fix casing
if (newConstraints.OfferToReceiveVideo !== undefined) {
newConstraints.offerToReceiveVideo = newConstraints.OfferToReceiveVideo
delete newConstraints['OfferToReceiveVideo']
}
if (newConstraints.OfferToReceiveAudio !== undefined) {
newConstraints.offerToReceiveAudio = newConstraints.OfferToReceiveAudio
delete newConstraints['OfferToReceiveAudio']
}
return newConstraints
} else if (!constraints.mandatory && !constraints.optional && self._isChromium) {
// convert to old format
// fix casing
if (constraints.offerToReceiveVideo !== undefined) {
constraints.OfferToReceiveVideo = constraints.offerToReceiveVideo
delete constraints['offerToReceiveVideo']
}
if (constraints.offerToReceiveAudio !== undefined) {
constraints.OfferToReceiveAudio = constraints.offerToReceiveAudio
delete constraints['offerToReceiveAudio']
}
return {
mandatory: constraints // NOTE: All constraints are upgraded to mandatory
}
}
return constraints
}
// HACK: Minimal shim to force Chrome and WRTC to use their more reliable callback API
function shimPromiseAPI (RTCPeerConnection, pc) {
pc.createOffer = function (constraints) {
return new Promise((resolve, reject) => {
RTCPeerConnection.prototype.createOffer.call(this, resolve, reject, constraints)
})
}
pc.createAnswer = function (constraints) {
return new Promise((resolve, reject) => {
RTCPeerConnection.prototype.createAnswer.call(this, resolve, reject, constraints)
})
}
pc.setLocalDescription = function (description) {
return new Promise((resolve, reject) => {
RTCPeerConnection.prototype.setLocalDescription.call(this, description, resolve, reject)
})
}
pc.setRemoteDescription = function (description) {
return new Promise((resolve, reject) => {
RTCPeerConnection.prototype.setRemoteDescription.call(this, description, resolve, reject)
})
}
}
function makeError (message, code) {
var err = new Error(message)
err.code = code
return err
}
function noop () {}