Skip to content

Commit b01318f

Browse files
let rust error, not the cpp sdk
1 parent 709ac96 commit b01318f

4 files changed

Lines changed: 139 additions & 60 deletions

File tree

‎docs/capture-sources.md‎

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -38,11 +38,14 @@ headers do not name it.
3838

3939
## Create and publish a source
4040

41-
Dimensions must be positive. Pattern and clock frame rates must also be positive.
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.
41+
Rust validates capture configurations, including zero dimensions and frame rates,
42+
and reports failures as `std::runtime_error` when the returned future is awaited.
43+
Resolution dimensions use `std::uint32_t`, matching the protobuf and Rust types.
44+
The C++ wrapper rejects invalid enum values that cannot be serialized, using
45+
`std::invalid_argument`. For GStreamer, resolution and codec can be omitted to
46+
discover them from negotiated pipeline caps.
47+
Producer setup failures reported by Rust also throw `std::runtime_error` through
48+
that future.
4649

4750
Discarding a creation future does not wait for creation to finish. Creation
4851
continues, and the source is released when the callback arrives.
@@ -126,9 +129,10 @@ A structured pump error received from Rust becomes a failed
126129
preserved. Check the result before calling `value()` or `error()`.
127130
128131
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+
name and diagnostic. Invalid enum values that cannot be serialized throw
133+
`std::invalid_argument`. Rust configuration validation errors, uninitialized SDK
134+
use, transport failures, malformed responses, shutdown cancellation, and untyped
135+
errors from Rust throw `std::runtime_error`.
132136
`create()` and `join()` deliver these exceptions from the returned future's
133137
`get()`; `start()` and `stop()` throw directly. Exceptions are captured at the
134138
FFI callback boundary. They never unwind through Rust callbacks.
@@ -144,8 +148,3 @@ successful results when their requests succeed; the current protocol supplies
144148
structured error kinds only for the terminal pump result. The SDK does not
145149
classify untyped Rust messages by parsing their text. Allocation failures may
146150
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: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,8 @@ enum class GstreamerBitrateUnit {
6565

6666
/// @brief Video resolution in pixels.
6767
struct CaptureResolution {
68-
int width = 0;
69-
int height = 0;
68+
std::uint32_t width = 0;
69+
std::uint32_t height = 0;
7070
};
7171

7272
/// @brief Binding from WebRTC rate-control targets to a GStreamer encoder property.
@@ -179,9 +179,11 @@ struct CaptureResult {
179179
/// through @ref CaptureSource::publishOptions(), then call @ref CaptureSource::start().
180180
///
181181
/// 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(),
182+
/// Failures without a protobuf error kind throw exceptions. Rust validates source
183+
/// configurations and reports failures as std::runtime_error. Invalid enum values
184+
/// cannot be serialized and throw std::invalid_argument.
185+
/// Initialization, transport, protocol, cancellation, and untyped Rust failures
186+
/// throw std::runtime_error. For create() and join(),
185187
/// these exceptions are delivered when awaiting the future.
186188
///
187189
/// Requires a capture-enabled SDK build (`LIVEKIT_CAPTURE`). Creation fails
@@ -202,9 +204,9 @@ class LIVEKIT_API CaptureSource {
202204
///
203205
/// @param config GStreamer pipeline configuration.
204206
/// @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.
207+
/// @throws std::invalid_argument When awaiting the future if enum values cannot be serialized.
208+
/// @throws std::runtime_error When awaiting the future if Rust rejects the configuration
209+
/// or setup, initialization, transport, protocol validation, or cancellation fails.
208210
/// @throws std::bad_alloc If allocation fails, including when awaiting the future.
209211
[[nodiscard]] static std::future<Result<std::shared_ptr<CaptureSource>, CaptureError>> create(
210212
const GstreamerVideoSourceConfig& config);
@@ -218,9 +220,9 @@ class LIVEKIT_API CaptureSource {
218220
///
219221
/// @param config Pattern source configuration.
220222
/// @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.
223+
/// @throws std::invalid_argument When awaiting the future if enum values cannot be serialized.
224+
/// @throws std::runtime_error When awaiting the future if Rust rejects the configuration
225+
/// or setup, initialization, transport, protocol validation, or cancellation fails.
224226
/// @throws std::bad_alloc If allocation fails, including when awaiting the future.
225227
[[nodiscard]] static std::future<Result<std::shared_ptr<CaptureSource>, CaptureError>> create(
226228
PatternVideoSourceConfig config);
@@ -234,9 +236,8 @@ class LIVEKIT_API CaptureSource {
234236
///
235237
/// @param config Clock source configuration.
236238
/// @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.
239+
/// @throws std::runtime_error When awaiting the future if Rust rejects the configuration
240+
/// or setup, initialization, transport, protocol validation, or cancellation fails.
240241
/// @throws std::bad_alloc If allocation fails, including when awaiting the future.
241242
[[nodiscard]] static std::future<Result<std::shared_ptr<CaptureSource>, CaptureError>> create(
242243
ClockVideoSourceConfig config);

‎src/capture_source.cpp‎

Lines changed: 5 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -59,18 +59,8 @@ std::future<CreationResult> createCaptureSource(const Config& config) {
5959
}
6060
}
6161

62-
void validateResolution(const CaptureResolution& resolution) {
63-
if (resolution.width <= 0 || resolution.height <= 0) {
64-
throw std::invalid_argument("CaptureSource::create: resolution dimensions must be positive");
65-
}
66-
}
67-
6862
template <typename ProtoConfig, typename Config>
6963
void copyPixelConfig(ProtoConfig& target, const Config& config) {
70-
validateResolution(config.resolution);
71-
if (config.framerate_fps == 0) {
72-
throw std::invalid_argument("CaptureSource::create: frame rate must be positive");
73-
}
7464
target.mutable_resolution()->set_width(config.resolution.width);
7565
target.mutable_resolution()->set_height(config.resolution.height);
7666
target.set_framerate_fps(config.framerate_fps);
@@ -104,14 +94,11 @@ std::future<Result<std::shared_ptr<CaptureSource>, CaptureError>> CaptureSource:
10494
}
10595

10696
proto::NewCaptureSourceRequest toProto(const GstreamerVideoSourceConfig& config) {
107-
if (config.resolution) {
108-
validateResolution(*config.resolution);
109-
}
110-
if (config.pipeline.empty() || (config.codec && !proto::VideoCodec_IsValid(static_cast<int>(*config.codec))) ||
111-
(config.rate_control && (config.rate_control->element.empty() || config.rate_control->property.empty() ||
112-
(config.rate_control->unit != GstreamerBitrateUnit::Bps &&
113-
config.rate_control->unit != GstreamerBitrateUnit::Kbps)))) {
114-
throw std::invalid_argument("CaptureSource::create: invalid GStreamer pipeline, codec, or rate-control binding");
97+
// Protobuf enum setters assert on invalid values; reject those before serialization.
98+
if ((config.codec && !proto::VideoCodec_IsValid(static_cast<int>(*config.codec))) ||
99+
(config.rate_control && config.rate_control->unit != GstreamerBitrateUnit::Bps &&
100+
config.rate_control->unit != GstreamerBitrateUnit::Kbps)) {
101+
throw std::invalid_argument("CaptureSource::create: invalid GStreamer codec or bitrate unit");
115102
}
116103
proto::NewCaptureSourceRequest request;
117104
auto* gstreamer = request.mutable_gstreamer();

‎src/tests/unit/test_capture_source.cpp‎

Lines changed: 107 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,11 @@
2121
#include <livekit/track.h>
2222

2323
#include <chrono>
24+
#include <limits>
2425
#include <new>
2526
#include <stdexcept>
2627
#include <thread>
28+
#include <type_traits>
2729
#include <utility>
2830

2931
#include "../common/ffi_utils.h"
@@ -664,31 +666,119 @@ TEST(CaptureSourceProtoTest, ErrorKindsMatchProtoExactly) {
664666
}
665667
}
666668

667-
TEST(CaptureSourceProtoTest, RejectsNonPositiveDimensionsBeforeUnsignedConversion) {
669+
TEST(CaptureSourceProtoTest, ResolutionMatchesUnsignedProtoFields) {
670+
static_assert(
671+
std::is_same_v<decltype(capture::CaptureResolution::width), decltype(proto::VideoSourceResolution{}.width())>);
672+
static_assert(
673+
std::is_same_v<decltype(capture::CaptureResolution::height), decltype(proto::VideoSourceResolution{}.height())>);
674+
constexpr auto kMaxDimension = std::numeric_limits<std::uint32_t>::max();
668675
for (const capture::CaptureResolution resolution :
669-
{capture::CaptureResolution{0, 720}, capture::CaptureResolution{-1, 720}, capture::CaptureResolution{1280, 0},
670-
capture::CaptureResolution{1280, -1}}) {
676+
{capture::CaptureResolution{0, 720}, capture::CaptureResolution{1280, 0},
677+
capture::CaptureResolution{kMaxDimension, kMaxDimension}}) {
678+
const capture::PatternVideoSourceConfig pattern{resolution, 30};
679+
const capture::ClockVideoSourceConfig clock{resolution, 30};
680+
capture::GstreamerVideoSourceConfig gstreamer;
681+
gstreamer.resolution = resolution;
682+
for (const auto& request : {toProto(pattern), toProto(clock), toProto(gstreamer)}) {
683+
ASSERT_TRUE(request.IsInitialized());
684+
const auto& serialized = request.has_pattern() ? request.pattern().resolution()
685+
: request.has_clock() ? request.clock().resolution()
686+
: request.gstreamer().resolution();
687+
EXPECT_EQ(serialized.width(), resolution.width);
688+
EXPECT_EQ(serialized.height(), resolution.height);
689+
}
690+
}
691+
}
692+
693+
TEST_F(CaptureSourceCallbackTest, RustRejectsZeroDimensions) {
694+
for (const capture::CaptureResolution resolution :
695+
{capture::CaptureResolution{0, 720}, capture::CaptureResolution{1280, 0}}) {
671696
capture::PatternVideoSourceConfig pattern;
672697
pattern.resolution = resolution;
673698
pattern.framerate_fps = 30;
674-
expectException<std::invalid_argument>([&pattern] { return toProto(pattern); }, "CaptureSource::create:");
699+
auto pattern_future = capture::CaptureSource::create(pattern);
700+
ASSERT_EQ(pattern_future.wait_for(std::chrono::seconds(5)), std::future_status::ready);
701+
expectException([&pattern_future] { return pattern_future.get(); },
702+
"CaptureSource::create: Rust source setup failed: invalid request: "
703+
"pattern source resolution must be non-zero");
704+
675705
capture::ClockVideoSourceConfig clock;
676706
clock.resolution = resolution;
677707
clock.framerate_fps = 30;
678-
expectException<std::invalid_argument>([&clock] { return toProto(clock); }, "CaptureSource::create:");
679-
capture::GstreamerVideoSourceConfig gstreamer;
680-
gstreamer.resolution = resolution;
681-
expectException<std::invalid_argument>([&gstreamer] { return toProto(gstreamer); }, "CaptureSource::create:");
708+
auto clock_future = capture::CaptureSource::create(clock);
709+
ASSERT_EQ(clock_future.wait_for(std::chrono::seconds(5)), std::future_status::ready);
710+
expectException([&clock_future] { return clock_future.get(); },
711+
"CaptureSource::create: Rust source setup failed: invalid request: "
712+
"clock source resolution must be non-zero");
682713
}
683714
}
684715

685-
TEST(CaptureSourceProtoTest, RejectsZeroFrameRate) {
716+
TEST_F(CaptureSourceCallbackTest, RustRejectsZeroFrameRate) {
686717
capture::PatternVideoSourceConfig pattern;
687718
pattern.resolution = {1280, 720};
688-
expectException<std::invalid_argument>([&pattern] { return toProto(pattern); }, "CaptureSource::create:");
719+
auto pattern_future = capture::CaptureSource::create(pattern);
720+
ASSERT_EQ(pattern_future.wait_for(std::chrono::seconds(5)), std::future_status::ready);
721+
expectException([&pattern_future] { return pattern_future.get(); },
722+
"CaptureSource::create: Rust source setup failed: invalid request: "
723+
"pattern source frame rate must be non-zero");
724+
689725
capture::ClockVideoSourceConfig clock;
690726
clock.resolution = {1280, 720};
691-
expectException<std::invalid_argument>([&clock] { return toProto(clock); }, "CaptureSource::create:");
727+
auto clock_future = capture::CaptureSource::create(clock);
728+
ASSERT_EQ(clock_future.wait_for(std::chrono::seconds(5)), std::future_status::ready);
729+
expectException([&clock_future] { return clock_future.get(); },
730+
"CaptureSource::create: Rust source setup failed: invalid request: "
731+
"clock source frame rate must be non-zero");
732+
}
733+
734+
TEST_F(CaptureSourceCallbackTest, RustRejectsEmptyGstreamerPipeline) {
735+
auto future = capture::CaptureSource::create(capture::GstreamerVideoSourceConfig{});
736+
ASSERT_EQ(future.wait_for(std::chrono::seconds(5)), std::future_status::ready);
737+
expectException([&future] { return future.get(); },
738+
"CaptureSource::create: Rust source setup failed: invalid request: "
739+
"GStreamer pipeline error: failed to create pipeline:");
740+
}
741+
742+
TEST_F(CaptureSourceCallbackTest, RustRejectsEmptyRateControlElement) {
743+
capture::GstreamerVideoSourceConfig config;
744+
config.pipeline = "appsrc ! video/x-vp8 ! appsink name=lk_appsink";
745+
config.rate_control = capture::GstreamerRateControl{"", "bitrate", capture::GstreamerBitrateUnit::Bps};
746+
auto future = capture::CaptureSource::create(config);
747+
ASSERT_EQ(future.wait_for(std::chrono::seconds(5)), std::future_status::ready);
748+
expectException([&future] { return future.get(); },
749+
"CaptureSource::create: Rust source setup failed: invalid request: "
750+
"pipeline has no element named '' for rate control");
751+
}
752+
753+
TEST_F(CaptureSourceCallbackTest, RustAcceptsEmptyRateControlPropertyDuringCreation) {
754+
capture::GstreamerVideoSourceConfig config;
755+
config.pipeline =
756+
"videotestsrc num-buffers=4 ! video/x-raw,width=320,height=240,framerate=30/1 ! "
757+
"vp8enc name=encoder deadline=1 ! appsink name=lk_appsink";
758+
config.rate_control = capture::GstreamerRateControl{"encoder", "", capture::GstreamerBitrateUnit::Bps};
759+
auto future = capture::CaptureSource::create(config);
760+
ASSERT_EQ(future.wait_for(std::chrono::seconds(5)), std::future_status::ready);
761+
const auto created = future.get();
762+
ASSERT_TRUE(created.ok());
763+
EXPECT_EQ(created.value()->width(), 320);
764+
EXPECT_EQ(created.value()->height(), 240);
765+
}
766+
767+
TEST_F(CaptureSourceCallbackTest, RustRejectsGstreamerResolutionMismatch) {
768+
for (const capture::CaptureResolution resolution :
769+
{capture::CaptureResolution{0, 240}, capture::CaptureResolution{320, 0}}) {
770+
capture::GstreamerVideoSourceConfig config;
771+
config.pipeline =
772+
"videotestsrc num-buffers=4 ! video/x-raw,width=320,height=240,framerate=30/1 ! "
773+
"vp8enc deadline=1 ! appsink name=lk_appsink";
774+
config.resolution = resolution;
775+
auto future = capture::CaptureSource::create(config);
776+
ASSERT_EQ(future.wait_for(std::chrono::seconds(5)), std::future_status::ready);
777+
expectException([&future] { return future.get(); },
778+
"CaptureSource::create: Rust source setup failed: invalid request: "
779+
"pipeline produces 320x240, but the configuration declares " +
780+
std::to_string(resolution.width) + "x" + std::to_string(resolution.height));
781+
}
692782
}
693783

694784
// Deliberately exercise invalid enum inputs at the public API boundary.
@@ -705,16 +795,18 @@ TEST(CaptureSourceProtoTest, RejectsInvalidEnumValues) {
705795
capture::GstreamerRateControl{"encoder", "bitrate", static_cast<capture::GstreamerBitrateUnit>(99)};
706796
expectException<std::invalid_argument>([&gstreamer] { return toProto(gstreamer); }, "CaptureSource::create:");
707797
}
708-
// NOLINTEND(clang-analyzer-optin.core.EnumCastOutOfRange)
709798

710-
TEST(CaptureSourceProtoTest, ValidationErrorsAreDeliveredThroughFuture) {
799+
TEST(CaptureSourceProtoTest, InvalidEnumsAreDeliveredThroughFuture) {
711800
std::future<CreationOutcome> future;
712-
EXPECT_NO_THROW(future = capture::CaptureSource::create(capture::ClockVideoSourceConfig{}));
801+
const capture::PatternVideoSourceConfig config{{1280, 720}, 30, static_cast<capture::Pattern>(99)};
802+
EXPECT_NO_THROW(future = capture::CaptureSource::create(config));
713803
ASSERT_TRUE(future.valid());
714804
expectException<std::invalid_argument>([&future] { return future.get(); },
715-
"CaptureSource::create: resolution dimensions must be positive");
805+
"CaptureSource::create: invalid capture pattern");
716806
}
717807

808+
// NOLINTEND(clang-analyzer-optin.core.EnumCastOutOfRange)
809+
718810
TEST(CaptureSourceProtoTest, SendErrorsAreDeliveredThroughFuture) {
719811
FfiClient::instance().shutdown();
720812
capture::ClockVideoSourceConfig config;

0 commit comments

Comments
 (0)