-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathroom.cpp
More file actions
1415 lines (1315 loc) · 49.3 KB
/
room.cpp
File metadata and controls
1415 lines (1315 loc) · 49.3 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 2025 LiveKit
*
* 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.
*/
#include "livekit/room.h"
#include "livekit/audio_stream.h"
#include "livekit/e2ee.h"
#include "livekit/local_data_track.h"
#include "livekit/local_participant.h"
#include "livekit/local_track_publication.h"
#include "livekit/remote_audio_track.h"
#include "livekit/remote_data_track.h"
#include "livekit/remote_participant.h"
#include "livekit/remote_track_publication.h"
#include "livekit/remote_video_track.h"
#include "livekit/room_delegate.h"
#include "livekit/room_event_types.h"
#include "data_track.pb.h"
#include "ffi.pb.h"
#include "ffi_client.h"
#include "livekit/lk_log.h"
#include "livekit_ffi.h"
#include "room.pb.h"
#include "room_proto_converter.h"
#include "trace/trace_event.h"
#include "track.pb.h"
#include "track_proto_converter.h"
#include <functional>
namespace livekit {
using proto::ConnectCallback;
using proto::ConnectRequest;
using proto::FfiEvent;
using proto::FfiRequest;
using proto::FfiResponse;
namespace {
std::shared_ptr<livekit::RemoteParticipant>
createRemoteParticipant(const proto::OwnedParticipant &owned) {
const auto &pinfo = owned.info();
std::unordered_map<std::string, std::string> attrs;
attrs.reserve(pinfo.attributes_size());
for (const auto &kv : pinfo.attributes()) {
attrs.emplace(kv.first, kv.second);
}
auto kind = livekit::fromProto(pinfo.kind());
auto reason = livekit::toDisconnectReason(pinfo.disconnect_reason());
livekit::FfiHandle handle(static_cast<uintptr_t>(owned.handle().id()));
return std::make_shared<livekit::RemoteParticipant>(
std::move(handle), pinfo.sid(), pinfo.name(), pinfo.identity(),
pinfo.metadata(), std::move(attrs), kind, reason);
}
} // namespace
Room::Room()
: subscription_thread_dispatcher_(
std::make_unique<SubscriptionThreadDispatcher>()) {}
Room::~Room() {
if (subscription_thread_dispatcher_) {
subscription_thread_dispatcher_->stopAll();
}
int listener_to_remove = 0;
std::unique_ptr<LocalParticipant> local_participant_to_cleanup;
{
std::lock_guard<std::mutex> g(lock_);
listener_to_remove = listener_id_;
listener_id_ = 0;
// Move local participant out for cleanup outside the lock
local_participant_to_cleanup = std::move(local_participant_);
}
// Shutdown local participant (unregisters RPC handlers, etc.) before
// removing the listener. This prevents in-flight RPC responses from
// trying to use destroyed handles.
if (local_participant_to_cleanup) {
local_participant_to_cleanup->shutdown();
}
if (listener_to_remove != 0) {
FfiClient::instance().RemoveListener(listener_to_remove);
}
// local_participant_to_cleanup is destroyed here after listener is removed
}
void Room::setDelegate(RoomDelegate *delegate) {
std::lock_guard<std::mutex> g(lock_);
delegate_ = delegate;
}
bool Room::Connect(const std::string &url, const std::string &token,
const RoomOptions &options) {
TRACE_EVENT0("livekit", "Room::Connect");
{
std::lock_guard<std::mutex> g(lock_);
if (connection_state_ != ConnectionState::Disconnected) {
throw std::runtime_error("already connected");
}
connection_state_ = ConnectionState::Reconnecting;
}
auto fut = FfiClient::instance().connectAsync(url, token, options);
try {
auto connectCb =
fut.get(); // fut will throw if it fails to connect to the room
const auto &owned_room = connectCb.result().room();
auto new_room_handle =
std::make_shared<FfiHandle>(owned_room.handle().id());
auto new_room_info = fromProto(owned_room.info());
// Setup local particpant
std::unique_ptr<LocalParticipant> new_local_participant;
{
const auto &owned_local = connectCb.result().local_participant();
const auto &pinfo = owned_local.info();
// Build attributes map
std::unordered_map<std::string, std::string> attrs;
for (const auto &kv : pinfo.attributes()) {
attrs.emplace(kv.first, kv.second);
}
auto kind = fromProto(pinfo.kind());
auto reason = toDisconnectReason(pinfo.disconnect_reason());
// Participant base stores a weak_ptr<FfiHandle>, so share the room handle
FfiHandle participant_handle(
static_cast<uintptr_t>(owned_local.handle().id()));
new_local_participant = std::make_unique<LocalParticipant>(
std::move(participant_handle), pinfo.sid(), pinfo.name(),
pinfo.identity(), pinfo.metadata(), std::move(attrs), kind, reason);
}
// Setup remote participants
std::unordered_map<std::string, std::shared_ptr<RemoteParticipant>>
new_remote_participants;
{
const auto &participants = connectCb.result().participants();
std::lock_guard<std::mutex> g(lock_);
for (const auto &pt : participants) {
const auto &owned = pt.participant();
auto rp = createRemoteParticipant(owned);
// Add the initial remote participant tracks
for (const auto &owned_publication_info : pt.publications()) {
auto publication =
std::make_shared<RemoteTrackPublication>(owned_publication_info);
rp->mutableTrackPublications().emplace(publication->sid(),
std::move(publication));
}
new_remote_participants.emplace(rp->identity(), std::move(rp));
}
}
// Setup e2eeManager
std::unique_ptr<E2EEManager> new_e2ee_manager;
if (options.encryption) {
LK_LOG_INFO("creating E2eeManager");
new_e2ee_manager = std::unique_ptr<E2EEManager>(
new E2EEManager(new_room_handle->get(), options.encryption.value()));
}
// Publish all state atomically under lock
{
std::lock_guard<std::mutex> g(lock_);
room_handle_ = std::move(new_room_handle);
room_info_ = std::move(new_room_info);
local_participant_ = std::move(new_local_participant);
remote_participants_ = std::move(new_remote_participants);
e2ee_manager_ = std::move(new_e2ee_manager);
connection_state_ = ConnectionState::Connected;
}
// Install listener (Room is fully initialized)
auto listenerId = FfiClient::instance().AddListener(
std::bind(&Room::OnEvent, this, std::placeholders::_1));
{
std::lock_guard<std::mutex> g(lock_);
listener_id_ = listenerId;
}
return true;
} catch (const std::exception &e) {
// On error, set the connection_state_ to Disconnected
connection_state_ = ConnectionState::Disconnected;
LK_LOG_ERROR("Room::Connect failed: {}", e.what());
return false;
}
}
RoomInfoData Room::room_info() const {
std::lock_guard<std::mutex> g(lock_);
return room_info_;
}
LocalParticipant *Room::localParticipant() const {
std::lock_guard<std::mutex> g(lock_);
return local_participant_.get();
}
RemoteParticipant *Room::remoteParticipant(const std::string &identity) const {
std::lock_guard<std::mutex> g(lock_);
auto it = remote_participants_.find(identity);
return it == remote_participants_.end() ? nullptr : it->second.get();
}
std::vector<std::shared_ptr<RemoteParticipant>>
Room::remoteParticipants() const {
std::lock_guard<std::mutex> guard(lock_);
std::vector<std::shared_ptr<RemoteParticipant>> out;
out.reserve(remote_participants_.size());
for (const auto &kv : remote_participants_) {
out.push_back(kv.second);
}
return out;
}
E2EEManager *Room::e2eeManager() const {
std::lock_guard<std::mutex> g(lock_);
return e2ee_manager_.get();
}
void Room::registerTextStreamHandler(const std::string &topic,
TextStreamHandler handler) {
std::lock_guard<std::mutex> g(lock_);
auto [it, inserted] =
text_stream_handlers_.emplace(topic, std::move(handler));
if (!inserted) {
throw std::runtime_error("text stream handler for topic '" + topic +
"' already set");
}
}
void Room::unregisterTextStreamHandler(const std::string &topic) {
std::lock_guard<std::mutex> g(lock_);
text_stream_handlers_.erase(topic);
}
void Room::registerByteStreamHandler(const std::string &topic,
ByteStreamHandler handler) {
std::lock_guard<std::mutex> g(lock_);
auto [it, inserted] =
byte_stream_handlers_.emplace(topic, std::move(handler));
if (!inserted) {
throw std::runtime_error("byte stream handler for topic '" + topic +
"' already set");
}
}
void Room::unregisterByteStreamHandler(const std::string &topic) {
std::lock_guard<std::mutex> g(lock_);
byte_stream_handlers_.erase(topic);
}
// -------------------------------------------------------------------
// Frame callback registration
// -------------------------------------------------------------------
void Room::setOnAudioFrameCallback(const std::string &participant_identity,
TrackSource source,
AudioFrameCallback callback,
AudioStream::Options opts) {
if (subscription_thread_dispatcher_) {
subscription_thread_dispatcher_->setOnAudioFrameCallback(
participant_identity, source, std::move(callback), std::move(opts));
}
}
void Room::setOnAudioFrameCallback(const std::string &participant_identity,
const std::string &track_name,
AudioFrameCallback callback,
AudioStream::Options opts) {
if (subscription_thread_dispatcher_) {
subscription_thread_dispatcher_->setOnAudioFrameCallback(
participant_identity, track_name, std::move(callback), std::move(opts));
}
}
void Room::setOnVideoFrameCallback(const std::string &participant_identity,
TrackSource source,
VideoFrameCallback callback,
VideoStream::Options opts) {
if (subscription_thread_dispatcher_) {
subscription_thread_dispatcher_->setOnVideoFrameCallback(
participant_identity, source, std::move(callback), std::move(opts));
}
}
void Room::setOnVideoFrameCallback(const std::string &participant_identity,
const std::string &track_name,
VideoFrameCallback callback,
VideoStream::Options opts) {
if (subscription_thread_dispatcher_) {
subscription_thread_dispatcher_->setOnVideoFrameCallback(
participant_identity, track_name, std::move(callback), std::move(opts));
}
}
void Room::clearOnAudioFrameCallback(const std::string &participant_identity,
TrackSource source) {
if (subscription_thread_dispatcher_) {
subscription_thread_dispatcher_->clearOnAudioFrameCallback(
participant_identity, source);
}
}
void Room::clearOnAudioFrameCallback(const std::string &participant_identity,
const std::string &track_name) {
if (subscription_thread_dispatcher_) {
subscription_thread_dispatcher_->clearOnAudioFrameCallback(
participant_identity, track_name);
}
}
void Room::clearOnVideoFrameCallback(const std::string &participant_identity,
TrackSource source) {
if (subscription_thread_dispatcher_) {
subscription_thread_dispatcher_->clearOnVideoFrameCallback(
participant_identity, source);
}
}
void Room::clearOnVideoFrameCallback(const std::string &participant_identity,
const std::string &track_name) {
if (subscription_thread_dispatcher_) {
subscription_thread_dispatcher_->clearOnVideoFrameCallback(
participant_identity, track_name);
}
}
DataFrameCallbackId
Room::addOnDataFrameCallback(const std::string &participant_identity,
const std::string &track_name,
DataFrameCallback callback) {
if (subscription_thread_dispatcher_) {
return subscription_thread_dispatcher_->addOnDataFrameCallback(
participant_identity, track_name, std::move(callback));
}
return std::numeric_limits<DataFrameCallbackId>::max();
}
void Room::removeOnDataFrameCallback(DataFrameCallbackId id) {
if (subscription_thread_dispatcher_) {
subscription_thread_dispatcher_->removeOnDataFrameCallback(id);
}
}
void Room::OnEvent(const FfiEvent &event) {
// Take a snapshot of the delegate under lock, but do NOT call it under the
// lock.
RoomDelegate *delegate_snapshot = nullptr;
{
std::lock_guard<std::mutex> guard(lock_);
delegate_snapshot = delegate_;
}
// First, handle RPC method invocations (not part of RoomEvent).
if (event.message_case() == FfiEvent::kRpcMethodInvocation) {
const auto &rpc = event.rpc_method_invocation();
LocalParticipant *lp = nullptr;
{
std::lock_guard<std::mutex> guard(lock_);
if (!local_participant_) {
return;
}
auto local_handle = local_participant_->ffiHandleId();
if (local_handle == INVALID_HANDLE ||
rpc.local_participant_handle() !=
static_cast<std::uint64_t>(local_handle)) {
// RPC is not targeted at this room's local participant; ignore.
return;
}
lp = local_participant_.get();
}
// Call outside the lock to avoid deadlocks / re-entrancy issues.
lp->handleRpcMethodInvocation(
rpc.invocation_id(), rpc.method(), rpc.request_id(),
rpc.caller_identity(), rpc.payload(),
static_cast<double>(rpc.response_timeout_ms()) / 1000.0);
return;
}
switch (event.message_case()) {
case FfiEvent::kRoomEvent: {
const proto::RoomEvent &re = event.room_event();
// Check if this event is for our room handle
{
std::lock_guard<std::mutex> guard(lock_);
if (!room_handle_ ||
re.room_handle() != static_cast<std::uint64_t>(room_handle_->get())) {
return;
}
}
switch (re.message_case()) {
case proto::RoomEvent::kParticipantConnected: {
std::shared_ptr<RemoteParticipant> new_participant;
{
std::lock_guard<std::mutex> guard(lock_);
const auto &owned = re.participant_connected().info();
// createRemoteParticipant takes proto::OwnedParticipant
new_participant = createRemoteParticipant(owned);
remote_participants_.emplace(new_participant->identity(),
new_participant);
}
ParticipantConnectedEvent ev;
ev.participant = new_participant.get();
if (delegate_snapshot) {
delegate_snapshot->onParticipantConnected(*this, ev);
}
break;
}
case proto::RoomEvent::kParticipantDisconnected: {
std::shared_ptr<RemoteParticipant> removed;
DisconnectReason reason = DisconnectReason::Unknown;
{
std::lock_guard<std::mutex> guard(lock_);
const auto &pd = re.participant_disconnected();
const std::string &identity = pd.participant_identity();
reason = toDisconnectReason(pd.disconnect_reason());
auto it = remote_participants_.find(identity);
if (it != remote_participants_.end()) {
removed = it->second;
remote_participants_.erase(it);
} else {
// We saw a disconnect event for a participant we don't track
// internally. This can happen on races or if we never created a
// RemoteParticipant
LK_LOG_WARN("participant_disconnected for unknown identity: {}",
identity);
}
}
if (removed) {
ParticipantDisconnectedEvent ev;
ev.participant = removed.get();
ev.reason = reason;
if (delegate_snapshot) {
delegate_snapshot->onParticipantDisconnected(*this, ev);
}
}
break;
}
case proto::RoomEvent::kLocalTrackPublished: {
LocalTrackPublishedEvent ev;
{
std::lock_guard<std::mutex> guard(lock_);
if (!local_participant_) {
LK_LOG_ERROR("kLocalTrackPublished: local_participant_ is nullptr");
break;
}
const auto <p = re.local_track_published();
const std::string &sid = ltp.track_sid();
const auto pubs = local_participant_->trackPublications();
auto it = pubs.find(sid);
if (it == pubs.end()) {
LK_LOG_WARN("local_track_published for unknown sid: {}", sid);
break;
}
ev.publication = it->second;
ev.track = ev.publication ? ev.publication->track() : nullptr;
}
if (delegate_snapshot) {
delegate_snapshot->onLocalTrackPublished(*this, ev);
}
break;
}
case proto::RoomEvent::kLocalTrackUnpublished: {
LocalTrackUnpublishedEvent ev;
{
std::lock_guard<std::mutex> guard(lock_);
if (!local_participant_) {
LK_LOG_ERROR("kLocalTrackUnpublished: local_participant_ is nullptr");
break;
}
const auto <u = re.local_track_unpublished();
const std::string &pub_sid = ltu.publication_sid();
const auto pubs = local_participant_->trackPublications();
auto it = pubs.find(pub_sid);
if (it == pubs.end()) {
LK_LOG_WARN("local_track_unpublished for unknown publication sid: {}",
pub_sid);
break;
}
ev.publication = it->second;
}
if (delegate_snapshot) {
delegate_snapshot->onLocalTrackUnpublished(*this, ev);
}
break;
}
case proto::RoomEvent::kLocalTrackSubscribed: {
LocalTrackSubscribedEvent ev;
{
std::lock_guard<std::mutex> guard(lock_);
if (!local_participant_) {
break;
}
const auto <s = re.local_track_subscribed();
const std::string &sid = lts.track_sid();
const auto pubs = local_participant_->trackPublications();
auto it = pubs.find(sid);
if (it == pubs.end()) {
LK_LOG_WARN("local_track_subscribed for unknown sid: {}", sid);
break;
}
auto publication = it->second;
ev.track = publication ? publication->track() : nullptr;
}
if (delegate_snapshot) {
delegate_snapshot->onLocalTrackSubscribed(*this, ev);
}
break;
}
case proto::RoomEvent::kTrackPublished: {
TrackPublishedEvent ev;
{
std::lock_guard<std::mutex> guard(lock_);
const auto &tp = re.track_published();
const std::string &identity = tp.participant_identity();
auto it = remote_participants_.find(identity);
if (it != remote_participants_.end()) {
RemoteParticipant *rparticipant = it->second.get();
const auto &owned_publication = tp.publication();
auto rpublication =
std::make_shared<RemoteTrackPublication>(owned_publication);
// Store it on the participant, keyed by SID
rparticipant->mutableTrackPublications().emplace(
rpublication->sid(), std::move(rpublication));
ev.participant = rparticipant;
ev.publication = rpublication;
} else {
// Optional: log if we get a track for an unknown participant
LK_LOG_WARN("track_published for unknown participant: {}", identity);
// Don't emit the
break;
}
}
if (delegate_snapshot) {
delegate_snapshot->onTrackPublished(*this, ev);
}
break;
}
case proto::RoomEvent::kTrackUnpublished: {
TrackUnpublishedEvent ev;
{
std::lock_guard<std::mutex> guard(lock_);
const auto &tu = re.track_unpublished();
const std::string &identity = tu.participant_identity();
const std::string &pub_sid = tu.publication_sid();
auto pit = remote_participants_.find(identity);
if (pit == remote_participants_.end()) {
LK_LOG_WARN("track_unpublished for unknown participant: {}",
identity);
break;
}
RemoteParticipant *rparticipant = pit->second.get();
auto &pubs = rparticipant->mutableTrackPublications();
auto it = pubs.find(pub_sid);
if (it == pubs.end()) {
LK_LOG_WARN("track_unpublished for unknown publication sid {} "
"(participant {})",
pub_sid, identity);
break;
}
ev.participant = rparticipant;
ev.publication = it->second;
pubs.erase(it);
}
if (delegate_snapshot) {
delegate_snapshot->onTrackUnpublished(*this, ev);
}
break;
}
case proto::RoomEvent::kTrackSubscribed: {
const auto &ts = re.track_subscribed();
const std::string &identity = ts.participant_identity();
const auto &owned_track = ts.track();
const auto &track_info = owned_track.info();
std::shared_ptr<RemoteTrackPublication> rpublication;
RemoteParticipant *rparticipant = nullptr;
std::shared_ptr<Track> remote_track;
{
std::lock_guard<std::mutex> guard(lock_);
// Find participant
auto pit = remote_participants_.find(identity);
if (pit == remote_participants_.end()) {
LK_LOG_WARN("track_subscribed for unknown participant: {}", identity);
break;
}
rparticipant = pit->second.get();
// Find existing publication by track SID (from track_published)
auto &pubs = rparticipant->mutableTrackPublications();
auto pubIt = pubs.find(track_info.sid());
if (pubIt == pubs.end()) {
LK_LOG_WARN("track_subscribed for unknown publication sid {} "
"(participant {})",
track_info.sid(), identity);
break;
}
rpublication = pubIt->second;
// Create RemoteVideoTrack / RemoteAudioTrack
if (track_info.kind() == proto::TrackKind::KIND_VIDEO) {
remote_track = std::make_shared<RemoteVideoTrack>(owned_track);
} else if (track_info.kind() == proto::TrackKind::KIND_AUDIO) {
remote_track = std::make_shared<RemoteAudioTrack>(owned_track);
} else {
LK_LOG_WARN("track_subscribed with unsupported kind: {}",
static_cast<int>(track_info.kind()));
break;
}
// Attach to publication, mark subscribed
rpublication->setTrack(remote_track);
rpublication->setSubscribed(true);
}
// Emit remote track_subscribed-style callback
TrackSubscribedEvent ev;
ev.track = remote_track;
ev.publication = rpublication;
ev.participant = rparticipant;
if (delegate_snapshot) {
delegate_snapshot->onTrackSubscribed(*this, ev);
}
if (subscription_thread_dispatcher_ && remote_track && rpublication) {
subscription_thread_dispatcher_->handleTrackSubscribed(
identity, rpublication->source(), rpublication->name(),
remote_track);
}
break;
}
case proto::RoomEvent::kTrackUnsubscribed: {
TrackUnsubscribedEvent ev;
TrackSource unsub_source = TrackSource::SOURCE_UNKNOWN;
std::string unsub_identity;
{
std::lock_guard<std::mutex> guard(lock_);
const auto &tu = re.track_unsubscribed();
unsub_identity = tu.participant_identity();
const std::string &track_sid = tu.track_sid();
auto pit = remote_participants_.find(unsub_identity);
if (pit == remote_participants_.end()) {
LK_LOG_WARN("track_unsubscribed for unknown participant: {}",
unsub_identity);
break;
}
RemoteParticipant *rparticipant = pit->second.get();
auto &pubs = rparticipant->mutableTrackPublications();
auto pubIt = pubs.find(track_sid);
if (pubIt == pubs.end()) {
LK_LOG_WARN("track_unsubscribed for unknown publication sid {} "
"(participant {})",
track_sid, unsub_identity);
break;
}
auto publication = pubIt->second;
unsub_source = publication->source();
auto track = publication->track();
publication->setTrack(nullptr);
publication->setSubscribed(false);
ev.participant = rparticipant;
ev.publication = publication;
ev.track = track;
}
if (delegate_snapshot) {
delegate_snapshot->onTrackUnsubscribed(*this, ev);
}
if (subscription_thread_dispatcher_ &&
unsub_source != TrackSource::SOURCE_UNKNOWN) {
subscription_thread_dispatcher_->handleTrackUnsubscribed(
unsub_identity, unsub_source,
ev.publication ? ev.publication->name() : "");
}
break;
}
case proto::RoomEvent::kTrackSubscriptionFailed: {
TrackSubscriptionFailedEvent ev;
{
std::lock_guard<std::mutex> guard(lock_);
const auto &tsf = re.track_subscription_failed();
const std::string &identity = tsf.participant_identity();
auto pit = remote_participants_.find(identity);
if (pit == remote_participants_.end()) {
LK_LOG_WARN("track_subscription_failed for unknown participant: {}",
identity);
break;
}
ev.participant = pit->second.get();
ev.track_sid = tsf.track_sid();
ev.error = tsf.error();
}
if (delegate_snapshot) {
delegate_snapshot->onTrackSubscriptionFailed(*this, ev);
}
break;
}
case proto::RoomEvent::kDataTrackPublished: {
const auto &rdtp = re.data_track_published();
auto remote_track =
std::shared_ptr<RemoteDataTrack>(new RemoteDataTrack(rdtp.track()));
if (subscription_thread_dispatcher_) {
subscription_thread_dispatcher_->handleDataTrackPublished(remote_track);
}
DataTrackPublishedEvent ev;
ev.track = remote_track;
if (delegate_snapshot) {
delegate_snapshot->onDataTrackPublished(*this, ev);
}
break;
}
case proto::RoomEvent::kDataTrackUnpublished: {
const auto &dtu = re.data_track_unpublished();
if (subscription_thread_dispatcher_) {
subscription_thread_dispatcher_->handleDataTrackUnpublished(dtu.sid());
}
DataTrackUnpublishedEvent ev;
ev.sid = dtu.sid();
if (delegate_snapshot) {
delegate_snapshot->onDataTrackUnpublished(*this, ev);
}
break;
}
case proto::RoomEvent::kTrackMuted: {
TrackMutedEvent ev;
bool success = false;
{
std::lock_guard<std::mutex> guard(lock_);
const auto &tm = re.track_muted();
const std::string &identity = tm.participant_identity();
const std::string &sid = tm.track_sid();
Participant *participant = nullptr;
if (local_participant_ && local_participant_->identity() == identity) {
participant = local_participant_.get();
} else {
auto pit = remote_participants_.find(identity);
if (pit != remote_participants_.end()) {
participant = pit->second.get();
}
}
if (!participant) {
LK_LOG_WARN("track_muted for unknown participant: {}", identity);
break;
}
auto pub = participant->findTrackPublication(sid);
if (!pub) {
LK_LOG_WARN("track_muted for unknown track sid: {}", sid);
} else {
pub->setMuted(true);
if (auto t = pub->track()) {
t->setMuted(true);
}
ev.participant = participant;
ev.publication = pub;
success = true;
}
}
if (success && delegate_snapshot) {
delegate_snapshot->onTrackMuted(*this, ev);
}
break;
}
case proto::RoomEvent::kTrackUnmuted: {
TrackUnmutedEvent ev;
bool success = false;
{
std::lock_guard<std::mutex> guard(lock_);
const auto &tu = re.track_unmuted();
const std::string &identity = tu.participant_identity();
const std::string &sid = tu.track_sid();
Participant *participant = nullptr;
if (local_participant_ && local_participant_->identity() == identity) {
participant = local_participant_.get();
} else {
auto pit = remote_participants_.find(identity);
if (pit != remote_participants_.end()) {
participant = pit->second.get();
}
}
if (!participant) {
LK_LOG_WARN("track_unmuted for unknown participant: {}", identity);
break;
}
auto pub = participant->findTrackPublication(sid);
if (!pub) {
LK_LOG_WARN("track_unmuted for unknown track sid: {}", sid);
} else {
pub->setMuted(false);
if (auto t = pub->track()) {
t->setMuted(false);
}
ev.participant = participant;
ev.publication = pub;
success = true;
}
ev.participant = participant;
ev.publication = pub;
}
if (success && delegate_snapshot) {
delegate_snapshot->onTrackUnmuted(*this, ev);
}
break;
}
case proto::RoomEvent::kActiveSpeakersChanged: {
ActiveSpeakersChangedEvent ev;
{
std::lock_guard<std::mutex> guard(lock_);
const auto &asc = re.active_speakers_changed();
for (const auto &identity : asc.participant_identities()) {
Participant *participant = nullptr;
if (local_participant_ &&
local_participant_->identity() == identity) {
participant = local_participant_.get();
} else {
auto pit = remote_participants_.find(identity);
if (pit != remote_participants_.end()) {
participant = pit->second.get();
}
}
if (participant) {
ev.speakers.push_back(participant);
}
}
}
if (delegate_snapshot) {
delegate_snapshot->onActiveSpeakersChanged(*this, ev);
}
break;
}
case proto::RoomEvent::kRoomMetadataChanged: {
RoomMetadataChangedEvent ev;
{
std::lock_guard<std::mutex> guard(lock_);
const auto old_metadata = room_info_.metadata;
room_info_.metadata = re.room_metadata_changed().metadata();
ev.old_metadata = old_metadata;
ev.new_metadata = room_info_.metadata;
}
if (delegate_snapshot) {
delegate_snapshot->onRoomMetadataChanged(*this, ev);
}
break;
}
case proto::RoomEvent::kRoomSidChanged: {
RoomSidChangedEvent ev;
{
std::lock_guard<std::mutex> guard(lock_);
room_info_.sid = re.room_sid_changed().sid();
ev.sid = room_info_.sid.value_or(std::string{});
}
if (delegate_snapshot) {
delegate_snapshot->onRoomSidChanged(*this, ev);
}
break;
}
case proto::RoomEvent::kParticipantMetadataChanged: {
ParticipantMetadataChangedEvent ev;
{
std::lock_guard<std::mutex> guard(lock_);
const auto &pm = re.participant_metadata_changed();
const std::string &identity = pm.participant_identity();
Participant *participant = nullptr;
if (local_participant_ && local_participant_->identity() == identity) {
participant = local_participant_.get();
} else {
auto it = remote_participants_.find(identity);
if (it != remote_participants_.end()) {
participant = it->second.get();
}
}
if (!participant) {
LK_LOG_WARN(
"participant_metadata_changed for unknown participant: {}",
identity);
break;
}
std::string old_metadata = participant->metadata();
participant->set_metadata(pm.metadata());
ev.participant = participant;
ev.old_metadata = old_metadata;
ev.new_metadata = participant->metadata();
}
if (delegate_snapshot) {
delegate_snapshot->onParticipantMetadataChanged(*this, ev);
}
break;
}
case proto::RoomEvent::kParticipantNameChanged: {
ParticipantNameChangedEvent ev;
{
std::lock_guard<std::mutex> guard(lock_);
const auto &pn = re.participant_name_changed();
const std::string &identity = pn.participant_identity();
Participant *participant = nullptr;
if (local_participant_ && local_participant_->identity() == identity) {
participant = local_participant_.get();
} else {
auto it = remote_participants_.find(identity);
if (it != remote_participants_.end()) {
participant = it->second.get();
}
}
if (!participant) {
LK_LOG_WARN("participant_name_changed for unknown participant: {}",
identity);
break;
}
std::string old_name = participant->name();
participant->set_name(pn.name());
ev.participant = participant;
ev.old_name = old_name;
ev.new_name = participant->name();
}
if (delegate_snapshot) {
delegate_snapshot->onParticipantNameChanged(*this, ev);
}
break;
}
case proto::RoomEvent::kParticipantAttributesChanged: {
ParticipantAttributesChangedEvent ev;
{
std::lock_guard<std::mutex> guard(lock_);
const auto &pa = re.participant_attributes_changed();
const std::string &identity = pa.participant_identity();
Participant *participant = nullptr;
if (local_participant_ && local_participant_->identity() == identity) {
participant = local_participant_.get();
} else {
auto it = remote_participants_.find(identity);
if (it != remote_participants_.end()) {
participant = it->second.get();
}
}
if (!participant) {
LK_LOG_WARN(
"participant_attributes_changed for unknown participant: {}",
identity);
break;
}
// Build full attributes map
std::unordered_map<std::string, std::string> attrs;
for (const auto &entry : pa.attributes()) {
attrs.emplace(entry.key(), entry.value());
}
participant->set_attributes(attrs);
// Build changed_attributes map
for (const auto &entry : pa.changed_attributes()) {
ev.changed_attributes.emplace_back(entry.key(), entry.value());
}
ev.participant = participant;
}
if (delegate_snapshot) {
delegate_snapshot->onParticipantAttributesChanged(*this, ev);
}
break;
}
case proto::RoomEvent::kParticipantEncryptionStatusChanged: {
ParticipantEncryptionStatusChangedEvent ev;
{
std::lock_guard<std::mutex> guard(lock_);
const auto &pe = re.participant_encryption_status_changed();
const std::string &identity = pe.participant_identity();
Participant *participant = nullptr;
if (local_participant_ && local_participant_->identity() == identity) {