-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
negotiator.ts
367 lines (304 loc) · 9.52 KB
/
negotiator.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
import logger from "./logger";
import type { MediaConnection } from "./mediaconnection";
import type { DataConnection } from "./dataconnection/DataConnection";
import {
BaseConnectionErrorType,
ConnectionType,
PeerErrorType,
ServerMessageType,
} from "./enums";
import type { BaseConnection, BaseConnectionEvents } from "./baseconnection";
import type { ValidEventTypes } from "eventemitter3";
/**
* Manages all negotiations between Peers.
*/
export class Negotiator<
Events extends ValidEventTypes,
ConnectionType extends BaseConnection<Events | BaseConnectionEvents>,
> {
constructor(readonly connection: ConnectionType) {}
/** Returns a PeerConnection object set up correctly (for data, media). */
startConnection(options: any) {
const peerConnection = this._startPeerConnection();
// Set the connection's PC.
this.connection.peerConnection = peerConnection;
if (this.connection.type === ConnectionType.Media && options._stream) {
this._addTracksToConnection(options._stream, peerConnection);
}
// What do we need to do now?
if (options.originator) {
const dataConnection = this.connection;
const config: RTCDataChannelInit = { ordered: !!options.reliable };
const dataChannel = peerConnection.createDataChannel(
dataConnection.label,
config,
);
dataConnection._initializeDataChannel(dataChannel);
void this._makeOffer();
} else {
void this.handleSDP("OFFER", options.sdp);
}
}
/** Start a PC. */
private _startPeerConnection(): RTCPeerConnection {
logger.log("Creating RTCPeerConnection.");
const peerConnection = new RTCPeerConnection(
this.connection.provider.options.config,
);
this._setupListeners(peerConnection);
return peerConnection;
}
/** Set up various WebRTC listeners. */
private _setupListeners(peerConnection: RTCPeerConnection) {
const peerId = this.connection.peer;
const connectionId = this.connection.connectionId;
const connectionType = this.connection.type;
const provider = this.connection.provider;
// ICE CANDIDATES.
logger.log("Listening for ICE candidates.");
peerConnection.onicecandidate = (evt) => {
if (!evt.candidate || !evt.candidate.candidate) return;
logger.log(`Received ICE candidates for ${peerId}:`, evt.candidate);
provider.socket.send({
type: ServerMessageType.Candidate,
payload: {
candidate: evt.candidate,
type: connectionType,
connectionId: connectionId,
},
dst: peerId,
});
};
peerConnection.oniceconnectionstatechange = () => {
switch (peerConnection.iceConnectionState) {
case "failed":
logger.log(
"iceConnectionState is failed, closing connections to " + peerId,
);
this.connection.emitError(
BaseConnectionErrorType.NegotiationFailed,
"Negotiation of connection to " + peerId + " failed.",
);
this.connection.close();
break;
case "closed":
logger.log(
"iceConnectionState is closed, closing connections to " + peerId,
);
this.connection.emitError(
BaseConnectionErrorType.ConnectionClosed,
"Connection to " + peerId + " closed.",
);
this.connection.close();
break;
case "disconnected":
logger.log(
"iceConnectionState changed to disconnected on the connection with " +
peerId,
);
break;
case "completed":
peerConnection.onicecandidate = () => {};
break;
}
this.connection.emit(
"iceStateChanged",
peerConnection.iceConnectionState,
);
};
// DATACONNECTION.
logger.log("Listening for data channel");
// Fired between offer and answer, so options should already be saved
// in the options hash.
peerConnection.ondatachannel = (evt) => {
logger.log("Received data channel");
const dataChannel = evt.channel;
const connection = <DataConnection>(
provider.getConnection(peerId, connectionId)
);
connection._initializeDataChannel(dataChannel);
};
// MEDIACONNECTION.
logger.log("Listening for remote stream");
peerConnection.ontrack = (evt) => {
logger.log("Received remote stream");
const stream = evt.streams[0];
const connection = provider.getConnection(peerId, connectionId);
if (connection.type === ConnectionType.Media) {
const mediaConnection = <MediaConnection>connection;
this._addStreamToMediaConnection(stream, mediaConnection);
}
};
}
cleanup(): void {
logger.log("Cleaning up PeerConnection to " + this.connection.peer);
const peerConnection = this.connection.peerConnection;
if (!peerConnection) {
return;
}
this.connection.peerConnection = null;
//unsubscribe from all PeerConnection's events
peerConnection.onicecandidate =
peerConnection.oniceconnectionstatechange =
peerConnection.ondatachannel =
peerConnection.ontrack =
() => {};
const peerConnectionNotClosed = peerConnection.signalingState !== "closed";
let dataChannelNotClosed = false;
const dataChannel = this.connection.dataChannel;
if (dataChannel) {
dataChannelNotClosed =
!!dataChannel.readyState && dataChannel.readyState !== "closed";
}
if (peerConnectionNotClosed || dataChannelNotClosed) {
peerConnection.close();
}
}
private async _makeOffer(): Promise<void> {
const peerConnection = this.connection.peerConnection;
const provider = this.connection.provider;
try {
const offer = await peerConnection.createOffer(
this.connection.options.constraints,
);
logger.log("Created offer.");
if (
this.connection.options.sdpTransform &&
typeof this.connection.options.sdpTransform === "function"
) {
offer.sdp =
this.connection.options.sdpTransform(offer.sdp) || offer.sdp;
}
try {
await peerConnection.setLocalDescription(offer);
logger.log(
"Set localDescription:",
offer,
`for:${this.connection.peer}`,
);
let payload: any = {
sdp: offer,
type: this.connection.type,
connectionId: this.connection.connectionId,
metadata: this.connection.metadata,
};
if (this.connection.type === ConnectionType.Data) {
const dataConnection = <DataConnection>(<unknown>this.connection);
payload = {
...payload,
label: dataConnection.label,
reliable: dataConnection.reliable,
serialization: dataConnection.serialization,
};
}
provider.socket.send({
type: ServerMessageType.Offer,
payload,
dst: this.connection.peer,
});
} catch (err) {
// TODO: investigate why _makeOffer is being called from the answer
if (
err !=
"OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"
) {
provider.emitError(PeerErrorType.WebRTC, err);
logger.log("Failed to setLocalDescription, ", err);
}
}
} catch (err_1) {
provider.emitError(PeerErrorType.WebRTC, err_1);
logger.log("Failed to createOffer, ", err_1);
}
}
private async _makeAnswer(): Promise<void> {
const peerConnection = this.connection.peerConnection;
const provider = this.connection.provider;
try {
const answer = await peerConnection.createAnswer();
logger.log("Created answer.");
if (
this.connection.options.sdpTransform &&
typeof this.connection.options.sdpTransform === "function"
) {
answer.sdp =
this.connection.options.sdpTransform(answer.sdp) || answer.sdp;
}
try {
await peerConnection.setLocalDescription(answer);
logger.log(
`Set localDescription:`,
answer,
`for:${this.connection.peer}`,
);
provider.socket.send({
type: ServerMessageType.Answer,
payload: {
sdp: answer,
type: this.connection.type,
connectionId: this.connection.connectionId,
},
dst: this.connection.peer,
});
} catch (err) {
provider.emitError(PeerErrorType.WebRTC, err);
logger.log("Failed to setLocalDescription, ", err);
}
} catch (err_1) {
provider.emitError(PeerErrorType.WebRTC, err_1);
logger.log("Failed to create answer, ", err_1);
}
}
/** Handle an SDP. */
async handleSDP(type: string, sdp: any): Promise<void> {
sdp = new RTCSessionDescription(sdp);
const peerConnection = this.connection.peerConnection;
const provider = this.connection.provider;
logger.log("Setting remote description", sdp);
const self = this;
try {
await peerConnection.setRemoteDescription(sdp);
logger.log(`Set remoteDescription:${type} for:${this.connection.peer}`);
if (type === "OFFER") {
await self._makeAnswer();
}
} catch (err) {
provider.emitError(PeerErrorType.WebRTC, err);
logger.log("Failed to setRemoteDescription, ", err);
}
}
/** Handle a candidate. */
async handleCandidate(ice: RTCIceCandidate) {
logger.log(`handleCandidate:`, ice);
try {
await this.connection.peerConnection.addIceCandidate(ice);
logger.log(`Added ICE candidate for:${this.connection.peer}`);
} catch (err) {
this.connection.provider.emitError(PeerErrorType.WebRTC, err);
logger.log("Failed to handleCandidate, ", err);
}
}
private _addTracksToConnection(
stream: MediaStream,
peerConnection: RTCPeerConnection,
): void {
logger.log(`add tracks from stream ${stream.id} to peer connection`);
if (!peerConnection.addTrack) {
return logger.error(
`Your browser does't support RTCPeerConnection#addTrack. Ignored.`,
);
}
stream.getTracks().forEach((track) => {
peerConnection.addTrack(track, stream);
});
}
private _addStreamToMediaConnection(
stream: MediaStream,
mediaConnection: MediaConnection,
): void {
logger.log(
`add stream ${stream.id} to media connection ${mediaConnection.connectionId}`,
);
mediaConnection.addStream(stream);
}
}