From b4431b3d96fc90dd40751c3982a44c20223835e1 Mon Sep 17 00:00:00 2001 From: Ryan Gaus Date: Mon, 30 Nov 2026 20:44:03 +1300 Subject: [PATCH 1/3] Add LocalParticipant::sendText / sendBytes / sendFile One-shot sends through the FFI's send_text / send_bytes / send_file. The SDK core frames, chunks and compresses them, so they use data streams v2 (single-packet delivery and deflate compression) when every recipient supports it, like the other LiveKit SDKs. They block until the send completes, return the sent stream's info, and throw DataStreamError on failure. - StreamTextOptions / StreamByteOptions carry topic, attributes, destinations, stream id, reply-to and attachments (text), name, MIME type and total length (bytes), compress (default true) and sender_identity. - sendFile names the stream after the file's basename unless a name is given. The SDK core does not infer a MIME type from the file name, so the docs say it sends application/octet-stream unless one is set. - The FFI panics if a stream is sent after the room session is gone, so sends throw DataStreamError once the room has disconnected instead of reaching it. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 1 + README.md | 4 +- include/livekit/data_stream.h | 86 +++++++++- include/livekit/local_participant.h | 57 +++++++ src/data_stream_proto_converter.cpp | 53 ++++++ src/data_stream_proto_converter.h | 10 ++ src/ffi_client.cpp | 124 ++++++++++++++ src/ffi_client.h | 10 ++ src/local_participant.cpp | 47 ++++++ src/room.cpp | 3 + src/tests/integration/test_data_streams.cpp | 169 +++++++++++++++++++- src/tests/unit/test_data_stream.cpp | 92 +++++++++++ 12 files changed, 645 insertions(+), 11 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 362cebe7..fde9ed31 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -77,6 +77,7 @@ All `RoomDelegate` callbacks and stream handler callbacks (e.g., `registerTextSt | `LocalAudioTrack` / `LocalVideoTrack` | No | Thin `sendRequest` wrappers with no internal synchronization. | | `LocalDataTrack::tryPush` | No | Thin `sendRequest` wrapper with no internal synchronization. | | `TextStreamReader` / `ByteStreamReader` | Yes | Fed on the FFI callback thread, read on a user thread (internal `std::mutex` + `condition_variable`). End-of-stream attributes are merged into `info()` on the reading thread, so don't call `info()` concurrently with `readNext()`. | +| `LocalParticipant::sendText` / `sendBytes` / `sendFile` | Yes | Independent async FFI requests; each call blocks its caller until its own callback arrives. They throw `DataStreamError` once the room has disconnected rather than reaching the FFI. | | `TextStreamWriter` / `ByteStreamWriter` | Serialized | `write()` is serialized by an internal `write_mutex_`. | ### Directory Layout diff --git a/README.md b/README.md index 243e1d3a..4bf10eb8 100644 --- a/README.md +++ b/README.md @@ -226,7 +226,9 @@ token source helpers for endpoint, development token server, and custom backends - Dynamic token sourcing (literal, custom, endpoint, development token server, caching) - Receive remote audio/video tracks - Publish local audio/video tracks -- Data tracks (low-level) and data streams (high-level) +- Data tracks (low-level) and data streams (high-level): one-shot `sendText` / + `sendBytes` / `sendFile` with compression, incremental writers, and + per-topic stream handlers - RPC between participants - End-to-end encryption (E2EE) - Hardware-accelerated codecs (via the underlying Rust SDK) diff --git a/include/livekit/data_stream.h b/include/livekit/data_stream.h index 511a02a5..85d5e74e 100644 --- a/include/livekit/data_stream.h +++ b/include/livekit/data_stream.h @@ -41,10 +41,12 @@ constexpr std::size_t kStreamChunkSize = 15'000; // 15 KB /// @brief Error raised by data stream operations. /// -/// Thrown by TextStreamReader / ByteStreamReader when an incoming stream ends -/// abnormally (for example the sender closed it with a reason, the stream -/// exceeded the receive size limit, or the room disconnected mid-stream). The -/// message carries the SDK's error description. +/// Thrown by the one-shot send APIs (for example +/// LocalParticipant::sendText()) when the send fails or the participant is no +/// longer connected, and by TextStreamReader / ByteStreamReader when an +/// incoming stream ends abnormally (for example the sender closed it with a +/// reason, the stream exceeded the receive size limit, or the room +/// disconnected mid-stream). The message carries the SDK's error description. /// /// Derives from std::runtime_error, so existing /// `catch (const std::runtime_error&)` handlers keep working. @@ -55,6 +57,82 @@ class LIVEKIT_API DataStreamError : public std::runtime_error { explicit DataStreamError(const std::string& message); }; +/// @brief Options for a one-shot text send or an incremental text stream. +/// +/// Used by LocalParticipant::sendText(). +struct StreamTextOptions { + /// Application-defined topic. Required; receivers route streams to handlers + /// registered with Room::registerTextStreamHandler() by topic. + std::string topic; + + /// Arbitrary key/value attributes sent with the stream header. + std::map attributes; + + /// Identities of the participants that should receive the stream. Empty + /// means every participant in the room. + std::vector destination_identities; + + /// Stream id to use. A unique id is generated when unset. + std::optional stream_id; + + /// Id of the stream this stream replies to, if any. + std::optional reply_to_stream_id; + + /// Ids of other streams (for example files) attached to this text stream. + std::vector attached_stream_ids; + + /// Compress the payload when every recipient supports compression. + /// + /// Only one-shot sends compress; incremental writers ignore this flag. + bool compress = true; + + /// Identity to send as. Leave unset to send as the local participant; + /// setting it requires the impersonation permission. + std::optional sender_identity; +}; + +/// @brief Options for a one-shot byte/file send or an incremental byte stream. +/// +/// Used by LocalParticipant::sendBytes() and LocalParticipant::sendFile(). +struct StreamByteOptions { + /// Application-defined topic. Required; receivers route streams to handlers + /// registered with Room::registerByteStreamHandler() by topic. + std::string topic; + + /// Arbitrary key/value attributes sent with the stream header. + std::map attributes; + + /// Identities of the participants that should receive the stream. Empty + /// means every participant in the room. + std::vector destination_identities; + + /// Stream id to use. A unique id is generated when unset. + std::optional stream_id; + + /// Name of the payload (for example a file name). When unset, sendBytes() + /// uses the SDK default ("unknown") and sendFile() uses the file's basename. + std::optional name; + + /// MIME type of the payload. When unset, the SDK uses + /// "application/octet-stream" (also for sendFile(); the SDK does not yet + /// infer a type from the file name). + std::optional mime_type; + + /// Total payload size in bytes, if known. Only meaningful for incremental + /// writers; one-shot sends always know their size. + std::optional total_length; + + /// Compress the payload when every recipient supports compression. + /// + /// Only one-shot sends compress; incremental writers ignore this flag. Turn + /// it off for payloads that are already compressed (images, video, archives). + bool compress = true; + + /// Identity to send as. Leave unset to send as the local participant; + /// setting it requires the impersonation permission. + std::optional sender_identity; +}; + /// Base metadata for any stream (text or bytes). struct BaseStreamInfo { /// Unique identifier for this stream. diff --git a/include/livekit/local_participant.h b/include/livekit/local_participant.h index 557205b0..353d8d26 100644 --- a/include/livekit/local_participant.h +++ b/include/livekit/local_participant.h @@ -27,6 +27,7 @@ #include #include +#include "livekit/data_stream.h" #include "livekit/data_track_error.h" #include "livekit/data_track_options.h" #include "livekit/data_track_schema.h" @@ -93,6 +94,50 @@ class LIVEKIT_API LocalParticipant : public Participant { void publishData(const std::vector& payload, bool reliable = true, const std::vector& destination_identities = {}, const std::string& topic = {}); + /// @brief Send a complete text message as a data stream. + /// + /// Blocks until the SDK reports the send complete. When every recipient + /// supports it, small messages go out as a single packet and the payload is + /// compressed (unless @c options.compress is false). Receivers get the + /// message through Room::registerTextStreamHandler() on @c options.topic. + /// + /// @param text UTF-8 text to send. + /// @param options Topic (required), destinations, attributes, and so on. + /// @return Metadata of the sent stream, including its stream id. + /// @throws DataStreamError if the send fails, or if the room is no longer + /// connected or the SDK isn't initialized. + TextStreamInfo sendText(const std::string& text, const StreamTextOptions& options); + + /// @brief Send a complete in-memory buffer as a byte data stream. + /// + /// Blocks until the SDK reports the send complete. When every recipient + /// supports it, small payloads go out as a single packet and the payload is + /// compressed (unless @c options.compress is false). Receivers get the data + /// through Room::registerByteStreamHandler() on @c options.topic. + /// + /// @param data Bytes to send. + /// @param options Topic (required), name, MIME type, destinations, and so on. + /// @return Metadata of the sent stream, including its stream id. + /// @throws DataStreamError if the send fails, or if the room is no longer + /// connected or the SDK isn't initialized. + ByteStreamInfo sendBytes(const std::vector& data, const StreamByteOptions& options); + + /// @brief Send a local file as a byte data stream. + /// + /// The SDK reads the file itself (in this process). Blocks until the send + /// completes. When @c options.name is unset, the file's basename is used. + /// When @c options.mime_type is unset, "application/octet-stream" is sent; + /// set it to label the file's type. + /// Consider setting @c options.compress to false for files that are + /// already compressed, such as images. + /// + /// @param path Path of the file to send (UTF-8). + /// @param options Topic (required), name, MIME type, destinations, and so on. + /// @return Metadata of the sent stream, including its stream id. + /// @throws DataStreamError if the file can't be read or the send fails, or + /// if the room is no longer connected or the SDK isn't initialized. + ByteStreamInfo sendFile(const std::string& path, const StreamByteOptions& options); + /// Publish a SIP DTMF (phone keypad) tone into the room. /// /// Only meaningful when a SIP trunk is bridging a phone call into the @@ -302,8 +347,20 @@ class LIVEKIT_API LocalParticipant : public Participant { /// prune expired @c weak_ptr entries. mutable TrackMap published_tracks_by_sid_; + /// Marks the participant as disconnected so data stream sends fail fast in + /// C++ instead of reaching an FFI participant whose session is gone. + void markDisconnected() noexcept { disconnected_.store(true, std::memory_order_release); } + + /// Returns the FFI handle id for a data stream operation, or throws + /// DataStreamError if the participant can no longer send. + std::uint64_t dataStreamHandle(const char* operation) const; + std::unordered_map rpc_handlers_; + /// Set once the room disconnects. Guarded by an atomic rather than + /// Room::lock_ so send paths never need the room lock. + std::atomic disconnected_{false}; + // Shared state for RPC invocation tracking. Using shared_ptr so the state // can outlive the LocalParticipant if there are in-flight invocations when // the participant is destroyed. diff --git a/src/data_stream_proto_converter.cpp b/src/data_stream_proto_converter.cpp index e87423c2..0cb087d3 100644 --- a/src/data_stream_proto_converter.cpp +++ b/src/data_stream_proto_converter.cpp @@ -18,6 +18,59 @@ namespace livekit { +proto::StreamTextOptions toProto(const StreamTextOptions& in) { + proto::StreamTextOptions out; + out.set_topic(in.topic); + for (const auto& kv : in.attributes) { + (*out.mutable_attributes())[kv.first] = kv.second; + } + for (const auto& identity : in.destination_identities) { + out.add_destination_identities(identity); + } + if (in.stream_id) { + out.set_id(*in.stream_id); + } + if (in.reply_to_stream_id) { + out.set_reply_to_stream_id(*in.reply_to_stream_id); + } + for (const auto& id : in.attached_stream_ids) { + out.add_attached_stream_ids(id); + } + out.set_compress(in.compress); + if (in.sender_identity) { + out.set_sender_identity(*in.sender_identity); + } + return out; +} + +proto::StreamByteOptions toProto(const StreamByteOptions& in) { + proto::StreamByteOptions out; + out.set_topic(in.topic); + for (const auto& kv : in.attributes) { + (*out.mutable_attributes())[kv.first] = kv.second; + } + for (const auto& identity : in.destination_identities) { + out.add_destination_identities(identity); + } + if (in.stream_id) { + out.set_id(*in.stream_id); + } + if (in.name) { + out.set_name(*in.name); + } + if (in.mime_type) { + out.set_mime_type(*in.mime_type); + } + if (in.total_length) { + out.set_total_length(*in.total_length); + } + out.set_compress(in.compress); + if (in.sender_identity) { + out.set_sender_identity(*in.sender_identity); + } + return out; +} + TextStreamInfo fromProto(const proto::TextStreamInfo& in) { TextStreamInfo out; out.stream_id = in.stream_id(); diff --git a/src/data_stream_proto_converter.h b/src/data_stream_proto_converter.h index bee9fa7a..acf3c0ee 100644 --- a/src/data_stream_proto_converter.h +++ b/src/data_stream_proto_converter.h @@ -22,6 +22,16 @@ namespace livekit { +/// @brief Convert one-shot text send options to the FFI proto. +/// @param in C++ options. +/// @return The FFI options; `compress` is always set explicitly. +LIVEKIT_INTERNAL_API proto::StreamTextOptions toProto(const StreamTextOptions& in); + +/// @brief Convert one-shot byte send options to the FFI proto. +/// @param in C++ options. +/// @return The FFI options; `compress` is always set explicitly. +LIVEKIT_INTERNAL_API proto::StreamByteOptions toProto(const StreamByteOptions& in); + /// @brief Convert FFI text stream metadata to the public info struct. /// @param in FFI info. /// @return Public info. diff --git a/src/ffi_client.cpp b/src/ffi_client.cpp index b984e910..ccb70300 100644 --- a/src/ffi_client.cpp +++ b/src/ffi_client.cpp @@ -27,6 +27,7 @@ #include "data_track_proto_converter.h" #include "ffi.pb.h" #include "livekit/build.h" +#include "livekit/data_stream.h" #include "livekit/data_track_error.h" #include "livekit/ffi_handle.h" #include "livekit/room.h" @@ -1123,6 +1124,129 @@ std::future FfiClient::performRpcAsync(std::uint64_t local_particip return fut; } +std::future FfiClient::sendTextAsync(std::uint64_t local_participant_handle, + const std::string& text, + const proto::StreamTextOptions& options) { + const AsyncId async_id = generateAsyncId(); + + auto fut = registerAsync( + async_id, + [async_id](const proto::FfiEvent& e) { return e.has_send_text() && e.send_text().async_id() == async_id; }, + [](const proto::FfiEvent& e, std::promise& pr) { + const auto& cb = e.send_text(); + if (cb.has_error()) { + pr.set_exception(std::make_exception_ptr(DataStreamError(cb.error().description()))); + return; + } + if (!cb.has_info()) { + pr.set_exception(std::make_exception_ptr(DataStreamError("send_text callback missing info"))); + return; + } + pr.set_value(cb.info()); + }); + + proto::FfiRequest req; + auto* msg = req.mutable_send_text(); + msg->set_local_participant_handle(local_participant_handle); + *msg->mutable_options() = options; + msg->set_text(text); + msg->set_request_async_id(async_id); + + try { + const proto::FfiResponse resp = sendRequest(req); + if (!resp.has_send_text()) { + logAndThrow("FfiResponse missing send_text"); + } + } catch (...) { + cancelPendingByAsyncId(async_id); + throw; + } + + return fut; +} + +std::future FfiClient::sendBytesAsync(std::uint64_t local_participant_handle, + const std::vector& bytes, + const proto::StreamByteOptions& options) { + const AsyncId async_id = generateAsyncId(); + + auto fut = registerAsync( + async_id, + [async_id](const proto::FfiEvent& e) { return e.has_send_bytes() && e.send_bytes().async_id() == async_id; }, + [](const proto::FfiEvent& e, std::promise& pr) { + const auto& cb = e.send_bytes(); + if (cb.has_error()) { + pr.set_exception(std::make_exception_ptr(DataStreamError(cb.error().description()))); + return; + } + if (!cb.has_info()) { + pr.set_exception(std::make_exception_ptr(DataStreamError("send_bytes callback missing info"))); + return; + } + pr.set_value(cb.info()); + }); + + proto::FfiRequest req; + auto* msg = req.mutable_send_bytes(); + msg->set_local_participant_handle(local_participant_handle); + *msg->mutable_options() = options; + msg->set_bytes(bytes.data(), bytes.size()); + msg->set_request_async_id(async_id); + + try { + const proto::FfiResponse resp = sendRequest(req); + if (!resp.has_send_bytes()) { + logAndThrow("FfiResponse missing send_bytes"); + } + } catch (...) { + cancelPendingByAsyncId(async_id); + throw; + } + + return fut; +} + +std::future FfiClient::sendFileAsync(std::uint64_t local_participant_handle, + const std::string& file_path, + const proto::StreamByteOptions& options) { + const AsyncId async_id = generateAsyncId(); + + auto fut = registerAsync( + async_id, + [async_id](const proto::FfiEvent& e) { return e.has_send_file() && e.send_file().async_id() == async_id; }, + [](const proto::FfiEvent& e, std::promise& pr) { + const auto& cb = e.send_file(); + if (cb.has_error()) { + pr.set_exception(std::make_exception_ptr(DataStreamError(cb.error().description()))); + return; + } + if (!cb.has_info()) { + pr.set_exception(std::make_exception_ptr(DataStreamError("send_file callback missing info"))); + return; + } + pr.set_value(cb.info()); + }); + + proto::FfiRequest req; + auto* msg = req.mutable_send_file(); + msg->set_local_participant_handle(local_participant_handle); + *msg->mutable_options() = options; + msg->set_file_path(file_path); + msg->set_request_async_id(async_id); + + try { + const proto::FfiResponse resp = sendRequest(req); + if (!resp.has_send_file()) { + logAndThrow("FfiResponse missing send_file"); + } + } catch (...) { + cancelPendingByAsyncId(async_id); + throw; + } + + return fut; +} + void FfiClient::textStreamReadIncremental(std::uint64_t reader_handle) { proto::FfiRequest req; req.mutable_text_read_incremental()->set_reader_handle(reader_handle); diff --git a/src/ffi_client.h b/src/ffi_client.h index 7922e045..1359f891 100644 --- a/src/ffi_client.h +++ b/src/ffi_client.h @@ -160,6 +160,16 @@ class LIVEKIT_INTERNAL_API FfiClient { Result subscribeDataTrack( std::uint64_t track_handle, std::optional buffer_size = std::nullopt); + // Data stream APIs (high-level; Rust handles framing, chunking and + // compression). A callback error is surfaced as DataStreamError. + std::future sendTextAsync(std::uint64_t local_participant_handle, const std::string& text, + const proto::StreamTextOptions& options); + std::future sendBytesAsync(std::uint64_t local_participant_handle, + const std::vector& bytes, + const proto::StreamByteOptions& options); + std::future sendFileAsync(std::uint64_t local_participant_handle, const std::string& file_path, + const proto::StreamByteOptions& options); + // Start incremental reads of an owned reader handle. Consumes the handle: // never drop it afterwards. Chunks and EOS arrive as // Text/ByteStreamReaderEvent keyed by reader handle. diff --git a/src/local_participant.cpp b/src/local_participant.cpp index 2607963d..e93e3fcc 100644 --- a/src/local_participant.cpp +++ b/src/local_participant.cpp @@ -21,6 +21,7 @@ #include #include +#include "data_stream_proto_converter.h" #include "data_track.pb.h" #include "ffi.pb.h" #include "ffi_client.h" @@ -86,6 +87,51 @@ void LocalParticipant::publishData(const std::vector& payload, boo fut.get(); } +std::uint64_t LocalParticipant::dataStreamHandle(const char* operation) const { + if (!FfiClient::instance().isInitialized()) { + throw DataStreamError(std::string("LocalParticipant::") + operation + ": LiveKit is not initialized"); + } + // The FFI panics (and the SDK raises SIGTERM) if a stream is sent after the + // room session is gone, so refuse here instead. + if (disconnected_.load(std::memory_order_acquire)) { + throw DataStreamError(std::string("LocalParticipant::") + operation + ": not connected"); + } + const auto handle_id = ffiHandleId(); + if (handle_id == 0) { + throw DataStreamError(std::string("LocalParticipant::") + operation + ": invalid FFI handle"); + } + return static_cast(handle_id); +} + +TextStreamInfo LocalParticipant::sendText(const std::string& text, const StreamTextOptions& options) { + const auto handle_id = dataStreamHandle("sendText"); + auto fut = FfiClient::instance().sendTextAsync(handle_id, text, toProto(options)); + return fromProto(fut.get()); +} + +ByteStreamInfo LocalParticipant::sendBytes(const std::vector& data, const StreamByteOptions& options) { + const auto handle_id = dataStreamHandle("sendBytes"); + auto fut = FfiClient::instance().sendBytesAsync(handle_id, data, toProto(options)); + return fromProto(fut.get()); +} + +ByteStreamInfo LocalParticipant::sendFile(const std::string& path, const StreamByteOptions& options) { + const auto handle_id = dataStreamHandle("sendFile"); + proto::StreamByteOptions proto_options = toProto(options); + if (!options.name) { + // Basename of a UTF-8 path. Done on the string rather than via + // std::filesystem so non-ASCII names survive on Windows. +#ifdef _WIN32 + const auto slash = path.find_last_of("/\\"); +#else + const auto slash = path.find_last_of('/'); +#endif + proto_options.set_name(slash == std::string::npos ? path : path.substr(slash + 1)); + } + auto fut = FfiClient::instance().sendFileAsync(handle_id, path, proto_options); + return fromProto(fut.get()); +} + void LocalParticipant::publishDtmf(int code, const std::string& digit) { auto handle_id = ffiHandleId(); if (handle_id == 0) { @@ -394,6 +440,7 @@ void LocalParticipant::unregisterRpcMethod(const std::string& method_name) { } void LocalParticipant::shutdown() { + markDisconnected(); // Mark as shutting down and wait for all active invocations to complete { std::unique_lock lock(rpc_state_->mutex); diff --git a/src/room.cpp b/src/room.cpp index 4bb969cd..28e69ef7 100644 --- a/src/room.cpp +++ b/src/room.cpp @@ -1276,6 +1276,9 @@ void Room::onEvent(const FfiEvent& event) { bool should_notify = false; { const std::scoped_lock guard(lock_); + if (local_participant_) { + local_participant_->markDisconnected(); + } // Local shutdown marks the state before awaiting the FFI response // and notifies the delegate itself. Suppress that duplicate while // passing server-initiated disconnects through unchanged. diff --git a/src/tests/integration/test_data_streams.cpp b/src/tests/integration/test_data_streams.cpp index 610aacbe..dc048b3b 100644 --- a/src/tests/integration/test_data_streams.cpp +++ b/src/tests/integration/test_data_streams.cpp @@ -25,6 +25,8 @@ #include #include #include +#include +#include #include #include #include @@ -329,6 +331,161 @@ TEST_F(DataStreamE2ETest, ByteStreamRoundTripEndToEnd) { EXPECT_EQ(collector.info().name, "payload.bin"); } +// --------------------------------------------------------------------------- +// One-shot sends (sendText / sendBytes / sendFile). These produce data streams +// v2 traffic (single-packet and compressed), like every other LiveKit SDK. +// --------------------------------------------------------------------------- + +TEST_F(DataStreamE2ETest, SendTextSmallRoundTrip) { + const auto topic = makeTopic("send_text_small"); + auto rooms = testRooms(2); + auto sender = lockLocalParticipant(*rooms[0]); + + TextStreamCollector collector; + collector.registerOn(*rooms[1], topic); + + StreamTextOptions options; + options.topic = topic; + options.attributes = {{"kind", "greeting"}}; + const auto sent = sender->sendText("hi there", options); + EXPECT_FALSE(sent.stream_id.empty()); + EXPECT_EQ(sent.topic, topic); + + ASSERT_TRUE(collector.wait(kStreamWaitTimeout)) << "Timed out waiting for text stream"; + EXPECT_FALSE(collector.error().has_value()) << *collector.error(); + EXPECT_EQ(collector.text(), "hi there"); + EXPECT_EQ(collector.info().stream_id, sent.stream_id); + EXPECT_EQ(collector.info().mime_type, "text/plain"); + EXPECT_EQ(collector.info().attributes.at("kind"), "greeting"); + EXPECT_EQ(collector.senderIdentity(), sender->identity()); +} + +TEST_F(DataStreamE2ETest, SendTextLargeCompressedRoundTrip) { + const auto topic = makeTopic("send_text_large"); + const auto payload = compressibleText(50 * 1024); + auto rooms = testRooms(2); + + TextStreamCollector collector; + collector.registerOn(*rooms[1], topic); + + StreamTextOptions options; + options.topic = topic; + (void)lockLocalParticipant(*rooms[0])->sendText(payload, options); + + ASSERT_TRUE(collector.wait(kStreamWaitTimeout)) << "Timed out waiting for text stream"; + EXPECT_FALSE(collector.error().has_value()) << *collector.error(); + EXPECT_EQ(collector.text(), payload); +} + +TEST_F(DataStreamE2ETest, SendTextUncompressedRoundTrip) { + const auto topic = makeTopic("send_text_uncompressed"); + const auto payload = compressibleText(50 * 1024); + auto rooms = testRooms(2); + + TextStreamCollector collector; + collector.registerOn(*rooms[1], topic); + + StreamTextOptions options; + options.topic = topic; + options.compress = false; + (void)lockLocalParticipant(*rooms[0])->sendText(payload, options); + + ASSERT_TRUE(collector.wait(kStreamWaitTimeout)) << "Timed out waiting for text stream"; + EXPECT_FALSE(collector.error().has_value()) << *collector.error(); + EXPECT_EQ(collector.text(), payload); +} + +TEST_F(DataStreamE2ETest, SendTextUnicodeRoundTrip) { + const auto topic = makeTopic("send_text_unicode"); + // Larger than one 15 KB chunk, uncompressed, so multi-byte code points + // straddle chunk boundaries. + const auto payload = unicodeText(40 * 1024); + auto rooms = testRooms(2); + + TextStreamCollector collector; + collector.registerOn(*rooms[1], topic); + + StreamTextOptions options; + options.topic = topic; + options.compress = false; + (void)lockLocalParticipant(*rooms[0])->sendText(payload, options); + + ASSERT_TRUE(collector.wait(kStreamWaitTimeout)) << "Timed out waiting for text stream"; + EXPECT_FALSE(collector.error().has_value()) << *collector.error(); + EXPECT_EQ(collector.text(), payload); +} + +TEST_F(DataStreamE2ETest, SendBytesSmallRoundTrip) { + const auto topic = makeTopic("send_bytes"); + const std::vector payload{0x00, 0x01, 0xFE, 0xFF, 'o', 'k'}; + auto rooms = testRooms(2); + + ByteStreamCollector collector; + collector.registerOn(*rooms[1], topic); + + StreamByteOptions options; + options.topic = topic; + options.name = "blob.bin"; + options.mime_type = "application/x-test"; + const auto sent = lockLocalParticipant(*rooms[0])->sendBytes(payload, options); + + ASSERT_TRUE(collector.wait(kStreamWaitTimeout)) << "Timed out waiting for byte stream"; + EXPECT_FALSE(collector.error().has_value()) << *collector.error(); + EXPECT_EQ(collector.content(), payload); + EXPECT_EQ(collector.info().stream_id, sent.stream_id); + EXPECT_EQ(collector.info().name, "blob.bin"); + EXPECT_EQ(collector.info().mime_type, "application/x-test"); +} + +TEST_F(DataStreamE2ETest, SendFileRoundTrip) { + const auto topic = makeTopic("send_file"); + const std::string file_name = "lk_send_file_" + std::to_string(getTimestampUs()) + ".txt"; + const std::string path = ::testing::TempDir() + file_name; + const auto payload = compressibleText(20 * 1024); + { + std::ofstream out(path, std::ios::binary); + out << payload; + } + auto rooms = testRooms(2); + + ByteStreamCollector collector; + collector.registerOn(*rooms[1], topic); + + StreamByteOptions options; + options.topic = topic; + const auto sent = lockLocalParticipant(*rooms[0])->sendFile(path, options); + EXPECT_EQ(sent.name, file_name) << "name defaults to the file's basename"; + EXPECT_FALSE(sent.mime_type.empty()); + + ASSERT_TRUE(collector.wait(kStreamWaitTimeout)) << "Timed out waiting for file stream"; + std::remove(path.c_str()); + EXPECT_FALSE(collector.error().has_value()) << *collector.error(); + EXPECT_EQ(std::string(collector.content().begin(), collector.content().end()), payload); + EXPECT_EQ(collector.info().name, file_name); + EXPECT_EQ(collector.info().mime_type, sent.mime_type); +} + +TEST_F(DataStreamE2ETest, SendFileMissingFileThrows) { + auto rooms = testRooms(1); + StreamByteOptions options; + options.topic = makeTopic("send_file_missing"); + EXPECT_THROW((void)lockLocalParticipant(*rooms[0])->sendFile(::testing::TempDir() + "no-such-file.bin", options), + DataStreamError); +} + +TEST_F(DataStreamE2ETest, SendAfterDisconnectThrows) { + auto rooms = testRooms(1); + auto sender = lockLocalParticipant(*rooms[0]); + ASSERT_TRUE(rooms[0]->disconnect()); + + StreamTextOptions text_options; + text_options.topic = makeTopic("after_disconnect"); + StreamByteOptions byte_options; + byte_options.topic = text_options.topic; + EXPECT_THROW((void)sender->sendText("late", text_options), DataStreamError); + EXPECT_THROW((void)sender->sendBytes({1}, byte_options), DataStreamError); +} + // --------------------------------------------------------------------------- // Receive-side behaviour // --------------------------------------------------------------------------- @@ -438,14 +595,14 @@ TEST_F(DataStreamE2ETest, StreamHandlesAreReleased) { TextStreamCollector collector; collector.registerOn(*rooms[1], handled_topic); + StreamTextOptions unhandled; + unhandled.topic = unhandled_topic; for (std::size_t i = 0; i < kUnhandledStreams; ++i) { - TextStreamWriter unhandled(*sender, unhandled_topic); - unhandled.write("nobody listens " + std::to_string(i)); - unhandled.close(); + (void)sender->sendText("nobody listens " + std::to_string(i), unhandled); } - TextStreamWriter handled(*sender, handled_topic); - handled.write("somebody listens"); - handled.close(); + StreamTextOptions handled; + handled.topic = handled_topic; + (void)sender->sendText("somebody listens", handled); ASSERT_TRUE(collector.wait(kStreamWaitTimeout)); ASSERT_TRUE(recorder.waitForCount(kUnhandledStreams + 1, kStreamWaitTimeout)); diff --git a/src/tests/unit/test_data_stream.cpp b/src/tests/unit/test_data_stream.cpp index 7d743024..198d9a6a 100644 --- a/src/tests/unit/test_data_stream.cpp +++ b/src/tests/unit/test_data_stream.cpp @@ -16,6 +16,7 @@ #include #include +#include #include #include @@ -205,6 +206,77 @@ TEST(DataStreamReaderTest, TerminalErrorWakesBlockedRead) { // Option / info conversion // --------------------------------------------------------------------------- +TEST(DataStreamConversionTest, TextOptionsDefaultsToProto) { + StreamTextOptions options; + options.topic = "chat"; + const auto proto = toProto(options); + EXPECT_EQ(proto.topic(), "chat"); + ASSERT_TRUE(proto.has_compress()) << "compress is always sent explicitly"; + EXPECT_TRUE(proto.compress()); + EXPECT_FALSE(proto.has_id()); + EXPECT_FALSE(proto.has_reply_to_stream_id()); + EXPECT_FALSE(proto.has_sender_identity()); + EXPECT_EQ(proto.destination_identities_size(), 0); +} + +TEST(DataStreamConversionTest, TextOptionsAllFieldsToProto) { + StreamTextOptions options; + options.topic = "chat"; + options.attributes = {{"k", "v"}}; + options.destination_identities = {"alice", "bob"}; + options.stream_id = "stream-1"; + options.reply_to_stream_id = "stream-0"; + options.attached_stream_ids = {"file-1"}; + options.compress = false; + options.sender_identity = "agent"; + + const auto proto = toProto(options); + EXPECT_EQ(attrs(proto.attributes()), (std::map{{"k", "v"}})); + ASSERT_EQ(proto.destination_identities_size(), 2); + EXPECT_EQ(proto.destination_identities(1), "bob"); + EXPECT_EQ(proto.id(), "stream-1"); + EXPECT_EQ(proto.reply_to_stream_id(), "stream-0"); + ASSERT_EQ(proto.attached_stream_ids_size(), 1); + EXPECT_EQ(proto.attached_stream_ids(0), "file-1"); + ASSERT_TRUE(proto.has_compress()); + EXPECT_FALSE(proto.compress()); + EXPECT_EQ(proto.sender_identity(), "agent"); +} + +TEST(DataStreamConversionTest, ByteOptionsToProto) { + StreamByteOptions defaults; + defaults.topic = "files"; + const auto unset = toProto(defaults); + EXPECT_TRUE(unset.has_compress()); + EXPECT_TRUE(unset.compress()); + EXPECT_FALSE(unset.has_name()); + EXPECT_FALSE(unset.has_mime_type()); + EXPECT_FALSE(unset.has_total_length()); + EXPECT_FALSE(unset.has_id()); + EXPECT_FALSE(unset.has_sender_identity()); + + StreamByteOptions options; + options.topic = "files"; + options.attributes = {{"k", "v"}}; + options.destination_identities = {"alice"}; + options.stream_id = "stream-2"; + options.name = "photo.jpg"; + options.mime_type = "image/jpeg"; + options.total_length = 1234; + options.compress = false; + options.sender_identity = "agent"; + const auto proto = toProto(options); + EXPECT_EQ(proto.topic(), "files"); + EXPECT_EQ(attrs(proto.attributes()), (std::map{{"k", "v"}})); + EXPECT_EQ(proto.destination_identities(0), "alice"); + EXPECT_EQ(proto.id(), "stream-2"); + EXPECT_EQ(proto.name(), "photo.jpg"); + EXPECT_EQ(proto.mime_type(), "image/jpeg"); + EXPECT_EQ(proto.total_length(), 1234u); + EXPECT_FALSE(proto.compress()); + EXPECT_EQ(proto.sender_identity(), "agent"); +} + TEST(DataStreamConversionTest, TextInfoFromProto) { proto::TextStreamInfo in; in.set_stream_id("s1"); @@ -252,8 +324,28 @@ TEST(DataStreamConversionTest, ByteInfoFromProto) { EXPECT_EQ(*out.size, 2048u); } +// --------------------------------------------------------------------------- +// One-shot sends refuse to reach an uninitialized FFI +// --------------------------------------------------------------------------- + +TEST(DataStreamSendTest, SendsThrowWhenNotInitialized) { + ASSERT_FALSE(FfiClient::instance().isInitialized()); + LocalParticipant participant(FfiHandle(0), "sid", "name", "identity", "", {}, ParticipantKind::Standard, + DisconnectReason::Unknown); + StreamTextOptions text_options; + text_options.topic = "t"; + StreamByteOptions byte_options; + byte_options.topic = "t"; + EXPECT_THROW((void)participant.sendText("hi", text_options), DataStreamError); + EXPECT_THROW((void)participant.sendBytes({1, 2}, byte_options), DataStreamError); + EXPECT_THROW((void)participant.sendFile("/tmp/does-not-matter", byte_options), DataStreamError); +} + TEST(DataStreamSendTest, FfiHelpersThrowWhenNotInitialized) { ASSERT_FALSE(FfiClient::instance().isInitialized()); + EXPECT_THROW(FfiClient::instance().sendTextAsync(1, "hi", proto::StreamTextOptions{}), std::runtime_error); + EXPECT_THROW(FfiClient::instance().sendBytesAsync(1, {1}, proto::StreamByteOptions{}), std::runtime_error); + EXPECT_THROW(FfiClient::instance().sendFileAsync(1, "/tmp/x", proto::StreamByteOptions{}), std::runtime_error); EXPECT_THROW(FfiClient::instance().textStreamReadIncremental(1), std::runtime_error); EXPECT_THROW(FfiClient::instance().byteStreamReadIncremental(1), std::runtime_error); } From 799e4aa864e0adb6df079a4fb39bf66b3e92e374 Mon Sep 17 00:00:00 2001 From: Ryan Gaus Date: Mon, 30 Nov 2026 20:44:04 +1300 Subject: [PATCH 2/3] Expose text stream operation type, version and generated Text stream headers carry an operation type (create, update, delete, reaction), an optional message version and a generated flag; agents, for example, mark transcriptions as generated. The C++ SDK dropped them. - TextStreamOperationType, plus operation_type / version / generated on StreamTextOptions and TextStreamInfo. - Only non-default values are put on the wire, matching the other SDKs. - Tests: remote header fields surface on TextStreamInfo, sendText puts them on the wire, and the defaults are create, unversioned, not generated. Co-Authored-By: Claude Opus 5.5 --- include/livekit/data_stream.h | 28 +++++ src/data_stream_proto_converter.cpp | 43 +++++++ src/data_stream_proto_converter.h | 10 ++ ...st_data_stream_conformance_text_header.cpp | 112 ++++++++++++++++++ src/tests/unit/test_data_stream.cpp | 28 +++++ 5 files changed, 221 insertions(+) create mode 100644 src/tests/integration/test_data_stream_conformance_text_header.cpp diff --git a/include/livekit/data_stream.h b/include/livekit/data_stream.h index 85d5e74e..35fa39d4 100644 --- a/include/livekit/data_stream.h +++ b/include/livekit/data_stream.h @@ -57,6 +57,17 @@ class LIVEKIT_API DataStreamError : public std::runtime_error { explicit DataStreamError(const std::string& message); }; +/// @brief What a text stream does to the conversation it belongs to. +/// +/// Chat-style applications use it to distinguish new messages from edits, +/// deletions and reactions; the SDK only transports it. +enum class TextStreamOperationType { + Create = 0, + Update = 1, + Delete = 2, + Reaction = 3, +}; + /// @brief Options for a one-shot text send or an incremental text stream. /// /// Used by LocalParticipant::sendText(). @@ -81,6 +92,16 @@ struct StreamTextOptions { /// Ids of other streams (for example files) attached to this text stream. std::vector attached_stream_ids; + /// Operation this stream performs (new message, edit, deletion, reaction). + TextStreamOperationType operation_type = TextStreamOperationType::Create; + + /// Version of the message this stream creates or updates, if any. + std::optional version; + + /// Whether the text was generated, for example by an agent transcribing a + /// participant's speech. + bool generated = false; + /// Compress the payload when every recipient supports compression. /// /// Only one-shot sends compress; incremental writers ignore this flag. @@ -160,6 +181,13 @@ struct TextStreamInfo : BaseStreamInfo { std::vector attachments; /// If this stream is a reply to another stream, this field holds its ID std::optional reply_to_stream_id; + /// Operation this stream performs (new message, edit, deletion, reaction). + TextStreamOperationType operation_type = TextStreamOperationType::Create; + /// Version of the message this stream creates or updates, if the sender set one. + std::optional version; + /// Whether the text was generated, for example by an agent transcribing a + /// participant's speech. + bool generated = false; }; /// Metadata for a byte stream. diff --git a/src/data_stream_proto_converter.cpp b/src/data_stream_proto_converter.cpp index 0cb087d3..1dbc15a1 100644 --- a/src/data_stream_proto_converter.cpp +++ b/src/data_stream_proto_converter.cpp @@ -18,6 +18,34 @@ namespace livekit { +proto::TextStreamInfo::OperationType toProto(TextStreamOperationType in) { + switch (in) { + case TextStreamOperationType::Update: + return proto::TextStreamInfo::UPDATE; + case TextStreamOperationType::Delete: + return proto::TextStreamInfo::DELETE; + case TextStreamOperationType::Reaction: + return proto::TextStreamInfo::REACTION; + case TextStreamOperationType::Create: + default: + return proto::TextStreamInfo::CREATE; + } +} + +TextStreamOperationType fromProto(proto::TextStreamInfo::OperationType in) { + switch (in) { + case proto::TextStreamInfo::UPDATE: + return TextStreamOperationType::Update; + case proto::TextStreamInfo::DELETE: + return TextStreamOperationType::Delete; + case proto::TextStreamInfo::REACTION: + return TextStreamOperationType::Reaction; + case proto::TextStreamInfo::CREATE: + default: + return TextStreamOperationType::Create; + } +} + proto::StreamTextOptions toProto(const StreamTextOptions& in) { proto::StreamTextOptions out; out.set_topic(in.topic); @@ -36,6 +64,16 @@ proto::StreamTextOptions toProto(const StreamTextOptions& in) { for (const auto& id : in.attached_stream_ids) { out.add_attached_stream_ids(id); } + // Unset means Create / not generated on the wire; only send non-defaults. + if (in.operation_type != TextStreamOperationType::Create) { + out.set_operation_type(toProto(in.operation_type)); + } + if (in.version) { + out.set_version(*in.version); + } + if (in.generated) { + out.set_generated(true); + } out.set_compress(in.compress); if (in.sender_identity) { out.set_sender_identity(*in.sender_identity); @@ -89,6 +127,11 @@ TextStreamInfo fromProto(const proto::TextStreamInfo& in) { if (in.has_reply_to_stream_id()) { out.reply_to_stream_id = in.reply_to_stream_id(); } + out.operation_type = fromProto(in.operation_type()); + if (in.has_version()) { + out.version = in.version(); + } + out.generated = in.generated(); return out; } diff --git a/src/data_stream_proto_converter.h b/src/data_stream_proto_converter.h index acf3c0ee..7b98243e 100644 --- a/src/data_stream_proto_converter.h +++ b/src/data_stream_proto_converter.h @@ -22,6 +22,16 @@ namespace livekit { +/// @brief Convert a text stream operation type to the FFI enum. +/// @param in C++ operation type. +/// @return The FFI enum value. +LIVEKIT_INTERNAL_API proto::TextStreamInfo::OperationType toProto(TextStreamOperationType in); + +/// @brief Convert an FFI text stream operation type to the public enum. +/// @param in FFI enum value. +/// @return The C++ operation type. +LIVEKIT_INTERNAL_API TextStreamOperationType fromProto(proto::TextStreamInfo::OperationType in); + /// @brief Convert one-shot text send options to the FFI proto. /// @param in C++ options. /// @return The FFI options; `compress` is always set explicitly. diff --git a/src/tests/integration/test_data_stream_conformance_text_header.cpp b/src/tests/integration/test_data_stream_conformance_text_header.cpp new file mode 100644 index 00000000..592d7bf5 --- /dev/null +++ b/src/tests/integration/test_data_stream_conformance_text_header.cpp @@ -0,0 +1,112 @@ +/* + * Copyright 2026 LiveKit + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Text stream header fields (operation type, version, generated, reply-to) +// in both directions: another SDK's text stream must surface them on the C++ +// TextStreamInfo, and C++ text streams must put them on the wire. Agents, for +// example, mark transcriptions with `generated`. +// +// Run with: +// ./build-debug/bin/livekit_integration_tests --gtest_filter=DataStreamTextHeader* + +#include + +#include + +#include "../common/data_stream_test_utils.h" + +namespace livekit::test::ds { + +class DataStreamTextHeaderTest : public DataStreamConformanceTest {}; + +TEST_F(DataStreamTextHeaderTest, RemoteHeaderFieldsSurfaceOnInfo) { + const auto topic = uniqueTopic("hdr_recv"); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + + PeerTextOptions opts; + opts.topic = topic; + opts.operation_type = static_cast(TextStreamOperationType::Update); + opts.version = 3; + opts.generated = true; + opts.reply_to_stream_id = "original"; + ASSERT_TRUE(peer.sendText("edited", opts).ok); // one-shot (inline) + const auto writer = peer.openText(opts); // writer (multi-packet) + ASSERT_TRUE(writer.ok) << writer.error; + ASSERT_TRUE(peer.writeText(writer.writer_handle, "edited again").ok); + ASSERT_TRUE(peer.closeText(writer.writer_handle).ok); + + ASSERT_TRUE(collector.waitFor(2)); + for (const auto& s : collector.streams()) { + EXPECT_FALSE(s.errored) << s.error; + EXPECT_EQ(s.info.operation_type, TextStreamOperationType::Update); + ASSERT_TRUE(s.info.version.has_value()); + EXPECT_EQ(*s.info.version, 3); + EXPECT_TRUE(s.info.generated); + ASSERT_TRUE(s.info.reply_to_stream_id.has_value()); + EXPECT_EQ(*s.info.reply_to_stream_id, "original"); + } +} + +TEST_F(DataStreamTextHeaderTest, LocalHeaderFieldsAreSent) { + const auto topic = uniqueTopic("hdr_send"); + RawPacketSniffer sniffer(receiverRoom()); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + auto sender = lockLocalParticipant(senderRoom()); + + StreamTextOptions opts; + opts.topic = topic; + opts.operation_type = TextStreamOperationType::Reaction; + opts.version = 5; + opts.generated = true; + const auto info = sender->sendText("+1", opts); + EXPECT_EQ(info.operation_type, TextStreamOperationType::Reaction); + + ASSERT_TRUE(collector.waitFor(1)); + for (const auto& s : collector.streams()) { + EXPECT_FALSE(s.errored) << s.error; + EXPECT_EQ(s.info.operation_type, TextStreamOperationType::Reaction); + ASSERT_TRUE(s.info.version.has_value()); + EXPECT_EQ(*s.info.version, 5); + EXPECT_TRUE(s.info.generated); + } + const auto headers = sniffer.headers(topic); + ASSERT_EQ(headers.size(), 1U); + for (const auto& h : headers) { + EXPECT_EQ(h.operation_type, static_cast(TextStreamOperationType::Reaction)); + EXPECT_EQ(h.version, 5); + EXPECT_TRUE(h.generated); + } +} + +TEST_F(DataStreamTextHeaderTest, DefaultsAreCreateUnversionedNotGenerated) { + const auto topic = uniqueTopic("hdr_default"); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + StreamTextOptions opts; + opts.topic = topic; + (void)lockLocalParticipant(senderRoom())->sendText("plain", opts); + + ASSERT_TRUE(collector.waitFor(1)); + const auto s = collector.only(); + EXPECT_EQ(s.info.operation_type, TextStreamOperationType::Create); + EXPECT_FALSE(s.info.generated); +} + +} // namespace livekit::test::ds diff --git a/src/tests/unit/test_data_stream.cpp b/src/tests/unit/test_data_stream.cpp index 198d9a6a..fc5bd389 100644 --- a/src/tests/unit/test_data_stream.cpp +++ b/src/tests/unit/test_data_stream.cpp @@ -216,6 +216,9 @@ TEST(DataStreamConversionTest, TextOptionsDefaultsToProto) { EXPECT_FALSE(proto.has_id()); EXPECT_FALSE(proto.has_reply_to_stream_id()); EXPECT_FALSE(proto.has_sender_identity()); + EXPECT_FALSE(proto.has_operation_type()) << "Create is the wire default"; + EXPECT_FALSE(proto.has_version()); + EXPECT_FALSE(proto.has_generated()); EXPECT_EQ(proto.destination_identities_size(), 0); } @@ -227,10 +230,16 @@ TEST(DataStreamConversionTest, TextOptionsAllFieldsToProto) { options.stream_id = "stream-1"; options.reply_to_stream_id = "stream-0"; options.attached_stream_ids = {"file-1"}; + options.operation_type = TextStreamOperationType::Update; + options.version = 3; + options.generated = true; options.compress = false; options.sender_identity = "agent"; const auto proto = toProto(options); + EXPECT_EQ(proto.operation_type(), proto::TextStreamInfo::UPDATE); + EXPECT_EQ(proto.version(), 3); + EXPECT_TRUE(proto.generated()); EXPECT_EQ(attrs(proto.attributes()), (std::map{{"k", "v"}})); ASSERT_EQ(proto.destination_identities_size(), 2); EXPECT_EQ(proto.destination_identities(1), "bob"); @@ -304,6 +313,25 @@ TEST(DataStreamConversionTest, TextInfoFromProto) { ASSERT_TRUE(out.size.has_value()); EXPECT_EQ(*out.size, 10u); EXPECT_FALSE(out.reply_to_stream_id.has_value()); + EXPECT_EQ(out.operation_type, TextStreamOperationType::Create); + EXPECT_FALSE(out.version.has_value()); + EXPECT_FALSE(out.generated); + + in.set_operation_type(proto::TextStreamInfo::REACTION); + in.set_version(7); + in.set_generated(true); + out = fromProto(in); + EXPECT_EQ(out.operation_type, TextStreamOperationType::Reaction); + ASSERT_TRUE(out.version.has_value()); + EXPECT_EQ(*out.version, 7); + EXPECT_TRUE(out.generated); +} + +TEST(DataStreamConversionTest, TextOperationTypeRoundTrips) { + for (const auto type : {TextStreamOperationType::Create, TextStreamOperationType::Update, + TextStreamOperationType::Delete, TextStreamOperationType::Reaction}) { + EXPECT_EQ(fromProto(toProto(type)), type); + } } TEST(DataStreamConversionTest, ByteInfoFromProto) { From 3bbc5116d47189e33bf9f37fa525b566ffc4a150 Mon Sep 17 00:00:00 2001 From: Ryan Gaus Date: Mon, 30 Nov 2026 20:44:04 +1300 Subject: [PATCH 3/3] Add send-side conformance tests for one-shot sends Ports the Rust outgoing-manager tests that sendText / sendBytes / sendFile can reproduce, checking the raw packets the receiving room gets: - Inline (single packet) vs multi-packet, and compressed vs not, for short, large-but-compressible, somewhat compressible and incompressible payloads, with and without compress. - Text with attachments never inlines; empty text is one inline packet. - sendFile never inlines, compresses when eligible, splits uncompressed files at the 15000-byte MTU, and handles empty and missing files. - Oversized attributes throw, and a broadcast to an empty room succeeds. Co-Authored-By: Claude Opus 5.5 --- .../test_data_stream_conformance_send.cpp | 528 ++++++++++++++++++ 1 file changed, 528 insertions(+) create mode 100644 src/tests/integration/test_data_stream_conformance_send.cpp diff --git a/src/tests/integration/test_data_stream_conformance_send.cpp b/src/tests/integration/test_data_stream_conformance_send.cpp new file mode 100644 index 00000000..1d3143b1 --- /dev/null +++ b/src/tests/integration/test_data_stream_conformance_send.cpp @@ -0,0 +1,528 @@ +/* + * Copyright 2026 LiveKit + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Send-side data stream conformance: the C++ SDK sends through its public API +// (sendText / sendBytes / sendFile), and the receiving room's raw packets are +// checked against what the Rust `livekit-data-stream` crate's outgoing-manager +// tests require (client-sdk-rust/livekit-data-stream/src/outgoing/manager.rs), +// along with the content the receiver's reader delivers. +// +// All test participants are FFI clients and advertise data streams v2 with +// deflate-raw compression, so every recipient here is "v2 capable". The raw +// header event carries neither `inline_content` nor `compression`, so an +// inline stream is observed as a header with no chunk or trailer packets, and +// compression as chunk bytes that differ from (and are smaller than) the +// payload. +// +// Run with: +// ./build-debug/bin/livekit_integration_tests --gtest_filter=DataStreamSend* + +#include + +#include +#include +#include +#include +#include + +#include "../common/data_stream_test_utils.h" + +namespace livekit::test::ds { + +namespace { + +/// "hello hello compressible world": 30 bytes that deflate to 28. +const std::string kShortCompressible = "hello hello compressible world"; + +/// Waits for the header on `topic`, then checks no chunk or trailer follows. +RawHeader expectInline(const RawPacketSniffer& sniffer, const std::string& topic) { + const auto header = sniffer.waitForHeader(topic); + EXPECT_TRUE(header.has_value()) << "no raw header received"; + if (!header) { + return {}; + } + std::this_thread::sleep_for(kQuietPeriod); + EXPECT_TRUE(sniffer.chunks(header->stream_id).empty()) << "inline stream must not send chunk packets"; + EXPECT_TRUE(sniffer.trailers(header->stream_id).empty()) << "inline stream must not send a trailer packet"; + return *header; +} + +/// Waits for a complete multi-packet stream on `topic` and returns its header. +RawHeader expectMultipacket(const RawPacketSniffer& sniffer, const std::string& topic) { + const auto header = sniffer.waitForHeader(topic); + EXPECT_TRUE(header.has_value()) << "no raw header received"; + if (!header) { + return {}; + } + const auto trailer = sniffer.waitForTrailer(header->stream_id); + EXPECT_TRUE(trailer.has_value()) << "multi-packet stream must end with a trailer"; + if (trailer) { + EXPECT_EQ(trailer->reason, ""); + } + return *header; +} + +std::vector chunkSizes(const RawPacketSniffer& sniffer, const std::string& stream_id) { + std::vector sizes; + for (const auto& c : sniffer.chunks(stream_id)) { + sizes.push_back(c.content.size()); + } + return sizes; +} + +std::vector chunkIndices(const RawPacketSniffer& sniffer, const std::string& stream_id) { + std::vector indices; + for (const auto& c : sniffer.chunks(stream_id)) { + indices.push_back(c.chunk_index); + } + return indices; +} + +/// A file in a fresh temporary directory, removed on destruction. +class TempFile { +public: + TempFile(const std::string& name, const std::string& content) { + dir_ = std::filesystem::temp_directory_path() / uniqueStreamId("ds_conf_file"); + std::filesystem::create_directories(dir_); + path_ = dir_ / name; + std::ofstream out(path_, std::ios::binary); + out.write(content.data(), static_cast(content.size())); + } + ~TempFile() { + std::error_code ec; + std::filesystem::remove_all(dir_, ec); + } + TempFile(const TempFile&) = delete; + TempFile& operator=(const TempFile&) = delete; + TempFile(TempFile&&) = delete; + TempFile& operator=(TempFile&&) = delete; + + std::string path() const { return path_.string(); } + +private: + std::filesystem::path dir_; + std::filesystem::path path_; +}; + +} // namespace + +class DataStreamSendConformanceTest : public DataStreamConformanceTest { +protected: + std::shared_ptr sender() { return lockLocalParticipant(senderRoom()); } + + StreamTextOptions textOptions(const std::string& topic) { + StreamTextOptions opts; + opts.topic = topic; + return opts; + } + + StreamByteOptions byteOptions(const std::string& topic) { + StreamByteOptions opts; + opts.topic = topic; + return opts; + } +}; + +// --------------------------------------------------------------------------- +// sendText +// --------------------------------------------------------------------------- + +// Rust: v2_short_incompressible_text_inlines_raw +TEST_F(DataStreamSendConformanceTest, SendTextShortIncompressibleInlines) { + const auto topic = uniqueTopic("send_short"); + RawPacketSniffer sniffer(receiverRoom()); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + const auto info = sender()->sendText("short", textOptions(topic)); + + const auto header = expectInline(sniffer, topic); + EXPECT_EQ(header.stream_id, info.stream_id); + EXPECT_TRUE(header.is_text); + EXPECT_EQ(header.mime_type, "text/plain"); + ASSERT_TRUE(header.total_length.has_value()); + EXPECT_EQ(*header.total_length, 5U); + ASSERT_TRUE(collector.waitFor(1)); + EXPECT_EQ(collector.only().content, "short"); +} + +// Rust: v2_short_compressible_text_inlines_compressed, +// v2_broadcast_all_capable_inlines_compressed +TEST_F(DataStreamSendConformanceTest, SendTextShortCompressibleInlines) { + const auto topic = uniqueTopic("send_short_z"); + RawPacketSniffer sniffer(receiverRoom()); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + (void)sender()->sendText(kShortCompressible, textOptions(topic)); + + const auto header = expectInline(sniffer, topic); + ASSERT_TRUE(header.total_length.has_value()); + EXPECT_EQ(*header.total_length, kShortCompressible.size()); + ASSERT_TRUE(collector.waitFor(1)); + EXPECT_EQ(collector.only().content, kShortCompressible); +} + +// Rust: v2_large_highly_compressible_text_still_inlines +TEST_F(DataStreamSendConformanceTest, SendTextLargeHighlyCompressibleStillInlines) { + const auto topic = uniqueTopic("send_large_z"); + std::string text; + for (int i = 0; i < 20'000; ++i) { + text += "hello world"; + } + RawPacketSniffer sniffer(receiverRoom()); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + (void)sender()->sendText(text, textOptions(topic)); + + const auto header = expectInline(sniffer, topic); + ASSERT_TRUE(header.total_length.has_value()); + EXPECT_EQ(*header.total_length, text.size()) << "total_length is the uncompressed length"; + ASSERT_TRUE(collector.waitFor(1)); + EXPECT_EQ(collector.only().content, text); +} + +// Rust: v2_somewhat_compressible_text_is_compressed_multipacket +TEST_F(DataStreamSendConformanceTest, SendTextSomewhatCompressibleIsCompressedMultipacket) { + const auto topic = uniqueTopic("send_somewhat_z"); + const auto text = randomText(50'000); + RawPacketSniffer sniffer(receiverRoom()); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + (void)sender()->sendText(text, textOptions(topic)); + + const auto header = expectMultipacket(sniffer, topic); + ASSERT_TRUE(header.total_length.has_value()); + EXPECT_EQ(*header.total_length, text.size()); + const auto sizes = chunkSizes(sniffer, header.stream_id); + ASSERT_GE(sizes.size(), 2U); + EXPECT_LT(sizes.size(), 4U) << "compressed chunks are fewer than uncompressed ones would be"; + EXPECT_EQ(sizes.front(), kMtu); + const auto raw = sniffer.rawContent(header.stream_id); + EXPECT_LT(raw.size(), text.size()); + EXPECT_NE(raw, text.substr(0, raw.size())) << "chunks must carry compressed bytes"; + ASSERT_TRUE(collector.waitFor(1)); + EXPECT_EQ(collector.only().content, text); +} + +// Rust: v2_compress_false_short_inlines_raw +TEST_F(DataStreamSendConformanceTest, SendTextCompressFalseShortInlines) { + const auto topic = uniqueTopic("send_nocomp_short"); + RawPacketSniffer sniffer(receiverRoom()); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + auto opts = textOptions(topic); + opts.compress = false; + (void)sender()->sendText(kShortCompressible, opts); + + (void)expectInline(sniffer, topic); + ASSERT_TRUE(collector.waitFor(1)); + EXPECT_EQ(collector.only().content, kShortCompressible); +} + +// Rust: v2_compress_false_large_is_uncompressed_multipacket +TEST_F(DataStreamSendConformanceTest, SendTextCompressFalseLargeIsUncompressedMultipacket) { + const auto topic = uniqueTopic("send_nocomp_large"); + const std::string text(50'000, 'B'); + RawPacketSniffer sniffer(receiverRoom()); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + auto opts = textOptions(topic); + opts.compress = false; + (void)sender()->sendText(text, opts); + + const auto header = expectMultipacket(sniffer, topic); + EXPECT_EQ(chunkSizes(sniffer, header.stream_id), (std::vector{kMtu, kMtu, kMtu, 5'000})); + EXPECT_EQ(chunkIndices(sniffer, header.stream_id), (std::vector{0, 1, 2, 3})); + EXPECT_EQ(sniffer.rawContent(header.stream_id), text) << "uncompressed chunks carry the text verbatim"; + ASSERT_TRUE(collector.waitFor(1)); + EXPECT_EQ(collector.only().content, text); +} + +// Rust: v2_send_text_with_attachments_never_inlines +TEST_F(DataStreamSendConformanceTest, SendTextWithAttachmentsNeverInlines) { + const auto topic = uniqueTopic("send_attach"); + RawPacketSniffer sniffer(receiverRoom()); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + auto opts = textOptions(topic); + opts.attached_stream_ids = {"att1"}; + (void)sender()->sendText(kShortCompressible, opts); + + const auto header = expectMultipacket(sniffer, topic); + EXPECT_EQ(header.attached_stream_ids, std::vector{"att1"}); + EXPECT_EQ(sniffer.chunks(header.stream_id).size(), 1U); + ASSERT_TRUE(collector.waitFor(1)); + const auto s = collector.only(); + EXPECT_EQ(s.content, kShortCompressible); + EXPECT_EQ(s.info.attachments, std::vector{"att1"}); +} + +// Rust: v2_empty_text_sends_single_inline_packet +TEST_F(DataStreamSendConformanceTest, SendTextEmptyIsSingleInlinePacket) { + const auto topic = uniqueTopic("send_empty"); + RawPacketSniffer sniffer(receiverRoom()); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + (void)sender()->sendText("", textOptions(topic)); + + const auto header = expectInline(sniffer, topic); + ASSERT_TRUE(header.total_length.has_value()); + EXPECT_EQ(*header.total_length, 0U); + ASSERT_TRUE(collector.waitFor(1)); + const auto s = collector.only(); + EXPECT_FALSE(s.errored) << s.error; + EXPECT_EQ(s.content, ""); +} + +// Rust: oversized_attributes_on_chunked_path_errors +TEST_F(DataStreamSendConformanceTest, SendTextOversizedAttributesThrows) { + const auto topic = uniqueTopic("send_big_attrs"); + RawPacketSniffer sniffer(receiverRoom()); + + auto opts = textOptions(topic); + opts.attributes = {{"big", std::string(20'000, 'x')}}; + try { + (void)sender()->sendText("hello", opts); + FAIL() << "a header over the packet size limit must be rejected"; + } catch (const DataStreamError& e) { + EXPECT_NE(std::string(e.what()).find("stream header exceeds maximum size"), std::string::npos) << e.what(); + } + EXPECT_FALSE(sniffer.waitForHeader(topic, kQuietPeriod).has_value()) << "nothing may be sent"; +} + +// --------------------------------------------------------------------------- +// sendBytes +// --------------------------------------------------------------------------- + +// Rust: v2_send_bytes_short_incompressible_inlines_raw +TEST_F(DataStreamSendConformanceTest, SendBytesShortIncompressibleInlines) { + const auto topic = uniqueTopic("bytes_short"); + const std::vector payload{0, 1, 2, 3}; + RawPacketSniffer sniffer(receiverRoom()); + ByteStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + (void)sender()->sendBytes(payload, byteOptions(topic)); + + const auto header = expectInline(sniffer, topic); + EXPECT_FALSE(header.is_text); + ASSERT_TRUE(collector.waitFor(1)); + EXPECT_EQ(collector.only().content, fromBytes(payload)); +} + +// Rust: v2_send_bytes_short_compressible_inlines_compressed (incl. returned info) +TEST_F(DataStreamSendConformanceTest, SendBytesShortCompressibleInlinesAndReturnsInfo) { + const auto topic = uniqueTopic("bytes_short_z"); + RawPacketSniffer sniffer(receiverRoom()); + ByteStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + auto opts = byteOptions(topic); + opts.attributes = {{"foo", "bar"}}; + const auto info = sender()->sendBytes(toBytes(kShortCompressible), opts); + + EXPECT_EQ(info.name, "unknown"); + EXPECT_EQ(info.mime_type, "application/octet-stream"); + ASSERT_TRUE(info.size.has_value()); + EXPECT_EQ(*info.size, kShortCompressible.size()); + EXPECT_EQ(info.attributes.at("foo"), "bar"); + const auto header = expectInline(sniffer, topic); + EXPECT_EQ(header.stream_id, info.stream_id); + EXPECT_EQ(header.name, "unknown"); + ASSERT_TRUE(collector.waitFor(1)); + const auto s = collector.only(); + EXPECT_EQ(s.content, kShortCompressible); + EXPECT_EQ(s.info.name, "unknown"); + EXPECT_EQ(s.info.attributes.at("foo"), "bar"); +} + +// Rust: v2_send_bytes_large_highly_compressible_inlines +TEST_F(DataStreamSendConformanceTest, SendBytesLargeHighlyCompressibleInlines) { + const auto topic = uniqueTopic("bytes_large_z"); + const std::string payload(50'000, '\x01'); + RawPacketSniffer sniffer(receiverRoom()); + ByteStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + (void)sender()->sendBytes(toBytes(payload), byteOptions(topic)); + + const auto header = expectInline(sniffer, topic); + ASSERT_TRUE(header.total_length.has_value()); + EXPECT_EQ(*header.total_length, 50'000U) << "total_length is the pre-compression length"; + ASSERT_TRUE(collector.waitFor(1)); + EXPECT_EQ(collector.only().content, payload); +} + +// Rust: v2_send_bytes_somewhat_compressible_is_compressed_multipacket +TEST_F(DataStreamSendConformanceTest, SendBytesSomewhatCompressibleIsCompressedMultipacket) { + const auto topic = uniqueTopic("bytes_somewhat_z"); + const auto payload = randomText(50'000); + RawPacketSniffer sniffer(receiverRoom()); + ByteStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + (void)sender()->sendBytes(toBytes(payload), byteOptions(topic)); + + const auto header = expectMultipacket(sniffer, topic); + EXPECT_FALSE(header.is_text); + const auto sizes = chunkSizes(sniffer, header.stream_id); + ASSERT_GE(sizes.size(), 2U); + EXPECT_LT(sizes.size(), 4U); + EXPECT_EQ(sizes.front(), kMtu); + EXPECT_LT(sniffer.rawContent(header.stream_id).size(), payload.size()); + ASSERT_TRUE(collector.waitFor(1)); + EXPECT_EQ(collector.only().content, payload); +} + +// Rust: v2_send_bytes_compress_false_large_is_uncompressed_multipacket +TEST_F(DataStreamSendConformanceTest, SendBytesCompressFalseLargeIsUncompressedMultipacket) { + const auto topic = uniqueTopic("bytes_nocomp_large"); + const std::string payload(40'000, '\x07'); + RawPacketSniffer sniffer(receiverRoom()); + ByteStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + auto opts = byteOptions(topic); + opts.compress = false; + (void)sender()->sendBytes(toBytes(payload), opts); + + const auto header = expectMultipacket(sniffer, topic); + EXPECT_EQ(chunkSizes(sniffer, header.stream_id), (std::vector{kMtu, kMtu, 10'000})); + EXPECT_EQ(sniffer.rawContent(header.stream_id), payload); + ASSERT_TRUE(collector.waitFor(1)); + EXPECT_EQ(collector.only().content, payload); +} + +// --------------------------------------------------------------------------- +// sendFile +// --------------------------------------------------------------------------- + +// Rust: send_file_never_inlines_and_compresses_when_eligible +TEST_F(DataStreamSendConformanceTest, SendFileNeverInlinesAndCompresses) { + const auto topic = uniqueTopic("file_z"); + const std::string content(10'000, '\x01'); + TempFile file("ones.bin", content); + RawPacketSniffer sniffer(receiverRoom()); + ByteStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + const auto info = sender()->sendFile(file.path(), byteOptions(topic)); + + EXPECT_EQ(info.name, "ones.bin") << "the name defaults to the file's name"; + const auto header = expectMultipacket(sniffer, topic); + ASSERT_TRUE(header.total_length.has_value()); + EXPECT_EQ(*header.total_length, content.size()); + const auto sizes = chunkSizes(sniffer, header.stream_id); + ASSERT_EQ(sizes.size(), 1U); + EXPECT_LT(sizes.front(), content.size()) << "the chunk must carry compressed bytes"; + ASSERT_TRUE(collector.waitFor(1)); + const auto s = collector.only(); + EXPECT_EQ(s.content, content); + EXPECT_EQ(s.info.name, "ones.bin"); +} + +// Rust: send_file_uncompressed_splits_at_mtu, send_file_streams_one_packet_per_request +TEST_F(DataStreamSendConformanceTest, SendFileUncompressedSplitsAtMtu) { + const auto topic = uniqueTopic("file_nocomp"); + const std::string content(20'000, '\x07'); + TempFile file("sevens.bin", content); + RawPacketSniffer sniffer(receiverRoom()); + ByteStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + auto opts = byteOptions(topic); + opts.compress = false; + (void)sender()->sendFile(file.path(), opts); + + const auto header = expectMultipacket(sniffer, topic); + EXPECT_EQ(chunkSizes(sniffer, header.stream_id), (std::vector{kMtu, 5'000})); + EXPECT_EQ(chunkIndices(sniffer, header.stream_id), (std::vector{0, 1})); + EXPECT_EQ(sniffer.rawContent(header.stream_id), content); + ASSERT_TRUE(collector.waitFor(1)); + EXPECT_EQ(collector.only().content, content); +} + +// Rust: send_file_incompressible_compressed_expands +TEST_F(DataStreamSendConformanceTest, SendFileIncompressibleCompressedExpands) { + const auto topic = uniqueTopic("file_random"); + const auto content = randomBytes(50'000); + TempFile file("random.bin", content); + RawPacketSniffer sniffer(receiverRoom()); + ByteStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + (void)sender()->sendFile(file.path(), byteOptions(topic)); + + const auto header = expectMultipacket(sniffer, topic); + const auto sizes = chunkSizes(sniffer, header.stream_id); + ASSERT_EQ(sizes.size(), 4U); + EXPECT_EQ(sizes.front(), kMtu); + EXPECT_GT(sniffer.rawContent(header.stream_id).size(), content.size()) + << "sendFile compresses whenever the recipients support it, even if that expands the data"; + ASSERT_TRUE(collector.waitFor(1)); + EXPECT_EQ(collector.only().content, content); +} + +// Rust: send_file_empty_file, send_file_reports_progress_for_empty_file +TEST_F(DataStreamSendConformanceTest, SendFileEmptyFile) { + const auto topic = uniqueTopic("file_empty"); + TempFile file("empty.bin", ""); + RawPacketSniffer sniffer(receiverRoom()); + ByteStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + (void)sender()->sendFile(file.path(), byteOptions(topic)); + + const auto header = expectMultipacket(sniffer, topic); + ASSERT_TRUE(header.total_length.has_value()); + EXPECT_EQ(*header.total_length, 0U); + ASSERT_TRUE(collector.waitFor(1)); + const auto s = collector.only(); + EXPECT_FALSE(s.errored) << s.error; + EXPECT_EQ(s.content, ""); +} + +TEST_F(DataStreamSendConformanceTest, SendFileMissingFileThrows) { + const auto topic = uniqueTopic("file_missing"); + const auto missing = (std::filesystem::temp_directory_path() / uniqueStreamId("missing") / "nope.bin").string(); + EXPECT_THROW((void)sender()->sendFile(missing, byteOptions(topic)), DataStreamError); +} + +// --------------------------------------------------------------------------- +// Routing and identity +// --------------------------------------------------------------------------- + +// Rust: empty_room_broadcast_is_v2_eligible +TEST_F(DataStreamSendConformanceTest, BroadcastToEmptyRoomSucceeds) { + (void)receiverRoom().disconnect(); + const auto deadline = std::chrono::steady_clock::now() + kStreamTimeout; + while (!senderRoom().remoteParticipants().empty() && std::chrono::steady_clock::now() < deadline) { + std::this_thread::sleep_for(50ms); + } + ASSERT_TRUE(senderRoom().remoteParticipants().empty()); + const auto topic = uniqueTopic("empty_room"); + EXPECT_NO_THROW((void)sender()->sendText(kShortCompressible, textOptions(topic))); + EXPECT_NO_THROW((void)sender()->sendBytes(toBytes(kShortCompressible), byteOptions(topic))); +} + +} // namespace livekit::test::ds