-
Notifications
You must be signed in to change notification settings - Fork 253
Expand file tree
/
Copy pathRTCEngine.ts
More file actions
1799 lines (1582 loc) · 57.4 KB
/
RTCEngine.ts
File metadata and controls
1799 lines (1582 loc) · 57.4 KB
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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Mutex } from '@livekit/mutex';
import {
type AddTrackRequest,
ClientConfigSetting,
ClientConfiguration,
type ConnectionQualityUpdate,
DataChannelInfo,
DataChannelReceiveState,
DataPacket,
DataPacket_Kind,
DisconnectReason,
EncryptedPacket,
EncryptedPacketPayload,
Encryption_Type,
type JoinResponse,
type LeaveRequest,
LeaveRequest_Action,
MediaSectionsRequirement,
ParticipantInfo,
ReconnectReason,
type ReconnectResponse,
RequestResponse,
Room as RoomModel,
RoomMovedResponse,
RpcAck,
RpcResponse,
SignalTarget,
SpeakerInfo,
type StreamStateUpdate,
SubscribedQualityUpdate,
type SubscriptionPermissionUpdate,
type SubscriptionResponse,
SyncState,
TrackInfo,
type TrackPublishedResponse,
TrackUnpublishedResponse,
Transcription,
UpdateSubscription,
type UserPacket,
} from '@livekit/protocol';
import { EventEmitter } from 'events';
import type { MediaAttributes } from 'sdp-transform';
import type TypedEventEmitter from 'typed-emitter';
import type { SignalOptions } from '../api/SignalClient';
import {
SignalClient,
SignalConnectionState,
toProtoSessionDescription,
} from '../api/SignalClient';
import type { BaseE2EEManager } from '../e2ee/E2eeManager';
import { asEncryptablePacket } from '../e2ee/utils';
import log, { LoggerNames, getLogger } from '../logger';
import type { InternalRoomOptions } from '../options';
import { DataPacketBuffer } from '../utils/dataPacketBuffer';
import { TTLMap } from '../utils/ttlmap';
import PCTransport, { PCEvents } from './PCTransport';
import { PCTransportManager, PCTransportState } from './PCTransportManager';
import type { ReconnectContext, ReconnectPolicy } from './ReconnectPolicy';
import { DEFAULT_MAX_AGE_MS, type RegionUrlProvider } from './RegionUrlProvider';
import { roomConnectOptionDefaults } from './defaults';
import {
ConnectionError,
ConnectionErrorReason,
NegotiationError,
SignalReconnectError,
TrackInvalidError,
UnexpectedConnectionState,
} from './errors';
import { EngineEvent } from './events';
import { RpcError } from './rpc';
import CriticalTimers from './timers';
import type LocalTrack from './track/LocalTrack';
import type LocalTrackPublication from './track/LocalTrackPublication';
import LocalVideoTrack from './track/LocalVideoTrack';
import type { SimulcastTrackInfo } from './track/LocalVideoTrack';
import type RemoteTrackPublication from './track/RemoteTrackPublication';
import type { Track } from './track/Track';
import type { TrackPublishOptions, VideoCodec } from './track/options';
import { getTrackPublicationInfo } from './track/utils';
import type { LoggerOptions } from './types';
import {
isChromiumBased,
isVideoCodec,
isVideoTrack,
isWeb,
sleep,
supportsAddTrack,
supportsTransceiver,
toHttpUrl,
} from './utils';
const lossyDataChannel = '_lossy';
const reliableDataChannel = '_reliable';
const minReconnectWait = 2 * 1000;
const leaveReconnect = 'leave-reconnect';
const reliabeReceiveStateTTL = 30_000;
const lossyDataChannelBufferThresholdMin = 8 * 1024;
const lossyDataChannelBufferThresholdMax = 256 * 1024;
enum PCState {
New,
Connected,
Disconnected,
Reconnecting,
Closed,
}
/** @internal */
export default class RTCEngine extends (EventEmitter as new () => TypedEventEmitter<EngineEventCallbacks>) {
client: SignalClient;
rtcConfig: RTCConfiguration = {};
peerConnectionTimeout: number = roomConnectOptionDefaults.peerConnectionTimeout;
fullReconnectOnNext: boolean = false;
pcManager?: PCTransportManager;
/**
* @internal
*/
latestJoinResponse?: JoinResponse;
/**
* @internal
*/
latestRemoteOfferId: number = 0;
/** @internal */
e2eeManager: BaseE2EEManager | undefined;
get isClosed() {
return this._isClosed;
}
get pendingReconnect() {
return !!this.reconnectTimeout;
}
private lossyDC?: RTCDataChannel;
// @ts-ignore noUnusedLocals
private lossyDCSub?: RTCDataChannel;
private reliableDC?: RTCDataChannel;
private dcBufferStatus: Map<DataPacket_Kind, boolean>;
// @ts-ignore noUnusedLocals
private reliableDCSub?: RTCDataChannel;
private subscriberPrimary: boolean = false;
private pcState: PCState = PCState.New;
private _isClosed: boolean = true;
private pendingTrackResolvers: {
[key: string]: { resolve: (info: TrackInfo) => void; reject: () => void };
} = {};
// keep join info around for reconnect, this could be a region url
private url?: string;
private token?: string;
private signalOpts?: SignalOptions;
private reconnectAttempts: number = 0;
private reconnectStart: number = 0;
private clientConfiguration?: ClientConfiguration;
private attemptingReconnect: boolean = false;
private reconnectPolicy: ReconnectPolicy;
private reconnectTimeout?: ReturnType<typeof setTimeout>;
private participantSid?: string;
/** keeps track of how often an initial join connection has been tried */
private joinAttempts: number = 0;
/** specifies how often an initial join connection is allowed to retry */
private maxJoinAttempts: number = 1;
private closingLock: Mutex;
private dataProcessLock: Mutex;
private shouldFailNext: boolean = false;
private regionUrlProvider?: RegionUrlProvider;
private log = log;
private loggerOptions: LoggerOptions;
private publisherConnectionPromise: Promise<void> | undefined;
private reliableDataSequence: number = 1;
private reliableMessageBuffer = new DataPacketBuffer();
private reliableReceivedState: TTLMap<string, number> = new TTLMap(reliabeReceiveStateTTL);
private lossyDataStatCurrentBytes: number = 0;
private lossyDataStatByterate: number = 0;
private lossyDataStatInterval: ReturnType<typeof setInterval> | undefined;
private lossyDataDropCount: number = 0;
private midToTrackId: { [key: string]: string } = {};
/** used to indicate whether the browser is currently waiting to reconnect */
private isWaitingForNetworkReconnect: boolean = false;
constructor(private options: InternalRoomOptions) {
super();
this.log = getLogger(options.loggerName ?? LoggerNames.Engine);
this.loggerOptions = {
loggerName: options.loggerName,
loggerContextCb: () => this.logContext,
};
this.client = new SignalClient(undefined, this.loggerOptions);
this.client.signalLatency = this.options.expSignalLatency;
this.reconnectPolicy = this.options.reconnectPolicy;
this.closingLock = new Mutex();
this.dataProcessLock = new Mutex();
this.dcBufferStatus = new Map([
[DataPacket_Kind.LOSSY, true],
[DataPacket_Kind.RELIABLE, true],
]);
this.client.onParticipantUpdate = (updates) =>
this.emit(EngineEvent.ParticipantUpdate, updates);
this.client.onConnectionQuality = (update) =>
this.emit(EngineEvent.ConnectionQualityUpdate, update);
this.client.onRoomUpdate = (update) => this.emit(EngineEvent.RoomUpdate, update);
this.client.onSubscriptionError = (resp) => this.emit(EngineEvent.SubscriptionError, resp);
this.client.onSubscriptionPermissionUpdate = (update) =>
this.emit(EngineEvent.SubscriptionPermissionUpdate, update);
this.client.onSpeakersChanged = (update) => this.emit(EngineEvent.SpeakersChanged, update);
this.client.onStreamStateUpdate = (update) => this.emit(EngineEvent.StreamStateChanged, update);
this.client.onRequestResponse = (response) =>
this.emit(EngineEvent.SignalRequestResponse, response);
}
/** @internal */
get logContext() {
return {
room: this.latestJoinResponse?.room?.name,
roomID: this.latestJoinResponse?.room?.sid,
participant: this.latestJoinResponse?.participant?.identity,
pID: this.participantSid,
};
}
async join(
url: string,
token: string,
opts: SignalOptions,
abortSignal?: AbortSignal,
): Promise<JoinResponse> {
this.url = url;
this.token = token;
this.signalOpts = opts;
this.maxJoinAttempts = opts.maxRetries;
try {
this.joinAttempts += 1;
this.setupSignalClientCallbacks();
const joinResponse = await this.client.join(url, token, opts, abortSignal);
this._isClosed = false;
this.latestJoinResponse = joinResponse;
this.subscriberPrimary = joinResponse.subscriberPrimary;
if (!this.pcManager) {
await this.configure(joinResponse);
}
// create offer
if (!this.subscriberPrimary || joinResponse.fastPublish) {
this.negotiate().catch((err) => {
log.error(err, this.logContext);
});
}
this.registerOnLineListener();
this.clientConfiguration = joinResponse.clientConfiguration;
this.emit(EngineEvent.SignalConnected, joinResponse);
return joinResponse;
} catch (e) {
if (e instanceof ConnectionError) {
if (e.reason === ConnectionErrorReason.ServerUnreachable) {
this.log.warn(
`Couldn't connect to server, attempt ${this.joinAttempts} of ${this.maxJoinAttempts}`,
this.logContext,
);
if (this.joinAttempts < this.maxJoinAttempts) {
return this.join(url, token, opts, abortSignal);
}
}
}
throw e;
}
}
async close() {
const unlock = await this.closingLock.lock();
if (this.isClosed) {
unlock();
return;
}
try {
this._isClosed = true;
this.joinAttempts = 0;
this.emit(EngineEvent.Closing);
this.removeAllListeners();
this.deregisterOnLineListener();
this.clearPendingReconnect();
this.cleanupLossyDataStats();
await this.cleanupPeerConnections();
await this.cleanupClient();
} finally {
unlock();
}
}
async cleanupPeerConnections() {
await this.pcManager?.close();
this.pcManager = undefined;
const dcCleanup = (dc: RTCDataChannel | undefined) => {
if (!dc) return;
dc.close();
dc.onbufferedamountlow = null;
dc.onclose = null;
dc.onclosing = null;
dc.onerror = null;
dc.onmessage = null;
dc.onopen = null;
};
dcCleanup(this.lossyDC);
dcCleanup(this.lossyDCSub);
dcCleanup(this.reliableDC);
dcCleanup(this.reliableDCSub);
this.lossyDC = undefined;
this.lossyDCSub = undefined;
this.reliableDC = undefined;
this.reliableDCSub = undefined;
this.reliableMessageBuffer = new DataPacketBuffer();
this.reliableDataSequence = 1;
this.reliableReceivedState.clear();
}
cleanupLossyDataStats() {
this.lossyDataStatByterate = 0;
this.lossyDataStatCurrentBytes = 0;
if (this.lossyDataStatInterval) {
clearInterval(this.lossyDataStatInterval);
this.lossyDataStatInterval = undefined;
}
this.lossyDataDropCount = 0;
}
async cleanupClient() {
await this.client.close();
this.client.resetCallbacks();
}
addTrack(req: AddTrackRequest): Promise<TrackInfo> {
if (this.pendingTrackResolvers[req.cid]) {
throw new TrackInvalidError('a track with the same ID has already been published');
}
return new Promise<TrackInfo>((resolve, reject) => {
const publicationTimeout = setTimeout(() => {
delete this.pendingTrackResolvers[req.cid];
reject(
ConnectionError.timeout('publication of local track timed out, no response from server'),
);
}, 10_000);
this.pendingTrackResolvers[req.cid] = {
resolve: (info: TrackInfo) => {
clearTimeout(publicationTimeout);
resolve(info);
},
reject: () => {
clearTimeout(publicationTimeout);
reject(new Error('Cancelled publication by calling unpublish'));
},
};
this.client.sendAddTrack(req);
});
}
/**
* Removes sender from PeerConnection, returning true if it was removed successfully
* and a negotiation is necessary
* @param sender
* @returns
*/
removeTrack(sender: RTCRtpSender): boolean {
if (sender.track && this.pendingTrackResolvers[sender.track.id]) {
const { reject } = this.pendingTrackResolvers[sender.track.id];
if (reject) {
reject();
}
delete this.pendingTrackResolvers[sender.track.id];
}
try {
this.pcManager!.removeTrack(sender);
return true;
} catch (e: unknown) {
this.log.warn('failed to remove track', { ...this.logContext, error: e });
}
return false;
}
updateMuteStatus(trackSid: string, muted: boolean) {
this.client.sendMuteTrack(trackSid, muted);
}
get dataSubscriberReadyState(): string | undefined {
return this.reliableDCSub?.readyState;
}
async getConnectedServerAddress(): Promise<string | undefined> {
return this.pcManager?.getConnectedAddress();
}
/* @internal */
setRegionUrlProvider(provider: RegionUrlProvider) {
this.regionUrlProvider = provider;
}
private async configure(joinResponse: JoinResponse) {
// already configured
if (this.pcManager && this.pcManager.currentState !== PCTransportState.NEW) {
return;
}
this.participantSid = joinResponse.participant?.sid;
const rtcConfig = this.makeRTCConfiguration(joinResponse);
this.pcManager = new PCTransportManager(
rtcConfig,
this.options.singlePeerConnection
? 'publisher-only'
: joinResponse.subscriberPrimary
? 'subscriber-primary'
: 'publisher-primary',
this.loggerOptions,
);
this.emit(EngineEvent.TransportsCreated, this.pcManager.publisher, this.pcManager.subscriber);
this.pcManager.onIceCandidate = (candidate, target) => {
this.client.sendIceCandidate(candidate, target);
};
this.pcManager.onPublisherOffer = (offer, offerId) => {
this.client.sendOffer(offer, offerId);
};
this.pcManager.onDataChannel = this.handleDataChannel;
this.pcManager.onStateChange = async (connectionState, publisherState, subscriberState) => {
this.log.debug(`primary PC state changed ${connectionState}`, this.logContext);
if (['closed', 'disconnected', 'failed'].includes(publisherState)) {
// reset publisher connection promise
this.publisherConnectionPromise = undefined;
}
if (connectionState === PCTransportState.CONNECTED) {
const shouldEmit = this.pcState === PCState.New;
this.pcState = PCState.Connected;
if (shouldEmit) {
this.emit(EngineEvent.Connected, joinResponse);
}
} else if (connectionState === PCTransportState.FAILED) {
// on Safari, PeerConnection will switch to 'disconnected' during renegotiation
if (this.pcState === PCState.Connected || this.pcState === PCState.Reconnecting) {
this.pcState = PCState.Disconnected;
this.handleDisconnect(
'peerconnection failed',
subscriberState === 'failed'
? ReconnectReason.RR_SUBSCRIBER_FAILED
: ReconnectReason.RR_PUBLISHER_FAILED,
);
}
}
// detect cases where both signal client and peer connection are severed and assume that user has lost network connection
const isSignalSevered =
this.client.isDisconnected ||
this.client.currentState === SignalConnectionState.RECONNECTING;
const isPCSevered = [
PCTransportState.FAILED,
PCTransportState.CLOSING,
PCTransportState.CLOSED,
].includes(connectionState);
if (isSignalSevered && isPCSevered && !this._isClosed) {
this.emit(EngineEvent.Offline);
}
};
this.pcManager.onTrack = (ev: RTCTrackEvent) => {
// this fires after the underlying transceiver is stopped and potentially
// peer connection closed, so do not bubble up if there are no streams
if (ev.streams.length === 0) return;
this.emit(EngineEvent.MediaTrackAdded, ev.track, ev.streams[0], ev.receiver);
};
if (!supportOptionalDatachannel(joinResponse.serverInfo?.protocol)) {
this.createDataChannels();
}
}
private setupSignalClientCallbacks() {
// configure signaling client
this.client.onAnswer = async (sd, offerId, midToTrackId) => {
if (!this.pcManager) {
return;
}
this.log.debug('received server answer', {
...this.logContext,
RTCSdpType: sd.type,
sdp: sd.sdp,
midToTrackId,
});
this.midToTrackId = midToTrackId;
await this.pcManager.setPublisherAnswer(sd, offerId);
};
// add candidate on trickle
this.client.onTrickle = (candidate, target) => {
if (!this.pcManager) {
return;
}
this.log.debug('got ICE candidate from peer', { ...this.logContext, candidate, target });
this.pcManager.addIceCandidate(candidate, target);
};
// when server creates an offer for the client
this.client.onOffer = async (sd, offerId, midToTrackId) => {
this.latestRemoteOfferId = offerId;
if (!this.pcManager) {
return;
}
this.midToTrackId = midToTrackId;
const answer = await this.pcManager.createSubscriberAnswerFromOffer(sd, offerId);
if (answer) {
this.client.sendAnswer(answer, offerId);
}
};
this.client.onLocalTrackPublished = (res: TrackPublishedResponse) => {
this.log.debug('received trackPublishedResponse', {
...this.logContext,
cid: res.cid,
track: res.track?.sid,
});
if (!this.pendingTrackResolvers[res.cid]) {
this.log.error(`missing track resolver for ${res.cid}`, {
...this.logContext,
cid: res.cid,
});
return;
}
const { resolve } = this.pendingTrackResolvers[res.cid];
delete this.pendingTrackResolvers[res.cid];
resolve(res.track!);
};
this.client.onLocalTrackUnpublished = (response: TrackUnpublishedResponse) => {
this.emit(EngineEvent.LocalTrackUnpublished, response);
};
this.client.onLocalTrackSubscribed = (trackSid: string) => {
this.emit(EngineEvent.LocalTrackSubscribed, trackSid);
};
this.client.onTokenRefresh = (token: string) => {
this.token = token;
this.regionUrlProvider?.updateToken(token);
};
this.client.onRemoteMuteChanged = (trackSid: string, muted: boolean) => {
this.emit(EngineEvent.RemoteMute, trackSid, muted);
};
this.client.onSubscribedQualityUpdate = (update: SubscribedQualityUpdate) => {
this.emit(EngineEvent.SubscribedQualityUpdate, update);
};
this.client.onRoomMoved = (res: RoomMovedResponse) => {
this.participantSid = res.participant?.sid;
if (this.latestJoinResponse) {
this.latestJoinResponse.room = res.room;
}
this.emit(EngineEvent.RoomMoved, res);
};
this.client.onMediaSectionsRequirement = (requirement: MediaSectionsRequirement) => {
const transceiverInit: RTCRtpTransceiverInit = { direction: 'recvonly' };
for (let i: number = 0; i < requirement.numAudios; i++) {
this.pcManager?.addPublisherTransceiverOfKind('audio', transceiverInit);
}
for (let i: number = 0; i < requirement.numVideos; i++) {
this.pcManager?.addPublisherTransceiverOfKind('video', transceiverInit);
}
this.negotiate();
};
this.client.onClose = () => {
this.handleDisconnect('signal', ReconnectReason.RR_SIGNAL_DISCONNECTED);
};
this.client.onLeave = (leave: LeaveRequest) => {
this.log.debug('client leave request', { ...this.logContext, reason: leave?.reason });
if (leave.regions && this.regionUrlProvider) {
this.log.debug('updating regions', this.logContext);
this.regionUrlProvider.setServerReportedRegions({
updatedAtInMs: Date.now(),
maxAgeInMs: DEFAULT_MAX_AGE_MS,
regionSettings: leave.regions,
});
}
switch (leave.action) {
case LeaveRequest_Action.DISCONNECT:
this.emit(EngineEvent.Disconnected, leave?.reason);
this.close();
break;
case LeaveRequest_Action.RECONNECT:
this.fullReconnectOnNext = true;
// reconnect immediately instead of waiting for next attempt
this.handleDisconnect(leaveReconnect);
break;
case LeaveRequest_Action.RESUME:
// reconnect immediately instead of waiting for next attempt
this.handleDisconnect(leaveReconnect);
default:
break;
}
};
}
private makeRTCConfiguration(serverResponse: JoinResponse | ReconnectResponse): RTCConfiguration {
const rtcConfig = { ...this.rtcConfig };
if (this.signalOpts?.e2eeEnabled || isChromiumBased()) {
this.log.debug('setting up transports with insertable streams', this.logContext);
// @ts-ignore
rtcConfig.encodedInsertableStreams = true;
}
// update ICE servers before creating PeerConnection
if (serverResponse.iceServers && !rtcConfig.iceServers) {
const rtcIceServers: RTCIceServer[] = [];
serverResponse.iceServers.forEach((iceServer) => {
const rtcIceServer: RTCIceServer = {
urls: iceServer.urls,
};
if (iceServer.username) rtcIceServer.username = iceServer.username;
if (iceServer.credential) {
rtcIceServer.credential = iceServer.credential;
}
rtcIceServers.push(rtcIceServer);
});
rtcConfig.iceServers = rtcIceServers;
}
if (
serverResponse.clientConfiguration &&
serverResponse.clientConfiguration.forceRelay === ClientConfigSetting.ENABLED
) {
rtcConfig.iceTransportPolicy = 'relay';
}
// @ts-ignore
rtcConfig.sdpSemantics = 'unified-plan';
// @ts-ignore
rtcConfig.continualGatheringPolicy = 'gather_continually';
return rtcConfig;
}
private createDataChannels() {
if (!this.pcManager) {
return;
}
// clear old data channel callbacks if recreate
if (this.lossyDC) {
this.lossyDC.onmessage = null;
this.lossyDC.onerror = null;
}
if (this.reliableDC) {
this.reliableDC.onmessage = null;
this.reliableDC.onerror = null;
}
// create data channels
this.lossyDC = this.pcManager.createPublisherDataChannel(lossyDataChannel, {
ordered: false,
maxRetransmits: 0,
});
this.reliableDC = this.pcManager.createPublisherDataChannel(reliableDataChannel, {
ordered: true,
});
// also handle messages over the pub channel, for backwards compatibility
this.lossyDC.onmessage = this.handleDataMessage;
this.reliableDC.onmessage = this.handleDataMessage;
// handle datachannel errors
this.lossyDC.onerror = this.handleDataError;
this.reliableDC.onerror = this.handleDataError;
// set up dc buffer threshold, set to 64kB (otherwise 0 by default)
this.lossyDC.bufferedAmountLowThreshold = 65535;
this.reliableDC.bufferedAmountLowThreshold = 65535;
// handle buffer amount low events
this.lossyDC.onbufferedamountlow = this.handleBufferedAmountLow;
this.reliableDC.onbufferedamountlow = this.handleBufferedAmountLow;
this.cleanupLossyDataStats();
this.lossyDataStatInterval = setInterval(() => {
this.lossyDataStatByterate = this.lossyDataStatCurrentBytes;
this.lossyDataStatCurrentBytes = 0;
const dc = this.dataChannelForKind(DataPacket_Kind.LOSSY);
if (dc) {
// control buffered latency to ~100ms
const threshold = this.lossyDataStatByterate / 10;
dc.bufferedAmountLowThreshold = Math.min(
Math.max(threshold, lossyDataChannelBufferThresholdMin),
lossyDataChannelBufferThresholdMax,
);
}
}, 1000);
}
private handleDataChannel = async ({ channel }: RTCDataChannelEvent) => {
if (!channel) {
return;
}
if (channel.label === reliableDataChannel) {
this.reliableDCSub = channel;
} else if (channel.label === lossyDataChannel) {
this.lossyDCSub = channel;
} else {
return;
}
this.log.debug(`on data channel ${channel.id}, ${channel.label}`, this.logContext);
channel.onmessage = this.handleDataMessage;
};
private handleDataMessage = async (message: MessageEvent) => {
// make sure to respect incoming data message order by processing message events one after the other
const unlock = await this.dataProcessLock.lock();
try {
// decode
let buffer: ArrayBuffer | undefined;
if (message.data instanceof ArrayBuffer) {
buffer = message.data;
} else if (message.data instanceof Blob) {
buffer = await message.data.arrayBuffer();
} else {
this.log.error('unsupported data type', { ...this.logContext, data: message.data });
return;
}
const dp = DataPacket.fromBinary(new Uint8Array(buffer));
if (dp.sequence > 0 && dp.participantSid !== '') {
const lastSeq = this.reliableReceivedState.get(dp.participantSid);
if (lastSeq && dp.sequence <= lastSeq) {
// ignore duplicate or out-of-order packets in reliable channel
return;
}
this.reliableReceivedState.set(dp.participantSid, dp.sequence);
}
if (dp.value?.case === 'speaker') {
// dispatch speaker updates
this.emit(EngineEvent.ActiveSpeakersUpdate, dp.value.value.speakers);
} else if (dp.value?.case === 'encryptedPacket') {
if (!this.e2eeManager) {
this.log.error('Received encrypted packet but E2EE not set up', this.logContext);
return;
}
const decryptedData = await this.e2eeManager?.handleEncryptedData(
dp.value.value.encryptedValue,
dp.value.value.iv,
dp.participantIdentity,
dp.value.value.keyIndex,
);
const decryptedPacket = EncryptedPacketPayload.fromBinary(decryptedData.payload);
const newDp = new DataPacket({
value: decryptedPacket.value,
participantIdentity: dp.participantIdentity,
participantSid: dp.participantSid,
});
if (newDp.value?.case === 'user') {
// compatibility
applyUserDataCompat(newDp, newDp.value.value);
}
this.emit(EngineEvent.DataPacketReceived, newDp, dp.value.value.encryptionType);
} else {
if (dp.value?.case === 'user') {
// compatibility
applyUserDataCompat(dp, dp.value.value);
}
this.emit(EngineEvent.DataPacketReceived, dp, Encryption_Type.NONE);
}
} finally {
unlock();
}
};
private handleDataError = (event: Event) => {
const channel = event.currentTarget as RTCDataChannel;
const channelKind = channel.maxRetransmits === 0 ? 'lossy' : 'reliable';
if (event instanceof ErrorEvent && event.error) {
const { error } = event.error;
this.log.error(`DataChannel error on ${channelKind}: ${event.message}`, {
...this.logContext,
error,
});
} else {
this.log.error(`Unknown DataChannel error on ${channelKind}`, { ...this.logContext, event });
}
};
private handleBufferedAmountLow = (event: Event) => {
const channel = event.currentTarget as RTCDataChannel;
const channelKind =
channel.maxRetransmits === 0 ? DataPacket_Kind.LOSSY : DataPacket_Kind.RELIABLE;
this.updateAndEmitDCBufferStatus(channelKind);
};
async createSender(
track: LocalTrack,
opts: TrackPublishOptions,
encodings?: RTCRtpEncodingParameters[],
) {
if (supportsTransceiver()) {
const sender = await this.createTransceiverRTCRtpSender(track, opts, encodings);
return sender;
}
if (supportsAddTrack()) {
this.log.warn('using add-track fallback', this.logContext);
const sender = await this.createRTCRtpSender(track.mediaStreamTrack);
return sender;
}
throw new UnexpectedConnectionState('Required webRTC APIs not supported on this device');
}
async createSimulcastSender(
track: LocalVideoTrack,
simulcastTrack: SimulcastTrackInfo,
opts: TrackPublishOptions,
encodings?: RTCRtpEncodingParameters[],
) {
// store RTCRtpSender
if (supportsTransceiver()) {
return this.createSimulcastTransceiverSender(track, simulcastTrack, opts, encodings);
}
if (supportsAddTrack()) {
this.log.debug('using add-track fallback', this.logContext);
return this.createRTCRtpSender(track.mediaStreamTrack);
}
throw new UnexpectedConnectionState('Cannot stream on this device');
}
private async createTransceiverRTCRtpSender(
track: LocalTrack,
opts: TrackPublishOptions,
encodings?: RTCRtpEncodingParameters[],
) {
if (!this.pcManager) {
throw new UnexpectedConnectionState('publisher is closed');
}
const streams: MediaStream[] = [];
if (track.mediaStream) {
streams.push(track.mediaStream);
}
if (isVideoTrack(track)) {
track.codec = opts.videoCodec;
}
const transceiverInit: RTCRtpTransceiverInit = { direction: 'sendonly', streams };
if (encodings) {
transceiverInit.sendEncodings = encodings;
}
// addTransceiver for react-native is async. web is synchronous, but await won't effect it.
const transceiver = await this.pcManager.addPublisherTransceiver(
track.mediaStreamTrack,
transceiverInit,
);
return transceiver.sender;
}
private async createSimulcastTransceiverSender(
track: LocalVideoTrack,
simulcastTrack: SimulcastTrackInfo,
opts: TrackPublishOptions,
encodings?: RTCRtpEncodingParameters[],
) {
if (!this.pcManager) {
throw new UnexpectedConnectionState('publisher is closed');
}
const transceiverInit: RTCRtpTransceiverInit = { direction: 'sendonly' };
if (encodings) {
transceiverInit.sendEncodings = encodings;
}
// addTransceiver for react-native is async. web is synchronous, but await won't effect it.
const transceiver = await this.pcManager.addPublisherTransceiver(
simulcastTrack.mediaStreamTrack,
transceiverInit,
);
if (!opts.videoCodec) {
return;
}
track.setSimulcastTrackSender(opts.videoCodec, transceiver.sender);
return transceiver.sender;
}
private async createRTCRtpSender(track: MediaStreamTrack) {
if (!this.pcManager) {
throw new UnexpectedConnectionState('publisher is closed');
}
return this.pcManager.addPublisherTrack(track);
}
// websocket reconnect behavior. if websocket is interrupted, and the PeerConnection
// continues to work, we can reconnect to websocket to continue the session
// after a number of retries, we'll close and give up permanently
private handleDisconnect = (connection: string, disconnectReason?: ReconnectReason) => {
if (this._isClosed) {
return;
}
this.log.warn(`${connection} disconnected`, this.logContext);
if (this.reconnectAttempts === 0) {
// only reset start time on the first try
this.reconnectStart = Date.now();
}
const disconnect = (duration: number) => {
this.log.warn(
`could not recover connection after ${this.reconnectAttempts} attempts, ${duration}ms. giving up`,
this.logContext,
);
this.emit(EngineEvent.Disconnected);
this.close();
};
const duration = Date.now() - this.reconnectStart;
let delay = this.getNextRetryDelay({
elapsedMs: duration,
retryCount: this.reconnectAttempts,
});
if (delay === null) {
disconnect(duration);
return;
}
if (connection === leaveReconnect) {
delay = 0;
}
this.log.debug(`reconnecting in ${delay}ms`, this.logContext);
this.clearReconnectTimeout();
if (this.token && this.regionUrlProvider) {
// token may have been refreshed, we do not want to recreate the regionUrlProvider
// since the current engine may have inherited a regional url
this.regionUrlProvider.updateToken(this.token);
}
this.reconnectTimeout = CriticalTimers.setTimeout(
() =>
this.attemptReconnect(disconnectReason).finally(() => (this.reconnectTimeout = undefined)),
delay,