-
-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathRTCPeerConnection.js
390 lines (323 loc) · 12 KB
/
RTCPeerConnection.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
import NodeDataChannel from '../lib/index.js';
import RTCSessionDescription from './RTCSessionDescription.js';
import RTCDataChannel from './RTCDataChannel.js';
import RTCIceCandidate from './RTCIceCandidate.js';
import { RTCDataChannelEvent, RTCPeerConnectionIceEvent } from './Events.js';
import RTCSctpTransport from './RTCSctpTransport.js';
import DOMException from 'node-domexception';
export default class _RTCPeerConnection extends EventTarget {
static async generateCertificate() {
throw new Error('Not implemented');
}
#peerConnection;
#localOffer;
#localAnswer;
#dataChannels;
#config;
#canTrickleIceCandidates;
#sctp;
#localCandidates = [];
#remoteCandidates = [];
onconnectionstatechange;
ondatachannel;
onicecandidate;
onicecandidateerror;
oniceconnectionstatechange;
onicegatheringstatechange;
onnegotiationneeded;
onsignalingstatechange;
ontrack;
constructor(init = {}) {
super();
this.#config = init;
this.#localOffer = createDeferredPromise();
this.#localAnswer = createDeferredPromise();
this.#dataChannels = new Set();
this.#canTrickleIceCandidates = null;
this.#peerConnection = new NodeDataChannel.PeerConnection(init?.peerIdentity ?? `peer-${getRandomString(7)}`, {
...init,
iceServers:
init?.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() ?? [],
});
// 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 dataChannel = new RTCDataChannel(channel);
this.#dataChannels.add(dataChannel);
this.dispatchEvent(new RTCDataChannelEvent(dataChannel));
});
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);
});
this.addEventListener('icecandidate', (e) => {
if (this.onicecandidate) this.onicecandidate(e);
});
this.#sctp = new RTCSctpTransport({
pc: this,
extraFunctions: {
maxDataChannelId: () => {
return this.#peerConnection?.maxDataChannelId() ?? 65535;
},
maxMessageSize: () => {
return this.#peerConnection?.maxMessageSize() ?? 65535;
},
localCandidates: () => {
return this.#localCandidates;
},
remoteCandidates: () => {
return this.#remoteCandidates;
},
selectedCandidatePair: () => {
return this.#peerConnection?.getSelectedCandidatePair() ?? {};
},
},
});
}
get canTrickleIceCandidates() {
return this.#canTrickleIceCandidates;
}
get connectionState() {
return this.#peerConnection?.state() ?? 'closed';
}
get iceConnectionState() {
return this.#peerConnection?.iceState() ?? 'closed';
}
get iceGatheringState() {
return this.#peerConnection?.gatheringState() ?? 'new';
}
get currentLocalDescription() {
return new RTCSessionDescription(this.#peerConnection?.localDescription() ?? {});
}
get currentRemoteDescription() {
return new RTCSessionDescription(this.#peerConnection?.remoteDescription() ?? {});
}
get localDescription() {
return new RTCSessionDescription(this.#peerConnection?.localDescription() ?? {});
}
get pendingLocalDescription() {
return new RTCSessionDescription(this.#peerConnection?.localDescription() ?? {});
}
get pendingRemoteDescription() {
return new RTCSessionDescription(this.#peerConnection?.remoteDescription() ?? {});
}
get remoteDescription() {
return new RTCSessionDescription(this.#peerConnection?.remoteDescription() ?? {});
}
get sctp() {
return this.#sctp;
}
get signalingState() {
return this.#peerConnection?.signalingState() ?? 'closed';
}
static generateCertificate(keygenAlgorithm) {
throw new DOMException('Not implemented');
}
async addIceCandidate(candidate) {
if (candidate == null || candidate.candidate == null) {
throw new DOMException('Candidate invalid');
}
if (!this.#peerConnection) {
throw new DOMException('Peer connection is closed');
}
this.#remoteCandidates.push(
new RTCIceCandidate({ candidate: candidate.candidate, sdpMid: candidate.sdpMid || '0' }),
);
this.#peerConnection.addRemoteCandidate(candidate.candidate, candidate.sdpMid || '0');
}
addTrack(track, ...streams) {
throw new DOMException('Not implemented');
}
addTransceiver(trackOrKind, init) {
throw new DOMException('Not implemented');
}
close() {
// close all channels before shutting down
this.#dataChannels.forEach((channel) => {
channel.close();
channel = null;
});
this.#peerConnection?.close();
this.#peerConnection = null;
}
createAnswer() {
return this.#localAnswer;
}
createDataChannel(label, opts = {}) {
if (!this.#peerConnection) {
throw new DOMException('Peer connection is closed');
}
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);
});
return dataChannel;
}
createOffer() {
return this.#localOffer;
}
getConfiguration() {
return this.#config;
}
getReceivers() {
throw new DOMException('Not implemented');
}
getSenders() {
throw new DOMException('Not implemented');
}
getStats() {
return new Promise((resolve) => {
let report = new Map();
if (!this.#peerConnection) {
return resolve(report);
}
let cp = this.#peerConnection.getSelectedCandidatePair();
let bytesSent = this.#peerConnection.bytesSent();
let bytesReceived = this.#peerConnection.bytesReceived();
let rtt = this.#peerConnection.rtt();
let localIdRs = getRandomString(8);
let localId = 'RTCIceCandidate_' + localIdRs;
report.set(localId, {
id: localId,
type: 'localcandidate',
timestamp: Date.now(),
candidateType: cp.local.type,
ip: cp.local.address,
port: cp.local.port,
});
let remoteIdRs = getRandomString(8);
let remoteId = 'RTCIceCandidate_' + remoteIdRs;
report.set(remoteId, {
id: remoteId,
type: 'remotecandidate',
timestamp: Date.now(),
candidateType: cp.remote.type,
ip: cp.remote.address,
port: cp.remote.port,
});
let 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,
});
let transportId = 'RTCTransport_0_1';
report.set(transportId, {
id: transportId,
timestamp: Date.now(),
type: 'transport',
bytesSent: bytesSent,
bytesReceived: bytesReceived,
dtlsState: 'connected',
selectedCandidatePairId: candidateId,
selectedCandidatePairChanges: 1,
});
return resolve(report);
});
}
getTransceivers() {
return []; // throw new DOMException('Not implemented');
}
removeTrack() {
throw new DOMException('Not implemented');
}
restartIce() {
throw new DOMException('Not implemented');
}
setConfiguration(config) {
this.#config = config;
}
async setLocalDescription(description) {
if (description == null || description.type == null) {
throw new DOMException('Local description type must be set');
}
if (description.type !== 'offer') {
// any other type causes libdatachannel to throw
return;
}
this.#peerConnection?.setLocalDescription(description.type);
}
async setRemoteDescription(description) {
if (description.sdp == null) {
throw new DOMException('Remote SDP must be set');
}
this.#peerConnection?.setRemoteDescription(description.sdp, description.type);
}
}
function createDeferredPromise() {
let resolve, reject;
let promise = new Promise(function (_resolve, _reject) {
resolve = _resolve;
reject = _reject;
});
promise.resolve = resolve;
promise.reject = reject;
return promise;
}
function getRandomString(length) {
return Math.random()
.toString(36)
.substring(2, 2 + length);
}