/
ICESession.ts
515 lines (466 loc) · 19.1 KB
/
ICESession.ts
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
import * as SDPUtils from 'sdp';
import { JingleAction, JingleReasonCondition, JingleSessionRole } from '../Constants';
import { NS_JINGLE_ICE_UDP_1 } from '../Namespaces';
import { Jingle, JingleContent, JingleIce, JingleReason } from '../protocol';
import { exportToSDP, importFromSDP } from './sdp/Intermediate';
import {
convertCandidateToIntermediate,
convertIntermediateToTransport,
convertIntermediateToTransportInfo,
convertRequestToIntermediate
} from './sdp/Protocol';
import BaseSession, { ActionCallback } from './Session';
export default class ICESession extends BaseSession {
public pc: RTCPeerConnection;
public bitrateLimit: number;
public maximumBitrate?: number;
public currentBitrate?: number;
public maxRelayBandwidth: number;
public candidateBuffer: Array<{
sdpMLineIndex: number;
sdpMid: string;
candidate: string;
} | null>;
public transportType: JingleIce['transportType'] = NS_JINGLE_ICE_UDP_1;
public restartingIce: boolean;
private _maybeRestartingIce: any;
private _firstTimeConnected?: boolean;
constructor(opts: any) {
super(opts);
this.pc = new (RTCPeerConnection as any)(
{
...opts.config,
iceServers: opts.iceServers
},
opts.constraints
);
this.pc.addEventListener('iceconnectionstatechange', () => {
this.onIceStateChange();
});
this.pc.addEventListener('icecandidate', e => {
if (e.candidate) {
this.onIceCandidate(e);
} else {
this.onIceEndOfCandidates();
}
});
this.restrictRelayBandwidth();
this.bitrateLimit = 0;
this.maxRelayBandwidth = opts.maxRelayBandwidth;
this.candidateBuffer = [];
this.restartingIce = false;
}
public end(reason: JingleReasonCondition | JingleReason = 'success', silent: boolean = false) {
this.pc.close();
super.end(reason, silent);
}
/* actually do an ice restart */
public async restartIce() {
// only initiators do an ice-restart to avoid conflicts.
if (!this.isInitiator) {
return;
}
if (this._maybeRestartingIce !== undefined) {
clearTimeout(this._maybeRestartingIce);
}
this.restartingIce = true;
try {
await this.processLocal('restart-ice', async () => {
const offer = await this.pc.createOffer({ iceRestart: true });
// extract new ufrag / pwd, send transport-info with just that.
const json = importFromSDP(offer.sdp!);
this.send(JingleAction.TransportInfo, {
contents: json.media.map<JingleContent>(media => ({
creator: JingleSessionRole.Initiator,
name: media.mid,
transport: convertIntermediateToTransport(media, this.transportType)
})),
sid: this.sid
});
await this.pc.setLocalDescription(offer);
});
} catch (err) {
this._log('error', 'Could not create WebRTC offer', err);
this.end(JingleReasonCondition.FailedTransport, true);
}
}
// set the maximum bitrate. Only supported in Chrome and Firefox right now.
public async setMaximumBitrate(maximumBitrate: number) {
if (this.maximumBitrate) {
// potentially take into account bandwidth restrictions due to using TURN.
maximumBitrate = Math.min(maximumBitrate, this.maximumBitrate);
}
this.currentBitrate = maximumBitrate;
if (
!(
(window as any).RTCRtpSender &&
'getParameters' in (window as any).RTCRtpSender.prototype
)
) {
return;
}
// changes the maximum bandwidth using RTCRtpSender.setParameters.
const sender = this.pc.getSenders().find(s => !!s.track && s.track.kind === 'video');
if (!sender) {
return;
}
let browser = '';
if (window.navigator && (window.navigator as any).mozGetUserMedia) {
browser = 'firefox';
} else if (window.navigator && (window.navigator as any).webkitGetUserMedia) {
browser = 'chrome';
}
const parameters = sender.getParameters();
if (browser === 'firefox' && !parameters.encodings) {
parameters.encodings = [{}];
}
if (maximumBitrate === 0) {
delete parameters.encodings[0].maxBitrate;
} else {
if (!parameters.encodings.length) {
parameters.encodings[0] = {};
}
parameters.encodings[0].maxBitrate = maximumBitrate;
}
try {
await this.processLocal('set-bitrate', async () => {
if (browser === 'chrome') {
await sender.setParameters(parameters);
} else if (browser === 'firefox') {
// Firefox needs renegotiation:
// https://bugzilla.mozilla.org/show_bug.cgi?id=1253499
// but we do not want to intefere with our queue so we
// just hope this gets picked up.
if (this.pc.signalingState !== 'stable') {
await sender.setParameters(parameters);
} else if (
this.pc.localDescription &&
this.pc.localDescription.type === 'offer'
) {
await sender.setParameters(parameters);
const offer = await this.pc.createOffer();
await this.pc.setLocalDescription(offer);
await this.pc.setRemoteDescription(this.pc.remoteDescription!);
await this.processBufferedCandidates();
} else if (
this.pc.localDescription &&
this.pc.localDescription.type === 'answer'
) {
await sender.setParameters(parameters);
await this.pc.setRemoteDescription(this.pc.remoteDescription!);
await this.processBufferedCandidates();
const answer = await this.pc.createAnswer();
await this.pc.setLocalDescription(answer);
}
}
});
} catch (err) {
this._log('error', 'setParameters failed', err);
}
}
// ----------------------------------------------------------------
// Jingle action handers
// ----------------------------------------------------------------
protected async onTransportInfo(changes: Jingle, cb: ActionCallback) {
if (
changes.contents &&
changes.contents[0] &&
(changes.contents[0].transport! as JingleIce).gatheringComplete
) {
try {
if (this.pc.signalingState === 'stable') {
await this.pc.addIceCandidate(null!);
} else {
this.candidateBuffer.push(null!);
}
} catch (err) {
this._log('debug', 'Could not add null ICE candidate');
} finally {
cb();
}
return;
}
// detect an ice restart.
if (this.pc.remoteDescription) {
const remoteDescription = this.pc.remoteDescription;
const remoteJSON = importFromSDP(remoteDescription.sdp);
const remoteMedia = remoteJSON.media.find(m => m.mid === changes.contents![0].name);
const currentUsernameFragment = remoteMedia!.iceParameters!.usernameFragment;
const remoteUsernameFragment = (changes.contents![0].transport! as JingleIce)
.usernameFragment;
if (remoteUsernameFragment && currentUsernameFragment !== remoteUsernameFragment) {
changes.contents!.forEach((content, idx) => {
const transport = content.transport! as JingleIce;
remoteJSON.media[idx].iceParameters = {
password: transport.password!,
usernameFragment: transport.usernameFragment!
};
remoteJSON.media[idx].candidates = [];
});
if (remoteDescription.type === 'offer') {
try {
await this.pc.setRemoteDescription(remoteDescription);
await this.processBufferedCandidates();
const answer = await this.pc.createAnswer();
const json = importFromSDP(answer.sdp!);
this.send(JingleAction.TransportInfo, {
contents: json.media.map(media => ({
creator: JingleSessionRole.Initiator,
name: media.mid,
transport: convertIntermediateToTransport(media, this.transportType)
})),
sid: this.sid
});
await this.pc.setLocalDescription(answer);
cb();
} catch (err) {
this._log('error', 'Could not do remote ICE restart', err);
cb(err);
this.end(JingleReasonCondition.FailedTransport);
}
return;
}
try {
await this.pc.setRemoteDescription(remoteDescription);
await this.processBufferedCandidates();
cb();
} catch (err) {
this._log('error', 'Could not do local ICE restart', err);
cb(err);
this.end(JingleReasonCondition.FailedTransport);
}
}
}
const all = (changes.contents || []).map(content => {
const sdpMid = content.name;
const results = ((content.transport! as JingleIce).candidates || []).map(async json => {
const candidate = SDPUtils.writeCandidate(convertCandidateToIntermediate(json));
let sdpMLineIndex!: number;
// workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=1456417
const remoteSDP = this.pc.remoteDescription!.sdp;
const mediaSections = SDPUtils.getMediaSections(remoteSDP);
for (let i = 0; i < mediaSections.length; i++) {
if (SDPUtils.getMid(mediaSections[i]) === sdpMid) {
sdpMLineIndex = i;
break;
}
}
if (this.pc.signalingState === 'stable') {
try {
await this.pc.addIceCandidate({ sdpMid, sdpMLineIndex, candidate });
} catch (err) {
this._log('error', 'Could not add ICE candidate', err);
}
} else {
this.candidateBuffer.push({ sdpMid, sdpMLineIndex, candidate });
}
});
return Promise.all(results);
});
try {
await Promise.all(all);
cb();
} catch (err) {
cb(err);
}
}
protected async onSessionAccept(changes: Jingle, cb: ActionCallback) {
this.state = 'active';
const json = convertRequestToIntermediate(changes, this.peerRole);
const sdp = exportToSDP(json);
try {
await this.pc.setRemoteDescription({ type: 'answer', sdp });
await this.processBufferedCandidates();
this.parent.emit('accepted', this, undefined);
cb();
} catch (err) {
this._log('error', `Could not process WebRTC answer: ${err}`);
cb({ condition: 'general-error' });
}
}
protected onSessionTerminate(changes: Jingle, cb: ActionCallback) {
this._log('info', 'Terminating session');
this.pc.close();
super.end(changes.reason, true);
cb();
}
// ----------------------------------------------------------------
// ICE action handers
// ----------------------------------------------------------------
protected onIceCandidate(e: RTCPeerConnectionIceEvent) {
if (!e.candidate!.candidate) {
return;
}
const candidate = SDPUtils.parseCandidate(e.candidate!.candidate);
const jingle = convertIntermediateToTransportInfo(
e.candidate!.sdpMid!,
candidate,
this.transportType
);
/* monkeypatch ufrag in Firefox */
jingle.contents!.forEach((content, idx) => {
const transport = content.transport as JingleIce;
if (!transport.usernameFragment) {
const json = importFromSDP(this.pc.localDescription!.sdp);
transport.usernameFragment = json.media[idx].iceParameters!.usernameFragment;
}
});
this._log('info', 'Discovered new ICE candidate', jingle);
this.send(JingleAction.TransportInfo, jingle);
}
protected onIceEndOfCandidates() {
this._log('info', 'ICE end of candidates');
const json = importFromSDP(this.pc.localDescription!.sdp);
const firstMedia = json.media[0];
// signal end-of-candidates with our first media mid/ufrag
this.send(JingleAction.TransportInfo, {
contents: [
{
creator: JingleSessionRole.Initiator,
name: firstMedia.mid,
transport: {
gatheringComplete: true,
transportType: this.transportType,
usernameFragment: firstMedia.iceParameters!.usernameFragment
} as JingleIce
}
]
});
}
protected onIceStateChange() {
switch (this.pc.iceConnectionState) {
case 'checking':
this.connectionState = 'connecting';
break;
case 'completed':
case 'connected':
this.connectionState = 'connected';
this.restartingIce = false;
break;
case 'disconnected':
if (this.pc.signalingState === 'stable') {
this.connectionState = 'interrupted';
} else {
this.connectionState = 'disconnected';
}
if (this.restartingIce) {
this.end(JingleReasonCondition.FailedTransport);
return;
}
this.maybeRestartIce();
break;
case 'failed':
if (this.connectionState === 'failed' || this.restartingIce) {
this.end(JingleReasonCondition.FailedTransport);
return;
}
this.connectionState = 'failed';
this.restartIce();
break;
case 'closed':
this.connectionState = 'disconnected';
if (this.restartingIce) {
this.end(JingleReasonCondition.FailedTransport);
} else {
this.end();
}
break;
}
}
protected async processBufferedCandidates() {
for (const candidate of this.candidateBuffer) {
try {
await this.pc.addIceCandidate(candidate!);
} catch (err) {
this._log('error', 'Could not add ICE candidate', err);
}
}
this.candidateBuffer = [];
}
/* when using TURN, we might want to restrict the bandwidth
* to the value specified by MAX_RELAY_BANDWIDTH
* in order to prevent sending excessive traffic through
* the TURN server.
*/
private restrictRelayBandwidth() {
if (
!(
(window as any).RTCRtpSender &&
'getParameters' in (window as any).RTCRtpSender.prototype
)
) {
return;
}
this.pc.addEventListener('iceconnectionstatechange', async () => {
if (
this.pc.iceConnectionState !== 'completed' &&
this.pc.iceConnectionState !== 'connected'
) {
return;
}
if (this._firstTimeConnected) {
return;
}
this._firstTimeConnected = true;
const stats = await this.pc.getStats();
let activeCandidatePair: any;
stats.forEach(report => {
if (report.type === 'transport') {
activeCandidatePair = (stats as any).get(report.selectedCandidatePairId);
}
});
// Fallback for Firefox.
if (!activeCandidatePair) {
stats.forEach(report => {
if (report.type === 'candidate-pair' && report.selected) {
activeCandidatePair = report;
}
});
}
if (activeCandidatePair) {
let isRelay = false;
if (activeCandidatePair.remoteCandidateId) {
const remoteCandidate = (stats as any).get(
activeCandidatePair.remoteCandidateId
);
if (remoteCandidate && remoteCandidate.candidateType === 'relay') {
isRelay = true;
}
}
if (activeCandidatePair.localCandidateId) {
const localCandidate = (stats as any).get(activeCandidatePair.localCandidateId);
if (localCandidate && localCandidate.candidateType === 'relay') {
isRelay = true;
}
}
if (isRelay) {
this.maximumBitrate = this.maxRelayBandwidth;
if (this.currentBitrate) {
this.setMaximumBitrate(Math.min(this.currentBitrate, this.maximumBitrate));
}
}
}
});
}
/* determine whether an ICE restart is in order
* when transitioning to disconnected. Strategy is
* 'wait 2 seconds for things to repair themselves'
* 'maybe check if bytes are sent/received' by comparing
* getStats measurements
*/
private maybeRestartIce() {
// only initiators do an ice-restart to avoid conflicts.
if (!this.isInitiator) {
return;
}
if (this._maybeRestartingIce !== undefined) {
clearTimeout(this._maybeRestartingIce);
}
this._maybeRestartingIce = setTimeout(() => {
delete this._maybeRestartingIce;
if (this.pc.iceConnectionState === 'disconnected') {
this.restartIce();
}
}, 2000);
}
}