Skip to content

Commit 23ddecf

Browse files
Result<> error returns
1 parent 67b3c5a commit 23ddecf

10 files changed

Lines changed: 572 additions & 300 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 as a failed `Result` containing `CaptureError`.
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: 68 additions & 9 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 `CaptureError` value 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,8 +39,8 @@ 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
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
4444
negotiated pipeline caps.
4545

4646
Discarding a creation future does not wait for creation to finish. Creation
@@ -54,7 +54,12 @@ continues, and the source is released when the callback arrives.
5454
auto pending = livekit::capture::CaptureSource::create(
5555
livekit::capture::PatternVideoSourceConfig{{1280, 720}, 30, livekit::capture::Pattern::Gradient});
5656
// Other application setup can run while the producer is being constructed.
57-
auto capture = pending.get();
57+
auto created = pending.get();
58+
if (!created) {
59+
// Handle created.error().kind and created.error().message.
60+
return;
61+
}
62+
auto capture = created.value();
5863
// For a wall clock, use ClockVideoSourceConfig{{1280, 720}, 30} instead.
5964

6065
auto track = livekit::LocalVideoTrack::createLocalVideoTrack("capture", capture->videoSource());
@@ -64,13 +69,24 @@ if (!participant) {
6469
}
6570
participant->publishTrack(track, capture->publishOptions());
6671

67-
if (!capture->start()) {
68-
// Handle the start failure.
72+
auto started = capture->start();
73+
if (!started) {
74+
// Handle started.error().
75+
return;
6976
}
7077

7178
// Later, when shutting down:
72-
capture->stop(); // Signals without waiting.
73-
auto result = capture->join().get(); // Waits for cleanup and returns statistics.
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.
7490
```
7591
7692
Keep `capture` alive while its track is published. `stop()` signals the pump to
@@ -90,7 +106,12 @@ config.pipeline = "videotestsrc ! video/x-raw,width=1280,height=720,framerate=30
90106
"vp8enc name=lk_encoder deadline=1 ! appsink name=lk_appsink";
91107
config.rate_control = livekit::capture::GstreamerRateControl{
92108
"lk_encoder", "target-bitrate", livekit::capture::GstreamerBitrateUnit::Bps};
93-
auto capture = livekit::capture::CaptureSource::create(config).get();
109+
auto created = livekit::capture::CaptureSource::create(config).get();
110+
if (!created) {
111+
// Handle created.error().
112+
return;
113+
}
114+
auto capture = created.value();
94115
```
95116

96117
The optional rate-control binding forwards WebRTC bitrate targets to the named
@@ -100,3 +121,41 @@ source's codec, the `PreEncoded` encoder, and disabled simulcast, which override
100121
conflicting application options. All other application options are preserved.
101122
Pattern and clock sources preserve every application option, including explicit
102123
codec and simulcast choices. Rust supplies defaults for fields left unset.
124+
125+
## Error contract
126+
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.

‎include/livekit/capture/capture_source.h‎

Lines changed: 50 additions & 39 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,17 +142,29 @@ enum class CaptureExit {
151142
EndOfStream = 1,
152143
};
153144

154-
/// @brief Why a capture ended with an error.
145+
/// @brief Category of a capture operation or pump failure.
155146
enum class CaptureErrorKind {
156-
/// @brief The capture source failed or violated its contract.
147+
/// @brief Producer setup failed, or the running source failed or violated its contract.
157148
Source = 0,
158149
/// @brief The RTC video source rejected a frame.
159150
Rtc = 1,
160151
/// @brief The pump thread panicked.
161152
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,
162165
};
163166

164-
/// @brief Terminal capture failure.
167+
/// @brief Capture failure with a category and diagnostic message.
165168
struct CaptureError {
166169
/// @brief Human-readable error message.
167170
std::string message;
@@ -170,15 +173,12 @@ struct CaptureError {
170173
CaptureErrorKind kind = CaptureErrorKind::Source;
171174
};
172175

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

181-
/// Why the capture ended; meaningful only when @ref error is empty.
181+
/// @brief Why the capture ended successfully.
182182
CaptureExit exit = CaptureExit::Stopped;
183183
};
184184

@@ -190,6 +190,10 @@ struct CaptureResult {
190190
/// a track from @ref CaptureSource::videoSource(), merge application options
191191
/// through @ref CaptureSource::publishOptions(), then call @ref CaptureSource::start().
192192
///
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.
196+
///
193197
/// Requires a capture-enabled SDK build (`LIVEKIT_CAPTURE`). Creation fails
194198
/// when the requested source was not compiled into the Rust FFI.
195199
///
@@ -200,16 +204,17 @@ class LIVEKIT_API CaptureSource {
200204
/// @brief Create a capture source from a GStreamer pipeline configuration.
201205
///
202206
/// 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.
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.
206210
/// Destroying the future does not wait for creation. The source is released
207211
/// when creation completes if the future was discarded.
208212
///
209213
/// @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);
214+
/// @return A future containing the source on success or a CaptureError on failure.
215+
/// @throws std::bad_alloc If allocation fails, including when awaiting the future.
216+
[[nodiscard]] static std::future<Result<std::shared_ptr<CaptureSource>, CaptureError>> create(
217+
const GstreamerVideoSourceConfig& config);
213218

214219
/// @brief Create the built-in test pattern capture source.
215220
///
@@ -219,9 +224,10 @@ class LIVEKIT_API CaptureSource {
219224
/// released when creation completes.
220225
///
221226
/// @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);
227+
/// @return A future containing the source on success or a CaptureError on failure.
228+
/// @throws std::bad_alloc If allocation fails, including when awaiting the future.
229+
[[nodiscard]] static std::future<Result<std::shared_ptr<CaptureSource>, CaptureError>> create(
230+
PatternVideoSourceConfig config);
225231

226232
/// @brief Create the built-in wall clock capture source.
227233
///
@@ -231,9 +237,10 @@ class LIVEKIT_API CaptureSource {
231237
/// released when creation completes.
232238
///
233239
/// @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);
240+
/// @return A future containing the source on success or a CaptureError on failure.
241+
/// @throws std::bad_alloc If allocation fails, including when awaiting the future.
242+
[[nodiscard]] static std::future<Result<std::shared_ptr<CaptureSource>, CaptureError>> create(
243+
ClockVideoSourceConfig config);
237244

238245
~CaptureSource();
239246

@@ -275,36 +282,40 @@ class LIVEKIT_API CaptureSource {
275282

276283
/// @brief Start pumping frames into the RTC video source.
277284
///
278-
/// @return @c true if the start request succeeds; otherwise @c false.
279-
bool start();
285+
/// @return Success, or a CaptureError describing initialization, request
286+
/// rejection, transport, protocol, or cancellation failure.
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 Success, or a CaptureError describing initialization, request
297+
/// rejection, transport, protocol, or cancellation failure.
298+
/// @throws std::bad_alloc If memory allocation fails.
299+
[[nodiscard]] Result<void, CaptureError> stop();
289300

290301
/// @brief Consume the running pump and wait asynchronously for it to exit.
291302
///
292303
/// This method does not signal the pump to stop. Call @ref stop() first when
293304
/// ending an unbounded source. Join may be called only once after a
294305
/// successful @ref start().
295306
///
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();
307+
/// @return A future containing statistics on success or a CaptureError on
308+
/// pump, initialization, transport, protocol, or cancellation failure.
309+
/// @throws std::bad_alloc If allocation fails, including when awaiting the future.
310+
[[nodiscard]] std::future<Result<CaptureResult, CaptureError>> join();
300311

301312
private:
302313
friend class livekit::FfiClient;
303314

304315
CaptureSource();
305316

306317
/// @brief Builds the wrapper from the callback payload, adopting its handles.
307-
static std::shared_ptr<CaptureSource> fromOwned(const proto::OwnedCaptureSource& owned);
318+
static Result<std::shared_ptr<CaptureSource>, CaptureError> fromOwned(const proto::OwnedCaptureSource& owned);
308319

309320
struct Impl;
310321
std::unique_ptr<Impl> impl_;

0 commit comments

Comments
 (0)