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
5 changes: 5 additions & 0 deletions .changeset/video-stream-eos.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"livekit-rtc": patch
---

Fix `async for` over a `VideoStream` hanging after the track ends: the stream now signals end-of-stream to its consumer and still delivers the frames buffered before it ended, including the last one when the queue is full, and `__del__` no longer raises if the stream was never fully initialized.
8 changes: 6 additions & 2 deletions livekit-rtc/livekit/rtc/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,9 @@ def __init__(self, capacity: int = 0) -> None:
self._event = asyncio.Event()

def put(self, item: T) -> None:
if self._capacity > 0 and len(self._queue) == self._capacity:
self._queue.popleft()
if item is not None and self._capacity > 0:
while len(self._queue) >= self._capacity:
self._queue.popleft()
self._queue.append(item)
self._event.set()

Expand All @@ -93,6 +94,9 @@ async def get(self) -> T:
self._event.clear()
return self._queue.popleft()

def empty(self) -> bool:
return not self._queue


class Queue(asyncio.Queue[T]):
"""asyncio.Queue with utility functions."""
Expand Down
61 changes: 33 additions & 28 deletions livekit-rtc/livekit/rtc/video_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ def __init__(
self._track: Track | None = track
self._format = format
self._capacity = capacity
self._format = format
stream: Any = None
if "participant" in kwargs:
stream = self._create_owned_stream_from_participant(
Expand Down Expand Up @@ -115,7 +114,10 @@ def from_track(
)

def __del__(self) -> None:
FfiClient.instance.queue.unsubscribe(self._ffi_queue)
# _ffi_queue is unset if __init__ raised early or the instance was built via __new__
ffi_queue = getattr(self, "_ffi_queue", None)
if ffi_queue is not None:
FfiClient.instance.queue.unsubscribe(ffi_queue)

def _create_owned_stream(self) -> Any:
assert self._track is not None
Expand Down Expand Up @@ -144,31 +146,33 @@ def _create_owned_stream_from_participant(
return resp.video_stream_from_participant.stream

async def _run(self) -> None:
while True:
event = await self._ffi_queue.wait_for(self._is_event)
video_event = event.video_stream_event

if video_event.HasField("frame_received"):
frame_received = video_event.frame_received
owned_buffer_info = frame_received.buffer
frame = VideoFrame._from_owned_info(owned_buffer_info)
metadata: proto_video_frame.FrameMetadata | None = None
if frame_received.HasField("metadata"):
metadata = proto_video_frame.FrameMetadata()
metadata.CopyFrom(frame_received.metadata)

event = VideoFrameEvent(
frame=frame,
timestamp_us=frame_received.timestamp_us,
rotation=frame_received.rotation,
metadata=metadata,
)

self._queue.put(event)
elif video_event.HasField("eos"):
break

FfiClient.instance.queue.unsubscribe(self._ffi_queue)
try:
while True:
event = await self._ffi_queue.wait_for(self._is_event)
video_event = event.video_stream_event

if video_event.HasField("frame_received"):
frame_received = video_event.frame_received
owned_buffer_info = frame_received.buffer
frame = VideoFrame._from_owned_info(owned_buffer_info)
metadata: proto_video_frame.FrameMetadata | None = None
if frame_received.HasField("metadata"):
metadata = proto_video_frame.FrameMetadata()
metadata.CopyFrom(frame_received.metadata)

event = VideoFrameEvent(
frame=frame,
timestamp_us=frame_received.timestamp_us,
rotation=frame_received.rotation,
metadata=metadata,
)

self._queue.put(event)
elif video_event.HasField("eos"):
self._queue.put(None)
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
break
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
finally:
FfiClient.instance.queue.unsubscribe(self._ffi_queue)

async def aclose(self) -> None:
self._ffi_handle.dispose()
Expand All @@ -181,7 +185,8 @@ def __aiter__(self) -> AsyncIterator[VideoFrameEvent]:
return self

async def __anext__(self) -> VideoFrameEvent:
if self._task.done():
# Frames buffered before the stream ended are still delivered.
if self._task.done() and self._queue.empty():
raise StopAsyncIteration

item = await self._queue.get()
Expand Down
9 changes: 7 additions & 2 deletions livekit-rtc/tests/test_ffi_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
"""


Expand Down
144 changes: 144 additions & 0 deletions livekit-rtc/tests/test_video_stream.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
# 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
from unittest.mock import MagicMock, patch

import pytest

from livekit import rtc
from livekit.rtc._ffi_client import FfiClient
from livekit.rtc._proto import ffi_pb2 as proto_ffi
from livekit.rtc._proto import video_frame_pb2 as proto_video_frame


def test_video_stream_del_without_ffi_queue() -> None:
# A partially constructed VideoStream collected during error in __init__
# must not raise AttributeError when __del__ is called.
stream = rtc.VideoStream.__new__(rtc.VideoStream)
stream.__del__()


async def test_video_stream_eos_terminates_iteration() -> None:
track = MagicMock(spec=rtc.Track)
stream_info = MagicMock()
stream_info.handle.id = 12345
stream_info.info = MagicMock()

with patch.object(rtc.VideoStream, "_create_owned_stream", return_value=stream_info):
video_stream = rtc.VideoStream(track)
# Mark mock handle disposed so GC does not attempt to drop non-existent handle
video_stream._ffi_handle._disposed = True

async def consume() -> list[rtc.VideoFrameEvent]:
frames: list[rtc.VideoFrameEvent] = []
async for frame in video_stream:
frames.append(frame)
return frames

consume_task = asyncio.create_task(consume())

# Send EOS event for this stream handle
event = proto_ffi.FfiEvent()
event.video_stream_event.stream_handle = 12345
event.video_stream_event.eos.CopyFrom(proto_video_frame.VideoStreamEOS())
FfiClient.instance.queue.put(event)

# Iteration must complete cleanly without hanging
frames = await asyncio.wait_for(consume_task, timeout=2.0)
assert frames == []

await video_stream.aclose()


async def test_video_stream_eos_does_not_evict_last_frame_at_capacity_one() -> None:
track = MagicMock(spec=rtc.Track)
stream_info = MagicMock()
stream_info.handle.id = 54321
stream_info.info = MagicMock()

with patch.object(rtc.VideoStream, "_create_owned_stream", return_value=stream_info):
video_stream = rtc.VideoStream(track, capacity=1)
video_stream._ffi_handle._disposed = True

mock_frame = MagicMock(spec=rtc.VideoFrame)
with patch.object(rtc.VideoFrame, "_from_owned_info", return_value=mock_frame):
# Enqueue frame and EOS before consumer reads
frame_event = proto_ffi.FfiEvent()
frame_event.video_stream_event.stream_handle = 54321
frame_event.video_stream_event.frame_received.timestamp_us = 1000
frame_event.video_stream_event.frame_received.rotation = (
proto_video_frame.VideoRotation.VIDEO_ROTATION_0
)
FfiClient.instance.queue.put(frame_event)

eos_event = proto_ffi.FfiEvent()
eos_event.video_stream_event.stream_handle = 54321
eos_event.video_stream_event.eos.CopyFrom(proto_video_frame.VideoStreamEOS())
FfiClient.instance.queue.put(eos_event)

# Consume stream
frames: list[rtc.VideoFrameEvent] = []
async for frame in video_stream:
frames.append(frame)

# The final frame must not be evicted by EOS sentinel
assert len(frames) == 1
assert frames[0].frame is mock_frame
assert frames[0].timestamp_us == 1000

await video_stream.aclose()


async def test_video_stream_delivers_buffered_frame_after_producer_finished() -> None:
# The consumer asks for the next frame only after the track has ended: the frame
# still buffered must be delivered before iteration stops.
track = MagicMock(spec=rtc.Track)
stream_info = MagicMock()
stream_info.handle.id = 67890
stream_info.info = MagicMock()

with patch.object(rtc.VideoStream, "_create_owned_stream", return_value=stream_info):
video_stream = rtc.VideoStream(track, capacity=1)
video_stream._ffi_handle._disposed = True

mock_frame = MagicMock(spec=rtc.VideoFrame)
with patch.object(rtc.VideoFrame, "_from_owned_info", return_value=mock_frame):
frame_event = proto_ffi.FfiEvent()
frame_event.video_stream_event.stream_handle = 67890
frame_event.video_stream_event.frame_received.timestamp_us = 2000
frame_event.video_stream_event.frame_received.rotation = (
proto_video_frame.VideoRotation.VIDEO_ROTATION_0
)
FfiClient.instance.queue.put(frame_event)

eos_event = proto_ffi.FfiEvent()
eos_event.video_stream_event.stream_handle = 67890
eos_event.video_stream_event.eos.CopyFrom(proto_video_frame.VideoStreamEOS())
FfiClient.instance.queue.put(eos_event)

# Let the producer handle both events and finish before reading
await asyncio.wait_for(asyncio.shield(video_stream._task), timeout=2.0)

frames = [frame async for frame in video_stream]
assert [f.timestamp_us for f in frames] == [2000]
assert frames[0].frame is mock_frame

# Once drained, further calls stop at once instead of waiting
with pytest.raises(StopAsyncIteration):
await asyncio.wait_for(video_stream.__anext__(), timeout=1.0)

await video_stream.aclose()
Loading