forked from feross/simple-peer
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
1041 lines (902 loc) · 32.4 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
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
/*! simple-peer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
const debug = require('debug')('simple-peer')
const getBrowserRTC = require('get-browser-rtc')
const randomstring = require('random-string')
const queueMicrotask = require('queue-microtask')
const { EventEmitter } = require('events')
const errCode = require('err-code')
const MAX_BUFFERED_AMOUNT = 64 * 1024
const ICECOMPLETE_TIMEOUT = 5 * 1000
const CHANNEL_CLOSING_TIMEOUT = 5 * 1000
// HACK: Filter trickle lines when trickle is disabled #354
function filterTrickle (sdp) {
return sdp.replace(/a=ice-options:trickle\s\n/g, '')
}
function warn (message) {
console.warn(message)
}
/**
* WebRTC peer connection. Same API as node core `net.Socket`, plus a few extra methods.
* Duplex stream.
* @param {Object} opts
*/
class Peer extends EventEmitter {
constructor (opts) {
opts = Object.assign({
allowHalfOpen: false
}, opts)
super(opts)
this.id = opts.id || randomstring({ length: 20 })
this._debug('new peer %o', opts)
this.channelName = opts.initiator
? opts.channelName || randomstring({ length: 20 })
: null
this.initiator = opts.initiator || false
this.channelConfig = opts.channelConfig || Peer.channelConfig
this.channelNegotiated = this.channelConfig.negotiated
this.config = Object.assign({}, Peer.config, opts.config)
this.proprietaryConstraints = Object.assign({}, Peer.proprietaryConstraints, opts.proprietaryConstraints)
this.offerOptions = opts.offerOptions || {}
this.answerOptions = opts.answerOptions || {}
this.sdpTransform = opts.sdpTransform || (sdp => sdp)
this.streams = opts.streams || (opts.stream ? [opts.stream] : []) // support old "stream" option
this.trickle = opts.trickle !== undefined ? opts.trickle : true
this.allowHalfTrickle = opts.allowHalfTrickle !== undefined ? opts.allowHalfTrickle : false
this.iceCompleteTimeout = opts.iceCompleteTimeout || ICECOMPLETE_TIMEOUT
this.destroyed = false
this.destroying = false
this._connected = false
this.remoteAddress = undefined
this.remoteFamily = undefined
this.remotePort = undefined
this.localAddress = undefined
this.localFamily = undefined
this.localPort = undefined
this._wrtc = (opts.wrtc && typeof opts.wrtc === 'object')
? opts.wrtc
: getBrowserRTC()
if (!this._wrtc) {
if (typeof window === 'undefined') {
throw errCode(new Error('No WebRTC support: Specify `opts.wrtc` option in this environment'), 'ERR_WEBRTC_SUPPORT')
} else {
throw errCode(new Error('No WebRTC support: Not a supported browser'), 'ERR_WEBRTC_SUPPORT')
}
}
this._pcReady = false
this._channelReady = false
this._iceComplete = false // ice candidate trickle done (got null candidate)
this._iceCompleteTimer = null // send an offer/answer anyway after some timeout
this._channel = null
this._pendingCandidates = []
this._isNegotiating = false // is this peer waiting for negotiation to complete?
this._firstNegotiation = true
this._batchedNegotiation = false // batch synchronous negotiations
this._queuedNegotiation = false // is there a queued negotiation request?
this._sendersAwaitingStable = []
this._senderMap = new Map()
this._closingInterval = null
this._remoteTracks = []
this._remoteStreams = []
this._chunk = null
this._cb = null
this._interval = null
try {
this._pc = new (this._wrtc.RTCPeerConnection)(this.config, this.proprietaryConstraints)
} catch (err) {
this.destroy(errCode(err, 'ERR_PC_CONSTRUCTOR'))
return
}
// We prefer feature detection whenever possible, but sometimes that's not
// possible for certain implementations.
this._isReactNativeWebrtc = typeof this._pc._peerConnectionId === 'number'
this._pc.oniceconnectionstatechange = () => {
this._onIceStateChange()
}
this._pc.onicegatheringstatechange = () => {
this._onIceStateChange()
}
this._pc.onconnectionstatechange = () => {
this._onConnectionStateChange()
}
this._pc.onsignalingstatechange = () => {
this._onSignalingStateChange()
}
this._pc.onicecandidate = event => {
this._onIceCandidate(event)
}
// HACK: Fix for odd Firefox behavior, see: https://github.com/feross/simple-peer/pull/783
if (typeof this._pc.peerIdentity === 'object') {
this._pc.peerIdentity.catch(err => {
this.destroy(errCode(err, 'ERR_PC_PEER_IDENTITY'))
})
}
// Other spec events, unused by this implementation:
// - onconnectionstatechange
// - onicecandidateerror
// - onfingerprintfailure
// - onnegotiationneeded
if (this.initiator || this.channelNegotiated) {
this._setupData({
channel: this._pc.createDataChannel(this.channelName, this.channelConfig)
})
} else {
this._pc.ondatachannel = event => {
this._setupData(event)
}
}
if (this.streams) {
this.streams.forEach(stream => {
this.addStream(stream)
})
}
this._pc.ontrack = event => {
this._onTrack(event)
}
this._debug('initial negotiation')
this._needsNegotiation()
this._onFinishBound = () => {
this._onFinish()
}
this.once('finish', this._onFinishBound)
}
get bufferSize () {
return (this._channel && this._channel.bufferedAmount) || 0
}
// HACK: it's possible channel.readyState is "closing" before peer.destroy() fires
// https://bugs.chromium.org/p/chromium/issues/detail?id=882743
get connected () {
return (this._connected && this._channel.readyState === 'open')
}
address () {
return { port: this.localPort, family: this.localFamily, address: this.localAddress }
}
signal (data) {
if (this.destroying) return
if (this.destroyed) throw errCode(new Error('cannot signal after peer is destroyed'), 'ERR_DESTROYED')
if (typeof data === 'string') {
try {
data = JSON.parse(data)
} catch (err) {
data = {}
}
}
this._debug('signal()')
if (data.renegotiate && this.initiator) {
this._debug('got request to renegotiate')
this._needsNegotiation()
}
if (data.transceiverRequest && this.initiator) {
this._debug('got request for transceiver')
this.addTransceiver(data.transceiverRequest.kind, data.transceiverRequest.init)
}
if (data.candidate) {
if (this._pc.remoteDescription && this._pc.remoteDescription.type) {
this._addIceCandidate(data.candidate)
} else {
this._pendingCandidates.push(data.candidate)
}
}
if (data.sdp) {
this._pc.setRemoteDescription(new (this._wrtc.RTCSessionDescription)(data))
.then(() => {
if (this.destroyed) return
this._pendingCandidates.forEach(candidate => {
this._addIceCandidate(candidate)
})
this._pendingCandidates = []
if (this._pc.remoteDescription.type === 'offer') this._createAnswer()
})
.catch(err => {
this.destroy(errCode(err, 'ERR_SET_REMOTE_DESCRIPTION'))
})
}
if (!data.sdp && !data.candidate && !data.renegotiate && !data.transceiverRequest) {
this.destroy(errCode(new Error('signal() called with invalid signal data'), 'ERR_SIGNALING'))
}
}
_addIceCandidate (candidate) {
const iceCandidateObj = new this._wrtc.RTCIceCandidate(candidate)
this._pc.addIceCandidate(iceCandidateObj)
.catch(err => {
if (!iceCandidateObj.address || iceCandidateObj.address.endsWith('.local')) {
warn('Ignoring unsupported ICE candidate.')
} else {
this.destroy(errCode(err, 'ERR_ADD_ICE_CANDIDATE'))
}
})
}
/**
* Send text/binary data to the remote peer.
* @param {ArrayBufferView|ArrayBuffer|Buffer|string|Blob} chunk
*/
send (chunk) {
if (this.destroying) return
if (this.destroyed) throw errCode(new Error('cannot send after peer is destroyed'), 'ERR_DESTROYED')
this._channel.send(chunk)
}
/**
* Add a Transceiver to the connection.
* @param {String} kind
* @param {Object} init
*/
addTransceiver (kind, init) {
if (this.destroying) return
if (this.destroyed) throw errCode(new Error('cannot addTransceiver after peer is destroyed'), 'ERR_DESTROYED')
this._debug('addTransceiver()')
if (this.initiator) {
try {
this._pc.addTransceiver(kind, init)
this._needsNegotiation()
} catch (err) {
this.destroy(errCode(err, 'ERR_ADD_TRANSCEIVER'))
}
} else {
this.emit('signal', { // request initiator to renegotiate
type: 'transceiverRequest',
transceiverRequest: { kind, init }
})
}
}
/**
* Add a MediaStream to the connection.
* @param {MediaStream} stream
*/
addStream (stream) {
if (this.destroying) return
if (this.destroyed) throw errCode(new Error('cannot addStream after peer is destroyed'), 'ERR_DESTROYED')
this._debug('addStream()')
stream.getTracks().forEach(track => {
this.addTrack(track, stream)
})
}
/**
* Add a MediaStreamTrack to the connection.
* @param {MediaStreamTrack} track
* @param {MediaStream} stream
*/
addTrack (track, stream) {
if (this.destroying) return
if (this.destroyed) throw errCode(new Error('cannot addTrack after peer is destroyed'), 'ERR_DESTROYED')
this._debug('addTrack()')
const submap = this._senderMap.get(track) || new Map() // nested Maps map [track, stream] to sender
let sender = submap.get(stream)
if (!sender) {
sender = this._pc.addTrack(track, stream)
submap.set(stream, sender)
this._senderMap.set(track, submap)
this._needsNegotiation()
} else if (sender.removed) {
throw errCode(new Error('Track has been removed. You should enable/disable tracks that you want to re-add.'), 'ERR_SENDER_REMOVED')
} else {
throw errCode(new Error('Track has already been added to that stream.'), 'ERR_SENDER_ALREADY_ADDED')
}
}
/**
* Replace a MediaStreamTrack by another in the connection.
* @param {MediaStreamTrack} oldTrack
* @param {MediaStreamTrack} newTrack
* @param {MediaStream} stream
*/
replaceTrack (oldTrack, newTrack, stream) {
if (this.destroying) return
if (this.destroyed) throw errCode(new Error('cannot replaceTrack after peer is destroyed'), 'ERR_DESTROYED')
this._debug('replaceTrack()')
const submap = this._senderMap.get(oldTrack)
const sender = submap ? submap.get(stream) : null
if (!sender) {
throw errCode(new Error('Cannot replace track that was never added.'), 'ERR_TRACK_NOT_ADDED')
}
if (newTrack) this._senderMap.set(newTrack, submap)
if (sender.replaceTrack != null) {
sender.replaceTrack(newTrack)
} else {
this.destroy(errCode(new Error('replaceTrack is not supported in this browser'), 'ERR_UNSUPPORTED_REPLACETRACK'))
}
}
/**
* Remove a MediaStreamTrack from the connection.
* @param {MediaStreamTrack} track
* @param {MediaStream} stream
*/
removeTrack (track, stream) {
if (this.destroying) return
if (this.destroyed) throw errCode(new Error('cannot removeTrack after peer is destroyed'), 'ERR_DESTROYED')
this._debug('removeSender()')
const submap = this._senderMap.get(track)
const sender = submap ? submap.get(stream) : null
if (!sender) {
throw errCode(new Error('Cannot remove track that was never added.'), 'ERR_TRACK_NOT_ADDED')
}
try {
sender.removed = true
this._pc.removeTrack(sender)
} catch (err) {
if (err.name === 'NS_ERROR_UNEXPECTED') {
this._sendersAwaitingStable.push(sender) // HACK: Firefox must wait until (signalingState === stable) https://bugzilla.mozilla.org/show_bug.cgi?id=1133874
} else {
this.destroy(errCode(err, 'ERR_REMOVE_TRACK'))
}
}
this._needsNegotiation()
}
/**
* Remove a MediaStream from the connection.
* @param {MediaStream} stream
*/
removeStream (stream) {
if (this.destroying) return
if (this.destroyed) throw errCode(new Error('cannot removeStream after peer is destroyed'), 'ERR_DESTROYED')
this._debug('removeSenders()')
stream.getTracks().forEach(track => {
this.removeTrack(track, stream)
})
}
_needsNegotiation () {
this._debug('_needsNegotiation')
if (this._batchedNegotiation) return // batch synchronous renegotiations
this._batchedNegotiation = true
queueMicrotask(() => {
this._batchedNegotiation = false
if (this.initiator || !this._firstNegotiation) {
this._debug('starting batched negotiation')
this.negotiate()
} else {
this._debug('non-initiator initial negotiation request discarded')
}
this._firstNegotiation = false
})
}
negotiate () {
if (this.destroying) return
if (this.destroyed) throw errCode(new Error('cannot negotiate after peer is destroyed'), 'ERR_DESTROYED')
if (this.initiator) {
if (this._isNegotiating) {
this._queuedNegotiation = true
this._debug('already negotiating, queueing')
} else {
this._debug('start negotiation')
setTimeout(() => { // HACK: Chrome crashes if we immediately call createOffer
this._createOffer()
}, 0)
}
} else {
if (this._isNegotiating) {
this._queuedNegotiation = true
this._debug('already negotiating, queueing')
} else {
this._debug('requesting negotiation from initiator')
this.emit('signal', { // request initiator to renegotiate
type: 'renegotiate',
renegotiate: true
})
}
}
this._isNegotiating = true
}
destroy (err) {
this._destroy(err, () => {})
}
_destroy (err, cb) {
if (this.destroyed || this.destroying) return
this.destroying = true
this._debug('destroying (error: %s)', err && (err.message || err))
queueMicrotask(() => { // allow events concurrent with the call to _destroy() to fire (see #692)
this.destroyed = true
this.destroying = false
this._debug('destroy (error: %s)', err && (err.message || err))
this._connected = false
this._pcReady = false
this._channelReady = false
this._remoteTracks = null
this._remoteStreams = null
this._senderMap = null
clearInterval(this._closingInterval)
this._closingInterval = null
clearInterval(this._interval)
this._interval = null
this._chunk = null
this._cb = null
if (this._onFinishBound) this.removeListener('finish', this._onFinishBound)
this._onFinishBound = null
if (this._channel) {
try {
this._channel.close()
} catch (err) {}
// allow events concurrent with destruction to be handled
this._channel.onmessage = null
this._channel.onopen = null
this._channel.onclose = null
this._channel.onerror = null
}
if (this._pc) {
try {
this._pc.close()
} catch (err) {}
// allow events concurrent with destruction to be handled
this._pc.oniceconnectionstatechange = null
this._pc.onicegatheringstatechange = null
this._pc.onsignalingstatechange = null
this._pc.onicecandidate = null
this._pc.ontrack = null
this._pc.ondatachannel = null
}
this._pc = null
this._channel = null
if (err) this.emit('error', err)
this.emit('close')
cb()
})
}
_setupData (event) {
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 this.destroy(errCode(new Error('Data channel event is missing `channel` property'), 'ERR_DATA_CHANNEL'))
}
this._channel = event.channel
this._channel.binaryType = 'arraybuffer'
if (typeof this._channel.bufferedAmountLowThreshold === 'number') {
this._channel.bufferedAmountLowThreshold = MAX_BUFFERED_AMOUNT
}
this.channelName = this._channel.label
this._channel.onmessage = event => {
this._onChannelMessage(event)
}
this._channel.onbufferedamountlow = () => {
this._onChannelBufferedAmountLow()
}
this._channel.onopen = () => {
this._onChannelOpen()
}
this._channel.onclose = () => {
this._onChannelClose()
}
this._channel.onerror = event => {
const err = event.error instanceof Error
? event.error
: new Error(`Datachannel error: ${event.message} ${event.filename}:${event.lineno}:${event.colno}`)
this.destroy(errCode(err, 'ERR_DATA_CHANNEL'))
}
// HACK: Chrome will sometimes get stuck in readyState "closing", let's check for this condition
// https://bugs.chromium.org/p/chromium/issues/detail?id=882743
let isClosing = false
this._closingInterval = setInterval(() => { // No "onclosing" event
if (this._channel && this._channel.readyState === 'closing') {
if (isClosing) this._onChannelClose() // closing timed out: equivalent to onclose firing
isClosing = true
} else {
isClosing = false
}
}, CHANNEL_CLOSING_TIMEOUT)
}
_read () {}
_write (chunk, encoding, cb) {
if (this.destroyed) return cb(errCode(new Error('cannot write after peer is destroyed'), 'ERR_DATA_CHANNEL'))
if (this._connected) {
try {
this.send(chunk)
} catch (err) {
return this.destroy(errCode(err, 'ERR_DATA_CHANNEL'))
}
if (this._channel.bufferedAmount > MAX_BUFFERED_AMOUNT) {
this._debug('start backpressure: bufferedAmount %d', this._channel.bufferedAmount)
this._cb = cb
} else {
cb(null)
}
} else {
this._debug('write before connect')
this._chunk = chunk
this._cb = cb
}
}
// When stream finishes writing, close socket. Half open connections are not
// supported.
_onFinish () {
if (this.destroyed) return
// Wait a bit before destroying so the socket flushes.
// TODO: is there a more reliable way to accomplish this?
const destroySoon = () => {
setTimeout(() => this.destroy(), 1000)
}
if (this._connected) {
destroySoon()
} else {
this.once('connect', destroySoon)
}
}
_startIceCompleteTimeout () {
if (this.destroyed) return
if (this._iceCompleteTimer) return
this._debug('started iceComplete timeout')
this._iceCompleteTimer = setTimeout(() => {
if (!this._iceComplete) {
this._iceComplete = true
this._debug('iceComplete timeout completed')
this.emit('iceTimeout')
this.emit('_iceComplete')
}
}, this.iceCompleteTimeout)
}
_createOffer () {
if (this.destroyed) return
this._pc.createOffer(this.offerOptions)
.then(offer => {
if (this.destroyed) return
if (!this.trickle && !this.allowHalfTrickle) offer.sdp = filterTrickle(offer.sdp)
offer.sdp = this.sdpTransform(offer.sdp)
const sendOffer = () => {
if (this.destroyed) return
const signal = this._pc.localDescription || offer
this._debug('signal')
this.emit('signal', {
type: signal.type,
sdp: signal.sdp
})
}
const onSuccess = () => {
this._debug('createOffer success')
if (this.destroyed) return
if (this.trickle || this._iceComplete) sendOffer()
else this.once('_iceComplete', sendOffer) // wait for candidates
}
const onError = err => {
this.destroy(errCode(err, 'ERR_SET_LOCAL_DESCRIPTION'))
}
this._pc.setLocalDescription(offer)
.then(onSuccess)
.catch(onError)
})
.catch(err => {
this.destroy(errCode(err, 'ERR_CREATE_OFFER'))
})
}
_requestMissingTransceivers () {
if (this._pc.getTransceivers) {
this._pc.getTransceivers().forEach(transceiver => {
if (!transceiver.mid && transceiver.sender.track && !transceiver.requested) {
transceiver.requested = true // HACK: Safari returns negotiated transceivers with a null mid
this.addTransceiver(transceiver.sender.track.kind)
}
})
}
}
_createAnswer () {
if (this.destroyed) return
this._pc.createAnswer(this.answerOptions)
.then(answer => {
if (this.destroyed) return
if (!this.trickle && !this.allowHalfTrickle) answer.sdp = filterTrickle(answer.sdp)
answer.sdp = this.sdpTransform(answer.sdp)
const sendAnswer = () => {
if (this.destroyed) return
const signal = this._pc.localDescription || answer
this._debug('signal')
this.emit('signal', {
type: signal.type,
sdp: signal.sdp
})
if (!this.initiator) this._requestMissingTransceivers()
}
const onSuccess = () => {
if (this.destroyed) return
if (this.trickle || this._iceComplete) sendAnswer()
else this.once('_iceComplete', sendAnswer)
}
const onError = err => {
this.destroy(errCode(err, 'ERR_SET_LOCAL_DESCRIPTION'))
}
this._pc.setLocalDescription(answer)
.then(onSuccess)
.catch(onError)
})
.catch(err => {
this.destroy(errCode(err, 'ERR_CREATE_ANSWER'))
})
}
_onConnectionStateChange () {
if (this.destroyed) return
if (this._pc.connectionState === 'failed') {
this.destroy(errCode(new Error('Connection failed.'), 'ERR_CONNECTION_FAILURE'))
}
}
_onIceStateChange () {
if (this.destroyed) return
const iceConnectionState = this._pc.iceConnectionState
const iceGatheringState = this._pc.iceGatheringState
this._debug(
'iceStateChange (connection: %s) (gathering: %s)',
iceConnectionState,
iceGatheringState
)
this.emit('iceStateChange', iceConnectionState, iceGatheringState)
if (iceConnectionState === 'connected' || iceConnectionState === 'completed') {
this._pcReady = true
this._maybeReady()
}
if (iceConnectionState === 'failed') {
this.destroy(errCode(new Error('Ice connection failed.'), 'ERR_ICE_CONNECTION_FAILURE'))
}
if (iceConnectionState === 'closed') {
this.destroy(errCode(new Error('Ice connection closed.'), 'ERR_ICE_CONNECTION_CLOSED'))
}
}
getStats (cb) {
// statreports can come with a value array instead of properties
const flattenValues = report => {
if (Object.prototype.toString.call(report.values) === '[object Array]') {
report.values.forEach(value => {
Object.assign(report, value)
})
}
return report
}
// Promise-based getStats() (standard)
if (this._pc.getStats.length === 0 || this._isReactNativeWebrtc) {
this._pc.getStats()
.then(res => {
const reports = []
res.forEach(report => {
reports.push(flattenValues(report))
})
cb(null, reports)
}, err => cb(err))
// Single-parameter callback-based getStats() (non-standard)
} else if (this._pc.getStats.length > 0) {
this._pc.getStats(res => {
// If we destroy connection in `connect` callback this code might happen to run when actual connection is already closed
if (this.destroyed) return
const reports = []
res.result().forEach(result => {
const report = {}
result.names().forEach(name => {
report[name] = result.stat(name)
})
report.id = result.id
report.type = result.type
report.timestamp = result.timestamp
reports.push(flattenValues(report))
})
cb(null, reports)
}, err => cb(err))
// Unknown browser, skip getStats() since it's anyone's guess which style of
// getStats() they implement.
} else {
cb(null, [])
}
}
_maybeReady () {
this._debug('maybeReady pc %s channel %s', this._pcReady, this._channelReady)
if (this._connected || this._connecting || !this._pcReady || !this._channelReady) return
this._connecting = true
// HACK: We can't rely on order here, for details see https://github.com/js-platform/node-webrtc/issues/339
const findCandidatePair = () => {
if (this.destroyed) return
this.getStats((err, items) => {
if (this.destroyed) return
// Treat getStats error as non-fatal. It's not essential.
if (err) items = []
const remoteCandidates = {}
const localCandidates = {}
const candidatePairs = {}
let foundSelectedCandidatePair = false
items.forEach(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
}
})
const setSelectedCandidatePair = selectedCandidatePair => {
foundSelectedCandidatePair = true
let local = localCandidates[selectedCandidatePair.localCandidateId]
if (local && (local.ip || local.address)) {
// Spec
this.localAddress = local.ip || local.address
this.localPort = Number(local.port)
} else if (local && local.ipAddress) {
// Firefox
this.localAddress = local.ipAddress
this.localPort = Number(local.portNumber)
} else if (typeof selectedCandidatePair.googLocalAddress === 'string') {
// TODO: remove this once Chrome 58 is released
local = selectedCandidatePair.googLocalAddress.split(':')
this.localAddress = local[0]
this.localPort = Number(local[1])
}
if (this.localAddress) {
this.localFamily = this.localAddress.includes(':') ? 'IPv6' : 'IPv4'
}
let remote = remoteCandidates[selectedCandidatePair.remoteCandidateId]
if (remote && (remote.ip || remote.address)) {
// Spec
this.remoteAddress = remote.ip || remote.address
this.remotePort = Number(remote.port)
} else if (remote && remote.ipAddress) {
// Firefox
this.remoteAddress = remote.ipAddress
this.remotePort = Number(remote.portNumber)
} else if (typeof selectedCandidatePair.googRemoteAddress === 'string') {
// TODO: remove this once Chrome 58 is released
remote = selectedCandidatePair.googRemoteAddress.split(':')
this.remoteAddress = remote[0]
this.remotePort = Number(remote[1])
}
if (this.remoteAddress) {
this.remoteFamily = this.remoteAddress.includes(':') ? 'IPv6' : 'IPv4'
}
this._debug(
'connect local: %s:%s remote: %s:%s',
this.localAddress,
this.localPort,
this.remoteAddress,
this.remotePort
)
}
items.forEach(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)
}
})
// 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 {
this._connecting = false
this._connected = true
}
if (this._chunk) {
try {
this.send(this._chunk)
} catch (err) {
return this.destroy(errCode(err, 'ERR_DATA_CHANNEL'))
}
this._chunk = null
this._debug('sent chunk from "write before connect"')
const cb = this._cb
this._cb = null
cb(null)
}
// If `bufferedAmountLowThreshold` and 'onbufferedamountlow' are unsupported,
// fallback to using setInterval to implement backpressure.
if (typeof this._channel.bufferedAmountLowThreshold !== 'number') {
this._interval = setInterval(() => this._onInterval(), 150)
if (this._interval.unref) this._interval.unref()
}
this._debug('connect')
this.emit('connect')
})
}
findCandidatePair()
}
_onInterval () {
if (!this._cb || !this._channel || this._channel.bufferedAmount > MAX_BUFFERED_AMOUNT) {
return
}
this._onChannelBufferedAmountLow()
}
_onSignalingStateChange () {
if (this.destroyed) return
if (this._pc.signalingState === 'stable') {
this._isNegotiating = false
// HACK: Firefox doesn't yet support removing tracks when signalingState !== 'stable'
this._debug('flushing sender queue', this._sendersAwaitingStable)
this._sendersAwaitingStable.forEach(sender => {
this._pc.removeTrack(sender)
this._queuedNegotiation = true
})
this._sendersAwaitingStable = []
if (this._queuedNegotiation) {
this._debug('flushing negotiation queue')
this._queuedNegotiation = false
this._needsNegotiation() // negotiate again
} else {
this._debug('negotiated')
this.emit('negotiated')
}
}
this._debug('signalingStateChange %s', this._pc.signalingState)
this.emit('signalingStateChange', this._pc.signalingState)
}
_onIceCandidate (event) {
if (this.destroyed) return
if (event.candidate && this.trickle) {
this.emit('signal', {
type: 'candidate',
candidate: {
candidate: event.candidate.candidate,
sdpMLineIndex: event.candidate.sdpMLineIndex,
sdpMid: event.candidate.sdpMid
}
})
} else if (!event.candidate && !this._iceComplete) {
this._iceComplete = true
this.emit('_iceComplete')
}
// as soon as we've received one valid candidate start timeout
if (event.candidate) {
this._startIceCompleteTimeout()
}
}
_onChannelMessage (event) {
if (this.destroyed) return
this.emit('data', event.data)
}
_onChannelBufferedAmountLow () {
if (this.destroyed || !this._cb) return
this._debug('ending backpressure: bufferedAmount %d', this._channel.bufferedAmount)
const cb = this._cb
this._cb = null
cb(null)
}
_onChannelOpen () {
if (this._connected || this.destroyed) return
this._debug('on channel open')
this._channelReady = true
this._maybeReady()
}
_onChannelClose () {
if (this.destroyed) return
this._debug('on channel close')
this.destroy()
}
_onTrack (event) {
if (this.destroyed) return
const { track, receiver, streams } = event
streams.forEach(eventStream => {
this._debug('on track')
this.emit('track', track, eventStream, receiver)
this._remoteTracks.push({ track, stream: eventStream })
if (this._remoteStreams.some(remoteStream => {