how can i setup simple load testing in python from...
# ask-ai
n
how can i setup simple load testing in python from stretch https://github.com/livekit/livekit-cli/
t
Thanks for reaching out, Darshak. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking how to set up simple load testing in Python using the LiveKit CLI (the repo you linked). Below is a concise, practical path you can follow plus a small Python example to call the CLI. Acknowledging: I’ll cover installing the CLI, a basic
lk load-test
command to simulate publishers/subscribers, environment notes, and how to invoke it from Python. 1) Install the LiveKit CLI • macOS (Homebrew): brew install livekit-cli • Linux: curl -sSL https://get.livekit.io/cli | bash • Windows: winget install LiveKit.LiveKitCLI (Or download a prebuilt binary from the CLI releases.) 2) Run a basic load test from the shell Example — simulate 10 audio publishers and 1000 subscribers in room "load-test": lk load-test \ --url wss://your-livekit-server.com \ --api-key <your-api-key> \ --api-secret <your-api-secret> \ --room load-test \ --audio-publishers 10 \ --subscribers 1000 Example — simulate a 150-person video meeting: lk load-test \ --url wss://your-livekit-server.com \ --api-key <your-api-key> \ --api-secret <your-api-secret> \ --room load-test \ --video-publishers 150 \ --subscribers 150 Replace the URL, API key, and secret with your values. 3) Environment tips • Run on a machine with sufficient CPU and network bandwidth. • Increase file descriptor limit: ulimit -n 65535 • Prevent sleep/idle for long tests. 4) Call the CLI from Python Use subprocess to run
lk load-test
from a script or CI job. Example:
Copy code
import subprocess

cmd = [
  "lk", "load-test",
  "--url", "wss://your-livekit-server.com",
  "--api-key", "your-api-key",
  "--api-secret", "your-secret",
  "--room", "test-room",
  "--video-publishers", "10",
  "--subscribers", "50"
]

proc = subprocess.run(cmd, capture_output=True, text=True)
print(proc.stdout)
if proc.returncode != 0:
    print("Error:", proc.stderr)
5) Notes • The CLI uses WebRTC to simulate real participants for realistic results. • If using LiveKit Cloud, tests count toward quotas/usage. If you want, tell me: • whether you’ll test on self-hosted LiveKit or LiveKit Cloud, • target numbers (publishers/subscribers) and media type (audio/video), and I’ll give a tailored command and recommended machine specs. Sources: LiveKit CLI Setup | LiveKit Docs | Benchmarking | LiveKit docs
n
but it's code is in go language , i want to write code in python for load testing
t
You're right—the CLI is written in Go. You can still build a Python-native load tester. I can help you with a focused plan and example code; first I need a few details so I give the right solution. Quick question: do you want the Python tester to • simulate many lightweight WebRTC participants (real audio/video) for realistic load, or • just create/join rooms and exercise server APIs (no real media) for connection/room-level load? Also tell me: • target scale (e.g., 100, 1k participants), • media type (audio, video, or none), • testing environment (self-hosted LiveKit or LiveKit Cloud). Answer those and I’ll provide a concise Python approach (libraries to use, architecture, and a starter script). Sources: Benchmarking | LiveKit docs | Python SDKs | livekit/livekit_composite | DeepWiki | Creating SIP Inbound Trunks and Dispatch Rules with Python SDK | Job lifecycle | LiveKit docs
n
I want to write code for agent load testing where creating room and checking STT, LLM, TTS just like did in agentloadtest.go
t
Acknowledging: you want a Python equivalent of agentloadtest.go that creates rooms and exercises STT, LLM, and TTS for agent load testing. I can provide a concise plan and a starter Python implementation outline. Before I produce code, one quick clarification so I tailor it correctly: • Do you need the Python agents to run actual WebRTC media (real audio streams) for STT/TTS, or is it acceptable to simulate media payloads and trigger STT/LLM/TTS API flows without full WebRTC media? Tell me that and your target scale (rough number of concurrent agents).
n
100 concurrent agents • Do you need the Python agents to run actual WebRTC media (real audio streams) for STT/TTS, or is it acceptable to simulate media payloads and trigger STT/LLM/TTS API flows without full WebRTC media? yes
t
Acknowledging: you want a Python equivalent of agentloadtest.go that creates rooms and runs 100 concurrent agents with real WebRTC media to exercise STT, LLM, and TTS. I can provide a concise, ready-to-run plan and a starter Python implementation. Before I produce that code, one last quick clarification to match your environment: • Are your agent workers (the STT/LLM/TTS pipeline) already deployed and reachable by the LiveKit server, or do you need guidance deploying/configuring the agent workers as well? If they’re already deployed, I’ll give a Python script that: • generates tokens, • opens 100 WebRTC connections, • publishes looped real audio per agent, • waits for STT/LLM/TTS roundtrips, and includes recommendations for process distribution and resource sizing. If you need agent deployment help, I’ll include the minimal agent config to enable STT/LLM/TTS alongside the Python load test. Which do you want? Sources: An open source stack for real-time multimodal AI | examples/voice_agents | livekit/livekit_composite | DeepWiki | livekit/livekit_composite | DeepWiki | OpenAI and LiveKit partner to turn Advanced Voice into an API | Pipeline nodes and hooks | LiveKit docs
n
• Are your agent workers (the STT/LLM/TTS pipeline) already deployed and reachable by the LiveKit server, or do you need guidance deploying/configuring the agent workers as well? yes
t
Acknowledging: you have agent workers already deployed and want a ready-to-run Python load test that opens 100 concurrent agents with real WebRTC audio to exercise STT, LLM, and TTS. Below is a concise plan, required dependencies, and a starter Python implementation you can run and adapt. It: • creates tokens, • distributes agents across rooms, • opens WebRTC connections, • publishes a looped audio file as a real microphone track, • keeps connections alive to trigger STT → LLM → TTS flows. Dependencies • Python 3.10+ • asyncio • livekit-client (Python client that provides rtc Room/Tracks) — install per your environment (package name may be
livekit-client
or `livekit`; use your existing SDK package) • soundfile or wave (for reading .wav) • Use multiprocessing or run multiple containers to avoid single-process limits Key configuration (fill with your values) • LIVEKIT_WS = wss://your-livekit-server • API_KEY / API_SECRET • AUDIO_FILE = test_speech_5s.wav (mono PCM, 16-bit, 16k or 24kHz recommended) • NUM_AGENTS = 100 • ROOMS = number of rooms to spread agents across (e.g., 10 → 10 agents/room) Starter implementation (concise)
Copy code
import asyncio
import os
import wave
from concurrent.futures import ThreadPoolExecutor
from livekit import Room, LocalAudioTrack, AudioSource, AccessToken, VideoGrant  # adjust imports for your SDK

LIVEKIT_WS = os.getenv("LIVEKIT_WS", "wss://your-livekit-server")
API_KEY = os.getenv("LIVEKIT_API_KEY", "your-api-key")
API_SECRET = os.getenv("LIVEKIT_API_SECRET", "your-api-secret")
AUDIO_FILE = os.getenv("AUDIO_FILE", "test_speech_5s.wav")
NUM_AGENTS = int(os.getenv("NUM_AGENTS", "100"))
ROOM_BASE = os.getenv("ROOM_BASE", "loadtest-room")
ROOM_COUNT = int(os.getenv("ROOM_COUNT", "10"))
AGENT_DURATION = int(os.getenv("AGENT_DURATION", "60"))  # seconds per agent run

def create_token(api_key, api_secret, room, identity):
    at = AccessToken(api_key, api_secret, identity=identity)
    at.add_grant(VideoGrant(room_join=True, room=room, can_publish=True, can_subscribe=True))
    return at.to_jwt()

class LoopWave:
    def __init__(self, path):
        wf = wave.open(path, "rb")
        self.sampwidth = wf.getsampwidth()
        self.framerate = wf.getframerate()
        self.nchannels = wf.getnchannels()
        self.frames = wf.readframes(wf.getnframes())
        wf.close()
        # split into small 10ms frames
        bytes_per_sample = self.sampwidth
        frame_bytes = int(self.framerate * 0.01) * self.nchannels * bytes_per_sample
        self.chunks = [self.frames[i:i+frame_bytes] for i in range(0, len(self.frames), frame_bytes)]

    async def frames_iter(self):
        while True:
            for c in self.chunks:
                yield c

async def run_agent(agent_idx, audio_loop):
    room_name = f"{ROOM_BASE}-{agent_idx % ROOM_COUNT}"
    identity = f"agent-{agent_idx}"
    token = create_token(API_KEY, API_SECRET, room_name, identity)

    room = Room()  # adjust instantiation to SDK
    await room.connect(LIVEKIT_WS, token)

    # create local audio source/track (adjust to SDK API)
    src = AudioSource(sample_rate=24000, channels=1)
    track = LocalAudioTrack("agent-audio", src)
    await room.local_participant.publish_track(track)

    async def send_audio():
        async for chunk in audio_loop.frames_iter():
            # SDK-specific: capture or push PCM frame into source
            await src.capture_frame(chunk, sample_rate=audio_loop.framerate, channels=audio_loop.nchannels)
            await asyncio.sleep(0.01)

    sender = asyncio.create_task(send_audio())

    # keep alive to allow STT/LLM/TTS turnarounds
    await asyncio.sleep(AGENT_DURATION)

    sender.cancel()
    await room.disconnect()

async def main():
    audio_loop = LoopWave(AUDIO_FILE)

    # run agents in batches to avoid stomping local resources
    concurrency = 20
    sem = asyncio.Semaphore(concurrency)

    async def guarded(i):
        async with sem:
            await run_agent(i, audio_loop)

    tasks = [asyncio.create_task(guarded(i)) for i in range(NUM_AGENTS)]
    await asyncio.gather(*tasks)

if __name__ == "__main__":
    asyncio.run(main())
Notes & recommendations • Use mono PCM WAV at 16k–24kHz, 16-bit. The starter assumes 10ms frames. • The SDK method names (
Room
,
AudioSource
,
LocalAudioTrack
,
capture_frame
, token classes) vary by package—adjust imports and calls to your installed LiveKit Python SDK. • Run agents across multiple processes or containers to reach 100 concurrent agents reliably. Example: 4 processes × 25 agents each. • Monitor CPU, memory, and network bandwidth. Increase ulimits: ulimit -n 65535. • Spread agents across multiple rooms (ROUNDS) to balance per-room bandwidth. • Add logging to measure STT/transcription latency and TTS response times (timestamps when publish occurs and when a response track is received). • If you hit media/ICE issues in headless environments, ensure NAT/ICE/STUN/TURN settings are correct and reachable. If you want, I can: • produce a tested code sample matching your exact installed Python SDK (tell me the package name/version), or • provide a multiprocessing/container orchestration snippet (Docker Compose) to run 100 agents across processes. Which would you like next?
n
i want to do it like first subscribe agent track and then let's say epoch_delay is 10 sec then after 10sec what agent has spoken publish it and then so and so on
t
Acknowledging: you want each agent to first subscribe to an agent track, wait epoch_delay seconds, then publish what was spoken during that epoch, and repeat — at scale (100 agents). Below is a concise plan and a focused Python starter implementation showing that subscribe-then-publish cycle with real WebRTC audio. Adjust SDK calls to your installed LiveKit Python client if names differ. Key points • Each agent: ◦ connects and subscribes to a target participant’s audio track, ◦ buffers incoming audio frames for epoch_delay seconds, ◦ after delay, republishes the buffered audio as a local published track, ◦ repeats the cycle. • Use an audio buffer per subscription (in-memory ring or list of chunks). • Run agents across processes/containers (e.g., 4 processes × 25 agents) for 100 concurrent agents. • Use mono PCM WAV frames (10ms chunks); ensure sample rate matches agent worker STT requirements. • Monitor resource usage and increase ulimits (ulimit -n 65535). Starter implementation (conceptual — adapt SDK names):
Copy code
import asyncio
import os
import wave
from collections import deque
from livekit import Room, AccessToken, VideoGrant, LocalAudioTrack, AudioSource  # adjust imports

LIVEKIT_WS = os.getenv("LIVEKIT_WS", "wss://your-livekit-server")
API_KEY = os.getenv("LIVEKIT_API_KEY", "key")
API_SECRET = os.getenv("LIVEKIT_API_SECRET", "secret")
NUM_AGENTS = int(os.getenv("NUM_AGENTS", "100"))
ROOM_BASE = os.getenv("ROOM_BASE", "loadtest-room")
ROOM_COUNT = int(os.getenv("ROOM_COUNT", "10"))
EPOCH_DELAY = float(os.getenv("EPOCH_DELAY", "10.0"))  # seconds
AGENT_DURATION = int(os.getenv("AGENT_DURATION", "120"))

def create_token(api_key, api_secret, room, identity):
    at = AccessToken(api_key, api_secret, identity=identity)
    at.add_grant(VideoGrant(room_join=True, room=room, can_publish=True, can_subscribe=True))
    return at.to_jwt()

class AudioBuffer:
    def __init__(self, max_seconds=30, sample_rate=24000, channels=1, chunk_ms=10):
        self.sample_rate = sample_rate
        self.channels = channels
        self.chunk_bytes = int(sample_rate * (chunk_ms/1000.0)) * 2 * channels  # 16-bit PCM
        max_chunks = int(max_seconds * 1000 / chunk_ms)
        self.deque = deque(maxlen=max_chunks)

    def push(self, pcm_bytes):
        self.deque.append(pcm_bytes)

    def drain(self):
        data = b"".join(self.deque)
        self.deque.clear()
        return data

async def handle_agent(agent_idx, target_identity=None):
    room_name = f"{ROOM_BASE}-{agent_idx % ROOM_COUNT}"
    identity = f"agent-{agent_idx}"
    token = create_token(API_KEY, API_SECRET, room_name, identity)

    room = Room()
    await room.connect(LIVEKIT_WS, token)

    # Create a local audio source/track (SDK-specific)
    src = AudioSource(sample_rate=24000, channels=1)
    local_track = LocalAudioTrack("agent-publish", src)
    await room.local_participant.publish_track(local_track)

    # Choose subscription target; here we subscribe to the first remote participant that appears
    audio_buffer = AudioBuffer(sample_rate=24000)

    @room.on("track_subscribed")
    def on_track_subscribed(track, participant):
        # Only handle audio tracks
        if track.kind != "audio":
            return
        # Hook into incoming audio frames - SDK-specific callback
        async def on_frame(frame):
            # frame.data is raw PCM bytes; push to buffer
            audio_buffer.push(frame.data)
        track.on("frame", on_frame)  # adjust for SDK event API

    # wait for initial subscriptions to stabilize
    await asyncio.sleep(1)

    async def epoch_loop():
        while True:
            await asyncio.sleep(EPOCH_DELAY)
            # drain buffer and publish it as a new local track (or replace source)
            pcm = audio_buffer.drain()
            if not pcm:
                continue
            # Option A: push PCM into the existing AudioSource
            # Many SDKs expose a capture_frame-like API:
            await src.capture_frame(pcm, sample_rate=24000, channels=1)
            # Option B: if SDK requires a new track, create and publish one with pcm
            # After publishing, allow time for agent worker to process (STT/LLM/TTS)
            await asyncio.sleep(1)  # small grace before next epoch

    coro = asyncio.create_task(epoch_loop())

    # keep agent alive for AGENT_DURATION then cleanup
    await asyncio.sleep(AGENT_DURATION)
    coro.cancel()
    await room.disconnect()

async def main():
    concurrency = 20
    sem = asyncio.Semaphore(concurrency)

    async def guarded(i):
        async with sem:
            await handle_agent(i)

    tasks = [asyncio.create_task(guarded(i)) for i in range(NUM_AGENTS)]
    await asyncio.gather(*tasks)

if __name__ == "__main__":
    asyncio.run(main())
Implementation notes and adjustments you must make • SDK events/callbacks differ: replace
track.on("frame", ...)
,
AudioSource.capture_frame
, and
Room
usage with the exact methods in your installed LiveKit Python client. • Frame encoding: ensure incoming frames are delivered as raw PCM. If SDK gives encoded RTP packets, use SDK helpers that provide decoded audio frames or configure the subscriber to provide raw audio frames. • If the SDK doesn’t expose direct raw frames on subscription, you can subscribe and have the agent worker publish a mirrored track that your load-test clients can also subscribe to; or use server-side mixing/forwarding logic. • Buffer sizing: tune chunk size and buffer length to match EPOCH_DELAY and memory limits. • Concurrency: run multiple processes/containers to hit 100 agents. Example: spawn N worker processes each running this script with NUM_AGENTS / N agents. • Latency metrics: timestamp when buffer drained and when a response track is received to measure STT→LLM→TTS roundtrip. If you want, I can next: • produce the same example adapted to the exact Python LiveKit package version you have installed (tell me the package name/version), or • provide a multiprocessing launcher/docker-compose snippet to run 100 agents across multiple processes. Which next step do you want?
n
Copy code
import asyncio
import time
from livekit import rtc
from livekit.rtc import RemoteTrackPublication, RemoteParticipant, Track


class LoadTestRoom:
    def __init__(self, echo_speech_delay, index, logger=None):
        self.echo_speech_delay = echo_speech_delay
        self.index = index
        self.room: rtc.Room = rtc.Room()
        self.echo_source = rtc.AudioSource(48000, 1)
        self.echo_track = rtc.LocalAudioTrack.create_audio_track(
            "echo-track",
            self.echo_source
        )
        self.running = True
        self.first_received = False
        self.logger = logger

    async def connect(self, url: str, token: str):
        await self.room.connect(url, token)
        self.room.on("track_subscribed", self._on_track_subscribed)

        # Create the echo track (same as Go)
        await self.room.local_participant.publish_track(self.echo_track)

        if self.logger:
            self.logger.info(f"[Room {self.index}] Echo participant connected.")

    def _on_track_subscribed(self, track: Track, publication: RemoteTrackPublication,
                             participant: RemoteParticipant):
        if track.kind != rtc.TrackKind.KIND_AUDIO:
            return

        if self.first_received:
            return
        self.first_received = True

        remote_audio = track
        if self.logger:
            self.logger.info(f"[Room {self.index}] Subscribed to agent audio.")

        asyncio.create_task(self._echo_audio(remote_audio))

    async def _echo_audio(self, remote_audio: Track):
        queue = asyncio.Queue(maxsize=2000)
        audio_stream = rtc.AudioStream(remote_audio)

        async def reader():
            async for event in audio_stream:  # event = AudioFrameEvent
                self.logger.info(f"[Room {self.index}] Received event AudioFram in Reader")
                await queue.put((event, time.time()))
                if not self.running:
                    break

        async def writer():
            while self.running:
                self.logger.info(f"[Room {self.index}] Start Point audio received.")
                event, ts = await queue.get()
                self.logger.info(f"[Room {self.index}] Going for delay event {event}.")
                delay = self.echo_speech_delay - (time.time() - ts)
                if delay > 0:
                    await asyncio.sleep(delay)

                self.logger.info(f"[Room {self.index}] Echo audio received.")

                # IMPORTANT FIX
                await self.echo_source.capture_frame(event.frame)

        await asyncio.gather(reader(), writer())

    async def stop(self):
        self.running = False
        await self.room.disconnect()
        if self.logger:
            self.logger.info(f"[Room {self.index}] Disconnected.")
this is how i have written but it is not working nothing is being publish on user track INFOloadtest[Room 4] Start Point audio received. INFOloadtest[Room 4] Going for delay event AudioFrameEvent(frame=rtc.AudioFrame(sample_rate=48000, num_channels=1, samples_per_channel=480, duration=0.010)). INFOloadtest[Room 4] Echo audio received.
t
Thanks — your code is very close. The logs show frames are received and processed, so the problem is not capture but the publish loop/lifecycle and a few runtime details. Below are concise fixes and a small corrected snippet you can drop into your class. What I’m addressing: keep the writer alive, handle end-of-stream, add error handling around capture_frame, and increase AudioSource buffer (queue_size_ms). Key fixes • Keep writer running (use timeout on queue.get and a sentinel for EOS). • Wrap
capture_frame
with try/except and log errors. • Increase
AudioSource
buffer (
queue_size_ms
) to avoid blocking/failing to capture. • Ensure you publish the local track before relying on capture_frame (you already do). • Optionally filter by participant.identity to ensure you subscribe to the intended agent. Corrected _echo_audio (concise)
Copy code
async def _echo_audio(self, remote_audio: Track):
    queue = asyncio.Queue(maxsize=2000)
    audio_stream = rtc.AudioStream(remote_audio)

    async def reader():
        try:
            async for event in audio_stream:
                if not self.running:
                    break
                await queue.put((event.frame, time.time()))
        except Exception as e:
            self.logger.error(f"[Room {self.index}] reader error: {e}")
        finally:
            # signal end of stream
            await queue.put((None, 0))

    async def writer():
        while True:
            try:
                item = await asyncio.wait_for(queue.get(), timeout=1.0)
            except asyncio.TimeoutError:
                if not self.running and queue.empty():
                    break
                continue

            frame, ts = item
            if frame is None:
                break

            delay = self.echo_speech_delay - (time.time() - ts)
            if delay > 0:
                await asyncio.sleep(delay)

            try:
                await self.echo_source.capture_frame(frame)
            except Exception as e:
                self.logger.error(f"[Room {self.index}] capture_frame failed: {e}")
            finally:
                queue.task_done()

        self.logger.info(f"[Room {self.index}] writer exiting")

    await asyncio.gather(reader(), writer())
AudioSource creation suggestion (increase queue size) • When you create the AudioSource, set a larger buffer (if constructor supports it):
Copy code
self.echo_source = rtc.AudioSource(48000, 1, queue_size_ms=2000)
(if your SDK’s constructor param name differs, adjust accordingly) Extra debugging tips • Log participant.identity in _on_track_subscribed to ensure you subscribe to the correct agent. • Log success of publish: after publish_track, log returned publication or SID. • Add a short sleep after publish to ensure the track is fully negotiated before you start capturing: await asyncio.sleep(0.2) • Monitor exceptions from capture_frame — they show if the source buffer is full or if the track isn’t published. If you want, I can: • produce a minimal end-to-end example with AudioSource creation and publish flow matching your installed livekit Python package version (tell me the package name/version), or • add participant identity filtering and a graceful shutdown example. Which would help most? Sources: client-sdk-android | livekit/livekit_composite | DeepWiki | Subscribing to tracks | LiveKit docs | Camera & microphone | LiveKit docs | Processing raw media tracks | LiveKit docs | Resolving &#34;InvalidState - failed to capture frame&#34; errors in AudioSource
n
suppose i have subscribed agent audio but i am also getting frame of where agent is ideal state not speaking
t
You will receive frames during idle/silent periods — that’s expected. To avoid echoing silence, detect voice activity before buffering/publishing. Two practical options: 1) Simple energy (RMS) threshold • Convert
frame.data
(int16 PCM) to numbers, compute RMS or dB, and skip frames below a threshold (e.g. -50 dB). • Cheap, fast, no extra deps. Example (insert into your reader loop):
Copy code
import numpy as np
def is_silent(frame, threshold_db=-50.0):
    samples = np.frombuffer(frame.data, dtype=np.int16).astype(np.float32)
    if samples.size == 0:
        return True
    rms = np.sqrt((samples**2).mean()) + 1e-10
    db = 20 * np.log10(rms / 32768.0)
    return db < threshold_db

# usage inside reader:
async for event in audio_stream:
    if is_silent(event.frame):
        continue
    await queue.put((event.frame, time.time()))
2) Use a VAD for better accuracy (recommended) • Use a VAD model (e.g., Silero VAD in LiveKit plugins or any VAD) to get speech probability per frame and only buffer frames when speech is detected. • More robust to background noise and tuning. Concept:
Copy code
# pseudo: use your VAD API to check frame
speech_prob = await vad_stream.recv_audio(event.frame)
if speech_prob > 0.5:
    await queue.put((event.frame, time.time()))
Integration tips for your echo logic • Buffer only non-silent frames, but keep short leading/trailing silence (e.g., keep N ms before/after speech) to avoid clipped words. • If you want epoch-based behavior (collect X seconds of spoken audio every epoch), use VAD to mark speech segments, append silent padding around segments, then on epoch end drain and publish only the buffered speech region. • Keep writer alive and robust (use timeout on queue.get) so brief silent gaps don’t stop the loop. • Monitor queue sizes and use
queue_size_ms
on
AudioSource
to avoid capture_frame failures. Example pattern for epoch with VAD/energy: • reader: discard silent frames until speech starts, then push frames to queue while speech continues (and for a short trailing timeout). • epoch task (every epoch_delay): drain queue → if drained buffer non-empty, publish via
capture_frame
(or push frames into
AudioSource
). If you want, I can: • adapt the RMS code into your existing
_echo_audio
(full patch), or • produce an example using the Silero VAD plugin for more reliable detection. Which would you prefer? Sources: Bringing Zoom&#39;s end-to-end optimizations to WebRTC | examples/dtmf | livekit/livekit_composite | DeepWiki | Resolving &#34;InvalidState - failed to capture frame&#34; errors in AudioSource | Subscribing to tracks | LiveKit docs | Processing raw media tracks | LiveKit docs
n
INFOloadtest[Room 0] Echo frame capture: rtc.AudioFrame(sample_rate=48000, num_channels=1, samples_per_channel=480, duration=0.010) i want to every 30 sec and then push not 0.010
t
Acknowledging: you want to collect incoming 10ms frames into a single ~30s buffer and then publish that buffered audio (not each 10ms frame) back into the room. Solution summary — what to do • Buffer raw PCM frames into an in-memory byte buffer for the epoch (30s). • Optionally drop silent frames with RMS/VAD while buffering. • After epoch ends, push the buffered PCM to the echo AudioSource in sequence (or create a single track from the whole buffer). • Use an async producer/consumer so reader never blocks writer; writer sleeps between pushing frames to respect original timing. Concise example patch to integrate into your _echo_audio writer: • assumptions: incoming frames are 10ms PCM int16, same sample rate/channel as AudioSource;
self.echo_source.capture_frame()
accepts an AudioFrame or raw PCM wrapped into rtc.AudioFrame. 1) Buffering approach (store frames and timestamps)
Copy code
# inside _echo_audio: replace per-frame immediate capture with epoch buffering

EPOCH_SEC = 30.0
frame_buffer = []  # list of rtc.AudioFrame or raw bytes
epoch_start = time.time()

async def reader():
    async for event in audio_stream:
        if not self.running:
            break
        # optional: skip silent frames here
        frame_buffer.append(event.frame)
        # continue reading without publishing

async def epoch_publisher():
    while self.running:
        await asyncio.sleep(EPOCH_SEC)
        if not frame_buffer:
            continue
        # Create a snapshot and clear buffer atomically
        frames_to_send = frame_buffer.copy()
        frame_buffer.clear()

        # publish frames_to_send sequentially to preserve timing
        for f in frames_to_send:
            try:
                await self.echo_source.capture_frame(f)
            except Exception as e:
                self.logger.error(f"[Room {self.index}] capture_frame failed: {e}")
            # preserve original frame duration (10ms)
            await asyncio.sleep(f.duration)
2) If
capture_frame
requires raw PCM instead of AudioFrame: • Convert frames_to_send into rtc.AudioFrame objects with correct metadata, or if you have raw bytes, package them into a single long AudioFrame with samples_per_channel = sample_rate * epoch_seconds (but many SDKs expect small frames; prefer sequential 10ms frames). 3) Optional: silence trimming and padding • Before sending, you can trim leading/trailing silent frames (use RMS or VAD) and add a small pre/post padding (e.g., 100–300ms) to avoid clipped words. 4) Use separate tasks and proper locking • Protect access to shared frame_buffer with an asyncio.Lock if reader and publisher run concurrently:
Copy code
buffer_lock = asyncio.Lock()
# when appending:
async with buffer_lock:
    frame_buffer.append(event.frame)
# when draining:
async with buffer_lock:
    frames_to_send = frame_buffer.copy()
    frame_buffer.clear()
5) Timing and pacing • Use
await asyncio.sleep(frame.duration)
between captures to avoid flooding the AudioSource; do not call capture_frame back-to-back without pacing. • Keep AudioSource
queue_size_ms
large enough (e.g., 2000) to handle bursts. 6) Memory considerations • 30s of 48kHz mono int16 ~= 48000 * 2 * 30 = ~2.88 MB per agent. For 100 agents, ensure host has enough RAM or reduce epoch size/sample rate. If you’d like, I can: • convert this into a complete replacement _echo_audio function matching your earlier class (with lock, VAD filter, and asyncio tasks), or • show how to stitch frames into a single long AudioFrame if your SDK prefers that. Which do you want?
n
means collect 30 sec audio frame and then publish it to audio track
t
Acknowledging: you want to collect ~30 seconds of incoming 10ms audio frames, then publish that 30s buffer back to the room as audio (not frame-by-frame immediate echo). Below is a focused implementation you can drop into your class. It: • subscribes and collects incoming
AudioFrame
objects into a thread-safe buffer for an epoch (30s), • drains the buffer at epoch end and publishes the collected audio sequentially to your
AudioSource
(preserving timing), • optionally trims leading/trailing silent frames (RMS-based) before publishing, • uses an asyncio.Lock to avoid races, and includes basic error handling. Adjust SDK method names if your installed package differs.
Copy code
import asyncio
import time
import numpy as np

EPOCH_SECONDS = 30.0
SILENCE_DB_THRESHOLD = -50.0  # tune as needed

def is_silent_frame(frame, threshold_db=SILENCE_DB_THRESHOLD):
    samples = np.frombuffer(frame.data, dtype=np.int16).astype(np.float32)
    if samples.size == 0:
        return True
    rms = np.sqrt((samples**2).mean()) + 1e-10
    db = 20 * np.log10(rms / 32768.0)
    return db < threshold_db

async def _echo_audio(self, remote_audio: Track):
    audio_stream = rtc.AudioStream(remote_audio)
    buffer_lock = asyncio.Lock()
    frame_buffer = []  # list of rtc.AudioFrame
    reader_done = False

    async def reader():
        nonlocal reader_done
        try:
            async for event in audio_stream:
                if not self.running:
                    break
                frame = event.frame
                # optional: skip silent frames to reduce buffer size
                if is_silent_frame(frame):
                    continue
                async with buffer_lock:
                    frame_buffer.append(frame)
        except Exception as e:
            self.logger.error(f"[Room {self.index}] reader error: {e}")
        finally:
            reader_done = True

    async def epoch_publisher():
        while self.running or not reader_done:
            await asyncio.sleep(EPOCH_SECONDS)
            # snapshot and clear buffer atomically
            async with buffer_lock:
                if not frame_buffer:
                    continue
                frames_to_send = frame_buffer.copy()
                frame_buffer.clear()

            # Optional: trim leading/trailing silence from frames_to_send (already filtered above)
            # Publish frames sequentially, preserving timing
            for f in frames_to_send:
                try:
                    await self.echo_source.capture_frame(f)
                except Exception as e:
                    self.logger.error(f"[Room {self.index}] capture_frame failed: {e}")
                    # consider retry/backoff or dropping remaining frames
                # preserve original per-frame duration (e.g., 0.01s)
                await asyncio.sleep(f.duration)

            self.logger.info(f"[Room {self.index}] Published {len(frames_to_send)} frames (~{len(frames_to_send)*frames_to_send[0].duration:.1f}s)")

    # start tasks
    reader_task = asyncio.create_task(reader())
    publisher_task = asyncio.create_task(epoch_publisher())

    await asyncio.gather(reader_task, publisher_task)
Important notes and tuning • Memory: 30s @ 48kHz mono int16 ≈ 2.88 MB per agent. For 100 agents, ensure enough RAM or reduce epoch/sample-rate. • Timing: we publish frames sequentially with
await asyncio.sleep(f.duration)
to keep real-time pacing. Do not flood capture_frame without pacing. • AudioSource buffer: ensure
AudioSource
was created with a sufficient internal buffer (e.g.,
queue_size_ms=2000
) to avoid capture_frame blocking/failing. • Silence handling: you can increase sensitivity or use a VAD for better detection; if you want exact original silence preserved, remove the
is_silent_frame
filter. • Synchronization: use the Lock to avoid race conditions between reader and publisher. • Graceful shutdown: ensure
self.running = False
triggers exit; publisher drains remaining frames before exit. Would you like a full, runnable minimal example adapted to your exact livekit-client package version (tell me the package name/version) or a version that writes the 30s buffer to a WAV and publishes that single long AudioFrame?