livekit-client 0.15.3 → 0.16.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/SignalClient.d.ts +6 -3
- package/dist/api/SignalClient.js +70 -28
- package/dist/api/SignalClient.js.map +1 -1
- package/dist/options.d.ts +5 -0
- package/dist/proto/livekit_models.d.ts +30 -0
- package/dist/proto/livekit_models.js +219 -1
- package/dist/proto/livekit_models.js.map +1 -1
- package/dist/proto/livekit_rtc.d.ts +15 -10
- package/dist/proto/livekit_rtc.js +36 -22
- package/dist/proto/livekit_rtc.js.map +1 -1
- package/dist/room/RTCEngine.d.ts +11 -2
- package/dist/room/RTCEngine.js +196 -44
- package/dist/room/RTCEngine.js.map +1 -1
- package/dist/room/Room.d.ts +7 -0
- package/dist/room/Room.js +70 -16
- package/dist/room/Room.js.map +1 -1
- package/dist/room/events.d.ts +5 -3
- package/dist/room/events.js +5 -3
- package/dist/room/events.js.map +1 -1
- package/dist/room/participant/LocalParticipant.d.ts +1 -2
- package/dist/room/participant/LocalParticipant.js +7 -6
- package/dist/room/participant/LocalParticipant.js.map +1 -1
- package/dist/room/participant/RemoteParticipant.js +3 -0
- package/dist/room/participant/RemoteParticipant.js.map +1 -1
- package/dist/room/participant/publishUtils.js +1 -1
- package/dist/room/participant/publishUtils.js.map +1 -1
- package/dist/room/participant/publishUtils.test.js +9 -0
- package/dist/room/participant/publishUtils.test.js.map +1 -1
- package/dist/room/track/LocalTrackPublication.d.ts +2 -0
- package/dist/room/track/LocalTrackPublication.js.map +1 -1
- package/dist/room/track/RemoteTrackPublication.d.ts +2 -1
- package/dist/room/track/RemoteTrackPublication.js +22 -8
- package/dist/room/track/RemoteTrackPublication.js.map +1 -1
- package/dist/room/track/RemoteVideoTrack.js +12 -7
- package/dist/room/track/RemoteVideoTrack.js.map +1 -1
- package/dist/room/track/Track.js +28 -20
- package/dist/room/track/Track.js.map +1 -1
- package/dist/room/track/create.js +5 -0
- package/dist/room/track/create.js.map +1 -1
- package/dist/room/utils.d.ts +3 -0
- package/dist/room/utils.js +16 -1
- package/dist/room/utils.js.map +1 -1
- package/dist/version.d.ts +2 -2
- package/dist/version.js +2 -2
- package/package.json +3 -3
- package/src/api/SignalClient.ts +444 -0
- package/src/connect.ts +100 -0
- package/src/index.ts +47 -0
- package/src/logger.ts +22 -0
- package/src/options.ts +152 -0
- package/src/proto/livekit_models.ts +1863 -0
- package/src/proto/livekit_rtc.ts +3415 -0
- package/src/room/DeviceManager.ts +57 -0
- package/src/room/PCTransport.ts +86 -0
- package/src/room/RTCEngine.ts +598 -0
- package/src/room/Room.ts +840 -0
- package/src/room/errors.ts +65 -0
- package/src/room/events.ts +398 -0
- package/src/room/participant/LocalParticipant.ts +685 -0
- package/src/room/participant/Participant.ts +214 -0
- package/src/room/participant/ParticipantTrackPermission.ts +32 -0
- package/src/room/participant/RemoteParticipant.ts +241 -0
- package/src/room/participant/publishUtils.test.ts +105 -0
- package/src/room/participant/publishUtils.ts +180 -0
- package/src/room/stats.ts +130 -0
- package/src/room/track/LocalAudioTrack.ts +112 -0
- package/src/room/track/LocalTrack.ts +124 -0
- package/src/room/track/LocalTrackPublication.ts +66 -0
- package/src/room/track/LocalVideoTrack.test.ts +70 -0
- package/src/room/track/LocalVideoTrack.ts +416 -0
- package/src/room/track/RemoteAudioTrack.ts +58 -0
- package/src/room/track/RemoteTrack.ts +59 -0
- package/src/room/track/RemoteTrackPublication.ts +198 -0
- package/src/room/track/RemoteVideoTrack.ts +220 -0
- package/src/room/track/Track.ts +307 -0
- package/src/room/track/TrackPublication.ts +120 -0
- package/src/room/track/create.ts +120 -0
- package/src/room/track/defaults.ts +23 -0
- package/src/room/track/options.ts +229 -0
- package/src/room/track/types.ts +8 -0
- package/src/room/track/utils.test.ts +93 -0
- package/src/room/track/utils.ts +76 -0
- package/src/room/utils.ts +62 -0
- package/src/version.ts +2 -0
- package/.github/workflows/publish.yaml +0 -55
- package/.github/workflows/test.yaml +0 -36
- package/example/index.html +0 -247
- package/example/sample.ts +0 -632
- package/example/styles.css +0 -144
- package/example/webpack.config.js +0 -33
@@ -0,0 +1,598 @@
|
|
1
|
+
import { EventEmitter } from 'events';
|
2
|
+
import { SignalClient, SignalOptions } from '../api/SignalClient';
|
3
|
+
import log from '../logger';
|
4
|
+
import { DataPacket, DataPacket_Kind, TrackInfo } from '../proto/livekit_models';
|
5
|
+
import {
|
6
|
+
AddTrackRequest, JoinResponse,
|
7
|
+
LeaveRequest,
|
8
|
+
SignalTarget,
|
9
|
+
TrackPublishedResponse,
|
10
|
+
} from '../proto/livekit_rtc';
|
11
|
+
import { ConnectionError, TrackInvalidError, UnexpectedConnectionState } from './errors';
|
12
|
+
import { EngineEvent } from './events';
|
13
|
+
import PCTransport from './PCTransport';
|
14
|
+
import { sleep } from './utils';
|
15
|
+
|
16
|
+
const lossyDataChannel = '_lossy';
|
17
|
+
const reliableDataChannel = '_reliable';
|
18
|
+
const maxReconnectRetries = 10;
|
19
|
+
const minReconnectWait = 1 * 1000;
|
20
|
+
const maxReconnectDuration = 60 * 1000;
|
21
|
+
export const maxICEConnectTimeout = 15 * 1000;
|
22
|
+
|
23
|
+
/** @internal */
|
24
|
+
export default class RTCEngine extends EventEmitter {
|
25
|
+
publisher?: PCTransport;
|
26
|
+
|
27
|
+
subscriber?: PCTransport;
|
28
|
+
|
29
|
+
client: SignalClient;
|
30
|
+
|
31
|
+
rtcConfig: RTCConfiguration = {};
|
32
|
+
|
33
|
+
private lossyDC?: RTCDataChannel;
|
34
|
+
|
35
|
+
// @ts-ignore noUnusedLocals
|
36
|
+
private lossyDCSub?: RTCDataChannel;
|
37
|
+
|
38
|
+
private reliableDC?: RTCDataChannel;
|
39
|
+
|
40
|
+
// @ts-ignore noUnusedLocals
|
41
|
+
private reliableDCSub?: RTCDataChannel;
|
42
|
+
|
43
|
+
private subscriberPrimary: boolean = false;
|
44
|
+
|
45
|
+
private primaryPC?: RTCPeerConnection;
|
46
|
+
|
47
|
+
private pcConnected: boolean = false;
|
48
|
+
|
49
|
+
private isClosed: boolean = true;
|
50
|
+
|
51
|
+
private pendingTrackResolvers: { [key: string]: (info: TrackInfo) => void } = {};
|
52
|
+
|
53
|
+
// true if publisher connection has already been established.
|
54
|
+
// this is helpful to know if we need to restart ICE on the publisher connection
|
55
|
+
private hasPublished: boolean = false;
|
56
|
+
|
57
|
+
// keep join info around for reconnect
|
58
|
+
private url?: string;
|
59
|
+
|
60
|
+
private token?: string;
|
61
|
+
|
62
|
+
private signalOpts?: SignalOptions;
|
63
|
+
|
64
|
+
private reconnectAttempts: number = 0;
|
65
|
+
|
66
|
+
private reconnectStart: number = 0;
|
67
|
+
|
68
|
+
private fullReconnect: boolean = false;
|
69
|
+
|
70
|
+
private connectedServerAddr?: string;
|
71
|
+
|
72
|
+
constructor() {
|
73
|
+
super();
|
74
|
+
this.client = new SignalClient();
|
75
|
+
}
|
76
|
+
|
77
|
+
async join(url: string, token: string, opts?: SignalOptions): Promise<JoinResponse> {
|
78
|
+
this.url = url;
|
79
|
+
this.token = token;
|
80
|
+
this.signalOpts = opts;
|
81
|
+
|
82
|
+
const joinResponse = await this.client.join(url, token, opts);
|
83
|
+
this.isClosed = false;
|
84
|
+
|
85
|
+
this.subscriberPrimary = joinResponse.subscriberPrimary;
|
86
|
+
if (!this.publisher) {
|
87
|
+
this.configure(joinResponse);
|
88
|
+
}
|
89
|
+
|
90
|
+
// create offer
|
91
|
+
if (!this.subscriberPrimary) {
|
92
|
+
this.negotiate();
|
93
|
+
}
|
94
|
+
|
95
|
+
return joinResponse;
|
96
|
+
}
|
97
|
+
|
98
|
+
close() {
|
99
|
+
this.isClosed = true;
|
100
|
+
|
101
|
+
this.removeAllListeners();
|
102
|
+
if (this.publisher && this.publisher.pc.signalingState !== 'closed') {
|
103
|
+
this.publisher.pc.getSenders().forEach((sender) => {
|
104
|
+
try {
|
105
|
+
this.publisher?.pc.removeTrack(sender);
|
106
|
+
} catch (e) {
|
107
|
+
log.warn('could not removeTrack', e);
|
108
|
+
}
|
109
|
+
});
|
110
|
+
this.publisher.close();
|
111
|
+
this.publisher = undefined;
|
112
|
+
}
|
113
|
+
if (this.subscriber) {
|
114
|
+
this.subscriber.close();
|
115
|
+
this.subscriber = undefined;
|
116
|
+
}
|
117
|
+
this.client.close();
|
118
|
+
}
|
119
|
+
|
120
|
+
addTrack(req: AddTrackRequest): Promise<TrackInfo> {
|
121
|
+
if (this.pendingTrackResolvers[req.cid]) {
|
122
|
+
throw new TrackInvalidError(
|
123
|
+
'a track with the same ID has already been published',
|
124
|
+
);
|
125
|
+
}
|
126
|
+
return new Promise<TrackInfo>((resolve) => {
|
127
|
+
this.pendingTrackResolvers[req.cid] = resolve;
|
128
|
+
this.client.sendAddTrack(req);
|
129
|
+
});
|
130
|
+
}
|
131
|
+
|
132
|
+
updateMuteStatus(trackSid: string, muted: boolean) {
|
133
|
+
this.client.sendMuteTrack(trackSid, muted);
|
134
|
+
}
|
135
|
+
|
136
|
+
get dataSubscriberReadyState(): string | undefined {
|
137
|
+
return this.reliableDCSub?.readyState;
|
138
|
+
}
|
139
|
+
|
140
|
+
get connectedServerAddress(): string | undefined {
|
141
|
+
return this.connectedServerAddr;
|
142
|
+
}
|
143
|
+
|
144
|
+
private configure(joinResponse: JoinResponse) {
|
145
|
+
// already configured
|
146
|
+
if (this.publisher || this.subscriber) {
|
147
|
+
return;
|
148
|
+
}
|
149
|
+
|
150
|
+
// update ICE servers before creating PeerConnection
|
151
|
+
if (joinResponse.iceServers && !this.rtcConfig.iceServers) {
|
152
|
+
const rtcIceServers: RTCIceServer[] = [];
|
153
|
+
joinResponse.iceServers.forEach((iceServer) => {
|
154
|
+
const rtcIceServer: RTCIceServer = {
|
155
|
+
urls: iceServer.urls,
|
156
|
+
};
|
157
|
+
if (iceServer.username) rtcIceServer.username = iceServer.username;
|
158
|
+
if (iceServer.credential) { rtcIceServer.credential = iceServer.credential; }
|
159
|
+
rtcIceServers.push(rtcIceServer);
|
160
|
+
});
|
161
|
+
this.rtcConfig.iceServers = rtcIceServers;
|
162
|
+
}
|
163
|
+
|
164
|
+
this.publisher = new PCTransport(this.rtcConfig);
|
165
|
+
this.subscriber = new PCTransport(this.rtcConfig);
|
166
|
+
|
167
|
+
this.publisher.pc.onicecandidate = (ev) => {
|
168
|
+
if (!ev.candidate) return;
|
169
|
+
log.trace('adding ICE candidate for peer', ev.candidate);
|
170
|
+
this.client.sendIceCandidate(ev.candidate, SignalTarget.PUBLISHER);
|
171
|
+
};
|
172
|
+
|
173
|
+
this.subscriber.pc.onicecandidate = (ev) => {
|
174
|
+
if (!ev.candidate) return;
|
175
|
+
this.client.sendIceCandidate(ev.candidate, SignalTarget.SUBSCRIBER);
|
176
|
+
};
|
177
|
+
|
178
|
+
this.publisher.onOffer = (offer) => {
|
179
|
+
this.client.sendOffer(offer);
|
180
|
+
};
|
181
|
+
|
182
|
+
let primaryPC = this.publisher.pc;
|
183
|
+
if (joinResponse.subscriberPrimary) {
|
184
|
+
primaryPC = this.subscriber.pc;
|
185
|
+
// in subscriber primary mode, server side opens sub data channels.
|
186
|
+
this.subscriber.pc.ondatachannel = this.handleDataChannel;
|
187
|
+
}
|
188
|
+
this.primaryPC = primaryPC;
|
189
|
+
primaryPC.onconnectionstatechange = () => {
|
190
|
+
if (primaryPC.connectionState === 'connected') {
|
191
|
+
log.trace('pc connected');
|
192
|
+
if (!this.pcConnected) {
|
193
|
+
this.pcConnected = true;
|
194
|
+
this.emit(EngineEvent.Connected);
|
195
|
+
}
|
196
|
+
getConnectedAddress(primaryPC).then((v) => {
|
197
|
+
this.connectedServerAddr = v;
|
198
|
+
});
|
199
|
+
} else if (primaryPC.connectionState === 'failed') {
|
200
|
+
// on Safari, PeerConnection will switch to 'disconnected' during renegotiation
|
201
|
+
log.trace('pc disconnected');
|
202
|
+
if (this.pcConnected) {
|
203
|
+
this.pcConnected = false;
|
204
|
+
|
205
|
+
this.handleDisconnect('peerconnection');
|
206
|
+
}
|
207
|
+
}
|
208
|
+
};
|
209
|
+
|
210
|
+
this.subscriber.pc.ontrack = (ev: RTCTrackEvent) => {
|
211
|
+
this.emit(EngineEvent.MediaTrackAdded, ev.track, ev.streams[0], ev.receiver);
|
212
|
+
};
|
213
|
+
|
214
|
+
// data channels
|
215
|
+
this.lossyDC = this.publisher.pc.createDataChannel(lossyDataChannel, {
|
216
|
+
// will drop older packets that arrive
|
217
|
+
ordered: true,
|
218
|
+
maxRetransmits: 0,
|
219
|
+
});
|
220
|
+
this.reliableDC = this.publisher.pc.createDataChannel(reliableDataChannel, {
|
221
|
+
ordered: true,
|
222
|
+
});
|
223
|
+
|
224
|
+
// also handle messages over the pub channel, for backwards compatibility
|
225
|
+
this.lossyDC.onmessage = this.handleDataMessage;
|
226
|
+
this.reliableDC.onmessage = this.handleDataMessage;
|
227
|
+
|
228
|
+
// handle datachannel errors
|
229
|
+
this.lossyDC.onerror = this.handleDataError;
|
230
|
+
this.reliableDC.onerror = this.handleDataError;
|
231
|
+
|
232
|
+
// configure signaling client
|
233
|
+
this.client.onAnswer = async (sd) => {
|
234
|
+
if (!this.publisher) {
|
235
|
+
return;
|
236
|
+
}
|
237
|
+
log.debug(
|
238
|
+
'received server answer',
|
239
|
+
sd.type,
|
240
|
+
this.publisher.pc.signalingState,
|
241
|
+
);
|
242
|
+
await this.publisher.setRemoteDescription(sd);
|
243
|
+
};
|
244
|
+
|
245
|
+
// add candidate on trickle
|
246
|
+
this.client.onTrickle = (candidate, target) => {
|
247
|
+
if (!this.publisher || !this.subscriber) {
|
248
|
+
return;
|
249
|
+
}
|
250
|
+
log.trace('got ICE candidate from peer', candidate, target);
|
251
|
+
if (target === SignalTarget.PUBLISHER) {
|
252
|
+
this.publisher.addIceCandidate(candidate);
|
253
|
+
} else {
|
254
|
+
this.subscriber.addIceCandidate(candidate);
|
255
|
+
}
|
256
|
+
};
|
257
|
+
|
258
|
+
// when server creates an offer for the client
|
259
|
+
this.client.onOffer = async (sd) => {
|
260
|
+
if (!this.subscriber) {
|
261
|
+
return;
|
262
|
+
}
|
263
|
+
log.debug(
|
264
|
+
'received server offer',
|
265
|
+
sd.type,
|
266
|
+
this.subscriber.pc.signalingState,
|
267
|
+
);
|
268
|
+
await this.subscriber.setRemoteDescription(sd);
|
269
|
+
|
270
|
+
// answer the offer
|
271
|
+
const answer = await this.subscriber.pc.createAnswer();
|
272
|
+
await this.subscriber.pc.setLocalDescription(answer);
|
273
|
+
this.client.sendAnswer(answer);
|
274
|
+
};
|
275
|
+
|
276
|
+
this.client.onLocalTrackPublished = (res: TrackPublishedResponse) => {
|
277
|
+
log.debug('received trackPublishedResponse', res);
|
278
|
+
const resolve = this.pendingTrackResolvers[res.cid];
|
279
|
+
if (!resolve) {
|
280
|
+
log.error('missing track resolver for ', res.cid);
|
281
|
+
return;
|
282
|
+
}
|
283
|
+
delete this.pendingTrackResolvers[res.cid];
|
284
|
+
resolve(res.track!);
|
285
|
+
};
|
286
|
+
|
287
|
+
this.client.onTokenRefresh = (token: string) => {
|
288
|
+
this.token = token;
|
289
|
+
};
|
290
|
+
|
291
|
+
this.client.onClose = () => {
|
292
|
+
this.handleDisconnect('signal');
|
293
|
+
};
|
294
|
+
|
295
|
+
this.client.onLeave = (leave?: LeaveRequest) => {
|
296
|
+
if (leave?.canReconnect) {
|
297
|
+
this.fullReconnect = true;
|
298
|
+
this.primaryPC = undefined;
|
299
|
+
} else {
|
300
|
+
this.emit(EngineEvent.Disconnected);
|
301
|
+
this.close();
|
302
|
+
}
|
303
|
+
};
|
304
|
+
}
|
305
|
+
|
306
|
+
private handleDataChannel = async ({ channel }: RTCDataChannelEvent) => {
|
307
|
+
if (!channel) {
|
308
|
+
return;
|
309
|
+
}
|
310
|
+
if (channel.label === reliableDataChannel) {
|
311
|
+
this.reliableDCSub = channel;
|
312
|
+
} else if (channel.label === lossyDataChannel) {
|
313
|
+
this.lossyDCSub = channel;
|
314
|
+
} else {
|
315
|
+
return;
|
316
|
+
}
|
317
|
+
channel.onmessage = this.handleDataMessage;
|
318
|
+
};
|
319
|
+
|
320
|
+
private handleDataMessage = async (message: MessageEvent) => {
|
321
|
+
// decode
|
322
|
+
let buffer: ArrayBuffer | undefined;
|
323
|
+
if (message.data instanceof ArrayBuffer) {
|
324
|
+
buffer = message.data;
|
325
|
+
} else if (message.data instanceof Blob) {
|
326
|
+
buffer = await message.data.arrayBuffer();
|
327
|
+
} else {
|
328
|
+
log.error('unsupported data type', message.data);
|
329
|
+
return;
|
330
|
+
}
|
331
|
+
const dp = DataPacket.decode(new Uint8Array(buffer));
|
332
|
+
if (dp.speaker) {
|
333
|
+
// dispatch speaker updates
|
334
|
+
this.emit(EngineEvent.ActiveSpeakersUpdate, dp.speaker.speakers);
|
335
|
+
} else if (dp.user) {
|
336
|
+
this.emit(EngineEvent.DataPacketReceived, dp.user, dp.kind);
|
337
|
+
}
|
338
|
+
};
|
339
|
+
|
340
|
+
private handleDataError = (event: Event) => {
|
341
|
+
const channel = event.currentTarget as RTCDataChannel;
|
342
|
+
const channelKind = channel.maxRetransmits === 0 ? 'lossy' : 'reliable';
|
343
|
+
|
344
|
+
if (event instanceof ErrorEvent) {
|
345
|
+
const { error } = event.error;
|
346
|
+
log.error(`DataChannel error on ${channelKind}: ${event.message}`, error);
|
347
|
+
} else {
|
348
|
+
log.error(`Unknown DataChannel Error on ${channelKind}`, event);
|
349
|
+
}
|
350
|
+
};
|
351
|
+
|
352
|
+
// websocket reconnect behavior. if websocket is interrupted, and the PeerConnection
|
353
|
+
// continues to work, we can reconnect to websocket to continue the session
|
354
|
+
// after a number of retries, we'll close and give up permanently
|
355
|
+
private handleDisconnect = (connection: string) => {
|
356
|
+
if (this.isClosed) {
|
357
|
+
return;
|
358
|
+
}
|
359
|
+
log.debug(`${connection} disconnected`);
|
360
|
+
if (this.reconnectAttempts === 0) {
|
361
|
+
// only reset start time on the first try
|
362
|
+
this.reconnectStart = Date.now();
|
363
|
+
}
|
364
|
+
|
365
|
+
const delay = (this.reconnectAttempts * this.reconnectAttempts) * 300;
|
366
|
+
setTimeout(async () => {
|
367
|
+
if (this.isClosed) {
|
368
|
+
return;
|
369
|
+
}
|
370
|
+
|
371
|
+
try {
|
372
|
+
if (this.fullReconnect) {
|
373
|
+
await this.restartConnection();
|
374
|
+
} else {
|
375
|
+
await this.resumeConnection();
|
376
|
+
}
|
377
|
+
this.reconnectAttempts = 0;
|
378
|
+
this.fullReconnect = false;
|
379
|
+
} catch (e) {
|
380
|
+
this.reconnectAttempts += 1;
|
381
|
+
let recoverable = true;
|
382
|
+
if (e instanceof UnexpectedConnectionState) {
|
383
|
+
log.debug('received unrecoverable error', e.message);
|
384
|
+
// unrecoverable
|
385
|
+
recoverable = false;
|
386
|
+
} else if (!(e instanceof SignalReconnectError)) {
|
387
|
+
// cannot resume
|
388
|
+
this.fullReconnect = true;
|
389
|
+
}
|
390
|
+
|
391
|
+
const duration = Date.now() - this.reconnectStart;
|
392
|
+
if (this.reconnectAttempts >= maxReconnectRetries || duration > maxReconnectDuration) {
|
393
|
+
recoverable = false;
|
394
|
+
}
|
395
|
+
|
396
|
+
if (recoverable) {
|
397
|
+
this.handleDisconnect('reconnect');
|
398
|
+
} else {
|
399
|
+
log.info(
|
400
|
+
`could not recover connection after ${maxReconnectRetries} attempts, ${duration}ms. giving up`,
|
401
|
+
);
|
402
|
+
this.emit(EngineEvent.Disconnected);
|
403
|
+
this.close();
|
404
|
+
}
|
405
|
+
}
|
406
|
+
}, delay);
|
407
|
+
};
|
408
|
+
|
409
|
+
private async restartConnection() {
|
410
|
+
if (!this.url || !this.token) {
|
411
|
+
// permanent failure, don't attempt reconnection
|
412
|
+
throw new UnexpectedConnectionState('could not reconnect, url or token not saved');
|
413
|
+
}
|
414
|
+
|
415
|
+
log.info('reconnecting, attempt', this.reconnectAttempts);
|
416
|
+
if (this.reconnectAttempts === 0) {
|
417
|
+
this.emit(EngineEvent.Restarting);
|
418
|
+
}
|
419
|
+
|
420
|
+
this.primaryPC = undefined;
|
421
|
+
this.publisher?.close();
|
422
|
+
this.publisher = undefined;
|
423
|
+
this.subscriber?.close();
|
424
|
+
this.subscriber = undefined;
|
425
|
+
|
426
|
+
let joinResponse: JoinResponse;
|
427
|
+
try {
|
428
|
+
joinResponse = await this.join(this.url, this.token, this.signalOpts);
|
429
|
+
} catch (e) {
|
430
|
+
throw new SignalReconnectError();
|
431
|
+
}
|
432
|
+
|
433
|
+
await this.waitForPCConnected();
|
434
|
+
|
435
|
+
// reconnect success
|
436
|
+
this.emit(EngineEvent.Restarted, joinResponse);
|
437
|
+
}
|
438
|
+
|
439
|
+
private async resumeConnection(): Promise<void> {
|
440
|
+
if (!this.url || !this.token) {
|
441
|
+
// permanent failure, don't attempt reconnection
|
442
|
+
throw new UnexpectedConnectionState('could not reconnect, url or token not saved');
|
443
|
+
}
|
444
|
+
// trigger publisher reconnect
|
445
|
+
if (!this.publisher || !this.subscriber) {
|
446
|
+
throw new UnexpectedConnectionState('publisher and subscriber connections unset');
|
447
|
+
}
|
448
|
+
log.info('resuming signal connection, attempt', this.reconnectAttempts);
|
449
|
+
if (this.reconnectAttempts === 0) {
|
450
|
+
this.emit(EngineEvent.Resuming);
|
451
|
+
}
|
452
|
+
|
453
|
+
try {
|
454
|
+
await this.client.reconnect(this.url, this.token);
|
455
|
+
} catch (e) {
|
456
|
+
throw new SignalReconnectError();
|
457
|
+
}
|
458
|
+
this.emit(EngineEvent.SignalResumed);
|
459
|
+
|
460
|
+
this.subscriber.restartingIce = true;
|
461
|
+
|
462
|
+
// only restart publisher if it's needed
|
463
|
+
if (this.hasPublished) {
|
464
|
+
await this.publisher.createAndSendOffer({ iceRestart: true });
|
465
|
+
}
|
466
|
+
|
467
|
+
await this.waitForPCConnected();
|
468
|
+
|
469
|
+
// resume success
|
470
|
+
this.emit(EngineEvent.Resumed);
|
471
|
+
}
|
472
|
+
|
473
|
+
async waitForPCConnected() {
|
474
|
+
const startTime = (new Date()).getTime();
|
475
|
+
let now = startTime;
|
476
|
+
this.pcConnected = false;
|
477
|
+
|
478
|
+
while (now - startTime < maxICEConnectTimeout) {
|
479
|
+
// if there is no connectionstatechange callback fired
|
480
|
+
// check connectionstate after minReconnectWait
|
481
|
+
if (this.primaryPC === undefined) {
|
482
|
+
// we can abort early, connection is hosed
|
483
|
+
break;
|
484
|
+
} else if (now - startTime > minReconnectWait && this.primaryPC?.connectionState === 'connected') {
|
485
|
+
this.pcConnected = true;
|
486
|
+
}
|
487
|
+
if (this.pcConnected) {
|
488
|
+
return;
|
489
|
+
}
|
490
|
+
await sleep(100);
|
491
|
+
now = (new Date()).getTime();
|
492
|
+
}
|
493
|
+
|
494
|
+
// have not reconnected, throw
|
495
|
+
throw new ConnectionError('could not establish PC connection');
|
496
|
+
}
|
497
|
+
|
498
|
+
/* @internal */
|
499
|
+
async sendDataPacket(packet: DataPacket, kind: DataPacket_Kind) {
|
500
|
+
const msg = DataPacket.encode(packet).finish();
|
501
|
+
|
502
|
+
// make sure we do have a data connection
|
503
|
+
await this.ensurePublisherConnected(kind);
|
504
|
+
|
505
|
+
if (kind === DataPacket_Kind.LOSSY && this.lossyDC) {
|
506
|
+
this.lossyDC.send(msg);
|
507
|
+
} else if (kind === DataPacket_Kind.RELIABLE && this.reliableDC) {
|
508
|
+
this.reliableDC.send(msg);
|
509
|
+
}
|
510
|
+
}
|
511
|
+
|
512
|
+
private async ensurePublisherConnected(kind: DataPacket_Kind) {
|
513
|
+
if (!this.subscriberPrimary) {
|
514
|
+
return;
|
515
|
+
}
|
516
|
+
|
517
|
+
if (!this.publisher) {
|
518
|
+
throw new ConnectionError('publisher connection not set');
|
519
|
+
}
|
520
|
+
|
521
|
+
if (!this.publisher.isICEConnected && this.publisher.pc.iceConnectionState !== 'checking') {
|
522
|
+
// start negotiation
|
523
|
+
this.negotiate();
|
524
|
+
}
|
525
|
+
|
526
|
+
const targetChannel = this.dataChannelForKind(kind);
|
527
|
+
if (targetChannel?.readyState === 'open') {
|
528
|
+
return;
|
529
|
+
}
|
530
|
+
|
531
|
+
// wait until publisher ICE connected
|
532
|
+
const endTime = (new Date()).getTime() + maxICEConnectTimeout;
|
533
|
+
while ((new Date()).getTime() < endTime) {
|
534
|
+
if (this.publisher.isICEConnected && this.dataChannelForKind(kind)?.readyState === 'open') {
|
535
|
+
return;
|
536
|
+
}
|
537
|
+
await sleep(50);
|
538
|
+
}
|
539
|
+
|
540
|
+
throw new ConnectionError(`could not establish publisher connection, state ${this.publisher?.pc.iceConnectionState}`);
|
541
|
+
}
|
542
|
+
|
543
|
+
/** @internal */
|
544
|
+
negotiate() {
|
545
|
+
if (!this.publisher) {
|
546
|
+
return;
|
547
|
+
}
|
548
|
+
|
549
|
+
this.hasPublished = true;
|
550
|
+
|
551
|
+
this.publisher.negotiate();
|
552
|
+
}
|
553
|
+
|
554
|
+
private dataChannelForKind(kind: DataPacket_Kind): RTCDataChannel | undefined {
|
555
|
+
if (kind === DataPacket_Kind.LOSSY) {
|
556
|
+
return this.lossyDC;
|
557
|
+
} if (kind === DataPacket_Kind.RELIABLE) {
|
558
|
+
return this.reliableDC;
|
559
|
+
}
|
560
|
+
}
|
561
|
+
}
|
562
|
+
|
563
|
+
async function getConnectedAddress(pc: RTCPeerConnection): Promise<string | undefined> {
|
564
|
+
let selectedCandidatePairId = '';
|
565
|
+
const candidatePairs = new Map<string, RTCIceCandidatePairStats>();
|
566
|
+
// id -> candidate ip
|
567
|
+
const candidates = new Map<string, string>();
|
568
|
+
const stats: RTCStatsReport = await pc.getStats();
|
569
|
+
stats.forEach((v) => {
|
570
|
+
switch (v.type) {
|
571
|
+
case 'transport':
|
572
|
+
selectedCandidatePairId = v.selectedCandidatePairId;
|
573
|
+
break;
|
574
|
+
case 'candidate-pair':
|
575
|
+
if (selectedCandidatePairId === '' && v.selected) {
|
576
|
+
selectedCandidatePairId = v.id;
|
577
|
+
}
|
578
|
+
candidatePairs.set(v.id, v);
|
579
|
+
break;
|
580
|
+
case 'remote-candidate':
|
581
|
+
candidates.set(v.id, `${v.address}:${v.port}`);
|
582
|
+
break;
|
583
|
+
default:
|
584
|
+
}
|
585
|
+
});
|
586
|
+
|
587
|
+
if (selectedCandidatePairId === '') {
|
588
|
+
return undefined;
|
589
|
+
}
|
590
|
+
const selectedID = candidatePairs.get(selectedCandidatePairId)?.remoteCandidateId;
|
591
|
+
if (selectedID === undefined) {
|
592
|
+
return undefined;
|
593
|
+
}
|
594
|
+
return candidates.get(selectedID);
|
595
|
+
}
|
596
|
+
|
597
|
+
class SignalReconnectError extends Error {
|
598
|
+
}
|