-
-
Notifications
You must be signed in to change notification settings - Fork 61
/
RTCPeerConnection.ts
504 lines (419 loc) · 18.9 KB
/
RTCPeerConnection.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
/* eslint-disable @typescript-eslint/no-explicit-any */
import { SelectedCandidateInfo } from '../lib/types';
import { PeerConnection } from '../lib/index';
import RTCSessionDescription from './RTCSessionDescription';
import RTCDataChannel from './RTCDataChannel';
import RTCIceCandidate from './RTCIceCandidate';
import { RTCDataChannelEvent, RTCPeerConnectionIceEvent } from './Events';
import RTCSctpTransport from './RTCSctpTransport';
import * as exceptions from './Exception';
import RTCCertificate from './RTCCertificate';
// extend RTCConfiguration with peerIdentity
interface RTCConfiguration extends globalThis.RTCConfiguration {
peerIdentity?: string;
}
export default class RTCPeerConnection extends EventTarget implements globalThis.RTCPeerConnection {
static async generateCertificate(): Promise<RTCCertificate> {
throw new DOMException('Not implemented');
}
#peerConnection: PeerConnection;
#localOffer: any;
#localAnswer: any;
#dataChannels: Set<RTCDataChannel>;
#dataChannelsClosed = 0;
#config: RTCConfiguration;
#canTrickleIceCandidates: boolean | null;
#sctp: RTCSctpTransport;
#localCandidates: RTCIceCandidate[] = [];
#remoteCandidates: RTCIceCandidate[] = [];
// events
onconnectionstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null;
ondatachannel: ((this: RTCPeerConnection, ev: RTCDataChannelEvent) => any) | null;
onicecandidate: ((this: RTCPeerConnection, ev: RTCPeerConnectionIceEvent) => any) | null;
onicecandidateerror: ((this: RTCPeerConnection, ev: Event) => any) | null;
oniceconnectionstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null;
onicegatheringstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null;
onnegotiationneeded: ((this: RTCPeerConnection, ev: Event) => any) | null;
onsignalingstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null;
ontrack: ((this: RTCPeerConnection, ev: globalThis.RTCTrackEvent) => any) | null;
private _checkConfiguration(config: RTCConfiguration): void {
if (config && config.iceServers === undefined) config.iceServers = [];
if (config && config.iceTransportPolicy === undefined) config.iceTransportPolicy = 'all';
if (config?.iceServers === null) throw new TypeError('IceServers cannot be null');
// Check for all the properties of iceServers
if (Array.isArray(config?.iceServers)) {
for (let i = 0; i < config.iceServers.length; i++) {
if (config.iceServers[i] === null) throw new TypeError('IceServers cannot be null');
if (config.iceServers[i] === undefined) throw new TypeError('IceServers cannot be undefined');
if (Object.keys(config.iceServers[i]).length === 0) throw new TypeError('IceServers cannot be empty');
// If iceServers is string convert to array
if (typeof config.iceServers[i].urls === 'string')
config.iceServers[i].urls = [config.iceServers[i].urls as string];
// urls can not be empty
if ((config.iceServers[i].urls as string[])?.some((url) => url == ''))
throw new exceptions.SyntaxError('IceServers urls cannot be empty');
// urls should be valid URLs and match the protocols "stun:|turn:|turns:"
if (
(config.iceServers[i].urls as string[])?.some(
(url) => {
try {
const parsedURL = new URL(url)
return !/^(stun:|turn:|turns:)$/.test(parsedURL.protocol)
} catch (error) {
return true
}
},
)
)
throw new exceptions.SyntaxError('IceServers urls wrong format');
// If this is a turn server check for username and credential
if ((config.iceServers[i].urls as string[])?.some((url) => url.startsWith('turn'))) {
if (!config.iceServers[i].username)
throw new exceptions.InvalidAccessError('IceServers username cannot be null');
if (!config.iceServers[i].credential)
throw new exceptions.InvalidAccessError('IceServers username cannot be undefined');
}
// length of urls can not be 0
if (config.iceServers[i].urls?.length === 0)
throw new exceptions.SyntaxError('IceServers urls cannot be empty');
}
}
if (
config &&
config.iceTransportPolicy &&
config.iceTransportPolicy !== 'all' &&
config.iceTransportPolicy !== 'relay'
)
throw new TypeError('IceTransportPolicy must be either "all" or "relay"');
}
setConfiguration(config: RTCConfiguration): void {
this._checkConfiguration(config);
this.#config = config;
}
constructor(config: RTCConfiguration = { iceServers: [], iceTransportPolicy: 'all' }) {
super();
this._checkConfiguration(config);
this.#config = config;
this.#localOffer = createDeferredPromise();
this.#localAnswer = createDeferredPromise();
this.#dataChannels = new Set();
this.#canTrickleIceCandidates = null;
try {
const peerIdentity = (config as any)?.peerIdentity ?? `peer-${getRandomString(7)}`;
this.#peerConnection = new PeerConnection(peerIdentity,
{
...config,
iceServers:
config?.iceServers
?.map((server) => {
const urls = Array.isArray(server.urls) ? server.urls : [server.urls];
return urls.map((url) => {
if (server.username && server.credential) {
const [protocol, rest] = url.split(/:(.*)/);
return `${protocol}:${server.username}:${server.credential}@${rest}`;
}
return url;
});
})
.flat() ?? [],
},
);
} catch (error) {
if (!error || !error.message) throw new exceptions.NotFoundError('Unknown error');
throw new exceptions.SyntaxError(error.message);
}
// forward peerConnection events
this.#peerConnection.onStateChange(() => {
this.dispatchEvent(new Event('connectionstatechange'));
});
this.#peerConnection.onIceStateChange(() => {
this.dispatchEvent(new Event('iceconnectionstatechange'));
});
this.#peerConnection.onSignalingStateChange(() => {
this.dispatchEvent(new Event('signalingstatechange'));
});
this.#peerConnection.onGatheringStateChange(() => {
this.dispatchEvent(new Event('icegatheringstatechange'));
});
this.#peerConnection.onDataChannel((channel) => {
const dc = new RTCDataChannel(channel);
this.#dataChannels.add(dc);
this.dispatchEvent(new RTCDataChannelEvent('datachannel', { channel: dc }));
});
this.#peerConnection.onLocalDescription((sdp, type) => {
if (type === 'offer') {
this.#localOffer.resolve({ sdp, type });
}
if (type === 'answer') {
this.#localAnswer.resolve({ sdp, type });
}
});
this.#peerConnection.onLocalCandidate((candidate, sdpMid) => {
if (sdpMid === 'unspec') {
this.#localAnswer.reject(new Error(`Invalid description type ${sdpMid}`));
return;
}
this.#localCandidates.push(new RTCIceCandidate({ candidate, sdpMid }));
this.dispatchEvent(new RTCPeerConnectionIceEvent(new RTCIceCandidate({ candidate, sdpMid })));
});
// forward events to properties
this.addEventListener('connectionstatechange', (e) => {
if (this.onconnectionstatechange) this.onconnectionstatechange(e);
});
this.addEventListener('signalingstatechange', (e) => {
if (this.onsignalingstatechange) this.onsignalingstatechange(e);
});
this.addEventListener('iceconnectionstatechange', (e) => {
if (this.oniceconnectionstatechange) this.oniceconnectionstatechange(e);
});
this.addEventListener('icegatheringstatechange', (e) => {
if (this.onicegatheringstatechange) this.onicegatheringstatechange(e);
});
this.addEventListener('datachannel', (e) => {
if (this.ondatachannel) this.ondatachannel(e as RTCDataChannelEvent);
});
this.addEventListener('icecandidate', (e) => {
if (this.onicecandidate) this.onicecandidate(e as RTCPeerConnectionIceEvent);
});
this.#sctp = new RTCSctpTransport({
pc: this,
extraFunctions: {
maxDataChannelId: (): number => {
return this.#peerConnection.maxDataChannelId();
},
maxMessageSize: (): number => {
return this.#peerConnection.maxMessageSize();
},
localCandidates: (): RTCIceCandidate[] => {
return this.#localCandidates;
},
remoteCandidates: (): RTCIceCandidate[] => {
return this.#remoteCandidates;
},
selectedCandidatePair: (): { local: SelectedCandidateInfo; remote: SelectedCandidateInfo } | null => {
return this.#peerConnection.getSelectedCandidatePair();
},
},
});
}
get canTrickleIceCandidates(): boolean | null {
return this.#canTrickleIceCandidates;
}
get connectionState(): globalThis.RTCPeerConnectionState {
return this.#peerConnection.state();
}
get iceConnectionState(): globalThis.RTCIceConnectionState {
let state = this.#peerConnection.iceState();
// libdatachannel uses 'completed' instead of 'connected'
// see /webrtc/getstats.html
if (state == 'completed') state = 'connected';
return state;
}
get iceGatheringState(): globalThis.RTCIceGatheringState {
return this.#peerConnection.gatheringState();
}
get currentLocalDescription(): RTCSessionDescription {
return new RTCSessionDescription(this.#peerConnection.localDescription() as any);
}
get currentRemoteDescription(): RTCSessionDescription {
return new RTCSessionDescription(this.#peerConnection.remoteDescription() as any);
}
get localDescription(): RTCSessionDescription {
return new RTCSessionDescription(this.#peerConnection.localDescription() as any);
}
get pendingLocalDescription(): RTCSessionDescription {
return new RTCSessionDescription(this.#peerConnection.localDescription() as any);
}
get pendingRemoteDescription(): RTCSessionDescription {
return new RTCSessionDescription(this.#peerConnection.remoteDescription() as any);
}
get remoteDescription(): RTCSessionDescription {
return new RTCSessionDescription(this.#peerConnection.remoteDescription() as any);
}
get sctp(): RTCSctpTransport {
return this.#sctp;
}
get signalingState(): globalThis.RTCSignalingState {
return this.#peerConnection.signalingState();
}
async addIceCandidate(candidate?: globalThis.RTCIceCandidateInit | RTCIceCandidate): Promise<void> {
if (!candidate || !candidate.candidate) {
return;
}
if (candidate.sdpMid === null && candidate.sdpMLineIndex === null) {
throw new TypeError('sdpMid must be set');
}
if (candidate.sdpMid === undefined && candidate.sdpMLineIndex == undefined) {
throw new TypeError('sdpMid must be set');
}
// Reject if sdpMid format is not valid
// ??
if (candidate.sdpMid && candidate.sdpMid.length > 3) {
// console.log(candidate.sdpMid);
throw new exceptions.OperationError('Invalid sdpMid format');
}
// We don't care about sdpMLineIndex, just for test
if (!candidate.sdpMid && candidate.sdpMLineIndex > 1) {
throw new exceptions.OperationError('This is only for test case.');
}
try {
this.#peerConnection.addRemoteCandidate(candidate.candidate, candidate.sdpMid || '0');
this.#remoteCandidates.push(
new RTCIceCandidate({ candidate: candidate.candidate, sdpMid: candidate.sdpMid || '0' }),
);
} catch (error) {
if (!error || !error.message) throw new exceptions.NotFoundError('Unknown error');
// Check error Message if contains specific message
if (error.message.includes('remote candidate without remote description'))
throw new exceptions.InvalidStateError(error.message);
if (error.message.includes('Invalid candidate format')) throw new exceptions.OperationError(error.message);
throw new exceptions.NotFoundError(error.message);
}
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
addTrack(_track, ..._streams): globalThis.RTCRtpSender {
throw new DOMException('Not implemented');
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
addTransceiver(_trackOrKind, _init): globalThis.RTCRtpTransceiver {
throw new DOMException('Not implemented');
}
close(): void {
// close all channels before shutting down
this.#dataChannels.forEach((channel) => {
channel.close();
this.#dataChannelsClosed++;
});
this.#peerConnection.close();
}
createAnswer(): Promise<globalThis.RTCSessionDescriptionInit | any> {
return this.#localAnswer;
}
createDataChannel(label, opts = {}): RTCDataChannel {
const channel = this.#peerConnection.createDataChannel(label, opts);
const dataChannel = new RTCDataChannel(channel, opts);
// ensure we can close all channels when shutting down
this.#dataChannels.add(dataChannel);
dataChannel.addEventListener('close', () => {
this.#dataChannels.delete(dataChannel);
this.#dataChannelsClosed++;
});
return dataChannel;
}
createOffer(): Promise<globalThis.RTCSessionDescriptionInit | any> {
return this.#localOffer;
}
getConfiguration(): globalThis.RTCConfiguration {
return this.#config;
}
getReceivers(): globalThis.RTCRtpReceiver[] {
throw new DOMException('Not implemented');
}
getSenders(): globalThis.RTCRtpSender[] {
throw new DOMException('Not implemented');
}
getStats(): Promise<globalThis.RTCStatsReport> {
return new Promise((resolve) => {
const report = new Map();
const cp = this.#peerConnection?.getSelectedCandidatePair();
const bytesSent = this.#peerConnection?.bytesSent();
const bytesReceived = this.#peerConnection?.bytesReceived();
const rtt = this.#peerConnection?.rtt();
if(!cp) {
return resolve(report);
}
const localIdRs = getRandomString(8);
const localId = 'RTCIceCandidate_' + localIdRs;
report.set(localId, {
id: localId,
type: 'local-candidate',
timestamp: Date.now(),
candidateType: cp.local.type,
ip: cp.local.address,
port: cp.local.port,
});
const remoteIdRs = getRandomString(8);
const remoteId = 'RTCIceCandidate_' + remoteIdRs;
report.set(remoteId, {
id: remoteId,
type: 'remote-candidate',
timestamp: Date.now(),
candidateType: cp.remote.type,
ip: cp.remote.address,
port: cp.remote.port,
});
const candidateId = 'RTCIceCandidatePair_' + localIdRs + '_' + remoteIdRs;
report.set(candidateId, {
id: candidateId,
type: 'candidate-pair',
timestamp: Date.now(),
localCandidateId: localId,
remoteCandidateId: remoteId,
state: 'succeeded',
nominated: true,
writable: true,
bytesSent: bytesSent,
bytesReceived: bytesReceived,
totalRoundTripTime: rtt,
currentRoundTripTime: rtt,
});
const transportId = 'RTCTransport_0_1';
report.set(transportId, {
id: transportId,
timestamp: Date.now(),
type: 'transport',
bytesSent: bytesSent,
bytesReceived: bytesReceived,
dtlsState: 'connected',
selectedCandidatePairId: candidateId,
selectedCandidatePairChanges: 1,
});
// peer-connection'
report.set('P', {
id: 'P',
type: 'peer-connection',
timestamp: Date.now(),
dataChannelsOpened: this.#dataChannels.size,
dataChannelsClosed: this.#dataChannelsClosed,
});
return resolve(report);
});
}
getTransceivers(): globalThis.RTCRtpTransceiver[] {
return []; // throw new DOMException('Not implemented');
}
removeTrack(): void {
throw new DOMException('Not implemented');
}
restartIce(): Promise<void> {
throw new DOMException('Not implemented');
}
async setLocalDescription(description: globalThis.RTCSessionDescriptionInit): Promise<void> {
if (description?.type !== 'offer') {
// any other type causes libdatachannel to throw
return;
}
this.#peerConnection.setLocalDescription(description?.type as any);
}
async setRemoteDescription(description: globalThis.RTCSessionDescriptionInit): Promise<void> {
if (description.sdp == null) {
throw new DOMException('Remote SDP must be set');
}
this.#peerConnection.setRemoteDescription(description.sdp, description.type as any);
}
}
function createDeferredPromise(): any {
let resolve: any, reject: any;
const promise = new Promise(function (_resolve, _reject) {
resolve = _resolve;
reject = _reject;
});
(promise as any).resolve = resolve;
(promise as any).reject = reject;
return promise;
}
function getRandomString(length): string {
return Math.random()
.toString(36)
.substring(2, 2 + length);
}