Skip to content

Commit c97bbf9

Browse files
committed
fix(rtc): handle cross-thread close, safe mock attributes, and isolate FFI lifecycle test
# Conflicts: # livekit-rtc/tests/test_ffi_handle_lifecycle.py
1 parent 8ae5792 commit c97bbf9

5 files changed

Lines changed: 52 additions & 31 deletions

File tree

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

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,17 @@ def __init__(
5353
"""
5454
self._sample_rate = sample_rate
5555
self._num_channels = num_channels
56-
self._loop = loop or asyncio.get_event_loop()
56+
57+
if loop is not None:
58+
self._loop = loop
59+
else:
60+
try:
61+
self._loop = asyncio.get_running_loop()
62+
except RuntimeError:
63+
try:
64+
self._loop = asyncio.get_event_loop()
65+
except RuntimeError:
66+
self._loop = asyncio.new_event_loop()
5767

5868
req = proto_ffi.FfiRequest()
5969
req.new_audio_source.type = proto_audio_frame.AudioSourceType.AUDIO_SOURCE_NATIVE
@@ -116,7 +126,7 @@ async def capture_frame(self, frame: AudioFrame) -> None:
116126
Exception: If there is an error during frame capture.
117127
"""
118128

119-
if frame.samples_per_channel == 0 or self._ffi_handle.disposed:
129+
if frame.samples_per_channel == 0 or getattr(self._ffi_handle, "disposed", False):
120130
return
121131

122132
now = time.monotonic()
@@ -192,7 +202,18 @@ def close(self) -> None:
192202
193203
This method cleans up resources associated with the audio source.
194204
"""
195-
self._release_waiter()
205+
try:
206+
running_loop = asyncio.get_running_loop()
207+
except RuntimeError:
208+
running_loop = None
209+
210+
if running_loop is self._loop:
211+
self._release_waiter()
212+
elif self._loop.is_running():
213+
self._loop.call_soon_threadsafe(self._release_waiter)
214+
else:
215+
self._release_waiter()
216+
196217
self._ffi_handle.dispose()
197218

198219
async def aclose(self) -> None:
@@ -201,4 +222,5 @@ async def aclose(self) -> None:
201222
This method cleans up resources associated with the audio source.
202223
"""
203224
self._release_waiter()
204-
await asyncio.to_thread(self._ffi_handle.dispose)
225+
if not getattr(self._ffi_handle, "disposed", False):
226+
await asyncio.to_thread(self._ffi_handle.dispose)

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

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -324,24 +324,15 @@ 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-
336327
async def aclose(self) -> None:
337328
"""Asynchronously close the audio stream.
338329
339330
This method cleans up resources associated with the audio stream and waits for
340-
any pending operations to complete without blocking the event loop.
331+
any pending operations to complete.
341332
"""
342333
if self._track is not None:
343334
self._track._unregister_audio_stream(self)
344-
await asyncio.to_thread(self._ffi_handle.dispose)
335+
self._ffi_handle.dispose()
345336
await self._task
346337
if self._processor is not None and self._processor_auto_close:
347338
self._processor._close()

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ def capture_frame(
6363
metadata: proto_video.FrameMetadata | None = None,
6464
) -> None:
6565
"""Capture a frame, optionally attaching frame metadata."""
66-
if self._ffi_handle.disposed:
66+
if getattr(self._ffi_handle, "disposed", False):
6767
return
6868

6969
req = proto_ffi.FfiRequest()
@@ -87,4 +87,5 @@ async def aclose(self) -> None:
8787
8888
This method cleans up resources associated with the video source.
8989
"""
90-
await asyncio.to_thread(self._ffi_handle.dispose)
90+
if not getattr(self._ffi_handle, "disposed", False):
91+
await asyncio.to_thread(self._ffi_handle.dispose)

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

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

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

173-
def close(self) -> None:
174-
"""Synchronously close the video stream and release its resources."""
175-
self._ffi_handle.dispose()
176-
FfiClient.instance.queue.unsubscribe(self._ffi_queue)
177-
178173
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)
174+
self._ffi_handle.dispose()
181175
await self._task
182176

183177
def _is_event(self, e: proto_ffi.FfiEvent) -> bool:

‎livekit-rtc/tests/test_source_stream_close.py‎

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414

1515
from __future__ import annotations
1616

17+
import asyncio
18+
import threading
1719

1820
import pytest
1921

@@ -24,22 +26,22 @@
2426
async def test_audio_source_aclose_releases_waiter_and_cancels_timer() -> None:
2527
source = rtc.AudioSource(48000, 1)
2628
frame = rtc.AudioFrame.create(48000, 1, 48000)
27-
await source.capture_frame(frame)
29+
await asyncio.wait_for(source.capture_frame(frame), timeout=5.0)
2830

2931
assert source._join_fut is not None
3032
assert source._join_handle is not None
3133

32-
await source.aclose()
34+
await asyncio.wait_for(source.aclose(), timeout=5.0)
3335

3436
assert source._ffi_handle.disposed
3537
assert source._join_fut is None
3638
assert source._join_handle is None
3739

3840
# After aclose, wait_for_playout should return immediately without hanging
39-
await source.wait_for_playout()
41+
await asyncio.wait_for(source.wait_for_playout(), timeout=2.0)
4042

4143
# Repeated calls are idempotent
42-
await source.aclose()
44+
await asyncio.wait_for(source.aclose(), timeout=2.0)
4345

4446

4547
def test_audio_source_sync_close() -> None:
@@ -53,14 +55,25 @@ def test_audio_source_sync_close() -> None:
5355
source.close()
5456

5557

58+
def test_audio_source_cross_thread_close() -> None:
59+
source = rtc.AudioSource(48000, 1)
60+
assert not source._ffi_handle.disposed
61+
62+
t = threading.Thread(target=source.close)
63+
t.start()
64+
t.join()
65+
66+
assert source._ffi_handle.disposed
67+
68+
5669
@pytest.mark.asyncio
5770
async def test_audio_source_capture_after_close_is_noop() -> None:
5871
source = rtc.AudioSource(48000, 1)
5972
source.close()
6073

6174
frame = rtc.AudioFrame.create(48000, 1, 480)
6275
# Should safely return without error
63-
await source.capture_frame(frame)
76+
await asyncio.wait_for(source.capture_frame(frame), timeout=2.0)
6477

6578

6679
def test_video_source_sync_close() -> None:
@@ -79,7 +92,7 @@ async def test_video_source_aclose_and_capture_after_close() -> None:
7992
source = rtc.VideoSource(640, 480)
8093
assert not source._ffi_handle.disposed
8194

82-
await source.aclose()
95+
await asyncio.wait_for(source.aclose(), timeout=5.0)
8396
assert source._ffi_handle.disposed
8497

8598
# Capture after close is safely ignored
@@ -92,4 +105,4 @@ async def test_video_source_aclose_and_capture_after_close() -> None:
92105
source.capture_frame(frame)
93106

94107
# Repeated aclose is idempotent
95-
await source.aclose()
108+
await asyncio.wait_for(source.aclose(), timeout=2.0)

0 commit comments

Comments
 (0)