Repository navigation
Expand file tree
/
Copy pathroom.ts
More file actions
1170 lines (1090 loc) · 44.1 KB
/
Copy pathroom.ts
File metadata and controls
1170 lines (1090 loc) · 44.1 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
// SPDX-FileCopyrightText: 2024 LiveKit, Inc.
//
// SPDX-License-Identifier: Apache-2.0
import { Mutex } from '@livekit/mutex';
import { EncryptionState, type EncryptionType } from '@livekit/rtc-ffi-bindings';
import type {
FfiEvent,
GetSessionStatsCallback,
GetSessionStatsResponse,
} from '@livekit/rtc-ffi-bindings';
import { DisconnectReason, type OwnedParticipant } from '@livekit/rtc-ffi-bindings';
import type {
DataStream_Trailer,
DisconnectCallback,
TrackPublicationInfo,
} from '@livekit/rtc-ffi-bindings';
import {
type ConnectCallback,
ConnectRequest,
type ConnectResponse,
type ConnectionQuality,
ConnectionState,
ContinualGatheringPolicy,
type DataPacketKind,
type DataStream_Chunk,
type DataStream_Header,
type DisconnectResponse,
RoomOptions as FfiRoomOptions,
type IceServer,
IceTransportType,
type ReadyForRoomEventResponse,
RoomDataStreamOptions,
type RoomInfo,
type SimulateScenarioCallback,
type SimulateScenarioKind,
type SimulateScenarioResponse,
} from '@livekit/rtc-ffi-bindings';
import { TrackKind } from '@livekit/rtc-ffi-bindings';
import type { TypedEventEmitter as TypedEmitter } from '@livekit/typed-emitter';
import EventEmitter from 'events';
import { ByteStreamReader, TextStreamReader } from './data_streams/stream_reader.js';
import type {
ByteStreamHandler,
ByteStreamInfo,
StreamController,
TextStreamHandler,
TextStreamInfo,
} from './data_streams/types.js';
import type { E2EEOptions } from './e2ee.js';
import { E2EEManager, defaultE2EEOptions } from './e2ee.js';
import { FfiClient, FfiClientEvent, FfiHandle } from './ffi_client.js';
import { log } from './log.js';
import type { Participant } from './participant.js';
import { LocalParticipant, RemoteParticipant } from './participant.js';
import type { LocalTrack, RemoteTrack } from './track.js';
import { RemoteAudioTrack, RemoteVideoTrack } from './track.js';
import type { LocalTrackPublication, TrackPublication } from './track_publication.js';
import { RemoteTrackPublication } from './track_publication.js';
import type { ChatMessage } from './types.js';
import { bigIntToNumber } from './utils.js';
export { RoomDataStreamOptions };
export interface RtcConfiguration {
iceTransportType: IceTransportType;
continualGatheringPolicy: ContinualGatheringPolicy;
iceServers: IceServer[];
}
export const defaultRtcConfiguration: RtcConfiguration = {
iceTransportType: IceTransportType.TRANSPORT_ALL,
continualGatheringPolicy: ContinualGatheringPolicy.GATHER_CONTINUALLY,
iceServers: [],
};
export interface RoomOptions {
autoSubscribe: boolean;
dynacast: boolean;
/**
* @deprecated Use `encryption` instead. See x for details
*/
e2ee?: E2EEOptions;
encryption?: E2EEOptions;
rtcConfig?: RtcConfiguration;
}
export const defaultRoomOptions = new FfiRoomOptions({
autoSubscribe: true,
dynacast: false,
e2ee: undefined,
encryption: undefined,
rtcConfig: undefined,
adaptiveStream: false,
joinRetries: 1,
});
export class Room extends (EventEmitter as new () => TypedEmitter<RoomCallbacks>) {
private info?: RoomInfo;
private ffiHandle?: FfiHandle;
/**
* used to ensure events are processed sequentially and allow for
* the local participant to acquire the lock while doing state updates related to FFI events
* before processing the next events
*/
private ffiEventLock = new Mutex();
private byteStreamControllers = new Map<string, StreamController<DataStream_Chunk>>();
private textStreamControllers = new Map<string, StreamController<DataStream_Chunk>>();
private byteStreamHandlers = new Map<string, ByteStreamHandler>();
private textStreamHandlers = new Map<string, TextStreamHandler>();
private preConnectEvents: FfiEvent[] = [];
// Aborted on disconnect to cancel any pending FfiClient.waitFor() listeners,
// preventing them from leaking when the room goes away.
private disconnectController = new AbortController();
// Guards cleanupOnDisconnect so the ConnectionStateChanged/Disconnected
// events fire exactly once, no matter which path (explicit disconnect()
// vs. FFI 'disconnected' event) wins the race.
private hasCleanedUp = false;
private _token?: string;
private _serverUrl?: string;
private _connectionState: ConnectionState = ConnectionState.CONN_DISCONNECTED;
e2eeManager?: E2EEManager;
remoteParticipants: Map<string, RemoteParticipant> = new Map();
localParticipant?: LocalParticipant;
constructor() {
super();
}
get connectionState() {
return this._connectionState;
}
get name(): string | undefined {
return this.info?.name;
}
get metadata(): string | undefined {
return this.info?.metadata;
}
get isConnected(): boolean {
return this.ffiHandle != undefined && this.connectionState != ConnectionState.CONN_DISCONNECTED;
}
/** @internal */
get token(): string | undefined {
return this._token;
}
/** @internal */
get serverUrl(): string | undefined {
return this._serverUrl;
}
// Shared promise for concurrent getSid() callers. Without this, each call
// registers its own RoomSidChanged + Disconnected listeners, and if many
// calls race only one of each pair is cleaned up — leaking the rest.
private sidPromise?: Promise<string>;
/**
* Gets the room's server ID. This ID is assigned by the LiveKit server
* and is unique for each room session.
* SID is assigned asynchronously after connection.
* @returns Promise that resolves to the room's server ID, or empty string if not connected
*/
async getSid(): Promise<string> {
if (!this.isConnected) {
return '';
}
if (this.info?.sid && this.info.sid !== '') {
return this.info.sid;
}
if (!this.sidPromise) {
this.sidPromise = new Promise<string>((resolve, reject) => {
const handleDisconnect = () => {
this.off(RoomEvent.RoomSidChanged, handleRoomUpdate);
this.sidPromise = undefined;
reject('Room disconnected before room server id was available');
};
const handleRoomUpdate = (sid: string) => {
if (sid !== '') {
this.off(RoomEvent.RoomSidChanged, handleRoomUpdate);
this.off(RoomEvent.Disconnected as any, handleDisconnect);
this.sidPromise = undefined;
resolve(sid);
}
};
this.on(RoomEvent.RoomSidChanged, handleRoomUpdate);
this.once(RoomEvent.Disconnected, handleDisconnect);
});
}
return this.sidPromise;
}
async getRtcStats() {
if (!this.isConnected || !this.ffiHandle) {
throw new Error('getRtcStats requires a connected room');
}
// subscribe before issuing the request
const requestId = FfiClient.instance.getNextRequestAsyncId();
const cbPromise = FfiClient.instance.waitFor<GetSessionStatsCallback>(
(ev: FfiEvent) =>
ev.message.case === 'getSessionStats' && ev.message.value.asyncId === requestId,
{ signal: this.disconnectController.signal },
);
FfiClient.instance.request<GetSessionStatsResponse>({
message: {
case: 'getSessionStats',
value: {
roomHandle: this.ffiHandle.handle,
requestAsyncId: requestId,
},
},
});
const cb = await cbPromise;
if (cb.message.case === 'error') {
throw new Error(cb.message.value);
} else if (cb.message.case === 'result') {
return cb.message.value;
} else {
throw new Error('could not retrieve rtc stats');
}
}
get numParticipants(): number {
return this.info?.numParticipants ?? 0;
}
get numPublishers(): number {
return this.info?.numPublishers ?? 0;
}
get creationTime(): Date {
// TODO: workaround for Rust SDK bug, remove after updating to:
// https://github.com/livekit/rust-sdks/pull/822
// check if creationTime looks like seconds (less than year 3000 in ms), convert to ms if needed
let creationTimeMs = Number(this.info?.creationTime ?? 0);
if (creationTimeMs > 0 && creationTimeMs < 1e12) {
creationTimeMs *= 1000;
}
return new Date(creationTimeMs);
}
get isRecording(): boolean {
return this.info?.activeRecording ?? false;
}
/**
* The time in seconds after which a room will be closed after the last
* participant has disconnected.
*/
get departureTimeout(): number {
return this.info?.departureTimeout ?? 0;
}
/**
* The time in seconds after which an empty room will be automatically closed.
*/
get emptyTimeout(): number {
return this.info?.emptyTimeout ?? 0;
}
/**
* Connects to a LiveKit room using the provided URL and access token.
* @param url - The WebSocket URL of the LiveKit server
* @param token - A valid LiveKit access token for authentication
* @param opts - Optional room configuration options
* @throws ConnectError - if connection fails
*/
async connect(url: string, token: string, opts?: RoomOptions) {
const options = { ...defaultRoomOptions, ...opts };
// The Node SDK still implements data streams in TypeScript on top of raw FFI
// packets, so always advertise only legacy (v1) data stream support to other
// clients, preserving any other data stream options provided by the user.
options.dataStream = new RoomDataStreamOptions({
...options.dataStream,
useLegacyClientImplementation: true,
});
const e2eeEnabled = options.encryption || options.e2ee;
const userE2EEOptions = options.encryption ?? options.e2ee;
const e2eeOptions: E2EEOptions = {
...defaultE2EEOptions,
...userE2EEOptions,
keyProviderOptions: {
...defaultE2EEOptions.keyProviderOptions,
...userE2EEOptions?.keyProviderOptions,
},
};
const mergedOptions = { ...options };
if (options.encryption) {
mergedOptions.encryption = e2eeOptions;
} else if (options.e2ee) {
mergedOptions.e2ee = e2eeOptions;
}
const req = new ConnectRequest({
url: url,
token: token,
options: mergedOptions,
});
FfiClient.instance.on(FfiClientEvent.FfiEvent, this.onFfiEvent);
try {
const res = FfiClient.instance.request<ConnectResponse>({
message: {
case: 'connect',
value: req,
},
});
const cb = await FfiClient.instance.waitFor<ConnectCallback>((ev: FfiEvent) => {
return ev.message.case == 'connect' && ev.message.value.asyncId == res.asyncId;
});
log.debug('Connect callback received');
switch (cb.message.case) {
case 'result':
this.ffiHandle = new FfiHandle(cb.message.value.room!.handle!.id!);
this.e2eeManager = e2eeEnabled && new E2EEManager(this.ffiHandle.handle, e2eeOptions);
this._token = token;
this._serverUrl = url;
this.info = cb.message.value.room!.info;
// Reset the abort controller for this connection session so that
// a previous disconnect doesn't immediately cancel new operations.
this.disconnectController = new AbortController();
this.hasCleanedUp = false;
this.localParticipant = new LocalParticipant(
cb.message.value.localParticipant!,
this.ffiEventLock,
this.disconnectController.signal,
);
for (const pt of cb.message.value.participants) {
const rp = this.createRemoteParticipant(pt.participant!);
for (const pub of pt.publications) {
const publication = new RemoteTrackPublication(pub);
rp.trackPublications.set(publication.sid!, publication);
}
}
this.updateConnectionState(ConnectionState.CONN_CONNECTED);
// Release the FFI room event gate after our listener and local state are ready.
FfiClient.instance.request<ReadyForRoomEventResponse>({
message: {
case: 'readyForRoomEvent',
value: {
roomHandle: this.ffiHandle.handle,
},
},
});
break;
case 'error':
default:
throw new ConnectError(cb.message.value || '');
}
} catch (e) {
FfiClient.instance.off(FfiClientEvent.FfiEvent, this.onFfiEvent);
this.preConnectEvents = [];
throw e;
}
}
/**
* Disconnects from the room and cleans up all resources.
* This will stop all tracks and close the connection.
*/
async disconnect() {
if (!this.isConnected) {
return;
}
const res = FfiClient.instance.request<DisconnectResponse>({
message: {
case: 'disconnect',
value: {
roomHandle: this.ffiHandle?.handle,
},
},
});
await FfiClient.instance.waitFor<DisconnectCallback>((ev: FfiEvent) => {
return ev.message.case == 'disconnect' && ev.message.value.asyncId == res.asyncId;
});
this.cleanupOnDisconnect(DisconnectReason.CLIENT_INITIATED);
FfiClient.instance.removeListener(FfiClientEvent.FfiEvent, this.onFfiEvent);
this.removeAllListeners();
}
/**
* Trigger a reconnection / chaos scenario for testing. Most useful in
* tests to deterministically force a Resume (signal-only reconnect that
* preserves the PeerConnection and existing publications) or a full
* reconnect (the SDK rebuilds the RtcSession and re-publishes existing
* local tracks; `RoomEvent.Reconnected` fires).
*/
async simulateScenario(scenario: SimulateScenarioKind): Promise<void> {
if (!this.isConnected || !this.ffiHandle) {
throw new Error('simulateScenario requires a connected room');
}
const res = FfiClient.instance.request<SimulateScenarioResponse>({
message: {
case: 'simulateScenario',
value: {
roomHandle: this.ffiHandle.handle,
scenario,
},
},
});
const cb = await FfiClient.instance.waitFor<SimulateScenarioCallback>(
(ev: FfiEvent) =>
ev.message.case === 'simulateScenario' && ev.message.value.asyncId === res.asyncId,
{ signal: this.disconnectController.signal },
);
if (cb.error) {
throw new Error(`simulateScenario failed: ${cb.error}`);
}
}
private updateConnectionState(newState: ConnectionState) {
if (this._connectionState === newState) {
return;
}
this._connectionState = newState;
this.emit(RoomEvent.ConnectionStateChanged, this._connectionState);
}
// Runs at most once per connection session. The FFI layer and explicit
// disconnect() both race to get here — whichever wins emits the events,
// the other is a no-op. A reconnect via connect() clears hasCleanedUp.
private cleanupOnDisconnect(reason: DisconnectReason = DisconnectReason.CLIENT_INITIATED) {
if (this.hasCleanedUp) return;
this.hasCleanedUp = true;
// Error all in-progress stream controllers to prevent FD leaks.
// Streams that were receiving data but never got a trailer (e.g. the sender
// disconnected mid-transfer) would otherwise keep their ReadableStream open
// indefinitely, leaking the underlying controller and any buffered chunks.
// Using error() instead of close() signals an abnormal termination to consumers.
for (const [, streamController] of this.byteStreamControllers) {
try {
streamController.controller.error(new Error('Disconnected while receiving'));
} catch {
// controller may already be closed or errored
}
}
this.byteStreamControllers.clear();
for (const [, streamController] of this.textStreamControllers) {
try {
streamController.controller.error(new Error('Disconnected while receiving'));
} catch {
// controller may already be closed or errored
}
}
this.textStreamControllers.clear();
// Detach every track from this room so attached FrameProcessors receive
// onStreamInfoCleared/onCredentialsCleared and the tokenRefreshed listener
// is removed. Otherwise a server-initiated disconnect leaves processors with
// stale room context and the Room holding a strong ref to each Track's bound
// listener until GC. setRoom(null) is idempotent, so this is safe even if a
// track was already detached (e.g. via unsubscribe/unpublish).
if (this.localParticipant) {
for (const pub of this.localParticipant.trackPublications.values()) {
pub.track?.setRoom(null);
}
}
for (const participant of this.remoteParticipants.values()) {
for (const pub of participant.trackPublications.values()) {
pub.track?.setRoom(null);
}
}
// Clear sidPromise before removing listeners so that a reconnect
// doesn't return a stale, permanently-pending promise.
this.sidPromise = undefined;
// Abort all pending FfiClient.waitFor() listeners so they don't leak.
// This causes any in-flight operations (publishData, publishTrack, etc.)
// to reject and clean up their event listeners.
this.disconnectController.abort();
this.updateConnectionState(ConnectionState.CONN_DISCONNECTED);
this.emit(RoomEvent.Disconnected, reason);
}
/**
* Registers a handler for incoming text data streams on a specific topic.
* Text streams are used for receiving structured text data from other participants.
* @param topic - The topic to listen for text streams on
* @param callback - Function to handle incoming text stream data
* @throws Error - if a handler for this topic is already registered
*/
registerTextStreamHandler(topic: string, callback: TextStreamHandler) {
if (this.textStreamHandlers.has(topic)) {
throw new Error(`A text stream handler for topic "${topic}" has already been set.`);
}
this.textStreamHandlers.set(topic, callback);
}
unregisterTextStreamHandler(topic: string) {
this.textStreamHandlers.delete(topic);
}
/**
* Registers a handler for incoming byte data streams on a specific topic.
* Byte streams are used for receiving binary data like files from other participants.
* @param topic - The topic to listen for byte streams on
* @param callback - Function to handle incoming byte stream data
* @throws Error - if a handler for this topic is already registered
*/
registerByteStreamHandler(topic: string, callback: ByteStreamHandler) {
if (this.byteStreamHandlers.has(topic)) {
throw new Error(`A byte stream handler for topic "${topic}" has already been set.`);
}
this.byteStreamHandlers.set(topic, callback);
}
unregisterByteStreamHandler(topic: string) {
this.byteStreamHandlers.delete(topic);
}
private onFfiEvent = async (ffiEvent: FfiEvent) => {
const unlock = await this.ffiEventLock.lock();
try {
if (!this.localParticipant || !this.ffiHandle || !this.info) {
this.preConnectEvents.push(ffiEvent);
return;
}
// process preConnectEvents if we received the connectCallback after the events were queued
for (const ev of this.preConnectEvents) {
await this.processFfiEvent(ev);
}
this.preConnectEvents = [];
await this.processFfiEvent(ffiEvent);
} finally {
unlock();
}
};
private processFfiEvent = async (ffiEvent: FfiEvent) => {
if (!this.localParticipant || !this.ffiHandle || !this.info) {
throw new Error('processFfiEvent called before connect');
}
if (ffiEvent.message.case == 'rpcMethodInvocation') {
if (
ffiEvent.message.value.localParticipantHandle == this.localParticipant.ffi_handle.handle
) {
this.localParticipant.handleRpcMethodInvocation(
ffiEvent.message.value.invocationId!,
ffiEvent.message.value.method!,
ffiEvent.message.value.requestId!,
ffiEvent.message.value.callerIdentity!,
ffiEvent.message.value.payload!,
ffiEvent.message.value.responseTimeoutMs!,
);
}
return;
} else if (
ffiEvent.message.case != 'roomEvent' ||
ffiEvent.message.value.roomHandle != this.ffiHandle.handle
) {
return;
}
const ev = ffiEvent.message.value.message;
if (process.env.LIVEKIT_DEBUG_LOG_ROOM_EVENTS) {
console.log('Room event:', ev);
}
if (ev.case == 'participantConnected') {
const participant = this.createRemoteParticipant(ev.value.info!);
this.remoteParticipants.set(participant.identity!, participant);
this.emit(RoomEvent.ParticipantConnected, participant);
} else if (ev.case == 'participantDisconnected') {
const participant = this.remoteParticipants.get(ev.value.participantIdentity!);
if (participant) {
this.remoteParticipants.delete(participant.identity);
participant.info.disconnectReason = ev.value.disconnectReason;
this.emit(RoomEvent.ParticipantDisconnected, participant);
} else {
log.warn(`RoomEvent.ParticipantDisconnected: Could not find participant`);
}
} else if (ev.case == 'localTrackPublished') {
const publication = this.localParticipant.trackPublications.get(ev.value.trackSid!);
if (publication?.track) {
publication.track.setRoom(this);
}
this.emit(RoomEvent.LocalTrackPublished, publication!, this.localParticipant);
} else if (ev.case == 'localTrackUnpublished') {
const publication = this.localParticipant.trackPublications.get(ev.value.publicationSid!);
const track = publication?.track;
if (track) {
track.setRoom(null);
}
this.localParticipant.trackPublications.delete(ev.value.publicationSid!);
// Emit while `publication.track` is still set, preserving the pre-existing
// payload for callbacks. The handler is synchronous, so nulling the track
// right after still completes before any other turn can observe it.
this.emit(RoomEvent.LocalTrackUnpublished, publication!, this.localParticipant!);
// Mirror trackUnsubscribed: drop the publication's track reference. This
// also makes unpublishTrack's own setRoom(null) a no-op when it loses the
// race (its `pub.track` guard short-circuits), avoiding a redundant clear.
if (track && publication) {
publication.track = undefined;
}
} else if ((ev.case as string) == 'localTrackRepublished') {
const value = (ev as any).value;
const previousSid: string = value.previousSid!;
const newInfo: TrackPublicationInfo = value.info!;
const publication = this.localParticipant.trackPublications.get(previousSid);
if (publication) {
publication.updateInfo(newInfo);
this.localParticipant.trackPublications.delete(previousSid);
this.localParticipant.trackPublications.set(publication.sid!, publication);
if (publication.track?.info) {
// Keep the local-track invariant (track.sid == publication.sid, set at
// publishTrack) intact across republish, then re-push metadata so any
// attached FrameProcessor learns the new publication SID / credentials.
// setRoom with the same room is a no-op for the tokenRefreshed listener
// but re-fans the metadata to every registered AudioStream.
publication.track.info.sid = publication.sid;
publication.track.setRoom(this);
}
this.emit(RoomEvent.LocalTrackRepublished, publication, previousSid, this.localParticipant);
} else {
log.warn(`RoomEvent.LocalTrackRepublished: previous publication not found: ${previousSid}`);
}
} else if (ev.case == 'localTrackSubscribed') {
const publication = this.localParticipant.trackPublications.get(ev.value.trackSid!);
if (publication) {
publication.resolveFirstSubscription();
this.emit(RoomEvent.LocalTrackSubscribed, publication!.track!);
} else {
log.warn(`RoomEvent.LocalTrackSubscribed: Publication not found: ${ev.value.trackSid}`);
}
} else if (ev.case == 'trackPublished') {
const participant = this.remoteParticipants.get(ev.value.participantIdentity!);
const publication = new RemoteTrackPublication(ev.value.publication!);
if (participant) {
participant.trackPublications.set(publication.sid!, publication);
} else {
log.warn(
`RoomEvent.TrackPublished: Could not find participant: ${ev.value.participantIdentity}`,
);
}
this.emit(RoomEvent.TrackPublished, publication, participant!);
} else if (ev.case == 'trackUnpublished') {
const participant = this.requireRemoteParticipant(ev.value.participantIdentity!);
const publication = participant.trackPublications.get(ev.value.publicationSid!);
participant.trackPublications.delete(ev.value.publicationSid!);
if (publication) {
this.emit(RoomEvent.TrackUnpublished, publication, participant);
// Dispose eagerly so handles don't accumulate when a participant
// publishes and unpublishes many tracks during a long-lived session.
publication.ffiHandle.dispose();
} else {
log.warn(`RoomEvent.TrackUnpublished: Could not find publication`);
}
} else if (ev.case == 'trackSubscribed') {
const ownedTrack = ev.value.track!;
const trackInfo = ownedTrack.info!;
try {
const { participant, publication } = this.requirePublicationOfRemoteParticipant(
ev.value.participantIdentity!,
trackInfo.sid!,
);
publication.subscribed = true;
if (trackInfo.kind == TrackKind.KIND_VIDEO) {
publication.track = new RemoteVideoTrack(ownedTrack);
} else if (trackInfo.kind == TrackKind.KIND_AUDIO) {
publication.track = new RemoteAudioTrack(ownedTrack);
}
publication.track?.setRoom(this);
this.emit(RoomEvent.TrackSubscribed, publication.track!, publication, participant);
} catch (e: unknown) {
log.warn(`RoomEvent.TrackSubscribed: ${(e as Error).message}`);
}
} else if (ev.case == 'trackUnsubscribed') {
try {
const { participant, publication } = this.requirePublicationOfRemoteParticipant(
ev.value.participantIdentity!,
ev.value.trackSid!,
);
const track = publication.track!;
track.setRoom(null);
publication.track = undefined;
publication.subscribed = false;
this.emit(RoomEvent.TrackUnsubscribed, track, publication, participant);
// An unsubscribed track never gets an `eos`, so any AudioStream on it
// keeps delivering frames. Tear them down here — after the event, so
// handlers still see a live track.
track.closeAudioStreams();
} catch (e: unknown) {
log.warn(`RoomEvent.TrackUnsubscribed: ${(e as Error).message}`);
}
} else if (ev.case == 'trackSubscriptionFailed') {
try {
const participant = this.requireRemoteParticipant(ev.value.participantIdentity!);
this.emit(
RoomEvent.TrackSubscriptionFailed,
ev.value.trackSid!,
participant,
ev.value.error,
);
} catch (e: unknown) {
log.warn(`RoomEvent.TrackSubscriptionFailed: ${(e as Error).message}`);
}
} else if (ev.case == 'trackMuted') {
try {
const { participant, publication } = this.requirePublicationOfParticipant(
ev.value.participantIdentity!,
ev.value.trackSid!,
);
publication.info!.muted = true;
if (publication.track) {
publication.track.info!.muted = true;
}
this.emit(RoomEvent.TrackMuted, publication, participant);
} catch (e: unknown) {
log.warn(`RoomEvent.TrackMuted: ${(e as Error).message}`);
}
} else if (ev.case == 'trackUnmuted') {
try {
const { participant, publication } = this.requirePublicationOfParticipant(
ev.value.participantIdentity!,
ev.value.trackSid!,
);
publication.info!.muted = false;
if (publication.track) {
publication.track.info!.muted = false;
}
this.emit(RoomEvent.TrackUnmuted, publication, participant);
} catch (e: unknown) {
log.warn(`RoomEvent.TrackUnmuted: ${(e as Error).message}`);
}
} else if (ev.case == 'activeSpeakersChanged') {
try {
const activeSpeakers = ev.value.participantIdentities.map((identity) =>
this.requireParticipantByIdentity(identity),
);
this.emit(RoomEvent.ActiveSpeakersChanged, activeSpeakers);
} catch (e: unknown) {
log.warn(`RoomEvent.ActiveSpeakersChanged: ${(e as Error).message}`);
}
} else if (ev.case == 'roomMetadataChanged') {
this.info.metadata = ev.value.metadata ?? '';
this.emit(RoomEvent.RoomMetadataChanged, this.info.metadata);
} else if (ev.case == 'participantMetadataChanged') {
try {
const participant = this.requireParticipantByIdentity(ev.value.participantIdentity!);
participant.info.metadata = ev.value.metadata;
this.emit(RoomEvent.ParticipantMetadataChanged, participant.metadata, participant);
} catch (e: unknown) {
log.warn(`RoomEvent.ParticipantMetadataChanged: ${(e as Error).message}`);
}
} else if (ev.case == 'participantNameChanged') {
try {
const participant = this.requireParticipantByIdentity(ev.value.participantIdentity!);
participant.info.name = ev.value.name;
this.emit(RoomEvent.ParticipantNameChanged, participant.name!, participant);
} catch (e: unknown) {
log.warn(`RoomEvent.ParticipantNameChanged: ${(e as Error).message}`);
}
} else if (ev.case == 'participantAttributesChanged') {
try {
const participant = this.requireParticipantByIdentity(ev.value.participantIdentity!);
participant.info.attributes = ev.value.attributes.reduce(
(acc, value) => {
acc[value.key!] = value.value!;
return acc;
},
{} as Record<string, string>,
);
if (Object.keys(ev.value.changedAttributes).length > 0) {
const changedAttributes = ev.value.changedAttributes.reduce(
(acc, value) => {
acc[value.key!] = value.value!;
return acc;
},
{} as Record<string, string>,
);
this.emit(RoomEvent.ParticipantAttributesChanged, changedAttributes, participant);
}
} catch (e: unknown) {
log.warn(`RoomEvent.ParticipantAttributesChanged: ${(e as Error).message}`);
}
} else if (ev.case == 'connectionQualityChanged') {
try {
const participant = this.requireParticipantByIdentity(ev.value.participantIdentity!);
this.emit(RoomEvent.ConnectionQualityChanged, ev.value.quality!, participant);
} catch (e: unknown) {
log.warn(`RoomEvent.ConnectionQualityChanged: ${(e as Error).message}`);
}
} else if (ev.case == 'chatMessage') {
const participant = this.retrieveParticipantByIdentity(ev.value.participantIdentity!);
const { id, message: messageText, timestamp, editTimestamp, generated } = ev.value.message!;
const message: ChatMessage = {
id: id!,
message: messageText!,
timestamp: Number(timestamp),
editTimestamp: Number(editTimestamp),
generated,
};
this.emit(RoomEvent.ChatMessage, message, participant);
} else if (ev.case == 'dataPacketReceived') {
// Can be undefined if the data is sent from a Server SDK
const participant = this.remoteParticipants.get(ev.value.participantIdentity!);
const dataPacket = ev.value.value;
switch (dataPacket.case) {
case 'user':
const buffer = FfiClient.instance.copyBuffer(
dataPacket.value.data!.data!.dataPtr!,
Number(dataPacket.value.data!.data!.dataLen),
);
new FfiHandle(dataPacket.value.data!.handle!.id!).dispose();
this.emit(
RoomEvent.DataReceived,
buffer,
participant,
ev.value.kind,
dataPacket.value.topic,
);
break;
case 'sipDtmf':
const { code, digit } = dataPacket.value;
this.emit(RoomEvent.DtmfReceived, code!, digit!, participant!);
break;
default:
break;
}
} else if (ev.case == 'e2eeStateChanged') {
if (ev.value.state == EncryptionState.INTERNAL_ERROR) {
// throw generic error until Rust SDK is updated to supply the error alongside INTERNAL_ERROR
this.emit(RoomEvent.EncryptionError, new Error('internal server error'));
}
} else if (ev.case == 'connectionStateChanged') {
this.updateConnectionState(ev.value.state!);
/*} else if (ev.case == 'connected') {
this.emit(RoomEvent.Connected);*/
} else if (ev.case == 'disconnected') {
// cleanupOnDisconnect emits RoomEvent.Disconnected itself (guarded by
// hasCleanedUp so it fires exactly once across both disconnect paths).
this.cleanupOnDisconnect(ev.value.reason!);
} else if (ev.case == 'reconnecting') {
this.emit(RoomEvent.Reconnecting);
} else if (ev.case == 'reconnected') {
this.emit(RoomEvent.Reconnected);
} else if (ev.case == 'roomSidChanged') {
this.emit(RoomEvent.RoomSidChanged, ev.value.sid!);
} else if (ev.case === 'streamHeaderReceived' && ev.value.header) {
this.handleStreamHeader(ev.value.header, ev.value.participantIdentity!);
} else if (ev.case === 'streamChunkReceived' && ev.value.chunk) {
this.handleStreamChunk(ev.value.chunk);
} else if (ev.case === 'streamTrailerReceived' && ev.value.trailer) {
this.handleStreamTrailer(ev.value.trailer);
} else if (ev.case === 'roomUpdated') {
this.info = ev.value;
this.emit(RoomEvent.RoomUpdated);
} else if (ev.case === 'moved') {
this.info = ev.value;
this.emit(RoomEvent.Moved);
} else if (ev.case === 'participantsUpdated') {
for (const info of ev.value.participants) {
const participant = this.retrieveParticipantByIdentity(info.identity!);
if (participant) {
participant.info = info;
}
}
} else if (ev.case === 'participantEncryptionStatusChanged') {
try {
const participant = this.requireParticipantByIdentity(ev.value.participantIdentity!);
this.emit(
RoomEvent.ParticipantEncryptionStatusChanged,
!!ev.value.isEncrypted,
participant,
);
} catch (e: unknown) {
log.warn(`RoomEvent.ParticipantEncryptionStatusChanged: ${(e as Error).message}`);
}
} else if (ev.case === 'tokenRefreshed') {
this._token = ev.value.token;
this.emit('tokenRefreshed');
}
};
private retrieveParticipantByIdentity(identity: string): Participant | undefined {
if (this.localParticipant?.identity === identity) {
return this.localParticipant;
} else {
return this.remoteParticipants.get(identity);
}
}
private requireParticipantByIdentity(identity: string): Participant {
if (this.localParticipant?.identity === identity) {
return this.localParticipant;
} else if (this.remoteParticipants.has(identity)) {
return this.remoteParticipants.get(identity)!;
} else {
throw new TypeError(`participant ${identity} not found`);
}
}
private requireRemoteParticipant(identity: string) {
const participant = this.remoteParticipants.get(identity);
if (!participant) {
throw new TypeError(`participant ${identity} not found`);
}
return participant;
}
private requirePublicationOfParticipant(identity: string, trackSid: string) {
const participant = this.requireParticipantByIdentity(identity);
const publication = participant.trackPublications.get(trackSid);
if (!publication) {
throw new TypeError(`publication ${trackSid} not found`);
}
return { participant, publication };
}
private requirePublicationOfRemoteParticipant(identity: string, trackSid: string) {
const participant = this.requireRemoteParticipant(identity);
const publication = participant.trackPublications.get(trackSid);
if (!publication) {
throw new TypeError(`publication ${trackSid} not found`);
}
return { participant, publication };
}
private createRemoteParticipant(ownedInfo: OwnedParticipant) {
if (this.remoteParticipants.has(ownedInfo.info!.identity!)) {
throw new Error('Participant already exists');
}
const participant = new RemoteParticipant(ownedInfo);
this.remoteParticipants.set(ownedInfo.info!.identity!, participant);
return participant;
}
private handleStreamHeader(streamHeader: DataStream_Header, participantIdentity: string) {
if (streamHeader.contentHeader.case === 'byteHeader') {
const streamHandlerCallback = this.byteStreamHandlers.get(streamHeader.topic ?? '');
if (!streamHandlerCallback) {
log.debug(
'ignoring incoming byte stream due to no handler for topic: %s',
streamHeader.topic ?? 'undefined',
);
return;
}
let streamController: ReadableStreamDefaultController<DataStream_Chunk>;
const stream = new ReadableStream({
start: (controller) => {
streamController = controller;
this.byteStreamControllers.set(streamHeader.streamId!, {
header: streamHeader,
controller: streamController,
startTime: Date.now(),
});
},
});
const info: ByteStreamInfo = {
streamId: streamHeader.streamId!,
name: streamHeader.contentHeader.value.name ?? 'unknown',
mimeType: streamHeader.mimeType!,
totalSize: streamHeader.totalLength ? Number(streamHeader.totalLength) : undefined,
topic: streamHeader.topic!,
timestamp: bigIntToNumber(streamHeader.timestamp!),
attributes: streamHeader.attributes,
};
streamHandlerCallback(
new ByteStreamReader(info, stream, bigIntToNumber(streamHeader.totalLength)),
{ identity: participantIdentity },
);
} else if (streamHeader.contentHeader.case === 'textHeader') {
const streamHandlerCallback = this.textStreamHandlers.get(streamHeader.topic ?? '');
if (!streamHandlerCallback) {
log.debug(
'ignoring incoming text stream due to no handler for topic: %s',
streamHeader.topic ?? 'undefined',
);
return;