Skip to content

Commit beb795d

Browse files
1egomanclaude
andcommitted
Port data stream receive path to FFI readers; add sendText/sendBytes/sendFile
Incoming data streams were rebuilt from the low-level stream_header/chunk/ trailer events. Since livekit-ffi 0.15.0 always advertises data streams v2, modern senders send C++ participants single-packet and deflate-compressed streams, which that path can't read: inline streams hang readAll() forever and compressed chunks arrive as raw deflate bytes. The FFI also handed C++ an owned reader handle for every incoming stream, which C++ ignored, so every stream's content stayed buffered in the FFI for the life of the process. Receive: - Room consumes text/byte_stream_opened: unhandled topics drop the reader handle; handled topics start read_incremental and route the resulting *_stream_reader_events (keyed by reader handle) to the reader. The low-level stream_*_received events are now ignored. - Readers surface abnormal ends (sender close reason, size limit, disconnect) as DataStreamError after draining buffered chunks, merge end-of-stream attributes into info() on the reading thread, gain close(), and ByteStreamReader gains readAll(). Room shutdown wakes blocked readers. - RoomOptions::data_stream.max_payload_byte_length sets the receive limit. Send: - LocalParticipant::sendText / sendBytes / sendFile use the FFI one-shot sends (compression and single-packet delivery when recipients support them). They throw DataStreamError on failure and refuse to reach the FFI once the room has disconnected, since the FFI panics there. TextStreamOpenedEvent / ByteStreamOpenedEvent::reader_handle stays 0 and is documented as deprecated. Existing writers are unchanged (v1 framing is still accepted by FFI readers). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 544211e commit beb795d

17 files changed

Lines changed: 1758 additions & 233 deletions

‎AGENTS.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ The SDK has three categories of threads:
5656
1. Completes any pending async `std::promise` matched by `async_id`.
5757
2. Invokes all registered `FfiClient` listeners (including `Room::onEvent`).
5858

59-
All `RoomDelegate` callbacks and stream handler callbacks (e.g., `registerTextStreamHandler`) are invoked on this FFI callback thread. **Handlers must not block**; spawn a background thread if synchronous work is needed.
59+
All `RoomDelegate` callbacks and stream handler callbacks (e.g., `registerTextStreamHandler`) are invoked on this FFI callback thread. **Handlers must not block**; spawn a background thread if synchronous work is needed. Incoming data stream chunks are also delivered to `TextStreamReader` / `ByteStreamReader` on this thread (routed by `Room` from `*_stream_reader_event`s keyed by reader handle), so a stream handler must never call `readNext()` / `readAll()` inline; readers log a warning if they would block on the FFI callback thread.
6060

6161
**Per-subscription reader threads** — `SubscriptionThreadDispatcher` creates a dedicated `std::thread` for each active audio, video, or data track subscription. These threads block on `AudioStream::read()`, `VideoStream::read()`, or `DataTrackStream::read()` and invoke the registered `AudioFrameCallback`, `VideoFrameCallback`, or `DataFrameCallback` on that reader thread — not on the FFI callback thread. A hard limit of 20 concurrent reader threads is enforced.
6262

@@ -76,6 +76,8 @@ All `RoomDelegate` callbacks and stream handler callbacks (e.g., `registerTextSt
7676
| `VideoSource::captureFrame` | No | Not safe to call concurrently from multiple threads. |
7777
| `LocalAudioTrack` / `LocalVideoTrack` | No | Thin `sendRequest` wrappers with no internal synchronization. |
7878
| `LocalDataTrack::tryPush` | No | Thin `sendRequest` wrapper with no internal synchronization. |
79+
| `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()`. |
80+
| `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. |
7981
| `TextStreamWriter` / `ByteStreamWriter` | Serialized | `write()` is serialized by an internal `write_mutex_`. |
8082

8183
### Directory Layout

‎CMakeLists.txt‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -422,6 +422,8 @@ add_library(livekit SHARED
422422
src/audio_stream.cpp
423423
src/data_track_frame.cpp
424424
src/data_stream.cpp
425+
src/data_stream_proto_converter.cpp
426+
src/data_stream_proto_converter.h
425427
src/data_track_error.cpp
426428
src/data_track_schema.cpp
427429
src/data_track_stream.cpp

‎README.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,9 @@ token source helpers for endpoint, development token server, and custom backends
226226
- Dynamic token sourcing (literal, custom, endpoint, development token server, caching)
227227
- Receive remote audio/video tracks
228228
- Publish local audio/video tracks
229-
- Data tracks (low-level) and data streams (high-level)
229+
- Data tracks (low-level) and data streams (high-level): one-shot `sendText` /
230+
`sendBytes` / `sendFile` with compression, incremental writers, and
231+
per-topic stream handlers
230232
- RPC between participants
231233
- End-to-end encryption (E2EE)
232234
- Hardware-accelerated codecs (via the underlying Rust SDK)

‎include/livekit/data_stream.h‎

Lines changed: 211 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
#include <memory>
2525
#include <mutex>
2626
#include <optional>
27+
#include <stdexcept>
2728
#include <string>
2829
#include <vector>
2930

@@ -38,6 +39,100 @@ class LocalParticipant;
3839
/// channels.
3940
constexpr std::size_t kStreamChunkSize = 15'000; // 15 KB
4041

42+
/// @brief Error raised by data stream operations.
43+
///
44+
/// Thrown by the one-shot send APIs (for example
45+
/// LocalParticipant::sendText()) when the send fails or the participant is no
46+
/// longer connected, and by TextStreamReader / ByteStreamReader when an
47+
/// incoming stream ends abnormally (for example the sender closed it with a
48+
/// reason, the stream exceeded RoomOptions::data_stream limits, or the room
49+
/// disconnected mid-stream). The message carries the SDK's error description.
50+
///
51+
/// Derives from std::runtime_error, so existing
52+
/// `catch (const std::runtime_error&)` handlers keep working.
53+
class LIVEKIT_API DataStreamError : public std::runtime_error {
54+
public:
55+
/// @brief Construct an error with a description.
56+
/// @param message Human-readable error description.
57+
explicit DataStreamError(const std::string& message);
58+
};
59+
60+
/// @brief Options for a one-shot text send or an incremental text stream.
61+
///
62+
/// Used by LocalParticipant::sendText().
63+
struct StreamTextOptions {
64+
/// Application-defined topic. Required; receivers route streams to handlers
65+
/// registered with Room::registerTextStreamHandler() by topic.
66+
std::string topic;
67+
68+
/// Arbitrary key/value attributes sent with the stream header.
69+
std::map<std::string, std::string> attributes;
70+
71+
/// Identities of the participants that should receive the stream. Empty
72+
/// means every participant in the room.
73+
std::vector<std::string> destination_identities;
74+
75+
/// Stream id to use. A unique id is generated when unset.
76+
std::optional<std::string> stream_id;
77+
78+
/// Id of the stream this stream replies to, if any.
79+
std::optional<std::string> reply_to_stream_id;
80+
81+
/// Ids of other streams (for example files) attached to this text stream.
82+
std::vector<std::string> attached_stream_ids;
83+
84+
/// Compress the payload when every recipient supports compression.
85+
///
86+
/// Only one-shot sends compress; incremental writers ignore this flag.
87+
bool compress = true;
88+
89+
/// Identity to send as. Leave unset to send as the local participant;
90+
/// setting it requires the impersonation permission.
91+
std::optional<std::string> sender_identity;
92+
};
93+
94+
/// @brief Options for a one-shot byte/file send or an incremental byte stream.
95+
///
96+
/// Used by LocalParticipant::sendBytes() and LocalParticipant::sendFile().
97+
struct StreamByteOptions {
98+
/// Application-defined topic. Required; receivers route streams to handlers
99+
/// registered with Room::registerByteStreamHandler() by topic.
100+
std::string topic;
101+
102+
/// Arbitrary key/value attributes sent with the stream header.
103+
std::map<std::string, std::string> attributes;
104+
105+
/// Identities of the participants that should receive the stream. Empty
106+
/// means every participant in the room.
107+
std::vector<std::string> destination_identities;
108+
109+
/// Stream id to use. A unique id is generated when unset.
110+
std::optional<std::string> stream_id;
111+
112+
/// Name of the payload (for example a file name). When unset, sendBytes()
113+
/// uses the SDK default ("unknown") and sendFile() uses the file's basename.
114+
std::optional<std::string> name;
115+
116+
/// MIME type of the payload. When unset, the SDK picks a default
117+
/// ("application/octet-stream" for bytes; derived from the file for
118+
/// sendFile()).
119+
std::optional<std::string> mime_type;
120+
121+
/// Total payload size in bytes, if known. Only meaningful for incremental
122+
/// writers; one-shot sends always know their size.
123+
std::optional<std::uint64_t> total_length;
124+
125+
/// Compress the payload when every recipient supports compression.
126+
///
127+
/// Only one-shot sends compress; incremental writers ignore this flag. Turn
128+
/// it off for payloads that are already compressed (images, video, archives).
129+
bool compress = true;
130+
131+
/// Identity to send as. Leave unset to send as the local participant;
132+
/// setting it requires the impersonation permission.
133+
std::optional<std::string> sender_identity;
134+
};
135+
41136
/// Base metadata for any stream (text or bytes).
42137
struct BaseStreamInfo {
43138
/// Unique identifier for this stream.
@@ -77,80 +172,156 @@ struct ByteStreamInfo : BaseStreamInfo {
77172
// - TextStreamReader: yields UTF-8 text chunks (std::string)
78173
// - ByteStreamReader: yields raw bytes (std::vector<uint8_t>)
79174

80-
/// Reader for incoming text streams.
81-
/// Created internally by the SDK when a text stream header is received.
175+
/// @brief Reader for incoming text streams.
176+
///
177+
/// Created by the SDK when a remote participant opens a text stream on a topic
178+
/// with a handler registered via Room::registerTextStreamHandler(). The SDK
179+
/// decompresses and reassembles the stream; each chunk is valid UTF-8.
180+
///
181+
/// Reading blocks the calling thread. Stream handlers run on the SDK's event
182+
/// thread, which also delivers the chunks, so never read from inside the
183+
/// handler: move the reader to another thread first.
82184
class LIVEKIT_API TextStreamReader {
83185
public:
84-
/// Construct a reader from initial stream metadata.
186+
/// @brief Construct a detached reader from stream metadata.
187+
///
188+
/// A reader built this way is not connected to any incoming stream and
189+
/// never receives data. Readers for real streams are created by the SDK.
190+
/// @param info Stream metadata.
85191
explicit TextStreamReader(TextStreamInfo info);
192+
~TextStreamReader();
86193

87194
TextStreamReader(const TextStreamReader&) = delete;
88195
TextStreamReader& operator=(const TextStreamReader&) = delete;
89196

90-
/// Blocking read of next text chunk.
91-
/// Returns false when the stream has ended.
197+
/// @brief Blocking read of the next text chunk.
198+
///
199+
/// When the stream ends normally, any final attributes the sender attached
200+
/// on close are merged into info().attributes before this returns false.
201+
///
202+
/// @param out Receives the next chunk.
203+
/// @return True if a chunk was read; false when the stream has ended or
204+
/// close() was called.
205+
/// @throws DataStreamError if the stream ended abnormally (for example the
206+
/// sender closed it with a reason, it exceeded the receive size
207+
/// limit, or the room disconnected mid-stream). Chunks received
208+
/// before the error are returned first.
92209
bool readNext(std::string& out);
93210

94-
/// Convenience: read entire stream into a single string.
95-
/// Blocks until the stream is closed.
211+
/// @brief Read the entire stream into a single string.
212+
///
213+
/// Blocks until the stream ends.
214+
///
215+
/// @return The concatenated text.
216+
/// @throws DataStreamError if the stream ended abnormally.
96217
std::string readAll();
97218

98-
/// Metadata associated with this stream.
219+
/// @brief Stop reading early.
220+
///
221+
/// Discards buffered chunks and wakes any thread blocked in readNext() or
222+
/// readAll(), which then return the end of the stream. Idempotent.
223+
void close();
224+
225+
/// @brief Metadata associated with this stream.
226+
///
227+
/// Attributes the sender attached when closing the stream are merged in
228+
/// once readNext() or readAll() has reached the end of the stream, on the
229+
/// reading thread. Don't call this concurrently with readNext() from
230+
/// another thread.
231+
///
232+
/// @return Stream metadata.
99233
const TextStreamInfo& info() const noexcept { return info_; }
100234

101235
private:
102236
friend class Room;
237+
friend struct DataStreamReaderTestAccess;
238+
struct Impl;
103239

104-
/// Called by the Room when a new chunk arrives.
105-
void onChunkUpdate(const std::string& text);
240+
/// Called by the Room when a chunk arrives.
241+
void onChunkReceived(std::string text);
106242

107-
/// Called by the Room when the stream is closed.
108-
/// Additional trailer attributes are merged into info().attributes.
109-
void onStreamClose(const std::map<std::string, std::string>& trailer_attrs);
243+
/// Called by the Room when the stream ends. @p error is set when the stream
244+
/// ended abnormally.
245+
void onStreamEnded(const std::map<std::string, std::string>& attributes, std::optional<std::string> error);
110246

111247
TextStreamInfo info_;
112-
113-
// Queue of text chunks; empty string with closed_==true means EOS.
114-
std::deque<std::string> queue_;
115-
bool closed_ = false;
116-
117-
std::mutex mutex_;
118-
std::condition_variable cv_;
248+
std::unique_ptr<Impl> impl_;
119249
};
120250

121-
/// Reader for incoming byte streams.
251+
/// @brief Reader for incoming byte streams.
252+
///
253+
/// Created by the SDK when a remote participant opens a byte stream on a topic
254+
/// with a handler registered via Room::registerByteStreamHandler(). The SDK
255+
/// decompresses and reassembles the stream.
256+
///
257+
/// Reading blocks the calling thread. Stream handlers run on the SDK's event
258+
/// thread, which also delivers the chunks, so never read from inside the
259+
/// handler: move the reader to another thread first.
122260
class LIVEKIT_API ByteStreamReader {
123261
public:
124-
/// Construct a reader from initial stream metadata.
262+
/// @brief Construct a detached reader from stream metadata.
263+
///
264+
/// A reader built this way is not connected to any incoming stream and
265+
/// never receives data. Readers for real streams are created by the SDK.
266+
/// @param info Stream metadata.
125267
explicit ByteStreamReader(ByteStreamInfo info);
268+
~ByteStreamReader();
126269

127270
ByteStreamReader(const ByteStreamReader&) = delete;
128271
ByteStreamReader& operator=(const ByteStreamReader&) = delete;
129272

130-
/// Blocking read of next byte chunk.
131-
/// Returns false when the stream has ended.
273+
/// @brief Blocking read of the next byte chunk.
274+
///
275+
/// When the stream ends normally, any final attributes the sender attached
276+
/// on close are merged into info().attributes before this returns false.
277+
///
278+
/// @param out Receives the next chunk.
279+
/// @return True if a chunk was read; false when the stream has ended or
280+
/// close() was called.
281+
/// @throws DataStreamError if the stream ended abnormally (for example the
282+
/// sender closed it with a reason, it exceeded the receive size
283+
/// limit, or the room disconnected mid-stream). Chunks received
284+
/// before the error are returned first.
132285
bool readNext(std::vector<std::uint8_t>& out);
133286

134-
/// Metadata associated with this stream.
287+
/// @brief Read the entire stream into a single buffer.
288+
///
289+
/// Blocks until the stream ends.
290+
///
291+
/// @return The concatenated bytes.
292+
/// @throws DataStreamError if the stream ended abnormally.
293+
std::vector<std::uint8_t> readAll();
294+
295+
/// @brief Stop reading early.
296+
///
297+
/// Discards buffered chunks and wakes any thread blocked in readNext() or
298+
/// readAll(), which then return the end of the stream. Idempotent.
299+
void close();
300+
301+
/// @brief Metadata associated with this stream.
302+
///
303+
/// Attributes the sender attached when closing the stream are merged in
304+
/// once readNext() or readAll() has reached the end of the stream, on the
305+
/// reading thread. Don't call this concurrently with readNext() from
306+
/// another thread.
307+
///
308+
/// @return Stream metadata.
135309
const ByteStreamInfo& info() const noexcept { return info_; }
136310

137311
private:
138312
friend class Room;
313+
friend struct DataStreamReaderTestAccess;
314+
struct Impl;
139315

140-
/// Called by the Room when a new chunk arrives.
141-
void onChunkUpdate(const std::vector<std::uint8_t>& bytes);
316+
/// Called by the Room when a chunk arrives.
317+
void onChunkReceived(std::vector<std::uint8_t> bytes);
142318

143-
/// Called by the Room when the stream is closed.
144-
/// Additional trailer attributes are merged into info().attributes.
145-
void onStreamClose(const std::map<std::string, std::string>& trailer_attrs);
319+
/// Called by the Room when the stream ends. @p error is set when the stream
320+
/// ended abnormally.
321+
void onStreamEnded(const std::map<std::string, std::string>& attributes, std::optional<std::string> error);
146322

147323
ByteStreamInfo info_;
148-
149-
std::deque<std::vector<std::uint8_t>> queue_;
150-
bool closed_ = false;
151-
152-
std::mutex mutex_;
153-
std::condition_variable cv_;
324+
std::unique_ptr<Impl> impl_;
154325
};
155326

156327
/// Base class for sending data streams.
@@ -267,15 +438,17 @@ class LIVEKIT_API ByteStreamWriter : public BaseStreamWriter {
267438
///
268439
/// The TextStreamReader is provided as a shared_ptr to ensure it remains
269440
/// alive for the duration of asynchronous reads (for example, when the
270-
/// user spawns a background thread to consume the stream).
441+
/// user spawns a background thread to consume the stream). The handler runs on
442+
/// the SDK event thread and must not read from the stream itself.
271443
using TextStreamHandler =
272444
std::function<void(std::shared_ptr<TextStreamReader>, const std::string& participant_identity)>;
273445

274446
/// Callback invoked when a new incoming byte stream is opened.
275447
///
276448
/// The ByteStreamReader is provided as a shared_ptr to ensure it remains
277449
/// alive for the duration of asynchronous reads (for example, file writes
278-
/// or background processing).
450+
/// or background processing). The handler runs on the SDK event thread and
451+
/// must not read from the stream itself.
279452
using ByteStreamHandler =
280453
std::function<void(std::shared_ptr<ByteStreamReader>, const std::string& participant_identity)>;
281454

0 commit comments

Comments
 (0)