acceptable-planet-23174
10/29/2025, 11:15 AMtall-airline-16756
10/29/2025, 11:15 AMtall-airline-16756
10/29/2025, 11:16 AMregisterTextStreamHandler in LiveKit. The system is thoughtfully designed to handle large volumes of text by automatically chunking and streaming the data for you.
In fact, the sendText method, which works hand-in-hand with registerTextStreamHandler, has been tested with payloads as large as 100,000 characters. This really shows its capability to support large data transfers smoothly. Plus, the text streaming mechanism offers the flexibility to send all data at once or stream it incrementally, depending on what works best for your needs.
That said, it’s good to keep in mind that performance can vary based on network conditions and how the client handles the data. If you have any concerns or need help optimizing this, I’m here to assist you every step of the way!
Sources: Sending text | LiveKit docs | lib/src/core/room.dart | README.mdacceptable-planet-23174
10/30/2025, 5:25 AMtall-airline-16756
10/30/2025, 5:26 AMsendText or streamText to send your message?
• On the receiver's side, are you using readAll() or going through each chunk to read the stream?
Knowing these details will really help me guide you more effectively. Looking forward to your response!
Sources: Web Applications & Integration Examples | livekit/livekit_composite | DeepW... | livekit-rtc/livekit/rtc/data_stream.py | Sending text | LiveKit docs | test/core/data_stream_test.dart | README.mdacceptable-planet-23174
10/30/2025, 5:26 AMtall-airline-16756
10/30/2025, 5:27 AMreadAll is being used. To help us get to the bottom of this together, could you please share a bit more information?
• How large is the data you’re sending?
• Are you seeing any error messages or warnings during the process?
• Are there any particular network conditions, like high latency, that might be impacting the stream?
Having these details will really help us understand what might be causing the truncation and find the best solution for you.
Sources: Runtime/Scripts/Proto/DataStream.cs | livekit-android-test/src/test/java/io/livekit/android/room/datastream/RoomI... | test/core/data_stream_test.dartacceptable-planet-23174
10/30/2025, 5:27 AMroom.registerTextStreamHandler("ui-command") { streamedValue, second ->
repositoryScope.launch {
val uiCommandData = streamedValue.readAll()
Log.d(TAG, "UI-command-> $uiCommandData")
processUICommandMessage(uiCommandData)
}
}tall-airline-16756
10/30/2025, 5:27 AMStreamException) or any silent data loss?
Your answers will really help us understand whether this is a known issue or if we need to dig a little deeper. We're here to support you every step of the way!
Sources: livekit-android-sdk/src/main/java/io/livekit/android/room/datastream/outgoi... | packages/livekit-rtc/src/room.ts | Text and transcriptions | LiveKit Docsacceptable-planet-23174
10/30/2025, 5:28 AMtall-airline-16756
10/30/2025, 5:28 AMacceptable-planet-23174
10/30/2025, 5:28 AMtall-airline-16756
10/30/2025, 5:29 AMacceptable-planet-23174
10/30/2025, 5:30 AMtall-airline-16756
10/30/2025, 5:30 AMacceptable-planet-23174
10/30/2025, 5:30 AMtall-airline-16756
10/30/2025, 5:31 AMreadAll() and waiting until the stream is fully closed before processing the data.
• Make sure the stream isn’t closing too early because of timeouts or errors.
• Double-check that the sender isn’t sending oversized chunks manually, bypassing LiveKit’s automatic chunking.
If you try these steps and still face issues, please don’t hesitate to reach out. I’m more than happy to help you dig deeper and find a solution together.
Sources: streams.go | livekit/src/room/data_stream/outgoing.rs | Data packets | LiveKit docs | src/room/rpc.ts | Sending text | LiveKit docsacceptable-planet-23174
10/30/2025, 5:32 AMreadAll() and waiting until the stream is fully closed before processing the data.
How to do it?tall-airline-16756
10/30/2025, 5:32 AMreadAll() in the LiveKit Kotlin Android SDK! To make sure it reads all chunks and waits for the stream to close, you can trust its built-in behavior. The readAll() method is designed to automatically suspend execution and wait for the stream to close before returning all the data it has gathered.
Here’s a friendly reminder on how to use it effectively:
• Make sure you call readAll() inside a coroutine, since it’s a suspending function.
• The method will pause until the sender closes the stream, so you’ll receive and process all chunks without missing anything.
For example:
room.registerTextStreamHandler("ui-command") { streamedValue, _ ->
repositoryScope.launch {
val uiCommandData = streamedValue.readAll()
Log.d(TAG, "UI-command-> $uiCommandData")
processUICommandMessage(uiCommandData)
}
}
This way, you can be confident that readAll() gathers all chunks before moving on to handle the data. If you have any more questions or want to explore this further, I’m here to help!
Sources: livekit-android-test/src/test/java/io/livekit/android/room/datastream/RoomI...acceptable-planet-23174
10/30/2025, 5:33 AMtall-airline-16756
10/30/2025, 5:34 AMreadAll() can be, and I’m here to help you work through it. This issue is often caused by the stream closing quietly or exceptions being suppressed, rather than a problem with how coroutines are used. Here are some friendly steps you can try:
• Try not to rely only on readAll() for important data: Instead, using flow.collect with clear error handling can help you catch stream issues like unexpected termination or incomplete data.
• Make sure the sender closes streams properly: It’s important that the sender signals the end of the stream by emitting a trailer and doesn’t disconnect too soon.
• Keep an eye on logs: Turning on debug logging can reveal network problems or protocol hiccups that might be causing trouble.
Here’s an example where you can swap out readAll() with something like this:
launch {
reader.flow
.catch { cause ->
Log.e("Stream", "Error: ${cause.message}", cause)
}
.collect { chunk ->
collectedData.add(chunk)
}
}
This way, you’ll get clearer insight into any stream errors and make sure every chunk is handled properly.
Please feel free to let me know if you’re able to adjust the sender-side logic, or if the stream’s origin is beyond your control. I’m happy to guide you through the next steps!
Sources: livekit-android-sdk/src/main/java/io/livekit/android/room/Room.kt | Sending files & bytes | LiveKit docsacceptable-planet-23174
10/30/2025, 5:34 AMtall-airline-16756
10/30/2025, 5:35 AMreader object in the LiveKit Kotlin Android SDK! This object is actually an instance of TextStreamReader, which helps you receive and process incoming text streams smoothly. When you register a text stream handler using registerTextStreamHandler, this reader gets passed to your handler function.
To give you a quick overview, some key methods of TextStreamReader are:
• `readAll()`: This reads the entire stream and waits until it’s closed before returning all the text. It’s great when you want the full message at once.
• `ReadIncremental()`: This one lets you process the text bit by bit as it arrives, which is super handy for live streaming situations.
Here’s a simple example using readAll() to help you see it in action:
room.registerTextStreamHandler("ui-command") { reader, participantIdentity ->
lifecycleScope.launch {
val text = reader.readAll()
Log.d("LiveKit", "Received: $text from $participantIdentity")
}
}
If you’d like, I’m here to help with more examples or to clarify anything specific to your project. Just let me know!
Sources: Runtime/Scripts/DataStream.cs | packages/livekit-rtc/src/proto/room_pb.ts | livekit-ffi/protocol/data_stream.proto | README.mdacceptable-planet-23174
10/30/2025, 5:36 AMtall-airline-16756
10/30/2025, 5:37 AMreadAll is acting differently on Android, could you please clarify a few things for me?
• Are you using ByteStreamReceiver or TextStreamReceiver?
• Can you confirm that the data is being sent correctly from the sender's side?
• Have you noticed any error callbacks or logs that might suggest the stream isn’t fully delivered?
• Are you able to reproduce this issue with the sample app?
Getting these details will really help us understand what’s going on and find a solution together.
Sources: LiveKit SDKs Overview | LiveKit Docs | livekit-android-sdk/src/main/java/io/livekit/android/room/datastream/outgoi... | Sending files & bytes | LiveKit docs | README.md | packages/livekit-rtc/src/proto/data_stream_pb.tsacceptable-planet-23174
10/30/2025, 5:51 AMtall-airline-16756
10/30/2025, 5:52 AMTextStreamReceiver. To help us get to the bottom of the truncation issue together, could you please share a few details?
• A minimal code example that shows the issue?
• The size and content of the text you’re sending (for example, does it include any special Unicode characters)?
• Are you using sendText for a single send, or streamText for incremental streaming?
• And if possible, the logging output that shows the stream lifecycle (like the header, chunks, and trailer)?
With this info, we’ll be in a great position to pinpoint what’s going on and guide you through the best solution. Looking forward to your reply!
Sources: Text and transcriptions | LiveKit Docs | livekit-android-sdk/src/main/java/io/livekit/android/room/datastream/outgoi... | Sending text | LiveKit docsacceptable-planet-23174
10/30/2025, 5:53 AM//
// TranscriptionStreamReciever.swift
// AiSdk
//
// Created by pranjal.agarwal on 21/08/25.
//
import Foundation
import LiveKitClient
/// An actor that converts raw text streams from the LiveKit `Room` into `Message` objects.
/// - Note: Streams are supported by `livekit-agents` >= 1.0.0.
/// - SeeAlso: ``TranscriptionDelegateReceiver``
///
/// For agent messages, new text stream is emitted for each message, and the stream is closed when the message is finalized.
/// Each agent message is delivered in chunks, that are accumulated and published into the message stream.
///
/// For user messages, the full transcription is sent each time, but may be updated until finalized.
///
/// The ID of the segment is stable and unique across the lifetime of the message.
/// This ID can be used directly for `Identifiable` conformance.
///
/// Example text stream for agent messages:
///
/// { segment_id: "1", content: "Hello" }
/// { segment_id: "1", content: " world" }
/// { segment_id: "1", content: "!" }
/// { segment_id: "2", content: "Hello" }
/// { segment_id: "2", content: " Apple" }
/// { segment_id: "2", content: "!" }
/// ///
/// Example text stream for user messages:
///
/// { segment_id: "3", content: "Hello" }
/// { segment_id: "3", content: "Hello world!" }
/// { segment_id: "4", content: "Hello" }
/// { segment_id: "4", content: "Hello Apple!" }
/// ///
/// Example output:
///
/// Message(id: "1", timestamp: 2025-01-01 120000 +0000, content: .agentTranscript("Hello world!"))
/// Message(id: "2", timestamp: 2025-01-01 120010 +0000, content: .agentTranscript("Hello Apple!"))
/// Message(id: "3", timestamp: 2025-01-01 120020 +0000, content: .userTranscript("Hello world!"))
/// Message(id: "4", timestamp: 2025-01-01 120030 +0000, content: .userTranscript("Hello Apple!"))
/// ///
actor TranscriptionStreamReceiver: MessageReceiver {
private struct PartialMessageID: Hashable {
let segmentID: String
let participantID: Participant.Identity
}
private struct PartialMessage {
var content: String
let timestamp: Date
var streamID: String
mutating func appendContent(_ newContent: String) {
content += newContent
}
mutating func replaceContent(_ newContent: String, streamID: String) {
content = newContent
self.streamID = streamID
}
}
private let transcriptionTopic = "ui-command"
private enum TranscriptionAttributes: String {
case final = "lk.transcription_final"
case segment = "lk.segment_id"
}
private let room: Room
private lazy var partialMessages: [PartialMessageID: PartialMessage] = [:]
init(room: Room) {
self.room = room
}
/// Creates a new message stream for the chat topic.
func messages() async throws -> AsyncStream<ReceivedMessage> {
let (stream, continuation) = AsyncStream.makeStream(of: ReceivedMessage.self)
try await room.registerTextStreamHandler(for: transcriptionTopic) { [weak self] reader, participantIdentity in
guard let self else { return }
for try await message in reader where !message.isEmpty {
await continuation.yield(processIncoming(partialMessage: message, reader: reader, participantIdentity: participantIdentity))
}
}
continuation.onTermination = { [weak self] val in
Task {
guard let self else { return }
// print("AISDK :- Unregistering text stream handler \(val) \(continuation)")
await self.room.unregisterTextStreamHandler(for: self.transcriptionTopic)
}
}
return stream
}
/// Aggregates the incoming text into a message, storing the partial content in the `partialMessages` dictionary.
/// - Note: When the message is finalized, or a new message is started, the dictionary is purged to limit memory usage.
private func processIncoming(partialMessage message: String, reader: TextStreamReader, participantIdentity: Participant.Identity) -> ReceivedMessage {
let segmentID = reader.info.attributes[TranscriptionAttributes.segment.rawValue] ?? reader.info.id
let participantID = participantIdentity
let partialID = PartialMessageID(segmentID: segmentID, participantID: participantID)
let currentStreamID = reader.info.id
let timestamp: Date
let updatedContent: String
if var existingMessage = partialMessages[partialID] {
// Update existing message
if existingMessage.streamID == currentStreamID {
// Same stream, append content
existingMessage.appendContent(message)
} else {
// Different stream for same segment, replace content
existingMessage.replaceContent(message, streamID: currentStreamID)
}
updatedContent = existingMessage.content
timestamp = existingMessage.timestamp
partialMessages[partialID] = existingMessage
} else {
// This is a new message
updatedContent = message
timestamp = reader.info.timestamp
partialMessages[partialID] = PartialMessage(
content: updatedContent,
timestamp: timestamp,
streamID: currentStreamID
)
cleanupPreviousTurn(participantIdentity, exceptSegmentID: segmentID)
}
let isFinal = reader.info.attributes[TranscriptionAttributes.final.rawValue] == "true"
if isFinal {
partialMessages[partialID] = nil
}
let newOrUpdatedMessage = ReceivedMessage(
id: segmentID,
timestamp: timestamp,
content: participantIdentity == room.localParticipant.identity ? .userTranscript(updatedContent) : .agentTranscript(updatedContent)
)
return newOrUpdatedMessage
}
private func cleanupPreviousTurn(_ participantID: Participant.Identity, exceptSegmentID: String) {
let keysToRemove = partialMessages.keys.filter {
$0.participantID == participantID && $0.segmentID != exceptSegmentID
}
for key in keysToRemove {
partialMessages[key] = nil
}
}
}tall-airline-16756
10/30/2025, 5:53 AMsendText or streamText)?
• Are there any differences in the payload or stream lifecycle between the two platforms that you’ve noticed?
Getting these details will really help us get to the bottom of this and find the best solution for you.
Sources: livekit-android-sdk/src/main/java/io/livekit/android/room/datastream/outgoi... | Sending text | LiveKit docs | Sources/LiveKit/Support/TextView.swift | Text and transcriptions | LiveKit Docsacceptable-planet-23174
10/30/2025, 5:54 AMtall-airline-16756
10/30/2025, 5:54 AMsendText in the Kotlin Android LiveKit SDK can be, especially since it works smoothly on iOS. This difference often comes down to how each platform handles stream closure and buffer management.
On Android, sendText relies on a TextStreamSender that breaks the text into UTF-8 byte arrays and carefully manages the stream closure by waiting for the WebRTC data channel buffer to clear. However, if the buffer status monitoring on Android behaves a bit differently than on iOS, it might cause the stream to close too soon, leading to truncation.
Here are some friendly suggestions to help you troubleshoot or fix this issue:
• Double-check that both your Android and iOS apps are using the same LiveKit server version and protocol definitions to keep things consistent.
• Try explicitly setting the totalSize in StreamTextOptions on Android to make sure the metadata is accurate.
• Keep an eye on the data channel buffer behavior on Android and consider adding a small delay between write and close if it seems necessary.
• Conduct end-to-end testing to capture the exact packet sequences and confirm that all chunks and the trailer are sent properly.
If you'd like, I’m here to help you walk through these steps or assist with debugging. Just let me know!
Sources: Sending text | LiveKit docs | Text and transcriptions | LiveKit Docs | Realtime data | LiveKit Docs | README.md | Mobile SDKs (Flutter, iOS, Android) | livekit/livekit_composite | DeepWikiacceptable-planet-23174
10/30/2025, 5:55 AMtall-airline-16756
10/30/2025, 5:56 AMTextStreamReceiver in the Kotlin Android LiveKit SDK. You can make use of the flow property of the receiver, which gives you a Flow<String> that emits each chunk of text as it comes in.
Here’s a simple example to help you get started:
room.registerTextStreamHandler(topic = "lk.chat") { receiver: TextStreamReceiver, identity: Participant.Identity ->
viewModelScope.launch {
receiver.flow.collect { textChunk: String ->
// Handle each chunk as it arrives
Log.d("LiveKit", "$identity: $textChunk")
}
}
}
This method lets you handle streaming text bit by bit, which is perfect for live chat or streamed responses, so you don’t have to wait for the entire stream to finish before processing.
If you have any questions or want to dive deeper into this, please don’t hesitate to ask—I’m here to help!
Sources: sample-app-common/src/main/java/io/livekit/android/sample/CallViewModel.kt | Sending text | LiveKit docs | Sending files & bytes | LiveKit docsacceptable-planet-23174
10/30/2025, 6:11 AMacceptable-planet-23174
10/30/2025, 6:11 AMtall-airline-16756
10/30/2025, 6:11 AMacceptable-planet-23174
10/30/2025, 6:54 AMtall-airline-16756
10/30/2025, 6:55 AMreadAll() method from the TextStreamReceiver. This handy method gathers all the incoming chunks and joins them into one complete string once the stream finishes.
Here’s a simple example to guide you:
room.registerTextStreamHandler(
topic = "lk.chat",
handler = { receiver: TextStreamReceiver, identity: Participant.Identity ->
viewModelScope.launch {
val message = receiver.readAll().joinToString(separator = "")
Log.d("LiveKit", "$identity: $message")
}
},
)
This way, you can be sure all the chunks come together as one full message before you process it further. If you have any questions or need more help with this, just let me know—I’m here for you!
Sources: sample-app-common/src/main/java/io/livekit/android/sample/CallViewModel.ktacceptable-planet-23174
10/30/2025, 6:56 AMtall-airline-16756
10/30/2025, 6:57 AMonStreamCompleted(), you can still tell when all the data has been received by using a few handy approaches:
• Using `readAll()`: This method finishes once all the data is received. Here’s a quick example:
room.registerTextStreamHandler("topic") { reader, _ ->
viewModelScope.launch {
val allText = reader.readAll()
Log.d("Stream", "Received complete text: ${allText.joinToString("")}")
}
}
• Using flow collection: The flow will naturally complete when the stream ends, like this:
room.registerTextStreamHandler("topic") { reader, _ ->
viewModelScope.launch {
reader.flow.collect { text ->
// Handle incoming text chunk
}
Log.d("Stream", "All data received and stream completed")
}
}
• Using `readNext()`: When a NoSuchElementException is thrown, it means the stream has ended:
room.registerTextStreamHandler("topic") { reader, _ ->
viewModelScope.launch {
try {
while (true) {
val text = reader.readNext()
// Handle text chunk
}
} catch (exception: NoSuchElementException) {
Log.d("Stream", "Stream completed")
}
}
}
If you’d like, I’m here to help walk you through any of these methods or clear up any questions you might have. Just let me know!
Sources: packages/livekit-rtc/src/room.ts | livekit-android-sdk/src/main/java/io/livekit/android/room/datastream/outgoi...acceptable-planet-23174
10/30/2025, 7:04 AMtall-airline-16756
10/30/2025, 7:05 AMNoSuchElementException happens when readNext() is called after the stream has already ended. If you’re encountering this exception multiple times, it might be because:
• There are multiple concurrent text streams opened on the same topic, which creates several reader instances.
• readNext() is being called repeatedly after the stream has been fully read.
To help you resolve this smoothly:
• Try using the flow property of TextStreamReceiver and collect from it. The flow will naturally complete when the stream ends, making things easier to manage:
room.registerTextStreamHandler("topic") { reader, _ ->
viewModelScope.launch {
reader.flow.collect { text ->
// Handle incoming text chunk
}
Log.d("Stream", "All data received and stream completed")
}
}
• Or, you could use readAll() to process all chunks as one complete message:
room.registerTextStreamHandler("topic") { reader, _ ->
viewModelScope.launch {
val allText = reader.readAll()
Log.d("Stream", "Received complete text: ${allText.joinToString("")}")
}
}
These methods help you handle the stream’s completion gracefully without running into those pesky exceptions. If you have any questions or want to explore this further, I’m here to help!
Sources: livekit-android-sdk/src/main/java/io/livekit/android/room/datastream/outgoi... | Sending text | LiveKit docsacceptable-planet-23174
10/30/2025, 7:06 AMpackage io.livekit.android.room.datastream.incoming
import android.os.SystemClock
import androidx.annotation.VisibleForTesting
import io.livekit.android.room.datastream.ByteStreamInfo
import io.livekit.android.room.datastream.StreamException
import io.livekit.android.room.datastream.StreamInfo
import io.livekit.android.room.datastream.TextStreamInfo
import io.livekit.android.room.participant.Participant
import io.livekit.android.util.LKLog
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.channels.Channel
import livekit.LivekitModels
import livekit.LivekitModels.DataStream
import java.util.Collections
import javax.inject.Inject
// Type-erased stream handler
private typealias AnyStreamHandler = (Channel<ByteArray>, Participant.Identity) -> Unit
typealias ByteStreamHandler = (reader: ByteStreamReceiver, fromIdentity: Participant.Identity) -> Unit
typealias TextStreamHandler = (reader: TextStreamReceiver, fromIdentity: Participant.Identity) -> Unit
interface IncomingDataStreamManager {
/**
* Registers a text stream handler for [topic]. Only one handler can be set for a particular topic at a time.
*
* @throws IllegalArgumentException if a topic is already set.
*/
fun registerTextStreamHandler(topic: String, handler: TextStreamHandler)
/**
* Unregisters a previously registered text handler for [topic].
*/
fun unregisterTextStreamHandler(topic: String)
/**
* Registers a byte stream handler for [topic]. Only one handler can be set for a particular topic at a time.
*
* @throws IllegalArgumentException if a topic is already set.
*/
fun registerByteStreamHandler(topic: String, handler: ByteStreamHandler)
/**
* Unregisters a previously registered byte handler for [topic].
*/
fun unregisterByteStreamHandler(topic: String)
/**
* @suppress
*/
fun handleStreamHeader(header: DataStream.Header, fromIdentity: Participant.Identity, encryptionType: LivekitModels.Encryption.Type)
/**
* @suppress
*/
fun handleDataChunk(chunk: DataStream.Chunk, encryptionType: LivekitModels.Encryption.Type)
/**
* @suppress
*/
fun handleStreamTrailer(trailer: DataStream.Trailer, encryptionType: LivekitModels.Encryption.Type)
/**
* @suppress
*/
fun clearOpenStreams()
}
/**
* @suppress
*/
class IncomingDataStreamManagerImpl @Inject constructor() : IncomingDataStreamManager {
/**
* A stream descriptor for any open incoming streams.
*/
private data class Descriptor(
val streamInfo: StreamInfo,
/**
* Measured by SystemClock.elapsedRealtime()
*/
val openTime: Long,
/**
* The channel to pipe any incoming data into.
*
* Calling [Channel.close] will automatically call [closeStream] and remove the stream.
*/
val channel: Channel<ByteArray>,
var readLength: Long = 0,
)
private val openStreams = Collections.synchronizedMap(mutableMapOf<String, Descriptor>())
private val textStreamHandlers = Collections.synchronizedMap(mutableMapOf<String, TextStreamHandler>())
private val byteStreamHandlers = Collections.synchronizedMap(mutableMapOf<String, ByteStreamHandler>())
/**
* Registers a text stream handler for [topic]. Only one handler can be set for a particular topic at a time.
*
* @throws IllegalArgumentException if a topic is already set.
*/
override fun registerTextStreamHandler(topic: String, handler: TextStreamHandler) {
synchronized(textStreamHandlers) {
if (textStreamHandlers.containsKey(topic)) {
throw IllegalArgumentException("A text stream handler for topic $topic has already been set.")
}
textStreamHandlers[topic] = handler
}
}
/**
* Unregisters a previously registered text handler for [topic].
*/
override fun unregisterTextStreamHandler(topic: String) {
synchronized(textStreamHandlers) {
textStreamHandlers.remove(topic)
}
}
/**
* Registers a byte stream handler for [topic]. Only one handler can be set for a particular topic at a time.
*
* @throws IllegalArgumentException if a topic is already set.
*/
override fun registerByteStreamHandler(topic: String, handler: ByteStreamHandler) {
synchronized(byteStreamHandlers) {
if (byteStreamHandlers.containsKey(topic)) {
throw IllegalArgumentException("A byte stream handler for topic $topic has already been set.")
}
byteStreamHandlers[topic] = handler
}
}
/**
* Unregisters a previously registered byte handler for [topic].
*/
override fun unregisterByteStreamHandler(topic: String) {
synchronized(byteStreamHandlers) {
byteStreamHandlers.remove(topic)
}
}
/**
* @suppress
*/
override fun handleStreamHeader(header: DataStream.Header, fromIdentity: Participant.Identity, encryptionType: LivekitModels.Encryption.Type) {
val info = streamInfoFromHeader(header, encryptionType) ?: return
openStream(info, fromIdentity)
}
@OptIn(ExperimentalCoroutinesApi::class)
private fun openStream(info: StreamInfo, fromIdentity: Participant.Identity) {
if (openStreams.containsKey(info.id)) {
LKLog.w { "Stream already open for id ${info.id}" }
return
}
val handler = getHandlerForInfo(info)
val channel = createChannelForStreamReceiver()
val descriptor = Descriptor(
streamInfo = info,
openTime = SystemClock.elapsedRealtime(),
channel = channel,
)
openStreams[info.id] = descriptor
channel.invokeOnClose { closeStream(id = info.id) }
LKLog.d { "Opened stream ${info.id}" }
try {
handler.invoke(channel, fromIdentity)
} catch (e: Exception) {
LKLog.e(e) { "Unhandled exception when invoking stream handler!" }
}
}
/**
* @suppress
*/
override fun handleDataChunk(chunk: DataStream.Chunk, encryptionType: LivekitModels.Encryption.Type) {
val content = chunk.content ?: return
val descriptor = openStreams[chunk.streamId] ?: return
if (encryptionType != descriptor.streamInfo.encryptionType) {
descriptor.channel.close(
StreamException.EncryptionTypeMismatch(
"Encryption type mismatch for stream ${chunk.streamId}. Expected ${descriptor.streamInfo.encryptionType}, got $encryptionType",
),
)
}
val totalReadLength = descriptor.readLength + content.size()
val totalLength = descriptor.streamInfo.totalSize
if (totalLength != null) {
if (totalReadLength > totalLength) {
descriptor.channel.close(StreamException.LengthExceededException())
return
}
}
descriptor.readLength = totalReadLength
descriptor.channel.trySend(content.toByteArray())
}
/**
* @suppress
*/
override fun handleStreamTrailer(trailer: DataStream.Trailer, encryptionType: LivekitModels.Encryption.Type) {
val descriptor = openStreams[trailer.streamId]
if (descriptor == null) {
LKLog.w { "Received trailer for unknown stream: ${trailer.streamId}" }
return
}
if (encryptionType != descriptor.streamInfo.encryptionType) {
descriptor.channel.close(
StreamException.EncryptionTypeMismatch(
"Encryption type mismatch for stream ${trailer.streamId}. Expected ${descriptor.streamInfo.encryptionType}, got $encryptionType",
),
)
}
val totalLength = descriptor.streamInfo.totalSize
if (totalLength != null) {
if (descriptor.readLength != totalLength) {
descriptor.channel.close(StreamException.IncompleteException())
return
}
}
val reason = trailer.reason
if (!reason.isNullOrEmpty()) {
// A non-empty reason string indicates an error
val exception = StreamException.AbnormalEndException(reason)
descriptor.channel.close(exception)
return
}
// Close successfully.
descriptor.channel.close()
}
private fun closeStream(id: String) {
synchronized(openStreams) {
val descriptor = openStreams[id]
if (descriptor == null) {
LKLog.d { "Attempted to close stream $id, but no descriptor was found." }
return
}
descriptor.channel.close()
val openMillis = SystemClock.elapsedRealtime() - descriptor.openTime
LKLog.d { "Closed stream $id, (open for ${openMillis}ms" }
openStreams.remove(id)
}
}
/**
* @suppress
*/
override fun clearOpenStreams() {
synchronized(openStreams) {
// Create a copy since closing the channel will also remove from openStreams,
// causing a ConcurrentModificationException
val descriptors = openStreams.values.toList()
for (descriptor in descriptors) {
descriptor.channel.close(StreamException.TerminatedException())
}
openStreams.clear()
}
}
private fun getHandlerForInfo(info: StreamInfo): AnyStreamHandler {
return when (info) {
is ByteStreamInfo -> {
val handler = byteStreamHandlers[info.topic]
{ channel, identity ->
if (handler == null) {
LKLog.w { "Received byte stream for topic \"${info.topic}\", but no handler was found. Ignoring." }
} else {
handler.invoke(ByteStreamReceiver(info, channel), identity)
}
}
}
is TextStreamInfo -> {
val handler = textStreamHandlers[info.topic]
{ channel, identity ->
if (handler == null) {
LKLog.w { "Received text stream for topic \"${info.topic}\", but no handler was found. Ignoring." }
} else {
handler.invoke(TextStreamReceiver(info, channel), identity)
}
}
}
}
}
private fun streamInfoFromHeader(header: DataStream.Header, encryptionType: LivekitModels.Encryption.Type): StreamInfo? {
try {
return when (header.contentHeaderCase) {
DataStream.Header.ContentHeaderCase.TEXT_HEADER -> {
TextStreamInfo(header, header.textHeader, encryptionType)
}
DataStream.Header.ContentHeaderCase.BYTE_HEADER -> {
ByteStreamInfo(header, header.byteHeader, encryptionType)
}
DataStream.Header.ContentHeaderCase.CONTENTHEADER_NOT_SET,
null,
-> {
LKLog.i { "received header with non-set content header. streamId: ${header.streamId}, topic: ${header.topic}" }
null
}
}
} catch (e: Exception) {
LKLog.e(e) { "Exception when processing new stream header." }
return null
}
}
companion object {
@VisibleForTesting
fun createChannelForStreamReceiver() = Channel<ByteArray>(
capacity = Int.MAX_VALUE,
onBufferOverflow = BufferOverflow.SUSPEND,
)
}
}
Is there any way u can help from it?tall-airline-16756
10/30/2025, 7:06 AM