Skip to content

Commit cf8f2a8

Browse files
trim capture results
1 parent 23ddecf commit cf8f2a8

10 files changed

Lines changed: 343 additions & 321 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 as a failed `Result` containing `CaptureError`.
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: 70 additions & 80 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-
a `CaptureError` value 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 a failed `Result` containing `CaptureError` when
43-
the returned future is 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,42 +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 created = pending.get();
58-
if (!created) {
59-
// Handle created.error().kind and created.error().message.
60-
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().
6182
}
62-
auto capture = created.value();
63-
// For a wall clock, use ClockVideoSourceConfig{{1280, 720}, 30} instead.
64-
65-
auto track = livekit::LocalVideoTrack::createLocalVideoTrack("capture", capture->videoSource());
66-
auto participant = room.localParticipant().lock();
67-
if (!participant) {
68-
return;
69-
}
70-
participant->publishTrack(track, capture->publishOptions());
71-
72-
auto started = capture->start();
73-
if (!started) {
74-
// Handle started.error().
75-
return;
76-
}
77-
78-
// Later, when shutting down:
79-
auto stopped = capture->stop(); // Signals without waiting.
80-
if (!stopped) {
81-
// Handle stopped.error().
82-
return;
83-
}
84-
auto result = capture->join().get(); // Waits for cleanup.
85-
if (!result) {
86-
// Handle result.error(); this includes pump failures.
87-
return;
88-
}
89-
auto stats = result.value(); // frames_captured and exit.
9083
```
9184

9285
Keep `capture` alive while its track is published. `stop()` signals the pump to
@@ -106,12 +99,8 @@ config.pipeline = "videotestsrc ! video/x-raw,width=1280,height=720,framerate=30
10699
"vp8enc name=lk_encoder deadline=1 ! appsink name=lk_appsink";
107100
config.rate_control = livekit::capture::GstreamerRateControl{
108101
"lk_encoder", "target-bitrate", livekit::capture::GstreamerBitrateUnit::Bps};
109-
auto created = livekit::capture::CaptureSource::create(config).get();
110-
if (!created) {
111-
// Handle created.error().
112-
return;
113-
}
114-
auto capture = created.value();
102+
// Use the exception handling shown above for configuration and setup failures.
103+
auto capture = livekit::capture::CaptureSource::create(config).get().value();
115104
```
116105
117106
The optional rate-control binding forwards WebRTC bitrate targets to the named
@@ -124,38 +113,39 @@ codec and simulcast choices. Rust supplies defaults for fields left unset.
124113
125114
## Error contract
126115
127-
All capture operations use `Result<T, CaptureError>`. Check the result before
128-
calling `value()` or `error()`. Expected failures are values; async operations
129-
return them inside their futures. Allocation failures may still throw, either
130-
when calling the operation or when getting its future.
131-
132-
| Operation | Return type |
133-
| --- | --- |
134-
| `create(config)` | `std::future<Result<std::shared_ptr<CaptureSource>, CaptureError>>` |
135-
| `start()` / `stop()` | `Result<void, CaptureError>` |
136-
| `join()` | `std::future<Result<CaptureResult, CaptureError>>` |
137-
138-
`CaptureResult` contains successful statistics only. Pump failures use the
139-
same `error()` branch as setup and control failures.
140-
141-
| `CaptureErrorKind` | Meaning |
142-
| --- | --- |
143-
| `InvalidConfiguration` | Invalid dimensions, frame rate, codec, pattern, or rate-control binding caught in C++. |
144-
| `NotInitialized` | The SDK was not initialized when the request began. |
145-
| `Source` | Producer setup failed in Rust, or the running source failed. Includes a backend omitted from the build. |
146-
| `Rejected` | Rust returned an error in a start or stop acknowledgement. |
147-
| `Transport` | The FFI request could not be sent or completed. |
148-
| `Protocol` | The FFI acknowledgement, source information, or terminal result was invalid. |
149-
| `Cancelled` | SDK shutdown cancelled an operation already in flight. |
150-
| `Rtc` | The RTC source rejected an encoded frame. |
151-
| `Panicked` | The pump thread panicked. |
152-
153-
The Rust FFI reports some failures as plain text. The SDK preserves that text
154-
in `CaptureError::message`; callers should branch on `kind` instead of parsing
155-
messages. Control rejections have the broad `Rejected` category because the
156-
FFI does not provide typed state errors. Request failures without a valid FFI
157-
response use `Transport`, or `Cancelled` if shutdown raced with the send.
158-
159-
This replaces the unreleased exception/boolean contract. Code that previously
160-
caught `CaptureSourceError` must check `Result::error()` instead. Code that read
161-
`CaptureResult::error` must check the outer join result before reading statistics.
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: 37 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -142,29 +142,17 @@ enum class CaptureExit {
142142
EndOfStream = 1,
143143
};
144144

145-
/// @brief Category of a capture operation or pump failure.
145+
/// @brief Terminal pump failure category; matches the FFI CaptureErrorKind enum.
146146
enum class CaptureErrorKind {
147-
/// @brief Producer setup failed, or the running source failed or violated its contract.
147+
/// @brief The capture source failed or violated its contract.
148148
Source = 0,
149149
/// @brief The RTC video source rejected a frame.
150150
Rtc = 1,
151151
/// @brief The pump thread panicked.
152152
Panicked = 2,
153-
/// @brief The C++ configuration is invalid.
154-
InvalidConfiguration = 3,
155-
/// @brief The SDK has not been initialized.
156-
NotInitialized = 4,
157-
/// @brief Rust rejected a capture control request.
158-
Rejected = 5,
159-
/// @brief Sending the FFI request failed.
160-
Transport = 6,
161-
/// @brief The FFI acknowledgement or callback is invalid.
162-
Protocol = 7,
163-
/// @brief SDK shutdown cancelled an operation in flight.
164-
Cancelled = 8,
165153
};
166154

167-
/// @brief Capture failure with a category and diagnostic message.
155+
/// @brief Structured terminal pump failure reported by the Rust FFI.
168156
struct CaptureError {
169157
/// @brief Human-readable error message.
170158
std::string message;
@@ -190,9 +178,11 @@ struct CaptureResult {
190178
/// a track from @ref CaptureSource::videoSource(), merge application options
191179
/// through @ref CaptureSource::publishOptions(), then call @ref CaptureSource::start().
192180
///
193-
/// Expected failures are returned as Result values containing @ref CaptureError.
194-
/// Creation and join futures also carry validation, transport, protocol, and
195-
/// cancellation failures as values. Allocation failures may still throw.
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.
196186
///
197187
/// Requires a capture-enabled SDK build (`LIVEKIT_CAPTURE`). Creation fails
198188
/// when the requested source was not compiled into the Rust FFI.
@@ -204,14 +194,17 @@ class LIVEKIT_API CaptureSource {
204194
/// @brief Create a capture source from a GStreamer pipeline configuration.
205195
///
206196
/// Completes asynchronously: construction starts the pipeline and may wait
207-
/// for its first output to discover stream settings. Invalid configuration,
208-
/// producer setup, transport, protocol, and cancellation failures are returned
209-
/// as @ref CaptureError values in the future.
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.
210200
/// Destroying the future does not wait for creation. The source is released
211201
/// when creation completes if the future was discarded.
212202
///
213203
/// @param config GStreamer pipeline configuration.
214-
/// @return A future containing the source on success or a CaptureError on failure.
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.
215208
/// @throws std::bad_alloc If allocation fails, including when awaiting the future.
216209
[[nodiscard]] static std::future<Result<std::shared_ptr<CaptureSource>, CaptureError>> create(
217210
const GstreamerVideoSourceConfig& config);
@@ -224,7 +217,10 @@ class LIVEKIT_API CaptureSource {
224217
/// released when creation completes.
225218
///
226219
/// @param config Pattern source configuration.
227-
/// @return A future containing the source on success or a CaptureError on failure.
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.
228224
/// @throws std::bad_alloc If allocation fails, including when awaiting the future.
229225
[[nodiscard]] static std::future<Result<std::shared_ptr<CaptureSource>, CaptureError>> create(
230226
PatternVideoSourceConfig config);
@@ -237,7 +233,10 @@ class LIVEKIT_API CaptureSource {
237233
/// released when creation completes.
238234
///
239235
/// @param config Clock source configuration.
240-
/// @return A future containing the source on success or a CaptureError on failure.
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.
241240
/// @throws std::bad_alloc If allocation fails, including when awaiting the future.
242241
[[nodiscard]] static std::future<Result<std::shared_ptr<CaptureSource>, CaptureError>> create(
243242
ClockVideoSourceConfig config);
@@ -282,8 +281,9 @@ class LIVEKIT_API CaptureSource {
282281

283282
/// @brief Start pumping frames into the RTC video source.
284283
///
285-
/// @return Success, or a CaptureError describing initialization, request
286-
/// rejection, transport, protocol, or cancellation failure.
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.
287287
/// @throws std::bad_alloc If memory allocation fails.
288288
[[nodiscard]] Result<void, CaptureError> start();
289289

@@ -293,8 +293,9 @@ class LIVEKIT_API CaptureSource {
293293
/// to synchronize and retrieve the terminal result. Stopping an
294294
/// already-finished capture is a no-op.
295295
///
296-
/// @return Success, or a CaptureError describing initialization, request
297-
/// rejection, transport, protocol, or cancellation failure.
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.
298299
/// @throws std::bad_alloc If memory allocation fails.
299300
[[nodiscard]] Result<void, CaptureError> stop();
300301

@@ -304,8 +305,10 @@ class LIVEKIT_API CaptureSource {
304305
/// ending an unbounded source. Join may be called only once after a
305306
/// successful @ref start().
306307
///
307-
/// @return A future containing statistics on success or a CaptureError on
308-
/// pump, initialization, transport, protocol, or cancellation failure.
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.
309312
/// @throws std::bad_alloc If allocation fails, including when awaiting the future.
310313
[[nodiscard]] std::future<Result<CaptureResult, CaptureError>> join();
311314

@@ -315,7 +318,10 @@ class LIVEKIT_API CaptureSource {
315318
CaptureSource();
316319

317320
/// @brief Builds the wrapper from the callback payload, adopting its handles.
318-
static Result<std::shared_ptr<CaptureSource>, CaptureError> fromOwned(const proto::OwnedCaptureSource& owned);
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.
324+
static std::shared_ptr<CaptureSource> fromOwned(const proto::OwnedCaptureSource& owned);
319325

320326
struct Impl;
321327
std::unique_ptr<Impl> impl_;

0 commit comments

Comments
 (0)