Skip to content

Commit cdcfe7a

Browse files
participants raw ptr -> weak_ptr
test that participant handles are expired after disconnect
1 parent ded4483 commit cdcfe7a

22 files changed

Lines changed: 316 additions & 198 deletions

‎benchmarks/data_track_throughput/consumer.cpp‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -481,7 +481,7 @@ int main(int argc, char* argv[]) {
481481
throw std::runtime_error("Failed to connect to LiveKit room");
482482
}
483483

484-
auto* local_participant = room.localParticipant();
484+
auto local_participant = room.localParticipant().lock();
485485
if (local_participant == nullptr) {
486486
throw std::runtime_error("Local participant unavailable after connect");
487487
}

‎benchmarks/data_track_throughput/producer.cpp‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -200,13 +200,15 @@ std::string waitForConsumerIdentity(Room& room, const std::string& requested_ide
200200
const auto deadline = std::chrono::steady_clock::now() + timeout;
201201
while (g_running.load() && std::chrono::steady_clock::now() < deadline) {
202202
if (!requested_identity.empty()) {
203-
if (room.remoteParticipant(requested_identity) != nullptr) {
203+
if (!room.remoteParticipant(requested_identity).expired()) {
204204
return requested_identity;
205205
}
206206
} else {
207207
const auto participants = room.remoteParticipants();
208-
if (participants.size() == 1 && participants.front() != nullptr) {
209-
return participants.front()->identity();
208+
if (participants.size() == 1) {
209+
if (auto participant = participants.front().lock()) {
210+
return participant->identity();
211+
}
210212
}
211213
}
212214

@@ -316,7 +318,7 @@ int main(int argc, char* argv[]) {
316318
throw std::runtime_error("Failed to connect to LiveKit room");
317319
}
318320

319-
auto* local_participant = room.localParticipant();
321+
auto local_participant = room.localParticipant().lock();
320322
if (local_participant == nullptr) {
321323
throw std::runtime_error("Local participant unavailable after connect");
322324
}

‎docs/doxygen/index.md‎

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,14 @@ bool initializeLivekit(const std::string& url, const std::string& token) {
2323

2424
std::cout << "Connected.\n";
2525

26+
// localParticipant() returns a weak_ptr; lock it once and guard. The handle
27+
// is empty before connect and after the room is torn down or destroyed.
28+
auto lp = room_->localParticipant().lock();
29+
if (!lp) {
30+
std::cerr << "Local participant unavailable\n";
31+
return false;
32+
}
33+
2634
// ---- Create & publish AUDIO ----
2735
// Note: Hook up your own audio capture flow to |audioSource_|
2836
audioSource_ = std::make_shared<livekit::AudioSource>(48000, 1, 10);
@@ -32,7 +40,7 @@ bool initializeLivekit(const std::string& url, const std::string& token) {
3240
audioOpts.source = livekit::TrackSource::SOURCE_MICROPHONE;
3341

3442
try {
35-
audioPub_ = room_->localParticipant()->publishTrack(audioTrack, audioOpts);
43+
audioPub_ = lp->publishTrack(audioTrack, audioOpts);
3644
std::cout << "Published audio: sid=" << audioPub_->sid() << "\n";
3745
} catch (const std::exception& e) {
3846
std::cerr << "Failed to publish audio: " << e.what() << "\n";
@@ -48,7 +56,7 @@ bool initializeLivekit(const std::string& url, const std::string& token) {
4856
videoOpts.source = livekit::TrackSource::SOURCE_CAMERA;
4957

5058
try {
51-
videoPub_ = room_->localParticipant()->publishTrack(videoTrack, videoOpts);
59+
videoPub_ = lp->publishTrack(videoTrack, videoOpts);
5260
std::cout << "Published video: sid=" << videoPub_->sid() << "\n";
5361
} catch (const std::exception& e) {
5462
std::cerr << "Failed to publish video: " << e.what() << "\n";
@@ -60,10 +68,12 @@ bool initializeLivekit(const std::string& url, const std::string& token) {
6068
void shutdownLivekit() {
6169
// Best-effort unpublish
6270
try {
63-
if (room_ && audioPub_)
64-
room_->localParticipant()->unpublishTrack(audioPub_->sid());
65-
if (room_ && videoPub_)
66-
room_->localParticipant()->unpublishTrack(videoPub_->sid());
71+
if (auto lp = room_ ? room_->localParticipant().lock() : nullptr) {
72+
if (audioPub_)
73+
lp->unpublishTrack(audioPub_->sid());
74+
if (videoPub_)
75+
lp->unpublishTrack(videoPub_->sid());
76+
}
6777
} catch (...) {
6878
}
6979

‎include/livekit/local_audio_track.h‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,9 @@ class AudioSource;
4242
///
4343
/// auto source = AudioSource::create(...);
4444
/// auto track = LocalAudioTrack::createLocalAudioTrack("mic", source);
45-
/// room->localParticipant()->publishTrack(track);
45+
/// if (auto lp = room->localParticipant().lock()) {
46+
/// lp->publishTrack(track);
47+
/// }
4648
///
4749
/// Muting a local audio track stops transmitting audio to the room, but
4850
/// the underlying source may continue capturing depending on platform

‎include/livekit/local_data_track.h‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,8 @@ class OwnedLocalDataTrack;
4545
///
4646
/// Typical usage:
4747
///
48-
/// auto lp = room->localParticipant();
48+
/// auto lp = room->localParticipant().lock();
49+
/// if (!lp) return; // room not connected or already torn down
4950
/// auto result = lp->publishDataTrack("sensor-data");
5051
/// if (result) {
5152
/// auto dt = result.value();

‎include/livekit/local_video_track.h‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,9 @@ class VideoSource;
4141
///
4242
/// auto source = std::make_shared<VideoSource>(1280, 720);
4343
/// auto track = LocalVideoTrack::createLocalVideoTrack("cam", source);
44-
/// room->localParticipant()->publishTrack(track);
44+
/// if (auto lp = room->localParticipant().lock()) {
45+
/// lp->publishTrack(track);
46+
/// }
4547
/// // Capture frames on the video thread via `source`, not via the track.
4648
///
4749
/// Muting a local video track stops transmitting video to the room, but

‎include/livekit/room.h‎

Lines changed: 28 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -164,27 +164,34 @@ class LIVEKIT_API Room {
164164
/// - published tracks (audio/video/screen)
165165
/// - identity, SID, metadata
166166
/// - publishing/unpublishing operations
167-
/// @return Non-null pointer while connected; nullptr before connect, after
168-
/// room end-of-stream teardown, or when the room is destroyed.
169-
LocalParticipant* localParticipant() const;
167+
///
168+
/// The returned handle is non-owning. Call @c lock() to obtain a usable
169+
/// @c weak_ptr; the result is empty (`lock() == nullptr`) before connect,
170+
/// after room end-of-stream teardown, or once the room is destroyed. This
171+
/// lets callers that cache the handle detect teardown instead of holding a
172+
/// dangling pointer.
173+
///
174+
/// @return Weak handle to the local participant.
175+
std::weak_ptr<LocalParticipant> localParticipant() const;
170176

171177
/// Look up a remote participant by identity.
172178
///
173-
/// @param identity The participant’s identity string (not SID)
174-
/// @return Pointer to RemoteParticipant if present, otherwise nullptr (also
175-
/// nullptr after room teardown or when the room is destroyed).
176-
/// RemoteParticipant contains:
179+
/// @param identity The participant’s identity string (not SID).
180+
/// @return Weak handle to the RemoteParticipant if present, otherwise an
181+
/// empty handle (`lock() == nullptr`). The handle also becomes empty once
182+
/// the participant disconnects, the room is torn down, or the room is
183+
/// destroyed. RemoteParticipant contains:
177184
/// - identity/name/metadata
178185
/// - track publications
179-
/// - callbacks for track subscribed/unsubscribed, muted/unmuted
180-
RemoteParticipant* remoteParticipant(const std::string& identity) const;
186+
/// - callbacks for track subscribed/unsubscribed, muted/unmuted
187+
std::weak_ptr<RemoteParticipant> remoteParticipant(const std::string& identity) const;
181188

182189
/// Returns a snapshot of all current remote participants.
183190
///
184-
/// @return Vector of non-null pointers to the current remote participants.
185-
/// The pointers are owned by the Room and remain valid until the
191+
/// @return Vector of weak handles to the current remote participants. Each
192+
/// handle can be promoted with @c lock(); a handle becomes empty once the
186193
/// corresponding participant disconnects or the room is torn down.
187-
std::vector<RemoteParticipant*> remoteParticipants() const;
194+
std::vector<std::weak_ptr<RemoteParticipant>> remoteParticipants() const;
188195

189196
/// Returns the current connection state of the room.
190197
ConnectionState connectionState() const;
@@ -247,13 +254,16 @@ class LIVEKIT_API Room {
247254
/// If no handler exists for the topic, this function is a no-op.
248255
void unregisterByteStreamHandler(const std::string& topic);
249256

250-
/// Returns the room's E2EE manager, or nullptr if E2EE was not enabled at
251-
/// connect time.
257+
/// Returns the room's E2EE manager as a weak handle, or an empty handle if
258+
/// E2EE was not enabled at connect time.
252259
///
253260
/// Notes:
254261
/// - The manager is created after a successful connect().
255-
/// - If E2EE was not configured in RoomOptions, this will return nullptr.
256-
E2EEManager* e2eeManager() const;
262+
/// - If E2EE was not configured in RoomOptions, @c lock() returns nullptr.
263+
/// - The handle also becomes empty once the room is torn down or destroyed.
264+
///
265+
/// @return Weak handle to the E2EE manager.
266+
std::weak_ptr<E2EEManager> e2eeManager() const;
257267

258268
// ---------------------------------------------------------------
259269
// Frame callbacks
@@ -293,15 +303,15 @@ class LIVEKIT_API Room {
293303
RoomDelegate* delegate_ = nullptr; // Not owned
294304
RoomInfoData room_info_;
295305
std::shared_ptr<FfiHandle> room_handle_;
296-
std::unique_ptr<LocalParticipant> local_participant_;
306+
std::shared_ptr<LocalParticipant> local_participant_;
297307
std::unordered_map<std::string, std::shared_ptr<RemoteParticipant>> remote_participants_;
298308
// Data stream
299309
std::unordered_map<std::string, TextStreamHandler> text_stream_handlers_;
300310
std::unordered_map<std::string, ByteStreamHandler> byte_stream_handlers_;
301311
std::unordered_map<std::string, std::shared_ptr<TextStreamReader>> text_stream_readers_;
302312
std::unordered_map<std::string, std::shared_ptr<ByteStreamReader>> byte_stream_readers_;
303313
// E2EE
304-
std::unique_ptr<E2EEManager> e2ee_manager_;
314+
std::shared_ptr<E2EEManager> e2ee_manager_;
305315
std::shared_ptr<SubscriptionThreadDispatcher> subscription_thread_dispatcher_;
306316

307317
// FfiClient listener ID (0 means no listener registered)

‎src/room.cpp‎

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ bool Room::connect(const std::string& url, const std::string& token, const RoomO
124124
auto new_room_info = fromProto(owned_room.info());
125125

126126
// Setup local particpant
127-
std::unique_ptr<LocalParticipant> new_local_participant;
127+
std::shared_ptr<LocalParticipant> new_local_participant;
128128
{
129129
const auto& owned_local = connectCb.result().local_participant();
130130
const auto& pinfo = owned_local.info();
@@ -141,7 +141,7 @@ bool Room::connect(const std::string& url, const std::string& token, const RoomO
141141
// Participant base stores a weak_ptr<FfiHandle>, so share the room handle
142142
FfiHandle participant_handle(static_cast<uintptr_t>(owned_local.handle().id()));
143143
new_local_participant =
144-
std::make_unique<LocalParticipant>(std::move(participant_handle), pinfo.sid(), pinfo.name(), pinfo.identity(),
144+
std::make_shared<LocalParticipant>(std::move(participant_handle), pinfo.sid(), pinfo.name(), pinfo.identity(),
145145
pinfo.metadata(), std::move(attrs), kind, reason);
146146
}
147147

@@ -164,11 +164,11 @@ bool Room::connect(const std::string& url, const std::string& token, const RoomO
164164
}
165165

166166
// Setup e2eeManager
167-
std::unique_ptr<E2EEManager> new_e2ee_manager;
167+
std::shared_ptr<E2EEManager> new_e2ee_manager;
168168
if (options.encryption) {
169169
LK_LOG_INFO("creating E2eeManager");
170170
new_e2ee_manager =
171-
std::unique_ptr<E2EEManager>(new E2EEManager(new_room_handle->get(), options.encryption.value()));
171+
std::shared_ptr<E2EEManager>(new E2EEManager(new_room_handle->get(), options.encryption.value()));
172172
}
173173

174174
// Publish all state atomically under lock
@@ -186,7 +186,7 @@ bool Room::connect(const std::string& url, const std::string& token, const RoomO
186186
return true;
187187
} catch (const std::exception& e) {
188188
int listener_to_remove = 0;
189-
std::unique_ptr<LocalParticipant> local_participant_to_cleanup;
189+
std::shared_ptr<LocalParticipant> local_participant_to_cleanup;
190190
{
191191
const std::scoped_lock<std::mutex> g(lock_);
192192
connection_state_ = ConnectionState::Disconnected;
@@ -299,23 +299,23 @@ RoomInfoData Room::roomInfo() const {
299299
return room_info_;
300300
}
301301

302-
LocalParticipant* Room::localParticipant() const {
302+
std::weak_ptr<LocalParticipant> Room::localParticipant() const {
303303
const std::scoped_lock<std::mutex> g(lock_);
304-
return local_participant_.get();
304+
return local_participant_;
305305
}
306306

307-
RemoteParticipant* Room::remoteParticipant(const std::string& identity) const {
307+
std::weak_ptr<RemoteParticipant> Room::remoteParticipant(const std::string& identity) const {
308308
const std::scoped_lock<std::mutex> g(lock_);
309309
auto it = remote_participants_.find(identity);
310-
return it == remote_participants_.end() ? nullptr : it->second.get();
310+
return it == remote_participants_.end() ? std::weak_ptr<RemoteParticipant>{} : it->second;
311311
}
312312

313-
std::vector<RemoteParticipant*> Room::remoteParticipants() const {
313+
std::vector<std::weak_ptr<RemoteParticipant>> Room::remoteParticipants() const {
314314
const std::scoped_lock<std::mutex> guard(lock_);
315-
std::vector<RemoteParticipant*> out;
315+
std::vector<std::weak_ptr<RemoteParticipant>> out;
316316
out.reserve(remote_participants_.size());
317317
for (const auto& kv : remote_participants_) {
318-
out.push_back(kv.second.get());
318+
out.push_back(kv.second);
319319
}
320320
return out;
321321
}
@@ -337,9 +337,9 @@ std::future<SessionStats> Room::getStats() const {
337337
return FfiClient::instance().getSessionStatsAsync(handle->get());
338338
}
339339

340-
E2EEManager* Room::e2eeManager() const {
340+
std::weak_ptr<E2EEManager> Room::e2eeManager() const {
341341
const std::scoped_lock<std::mutex> g(lock_);
342-
return e2ee_manager_.get();
342+
return e2ee_manager_;
343343
}
344344

345345
void Room::registerTextStreamHandler(const std::string& topic, TextStreamHandler handler) {
@@ -1211,10 +1211,10 @@ void Room::onEvent(const FfiEvent& event) {
12111211

12121212
// Move state out of lock scope before destroying to avoid holding lock
12131213
// during potentially long destructors
1214-
std::unique_ptr<LocalParticipant> old_local_participant;
1214+
std::shared_ptr<LocalParticipant> old_local_participant;
12151215
std::unordered_map<std::string, std::shared_ptr<RemoteParticipant>> old_remote_participants;
12161216
std::shared_ptr<FfiHandle> old_room_handle;
1217-
std::unique_ptr<E2EEManager> old_e2ee_manager;
1217+
std::shared_ptr<E2EEManager> old_e2ee_manager;
12181218
std::unordered_map<std::string, std::shared_ptr<TextStreamReader>> old_text_readers;
12191219
std::unordered_map<std::string, std::shared_ptr<ByteStreamReader>> old_byte_readers;
12201220

‎src/tests/common/test_common.h‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ inline uint64_t getTimestampUs() {
130130
inline bool waitForParticipant(Room* room, const std::string& identity, std::chrono::milliseconds timeout) {
131131
auto start = std::chrono::steady_clock::now();
132132
while (std::chrono::steady_clock::now() - start < timeout) {
133-
if (room->remoteParticipant(identity) != nullptr) {
133+
if (!room->remoteParticipant(identity).expired()) {
134134
return true;
135135
}
136136
std::this_thread::sleep_for(100ms);
@@ -161,18 +161,18 @@ inline void waitForParticipantVisibility(const std::vector<std::unique_ptr<Room>
161161
std::vector<std::string> participant_identities;
162162
participant_identities.reserve(rooms.size());
163163
for (const auto& room : rooms) {
164-
if (!room || room->localParticipant() == nullptr) {
164+
if (!room || room->localParticipant().expired()) {
165165
throw std::runtime_error("Test room is missing a local participant after connect");
166166
}
167-
participant_identities.push_back(room->localParticipant()->identity());
167+
participant_identities.push_back(room->localParticipant().lock()->identity());
168168
}
169169

170170
auto start = std::chrono::steady_clock::now();
171171
while (std::chrono::steady_clock::now() - start < timeout) {
172172
bool all_visible = true;
173173
for (size_t i = 0; i < rooms.size(); ++i) {
174174
const auto& room = rooms[i];
175-
if (!room || room->localParticipant() == nullptr) {
175+
if (!room || room->localParticipant().expired()) {
176176
throw std::runtime_error("Test room is missing a local participant after connect");
177177
}
178178

@@ -181,7 +181,7 @@ inline void waitForParticipantVisibility(const std::vector<std::unique_ptr<Room>
181181
continue;
182182
}
183183

184-
if (room->remoteParticipant(participant_identities[j]) == nullptr) {
184+
if (room->remoteParticipant(participant_identities[j]).expired()) {
185185
all_visible = false;
186186
break;
187187
}

0 commit comments

Comments
 (0)