agents icon indicating copy to clipboard operation
agents copied to clipboard

RecorderIO drops the resampler tail of every agent speech segment

Open Samu-14 opened this issue 3 months ago โ€ข 1 comments

Bug Description

RecorderIO loses the tail of every agent speech segment whenever the audio output's sample rate differs from the recorder's, which is the normal case (a 16 kHz or 24 kHz TTS into a 48 kHz recording).

_Track keeps one rtc.AudioResampler per channel and holds back whatever the resampler has not yet returned. That held-back tail is only flushed lazily, in _Track.push, when the next run re-anchors:

https://github.com/livekit/agents/blob/main/livekit-agents/livekit/agents/voice/recorder_io/recorder_io.py#L104-L110

if expected is None or abs(started_at - expected) > RESYNC_TOLERANCE:
    if self._resampler is not None:
        # whatever the resampler still holds is the tail of the run that just ended
        _place(self._resampler.flush())
    self._run_start, self._run_samples = started_at, 0

_place puts that tail at the end of the previous run. But a run ends when the agent stops speaking, and the next run starts when it speaks again โ€” seconds later โ€” so by then _write_task has flushed several times and cursor is far past the old run's end. _Track.take therefore discards it:

if stop <= start:
    self.dropped_samples += len(samples)
    continue

So each agent turn is recorded ~15โ€“35 ms short at its end, and at aclose() the last turn's tail is lost too โ€” _encode_thread breaks on None without flushing the resamplers, so it is not even counted.

The dropped_samples warning is emitted once in _encode_thread's finally, which makes this look like a shutdown-ordering problem in the logs. It is not: the audio was already lost during the call.

In production (SIP, ElevenLabs pcm_16000) we see this on every call:

{"message": "recorder dropped audio that reached it after its place in the timeline had been written",
 "level": "WARNING", "name": "livekit.agents", "channel": "output", "samples": 16858}

16858 samples = 351 ms over a ~2.5 minute call. Shorter calls scale down proportionally to the number of agent turns (7362 and 4092 samples on two others).

Expected Behavior

The recording contains all the agent audio the sink reported as played. Nothing is dropped, and dropped_samples stays at 0 on a call where every segment played normally.

Reproduction Steps

pip install livekit-agents==1.7.1
python repro_recorder_tail.py                  # 16 kHz output -> ~19 ms lost per segment
TTS_RATE=48000 python repro_recorder_tail.py   # no resampling -> nothing lost

Output:

-- TTS_RATE=16000
WARNING: recorder dropped audio that reached it after its place in the timeline had been written [channel=output samples=5400 = 112 ms]
6 segments, 9.0s of agent audio at 16000 Hz

-- TTS_RATE=24000
WARNING: recorder dropped audio that reached it after its place in the timeline had been written [channel=output samples=4940 = 103 ms]
6 segments, 9.0s of agent audio at 24000 Hz

-- TTS_RATE=48000
6 segments, 9.0s of agent audio at 48000 Hz

The control at 48 kHz โ€” the only run where _Track._resample returns the frame without a resampler โ€” drops nothing. That isolates the cause to the resampler tail.

repro_recorder_tail.py
"""RecorderIO drops the resampler tail of every agent speech segment.

Public path only: RecorderIO.record_input / record_output, driven with exactly
the callbacks livekit.agents.voice.room_io._output._report_run() emits.

    python repro_recorder_tail.py              # TTS at 16 kHz -> audio is dropped
    TTS_RATE=48000 python repro_recorder_tail.py   # no resampling -> nothing dropped
"""

import asyncio
import logging
import os
import time

import numpy as np
from livekit import rtc
from livekit.agents.voice import io
from livekit.agents.voice.recorder_io import RecorderIO

TTS_RATE = int(os.getenv("TTS_RATE", "16000"))  # e.g. elevenlabs encoding="pcm_16000"
RECORDER_RATE = 48000
SEGMENTS = 6
SPEECH = 1.5  # seconds of agent speech per segment
GAP = 2.0  # silence between segments, long enough for a periodic flush


def tone(seconds: float, rate: int) -> rtc.AudioFrame:
    n = int(seconds * rate)
    t = np.arange(n) / rate
    data = (np.sin(2 * np.pi * 220 * t) * 8000).astype(np.int16)
    return rtc.AudioFrame(
        data=data.tobytes(), sample_rate=rate, num_channels=1, samples_per_channel=n
    )


class SilentInput(io.AudioInput):
    """A caller who says nothing, delivering frames in lockstep with wall time.

    Kept exactly real-time so the input channel never looks stalled: the point
    of the repro is the output channel.
    """

    FRAME = 0.02

    def __init__(self) -> None:
        super().__init__(label="repro")
        self._next: float | None = None

    def __aiter__(self):
        return self

    async def __anext__(self) -> rtc.AudioFrame:
        now = time.time()
        self._next = (self._next or now) + self.FRAME
        if (delay := self._next - now) > 0:
            await asyncio.sleep(delay)
        return tone(self.FRAME, RECORDER_RATE)


async def main() -> None:
    recorder = RecorderIO(agent_session=None, sample_rate=RECORDER_RATE)  # type: ignore[arg-type]
    audio_input = recorder.record_input(SilentInput())
    audio_output = recorder.record_output(None)

    async def pump() -> None:
        async for _ in audio_input:
            pass

    pump_task = asyncio.create_task(pump())
    await recorder.start(output_path="/tmp/repro.ogg")

    for _ in range(SEGMENTS):
        await audio_output.capture_frame(tone(SPEECH, TTS_RATE))
        audio_output.flush()
        started_at = time.time()
        await asyncio.sleep(SPEECH)
        # what _report_run() reports once the sink has drained the segment
        audio_output.on_playback_started(created_at=started_at)
        audio_output.on_playback_progressed(
            started_at=started_at, offset=0.0, duration=SPEECH
        )
        audio_output.on_playback_finished(playback_position=SPEECH, interrupted=False)
        await asyncio.sleep(GAP)

    await recorder.aclose()
    pump_task.cancel()

    print(
        f"{SEGMENTS} segments, {SEGMENTS * SPEECH:.1f}s of agent audio at {TTS_RATE} Hz"
    )


class ShowExtras(logging.Handler):
    def emit(self, record: logging.LogRecord) -> None:
        if "samples" in record.__dict__:
            print(
                f"{record.levelname}: {record.getMessage()} "
                f"[channel={record.channel} samples={record.samples} "
                f"= {record.samples / RECORDER_RATE * 1000:.0f} ms]"
            )


if __name__ == "__main__":
    logging.getLogger("livekit.agents").addHandler(ShowExtras())
    asyncio.run(main())

Operating System

Debian (python:3.12-slim container), Linux x86_64

Models Used

Deepgram Nova-3 ยท OpenAI-compatible LLM ยท ElevenLabs Flash v2.5 (encoding="pcm_16000")

Package Versions

livekit==1.1.15
livekit-agents==1.7.1
livekit-plugins-deepgram==1.7.1
livekit-plugins-elevenlabs==1.7.1
livekit-plugins-openai==1.7.1

Proposed Solution

# The tail belongs to the run that is ending, and it has to be placed while the
# writer is still held behind that run โ€” not lazily at the next push, by which
# time the cursor has moved on.
#
# 1. Give _Track an explicit end-of-run, and call it from
#    RecorderAudioOutput.on_playback_finished (and from RecorderAudioInput when
#    the source ends), i.e. while RecorderIO._write_task is still clamping
#    `settled` to `self._out_record.pending_since`:

class _Track:
    def flush_run(self) -> None:
        """Place whatever the resampler still holds, closing the open run."""
        if self._resampler is not None and self._run_start is not None:
            self._place(self._resampler.flush())

# 2. Flush both tracks before _encode_thread exits, so the last segment's tail
#    is written instead of being silently discarded on the `None` sentinel:

for track in tracks:
    track.flush_run()
block = np.stack([t.take(cursor, <end of timeline>) for t in tracks])

Alternatively _Track.take could keep, rather than drop, samples that land behind the cursor and mix them into the next block with a small tolerance โ€” but that hides the misplacement instead of fixing it.

Additional Context

Discovered while auditing a SIP voice agent's shutdown logs, where the warning appears right after AgentSession.aclose() and reads like a close-ordering bug. It would be easier to diagnose if the warning were emitted where the drop happens (with the timeline position) rather than aggregated at close.

Samu-14 avatar Aug 30 '26 14:08 Samu-14

Please assign me this

BUTTERFINGERS7498 avatar Aug 30 '26 22:08 BUTTERFINGERS7498