Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion livekit-agents/livekit/agents/voice/avatar/_datastream_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,14 +188,24 @@ async def _finish_cancelled_capture(self, clear_task: asyncio.Task[None]) -> Non
_CaptureCancelledEvent(playback_position=0, interrupted=True)
)

async def _aclose_writer(self, writer: rtc.ByteStreamWriter) -> None:
Comment thread
regalmoix marked this conversation as resolved.
Resolved
"""Close an avatar audio stream and log failures without propagating them."""
try:
await writer.aclose()
except Exception as e:
if self._room.isconnected():
logger.warning("failed to close the avatar audio stream", exc_info=e)
else:
logger.debug("failed to close the avatar audio stream", exc_info=e)

def flush(self) -> None:
"""Mark end of current audio segment"""
super().flush()
if self._stream_writer is None or not self._started:
return

# close the stream marking the end of the segment
task = asyncio.create_task(self._stream_writer.aclose())
task = asyncio.create_task(self._aclose_writer(self._stream_writer))
self._tasks.add(task)
task.add_done_callback(self._tasks.discard)

Expand Down
14 changes: 14 additions & 0 deletions tests/test_datastream_audio_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -542,3 +542,17 @@ async def test_clear_fallback_releases_waiter_and_preserves_next_reply(
_finish(output)
event = await asyncio.wait_for(output.wait_for_playout(), timeout=1.0)
assert not event.interrupted


async def test_flush_close_failure_is_handled(
sink: tuple[ds.DataStreamAudioOutput, MagicMock], caplog: pytest.LogCaptureFixture
) -> None:
output, room = sink
writer = room.local_participant.stream_bytes.return_value
writer.aclose.side_effect = rtc.StreamError("handle not found")

await output.capture_frame(_frame())
output.flush()
await asyncio.gather(*output._tasks)
writer.aclose.assert_awaited_once()
assert "failed to close the avatar audio stream" in caplog.text
Loading