Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ The SDK has three categories of threads:
1. Completes any pending async `std::promise` matched by `async_id`.
2. Invokes all registered `FfiClient` listeners (including `Room::onEvent`).

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.
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.

**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.

Expand All @@ -76,6 +76,7 @@ All `RoomDelegate` callbacks and stream handler callbacks (e.g., `registerTextSt
| `VideoSource::captureFrame` | No | Not safe to call concurrently from multiple threads. |
| `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()`. |
| `TextStreamWriter` / `ByteStreamWriter` | Serialized | `write()` is serialized by an internal `write_mutex_`. |

### Directory Layout
Expand Down
2 changes: 2 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,8 @@ add_library(livekit SHARED
src/audio_stream.cpp
src/data_track_frame.cpp
src/data_stream.cpp
src/data_stream_proto_converter.cpp
src/data_stream_proto_converter.h
src/data_track_error.cpp
src/data_track_schema.cpp
src/data_track_stream.cpp
Expand Down
171 changes: 133 additions & 38 deletions include/livekit/data_stream.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
#include <memory>
#include <mutex>
#include <optional>
#include <stdexcept>
#include <string>
#include <vector>

Expand All @@ -38,6 +39,22 @@ class LocalParticipant;
/// channels.
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.
///
/// Derives from std::runtime_error, so existing
/// `catch (const std::runtime_error&)` handlers keep working.
class LIVEKIT_API DataStreamError : public std::runtime_error {
public:
/// @brief Construct an error with a description.
/// @param message Human-readable error description.
explicit DataStreamError(const std::string& message);
};

/// Base metadata for any stream (text or bytes).
struct BaseStreamInfo {
/// Unique identifier for this stream.
Expand Down Expand Up @@ -77,80 +94,156 @@ struct ByteStreamInfo : BaseStreamInfo {
// - TextStreamReader: yields UTF-8 text chunks (std::string)
// - ByteStreamReader: yields raw bytes (std::vector<uint8_t>)

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

TextStreamReader(const TextStreamReader&) = delete;
TextStreamReader& operator=(const TextStreamReader&) = delete;

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

/// Convenience: read entire stream into a single string.
/// Blocks until the stream is closed.
/// @brief Read the entire stream into a single string.
///
/// Blocks until the stream ends.
///
/// @return The concatenated text.
/// @throws DataStreamError if the stream ended abnormally.
std::string readAll();

/// Metadata associated with this stream.
/// @brief Stop reading early.
///
/// Discards buffered chunks and wakes any thread blocked in readNext() or
/// readAll(), which then return the end of the stream. Idempotent.
void close();

/// @brief Metadata associated with this stream.
///
/// Attributes the sender attached when closing the stream are merged in
/// once readNext() or readAll() has reached the end of the stream, on the
/// reading thread. Don't call this concurrently with readNext() from
/// another thread.
///
/// @return Stream metadata.
const TextStreamInfo& info() const noexcept { return info_; }

private:
friend class Room;
friend struct DataStreamReaderTestAccess;
struct Impl;

/// Called by the Room when a new chunk arrives.
void onChunkUpdate(const std::string& text);
/// Called by the Room when a chunk arrives.
void onChunkReceived(std::string text);

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

TextStreamInfo info_;

// Queue of text chunks; empty string with closed_==true means EOS.
std::deque<std::string> queue_;
bool closed_ = false;

std::mutex mutex_;
std::condition_variable cv_;
std::unique_ptr<Impl> impl_;
};

/// Reader for incoming byte streams.
/// @brief Reader for incoming byte streams.
///
/// Created by the SDK when a remote participant opens a byte stream on a topic
/// with a handler registered via Room::registerByteStreamHandler(). The SDK
/// decompresses and reassembles the stream.
///
/// Reading blocks the calling thread. Stream handlers run on the SDK's event
/// thread, which also delivers the chunks, so never read from inside the
/// handler: move the reader to another thread first.
class LIVEKIT_API ByteStreamReader {
public:
/// Construct a reader from initial stream metadata.
/// @brief Construct a detached reader from stream metadata.
///
/// A reader built this way is not connected to any incoming stream and
/// never receives data. Readers for real streams are created by the SDK.
/// @param info Stream metadata.
explicit ByteStreamReader(ByteStreamInfo info);
~ByteStreamReader();

ByteStreamReader(const ByteStreamReader&) = delete;
ByteStreamReader& operator=(const ByteStreamReader&) = delete;

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

/// Metadata associated with this stream.
/// @brief Read the entire stream into a single buffer.
///
/// Blocks until the stream ends.
///
/// @return The concatenated bytes.
/// @throws DataStreamError if the stream ended abnormally.
std::vector<std::uint8_t> readAll();

/// @brief Stop reading early.
///
/// Discards buffered chunks and wakes any thread blocked in readNext() or
/// readAll(), which then return the end of the stream. Idempotent.
void close();

/// @brief Metadata associated with this stream.
///
/// Attributes the sender attached when closing the stream are merged in
/// once readNext() or readAll() has reached the end of the stream, on the
/// reading thread. Don't call this concurrently with readNext() from
/// another thread.
///
/// @return Stream metadata.
const ByteStreamInfo& info() const noexcept { return info_; }

private:
friend class Room;
friend struct DataStreamReaderTestAccess;
struct Impl;

/// Called by the Room when a new chunk arrives.
void onChunkUpdate(const std::vector<std::uint8_t>& bytes);
/// Called by the Room when a chunk arrives.
void onChunkReceived(std::vector<std::uint8_t> bytes);

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

ByteStreamInfo info_;

std::deque<std::vector<std::uint8_t>> queue_;
bool closed_ = false;

std::mutex mutex_;
std::condition_variable cv_;
std::unique_ptr<Impl> impl_;
};

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

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

Expand Down
30 changes: 24 additions & 6 deletions include/livekit/room.h
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ class RoomDelegate;
struct RoomInfoData;
namespace proto {
class FfiEvent;
}
class TextStreamOpened;
class ByteStreamOpened;
} // namespace proto

struct E2EEOptions;
class E2EEManager;
Expand Down Expand Up @@ -267,9 +269,11 @@ class LIVEKIT_API Room {
/// - Only one handler may be registered per topic.
/// - If no handler is registered for a topic, incoming streams with that
/// topic are ignored.
/// - The handler is invoked on the Room event thread. The handler must
/// not block; spawn a background thread if synchronous reading is
/// required.
/// - The handler is invoked on the SDK event thread, which also delivers
/// the stream's chunks. The handler must not block: never call
/// TextStreamReader::readNext() or readAll() inside it. Hand the reader
/// to a background thread instead.
/// - Reading throws DataStreamError if the stream ends abnormally.
///
/// @throws std::runtime_error if a handler is already registered for the topic.
void registerTextStreamHandler(const std::string& topic, TextStreamHandler handler);
Expand All @@ -292,6 +296,11 @@ class LIVEKIT_API Room {
/// topic are ignored.
/// - The ByteStreamReader remains valid as long as the shared_ptr is held,
/// preventing lifetime-related crashes when reading asynchronously.
/// - The handler is invoked on the SDK event thread, which also delivers
/// the stream's chunks. The handler must not block: never call
/// ByteStreamReader::readNext() or readAll() inside it. Hand the reader
/// to a background thread instead.
/// - Reading throws DataStreamError if the stream ends abnormally.
///
/// @throws std::runtime_error if a handler is already registered for the topic.
void registerByteStreamHandler(const std::string& topic, ByteStreamHandler handler);
Expand Down Expand Up @@ -357,8 +366,12 @@ class LIVEKIT_API Room {
// Data stream
std::unordered_map<std::string, TextStreamHandler> text_stream_handlers_;
std::unordered_map<std::string, ByteStreamHandler> byte_stream_handlers_;
std::unordered_map<std::string, std::shared_ptr<TextStreamReader>> text_stream_readers_;
std::unordered_map<std::string, std::shared_ptr<ByteStreamReader>> byte_stream_readers_;
// Active incoming stream readers, keyed by FFI reader handle id. A reader is
// removed when its end-of-stream event arrives or the room shuts down.
using TextStreamReaderMap = std::unordered_map<std::uint64_t, std::shared_ptr<TextStreamReader>>;
using ByteStreamReaderMap = std::unordered_map<std::uint64_t, std::shared_ptr<ByteStreamReader>>;
TextStreamReaderMap text_stream_readers_;
ByteStreamReaderMap byte_stream_readers_;
// The E2EE manager is owned by the room and is not shared with other objects.
// It is a shared_ptr just to utilize the weak_ptr interface for the e2eeManager() accessor.
std::shared_ptr<E2EEManager> e2ee_manager_;
Expand All @@ -368,6 +381,11 @@ class LIVEKIT_API Room {
int listener_id_{0};

void onEvent(const proto::FfiEvent& event);
void onTextStreamOpened(const proto::TextStreamOpened& opened, RoomDelegate* delegate);
void onByteStreamOpened(const proto::ByteStreamOpened& opened, RoomDelegate* delegate);
bool dispatchStreamReaderEvent(const proto::FfiEvent& event);
// Gives every reader a terminal "disconnected" error so blocked reads wake.
static void endStreamReaders(const TextStreamReaderMap& text_readers, const ByteStreamReaderMap& byte_readers);

// Shared shutdown path for explicit disconnect, server disconnect, EOS, and destruction.
bool shutdown(bool disconnect_ffi, DisconnectReason reason, bool notify_delegate);
Expand Down
12 changes: 10 additions & 2 deletions include/livekit/room_event_types.h
Original file line number Diff line number Diff line change
Expand Up @@ -664,7 +664,11 @@ struct DataChannelBufferedAmountLowThresholdChangedEvent {

/// Fired when a high-level byte stream reader is opened.
struct ByteStreamOpenedEvent {
/// Handle to the underlying byte stream reader.
/// Always 0.
///
/// @deprecated The reader handle is owned and consumed by the
/// ByteStreamReader the SDK passes to the handler registered with
/// Room::registerByteStreamHandler(); use that reader instead.
std::uint64_t reader_handle = 0;

/// Identity of the participant that opened the stream.
Expand All @@ -673,7 +677,11 @@ struct ByteStreamOpenedEvent {

/// Fired when a high-level text stream reader is opened.
struct TextStreamOpenedEvent {
/// Handle to the underlying text stream reader.
/// Always 0.
///
/// @deprecated The reader handle is owned and consumed by the
/// TextStreamReader the SDK passes to the handler registered with
/// Room::registerTextStreamHandler(); use that reader instead.
std::uint64_t reader_handle = 0;

/// Identity of the participant that opened the stream.
Expand Down
Loading
Loading