diff --git a/.changeset/source-close-off-loop.md b/.changeset/source-close-off-loop.md new file mode 100644 index 00000000..13907928 --- /dev/null +++ b/.changeset/source-close-off-loop.md @@ -0,0 +1,5 @@ +--- +"livekit-rtc": patch +--- + +`AudioSource.aclose()` and `VideoSource.aclose()` now dispose the native handle in a worker thread, so they no longer block the event loop, and both sources gain a synchronous `close()`. `AudioSource.close()`, `clear_queue()` and `asyncio.run(source.aclose())` can be called from another thread: a pending `wait_for_playout()` is released on the source's own loop, and audio captured after a `clear_queue()` keeps its own playout tracking. `wait_for_playout()` no longer returns early after the source moves to a new event loop. Capturing a frame after close is now a no-op. diff --git a/livekit-rtc/livekit/rtc/audio_source.py b/livekit-rtc/livekit/rtc/audio_source.py index 680cc803..afc08291 100644 --- a/livekit-rtc/livekit/rtc/audio_source.py +++ b/livekit-rtc/livekit/rtc/audio_source.py @@ -14,8 +14,10 @@ from __future__ import annotations -import time import asyncio +import threading +import time +from typing import Any, Callable from ._ffi_client import FfiHandle, FfiClient from ._proto import audio_frame_pb2 as proto_audio_frame @@ -23,6 +25,29 @@ from .audio_frame import AudioFrame +def _call_on_loop( + loop: asyncio.AbstractEventLoop | None, callback: Callable[..., None], *args: Any +) -> None: + """Run `callback` on `loop` if it is running on another thread, else run it here.""" + try: + running_loop = asyncio.get_running_loop() + except RuntimeError: + running_loop = None + + if loop is not None and loop.is_running() and running_loop is not loop: + loop.call_soon_threadsafe(callback, *args) + else: + callback(*args) + + +def _finish_waiter(fut: asyncio.Future[None], handle: asyncio.TimerHandle | None) -> None: + """Cancel a detached playout timer and release the waiters of its future.""" + if handle is not None: + handle.cancel() + if not fut.done(): + fut.set_result(None) + + class AudioSource: """ Represents a real-time audio source with an internal audio queue. @@ -53,7 +78,12 @@ def __init__( """ self._sample_rate = sample_rate self._num_channels = num_channels - self._loop = loop or asyncio.get_event_loop() + self._loop: asyncio.AbstractEventLoop | None = loop + if self._loop is None: + try: + self._loop = asyncio.get_running_loop() + except RuntimeError: + self._loop = None req = proto_ffi.FfiRequest() req.new_audio_source.type = proto_audio_frame.AudioSourceType.AUDIO_SOURCE_NATIVE @@ -67,6 +97,8 @@ def __init__( self._last_capture = 0.0 self._q_size = 0.0 + self._capture_gen = 0 + self._lock = threading.Lock() self._join_handle: asyncio.TimerHandle | None = None self._join_fut: asyncio.Future[None] | None = None @@ -83,7 +115,8 @@ def num_channels(self) -> int: @property def queued_duration(self) -> float: """The current duration (in seconds) of audio data queued for playback.""" - return max(self._q_size - time.monotonic() + self._last_capture, 0.0) + with self._lock: + return max(self._q_size - time.monotonic() + self._last_capture, 0.0) def clear_queue(self) -> None: """ @@ -96,8 +129,23 @@ def clear_queue(self) -> None: """ req = proto_ffi.FfiRequest() req.clear_audio_buffer.source_handle = self._ffi_handle.handle - _ = FfiClient.instance.request(req) - self._release_waiter() + # The native clear shares the lock with capture_frame()'s submission, so a capture + # is ordered entirely before the clear or entirely after it. The cleared audio's + # future and timer are detached here, so a later capture starts with fresh ones. + with self._lock: + _ = FfiClient.instance.request(req) + self._last_capture = 0.0 + self._q_size = 0.0 + fut, handle = self._join_fut, self._join_handle + self._join_fut = None + self._join_handle = None + if fut is not None: + _call_on_loop(fut.get_loop(), _finish_waiter, fut, handle) + + def _get_loop(self) -> asyncio.AbstractEventLoop: + if self._loop is None or self._loop.is_closed(): + self._loop = asyncio.get_running_loop() + return self._loop async def capture_frame(self, frame: AudioFrame) -> None: """ @@ -116,21 +164,10 @@ async def capture_frame(self, frame: AudioFrame) -> None: Exception: If there is an error during frame capture. """ - if frame.samples_per_channel == 0 or self._ffi_handle.disposed: + if frame.samples_per_channel == 0 or getattr(self._ffi_handle, "disposed", False): return - now = time.monotonic() - elapsed = 0.0 if self._last_capture == 0.0 else now - self._last_capture - self._q_size += frame.samples_per_channel / self.sample_rate - elapsed - self._last_capture = now - - if self._join_handle: - self._join_handle.cancel() - - if self._join_fut is None: - self._join_fut = self._loop.create_future() - - self._join_handle = self._loop.call_later(self._q_size, self._release_waiter) + loop = self._get_loop() req = proto_ffi.FfiRequest() req.capture_audio_frame.source_handle = self._ffi_handle.handle @@ -140,14 +177,42 @@ async def capture_frame(self, frame: AudioFrame) -> None: # callback is let through, and wait_for drops the ones of other captures. async_id: int | None = None queue = FfiClient.instance.queue.subscribe( - loop=self._loop, + loop=loop, filter_fn=lambda e: ( e.WhichOneof("message") == "capture_audio_frame" and (async_id is None or e.capture_audio_frame.async_id == async_id) ), ) try: - resp = FfiClient.instance.request(req) + # The playout state update and the native submission happen under one lock, + # shared with clear_queue(), so a clear never lands between the two. + with self._lock: + self._capture_gen += 1 + current_gen = self._capture_gen + + now = time.monotonic() + elapsed = 0.0 if self._last_capture == 0.0 else now - self._last_capture + # Clamp the remaining backlog: if the timer that resets it never ran (its + # loop closed), the expired time must not shorten this frame. + self._q_size = ( + max(self._q_size - elapsed, 0.0) + frame.samples_per_channel / self.sample_rate + ) + self._last_capture = now + q_size = self._q_size + + if self._join_handle: + self._join_handle.cancel() + + if ( + self._join_fut is None + or self._join_fut.get_loop() is not loop + or self._join_fut.get_loop().is_closed() + ): + self._join_fut = loop.create_future() + + self._join_handle = loop.call_later(q_size, self._release_waiter, current_gen) + + resp = FfiClient.instance.request(req) async_id = resp.capture_audio_frame.async_id cb: proto_ffi.FfiEvent = await queue.wait_for( lambda e: e.capture_audio_frame.async_id == resp.capture_audio_frame.async_id @@ -167,25 +232,51 @@ async def wait_for_playout(self) -> None: audio queue is empty. """ - if self._join_fut is None: + # One read: clear_queue() on another thread may detach the future at any point, + # and it still releases the detached one. + fut = self._join_fut + if fut is None: return - await asyncio.shield(self._join_fut) + await asyncio.shield(fut) - def _release_waiter(self) -> None: - if self._join_fut is None: - return # could be None when clear_queue is called + def _release_waiter(self, gen: int | None = None) -> None: + with self._lock: + if gen is not None and gen != self._capture_gen: + return - if not self._join_fut.done(): - self._join_fut.set_result(None) + if self._join_handle is not None: + self._join_handle.cancel() + self._join_handle = None - self._last_capture = 0.0 - self._q_size = 0.0 - self._join_fut = None + if self._join_fut is None: + return # could be None when clear_queue is called - async def aclose(self) -> None: - """Close the audio source + if not self._join_fut.done(): + self._join_fut.set_result(None) + + self._last_capture = 0.0 + self._q_size = 0.0 + self._join_fut = None + + def _release_waiter_threadsafe(self) -> None: + _call_on_loop(self._loop, self._release_waiter) + + def close(self) -> None: + """Close the audio source. This method cleans up resources associated with the audio source. """ + self._release_waiter_threadsafe() self._ffi_handle.dispose() + + async def aclose(self) -> None: + """Close the audio source without blocking the event loop. + + This method cleans up resources associated with the audio source. + """ + # aclose() may run on another thread's loop (asyncio.run(source.aclose()), see + # #832); the playout waiter belongs to the source's loop and is released there. + self._release_waiter_threadsafe() + if not getattr(self._ffi_handle, "disposed", False): + await asyncio.to_thread(self._ffi_handle.dispose) diff --git a/livekit-rtc/livekit/rtc/video_source.py b/livekit-rtc/livekit/rtc/video_source.py index c8dd2a02..6b2c3947 100644 --- a/livekit-rtc/livekit/rtc/video_source.py +++ b/livekit-rtc/livekit/rtc/video_source.py @@ -14,6 +14,8 @@ from __future__ import annotations +import asyncio + from ._ffi_client import FfiHandle, FfiClient from ._proto import ffi_pb2 as proto_ffi from ._proto import video_frame_pb2 as proto_video @@ -61,6 +63,9 @@ def capture_frame( metadata: proto_video.FrameMetadata | None = None, ) -> None: """Capture a frame, optionally attaching frame metadata.""" + if getattr(self._ffi_handle, "disposed", False): + return + req = proto_ffi.FfiRequest() req.capture_video_frame.source_handle = self._ffi_handle.handle req.capture_video_frame.buffer.CopyFrom(frame._proto_info()) @@ -70,5 +75,17 @@ def capture_frame( req.capture_video_frame.metadata.CopyFrom(metadata) FfiClient.instance.request(req) - async def aclose(self) -> None: + def close(self) -> None: + """Close the video source. + + This method cleans up resources associated with the video source. + """ self._ffi_handle.dispose() + + async def aclose(self) -> None: + """Close the video source without blocking the event loop. + + This method cleans up resources associated with the video source. + """ + if not getattr(self._ffi_handle, "disposed", False): + await asyncio.to_thread(self._ffi_handle.dispose) diff --git a/livekit-rtc/tests/test_ffi_client.py b/livekit-rtc/tests/test_ffi_client.py index 53873884..bededd77 100644 --- a/livekit-rtc/tests/test_ffi_client.py +++ b/livekit-rtc/tests/test_ffi_client.py @@ -22,15 +22,20 @@ _COUNT_ARRAY_TYPES_IN_GARBAGE = """ import ctypes import gc +import os +import sys from livekit import rtc gc.collect() gc.set_debug(gc.DEBUG_SAVEALL) -for _ in range(50): +for _ in range(10): rtc.AudioProcessingModule() gc.collect() -print(sum(isinstance(o, type(ctypes.Array)) for o in gc.garbage)) +count = sum(isinstance(o, type(ctypes.Array)) for o in gc.garbage) +sys.stdout.write(f"{count}\\n") +sys.stdout.flush() +os._exit(0) """ diff --git a/livekit-rtc/tests/test_source_stream_close.py b/livekit-rtc/tests/test_source_stream_close.py new file mode 100644 index 00000000..863ca8fa --- /dev/null +++ b/livekit-rtc/tests/test_source_stream_close.py @@ -0,0 +1,321 @@ +# Copyright 2026 LiveKit, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import asyncio +import threading +import time + +import pytest + +from livekit import rtc +from livekit.rtc._ffi_client import FfiClient +from livekit.rtc._proto import ffi_pb2 as proto_ffi + + +@pytest.mark.asyncio +async def test_audio_source_aclose_releases_waiter_and_cancels_timer() -> None: + source = rtc.AudioSource(48000, 1) + frame = rtc.AudioFrame.create(48000, 1, 48000) + await asyncio.wait_for(source.capture_frame(frame), timeout=5.0) + + assert source._join_fut is not None + assert source._join_handle is not None + + await asyncio.wait_for(source.aclose(), timeout=5.0) + + assert source._ffi_handle.disposed + assert source._join_fut is None + assert source._join_handle is None + + # After aclose, wait_for_playout should return immediately without hanging + await asyncio.wait_for(source.wait_for_playout(), timeout=2.0) + + # Repeated calls are idempotent + await asyncio.wait_for(source.aclose(), timeout=2.0) + + +def test_audio_source_sync_close() -> None: + source = rtc.AudioSource(48000, 1) + assert not source._ffi_handle.disposed + + source.close() + assert source._ffi_handle.disposed + + # Repeated close is idempotent + source.close() + + +def test_audio_source_cross_thread_close() -> None: + source = rtc.AudioSource(48000, 1) + assert not source._ffi_handle.disposed + + t = threading.Thread(target=source.close) + t.start() + t.join() + + assert source._ffi_handle.disposed + + +@pytest.mark.asyncio +async def test_audio_source_capture_after_close_is_noop() -> None: + source = rtc.AudioSource(48000, 1) + source.close() + + frame = rtc.AudioFrame.create(48000, 1, 480) + # Should safely return without error + await asyncio.wait_for(source.capture_frame(frame), timeout=2.0) + + +def test_video_source_sync_close() -> None: + source = rtc.VideoSource(640, 480) + assert not source._ffi_handle.disposed + + source.close() + assert source._ffi_handle.disposed + + # Repeated close is idempotent + source.close() + + +@pytest.mark.asyncio +async def test_video_source_aclose_and_capture_after_close() -> None: + source = rtc.VideoSource(640, 480) + assert not source._ffi_handle.disposed + + await asyncio.wait_for(source.aclose(), timeout=5.0) + assert source._ffi_handle.disposed + + # Capture after close is safely ignored + frame = rtc.VideoFrame( + 640, + 480, + rtc.VideoBufferType.RGBA, + b"\x00" * (640 * 480 * 4), + ) + source.capture_frame(frame) + + # Repeated aclose is idempotent + await asyncio.wait_for(source.aclose(), timeout=2.0) + + +def test_audio_source_init_outside_loop_and_capture_in_asyncio_run() -> None: + source = rtc.AudioSource(48000, 1) + assert source._loop is None + frame = rtc.AudioFrame.create(48000, 1, 480) + + async def _capture() -> None: + await asyncio.wait_for(source.capture_frame(frame), timeout=5.0) + assert source._loop is not None + assert source._loop.is_running() + await asyncio.wait_for(source.aclose(), timeout=5.0) + + asyncio.run(_capture()) + + +def test_audio_source_cross_thread_clear_queue() -> None: + source = rtc.AudioSource(48000, 1) + frame = rtc.AudioFrame.create(48000, 1, 48000) + + async def _run() -> None: + await source.capture_frame(frame) + assert source._join_fut is not None + + t = threading.Thread(target=source.clear_queue) + t.start() + t.join() + + # Playout waiter should be released by cross-thread clear_queue + await asyncio.wait_for(source.wait_for_playout(), timeout=2.0) + await source.aclose() + + asyncio.run(_run()) + + +def test_audio_source_cross_thread_aclose_releases_waiter() -> None: + # The #832 workaround: while the source's loop waits for playout, another thread + # closes the source with asyncio.run(source.aclose()). The playout future belongs to + # the source's loop, so it must be released there. Debug mode on both loops turns a + # release from the wrong thread into a RuntimeError, as asyncio reports it. + source = rtc.AudioSource(48000, 1) + frame = rtc.AudioFrame.create(48000, 1, 48000) # 1s of audio keeps the waiter pending + errors: list[BaseException] = [] + + def _aclose_in_other_thread() -> None: + try: + asyncio.run(source.aclose(), debug=True) + except BaseException as e: + errors.append(e) + + async def _run() -> None: + await source.capture_frame(frame) + waiter = asyncio.ensure_future(source.wait_for_playout()) + await asyncio.sleep(0) + assert not waiter.done() + + t = threading.Thread(target=_aclose_in_other_thread) + t.start() + await asyncio.to_thread(t.join) # keep the source's loop running meanwhile + + await asyncio.wait_for(waiter, timeout=2.0) + + asyncio.run(_run(), debug=True) + + assert errors == [] + assert source._ffi_handle.disposed + assert source._join_fut is None + assert source._join_handle is None + + +def test_audio_source_clear_queue_does_not_cancel_subsequent_capture() -> None: + source = rtc.AudioSource(48000, 1, queue_size_ms=10000) + frame1 = rtc.AudioFrame.create(48000, 1, 48000) + frame2 = rtc.AudioFrame.create(48000, 1, 48000) + + async def _run() -> None: + await source.capture_frame(frame1) + gen1 = source._capture_gen + + # Simulate clear_queue scheduled from another thread + loop = asyncio.get_running_loop() + loop.call_soon(source._release_waiter, gen1) + + # Capture a subsequent frame before yielding + await source.capture_frame(frame2) + assert source._capture_gen > gen1 + assert source._join_fut is not None + + # Allow queued clear callback to execute + await asyncio.sleep(0.01) + + # The subsequent frame's playout future and timer must not be cleared + assert source._join_fut is not None + assert not source._join_fut.done() + + await source.aclose() + + asyncio.run(_run()) + + +def test_audio_source_cross_thread_clear_then_capture_releases_cleared_waiter() -> None: + # A waiter for cleared audio is released by the clear, even when a new frame is + # captured on the source's loop before the clear's callback has run there. + source = rtc.AudioSource(48000, 1, queue_size_ms=10000) + frame_a = rtc.AudioFrame.create(48000, 1, 48000) # 1s + frame_b = rtc.AudioFrame.create(48000, 1, 96000) # 2s + + async def _run() -> None: + await source.capture_frame(frame_a) + waiter_a = asyncio.ensure_future(source.wait_for_playout()) + await asyncio.sleep(0) + + t = threading.Thread(target=source.clear_queue) + t.start() + t.join() # blocks this loop, so the clear's callback is still queued + + # Awaiting the coroutine directly runs its synchronous part before yielding. + await source.capture_frame(frame_b) + + await asyncio.wait_for(waiter_a, timeout=0.5) + + # The replacement audio keeps its own duration, future and timer. + assert source._join_fut is not None + assert not source._join_fut.done() + assert source._join_handle is not None + assert source.queued_duration > 1.5 + + await source.aclose() + + asyncio.run(_run()) + + +def test_audio_source_capture_on_new_loop_keeps_full_frame_duration() -> None: + # The first loop closes while its playout timer is pending, so the timer that resets + # the backlog never runs. The idle time since then must not shorten the next frame. + source = rtc.AudioSource(48000, 1) + frame = rtc.AudioFrame.create(48000, 1, 4800) # 100 ms + + async def _capture() -> None: + await source.capture_frame(frame) + + asyncio.run(_capture()) + time.sleep(0.3) + + async def _capture_and_wait() -> None: + await source.capture_frame(frame) + assert source._q_size == pytest.approx(0.1) + + waiter = asyncio.ensure_future(source.wait_for_playout()) + await asyncio.sleep(0.02) + assert not waiter.done() + await asyncio.wait_for(waiter, timeout=2.0) + await source.aclose() + + asyncio.run(_capture_and_wait()) + + +def test_audio_source_native_requests_hold_the_playout_lock( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # capture_frame() and clear_queue() submit their native request under the lock that + # guards the playout state, so a clear cannot land between a capture's state update + # and its submission, nor a capture between the native clear and the state reset. + source = rtc.AudioSource(48000, 1) + client: FfiClient = FfiClient.instance + real_request = client.request + lock_held: dict[str, bool] = {} + + def request(req: proto_ffi.FfiRequest) -> proto_ffi.FfiResponse: + kind = req.WhichOneof("message") + if kind in ("capture_audio_frame", "clear_audio_buffer"): + lock_held[kind] = source._lock.locked() + return real_request(req) + + monkeypatch.setattr(client, "request", request) + + async def _run() -> None: + await source.capture_frame(rtc.AudioFrame.create(48000, 1, 480)) + source.clear_queue() + await source.aclose() + + asyncio.run(_run()) + assert lock_held == {"capture_audio_frame": True, "clear_audio_buffer": True} + + +def test_audio_source_cross_thread_clear_queue_resets_queued_duration() -> None: + source = rtc.AudioSource(48000, 1, queue_size_ms=10000) + frame1 = rtc.AudioFrame.create(48000, 1, 48000) + frame2 = rtc.AudioFrame.create(48000, 1, 48000) + + async def _run() -> None: + await source.capture_frame(frame1) + assert source.queued_duration > 0.8 + + t = threading.Thread(target=source.clear_queue) + t.start() + t.join() + + # Queued duration should be reset immediately + assert source.queued_duration == 0.0 + + # Capture a new frame immediately after cross-thread clear + await source.capture_frame(frame2) + + # Queued duration should reflect only the new frame (~1.0s), not ~2.0s + assert 0.8 < source.queued_duration <= 1.05 + + await source.aclose() + + asyncio.run(_run())