Welcome to mirror list, hosted at ThFree Co, Russian Federation.

peer.js « simplewebrtc « webrtc « utils « src - github.com/nextcloud/spreed.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 0d1e3222a1901627cda282be89c71368ae3626cb (plain)
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
/* global module */
const initialState = require('@nextcloud/initial-state')
const sdpTransform = require('sdp-transform')

const adapter = require('webrtc-adapter')
const util = require('util')
const webrtcSupport = require('webrtcsupport')
const WildEmitter = require('wildemitter')

function isAllTracksEnded(stream) {
	let isAllTracksEnded = true
	stream.getTracks().forEach(function(t) {
		isAllTracksEnded = t.readyState === 'ended' && isAllTracksEnded
	})
	return isAllTracksEnded
}

function Peer(options) {
	const self = this

	// call emitter constructor
	WildEmitter.call(this)

	this.id = options.id
	this.parent = options.parent
	this.type = options.type || 'video'
	this.oneway = options.oneway || false
	this.sharemyscreen = options.sharemyscreen || false
	this.stream = options.stream
	this.sendVideoIfAvailable = options.sendVideoIfAvailable === undefined ? true : options.sendVideoIfAvailable
	this.enableDataChannels = options.enableDataChannels === undefined ? this.parent.config.enableDataChannels : options.enableDataChannels
	this.enableSimulcast = options.enableSimulcast === undefined ? this.parent.config.enableSimulcast : options.enableSimulcast
	this.maxBitrates = options.maxBitrates === undefined ? this.parent.config.maxBitrates : options.maxBitrates
	this.receiveMedia = options.receiveMedia || this.parent.config.receiveMedia
	this.channels = {}
	this.pendingDCMessages = [] // key (datachannel label) -> value (array[pending messages])
	this._pendingReplaceTracksQueue = []
	this._processPendingReplaceTracksPromise = null
	this._initialStreamSetup = false
	this.sid = options.sid || Date.now().toString()
	this.pc = new RTCPeerConnection(this.parent.config.peerConnectionConfig)
	this.pc.addEventListener('icecandidate', this.onIceCandidate.bind(this))
	this.pc.addEventListener('endofcandidates', function(event) {
		self.send('endOfCandidates', event)
	})
	this.pc.addEventListener('addstream', this.handleRemoteStreamAdded.bind(this))
	this.pc.addEventListener('datachannel', this.handleDataChannelAdded.bind(this))
	this.pc.addEventListener('removestream', this.handleStreamRemoved.bind(this))
	// Just fire negotiation needed events for now
	// When browser re-negotiation handling seems to work
	// we can use this as the trigger for starting the offer/answer process
	// automatically. We'll just leave it be for now while this stabalizes.
	this.pc.addEventListener('negotiationneeded', this.emit.bind(this, 'negotiationNeeded'))
	this.pc.addEventListener('iceconnectionstatechange', this.emit.bind(this, 'iceConnectionStateChange'))
	this.pc.addEventListener('iceconnectionstatechange', function() {
		if (!options.receiverOnly && self.pc.iceConnectionState !== 'new') {
			self._processPendingReplaceTracks().then(finished => {
				if (finished === false || self._initialStreamSetup) {
					return
				}

				// Ensure that initially disabled tracks are stopped after
				// establishing a connection.
				self.pc.getSenders().forEach(sender => {
					if (sender.track) {
						// The stream is not known, but it is only used when the
						// track is added, so it can be ignored here.
						self.handleLocalTrackEnabledChanged(sender.track, null)
					}
				})

				self._initialStreamSetup = true
			})
		} else {
			self._initialStreamSetup = false
		}

		switch (self.pc.iceConnectionState) {
		case 'failed':
			// currently, in chrome only the initiator goes to failed
			// so we need to signal this to the peer
			if (self.pc.localDescription.type === 'offer') {
				self.parent.emit('iceFailed', self)
				self.send('connectivityError')
			}
			break
		}
	})
	this.pc.addEventListener('signalingstatechange', this.emit.bind(this, 'signalingStateChange'))
	this.logger = this.parent.logger

	if (!options.receiverOnly) {
		// handle screensharing/broadcast mode
		if (options.type === 'screen') {
			if (this.parent.localScreen && this.sharemyscreen) {
				this.logger.log('adding local screen stream to peer connection')
				this.pc.addStream(this.parent.localScreen)
				this.broadcaster = options.broadcaster
			}
		} else {
			this.parent.localStreams.forEach(function(stream) {
				stream.getTracks().forEach(function(track) {
					if (track.kind !== 'video' || self.sendVideoIfAvailable) {
						self.pc.addTrack(track, stream)
					}
				})
			})

			this.handleLocalTrackReplacedBound = this.handleLocalTrackReplaced.bind(this)
			// TODO What would happen if the track is replaced while the peer is
			// still negotiating the offer and answer?
			this.parent.on('localTrackReplaced', this.handleLocalTrackReplacedBound)

			this.handleLocalTrackEnabledChangedBound = this.handleLocalTrackEnabledChanged.bind(this)
			this.parent.on('localTrackEnabledChanged', this.handleLocalTrackEnabledChangedBound)
		}
	}

	// proxy events to parent
	this.on('*', function() {
		self.parent.emit.apply(self.parent, arguments)
	})
}

util.inherits(Peer, WildEmitter)

function shouldPreferH264() {
	try {
		return initialState.loadState('spreed', 'prefer_h264')
	} catch (exception) {
		// If the state can not be loaded an exception is thrown
		console.warn('Could not find initial state for H.264 preference')
		return false
	}
}

function preferH264VideoCodecIfAvailable(sessionDescription) {
	const sdpInfo = sdpTransform.parse(sessionDescription.sdp)

	if (!sdpInfo || !sdpInfo.media) {
		return sessionDescription
	}

	// Find video media
	let videoIndex = -1
	sdpInfo.media.forEach((media, mediaIndex) => {
		if (media.type === 'video') {
			videoIndex = mediaIndex
		}
	})

	if (videoIndex === -1 || !sdpInfo.media[videoIndex].rtp) {
		return sessionDescription
	}

	// Find all H264 codec videos
	const h264Rtps = []
	sdpInfo.media[videoIndex].rtp.forEach((rtp, rtpIndex) => {
		if (rtp.codec.toLowerCase() === 'h264') {
			h264Rtps.push(rtp.payload)
		}
	})

	if (!h264Rtps.length) {
		// No H264 codecs found
		return sessionDescription
	}

	// Sort the H264 codecs to the front in the payload (which defines the preferred order)
	const payloads = sdpInfo.media[videoIndex].payloads.split(' ')
	payloads.sort((a, b) => {
		if (h264Rtps.indexOf(parseInt(a, 10)) !== -1) {
			return -1
		}
		if (h264Rtps.indexOf(parseInt(b, 10)) !== -1) {
			return 1
		}
		return 0
	})

	// Write new payload order into video media payload
	sdpInfo.media[videoIndex].payloads = payloads.join(' ')

	// Write back the sdpInfo into the session description
	sessionDescription.sdp = sdpTransform.write(sdpInfo)

	return sessionDescription
}

// Helper method to munge an SDP to enable simulcasting (Chrome only)
// Taken from janus.js (MIT license).
/* eslint-disable */
function mungeSdpForSimulcasting(sdp) {
	// Let's munge the SDP to add the attributes for enabling simulcasting
	// (based on https://gist.github.com/ggarber/a19b4c33510028b9c657)
	var lines = sdp.split("\r\n");
	var video = false;
	var ssrc = [ -1 ], ssrc_fid = [ -1 ];
	var cname = null, msid = null, mslabel = null, label = null;
	var insertAt = -1;
	for(var i=0; i<lines.length; i++) {
		var mline = lines[i].match(/m=(\w+) */);
		if(mline) {
			var medium = mline[1];
			if(medium === "video") {
				// New video m-line: make sure it's the first one
				if(ssrc[0] < 0) {
					video = true;
				} else {
					// We're done, let's add the new attributes here
					insertAt = i;
					break;
				}
			} else {
				// New non-video m-line: do we have what we were looking for?
				if(ssrc[0] > -1) {
					// We're done, let's add the new attributes here
					insertAt = i;
					break;
				}
			}
			continue;
		}
		if(!video)
			continue;
		var fid = lines[i].match(/a=ssrc-group:FID (\d+) (\d+)/);
		if(fid) {
			ssrc[0] = fid[1];
			ssrc_fid[0] = fid[2];
			lines.splice(i, 1); i--;
			continue;
		}
		if(ssrc[0]) {
			var match = lines[i].match('a=ssrc:' + ssrc[0] + ' cname:(.+)')
			if(match) {
				cname = match[1];
			}
			match = lines[i].match('a=ssrc:' + ssrc[0] + ' msid:(.+)')
			if(match) {
				msid = match[1];
			}
			match = lines[i].match('a=ssrc:' + ssrc[0] + ' mslabel:(.+)')
			if(match) {
				mslabel = match[1];
			}
			match = lines[i].match('a=ssrc:' + ssrc[0] + ' label:(.+)')
			if(match) {
				label = match[1];
			}
			if(lines[i].indexOf('a=ssrc:' + ssrc_fid[0]) === 0) {
				lines.splice(i, 1); i--;
				continue;
			}
			if(lines[i].indexOf('a=ssrc:' + ssrc[0]) === 0) {
				lines.splice(i, 1); i--;
				continue;
			}
		}
		if(lines[i].length == 0) {
			lines.splice(i, 1); i--;
			continue;
		}
	}
	if(ssrc[0] < 0) {
		// Couldn't find a FID attribute, let's just take the first video SSRC we find
		insertAt = -1;
		video = false;
		for(var i=0; i<lines.length; i++) {
			var mline = lines[i].match(/m=(\w+) */);
			if(mline) {
				var medium = mline[1];
				if(medium === "video") {
					// New video m-line: make sure it's the first one
					if(ssrc[0] < 0) {
						video = true;
					} else {
						// We're done, let's add the new attributes here
						insertAt = i;
						break;
					}
				} else {
					// New non-video m-line: do we have what we were looking for?
					if(ssrc[0] > -1) {
						// We're done, let's add the new attributes here
						insertAt = i;
						break;
					}
				}
				continue;
			}
			if(!video)
				continue;
			if(ssrc[0] < 0) {
				var value = lines[i].match(/a=ssrc:(\d+)/);
				if(value) {
					ssrc[0] = value[1];
					lines.splice(i, 1); i--;
					continue;
				}
			} else {
				var match = lines[i].match('a=ssrc:' + ssrc[0] + ' cname:(.+)')
				if(match) {
					cname = match[1];
				}
				match = lines[i].match('a=ssrc:' + ssrc[0] + ' msid:(.+)')
				if(match) {
					msid = match[1];
				}
				match = lines[i].match('a=ssrc:' + ssrc[0] + ' mslabel:(.+)')
				if(match) {
					mslabel = match[1];
				}
				match = lines[i].match('a=ssrc:' + ssrc[0] + ' label:(.+)')
				if(match) {
					label = match[1];
				}
				if(lines[i].indexOf('a=ssrc:' + ssrc_fid[0]) === 0) {
					lines.splice(i, 1); i--;
					continue;
				}
				if(lines[i].indexOf('a=ssrc:' + ssrc[0]) === 0) {
					lines.splice(i, 1); i--;
					continue;
				}
			}
			if(lines[i].length === 0) {
				lines.splice(i, 1); i--;
				continue;
			}
		}
	}
	if(ssrc[0] < 0) {
		// Still nothing, let's just return the SDP we were asked to munge
		console.warn("Couldn't find the video SSRC, simulcasting NOT enabled");
		return sdp;
	}
	if(insertAt < 0) {
		// Append at the end
		insertAt = lines.length;
	}
	// Generate a couple of SSRCs (for retransmissions too)
	// Note: should we check if there are conflicts, here?
	ssrc[1] = Math.floor(Math.random()*0xFFFFFFFF);
	ssrc[2] = Math.floor(Math.random()*0xFFFFFFFF);
	ssrc_fid[1] = Math.floor(Math.random()*0xFFFFFFFF);
	ssrc_fid[2] = Math.floor(Math.random()*0xFFFFFFFF);
	// Add attributes to the SDP
	for(var i=0; i<ssrc.length; i++) {
		if(cname) {
			lines.splice(insertAt, 0, 'a=ssrc:' + ssrc[i] + ' cname:' + cname);
			insertAt++;
		}
		if(msid) {
			lines.splice(insertAt, 0, 'a=ssrc:' + ssrc[i] + ' msid:' + msid);
			insertAt++;
		}
		if(mslabel) {
			lines.splice(insertAt, 0, 'a=ssrc:' + ssrc[i] + ' mslabel:' + mslabel);
			insertAt++;
		}
		if(label) {
			lines.splice(insertAt, 0, 'a=ssrc:' + ssrc[i] + ' label:' + label);
			insertAt++;
		}
		// Add the same info for the retransmission SSRC
		if(cname) {
			lines.splice(insertAt, 0, 'a=ssrc:' + ssrc_fid[i] + ' cname:' + cname);
			insertAt++;
		}
		if(msid) {
			lines.splice(insertAt, 0, 'a=ssrc:' + ssrc_fid[i] + ' msid:' + msid);
			insertAt++;
		}
		if(mslabel) {
			lines.splice(insertAt, 0, 'a=ssrc:' + ssrc_fid[i] + ' mslabel:' + mslabel);
			insertAt++;
		}
		if(label) {
			lines.splice(insertAt, 0, 'a=ssrc:' + ssrc_fid[i] + ' label:' + label);
			insertAt++;
		}
	}
	lines.splice(insertAt, 0, 'a=ssrc-group:FID ' + ssrc[2] + ' ' + ssrc_fid[2]);
	lines.splice(insertAt, 0, 'a=ssrc-group:FID ' + ssrc[1] + ' ' + ssrc_fid[1]);
	lines.splice(insertAt, 0, 'a=ssrc-group:FID ' + ssrc[0] + ' ' + ssrc_fid[0]);
	lines.splice(insertAt, 0, 'a=ssrc-group:SIM ' + ssrc[0] + ' ' + ssrc[1] + ' ' + ssrc[2]);
	sdp = lines.join("\r\n");
	if(!sdp.endsWith("\r\n"))
		sdp += "\r\n";
	return sdp;
}
/* eslint-enable */

Peer.prototype.offer = function(options) {
	const sendVideo = this.sendVideoIfAvailable && this.type !== 'screen'
	if (sendVideo && this.enableSimulcast && adapter.browserDetails.browser === 'firefox') {
		console.debug('Enabling Simulcasting for Firefox (RID)')
		const sender = this.pc.getSenders().find(function(s) {
			return s.track.kind === 'video'
		})
		if (sender) {
			let parameters = sender.getParameters()
			if (!parameters) {
				parameters = {}
			}
			parameters.encodings = [
				{
					rid: 'h',
					active: true,
					maxBitrate: this.maxBitrates.high,
				},
				{
					rid: 'm',
					active: true,
					maxBitrate: this.maxBitrates.medium,
					scaleResolutionDownBy: 2,
				},
				{
					rid: 'l',
					active: true,
					maxBitrate: this.maxBitrates.low,
					scaleResolutionDownBy: 4,
				},
			]
			sender.setParameters(parameters)
		}
	}
	this.pc.createOffer(options).then(function(offer) {
		if (shouldPreferH264()) {
			console.debug('Preferring hardware codec H.264 as per global configuration')
			offer = preferH264VideoCodecIfAvailable(offer)
		}

		if (sendVideo && this.enableSimulcast) {
			// This SDP munging only works with Chrome (Safari STP may support it too)
			if (adapter.browserDetails.browser === 'chrome' || adapter.browserDetails.browser === 'safari') {
				console.debug('Enabling Simulcasting for Chrome (SDP munging)')
				offer.sdp = mungeSdpForSimulcasting(offer.sdp)
			} else if (adapter.browserDetails.browser !== 'firefox') {
				console.debug('Simulcast can only be enabled on Chrome or Firefox')
			}
		}

		this.pc.setLocalDescription(offer).then(function() {
			if (this.parent.config.nick) {
				// The offer is a RTCSessionDescription that only serializes
				// its own attributes to JSON, so if extra attributes are needed
				// a regular object has to be sent instead.
				offer = {
					type: offer.type,
					sdp: offer.sdp,
					nick: this.parent.config.nick,
				}
			}
			this.send('offer', offer)
		}.bind(this)).catch(function(error) {
			console.warn('setLocalDescription for offer failed: ', error)
		})
	}.bind(this)).catch(function(error) {
		console.warn('createOffer failed: ', error)
	})
}

Peer.prototype.handleOffer = function(offer) {
	this.pc.setRemoteDescription(offer).then(function() {
		this.answer()
	}.bind(this)).catch(function(error) {
		console.warn('setRemoteDescription for offer failed: ', error)
	})
}

Peer.prototype.answer = function() {
	this.pc.createAnswer().then(function(answer) {
		if (shouldPreferH264()) {
			console.debug('Preferring hardware codec H.264 as per global configuration')
			answer = preferH264VideoCodecIfAvailable(answer)
		}
		this.pc.setLocalDescription(answer).then(function() {
			if (this.parent.config.nick) {
				// The answer is a RTCSessionDescription that only serializes
				// its own attributes to JSON, so if extra attributes are needed
				// a regular object has to be sent instead.
				answer = {
					type: answer.type,
					sdp: answer.sdp,
					nick: this.parent.config.nick,
				}
			}
			this.send('answer', answer)
		}.bind(this)).catch(function(error) {
			console.warn('setLocalDescription for answer failed: ', error)
		})
	}.bind(this)).catch(function(error) {
		console.warn('createAnswer failed: ', error)
	})
}

Peer.prototype.handleAnswer = function(answer) {
	this.pc.setRemoteDescription(answer).catch(function(error) {
		console.warn('setRemoteDescription for answer failed: ', error)
	})
}

Peer.prototype.selectSimulcastStream = function(substream, temporal) {
	if (this.substream === substream && this.temporal === temporal) {
		console.debug('Simulcast stream not changed', this, substream, temporal)
		return
	}

	console.debug('Changing simulcast stream', this, substream, temporal)
	this.send('selectStream', {
		substream,
		temporal,
	})
	this.substream = substream
	this.temporal = temporal
}

Peer.prototype.handleMessage = function(message) {
	const self = this

	this.logger.log('getting', message.type, message)

	if (message.type === 'offer') {
		if (!this.nick) {
			this.nick = message.payload.nick
		}
		delete message.payload.nick
		this.handleOffer(message.payload)
	} else if (message.type === 'answer') {
		if (!this.nick) {
			this.nick = message.payload.nick
		}
		delete message.payload.nick
		this.handleAnswer(message.payload)
	} else if (message.type === 'candidate') {
		this.pc.addIceCandidate(message.payload.candidate)
	} else if (message.type === 'connectivityError') {
		this.parent.emit('connectivityError', self)
	} else if (message.type === 'mute') {
		this.parent.emit('mute', { id: message.from, name: message.payload.name })
	} else if (message.type === 'unmute') {
		this.parent.emit('unmute', { id: message.from, name: message.payload.name })
	} else if (message.type === 'endOfCandidates') {
		this.pc.addIceCandidate('')
	} else if (message.type === 'unshareScreen') {
		this.parent.emit('unshareScreen', { id: message.from })
		this.end()
	}
}

// send via signalling channel
Peer.prototype.send = function(messageType, payload) {
	const message = {
		to: this.id,
		sid: this.sid,
		broadcaster: this.broadcaster,
		roomType: this.type,
		type: messageType,
		payload,
	}
	this.logger.log('sending', messageType, message)
	this.parent.emit('message', message)
}

// send via data channel
// returns true when message was sent and false if channel is not open
Peer.prototype.sendDirectly = function(channel, messageType, payload) {
	const message = {
		type: messageType,
		payload,
	}
	this.logger.log('sending via datachannel', channel, messageType, message)
	const dc = this.getDataChannel(channel)
	if (dc.readyState !== 'open') {
		if (!Object.prototype.hasOwnProperty.call(this.pendingDCMessages, channel)) {
			this.pendingDCMessages[channel] = []
		}
		this.pendingDCMessages[channel].push(message)
		return false
	}
	dc.send(JSON.stringify(message))
	return true
}

// Internal method registering handlers for a data channel and emitting events on the peer
Peer.prototype._observeDataChannel = function(channel) {
	const self = this
	channel.onclose = this.emit.bind(this, 'channelClose', channel)
	channel.onerror = this.emit.bind(this, 'channelError', channel)
	channel.onmessage = function(event) {
		self.emit('channelMessage', self, channel.label, JSON.parse(event.data), channel, event)
	}
	channel.onopen = function() {
		self.emit('channelOpen', channel)
		// Check if there are messages that could not be send
		if (Object.prototype.hasOwnProperty.call(self.pendingDCMessages, channel.label)) {
			const pendingMessages = self.pendingDCMessages[channel.label].slice()
			self.pendingDCMessages[channel.label] = []
			for (let i = 0; i < pendingMessages.length; i++) {
				self.sendDirectly(channel.label, pendingMessages[i].type, pendingMessages[i].payload)
			}
		}
	}
}

// Fetch or create a data channel by the given name
Peer.prototype.getDataChannel = function(name, opts) {
	if (!webrtcSupport.supportDataChannel) {
		return this.emit('error', new Error('createDataChannel not supported'))
	}
	let channel = this.channels[name]
	opts || (opts = {})
	if (channel) {
		return channel
	}
	// if we don't have one by this label, create it
	channel = this.channels[name] = this.pc.createDataChannel(name, opts)
	this._observeDataChannel(channel)
	return channel
}

Peer.prototype.onIceCandidate = function(event) {
	const candidate = event.candidate
	if (this.closed) {
		return
	}
	if (candidate) {
		// Retain legacy data structure for compatibility with
		// mobile clients.
		const expandedCandidate = {
			candidate: {
				candidate: candidate.candidate,
				sdpMid: candidate.sdpMid,
				sdpMLineIndex: candidate.sdpMLineIndex,
			},
		}
		this.send('candidate', expandedCandidate)
	} else {
		this.logger.log('End of candidates.')
	}
}

Peer.prototype.start = function() {
	// well, the webrtc api requires that we either
	// a) create a datachannel a priori
	// b) do a renegotiation later to add the SCTP m-line
	// Let's do (a) first...
	if (this.enableDataChannels) {
		this.getDataChannel('simplewebrtc')
	}

	this.offer(this.receiveMedia)
}

Peer.prototype.icerestart = function() {
	const constraints = this.receiveMedia
	constraints.iceRestart = true
	this.offer(constraints)
}

Peer.prototype.end = function() {
	if (this.closed) {
		return
	}
	this.pc.close()
	this.handleStreamRemoved()
	this.parent.off('localTrackReplaced', this.handleLocalTrackReplacedBound)
	this.parent.off('localTrackEnabledChanged', this.handleLocalTrackEnabledChangedBound)
}

Peer.prototype.handleLocalTrackReplaced = function(newTrack, oldTrack, stream) {
	this._pendingReplaceTracksQueue.push({ newTrack, oldTrack, stream })

	this._processPendingReplaceTracks()
}

/**
 * Process pending replace track actions.
 *
 * All the pending replace track actions are executed from the oldest to the
 * newest, waiting until the previous action was executed before executing the
 * next one.
 *
 * The process may be stopped if the connection is lost, or if a track needs to
 * be added rather than replaced, which requires a renegotiation. In both cases
 * the process will start again once the connection is restablished.
 *
 * @returns {Promise} a Promise fulfilled when the processing ends; if it was
 *          completed the resolved value is true, and if it was stopped before
 *          finishing the resolved value is false.
 */
Peer.prototype._processPendingReplaceTracks = function() {
	if (this._processPendingReplaceTracksPromise) {
		return this._processPendingReplaceTracksPromise
	}

	this._processPendingReplaceTracksPromise = this._processPendingReplaceTracksAsync()

	// For compatibility with older browsers "finally" should not be used on
	// Promises.
	this._processPendingReplaceTracksPromise.then(() => {
		this._processPendingReplaceTracksPromise = null
	}).catch(() => {
		this._processPendingReplaceTracksPromise = null
	})

	return this._processPendingReplaceTracksPromise
}

Peer.prototype._processPendingReplaceTracksAsync = async function() {
	while (this._pendingReplaceTracksQueue.length > 0) {
		if (this.pc.iceConnectionState === 'new') {
			// Do not replace the tracks when the connection has not started
			// yet, as Firefox can get "stuck" and not replace the tracks even
			// if tried later again once connected.
			return false
		}

		const pending = this._pendingReplaceTracksQueue.shift()

		try {
			await this._replaceTrack(pending.newTrack, pending.oldTrack, pending.stream)
		} catch (exception) {
			// If the track is added instead of replaced a renegotiation will be
			// needed, so stop replacing tracks.
			return false
		}
	}

	return true
}

/**
 * Replaces the old track with the new track in the appropriate sender.
 *
 * If the new track is disabled the old track will be replaced by a null track
 * instead, which stops the sent data. The old and new tracks can be the same
 * track, which can be used to start or stop sending the track data depending on
 * whether the track is enabled or disabled (at the time of being passed to this
 * method).
 *
 * If a new track is provided but no sender was found the new track is added
 * instead of replaced (which will require a renegotiation).
 *
 * The method returns a promise which is fulfilled once the track was replaced
 * in the appropriate sender, or immediately if no sender was found and no track
 * was added. If a track had to be added the promise is rejected instead.
 *
 * @param {MediaStreamTrack|null} newTrack the new track to set.
 * @param {MediaStreamTrack|null} oldTrack the old track to be replaced.
 * @param {MediaStream} stream the stream that the new track belongs to.
 * @returns {Promise}
 */
Peer.prototype._replaceTrack = async function(newTrack, oldTrack, stream) {
	let senderFound = false

	// The track should be replaced in just one sender, but an array of promises
	// is used to be on the safe side.
	const replaceTrackPromises = []

	this.pc.getSenders().forEach(sender => {
		if (sender.track !== oldTrack && sender.trackDisabled !== oldTrack) {
			return
		}

		if ((sender.track || sender.trackDisabled) && !oldTrack) {
			return
		}

		if (!sender.track && !newTrack) {
			// The old track was disabled and thus already stopped, so it does
			// not need to be replaced, but the null track needs to be set as
			// the disabled track.
			if (sender.trackDisabled === oldTrack) {
				sender.trackDisabled = newTrack
			}

			return
		}

		if (!sender.kind && sender.track) {
			sender.kind = sender.track.kind
		} else if (!sender.kind && sender.trackDisabled) {
			sender.kind = sender.trackDisabled.kind
		} else if (!sender.kind) {
			this.pc.getTransceivers().forEach(transceiver => {
				if (transceiver.sender === sender) {
					sender.kind = transceiver.mid
				}
			})
		}

		// A null track can match on audio and video senders, so it needs to be
		// ensured that the sender kind and the new track kind are compatible.
		// However, in some cases it may not be possible to know the sender
		// kind. In those cases just go ahead and try to replace the track; if
		// the kind does not match then replacing the track will fail, but this
		// should not prevent replacing the track with a proper one later, nor
		// affect any other sender.
		if (!sender.track && sender.kind && sender.kind !== newTrack.kind) {
			return
		}

		senderFound = true

		// Save reference to trackDisabled to be able to restore it if the track
		// can not be replaced.
		const oldTrackDisabled = sender.trackDisabled

		if (newTrack && !newTrack.enabled) {
			sender.trackDisabled = newTrack
		} else {
			sender.trackDisabled = null
		}

		if (!sender.track && !newTrack.enabled) {
			// Nothing to replace now, it will be done once the track is
			// enabled.
			return
		}

		if (sender.track && newTrack && !newTrack.enabled) {
			// Replace with a null track to stop the sender.
			newTrack = null
		}

		const replaceTrackPromise = sender.replaceTrack(newTrack)

		replaceTrackPromise.catch(error => {
			sender.trackDisabled = oldTrackDisabled

			if (error.name === 'InvalidModificationError') {
				console.debug('Track could not be replaced, negotiation needed')
			} else {
				console.error('Track could not be replaced: ', error, oldTrack, newTrack)
			}
		})

		replaceTrackPromises.push(replaceTrackPromise)
	})

	// If the call started when the audio or video device was not active there
	// will be no sender for that type. In that case the track needs to be added
	// instead of replaced.
	if (!senderFound && newTrack) {
		this.pc.addTrack(newTrack, stream)

		return Promise.reject(new Error('Track added instead of replaced'))
	}

	return Promise.allSettled(replaceTrackPromises)
}

Peer.prototype.handleLocalTrackEnabledChanged = function(track, stream) {
	const sender = this.pc.getSenders().find(sender => sender.track === track)
	const stoppedSender = this.pc.getSenders().find(sender => sender.trackDisabled === track)

	if (track.enabled && stoppedSender) {
		this.handleLocalTrackReplacedBound(track, track, stream)
	} else if (!track.enabled && sender) {
		this.handleLocalTrackReplacedBound(track, track, stream)
	}
}

Peer.prototype.handleRemoteStreamAdded = function(event) {
	const self = this
	if (this.stream) {
		this.logger.warn('Already have a remote stream')
	} else {
		this.stream = event.stream

		this.stream.getTracks().forEach(function(track) {
			track.addEventListener('ended', function() {
				if (isAllTracksEnded(self.stream)) {
					self.end()
				}
			})
		})

		this.parent.emit('peerStreamAdded', this)
	}
}

Peer.prototype.handleStreamRemoved = function() {
	const peerIndex = this.parent.peers.indexOf(this)
	if (peerIndex > -1) {
		this.parent.peers.splice(peerIndex, 1)
		this.closed = true
		this.parent.emit('peerStreamRemoved', this)
	}
}

Peer.prototype.handleDataChannelAdded = function(event) {
	const channel = event.channel
	this.channels[channel.label] = channel
	this._observeDataChannel(channel)
}

module.exports = Peer