Skip to content

Commit 98fd218

Browse files
address cancelled async future comments
1 parent 2bb8e13 commit 98fd218

7 files changed

Lines changed: 379 additions & 64 deletions

File tree

‎docs/capture-sources.md‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,9 @@ Invalid configurations produce `CaptureSourceError` when the returned future is
5252
awaited. For GStreamer, resolution and codec can be omitted to discover them from
5353
negotiated pipeline caps.
5454

55+
Discarding a creation future does not wait for creation to finish. Creation
56+
continues, and the source is released when the callback arrives.
57+
5558
```cpp
5659
#include <livekit/livekit.h>
5760

@@ -98,5 +101,7 @@ auto capture = livekit::CaptureSource::create(config).get();
98101
The optional rate-control binding forwards WebRTC bitrate targets to the named
99102
encoder property. Without it, the pipeline uses its configured fixed bitrate.
100103
Use `capture->publishOptions()` when publishing: encoded sources require the
101-
source's codec and encoder settings, which override conflicting application
102-
options.
104+
source's codec, the `PreEncoded` encoder, and disabled simulcast, which override
105+
conflicting application options. All other application options are preserved.
106+
Pattern and clock sources preserve every application option, including explicit
107+
codec and simulcast choices. Rust supplies defaults for fields left unset.

‎include/livekit/capture_source.h‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,8 @@ class LIVEKIT_API CaptureSource {
178178
/// for its first output to discover stream settings. Errors (invalid
179179
/// pipeline, missing capture feature, discovery timeout) are thrown from
180180
/// the future as @ref CaptureSourceError.
181+
/// Destroying the future does not wait for creation. The source is released
182+
/// when creation completes if the future was discarded.
181183
///
182184
/// @param config GStreamer pipeline configuration.
183185
/// @return A future that resolves to the created capture source.
@@ -188,6 +190,8 @@ class LIVEKIT_API CaptureSource {
188190
///
189191
/// Completes asynchronously after Rust initializes the GPU renderer.
190192
/// Keep the future to overlap setup with other work, or await it immediately.
193+
/// Destroying the future does not wait for creation; an abandoned result is
194+
/// released when creation completes.
191195
///
192196
/// @param config Pattern source configuration.
193197
/// @return A future that resolves to the created capture source.
@@ -198,6 +202,8 @@ class LIVEKIT_API CaptureSource {
198202
///
199203
/// Completes asynchronously after Rust initializes the GPU renderer.
200204
/// Keep the future to overlap setup with other work, or await it immediately.
205+
/// Destroying the future does not wait for creation; an abandoned result is
206+
/// released when creation completes.
201207
///
202208
/// @param config Clock source configuration.
203209
/// @return A future that resolves to the created capture source.
@@ -234,10 +240,10 @@ class LIVEKIT_API CaptureSource {
234240

235241
/// @brief Returns publish options for this track, applying application options.
236242
///
237-
/// Fields the source dictates (e.g. codec, encoder backend, and simulcast
238-
/// for encoded sources) are required for correct publication and override
239-
/// the application values; all other fields are taken from @p options
240-
/// unchanged.
243+
/// Encoded sources override codec with the source codec, select the
244+
/// PreEncoded encoder backend, and disable simulcast. All other fields are
245+
/// taken from @p options unchanged. Pixel sources preserve every application
246+
/// option; Rust supplies defaults for fields left unset.
241247
/// @param options Application publish options.
242248
/// @return Options with source-required fields applied.
243249
TrackPublishOptions publishOptions(TrackPublishOptions options = {}) const;
@@ -259,6 +265,8 @@ class LIVEKIT_API CaptureSource {
259265
bool stop();
260266

261267
private:
268+
friend class FfiClient;
269+
262270
CaptureSource();
263271

264272
/// @brief Shared creation path: sends the request and maps the callback payload

‎src/capture_source.cpp‎

Lines changed: 19 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
#include "livekit/capture_source.h"
1818

19+
#include <limits>
1920
#include <mutex>
2021
#include <stdexcept>
2122

@@ -24,7 +25,6 @@
2425
#include "ffi.pb.h"
2526
#include "ffi_client.h"
2627
#include "lk_log.h"
27-
#include "room_proto_converter.h"
2828

2929
namespace livekit {
3030

@@ -35,7 +35,6 @@ struct CaptureSource::Impl {
3535
int height = 0;
3636
std::optional<VideoCodec> codec;
3737
std::shared_ptr<VideoSource> video_source;
38-
TrackPublishOptions source_publish_options;
3938
std::mutex callback_mutex;
4039
FinishedCallback on_finished;
4140
int listener_id = 0;
@@ -182,42 +181,36 @@ proto::NewCaptureSourceRequest toProto(const ClockVideoSourceConfig& config) {
182181
std::future<std::shared_ptr<CaptureSource>> CaptureSource::createFromRequest(proto::NewCaptureSourceRequest request) {
183182
// A synchronous send failure is delivered through the
184183
// future rather than thrown from the factory.
185-
std::future<proto::OwnedCaptureSource> owned;
186184
try {
187-
owned = FfiClient::instance().newCaptureSourceAsync(std::move(request));
185+
return FfiClient::instance().newCaptureSourceAsync(std::move(request));
188186
} catch (const std::exception& e) {
189187
return readyCaptureError<std::shared_ptr<CaptureSource>>(e);
190188
}
191-
192-
// Map the FFI payload onto a wrapper once the callback resolves. A helper
193-
// thread keeps the returned future's wait semantics standard.
194-
return std::async(std::launch::async, [owned = std::move(owned)]() mutable {
195-
try {
196-
return fromOwned(owned.get());
197-
} catch (const CaptureSourceError&) {
198-
throw;
199-
} catch (const std::exception& e) {
200-
throw CaptureSourceError(e.what());
201-
}
202-
});
203189
}
204190

205191
std::shared_ptr<CaptureSource> CaptureSource::fromOwned(const proto::OwnedCaptureSource& owned) {
206192
const proto::CaptureSourceInfo& info = owned.info();
193+
// Guard both Rust-owned handles before validation or wrapper allocations.
194+
FfiHandle capture_handle_owner(static_cast<uintptr_t>(owned.handle().id()));
195+
FfiHandle video_handle_owner(static_cast<uintptr_t>(info.video_source().handle().id()));
196+
if (!owned.IsInitialized() || info.resolution().width() == 0 || info.resolution().height() == 0 ||
197+
info.resolution().width() > static_cast<std::uint32_t>(std::numeric_limits<int>::max()) ||
198+
info.resolution().height() > static_cast<std::uint32_t>(std::numeric_limits<int>::max()) ||
199+
(info.kind() == proto::CAPTURE_SOURCE_ENCODED && !info.has_codec())) {
200+
throw CaptureSourceError("Invalid capture source info");
201+
}
207202

208203
std::shared_ptr<CaptureSource> source(new CaptureSource());
209-
source->impl_->handle = FfiHandle(static_cast<uintptr_t>(owned.handle().id()));
204+
source->impl_->handle = std::move(capture_handle_owner);
210205
source->impl_->kind = info.kind() == proto::CaptureSourceKind::CAPTURE_SOURCE_ENCODED ? CaptureSourceKind::Encoded
211206
: CaptureSourceKind::Pixel;
212207
source->impl_->width = static_cast<int>(info.resolution().width());
213208
source->impl_->height = static_cast<int>(info.resolution().height());
214209
if (info.has_codec()) {
215210
source->impl_->codec = static_cast<VideoCodec>(info.codec());
216211
}
217-
source->impl_->source_publish_options = fromProto(info.recommended_publish_options());
218-
source->impl_->video_source =
219-
std::shared_ptr<VideoSource>(new VideoSource(FfiHandle(static_cast<uintptr_t>(info.video_source().handle().id())),
220-
source->impl_->width, source->impl_->height));
212+
source->impl_->video_source = std::shared_ptr<VideoSource>(
213+
new VideoSource(std::move(video_handle_owner), source->impl_->width, source->impl_->height));
221214

222215
// The terminal CaptureSourceEvent is unsolicited (not async-id
223216
// correlated); observe it with a listener filtered by our handle. The
@@ -244,23 +237,11 @@ std::shared_ptr<CaptureSource> CaptureSource::fromOwned(const proto::OwnedCaptur
244237
}
245238

246239
TrackPublishOptions CaptureSource::publishOptions(TrackPublishOptions options) const {
247-
const auto overlay = [](auto& target, const auto& source) {
248-
if (source.has_value()) {
249-
target = source;
250-
}
251-
};
252-
overlay(options.video_encoding, impl_->source_publish_options.video_encoding);
253-
overlay(options.audio_encoding, impl_->source_publish_options.audio_encoding);
254-
overlay(options.video_codec, impl_->source_publish_options.video_codec);
255-
overlay(options.dtx, impl_->source_publish_options.dtx);
256-
overlay(options.red, impl_->source_publish_options.red);
257-
overlay(options.simulcast, impl_->source_publish_options.simulcast);
258-
overlay(options.source, impl_->source_publish_options.source);
259-
overlay(options.stream, impl_->source_publish_options.stream);
260-
overlay(options.preconnect_buffer, impl_->source_publish_options.preconnect_buffer);
261-
overlay(options.frame_metadata_features, impl_->source_publish_options.frame_metadata_features);
262-
overlay(options.degradation_preference, impl_->source_publish_options.degradation_preference);
263-
overlay(options.video_encoder, impl_->source_publish_options.video_encoder);
240+
if (impl_->kind == CaptureSourceKind::Encoded) {
241+
options.video_codec = impl_->codec;
242+
options.video_encoder = VideoEncoderBackend::PreEncoded;
243+
options.simulcast = false;
244+
}
264245
return options;
265246
}
266247

‎src/ffi_client.cpp‎

Lines changed: 26 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
#include "data_track_proto_converter.h"
2727
#include "ffi.pb.h"
2828
#include "livekit/build.h"
29+
#include "livekit/capture_source.h"
2930
#include "livekit/data_track_error.h"
3031
#include "livekit/ffi_handle.h"
3132
#include "livekit/room.h"
@@ -463,12 +464,14 @@ bool FfiClient::cancelPendingByAsyncId(AsyncId async_id) {
463464

464465
template <typename T>
465466
std::future<T> FfiClient::registerAsync(AsyncId async_id, std::function<bool(const proto::FfiEvent&)> match,
466-
std::function<void(const proto::FfiEvent&, std::promise<T>&)> handler) {
467+
std::function<void(const proto::FfiEvent&, std::promise<T>&)> handler,
468+
std::exception_ptr cancellation_error) {
467469
auto pending = std::make_unique<Pending<T>>();
468470
pending->async_id = async_id;
469471
auto fut = pending->promise.get_future();
470472
pending->match = std::move(match);
471473
pending->handler = std::move(handler);
474+
pending->cancellation_error = std::move(cancellation_error);
472475
{
473476
const std::scoped_lock<std::mutex> guard(lock_);
474477
pending_by_id_.emplace(async_id, std::move(pending));
@@ -715,38 +718,44 @@ std::future<proto::OwnedTrackPublication> FfiClient::publishTrackAsync(std::uint
715718
return fut;
716719
}
717720

718-
std::future<proto::OwnedCaptureSource> FfiClient::newCaptureSourceAsync(proto::NewCaptureSourceRequest request) {
721+
std::future<std::shared_ptr<CaptureSource>> FfiClient::newCaptureSourceAsync(
722+
proto::NewCaptureSourceRequest request, const std::function<proto::FfiResponse(const proto::FfiRequest&)>& send) {
719723
// Generate client-side async_id first
720724
const AsyncId async_id = generateAsyncId();
721725

722726
// Register the async handler BEFORE sending the request
723-
auto fut = registerAsync<proto::OwnedCaptureSource>(
727+
auto fut = registerAsync<std::shared_ptr<CaptureSource>>(
724728
async_id,
725729
[async_id](const proto::FfiEvent& event) {
726730
return event.has_new_capture_source() && event.new_capture_source().async_id() == async_id;
727731
},
728-
[](const proto::FfiEvent& event, std::promise<proto::OwnedCaptureSource>& pr) {
732+
[](const proto::FfiEvent& event, std::promise<std::shared_ptr<CaptureSource>>& pr) {
729733
const auto& cb = event.new_capture_source();
730-
731-
// Oneof message { string error = 2; OwnedCaptureSource source = 3; }
732-
if (cb.has_error() && !cb.error().empty()) {
733-
pr.set_exception(std::make_exception_ptr(std::runtime_error(cb.error())));
734-
return;
735-
}
736-
if (!cb.has_source()) {
737-
pr.set_exception(std::make_exception_ptr(std::runtime_error("NewCaptureSourceCallback missing source")));
738-
return;
734+
try {
735+
if (cb.has_error()) {
736+
throw CaptureSourceError(cb.error());
737+
}
738+
if (!cb.has_source()) {
739+
throw CaptureSourceError("NewCaptureSourceCallback missing source");
740+
}
741+
// Adopt the handles before satisfying the promise. If the caller has
742+
// discarded its future, destroying the pending promise releases the
743+
// wrapper and both handles after this callback completes.
744+
pr.set_value(CaptureSource::fromOwned(cb.source()));
745+
} catch (const std::exception& error) {
746+
pr.set_exception(std::make_exception_ptr(CaptureSourceError(error.what())));
747+
} catch (...) {
748+
pr.set_exception(std::make_exception_ptr(CaptureSourceError("Capture source construction failed")));
739749
}
740-
741-
pr.set_value(cb.source());
742-
});
750+
},
751+
std::make_exception_ptr(CaptureSourceError("Async operation cancelled")));
743752

744753
request.set_request_async_id(async_id);
745754
proto::FfiRequest req;
746755
req.mutable_new_capture_source()->CopyFrom(request);
747756

748757
try {
749-
const proto::FfiResponse resp = sendRequest(req);
758+
const proto::FfiResponse resp = send ? send(req) : sendRequest(req);
750759
if (!resp.has_new_capture_source()) {
751760
logAndThrow("FfiResponse missing new_capture_source");
752761
}

‎src/ffi_client.h‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ class DataStream;
5858

5959
struct RoomOptions;
6060
struct TrackPublishOptions;
61+
class CaptureSource;
6162

6263
using FfiCallbackFn = void (*)(const uint8_t*, size_t);
6364
extern "C" void livekit_ffi_initialize(FfiCallbackFn cb, bool capture_logs, const char* sdk, const char* sdk_version);
@@ -121,7 +122,11 @@ class LIVEKIT_INTERNAL_API FfiClient {
121122
const std::vector<std::string>& destination_identities);
122123

123124
// Capture APIs
124-
std::future<proto::OwnedCaptureSource> newCaptureSourceAsync(proto::NewCaptureSourceRequest request);
125+
// Optional request transport permits deterministic callback tests without
126+
// starting a GPU renderer or GStreamer pipeline.
127+
std::future<std::shared_ptr<CaptureSource>> newCaptureSourceAsync(
128+
proto::NewCaptureSourceRequest request,
129+
const std::function<proto::FfiResponse(const proto::FfiRequest&)>& send = {});
125130
std::future<void> setLocalMetadataAsync(std::uint64_t local_participant_handle, const std::string& metadata);
126131
std::future<void> captureAudioFrameAsync(std::uint64_t source_handle, const proto::AudioFrameBufferInfo& buffer);
127132
std::future<std::string> performRpcAsync(std::uint64_t local_participant_handle,
@@ -162,6 +167,8 @@ class LIVEKIT_INTERNAL_API FfiClient {
162167
proto::FfiResponse sendRequest(const proto::FfiRequest& request) const;
163168

164169
private:
170+
friend struct FfiClientTestAccess;
171+
165172
FfiClient() = default;
166173

167174
/// Lifecycle state of the FfiClient
@@ -186,14 +193,17 @@ class LIVEKIT_INTERNAL_API FfiClient {
186193
std::promise<T> promise;
187194
std::function<bool(const proto::FfiEvent&)> match;
188195
std::function<void(const proto::FfiEvent&, std::promise<T>&)> handler;
196+
std::exception_ptr cancellation_error;
189197

190198
bool matches(const proto::FfiEvent& event) const override { return match && match(event); }
191199

192200
void complete(const proto::FfiEvent& event) override { handler(event, promise); }
193201

194202
void cancel() override {
195203
try {
196-
promise.set_exception(std::make_exception_ptr(std::runtime_error("Async operation cancelled")));
204+
promise.set_exception(cancellation_error
205+
? cancellation_error
206+
: std::make_exception_ptr(std::runtime_error("Async operation cancelled")));
197207
} catch (const std::future_error& e) {
198208
// Unlikely to throw here as the promise should be satisfied before
199209
// cancel() Logging a debug message to avoid clang empty catch warning
@@ -223,7 +233,8 @@ class LIVEKIT_INTERNAL_API FfiClient {
223233

224234
template <typename T>
225235
std::future<T> registerAsync(AsyncId async_id, std::function<bool(const proto::FfiEvent&)> match,
226-
std::function<void(const proto::FfiEvent&, std::promise<T>&)> handler);
236+
std::function<void(const proto::FfiEvent&, std::promise<T>&)> handler,
237+
std::exception_ptr cancellation_error = {});
227238

228239
// Generate a unique client-side async ID for request correlation
229240
AsyncId generateAsyncId();

‎src/tests/CMakeLists.txt‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ if(UNIT_TEST_SOURCES)
8989
target_link_libraries(livekit_unit_tests
9090
PRIVATE
9191
livekit
92+
livekit_ffi # Capture ownership tests verify Rust handle disposal directly.
9293
spdlog::spdlog
9394
${LIVEKIT_PROTOBUF_TARGET}
9495
GTest::gtest_main
@@ -104,6 +105,7 @@ if(UNIT_TEST_SOURCES)
104105
${LIVEKIT_TEST_PROTOBUF_DEP_INCLUDE_DIRS}
105106
)
106107
target_include_directories(livekit_unit_tests SYSTEM PRIVATE
108+
${LIVEKIT_ROOT_DIR}/client-sdk-rust/livekit-ffi/include
107109
${LIVEKIT_TEST_SYSTEM_INCLUDE_DIRS}
108110
)
109111

0 commit comments

Comments
 (0)