-
Notifications
You must be signed in to change notification settings - Fork 232
Expand file tree
/
Copy pathroom.dart
More file actions
1543 lines (1359 loc) · 54.2 KB
/
room.dart
File metadata and controls
1543 lines (1359 loc) · 54.2 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
// Copyright 2024 LiveKit, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'dart:async';
import 'dart:typed_data' show Uint8List;
import 'package:collection/collection.dart';
import 'package:http/http.dart' as http;
import 'package:meta/meta.dart';
import '../core/signal_client.dart';
import '../data_stream/errors.dart';
import '../data_stream/stream_reader.dart';
import '../e2ee/e2ee_manager.dart';
import '../e2ee/options.dart';
import '../events.dart';
import '../exceptions.dart';
import '../extensions.dart';
import '../hardware/hardware.dart';
import '../internal/events.dart';
import '../logger.dart';
import '../managers/event.dart';
import '../options.dart';
import '../participant/local.dart';
import '../participant/participant.dart';
import '../participant/remote.dart';
import '../preconnect/pre_connect_audio_buffer.dart';
import '../proto/livekit_models.pb.dart' as lk_models;
import '../proto/livekit_rtc.pb.dart' as lk_rtc;
import '../support/disposable.dart';
import '../support/platform.dart';
import '../support/region_url_provider.dart';
import '../support/websocket.dart' show WebSocketException;
import '../track/audio_management.dart';
import '../track/local/audio.dart';
import '../track/local/video.dart';
import '../track/track.dart';
import '../track/web/_audio_api.dart' if (dart.library.js_interop) '../track/web/_audio_html.dart' as audio;
import '../types/data_stream.dart';
import '../types/other.dart';
import '../types/rpc.dart';
import '../types/transcription_segment.dart';
import '../utils.dart' show isSVCCodec, unpackStreamId;
import 'engine.dart';
import 'participant_collection.dart';
import 'pending_track_queue.dart';
/// Room is the primary construct for LiveKit conferences. It contains a
/// group of [Participant]s, each publishing and subscribing to [Track]s.
/// Notifies changes to its state via two ways, by assigning a delegate, or using
/// it as a provider.
/// Room will trigger a change notification update when
/// * state changes
/// * participant membership changes
/// * active speakers are different
/// {@category Room}
class Room extends DisposableChangeNotifier with EventsEmittable<RoomEvent> {
// expose engine's params
/// connection state of the room
ConnectionState get connectionState => engine.connectionState;
ConnectOptions get connectOptions => engine.connectOptions;
RoomOptions get roomOptions => engine.roomOptions;
final ParticipantCollection<RemoteParticipant> _remoteParticipants = ParticipantCollection();
UnmodifiableMapView<String, RemoteParticipant> get remoteParticipants =>
UnmodifiableMapView(_remoteParticipants.byIdentity);
/// the current participant
LocalParticipant? get localParticipant => _localParticipant;
LocalParticipant? _localParticipant;
/// name of the room
String? get name => _name;
String? _name;
/// metadata of the room
String? get metadata => _metadata;
String? _metadata;
/// Server version
String? get serverVersion => _serverVersion;
String? _serverVersion;
/// Server region
String? get serverRegion => _serverRegion;
String? _serverRegion;
E2EEManager? get e2eeManager => _e2eeManager;
E2EEManager? _e2eeManager;
bool get isRecording => _isRecording;
bool _isRecording = false;
bool _audioEnabled = true;
lk_models.Room? _roomInfo;
/// a list of participants that are actively speaking, including local participant.
UnmodifiableListView<Participant> get activeSpeakers => UnmodifiableListView<Participant>(_activeSpeakers);
List<Participant> _activeSpeakers = [];
@internal
final Engine engine;
// suppport for multiple event listeners
late final EventsListener<EngineEvent> _engineListener;
//
late EventsListener<SignalEvent> _signalListener;
RegionUrlProvider? _regionUrlProvider;
String? _regionUrl;
// Agents
final Map<String, DateTime> _transcriptionReceivedTimes = {};
// RPC Handlers
final Map<String, RpcRequestHandler> _rpcHandlers = {};
final Map<String, DataStreamController<lk_models.DataStream_Chunk>> _byteStreamControllers = {};
final Map<String, DataStreamController<lk_models.DataStream_Chunk>> _textStreamControllers = {};
final Map<String, ByteStreamHandler> _byteStreamHandlers = {};
final Map<String, TextStreamHandler> _textStreamHandlers = {};
@internal
late final PreConnectAudioBuffer preConnectAudioBuffer;
// Pending subscriber tracks keyed by participantSid, for tracks arriving before metadata or before the room connected.
late final PendingTrackQueue _pendingTrackQueue;
// for testing
@internal
Map<String, RpcRequestHandler> get rpcHandlers => _rpcHandlers;
@internal
Map<String, TextStreamHandler> get textStreamHandlers => _textStreamHandlers;
@internal
Map<String, ByteStreamHandler> get byteStreamHandlers => _byteStreamHandlers;
Room({
@Deprecated('deprecated, please use connectOptions in room.connect()')
ConnectOptions connectOptions = const ConnectOptions(),
RoomOptions roomOptions = const RoomOptions(),
Engine? engine,
}) : engine = engine ??
Engine(
connectOptions: connectOptions,
roomOptions: roomOptions,
) {
//
_engineListener = this.engine.createListener();
_setUpEngineListeners();
_signalListener = this.engine.signalClient.createListener();
_setUpSignalListeners();
_pendingTrackQueue = PendingTrackQueue(
ttl: this.engine.connectOptions.timeouts.subscribe,
emitException: (event) => events.emit(event),
);
// Any event emitted will trigger ChangeNotifier
events.listen((event) {
logger.finer('[RoomEvent] $event, will notifyListeners()');
notifyListeners();
});
// Keep a connected flush as a fallback in case tracks arrive pre-connected but before metadata.
events.on<RoomConnectedEvent>((event) => _flushPendingTracks());
_setupRpcListeners();
_setupDataStreamListeners();
preConnectAudioBuffer = PreConnectAudioBuffer(this);
onDispose(() async {
// clean up routine
await _cleanUp();
// dispose preConnectAudioBuffer
await preConnectAudioBuffer.dispose();
// dispose events
await events.dispose();
// dispose local participant
await localParticipant?.dispose();
// dispose all listeners for SignalClient
await _signalListener.dispose();
// dispose all listeners for Engine
await _engineListener.dispose();
// dispose the engine
await this.engine.dispose();
});
}
/// prepareConnection should be called as soon as the page is loaded, in order
/// to speed up the connection attempt. This function will
/// - perform DNS resolution and pre-warm the DNS cache
/// - establish TLS connection and cache TLS keys
///
/// With LiveKit Cloud, it will also determine the best edge data center for
/// the current client to connect to if a token is provided.
Future<void> prepareConnection(String url, String? token) async {
if (engine.connectionState != ConnectionState.disconnected) {
return;
}
logger.info('prepareConnection to $url');
try {
if (isCloudUrl(Uri.parse(url)) && token != null) {
_regionUrlProvider = RegionUrlProvider(token: token, url: url);
final regionUrl = await _regionUrlProvider!.getNextBestRegionUrl();
// we will not replace the regionUrl if an attempt had already started
// to avoid overriding regionUrl after a new connection attempt had started
if (regionUrl != null && connectionState == ConnectionState.disconnected) {
_regionUrl = regionUrl;
await http.head(Uri.parse(toHttpUrl(regionUrl)));
logger.fine('prepared connection to ${regionUrl}');
}
} else {
await http.head(Uri.parse(toHttpUrl(url)));
}
} catch (e) {
logger.warning('could not prepare connection');
}
}
Future<void> connect(
String url,
String token, {
ConnectOptions? connectOptions,
@Deprecated('deprecated, please use roomOptions in Room constructor') RoomOptions? roomOptions,
FastConnectOptions? fastConnectOptions,
}) async {
var roomOptions = this.roomOptions;
connectOptions ??= ConnectOptions();
_pendingTrackQueue.updateTtl(connectOptions.timeouts.subscribe);
// ignore: deprecated_member_use_from_same_package
if ((roomOptions.encryption != null || roomOptions.e2eeOptions != null) && engine.e2eeManager == null) {
if (!lkPlatformSupportsE2EE()) {
throw LiveKitE2EEException('E2EE is not supported on this platform');
}
// ignore: deprecated_member_use_from_same_package
final e2eeOptions = roomOptions.encryption ?? roomOptions.e2eeOptions;
_e2eeManager = E2EEManager(
options: e2eeOptions!,
dcEncryptionEnabled: roomOptions.encryption != null,
);
await _e2eeManager!.setup(this);
engine.setE2eeManager(_e2eeManager);
} else {
_e2eeManager = engine.e2eeManager;
}
if (_e2eeManager != null) {
// Disable backup codec when e2ee is enabled
roomOptions = roomOptions.copyWith(
defaultVideoPublishOptions: roomOptions.defaultVideoPublishOptions.copyWith(
backupVideoCodec: const BackupVideoCodec(enabled: false),
),
);
}
if (_regionUrlProvider?.getServerUrl().toString() != url) {
_regionUrl = null;
_regionUrlProvider = null;
}
if (isCloudUrl(Uri.parse(url))) {
if (_regionUrlProvider == null) {
_regionUrlProvider = RegionUrlProvider(url: url, token: token);
} else {
_regionUrlProvider?.updateToken(token);
}
// trigger the first fetch without waiting for a response
// if initial connection fails, this will speed up picking regional url
// on subsequent runs
unawaited(_regionUrlProvider?.fetchRegionSettings().then((settings) {
_regionUrlProvider?.setServerReportedRegions(settings);
}).catchError((e) {
logger.warning('could not fetch region settings $e');
}));
}
// configure audio for native platform
await NativeAudioManagement.start();
try {
await engine.connect(
_regionUrl ?? url,
token,
connectOptions: connectOptions,
roomOptions: roomOptions,
fastConnectOptions: fastConnectOptions,
regionUrlProvider: _regionUrlProvider,
);
} catch (e) {
logger.warning('could not connect to $url $e');
if (_regionUrlProvider != null &&
(e is WebSocketException || (e is ConnectException && e.reason != ConnectionErrorReason.NotAllowed))) {
String? nextUrl;
try {
nextUrl = await _regionUrlProvider!.getNextBestRegionUrl();
} catch (error) {
if (error is ConnectException && (error.statusCode == 401)) {
rethrow;
}
}
if (nextUrl != null) {
logger.fine('Initial connection failed with ConnectionError: $e. Retrying with another region: ${nextUrl}');
await engine.connect(
nextUrl,
token,
connectOptions: connectOptions,
roomOptions: roomOptions,
fastConnectOptions: fastConnectOptions,
regionUrlProvider: _regionUrlProvider,
);
} else {
rethrow;
}
} else {
rethrow;
}
}
}
void _setUpSignalListeners() => _signalListener
..on<SignalParticipantUpdateEvent>((event) => _onParticipantUpdateEvent(event.participants))
..on<SignalSpeakersChangedEvent>((event) => _onSignalSpeakersChangedEvent(event.speakers))
..on<SignalConnectionQualityUpdateEvent>((event) => _onSignalConnectionQualityUpdateEvent(event.updates))
..on<SignalStreamStateUpdatedEvent>((event) => _onSignalStreamStateUpdateEvent(event.updates))
..on<SignalSubscribedQualityUpdatedEvent>((event) async {
// Dynacast is off or is unsupported
if (!roomOptions.dynacast || _serverVersion == '0.15.1') {
logger.fine('Received subscribed quality update'
' but Dynacast is off or server version is not supported.');
return;
}
// Find the publication
final publication = localParticipant?.trackPublications[event.trackSid];
if (publication == null) {
logger.warning('Received subscribed quality update for unknown track (${event.trackSid})');
return;
}
if (event.subscribedCodecs.isNotEmpty) {
if (publication.track! is! LocalVideoTrack) {
return;
}
final videoTrack = publication.track as LocalVideoTrack;
final newCodecs = await videoTrack.setPublishingCodecs(event.subscribedCodecs, videoTrack);
for (var codec in newCodecs) {
if (isBackupCodec(codec)) {
logger.info('publishing backup codec ${codec} for ${publication.track?.sid}');
await localParticipant?.publishAdditionalCodecForPublication(publication, codec);
}
}
} else if (event.subscribedQualities.isNotEmpty) {
final videoTrack = publication.track as LocalVideoTrack;
await videoTrack.setPublishingLayers(videoTrack, event.subscribedQualities,
isSVC: isSVCCodec(videoTrack.codec ?? ''));
}
})
..on<SignalSubscriptionPermissionUpdateEvent>((event) async {
logger.fine('SignalSubscriptionPermissionUpdateEvent '
'participantSid:${event.participantSid} '
'trackSid:${event.trackSid} '
'allowed:${event.allowed}');
// find participant
final participant = _remoteParticipants.bySid[event.participantSid];
if (participant == null) {
return;
}
// find track
final publication = participant.getTrackPublicationBySid(event.trackSid);
if (publication == null) {
return;
}
//
await publication.updateSubscriptionAllowed(event.allowed);
emitWhenConnected(TrackSubscriptionPermissionChangedEvent(
participant: participant,
publication: publication,
state: publication.subscriptionState,
));
})
..on<SignalRoomUpdateEvent>((event) async => _applyRoomUpdate(event.room))
..on<SignalRemoteMuteTrackEvent>((event) async {
final publication = localParticipant?.trackPublications[event.sid];
final stopOnMute = switch (publication?.source) {
TrackSource.camera => roomOptions.defaultCameraCaptureOptions.stopCameraCaptureOnMute,
TrackSource.microphone => roomOptions.defaultAudioCaptureOptions.stopAudioCaptureOnMute,
_ => true,
};
if (event.muted) {
await publication?.mute(stopOnMute: stopOnMute);
} else {
await publication?.unmute(stopOnMute: stopOnMute);
}
})
..on<SignalTrackUnpublishedEvent>((event) async {
// unpublish local track
await localParticipant?.removePublishedTrack(event.trackSid);
});
void _setUpEngineListeners() => _engineListener
..on<EngineJoinResponseEvent>((event) async {
_applyRoomUpdate(event.response.room);
_serverVersion = event.response.serverVersion;
_serverRegion = event.response.serverRegion;
logger.fine('[Engine] Received JoinResponse, '
'serverVersion: ${event.response.serverVersion}');
_localParticipant ??= await LocalParticipant.createFromInfo(
room: this,
info: event.response.participant,
);
if (engine.fullReconnectOnNext) {
await _localParticipant!.updateFromInfo(event.response.participant);
}
// Check if preconnect buffer is recording and publish its track
if (preConnectAudioBuffer.isRecording && preConnectAudioBuffer.localTrack != null) {
logger.info('Publishing preconnect audio track');
await _localParticipant!.publishAudioTrack(
preConnectAudioBuffer.localTrack!,
publishOptions: roomOptions.defaultAudioPublishOptions.copyWith(preConnect: true),
);
}
if (connectOptions.protocolVersion.index >= ProtocolVersion.v8.index &&
engine.fastConnectOptions != null &&
!engine.fullReconnectOnNext) {
final options = engine.fastConnectOptions!;
final audio = options.microphone;
final bool audioEnabled = audio.enabled == true || audio.track != null;
// Only enable microphone if preconnect buffer is not active
if (audioEnabled && !preConnectAudioBuffer.isRecording) {
if (audio.track != null) {
await _localParticipant!.publishAudioTrack(audio.track as LocalAudioTrack,
publishOptions: roomOptions.defaultAudioPublishOptions);
} else {
await _localParticipant!
.setMicrophoneEnabled(true, audioCaptureOptions: roomOptions.defaultAudioCaptureOptions);
}
}
final video = options.camera;
final bool videoEnabled = video.enabled == true || video.track != null;
if (videoEnabled) {
if (video.track != null) {
await _localParticipant!.publishVideoTrack(video.track as LocalVideoTrack,
publishOptions: roomOptions.defaultVideoPublishOptions);
} else {
await _localParticipant!
.setCameraEnabled(true, cameraCaptureOptions: roomOptions.defaultCameraCaptureOptions);
}
}
final screen = options.screen;
final bool screenEnabled = screen.enabled == true || screen.track != null;
if (screenEnabled) {
if (screen.track != null) {
await _localParticipant!.publishVideoTrack(screen.track as LocalVideoTrack,
publishOptions: roomOptions.defaultVideoPublishOptions);
} else {
await _localParticipant!
.setScreenShareEnabled(true, screenShareCaptureOptions: roomOptions.defaultScreenShareCaptureOptions);
}
}
}
for (final info in event.response.otherParticipants) {
logger.fine('Creating RemoteParticipant: sid = ${info.sid}(identity:${info.identity}) '
'tracks:${info.tracks.map((e) => e.sid)}');
await _getOrCreateRemoteParticipant(info);
}
if (e2eeManager != null && event.response.sifTrailer.isNotEmpty) {
await e2eeManager!.keyProvider.setSifTrailer(Uint8List.fromList(event.response.sifTrailer));
}
logger.fine('Room Connect completed');
events.emit(RoomConnectedEvent(room: this, metadata: _metadata));
})
..on<EngineResumedEvent>((event) async {
// re-send tracks permissions
localParticipant?.sendTrackSubscriptionPermissions();
events.emit(const RoomReconnectedEvent());
notifyListeners();
})
..on<EngineFullRestartingEvent>((event) async {
events.emit(const RoomReconnectingEvent());
// reset params
_name = null;
_metadata = null;
_serverVersion = null;
_serverRegion = null;
final participants = _remoteParticipants.toList();
_remoteParticipants.clear();
_activeSpeakers.clear();
for (final participant in participants) {
events.emit(ParticipantDisconnectedEvent(participant: participant));
await participant.removeAllPublishedTracks(notify: false);
await participant.dispose();
}
notifyListeners();
})
..on<EngineRestartedEvent>((event) async {
// re-publish all tracks
await localParticipant?.rePublishAllTracks();
for (var participant in _remoteParticipants.toList()) {
for (var pub in participant.trackPublications.values.toList()) {
if (pub.subscribed) {
pub.sendUpdateTrackSettings();
}
}
}
events.emit(const RoomReconnectedEvent());
notifyListeners();
})
..on<EngineResumingEvent>((event) async {
events.emit(const RoomResumingEvent());
notifyListeners();
})
..on<SignalReconnectedEvent>((event) async {
await _sendSyncState();
})
..on<EngineAttemptReconnectEvent>((event) async {
events.emit(RoomAttemptReconnectEvent(
attempt: event.attempt,
maxAttemptsRetry: event.maxAttempts,
nextRetryDelaysInMs: event.nextRetryDelaysInMs,
));
notifyListeners();
})
..on<EngineDisconnectedEvent>((event) async {
if (!engine.fullReconnectOnNext || event.reason == DisconnectReason.clientInitiated) {
await _cleanUp(disposeLocalParticipant: false);
events.emit(RoomDisconnectedEvent(reason: event.reason));
notifyListeners();
}
})
..on<EngineLocalTrackSubscribedEvent>(
(event) => events.emit(
LocalTrackSubscribedEvent(
trackSid: event.trackSid,
),
),
)
..on<EngineActiveSpeakersUpdateEvent>((event) => _onEngineActiveSpeakersUpdateEvent(event.speakers))
..on<EngineDataPacketReceivedEvent>(_onDataMessageEvent)
..on<EngineTranscriptionReceivedEvent>(_onTranscriptionEvent)
..on<EngineRequestResponseEvent>((event) {
localParticipant?.handleSignalRequestResponse(event.response);
})
..on<EngineRoomMovedEvent>((event) async {
final response = event.response;
logger.fine('Room moved to: ${response.room.name}');
// Apply room info from move response
if (response.hasRoom()) {
_applyRoomUpdate(response.room);
}
// Disconnect all remote participants
final identities = _remoteParticipants.byIdentity.keys.toList();
for (final identity in identities) {
await _handleParticipantDisconnect(identity);
}
// Emit public event
events.emit(RoomMovedEvent(roomName: response.room.name));
// Update local participant info
if (response.hasParticipant()) {
await localParticipant?.updateFromInfo(response.participant);
}
// Add new participants
if (response.otherParticipants.isNotEmpty) {
await _onParticipantUpdateEvent(response.otherParticipants);
}
notifyListeners();
})
..on<AudioPlaybackStarted>((event) {
_handleAudioPlaybackStarted();
})
..on<AudioPlaybackFailed>((event) {
_handleAudioPlaybackFailed();
})
..on<EngineTrackAddedEvent>((event) async {
logger.fine('EngineTrackAddedEvent trackSid:${event.track.id}');
final idParts = unpackStreamId(event.stream.id);
final participantSid = idParts[0];
final streamId = idParts[1];
var trackSid = event.track.id;
// firefox will get streamId (pID|trackId) instead of (pID|streamId) as it doesn't support sync tracks by stream
// and generates its own track id instead of infer from sdp track id.
if (streamId.isNotEmpty && streamId.startsWith('TR')) {
trackSid = streamId;
}
final participant = _remoteParticipants.bySid[participantSid];
try {
if (trackSid == null || trackSid.isEmpty) {
throw TrackSubscriptionExceptionEvent(
participant: participant,
reason: TrackSubscribeFailReason.invalidServerResponse,
);
}
final shouldDefer = connectionState != ConnectionState.connected || participant == null;
if (shouldDefer) {
_pendingTrackQueue.enqueue(
track: event.track,
stream: event.stream,
receiver: event.receiver,
participantSid: participantSid,
trackSid: trackSid,
connectionState: connectionState,
);
return;
}
await participant.addSubscribedMediaTrack(
event.track,
event.stream,
trackSid,
receiver: event.receiver,
audioOutputOptions: roomOptions.defaultAudioOutputOptions,
);
} on TrackSubscriptionExceptionEvent catch (event) {
logger.severe('addSubscribedMediaTrack() throwed ${event}');
events.emit(event);
} catch (exception) {
// We don't want to pass up any exception so catch everything here.
logger.warning('Unknown exception on addSubscribedMediaTrack() ${exception}');
}
});
/// Disconnects from the room, notifying server of disconnection.
Future<void> disconnect() async {
final bool isPendingReconnect = engine.isPendingReconnect;
if (engine.isClosed && !isPendingReconnect && engine.connectionState == ConnectionState.disconnected) {
logger.warning('Engine is already closed');
return;
}
await engine.disconnect();
if (!isPendingReconnect) {
await _engineListener.waitFor<EngineDisconnectedEvent>(duration: const Duration(seconds: 10));
}
await _cleanUp();
}
Future<void> setE2EEEnabled(bool enabled) async {
if (_e2eeManager != null) {
await _e2eeManager!.setEnabled(enabled);
} else {
throw LiveKitE2EEException('_e2eeManager not setup!');
}
}
/// retrieves a participant by identity
Participant? getParticipantByIdentity(String identity) {
if (_localParticipant?.identity == identity) {
return _localParticipant;
}
return _remoteParticipants.byIdentity[identity];
}
Future<ParticipantCreationResult> _getOrCreateRemoteParticipant(lk_models.ParticipantInfo info) async {
if (!info.hasIdentity() || !info.hasSid()) {
throw Exception('ParticipantInfo must have identity and sid');
}
final participant = _remoteParticipants.byIdentity[info.identity];
if (participant != null) {
// Return existing participant with no new publications; caller handles updates.
return ParticipantCreationResult(
participant: participant,
newPublications: const [],
);
}
final result = await RemoteParticipant.createFromInfo(
room: this,
info: info,
);
_remoteParticipants.set(result.participant);
await _flushPendingTracks(participant: result.participant);
return result;
}
Future<void> _onParticipantUpdateEvent(List<lk_models.ParticipantInfo> updates) async {
// trigger change notifier only if list of participants membership is changed
var hasChanged = false;
for (final info in updates) {
// The local participant is not ready yet, waiting for the
// `RoomConnectedEvent` to create the local participant.
if (_localParticipant == null) {
await events.waitFor<RoomConnectedEvent>(
duration: const Duration(seconds: 10),
);
}
if (localParticipant?.identity == info.identity) {
await localParticipant?.updateFromInfo(info);
continue;
}
final isNew = !_remoteParticipants.containsIdentity(info.identity);
if (info.state == lk_models.ParticipantInfo_State.DISCONNECTED) {
hasChanged = await _handleParticipantDisconnect(info.identity);
continue;
}
final result = await _getOrCreateRemoteParticipant(info);
if (isNew) {
hasChanged = true;
// Emit connected event
emitWhenConnected(ParticipantConnectedEvent(participant: result.participant));
// Emit TrackPublishedEvent for each new track
if (connectionState == ConnectionState.connected) {
for (final pub in result.newPublications) {
final event = TrackPublishedEvent(
participant: result.participant,
publication: pub,
);
[result.participant.events, events].emit(event);
}
}
_remoteParticipants.set(result.participant);
await _flushPendingTracks(participant: result.participant);
} else {
final wasUpdated = await result.participant.updateFromInfo(info);
if (wasUpdated) {
_remoteParticipants.set(result.participant);
await _flushPendingTracks(participant: result.participant);
}
}
}
if (hasChanged) {
notifyListeners();
}
}
void _onSignalSpeakersChangedEvent(List<lk_models.SpeakerInfo> speakers) {
final lastSpeakers = {
for (final p in _activeSpeakers) p.sid: p,
};
for (final speaker in speakers) {
Participant? p = _remoteParticipants.bySid[speaker.sid];
if (speaker.sid == localParticipant?.sid) p = localParticipant;
if (p == null) continue;
p.audioLevel = speaker.level;
p.isSpeaking = speaker.active;
if (speaker.active) {
lastSpeakers[speaker.sid] = p;
} else {
lastSpeakers.remove(speaker.sid);
}
}
final activeSpeakers = lastSpeakers.values.toList();
activeSpeakers.sort((a, b) => b.audioLevel.compareTo(a.audioLevel));
_activeSpeakers = activeSpeakers;
emitWhenConnected(ActiveSpeakersChangedEvent(speakers: activeSpeakers));
}
Future<void> _flushPendingTracks({RemoteParticipant? participant}) => _pendingTrackQueue.flush(
isConnected: connectionState == ConnectionState.connected,
participantSid: participant?.sid,
subscriber: (pending) async {
final target = participant ?? _remoteParticipants.bySid[pending.participantSid];
if (target == null) return false;
try {
await target.addSubscribedMediaTrack(
pending.track,
pending.stream,
pending.trackSid,
receiver: pending.receiver,
audioOutputOptions: roomOptions.defaultAudioOutputOptions,
);
return true;
} on TrackSubscriptionExceptionEvent catch (event) {
logger.severe('Track subscription failed during flush: ${event}');
events.emit(event);
return true;
} catch (exception) {
logger.warning('Unknown exception during pending track flush: ${exception}');
return false;
}
},
);
// from data channel
// updates are sent only when there's a change to speaker ordering
void _onEngineActiveSpeakersUpdateEvent(List<lk_models.SpeakerInfo> speakers) {
final List<Participant> activeSpeakers = [];
// localParticipant & remote participants
final allParticipants = <String, Participant>{
if (localParticipant != null) localParticipant!.sid: localParticipant!,
..._remoteParticipants.bySid,
};
for (final speaker in speakers) {
final p = allParticipants[speaker.sid];
if (p != null) {
p.audioLevel = speaker.level;
p.isSpeaking = true;
activeSpeakers.add(p);
}
}
// clear if not in the speakers list
final speakerSids = speakers.map((e) => e.sid).toSet();
for (final p in allParticipants.values) {
if (!speakerSids.contains(p.sid)) {
p.audioLevel = 0;
p.isSpeaking = false;
}
}
_activeSpeakers = activeSpeakers;
emitWhenConnected(ActiveSpeakersChangedEvent(speakers: activeSpeakers));
}
void _onSignalConnectionQualityUpdateEvent(List<lk_rtc.ConnectionQualityInfo> updates) {
for (final entry in updates) {
Participant? participant;
if (entry.participantSid == localParticipant?.sid) {
participant = localParticipant;
} else {
participant = _remoteParticipants.bySid[entry.participantSid];
}
if (participant != null) {
// update the connection quality if the participant is found
participant.updateConnectionQuality(entry.quality.toLKType());
}
}
}
void _onSignalStreamStateUpdateEvent(List<lk_rtc.StreamStateInfo> updates) async {
for (final update in updates) {
// try to find RemoteParticipant
final participant = _remoteParticipants.bySid[update.participantSid];
if (participant == null) {
logger.warning('Participant not found for sid ${update.participantSid}');
continue;
}
// try to find RemoteTrackPublication
final trackPublication = participant.trackPublications[update.trackSid];
if (trackPublication == null) continue;
// update the stream state
await trackPublication.updateStreamState(update.state.toLKType());
emitWhenConnected(TrackStreamStateUpdatedEvent(
participant: participant,
publication: trackPublication,
streamState: update.state.toLKType(),
));
}
}
void _onTranscriptionEvent(EngineTranscriptionReceivedEvent event) {
final participant = getParticipantByIdentity(event.transcription.transcribedParticipantIdentity);
if (participant == null || event.transcription.segments.isEmpty) {
return;
}
final publication = participant.getTrackPublicationBySid(event.transcription.trackId);
final segments = event.transcription.segments.map((segment) {
return TranscriptionSegment(
text: segment.text,
id: segment.id,
firstReceivedTime: _transcriptionReceivedTimes[segment.id] ?? DateTime.timestamp(),
lastReceivedTime: DateTime.timestamp(),
isFinal: segment.final_5,
language: segment.language,
);
}).toList();
for (var segment in segments) {
segment.isFinal
? _transcriptionReceivedTimes.remove(segment.id)
: _transcriptionReceivedTimes[segment.id] = DateTime.timestamp();
}
final transcription = TranscriptionEvent(
participant: participant,
publication: publication,
segments: segments,
);
participant.events.emit(transcription);
events.emit(transcription);
}
void _onDataMessageEvent(EngineDataPacketReceivedEvent dataPacketEvent) {
// participant may be null if data is sent from Server-API
RemoteParticipant? senderParticipant;
if (dataPacketEvent.identity.isNotEmpty) {
senderParticipant = getParticipantByIdentity(dataPacketEvent.identity) as RemoteParticipant?;
}
final event = DataReceivedEvent(
participant: senderParticipant,
data: dataPacketEvent.packet.payload,
topic: dataPacketEvent.packet.topic,
);
senderParticipant?.events.emit(event);
events.emit(event);
}
Future<bool> _handleParticipantDisconnect(String identity) async {
final participant = _remoteParticipants.removeByIdentity(identity);
if (participant == null) return false;
await validateParticipantHasNoActiveDataStreams(identity);
await participant.removeAllPublishedTracks(notify: true);
emitWhenConnected(ParticipantDisconnectedEvent(participant: participant));
return true;
}
Future<void> _sendSyncState() async {
final autoSubscribe = connectOptions.autoSubscribe;
final trackSids = <String>[];
final trackSidsDisabled = <String>[];
for (var participant in _remoteParticipants.toList()) {
for (var track in participant.trackPublications.values.toList()) {
if (track.subscribed != autoSubscribe) {
trackSids.add(track.sid);
}
if (!track.enabled) {
trackSidsDisabled.add(track.sid);
}
}
}
await engine.sendSyncState(
subscription: lk_rtc.UpdateSubscription(
participantTracks: [],
trackSids: trackSids,
subscribe: !autoSubscribe,
),
trackSidsDisabled: trackSidsDisabled,
publishTracks: localParticipant?.publishedTracksInfo(),
);
}
}
extension RoomPrivateMethods on Room {
// resets internal state to a re-usable state
Future<void> _cleanUp({bool disposeLocalParticipant = true}) async {
logger.fine('[${objectId}] cleanUp()');
// clean up RemoteParticipants
final participants = _remoteParticipants.toList();
_remoteParticipants.clear();
for (final participant in participants) {
await participant.removeAllPublishedTracks(notify: false);
// RemoteParticipant is responsible for disposing resources
await participant.dispose();