Skip to content

Commit 2ceac5a

Browse files
committed
fix(rtc): signal eos on VideoStream queue and guard stream finalizers
In VideoStream._run(), push None to self._queue when receiving an eos event, matching AudioStream. Without this terminal sentinel, consumers awaiting __anext__() remain suspended indefinitely on stream completion or aclose(). Wrap _run() in try/finally to guarantee unsubscribing from the FFI event queue even on cancellation or error. Remove duplicate self._format assignment in VideoStream.__init__. Guard __del__ in VideoStream and AudioStream with hasattr(self, '_ffi_queue') to prevent AttributeError during garbage collection of partially initialized instances.
1 parent 462e103 commit 2ceac5a

3 files changed

Lines changed: 93 additions & 28 deletions

File tree

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,8 @@ def from_track(
248248
)
249249

250250
def __del__(self) -> None:
251-
FfiClient.instance.queue.unsubscribe(self._ffi_queue)
251+
if hasattr(self, "_ffi_queue"):
252+
FfiClient.instance.queue.unsubscribe(self._ffi_queue)
252253

253254
def _create_owned_stream(self) -> Any:
254255
assert self._track is not None

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

Lines changed: 29 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,6 @@ def __init__(
5858
self._track: Track | None = track
5959
self._format = format
6060
self._capacity = capacity
61-
self._format = format
6261
stream: Any = None
6362
if "participant" in kwargs:
6463
stream = self._create_owned_stream_from_participant(
@@ -109,7 +108,8 @@ def from_track(
109108
)
110109

111110
def __del__(self) -> None:
112-
FfiClient.instance.queue.unsubscribe(self._ffi_queue)
111+
if hasattr(self, "_ffi_queue"):
112+
FfiClient.instance.queue.unsubscribe(self._ffi_queue)
113113

114114
def _create_owned_stream(self) -> Any:
115115
assert self._track is not None
@@ -138,31 +138,33 @@ def _create_owned_stream_from_participant(
138138
return resp.video_stream_from_participant.stream
139139

140140
async def _run(self) -> None:
141-
while True:
142-
event = await self._ffi_queue.wait_for(self._is_event)
143-
video_event = event.video_stream_event
144-
145-
if video_event.HasField("frame_received"):
146-
frame_received = video_event.frame_received
147-
owned_buffer_info = frame_received.buffer
148-
frame = VideoFrame._from_owned_info(owned_buffer_info)
149-
metadata: proto_video_frame.FrameMetadata | None = None
150-
if frame_received.HasField("metadata"):
151-
metadata = proto_video_frame.FrameMetadata()
152-
metadata.CopyFrom(frame_received.metadata)
153-
154-
event = VideoFrameEvent(
155-
frame=frame,
156-
timestamp_us=frame_received.timestamp_us,
157-
rotation=frame_received.rotation,
158-
metadata=metadata,
159-
)
160-
161-
self._queue.put(event)
162-
elif video_event.HasField("eos"):
163-
break
164-
165-
FfiClient.instance.queue.unsubscribe(self._ffi_queue)
141+
try:
142+
while True:
143+
event = await self._ffi_queue.wait_for(self._is_event)
144+
video_event = event.video_stream_event
145+
146+
if video_event.HasField("frame_received"):
147+
frame_received = video_event.frame_received
148+
owned_buffer_info = frame_received.buffer
149+
frame = VideoFrame._from_owned_info(owned_buffer_info)
150+
metadata: proto_video_frame.FrameMetadata | None = None
151+
if frame_received.HasField("metadata"):
152+
metadata = proto_video_frame.FrameMetadata()
153+
metadata.CopyFrom(frame_received.metadata)
154+
155+
event = VideoFrameEvent(
156+
frame=frame,
157+
timestamp_us=frame_received.timestamp_us,
158+
rotation=frame_received.rotation,
159+
metadata=metadata,
160+
)
161+
162+
self._queue.put(event)
163+
elif video_event.HasField("eos"):
164+
self._queue.put(None)
165+
break
166+
finally:
167+
FfiClient.instance.queue.unsubscribe(self._ffi_queue)
166168

167169
async def aclose(self) -> None:
168170
self._ffi_handle.dispose()
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
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+
import asyncio
18+
from unittest.mock import MagicMock, patch
19+
20+
from livekit import rtc
21+
from livekit.rtc._ffi_client import FfiClient
22+
from livekit.rtc._proto import ffi_pb2 as proto_ffi
23+
from livekit.rtc._proto import video_frame_pb2 as proto_video_frame
24+
25+
26+
def test_video_stream_del_without_ffi_queue() -> None:
27+
# A partially constructed VideoStream collected during error in __init__
28+
# must not raise AttributeError when __del__ is called.
29+
stream = rtc.VideoStream.__new__(rtc.VideoStream)
30+
stream.__del__()
31+
32+
33+
async def test_video_stream_eos_terminates_iteration() -> None:
34+
track = MagicMock(spec=rtc.Track)
35+
stream_info = MagicMock()
36+
stream_info.handle.id = 12345
37+
stream_info.info = MagicMock()
38+
39+
with patch.object(rtc.VideoStream, "_create_owned_stream", return_value=stream_info):
40+
video_stream = rtc.VideoStream(track)
41+
# Mark mock handle disposed so GC does not attempt to drop non-existent handle
42+
video_stream._ffi_handle._disposed = True
43+
44+
async def consume() -> list[rtc.VideoFrameEvent]:
45+
frames: list[rtc.VideoFrameEvent] = []
46+
async for frame in video_stream:
47+
frames.append(frame)
48+
return frames
49+
50+
consume_task = asyncio.create_task(consume())
51+
52+
# Send EOS event for this stream handle
53+
event = proto_ffi.FfiEvent()
54+
event.video_stream_event.stream_handle = 12345
55+
event.video_stream_event.eos.CopyFrom(proto_video_frame.VideoStreamEOS())
56+
FfiClient.instance.queue.put(event)
57+
58+
# Iteration must complete cleanly without hanging
59+
frames = await asyncio.wait_for(consume_task, timeout=2.0)
60+
assert frames == []
61+
62+
await video_stream.aclose()

0 commit comments

Comments
 (0)