Skip to content

Commit 24f3bd6

Browse files
participants raw ptr -> weak_ptr
test that participant handles are expired after disconnect
1 parent 3981c2a commit 24f3bd6

22 files changed

Lines changed: 318 additions & 200 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
@@ -148,27 +148,34 @@ class LIVEKIT_API Room {
148148
/// - published tracks (audio/video/screen)
149149
/// - identity, SID, metadata
150150
/// - publishing/unpublishing operations
151-
/// @return Non-null pointer while connected; nullptr before connect, after
152-
/// room end-of-stream teardown, or when the room is destroyed.
153-
LocalParticipant* localParticipant() const;
151+
///
152+
/// The returned handle is non-owning. Call @c lock() to obtain a usable
153+
/// @c weak_ptr; the result is empty (`lock() == nullptr`) before connect,
154+
/// after room end-of-stream teardown, or once the room is destroyed. This
155+
/// lets callers that cache the handle detect teardown instead of holding a
156+
/// dangling pointer.
157+
///
158+
/// @return Weak handle to the local participant.
159+
std::weak_ptr<LocalParticipant> localParticipant() const;
154160

155161
/// Look up a remote participant by identity.
156162
///
157-
/// @param identity The participant’s identity string (not SID)
158-
/// @return Pointer to RemoteParticipant if present, otherwise nullptr (also
159-
/// nullptr after room teardown or when the room is destroyed).
160-
/// RemoteParticipant contains:
163+
/// @param identity The participant’s identity string (not SID).
164+
/// @return Weak handle to the RemoteParticipant if present, otherwise an
165+
/// empty handle (`lock() == nullptr`). The handle also becomes empty once
166+
/// the participant disconnects, the room is torn down, or the room is
167+
/// destroyed. RemoteParticipant contains:
161168
/// - identity/name/metadata
162169
/// - track publications
163-
/// - callbacks for track subscribed/unsubscribed, muted/unmuted
164-
RemoteParticipant* remoteParticipant(const std::string& identity) const;
170+
/// - callbacks for track subscribed/unsubscribed, muted/unmuted
171+
std::weak_ptr<RemoteParticipant> remoteParticipant(const std::string& identity) const;
165172

166173
/// Returns a snapshot of all current remote participants.
167174
///
168-
/// @return Vector of non-null pointers to the current remote participants.
169-
/// The pointers are owned by the Room and remain valid until the
175+
/// @return Vector of weak handles to the current remote participants. Each
176+
/// handle can be promoted with @c lock(); a handle becomes empty once the
170177
/// corresponding participant disconnects or the room is torn down.
171-
std::vector<RemoteParticipant*> remoteParticipants() const;
178+
std::vector<std::weak_ptr<RemoteParticipant>> remoteParticipants() const;
172179

173180
/// Returns the current connection state of the room.
174181
ConnectionState connectionState() const;
@@ -231,13 +238,16 @@ class LIVEKIT_API Room {
231238
/// If no handler exists for the topic, this function is a no-op.
232239
void unregisterByteStreamHandler(const std::string& topic);
233240

234-
/// Returns the room's E2EE manager, or nullptr if E2EE was not enabled at
235-
/// connect time.
241+
/// Returns the room's E2EE manager as a weak handle, or an empty handle if
242+
/// E2EE was not enabled at connect time.
236243
///
237244
/// Notes:
238245
/// - The manager is created after a successful connect().
239-
/// - If E2EE was not configured in RoomOptions, this will return nullptr.
240-
E2EEManager* e2eeManager() const;
246+
/// - If E2EE was not configured in RoomOptions, @c lock() returns nullptr.
247+
/// - The handle also becomes empty once the room is torn down or destroyed.
248+
///
249+
/// @return Weak handle to the E2EE manager.
250+
std::weak_ptr<E2EEManager> e2eeManager() const;
241251

242252
// ---------------------------------------------------------------
243253
// Frame callbacks
@@ -277,15 +287,15 @@ class LIVEKIT_API Room {
277287
RoomDelegate* delegate_ = nullptr; // Not owned
278288
RoomInfoData room_info_;
279289
std::shared_ptr<FfiHandle> room_handle_;
280-
std::unique_ptr<LocalParticipant> local_participant_;
290+
std::shared_ptr<LocalParticipant> local_participant_;
281291
std::unordered_map<std::string, std::shared_ptr<RemoteParticipant>> remote_participants_;
282292
// Data stream
283293
std::unordered_map<std::string, TextStreamHandler> text_stream_handlers_;
284294
std::unordered_map<std::string, ByteStreamHandler> byte_stream_handlers_;
285295
std::unordered_map<std::string, std::shared_ptr<TextStreamReader>> text_stream_readers_;
286296
std::unordered_map<std::string, std::shared_ptr<ByteStreamReader>> byte_stream_readers_;
287297
// E2EE
288-
std::unique_ptr<E2EEManager> e2ee_manager_;
298+
std::shared_ptr<E2EEManager> e2ee_manager_;
289299
std::shared_ptr<SubscriptionThreadDispatcher> subscription_thread_dispatcher_;
290300

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

‎src/room.cpp‎

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -81,14 +81,14 @@ Room::~Room() {
8181
}
8282

8383
int listener_to_remove = 0;
84-
std::unique_ptr<LocalParticipant> local_participant_to_cleanup;
84+
std::shared_ptr<LocalParticipant> local_participant_to_cleanup;
8585
std::unordered_map<std::string, std::shared_ptr<RemoteParticipant>> remote_participants_to_cleanup;
8686
{
8787
const std::scoped_lock<std::mutex> g(lock_);
8888
listener_to_remove = listener_id_;
8989
listener_id_ = 0;
9090
connection_state_ = ConnectionState::Disconnected;
91-
// Move participant state out so accessors return nullptr during teardown.
91+
// Move participant state out so weak handles expire during teardown.
9292
local_participant_to_cleanup = std::move(local_participant_);
9393
remote_participants_to_cleanup = std::move(remote_participants_);
9494
room_handle_.reset();
@@ -149,7 +149,7 @@ bool Room::connect(const std::string& url, const std::string& token, const RoomO
149149
auto new_room_info = fromProto(owned_room.info());
150150

151151
// Setup local particpant
152-
std::unique_ptr<LocalParticipant> new_local_participant;
152+
std::shared_ptr<LocalParticipant> new_local_participant;
153153
{
154154
const auto& owned_local = connectCb.result().local_participant();
155155
const auto& pinfo = owned_local.info();
@@ -166,7 +166,7 @@ bool Room::connect(const std::string& url, const std::string& token, const RoomO
166166
// Participant base stores a weak_ptr<FfiHandle>, so share the room handle
167167
FfiHandle participant_handle(static_cast<uintptr_t>(owned_local.handle().id()));
168168
new_local_participant =
169-
std::make_unique<LocalParticipant>(std::move(participant_handle), pinfo.sid(), pinfo.name(), pinfo.identity(),
169+
std::make_shared<LocalParticipant>(std::move(participant_handle), pinfo.sid(), pinfo.name(), pinfo.identity(),
170170
pinfo.metadata(), std::move(attrs), kind, reason);
171171
}
172172

@@ -189,11 +189,11 @@ bool Room::connect(const std::string& url, const std::string& token, const RoomO
189189
}
190190

191191
// Setup e2eeManager
192-
std::unique_ptr<E2EEManager> new_e2ee_manager;
192+
std::shared_ptr<E2EEManager> new_e2ee_manager;
193193
if (options.encryption) {
194194
LK_LOG_INFO("creating E2eeManager");
195195
new_e2ee_manager =
196-
std::unique_ptr<E2EEManager>(new E2EEManager(new_room_handle->get(), options.encryption.value()));
196+
std::shared_ptr<E2EEManager>(new E2EEManager(new_room_handle->get(), options.encryption.value()));
197197
}
198198

199199
// Publish all state atomically under lock
@@ -211,7 +211,7 @@ bool Room::connect(const std::string& url, const std::string& token, const RoomO
211211
return true;
212212
} catch (const std::exception& e) {
213213
int listener_to_remove = 0;
214-
std::unique_ptr<LocalParticipant> local_participant_to_cleanup;
214+
std::shared_ptr<LocalParticipant> local_participant_to_cleanup;
215215
{
216216
const std::scoped_lock<std::mutex> g(lock_);
217217
connection_state_ = ConnectionState::Disconnected;
@@ -242,23 +242,23 @@ RoomInfoData Room::roomInfo() const {
242242
return room_info_;
243243
}
244244

245-
LocalParticipant* Room::localParticipant() const {
245+
std::weak_ptr<LocalParticipant> Room::localParticipant() const {
246246
const std::scoped_lock<std::mutex> g(lock_);
247-
return local_participant_.get();
247+
return local_participant_;
248248
}
249249

250-
RemoteParticipant* Room::remoteParticipant(const std::string& identity) const {
250+
std::weak_ptr<RemoteParticipant> Room::remoteParticipant(const std::string& identity) const {
251251
const std::scoped_lock<std::mutex> g(lock_);
252252
auto it = remote_participants_.find(identity);
253-
return it == remote_participants_.end() ? nullptr : it->second.get();
253+
return it == remote_participants_.end() ? std::weak_ptr<RemoteParticipant>{} : it->second;
254254
}
255255

256-
std::vector<RemoteParticipant*> Room::remoteParticipants() const {
256+
std::vector<std::weak_ptr<RemoteParticipant>> Room::remoteParticipants() const {
257257
const std::scoped_lock<std::mutex> guard(lock_);
258-
std::vector<RemoteParticipant*> out;
258+
std::vector<std::weak_ptr<RemoteParticipant>> out;
259259
out.reserve(remote_participants_.size());
260260
for (const auto& kv : remote_participants_) {
261-
out.push_back(kv.second.get());
261+
out.push_back(kv.second);
262262
}
263263
return out;
264264
}
@@ -280,9 +280,9 @@ std::future<SessionStats> Room::getStats() const {
280280
return FfiClient::instance().getSessionStatsAsync(handle->get());
281281
}
282282

283-
E2EEManager* Room::e2eeManager() const {
283+
std::weak_ptr<E2EEManager> Room::e2eeManager() const {
284284
const std::scoped_lock<std::mutex> g(lock_);
285-
return e2ee_manager_.get();
285+
return e2ee_manager_;
286286
}
287287

288288
void Room::registerTextStreamHandler(const std::string& topic, TextStreamHandler handler) {
@@ -1143,10 +1143,10 @@ void Room::onEvent(const FfiEvent& event) {
11431143

11441144
// Move state out of lock scope before destroying to avoid holding lock
11451145
// during potentially long destructors
1146-
std::unique_ptr<LocalParticipant> old_local_participant;
1146+
std::shared_ptr<LocalParticipant> old_local_participant;
11471147
std::unordered_map<std::string, std::shared_ptr<RemoteParticipant>> old_remote_participants;
11481148
std::shared_ptr<FfiHandle> old_room_handle;
1149-
std::unique_ptr<E2EEManager> old_e2ee_manager;
1149+
std::shared_ptr<E2EEManager> old_e2ee_manager;
11501150
std::unordered_map<std::string, std::shared_ptr<TextStreamReader>> old_text_readers;
11511151
std::unordered_map<std::string, std::shared_ptr<ByteStreamReader>> old_byte_readers;
11521152

‎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)