Skip to content

Commit 623ba8c

Browse files
1egomanclaude
andcommitted
Port data stream writers to FFI writer handles; add streamText/streamBytes
TextStreamWriter / ByteStreamWriter now open an FFI writer (text/byte_stream_open) and send through text/byte_stream_write and *_stream_close instead of hand-built header/chunk/trailer packets. Rust does the chunking and UTF-8 splitting. - LocalParticipant::streamText / streamBytes return an already-open writer (blocking until the open callback, throwing DataStreamError on failure). The public writer constructors keep working but are deprecated; they open lazily on the first write or close, as the header did before. - write() and close() share one mutex and each waits for its FFI callback, so a close never overtakes an in-flight write (python-sdks#879); this also fixes close() not taking the write lock. - A LocalParticipant tracks its writers in a registry shared with them. On disconnect (or participant destruction) every writer is closed and its handle dropped, so later write/close throw DataStreamError instead of reaching an FFI session that would panic. - A writer destroyed without close() sends a non-waiting FFI close. Rust's writer only sends its drop-time trailer from a Tokio thread, so a plain handle drop from C++ left receivers waiting forever. - kStreamChunkSize and the protected ensureHeaderSent / sendChunk / sendTrailer helpers are deprecated and reimplemented on the new path. - Removed FfiClient::sendStream*Async, splitUtf8 and the now-unused header/chunk/trailer converters. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent beb795d commit 623ba8c

14 files changed

Lines changed: 1107 additions & 416 deletions

‎AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ All `RoomDelegate` callbacks and stream handler callbacks (e.g., `registerTextSt
7878
| `LocalDataTrack::tryPush` | No | Thin `sendRequest` wrapper with no internal synchronization. |
7979
| `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()`. |
8080
| `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. |
81-
| `TextStreamWriter` / `ByteStreamWriter` | Serialized | `write()` is serialized by an internal `write_mutex_`. |
81+
| `TextStreamWriter` / `ByteStreamWriter` | Serialized | `write()` and `close()` are serialized by an internal mutex and each waits for its FFI callback, so `close()` never overtakes a write. `LocalParticipant` closes its writers on disconnect (via a shared registry, so writers may outlive the participant); later calls throw `DataStreamError`. Create writers with `LocalParticipant::streamText` / `streamBytes`; the constructors are deprecated. |
8282

8383
### Directory Layout
8484
Be sure to update the directory layout in this file if the directory layout changes.

‎CMakeLists.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -424,6 +424,7 @@ add_library(livekit SHARED
424424
src/data_stream.cpp
425425
src/data_stream_proto_converter.cpp
426426
src/data_stream_proto_converter.h
427+
src/data_stream_writer_registry.h
427428
src/data_track_error.cpp
428429
src/data_track_schema.cpp
429430
src/data_track_stream.cpp

‎include/livekit/data_stream.h‎

Lines changed: 167 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
#pragma once
1818

19+
#include <atomic>
1920
#include <condition_variable>
2021
#include <cstdint>
2122
#include <deque>
@@ -34,9 +35,15 @@ namespace livekit {
3435

3536
class LocalParticipant;
3637

38+
namespace detail {
39+
class StreamWriterRegistry;
40+
} // namespace detail
41+
3742
/// Chunk size for data streams (matches Python STREAM_CHUNK_SIZE).
38-
/// Chosen to balance throughput and latency, and to work well with WebRTC data
39-
/// channels.
43+
///
44+
/// @deprecated The SDK core now chunks data streams itself (at 15 KB); this
45+
/// constant no longer controls anything.
46+
[[deprecated("kStreamChunkSize no longer controls chunking; the SDK core chunks data streams itself")]]
4047
constexpr std::size_t kStreamChunkSize = 15'000; // 15 KB
4148

4249
/// @brief Error raised by data stream operations.
@@ -324,29 +331,58 @@ class LIVEKIT_API ByteStreamReader {
324331
std::unique_ptr<Impl> impl_;
325332
};
326333

327-
/// Base class for sending data streams.
328-
/// Concrete subclasses are TextStreamWriter and ByteStreamWriter.
334+
/// @brief Base class for sending data streams incrementally.
335+
///
336+
/// Concrete subclasses are TextStreamWriter and ByteStreamWriter; create them
337+
/// with LocalParticipant::streamText() / LocalParticipant::streamBytes().
338+
///
339+
/// Thread safety: write() and close() are serialized internally, and each one
340+
/// returns only after the SDK has processed it, so a close() always follows
341+
/// every write() that returned before it. When the room disconnects, the
342+
/// writer is closed and later write() / close() calls throw DataStreamError.
343+
///
344+
/// Destroying a writer that was opened but not closed closes the stream
345+
/// normally (without waiting), so receivers don't wait forever.
329346
class LIVEKIT_API BaseStreamWriter {
330347
public:
331-
virtual ~BaseStreamWriter() = default;
348+
virtual ~BaseStreamWriter();
349+
350+
BaseStreamWriter(const BaseStreamWriter&) = delete;
351+
BaseStreamWriter& operator=(const BaseStreamWriter&) = delete;
332352

333-
/// Stream id assigned to this writer.
353+
/// @brief Stream id assigned to this writer.
354+
/// @return The stream id.
334355
const std::string& streamId() const noexcept { return stream_id_; }
335356

336-
/// Topic of this stream.
357+
/// @brief Topic of this stream.
358+
/// @return The topic.
337359
const std::string& topic() const noexcept { return topic_; }
338360

339-
/// MIME type for this stream.
361+
/// @brief MIME type for this stream.
362+
/// @return The MIME type.
340363
const std::string& mimeType() const noexcept { return mime_type_; }
341364

342-
/// Timestamp (ms) when the stream was created.
365+
/// @brief Timestamp (ms) when the stream was created.
366+
///
367+
/// Updated to the SDK core's timestamp once the stream is opened.
368+
/// @return Creation timestamp in milliseconds since the Unix epoch.
343369
std::int64_t timestampMs() const noexcept { return timestamp_ms_; }
344370

345-
/// Whether the stream has been closed.
371+
/// @brief Whether the stream has been closed (explicitly or because the room
372+
/// disconnected).
373+
/// @return True if closed.
346374
bool isClosed() const noexcept { return closed_; }
347375

348-
/// Close the stream with optional reason and attributes.
349-
/// Throws on FFI error or if already closed.
376+
/// @brief Close the stream.
377+
///
378+
/// Waits for any in-progress write() to finish first. A non-empty @p reason
379+
/// closes the stream abnormally: receivers' reads throw DataStreamError
380+
/// carrying the reason.
381+
///
382+
/// @param reason Empty for a normal close; otherwise the error reason.
383+
/// @param attributes Attributes merged into the receiver's stream info.
384+
/// @throws DataStreamError if the stream is already closed, the room has
385+
/// disconnected, or the SDK reports an error.
350386
void close(const std::string& reason = "", const std::map<std::string, std::string>& attributes = {});
351387

352388
protected:
@@ -369,69 +405,169 @@ class LIVEKIT_API BaseStreamWriter {
369405
std::vector<std::string> destination_identities_;
370406
std::string sender_identity_;
371407

372-
bool closed_ = false;
408+
std::atomic<bool> closed_{false};
409+
/// True once the stream has been opened with the SDK core.
373410
bool header_sent_ = false;
411+
/// Unused; chunking is done by the SDK core.
374412
std::uint64_t next_chunk_index_ = 0;
375413
StreamKind kind_ = StreamKind::kUnknown;
376414
std::string reply_to_id_;
377415
std::string byte_name_; // Used by ByteStreamWriter
378416

379-
/// Ensure the header has been sent once.
380-
/// Throws on error.
417+
/// @brief Open the stream if it isn't open yet.
418+
/// @deprecated The SDK opens the stream on the first write() or close().
419+
/// @throws DataStreamError on error.
420+
[[deprecated("BaseStreamWriter::ensureHeaderSent is deprecated; the stream opens on the first write or close")]]
381421
void ensureHeaderSent();
382422

383-
/// Send a raw chunk of bytes.
384-
/// Throws on error or if stream is closed.
423+
/// @brief Write raw bytes to the stream (UTF-8 text for a text stream).
424+
/// @deprecated Use TextStreamWriter::write() or ByteStreamWriter::write() instead.
425+
/// @param content Payload to write.
426+
/// @throws std::runtime_error if the stream is closed; DataStreamError on error.
427+
[[deprecated(
428+
"BaseStreamWriter::sendChunk is deprecated; use TextStreamWriter::write or ByteStreamWriter::write "
429+
"instead")]]
385430
void sendChunk(const std::vector<std::uint8_t>& content);
386431

387-
/// Send the trailer with given reason and attributes.
388-
/// Throws on error.
432+
/// @brief Close the stream with the given reason and attributes.
433+
/// @deprecated Use close() instead.
434+
/// @param reason Empty for a normal close; otherwise the error reason.
435+
/// @param attributes Attributes merged into the receiver's stream info.
436+
/// @throws DataStreamError on error.
437+
[[deprecated("BaseStreamWriter::sendTrailer is deprecated; use BaseStreamWriter::close instead")]]
389438
void sendTrailer(const std::string& reason, const std::map<std::string, std::string>& attributes);
439+
440+
/// @brief Open the stream now (requires @c kind_ to be set). Serialized with
441+
/// write() and close().
442+
/// @throws DataStreamError on error.
443+
void open();
444+
445+
/// @brief Write a payload (text for kText, bytes for kByte), opening first if
446+
/// needed. Serialized with other operations.
447+
/// @param data Payload bytes.
448+
/// @param size Payload size.
449+
/// @param closed_message Message thrown if the writer is already closed.
450+
/// @throws DataStreamError on error.
451+
void writePayload(const char* data, std::size_t size, const char* closed_message);
452+
453+
private:
454+
friend class detail::StreamWriterRegistry;
455+
456+
void openLocked();
457+
void closeLocked(const std::string& reason, const std::map<std::string, std::string>& attributes);
458+
void applyOpenedInfo(std::int64_t timestamp_ms, const std::string& mime_type);
459+
std::uint64_t takeHandle() noexcept;
460+
void onParticipantDisconnected() noexcept;
461+
[[noreturn]] void throwNotConnected() const;
462+
463+
/// Serializes open/write/close. Held across FFI waits.
464+
std::mutex op_mutex_;
465+
/// Guards writer_handle_ and participant_gone_. Never held across FFI calls.
466+
mutable std::mutex state_mutex_;
467+
/// Owned FFI writer handle; 0 before open and after close consumes it.
468+
std::uint64_t writer_handle_ = 0;
469+
bool participant_gone_ = false;
470+
std::shared_ptr<detail::StreamWriterRegistry> registry_;
390471
};
391472

392-
/// Writer for outgoing text streams.
473+
/// @brief Writer for outgoing text streams.
474+
///
475+
/// Create one with LocalParticipant::streamText(). Text is sent as UTF-8; the
476+
/// SDK splits it into chunks on code point boundaries.
393477
class LIVEKIT_API TextStreamWriter : public BaseStreamWriter {
394478
public:
479+
/// @brief Construct a text stream writer.
480+
///
481+
/// The stream is opened lazily on the first write() or close().
482+
///
483+
/// @deprecated Use LocalParticipant::streamText() instead.
484+
/// @param local_participant Participant that sends the stream; must outlive the writer.
485+
/// @param topic Topic receivers register handlers on.
486+
/// @param attributes Attributes sent with the stream header.
487+
/// @param stream_id Stream id; generated when empty.
488+
/// @param total_size Recorded locally in info() only; text streams can't transmit a size.
489+
/// @param reply_to_id Id of the stream this one replies to, or empty.
490+
/// @param destination_identities Recipients; empty for everyone.
491+
/// @param sender_identity Identity to send as; defaults to the local participant.
492+
[[deprecated("Constructing TextStreamWriter directly is deprecated; use LocalParticipant::streamText instead")]]
395493
TextStreamWriter(LocalParticipant& local_participant, const std::string& topic = "",
396494
const std::map<std::string, std::string>& attributes = {}, const std::string& stream_id = "",
397495
std::optional<std::size_t> total_size = std::nullopt, const std::string& reply_to_id = "",
398496
const std::vector<std::string>& destination_identities = {},
399497
const std::string& sender_identity = "");
400498

401-
/// Write a UTF-8 string to the stream.
402-
/// Data will be split into chunks of at most kStreamChunkSize bytes.
403-
/// Throws on error or if the stream is closed.
499+
/// @brief Write a UTF-8 string to the stream.
500+
///
501+
/// Blocks until the SDK has sent it.
502+
///
503+
/// @param text UTF-8 text to append.
504+
/// @throws DataStreamError if the stream is closed, the room has
505+
/// disconnected, or the SDK reports an error.
404506
void write(const std::string& text);
405507

406-
/// Metadata associated with this stream.
508+
/// @brief Metadata associated with this stream.
509+
/// @return Stream metadata; updated with the SDK core's info once opened.
407510
const TextStreamInfo& info() const noexcept { return info_; }
408511

409512
private:
513+
friend class BaseStreamWriter;
514+
friend class LocalParticipant;
515+
struct FactoryTag {};
516+
517+
TextStreamWriter(FactoryTag, LocalParticipant& local_participant, const StreamTextOptions& options);
518+
410519
TextStreamInfo info_;
411-
std::mutex write_mutex_;
520+
std::vector<std::string> attached_stream_ids_;
412521
};
413522

414-
/// Writer for outgoing byte streams.
523+
/// @brief Writer for outgoing byte streams.
524+
///
525+
/// Create one with LocalParticipant::streamBytes().
415526
class LIVEKIT_API ByteStreamWriter : public BaseStreamWriter {
416527
public:
528+
/// @brief Construct a byte stream writer.
529+
///
530+
/// The stream is opened lazily on the first write() or close().
531+
///
532+
/// @deprecated Use LocalParticipant::streamBytes() instead.
533+
/// @param local_participant Participant that sends the stream; must outlive the writer.
534+
/// @param name Name of the payload (for example a file name).
535+
/// @param topic Topic receivers register handlers on.
536+
/// @param attributes Attributes sent with the stream header.
537+
/// @param stream_id Stream id; generated when empty.
538+
/// @param total_size Total payload size, if known.
539+
/// @param mime_type MIME type of the payload.
540+
/// @param destination_identities Recipients; empty for everyone.
541+
/// @param sender_identity Identity to send as; defaults to the local participant.
542+
[[deprecated("Constructing ByteStreamWriter directly is deprecated; use LocalParticipant::streamBytes instead")]]
417543
ByteStreamWriter(LocalParticipant& local_participant, const std::string& name, const std::string& topic = "",
418544
const std::map<std::string, std::string>& attributes = {}, const std::string& stream_id = "",
419545
std::optional<std::size_t> total_size = std::nullopt,
420546
const std::string& mime_type = "application/octet-stream",
421547
const std::vector<std::string>& destination_identities = {},
422548
const std::string& sender_identity = "");
423549

424-
/// Write binary data to the stream.
425-
/// Data will be chunked into kStreamChunkSize-sized chunks.
426-
/// Throws on error or if the stream is closed.
550+
/// @brief Write binary data to the stream.
551+
///
552+
/// Blocks until the SDK has sent it.
553+
///
554+
/// @param data Bytes to append.
555+
/// @throws DataStreamError if the stream is closed, the room has
556+
/// disconnected, or the SDK reports an error.
427557
void write(const std::vector<std::uint8_t>& data);
428558

429-
/// Metadata associated with this stream.
559+
/// @brief Metadata associated with this stream.
560+
/// @return Stream metadata; updated with the SDK core's info once opened.
430561
const ByteStreamInfo& info() const noexcept { return info_; }
431562

432563
private:
564+
friend class BaseStreamWriter;
565+
friend class LocalParticipant;
566+
struct FactoryTag {};
567+
568+
ByteStreamWriter(FactoryTag, LocalParticipant& local_participant, const StreamByteOptions& options);
569+
433570
ByteStreamInfo info_;
434-
std::mutex write_mutex_;
435571
};
436572

437573
/// Callback invoked when a new incoming text stream is opened.

‎include/livekit/local_participant.h‎

Lines changed: 48 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,9 @@ struct ParticipantTrackPermission;
4747

4848
class FfiClient;
4949
class Track;
50+
namespace detail {
51+
class StreamWriterRegistry;
52+
} // namespace detail
5053
class LocalTrackPublication;
5154

5255
/// @brief Data passed to a registered RPC method handler.
@@ -76,6 +79,12 @@ class LIVEKIT_API LocalParticipant : public Participant {
7679
LocalParticipant(FfiHandle handle, std::string sid, std::string name, std::string identity, std::string metadata,
7780
std::unordered_map<std::string, std::string> attributes, ParticipantKind kind,
7881
DisconnectReason reason);
82+
~LocalParticipant() override;
83+
84+
LocalParticipant(const LocalParticipant&) = delete;
85+
LocalParticipant& operator=(const LocalParticipant&) = delete;
86+
LocalParticipant(LocalParticipant&&) = delete;
87+
LocalParticipant& operator=(LocalParticipant&&) = delete;
7988

8089
/// Track publications for this participant, keyed by publication SID.
8190
///
@@ -137,6 +146,36 @@ class LIVEKIT_API LocalParticipant : public Participant {
137146
/// if the room is no longer connected or the SDK isn't initialized.
138147
ByteStreamInfo sendFile(const std::string& path, const StreamByteOptions& options);
139148

149+
/// @brief Open a text stream for incremental writes.
150+
///
151+
/// Blocks until the stream is open. Write with TextStreamWriter::write() and
152+
/// finish with TextStreamWriter::close(). Incremental streams are never
153+
/// compressed; @c options.compress is ignored. Use sendText() when the whole
154+
/// text is available up front.
155+
///
156+
/// @param options Topic (required), destinations, attributes, and so on.
157+
/// @return An open writer. It must not outlive this participant's room
158+
/// connection in a meaningful way: once the room disconnects, its
159+
/// write() and close() throw DataStreamError.
160+
/// @throws DataStreamError if the open fails, or if the room is no longer
161+
/// connected or the SDK isn't initialized.
162+
std::unique_ptr<TextStreamWriter> streamText(const StreamTextOptions& options);
163+
164+
/// @brief Open a byte stream for incremental writes.
165+
///
166+
/// Blocks until the stream is open. Write with ByteStreamWriter::write() and
167+
/// finish with ByteStreamWriter::close(). Incremental streams are never
168+
/// compressed; @c options.compress is ignored. Use sendBytes() or sendFile()
169+
/// when the whole payload is available up front.
170+
///
171+
/// @param options Topic (required), name, MIME type, total length,
172+
/// destinations, and so on.
173+
/// @return An open writer. Once the room disconnects, its write() and
174+
/// close() throw DataStreamError.
175+
/// @throws DataStreamError if the open fails, or if the room is no longer
176+
/// connected or the SDK isn't initialized.
177+
std::unique_ptr<ByteStreamWriter> streamBytes(const StreamByteOptions& options);
178+
140179
/// Publish a SIP DTMF (phone keypad) tone into the room.
141180
///
142181
/// Only meaningful when a SIP trunk is bridging a phone call into the
@@ -346,9 +385,12 @@ class LIVEKIT_API LocalParticipant : public Participant {
346385
/// prune expired @c weak_ptr entries.
347386
mutable TrackMap published_tracks_by_sid_;
348387

388+
friend class BaseStreamWriter;
389+
349390
/// Marks the participant as disconnected so data stream sends fail fast in
350-
/// C++ instead of reaching an FFI participant whose session is gone.
351-
void markDisconnected() noexcept { disconnected_.store(true, std::memory_order_release); }
391+
/// C++ instead of reaching an FFI participant whose session is gone, and
392+
/// closes every open stream writer.
393+
void markDisconnected() noexcept;
352394

353395
/// Returns the FFI handle id for a data stream operation, or throws
354396
/// DataStreamError if the participant can no longer send.
@@ -360,6 +402,10 @@ class LIVEKIT_API LocalParticipant : public Participant {
360402
/// Room::lock_ so send paths never need the room lock.
361403
std::atomic<bool> disconnected_{false};
362404

405+
/// Stream writers created for this participant; shared with the writers so
406+
/// they never touch a destroyed participant.
407+
std::shared_ptr<detail::StreamWriterRegistry> stream_writers_;
408+
363409
// Shared state for RPC invocation tracking. Using shared_ptr so the state
364410
// can outlive the LocalParticipant if there are in-flight invocations when
365411
// the participant is destroyed.

0 commit comments

Comments
 (0)