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
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
114 changes: 110 additions & 4 deletions include/livekit/data_stream.h
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -55,6 +57,103 @@ 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().
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<std::string, std::string> attributes;

/// Identities of the participants that should receive the stream. Empty
/// means every participant in the room.
std::vector<std::string> destination_identities;

/// Stream id to use. A unique id is generated when unset.
std::optional<std::string> stream_id;

/// Id of the stream this stream replies to, if any.
std::optional<std::string> reply_to_stream_id;

/// Ids of other streams (for example files) attached to this text stream.
std::vector<std::string> 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<std::int32_t> 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.
bool compress = true;

/// Identity to send as. Leave unset to send as the local participant;
/// setting it requires the impersonation permission.
std::optional<std::string> 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<std::string, std::string> attributes;

/// Identities of the participants that should receive the stream. Empty
/// means every participant in the room.
std::vector<std::string> destination_identities;

/// Stream id to use. A unique id is generated when unset.
std::optional<std::string> 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<std::string> 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<std::string> mime_type;

/// Total payload size in bytes, if known. Only meaningful for incremental
/// writers; one-shot sends always know their size.
std::optional<std::uint64_t> 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<std::string> sender_identity;
};

/// Base metadata for any stream (text or bytes).
struct BaseStreamInfo {
/// Unique identifier for this stream.
Expand Down Expand Up @@ -82,6 +181,13 @@ struct TextStreamInfo : BaseStreamInfo {
std::vector<std::string> attachments;
/// If this stream is a reply to another stream, this field holds its ID
std::optional<std::string> 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<std::int32_t> version;
/// Whether the text was generated, for example by an agent transcribing a
/// participant's speech.
bool generated = false;
};

/// Metadata for a byte stream.
Expand Down
57 changes: 57 additions & 0 deletions include/livekit/local_participant.h
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
#include <unordered_map>
#include <vector>

#include "livekit/data_stream.h"
#include "livekit/data_track_error.h"
#include "livekit/data_track_options.h"
#include "livekit/data_track_schema.h"
Expand Down Expand Up @@ -93,6 +94,50 @@ class LIVEKIT_API LocalParticipant : public Participant {
void publishData(const std::vector<std::uint8_t>& payload, bool reliable = true,
const std::vector<std::string>& 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<std::uint8_t>& 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
Expand Down Expand Up @@ -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<std::string, RpcHandler> 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<bool> 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.
Expand Down
96 changes: 96 additions & 0 deletions src/data_stream_proto_converter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,97 @@

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);
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);
}
// 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);
}
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();
Expand All @@ -36,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;
}

Expand Down
20 changes: 20 additions & 0 deletions src/data_stream_proto_converter.h
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,26 @@

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.
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.
Expand Down
Loading
Loading