Skip to content

Commit 709ac96

Browse files
CaptureErrorKind when applicable, exception when not
1 parent 67b3c5a commit 709ac96

10 files changed

Lines changed: 585 additions & 291 deletions

File tree

‎docs/building.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -443,7 +443,7 @@ The build scripts set `LIVEKIT_CAPTURE`. The generated numeric
443443
It indicates whether any source was compiled in; it does not identify which
444444
sources are available. Check `cargo_features` in `share/livekit/build-info.json`
445445
for the selected backends. Creating a source omitted from the SDK build fails
446-
through the returned future with `CaptureSourceError`.
446+
through the returned future with `std::runtime_error`.
447447
Capture-enabled bundles install the public API under `include/livekit/capture/`;
448448
standard bundles omit that directory. Use `<livekit/capture/capture_source.h>`
449449
for direct inclusion. The source-tree header also rejects use in a standard

‎docs/capture-sources.md‎

Lines changed: 73 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ A custom SDK build can include all sources or a subset selected with
1616
`--capture=pattern,clock` or `--capture=gstreamer`. Release `-capture` bundles
1717
include all sources. `LIVEKIT_CAPTURE_ENABLED` indicates that at least one
1818
source is enabled; creating a source omitted from the build reports
19-
`CaptureSourceError` through the returned future. Pattern/clock-only builds do
19+
a `std::runtime_error` through the returned future. Pattern/clock-only builds do
2020
not require GStreamer.
2121

2222
Native camera device capture and device enumeration are not part of this API.
@@ -39,9 +39,10 @@ headers do not name it.
3939
## Create and publish a source
4040

4141
Dimensions must be positive. Pattern and clock frame rates must also be positive.
42-
Invalid configurations produce `CaptureSourceError` when the returned future is
43-
awaited. For GStreamer, resolution and codec can be omitted to discover them from
44-
negotiated pipeline caps.
42+
Invalid C++ configurations throw `std::invalid_argument` when the returned
43+
future is awaited. For GStreamer, resolution and codec can be omitted to discover
44+
them from negotiated pipeline caps. Producer setup failures reported by Rust
45+
throw `std::runtime_error` through that future.
4546

4647
Discarding a creation future does not wait for creation to finish. Creation
4748
continues, and the source is released when the callback arrives.
@@ -51,26 +52,34 @@ continues, and the source is released when the callback arrives.
5152
#include <livekit/capture/capture_source.h>
5253

5354
// The SDK is initialized, and room is connected.
54-
auto pending = livekit::capture::CaptureSource::create(
55-
livekit::capture::PatternVideoSourceConfig{{1280, 720}, 30, livekit::capture::Pattern::Gradient});
56-
// Other application setup can run while the producer is being constructed.
57-
auto capture = pending.get();
58-
// For a wall clock, use ClockVideoSourceConfig{{1280, 720}, 30} instead.
59-
60-
auto track = livekit::LocalVideoTrack::createLocalVideoTrack("capture", capture->videoSource());
61-
auto participant = room.localParticipant().lock();
62-
if (!participant) {
63-
return;
55+
try {
56+
auto pending = livekit::capture::CaptureSource::create(
57+
livekit::capture::PatternVideoSourceConfig{{1280, 720}, 30, livekit::capture::Pattern::Gradient});
58+
// Other application setup can run while the producer is being constructed.
59+
auto capture = pending.get().value();
60+
// For a wall clock, use ClockVideoSourceConfig{{1280, 720}, 30} instead.
61+
62+
auto track = livekit::LocalVideoTrack::createLocalVideoTrack("capture", capture->videoSource());
63+
auto participant = room.localParticipant().lock();
64+
if (!participant) {
65+
return;
66+
}
67+
participant->publishTrack(track, capture->publishOptions());
68+
capture->start().value(); // Rust rejection or a binding failure throws.
69+
70+
// Later, when shutting down:
71+
capture->stop().value(); // Signals without waiting.
72+
auto result = capture->join().get(); // Waits for cleanup.
73+
if (!result) {
74+
// Handle result.error().kind and result.error().message: a typed pump failure.
75+
return;
76+
}
77+
auto stats = result.value(); // frames_captured and exit.
78+
} catch (const std::invalid_argument& error) {
79+
// Handle an invalid C++ capture configuration using error.what().
80+
} catch (const std::runtime_error& error) {
81+
// Handle setup, control, transport, protocol, or shutdown failure using error.what().
6482
}
65-
participant->publishTrack(track, capture->publishOptions());
66-
67-
if (!capture->start()) {
68-
// Handle the start failure.
69-
}
70-
71-
// Later, when shutting down:
72-
capture->stop(); // Signals without waiting.
73-
auto result = capture->join().get(); // Waits for cleanup and returns statistics.
7483
```
7584

7685
Keep `capture` alive while its track is published. `stop()` signals the pump to
@@ -90,7 +99,8 @@ config.pipeline = "videotestsrc ! video/x-raw,width=1280,height=720,framerate=30
9099
"vp8enc name=lk_encoder deadline=1 ! appsink name=lk_appsink";
91100
config.rate_control = livekit::capture::GstreamerRateControl{
92101
"lk_encoder", "target-bitrate", livekit::capture::GstreamerBitrateUnit::Bps};
93-
auto capture = livekit::capture::CaptureSource::create(config).get();
102+
// Use the exception handling shown above for configuration and setup failures.
103+
auto capture = livekit::capture::CaptureSource::create(config).get().value();
94104
```
95105
96106
The optional rate-control binding forwards WebRTC bitrate targets to the named
@@ -100,3 +110,42 @@ source's codec, the `PreEncoded` encoder, and disabled simulcast, which override
100110
conflicting application options. All other application options are preserved.
101111
Pattern and clock sources preserve every application option, including explicit
102112
codec and simulcast choices. Rust supplies defaults for fields left unset.
113+
114+
## Error contract
115+
116+
`CaptureErrorKind` matches the protobuf enum exactly:
117+
118+
| C++ value | Protobuf value | Meaning |
119+
| --- | --- | --- |
120+
| `Source = 0` | `CAPTURE_ERROR_KIND_SOURCE = 0` | The running capture source failed or violated its contract. |
121+
| `Rtc = 1` | `CAPTURE_ERROR_KIND_RTC = 1` | The RTC source rejected a frame. |
122+
| `Panicked = 2` | `CAPTURE_ERROR_KIND_PANICKED = 2` | The pump thread panicked. |
123+
124+
A structured pump error received from Rust becomes a failed
125+
`Result<CaptureResult, CaptureError>` from `join()`. Its message and kind are
126+
preserved. Check the result before calling `value()` or `error()`.
127+
128+
Failures without a protobuf error kind throw a clear exception with the operation
129+
name and diagnostic. C++ configuration validation throws `std::invalid_argument`.
130+
Uninitialized SDK use, transport failures, malformed responses, shutdown
131+
cancellation, and untyped errors from Rust throw `std::runtime_error`.
132+
`create()` and `join()` deliver these exceptions from the returned future's
133+
`get()`; `start()` and `stop()` throw directly. Exceptions are captured at the
134+
FFI callback boundary. They never unwind through Rust callbacks.
135+
136+
| Operation | Return type | Failure handling |
137+
| --- | --- | --- |
138+
| `create(config)` | `std::future<Result<std::shared_ptr<CaptureSource>, CaptureError>>` | Configuration and untyped setup errors throw from `get()`. |
139+
| `start()` / `stop()` | `Result<void, CaptureError>` | Current control responses carry untyped strings, so rejection throws directly. |
140+
| `join()` | `std::future<Result<CaptureResult, CaptureError>>` | Structured pump errors use `error()`; binding failures throw from `get()`. |
141+
142+
`CaptureResult` contains successful statistics only. Creation and control return
143+
successful results when their requests succeed; the current protocol supplies
144+
structured error kinds only for the terminal pump result. The SDK does not
145+
classify untyped Rust messages by parsing their text. Allocation failures may
146+
also throw.
147+
148+
This replaces the unreleased C++-only error categories. Code that handled
149+
`InvalidConfiguration`, `NotInitialized`, `Rejected`, `Transport`, `Protocol`, or
150+
`Cancelled` as enum values must now catch the corresponding exception. Existing
151+
`Source`, `Rtc`, and `Panicked` pump-error handling remains unchanged.

‎include/livekit/capture/capture_source.h‎

Lines changed: 54 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,9 @@
2727
#include <future>
2828
#include <memory>
2929
#include <optional>
30-
#include <stdexcept>
3130
#include <string>
3231

32+
#include "livekit/result.h"
3333
#include "livekit/room_event_types.h"
3434
#include "livekit/video_source.h"
3535
#include "livekit/visibility.h"
@@ -47,15 +47,6 @@ class OwnedCaptureSource;
4747
/// @brief Capture sources and their configuration types.
4848
namespace livekit::capture {
4949

50-
/// @brief Error raised when capture source creation or control fails.
51-
class LIVEKIT_API CaptureSourceError : public std::runtime_error {
52-
public:
53-
/// @brief Create a capture source error.
54-
///
55-
/// @param message Human-readable error message.
56-
explicit CaptureSourceError(const std::string& message) : std::runtime_error(message) {}
57-
};
58-
5950
/// @brief Kind of media a capture source produces.
6051
enum class CaptureSourceKind {
6152
/// @brief Pixel frames, published through the WebRTC encoder.
@@ -151,7 +142,7 @@ enum class CaptureExit {
151142
EndOfStream = 1,
152143
};
153144

154-
/// @brief Why a capture ended with an error.
145+
/// @brief Terminal pump failure category; matches the FFI CaptureErrorKind enum.
155146
enum class CaptureErrorKind {
156147
/// @brief The capture source failed or violated its contract.
157148
Source = 0,
@@ -161,7 +152,7 @@ enum class CaptureErrorKind {
161152
Panicked = 2,
162153
};
163154

164-
/// @brief Terminal capture failure.
155+
/// @brief Structured terminal pump failure reported by the Rust FFI.
165156
struct CaptureError {
166157
/// @brief Human-readable error message.
167158
std::string message;
@@ -170,15 +161,12 @@ struct CaptureError {
170161
CaptureErrorKind kind = CaptureErrorKind::Source;
171162
};
172163

173-
/// @brief Terminal result of a started capture.
164+
/// @brief Successful terminal statistics of a started capture.
174165
struct CaptureResult {
175-
/// @brief Failure details when the capture failed; empty on success.
176-
std::optional<CaptureError> error;
177-
178166
/// @brief Number of frames or access units captured.
179167
std::uint64_t frames_captured = 0;
180168

181-
/// Why the capture ended; meaningful only when @ref error is empty.
169+
/// @brief Why the capture ended successfully.
182170
CaptureExit exit = CaptureExit::Stopped;
183171
};
184172

@@ -190,6 +178,12 @@ struct CaptureResult {
190178
/// a track from @ref CaptureSource::videoSource(), merge application options
191179
/// through @ref CaptureSource::publishOptions(), then call @ref CaptureSource::start().
192180
///
181+
/// Structured pump failures are returned as Result values containing @ref CaptureError.
182+
/// Failures without a protobuf error kind throw exceptions. Invalid C++ input
183+
/// throws std::invalid_argument; initialization, transport, protocol, cancellation,
184+
/// and untyped Rust failures throw std::runtime_error. For create() and join(),
185+
/// these exceptions are delivered when awaiting the future.
186+
///
193187
/// Requires a capture-enabled SDK build (`LIVEKIT_CAPTURE`). Creation fails
194188
/// when the requested source was not compiled into the Rust FFI.
195189
///
@@ -200,16 +194,20 @@ class LIVEKIT_API CaptureSource {
200194
/// @brief Create a capture source from a GStreamer pipeline configuration.
201195
///
202196
/// Completes asynchronously: construction starts the pipeline and may wait
203-
/// for its first output to discover stream settings. Errors (invalid
204-
/// pipeline, missing capture feature, discovery timeout) are thrown from
205-
/// the future as @ref CaptureSourceError.
197+
/// for its first output to discover stream settings. Configuration, producer
198+
/// setup, transport, protocol, and cancellation failures are delivered as
199+
/// exceptions through the future.
206200
/// Destroying the future does not wait for creation. The source is released
207201
/// when creation completes if the future was discarded.
208202
///
209203
/// @param config GStreamer pipeline configuration.
210-
/// @return A future that resolves to the created capture source.
211-
/// @throws CaptureSourceError When awaiting the future if creation fails.
212-
static std::future<std::shared_ptr<CaptureSource>> create(const GstreamerVideoSourceConfig& config);
204+
/// @return A future containing a successful Result with the created source.
205+
/// @throws std::invalid_argument When awaiting the future if the C++ configuration is invalid.
206+
/// @throws std::runtime_error When awaiting the future if setup, initialization,
207+
/// transport, protocol validation, or cancellation fails.
208+
/// @throws std::bad_alloc If allocation fails, including when awaiting the future.
209+
[[nodiscard]] static std::future<Result<std::shared_ptr<CaptureSource>, CaptureError>> create(
210+
const GstreamerVideoSourceConfig& config);
213211

214212
/// @brief Create the built-in test pattern capture source.
215213
///
@@ -219,9 +217,13 @@ class LIVEKIT_API CaptureSource {
219217
/// released when creation completes.
220218
///
221219
/// @param config Pattern source configuration.
222-
/// @return A future that resolves to the created capture source.
223-
/// @throws CaptureSourceError When awaiting the future if creation fails.
224-
static std::future<std::shared_ptr<CaptureSource>> create(PatternVideoSourceConfig config);
220+
/// @return A future containing a successful Result with the created source.
221+
/// @throws std::invalid_argument When awaiting the future if the C++ configuration is invalid.
222+
/// @throws std::runtime_error When awaiting the future if setup, initialization,
223+
/// transport, protocol validation, or cancellation fails.
224+
/// @throws std::bad_alloc If allocation fails, including when awaiting the future.
225+
[[nodiscard]] static std::future<Result<std::shared_ptr<CaptureSource>, CaptureError>> create(
226+
PatternVideoSourceConfig config);
225227

226228
/// @brief Create the built-in wall clock capture source.
227229
///
@@ -231,9 +233,13 @@ class LIVEKIT_API CaptureSource {
231233
/// released when creation completes.
232234
///
233235
/// @param config Clock source configuration.
234-
/// @return A future that resolves to the created capture source.
235-
/// @throws CaptureSourceError When awaiting the future if creation fails.
236-
static std::future<std::shared_ptr<CaptureSource>> create(ClockVideoSourceConfig config);
236+
/// @return A future containing a successful Result with the created source.
237+
/// @throws std::invalid_argument When awaiting the future if the C++ configuration is invalid.
238+
/// @throws std::runtime_error When awaiting the future if setup, initialization,
239+
/// transport, protocol validation, or cancellation fails.
240+
/// @throws std::bad_alloc If allocation fails, including when awaiting the future.
241+
[[nodiscard]] static std::future<Result<std::shared_ptr<CaptureSource>, CaptureError>> create(
242+
ClockVideoSourceConfig config);
237243

238244
~CaptureSource();
239245

@@ -275,35 +281,46 @@ class LIVEKIT_API CaptureSource {
275281

276282
/// @brief Start pumping frames into the RTC video source.
277283
///
278-
/// @return @c true if the start request succeeds; otherwise @c false.
279-
bool start();
284+
/// @return A successful Result when Rust acknowledges the request.
285+
/// @throws std::runtime_error If the SDK is not initialized, Rust rejects the
286+
/// request, or transport or protocol validation fails.
287+
/// @throws std::bad_alloc If memory allocation fails.
288+
[[nodiscard]] Result<void, CaptureError> start();
280289

281290
/// @brief Signal a running capture to stop after the frame in flight.
282291
///
283292
/// This method does not wait for the pump thread to exit. Call @ref join()
284293
/// to synchronize and retrieve the terminal result. Stopping an
285294
/// already-finished capture is a no-op.
286295
///
287-
/// @return @c true if the stop request succeeds; otherwise @c false.
288-
bool stop();
296+
/// @return A successful Result when Rust acknowledges the request.
297+
/// @throws std::runtime_error If the SDK is not initialized, Rust rejects the
298+
/// request, or transport or protocol validation fails.
299+
/// @throws std::bad_alloc If memory allocation fails.
300+
[[nodiscard]] Result<void, CaptureError> stop();
289301

290302
/// @brief Consume the running pump and wait asynchronously for it to exit.
291303
///
292304
/// This method does not signal the pump to stop. Call @ref stop() first when
293305
/// ending an unbounded source. Join may be called only once after a
294306
/// successful @ref start().
295307
///
296-
/// @return A future containing the terminal result and captured frame count.
297-
/// @throws CaptureSourceError When awaiting the future if the FFI request
298-
/// fails, its result is invalid, or SDK shutdown cancels the operation.
299-
std::future<CaptureResult> join();
308+
/// @return A future containing statistics on success or a structured pump
309+
/// CaptureError whose kind is supplied by Rust.
310+
/// @throws std::runtime_error When awaiting the future if initialization,
311+
/// transport, protocol validation, or cancellation fails.
312+
/// @throws std::bad_alloc If allocation fails, including when awaiting the future.
313+
[[nodiscard]] std::future<Result<CaptureResult, CaptureError>> join();
300314

301315
private:
302316
friend class livekit::FfiClient;
303317

304318
CaptureSource();
305319

306320
/// @brief Builds the wrapper from the callback payload, adopting its handles.
321+
/// @param owned Rust-owned source handles and metadata.
322+
/// @return The capture source wrapper.
323+
/// @throws std::runtime_error If the source metadata is invalid.
307324
static std::shared_ptr<CaptureSource> fromOwned(const proto::OwnedCaptureSource& owned);
308325

309326
struct Impl;

0 commit comments

Comments
 (0)