Skip to content

Commit 8ae5792

Browse files
committed
fix(rtc): offload FFI handle disposal to thread in aclose and add sync close (#832)
- In AudioSource, AudioStream, VideoSource, and VideoStream, add a synchronous close() method. - In AudioSource, VideoSource, AudioStream, and VideoStream, run self._ffi_handle.dispose() via asyncio.to_thread in aclose() so the synchronous native drop call does not block the asyncio event loop. - In AudioSource, cancel any pending _join_handle timer and resolve _join_fut when close() or aclose() is called so waiters on wait_for_playout are immediately unblocked. - In VideoSource.capture_frame, safely ignore frames if the handle is already disposed. Fixes #832
1 parent d8d4010 commit 8ae5792

5 files changed

Lines changed: 145 additions & 6 deletions

File tree

‎livekit-rtc/livekit/rtc/audio_source.py‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,10 @@ async def wait_for_playout(self) -> None:
173173
await asyncio.shield(self._join_fut)
174174

175175
def _release_waiter(self) -> None:
176+
if self._join_handle is not None:
177+
self._join_handle.cancel()
178+
self._join_handle = None
179+
176180
if self._join_fut is None:
177181
return # could be None when clear_queue is called
178182

@@ -183,9 +187,18 @@ def _release_waiter(self) -> None:
183187
self._q_size = 0.0
184188
self._join_fut = None
185189

186-
async def aclose(self) -> None:
187-
"""Close the audio source
190+
def close(self) -> None:
191+
"""Close the audio source.
188192
189193
This method cleans up resources associated with the audio source.
190194
"""
195+
self._release_waiter()
191196
self._ffi_handle.dispose()
197+
198+
async def aclose(self) -> None:
199+
"""Close the audio source without blocking the event loop.
200+
201+
This method cleans up resources associated with the audio source.
202+
"""
203+
self._release_waiter()
204+
await asyncio.to_thread(self._ffi_handle.dispose)

‎livekit-rtc/livekit/rtc/audio_stream.py‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -324,15 +324,24 @@ async def _run(self) -> None:
324324

325325
FfiClient.instance.queue.unsubscribe(self._ffi_queue)
326326

327+
def close(self) -> None:
328+
"""Synchronously close the audio stream and release its resources."""
329+
if self._track is not None:
330+
self._track._unregister_audio_stream(self)
331+
self._ffi_handle.dispose()
332+
FfiClient.instance.queue.unsubscribe(self._ffi_queue)
333+
if self._processor is not None and self._processor_auto_close:
334+
self._processor._close()
335+
327336
async def aclose(self) -> None:
328337
"""Asynchronously close the audio stream.
329338
330339
This method cleans up resources associated with the audio stream and waits for
331-
any pending operations to complete.
340+
any pending operations to complete without blocking the event loop.
332341
"""
333342
if self._track is not None:
334343
self._track._unregister_audio_stream(self)
335-
self._ffi_handle.dispose()
344+
await asyncio.to_thread(self._ffi_handle.dispose)
336345
await self._task
337346
if self._processor is not None and self._processor_auto_close:
338347
self._processor._close()

‎livekit-rtc/livekit/rtc/video_source.py‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414

1515
from __future__ import annotations
1616

17+
import asyncio
18+
1719
from ._ffi_client import FfiHandle, FfiClient
1820
from ._proto import ffi_pb2 as proto_ffi
1921
from ._proto import video_frame_pb2 as proto_video
@@ -61,6 +63,9 @@ def capture_frame(
6163
metadata: proto_video.FrameMetadata | None = None,
6264
) -> None:
6365
"""Capture a frame, optionally attaching frame metadata."""
66+
if self._ffi_handle.disposed:
67+
return
68+
6469
req = proto_ffi.FfiRequest()
6570
req.capture_video_frame.source_handle = self._ffi_handle.handle
6671
req.capture_video_frame.buffer.CopyFrom(frame._proto_info())
@@ -70,5 +75,16 @@ def capture_frame(
7075
req.capture_video_frame.metadata.CopyFrom(metadata)
7176
FfiClient.instance.request(req)
7277

73-
async def aclose(self) -> None:
78+
def close(self) -> None:
79+
"""Close the video source.
80+
81+
This method cleans up resources associated with the video source.
82+
"""
7483
self._ffi_handle.dispose()
84+
85+
async def aclose(self) -> None:
86+
"""Close the video source without blocking the event loop.
87+
88+
This method cleans up resources associated with the video source.
89+
"""
90+
await asyncio.to_thread(self._ffi_handle.dispose)

‎livekit-rtc/livekit/rtc/video_stream.py‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -170,8 +170,14 @@ async def _run(self) -> None:
170170

171171
FfiClient.instance.queue.unsubscribe(self._ffi_queue)
172172

173-
async def aclose(self) -> None:
173+
def close(self) -> None:
174+
"""Synchronously close the video stream and release its resources."""
174175
self._ffi_handle.dispose()
176+
FfiClient.instance.queue.unsubscribe(self._ffi_queue)
177+
178+
async def aclose(self) -> None:
179+
"""Asynchronously close the video stream without blocking the event loop."""
180+
await asyncio.to_thread(self._ffi_handle.dispose)
175181
await self._task
176182

177183
def _is_event(self, e: proto_ffi.FfiEvent) -> bool:
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
# Copyright 2026 LiveKit, Inc.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
from __future__ import annotations
16+
17+
18+
import pytest
19+
20+
from livekit import rtc
21+
22+
23+
@pytest.mark.asyncio
24+
async def test_audio_source_aclose_releases_waiter_and_cancels_timer() -> None:
25+
source = rtc.AudioSource(48000, 1)
26+
frame = rtc.AudioFrame.create(48000, 1, 48000)
27+
await source.capture_frame(frame)
28+
29+
assert source._join_fut is not None
30+
assert source._join_handle is not None
31+
32+
await source.aclose()
33+
34+
assert source._ffi_handle.disposed
35+
assert source._join_fut is None
36+
assert source._join_handle is None
37+
38+
# After aclose, wait_for_playout should return immediately without hanging
39+
await source.wait_for_playout()
40+
41+
# Repeated calls are idempotent
42+
await source.aclose()
43+
44+
45+
def test_audio_source_sync_close() -> None:
46+
source = rtc.AudioSource(48000, 1)
47+
assert not source._ffi_handle.disposed
48+
49+
source.close()
50+
assert source._ffi_handle.disposed
51+
52+
# Repeated close is idempotent
53+
source.close()
54+
55+
56+
@pytest.mark.asyncio
57+
async def test_audio_source_capture_after_close_is_noop() -> None:
58+
source = rtc.AudioSource(48000, 1)
59+
source.close()
60+
61+
frame = rtc.AudioFrame.create(48000, 1, 480)
62+
# Should safely return without error
63+
await source.capture_frame(frame)
64+
65+
66+
def test_video_source_sync_close() -> None:
67+
source = rtc.VideoSource(640, 480)
68+
assert not source._ffi_handle.disposed
69+
70+
source.close()
71+
assert source._ffi_handle.disposed
72+
73+
# Repeated close is idempotent
74+
source.close()
75+
76+
77+
@pytest.mark.asyncio
78+
async def test_video_source_aclose_and_capture_after_close() -> None:
79+
source = rtc.VideoSource(640, 480)
80+
assert not source._ffi_handle.disposed
81+
82+
await source.aclose()
83+
assert source._ffi_handle.disposed
84+
85+
# Capture after close is safely ignored
86+
frame = rtc.VideoFrame(
87+
640,
88+
480,
89+
rtc.VideoBufferType.RGBA,
90+
b"\x00" * (640 * 480 * 4),
91+
)
92+
source.capture_frame(frame)
93+
94+
# Repeated aclose is idempotent
95+
await source.aclose()

0 commit comments

Comments
 (0)