Is there any limit on data which backend can send ...
# ask-ai
a
Is there any limit on data which backend can send on registerTextStreamHandler
t
Thanks for reaching out, Himanshu. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm happy to share that there’s no explicit limit on the amount of data the backend can send using
registerTextStreamHandler
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.md
a
Processing agent message (size: 14.57 KB) message is this much, it is still getting truncated , why it is happening?
t
I'd love to help you get to the bottom of the truncation issue! Could you please share a bit more about your setup? • Which SDK are you working with (like Flutter, Unity, or JavaScript)? • Are you using
sendText
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.md
a
readAll yes readAll
t
Thank you so much for confirming that
readAll
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.dart
a
Copy code
room.registerTextStreamHandler("ui-command") { streamedValue, second ->
  repositoryScope.launch {
    val uiCommandData = streamedValue.readAll()
    Log.d(TAG, "UI-command-> $uiCommandData")
    processUICommandMessage(uiCommandData)
  }
}
t
Thank you so much for sharing the code snippet! To help us get to the bottom of the truncation issue together, could you please clarify a few things? • Are you using LiveKit Agents with synchronized transcription? • Is the stream getting interrupted or canceled before it finishes? • Have you noticed any exceptions (like a
StreamException
) 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 Docs
a
Error processing ACTUAL agent message (size: 14.57 KB): Unexpected EOF at path: $.widget.data[0].description (Ask Gemini) JSON input: .....016, India</span></div></div></div><div class=\"restaurant-c kotlinx.serialization.json.internal.JsonDecodingException: Unexpected EOF at path: $.widget.data[0].description JSON input: .....016, India</span></div></div></div><div class=\"restaurant-c
t
It looks like you're encountering the error "Unexpected EOF at path," which usually points to some incomplete JSON data. Let's work through this together! Could you please share a bit more detail? • Is this error popping up on the client side or the server side? • Which LiveKit SDK are you using—JavaScript, Kotlin, Python, or something else? • If possible, could you share the exact code snippet or the context where this error shows up? With this info, I’ll be better equipped to help you pinpoint the issue and find the best solution. Looking forward to your reply! Sources: Tests/LiveKitCoreTests/DataStream/IncomingStreamManagerTests.swift | Web Applications & Integration Examples | livekit/livekit_composite | DeepW... | Text and transcriptions | LiveKit Docs
a
kotlin android livekit
t
I'm sorry to hear you're encountering the "Unexpected EOF at path" error. This usually happens when the JSON data is incomplete or not formatted quite right. To help you better, could you please share a bit more? • Is this error popping up when you're deserializing a specific message, or does it happen in response to a server event? • Are you using a custom JSON parser, or are you sticking with the default one from the LiveKit SDK? • Also, which version of the LiveKit Android SDK are you currently using? With these details, I’ll be able to guide you more effectively and get this sorted out together. Sources: livekit-android-test/src/test/java/io/livekit/android/room/datastream/RoomI... | Text and transcriptions | LiveKit Docs | Tests/LiveKitCoreTests/DataStream/IncomingStreamManagerTests.swift
a
Json shared from backend is correct, but I am using readAll, in this process it is getting truncated.
t
Thank you so much for confirming that the JSON from the backend looks correct. To help us get to the bottom of the truncation issue, could you please share a bit more detail? • Approximately how large is the JSON payload you're sending? • Are you sending the JSON through data packets or as text streams? • Have you noticed if the truncation happens on the sender side or the receiver side? Knowing this will really help us pinpoint the cause and guide you more effectively. We're here to support you every step of the way! Sources: livekit-android-sdk/src/main/java/io/livekit/android/token/EndpointTokenSou... | packages/livekit-rtc/src/proto/data_stream_pb.ts
a
38kb json payload. Text stream. Truncation on receiver side.
t
I understand how frustrating it can be when your 38KB JSON payload gets truncated, and I’m here to help you through this. The truncation usually happens because of how the receiver processes the text stream. Just so you know, LiveKit automatically breaks down large payloads into smaller chunks of up to 15,000 bytes (~15KB) to make transmission smoother. So, for your 38KB payload, it would be split into at least three chunks (~15KB, ~15KB, and ~8KB). To make sure you receive the entire payload, here are a few things you can check: • Confirm that the receiver is reading all the chunks by using
readAll()
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 docs
a
• Confirm that the receiver is reading all the chunks by using
readAll()
and waiting until the stream is fully closed before processing the data. How to do it?
t
I’m glad you’re exploring how to use
readAll()
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:
Copy code
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...
a
I am doing this only. Why it is trucnating then?
t
I understand how frustrating truncation during
readAll()
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:
Copy code
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 docs
a
what is this reader?
t
I'm glad you're exploring the
reader
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:
Copy code
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.md
a
But it is working fine in IOS.
t
Thanks so much for sharing that this works on iOS! To help us get to the bottom of why
readAll
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.ts
a
I am using textStream Receiver
t
Thank you so much for confirming that you’re using
TextStreamReceiver
. 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 docs
a
On receiver end I am facing this issue. on IOS they aredoing this and its working fine.
Copy code
//
//  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: "!" } ///
Copy code
///
/// 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!" } ///
Copy code
///
/// 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!")) ///
Copy code
///
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
        }
    }
}
t
Thanks so much for sharing the iOS implementation! To help us understand why truncation is happening on Android but not on iOS, could you please share a bit more with us? • Do you have any specific examples or logs showing the truncation issue on Android? • Could you tell us how the sender is transmitting the text (for example, using
sendText
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 Docs
a
sendText Sender is sending using this. No difference in payload.
t
I understand how frustrating the truncation issue with
sendText
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 | DeepWiki
a
• Conduct end-to-end testing to capture the exact packet sequences and confirm that all chunks and the trailer are sent properly. How to receive data on receiver end in chunks?
t
I'm glad you're exploring how to receive data in chunks on the receiver end using
TextStreamReceiver
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:
Copy code
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 docs
a
Check the logs.tsv
Check the logs I have attached.
t
Hi there! It looks like your last message didn’t come through. Whenever you’re ready, feel free to share more details or let me know if the solution worked for you. I’m here to help!
a
Backend is sending data of 38 kb from their end but livekit breaks into 15, 8,8,8 kb and then we receive it in chunks how to handle all the data in one go now?
t
I’m happy to help you handle all chunks of data as a single message in the LiveKit Kotlin Android SDK! You can use the
readAll()
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:
Copy code
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.kt
a
Is there a callback, that now all the data has been received? in that viewmodelscope only
t
Thanks for reaching out! While the LiveKit Kotlin Android SDK doesn’t have a specific callback like
onStreamCompleted()
, 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:
Copy code
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:
Copy code
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:
Copy code
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...
a
I am getting catch (exception: NoSuchElementException) { Log.d("Stream", "Stream completed") } 4 times.
t
The
NoSuchElementException
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:
Copy code
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:
Copy code
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 docs
a
Copy code
package 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?
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!