forked from feross/simple-peer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
750 lines (642 loc) · 21.2 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
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.reconnectTimer = opts.reconnectTimer || false
self.sdpTransform = opts.sdpTransform || function (sdp) { return sdp }
self.stream = opts.stream || false
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 new Error('No WebRTC support: Specify `opts.wrtc` option in this environment')
} else {
throw new Error('No WebRTC support: Not a supported browser')
}
}
self._pcReady = false
self._channelReady = false
self._iceComplete = false // ice candidate trickle done (got null candidate)
self._channel = null
self._pendingCandidates = []
self._previousStreams = []
self._chunk = null
self._cb = null
self._interval = null
self._reconnectTimeout = null
self._pc = new (self._wrtc.RTCPeerConnection)(self.config, self.constraints)
// We prefer feature detection whenever possible, but sometimes that's not
// possible for certain implementations.
self._isWrtc = Array.isArray(self._pc.RTCIceConnectionStates)
self._isReactNativeWebrtc = typeof self._pc._peerConnectionId === 'number'
self._pc.oniceconnectionstatechange = function () {
self._onIceConnectionStateChange()
}
self._pc.onsignalingstatechange = function () {
self._onSignalingStateChange()
}
self._pc.onicecandidate = function (event) {
self._onIceCandidate(event)
}
if (self.initiator) {
var createdOffer = false
self._pc.onnegotiationneeded = function () {
if (!createdOffer) self._createOffer()
createdOffer = true
}
self._setupData({
channel: self._pc.createDataChannel(self.channelName, self.channelConfig)
})
} else {
self._pc.ondatachannel = function (event) {
self._setupData(event)
}
}
if ('addTrack' in self._pc) {
// WebRTC Spec, Firefox
if (self.stream) {
self.stream.getTracks().forEach(function (track) {
self._pc.addTrack(track, self.stream)
})
}
self._pc.ontrack = function (event) {
self._onTrack(event)
}
} else {
// Chrome, etc. This can be removed once all browsers support `ontrack`
if (self.stream) self._pc.addStream(self.stream)
self._pc.onaddstream = function (event) {
self._onAddStream(event)
}
}
// HACK: wrtc doesn't fire the 'negotionneeded' event
if (self.initiator && self._isWrtc) {
self._pc.onnegotiationneeded()
}
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 new Error('cannot signal after peer is destroyed')
if (typeof data === 'string') {
try {
data = JSON.parse(data)
} catch (err) {
data = {}
}
}
self._debug('signal()')
if (data.candidate) {
if (self._pc.remoteDescription) self._addIceCandidate(data.candidate)
else self._pendingCandidates.push(data.candidate)
}
if (data.sdp) {
self._pc.setRemoteDescription(new (self._wrtc.RTCSessionDescription)(data), function () {
if (self.destroyed) return
self._pendingCandidates.forEach(function (candidate) {
self._addIceCandidate(candidate)
})
self._pendingCandidates = []
if (self._pc.remoteDescription.type === 'offer') self._createAnswer()
}, function (err) { self._onError(err) })
}
if (!data.sdp && !data.candidate) {
self._destroy(new Error('signal() called with invalid signal data'))
}
}
Peer.prototype._addIceCandidate = function (candidate) {
var self = this
try {
self._pc.addIceCandidate(
new self._wrtc.RTCIceCandidate(candidate),
noop,
function (err) { self._onError(err) }
)
} catch (err) {
self._destroy(new Error('error adding candidate: ' + err.message))
}
}
/**
* Send text/binary data to the remote peer.
* @param {TypedArrayView|ArrayBuffer|Buffer|string|Blob|Object} chunk
*/
Peer.prototype.send = function (chunk) {
var self = this
// HACK: `wrtc` module crashes on Node.js Buffer, so convert to Uint8Array
// See: https://github.com/feross/simple-peer/issues/60
if (self._isWrtc && Buffer.isBuffer(chunk)) {
chunk = new Uint8Array(chunk)
}
self._channel.send(chunk)
}
Peer.prototype.destroy = function (onclose) {
var self = this
self._destroy(null, onclose)
}
Peer.prototype._destroy = function (err, onclose) {
var self = this
if (self.destroyed) return
if (onclose) self.once('close', onclose)
self._debug('destroy (error: %s)', err && err.message)
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._previousStreams = null
clearInterval(self._interval)
clearTimeout(self._reconnectTimeout)
self._interval = null
self._reconnectTimeout = null
self._chunk = null
self._cb = null
if (self._onFinishBound) self.removeListener('finish', self._onFinishBound)
self._onFinishBound = null
if (self._pc) {
try {
self._pc.close()
} catch (err) {}
self._pc.oniceconnectionstatechange = null
self._pc.onsignalingstatechange = null
self._pc.onicecandidate = null
if ('addTrack' in self._pc) {
self._pc.ontrack = null
} else {
self._pc.onaddstream = null
}
self._pc.onnegotiationneeded = null
self._pc.ondatachannel = null
}
if (self._channel) {
try {
self._channel.close()
} catch (err) {}
self._channel.onmessage = null
self._channel.onopen = null
self._channel.onclose = null
}
self._pc = null
self._channel = null
if (err) self.emit('error', err)
self.emit('close')
}
Peer.prototype._setupData = function (event) {
var self = this
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()
}
}
Peer.prototype._read = function () {}
Peer.prototype._write = function (chunk, encoding, cb) {
var self = this
if (self.destroyed) return cb(new Error('cannot write after peer is destroyed'))
if (self.connected) {
try {
self.send(chunk)
} catch (err) {
return self._onError(err)
}
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()
}, 100)
}
}
Peer.prototype._createOffer = function () {
var self = this
if (self.destroyed) return
self._pc.createOffer(function (offer) {
if (self.destroyed) return
offer.sdp = self.sdpTransform(offer.sdp)
self._pc.setLocalDescription(offer, noop, function (err) { self._onError(err) })
var sendOffer = function () {
var signal = self._pc.localDescription || offer
self._debug('signal')
self.emit('signal', {
type: signal.type,
sdp: signal.sdp
})
}
if (self.trickle || self._iceComplete) sendOffer()
else self.once('_iceComplete', sendOffer) // wait for candidates
}, function (err) { self._onError(err) }, self.offerConstraints)
}
Peer.prototype._createAnswer = function () {
var self = this
if (self.destroyed) return
self._pc.createAnswer(function (answer) {
if (self.destroyed) return
answer.sdp = self.sdpTransform(answer.sdp)
self._pc.setLocalDescription(answer, noop, function (err) { self._onError(err) })
if (self.trickle || self._iceComplete) sendAnswer()
else self.once('_iceComplete', sendAnswer)
function sendAnswer () {
var signal = self._pc.localDescription || answer
self._debug('signal')
self.emit('signal', {
type: signal.type,
sdp: signal.sdp
})
}
}, function (err) { self._onError(err) }, self.answerConstraints)
}
Peer.prototype._onIceConnectionStateChange = function () {
var self = this
if (self.destroyed) return
var iceGatheringState = self._pc.iceGatheringState
var iceConnectionState = self._pc.iceConnectionState
self._debug('iceConnectionStateChange %s %s', iceGatheringState, iceConnectionState)
self.emit('iceConnectionStateChange', iceGatheringState, iceConnectionState)
if (iceConnectionState === 'connected' || iceConnectionState === 'completed') {
clearTimeout(self._reconnectTimeout)
self._pcReady = true
self._maybeReady()
}
if (iceConnectionState === 'disconnected') {
if (self.reconnectTimer) {
// If user has set `opt.reconnectTimer`, allow time for ICE to attempt a reconnect
clearTimeout(self._reconnectTimeout)
self._reconnectTimeout = setTimeout(function () {
self._destroy()
}, self.reconnectTimer)
} else {
self._destroy()
}
}
if (iceConnectionState === 'failed') {
self._destroy(new Error('Ice connection failed.'))
}
if (iceConnectionState === 'closed') {
self._destroy()
}
}
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(reports)
}, function (err) { self._onError(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(reports)
}, function (err) { self._onError(err) })
// Single-parameter callback-based getStats() (non-standard)
} else if (self._pc.getStats.length > 0) {
self._pc.getStats(function (res) {
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(reports)
}, function (err) { self._onError(err) })
// Unknown browser, skip getStats() since it's anyone's guess which style of
// getStats() they implement.
} else {
cb([])
}
}
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
self.getStats(function (items) {
self._connecting = false
self.connected = true
var remoteCandidates = {}
var localCandidates = {}
var candidatePairs = {}
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') {
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) {
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
)
}
if (self._chunk) {
try {
self.send(self._chunk)
} catch (err) {
return self._onError(err)
}
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')
})
}
Peer.prototype._onInterval = function () {
if (!this._cb || !this._channel || this._channel.bufferedAmount > MAX_BUFFERED_AMOUNT) {
return
}
this._onChannelBufferedAmountLow()
}
Peer.prototype._onSignalingStateChange = function () {
var self = this
if (self.destroyed) return
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 = new Buffer(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._onAddStream = function (event) {
var self = this
if (self.destroyed) return
self._debug('on add stream')
self.emit('stream', event.stream)
}
Peer.prototype._onTrack = function (event) {
var self = this
if (self.destroyed) return
self._debug('on track')
var id = event.streams[0].id
if (self._previousStreams.indexOf(id) !== -1) return // Only fire one 'stream' event, even though there may be multiple tracks per stream
self._previousStreams.push(id)
self.emit('stream', event.streams[0])
}
Peer.prototype._onError = function (err) {
var self = this
if (self.destroyed) return
self._debug('error %s', err.message || err)
self._destroy(err)
}
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
}
function noop () {}