|
| 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 | +"""Exercise the media streams' and AudioSource's FFI subscriptions without a native FFI.""" |
| 16 | + |
| 17 | +import asyncio |
| 18 | +from collections.abc import Iterator |
| 19 | +from types import SimpleNamespace |
| 20 | +from typing import Union |
| 21 | +from unittest.mock import patch |
| 22 | + |
| 23 | +import pytest |
| 24 | + |
| 25 | +from livekit import rtc |
| 26 | +from livekit.rtc._ffi_client import FfiClient, FfiQueue |
| 27 | +from livekit.rtc._proto import ffi_pb2 as proto_ffi |
| 28 | +from livekit.rtc._proto import track_pb2 as proto_track |
| 29 | + |
| 30 | + |
| 31 | +@pytest.fixture |
| 32 | +def queue(monkeypatch: pytest.MonkeyPatch) -> Iterator[FfiQueue[proto_ffi.FfiEvent]]: |
| 33 | + queue = FfiQueue[proto_ffi.FfiEvent]() |
| 34 | + handles = iter(range(100, 200)) |
| 35 | + |
| 36 | + def request(req: proto_ffi.FfiRequest) -> proto_ffi.FfiResponse: |
| 37 | + response = proto_ffi.FfiResponse() |
| 38 | + which = req.WhichOneof("message") |
| 39 | + if which == "new_audio_stream": |
| 40 | + response.new_audio_stream.stream.handle.id = next(handles) |
| 41 | + elif which == "new_video_stream": |
| 42 | + response.new_video_stream.stream.handle.id = next(handles) |
| 43 | + elif which == "new_audio_source": |
| 44 | + response.new_audio_source.source.handle.id = next(handles) |
| 45 | + elif which == "capture_audio_frame": |
| 46 | + response.capture_audio_frame.async_id = 1 |
| 47 | + else: |
| 48 | + raise AssertionError(f"unexpected FFI request: {which}") |
| 49 | + return response |
| 50 | + |
| 51 | + # A different PID prevents synthetic handles from being dropped natively. |
| 52 | + monkeypatch.setattr( |
| 53 | + FfiClient, "_instance", SimpleNamespace(queue=queue, request=request, _pid=-1) |
| 54 | + ) |
| 55 | + yield queue |
| 56 | + assert not queue._subscribers |
| 57 | + |
| 58 | + |
| 59 | +def _create_stream(event_type: str) -> Union[rtc.AudioStream, rtc.VideoStream]: |
| 60 | + track = rtc.Track(proto_track.OwnedTrack()) |
| 61 | + if event_type == "audio_stream_event": |
| 62 | + return rtc.AudioStream(track) |
| 63 | + return rtc.VideoStream(track) |
| 64 | + |
| 65 | + |
| 66 | +def _stream_event(event_type: str, stream_handle: int, *, eos: bool = False) -> proto_ffi.FfiEvent: |
| 67 | + event = proto_ffi.FfiEvent() |
| 68 | + stream_event = getattr(event, event_type) |
| 69 | + stream_event.stream_handle = stream_handle |
| 70 | + if eos: |
| 71 | + stream_event.eos.SetInParent() |
| 72 | + return event |
| 73 | + |
| 74 | + |
| 75 | +@pytest.mark.parametrize("event_type", ["audio_stream_event", "video_stream_event"]) |
| 76 | +async def test_stream_does_not_receive_other_streams_events( |
| 77 | + queue: FfiQueue[proto_ffi.FfiEvent], event_type: str |
| 78 | +) -> None: |
| 79 | + first = _create_stream(event_type) |
| 80 | + second = _create_stream(event_type) |
| 81 | + loop = asyncio.get_running_loop() |
| 82 | + event = _stream_event(event_type, second._ffi_handle.handle) |
| 83 | + |
| 84 | + try: |
| 85 | + with patch.object( |
| 86 | + loop, "call_soon_threadsafe", wraps=loop.call_soon_threadsafe |
| 87 | + ) as schedule: |
| 88 | + for _ in range(100): |
| 89 | + queue.put(event) |
| 90 | + |
| 91 | + # Only the stream the events belong to should incur an event-loop wakeup. |
| 92 | + assert schedule.call_count == 100 |
| 93 | + assert all(call.args[0] == second._ffi_queue.put_nowait for call in schedule.call_args_list) |
| 94 | + finally: |
| 95 | + for stream in (first, second): |
| 96 | + queue.put(_stream_event(event_type, stream._ffi_handle.handle, eos=True)) |
| 97 | + await asyncio.wait_for(stream.aclose(), 1) |
| 98 | + |
| 99 | + |
| 100 | +@pytest.mark.parametrize("event_type", ["audio_stream_event", "video_stream_event"]) |
| 101 | +async def test_stream_receives_events_sent_while_it_is_created( |
| 102 | + queue: FfiQueue[proto_ffi.FfiEvent], |
| 103 | + monkeypatch: pytest.MonkeyPatch, |
| 104 | + event_type: str, |
| 105 | +) -> None: |
| 106 | + instance = FfiClient._instance |
| 107 | + assert instance is not None |
| 108 | + create = instance.request |
| 109 | + |
| 110 | + def request(req: proto_ffi.FfiRequest) -> proto_ffi.FfiResponse: |
| 111 | + response = create(req) |
| 112 | + which = req.WhichOneof("message") |
| 113 | + assert which is not None |
| 114 | + # the native stream can end before the request that created it returns |
| 115 | + handle = getattr(response, which).stream.handle.id |
| 116 | + queue.put(_stream_event(event_type, handle, eos=True)) |
| 117 | + return response |
| 118 | + |
| 119 | + monkeypatch.setattr(instance, "request", request) |
| 120 | + stream = _create_stream(event_type) |
| 121 | + await asyncio.wait_for(stream.aclose(), 1) |
| 122 | + |
| 123 | + |
| 124 | +async def test_capture_frame_only_receives_its_own_callback( |
| 125 | + queue: FfiQueue[proto_ffi.FfiEvent], |
| 126 | +) -> None: |
| 127 | + source = rtc.AudioSource(48000, 1) |
| 128 | + capture = asyncio.create_task(source.capture_frame(rtc.AudioFrame.create(48000, 1, 480))) |
| 129 | + await asyncio.sleep(0) |
| 130 | + |
| 131 | + loop = asyncio.get_running_loop() |
| 132 | + room_event = proto_ffi.FfiEvent() |
| 133 | + room_event.room_event.SetInParent() |
| 134 | + other_capture = proto_ffi.FfiEvent() |
| 135 | + other_capture.capture_audio_frame.async_id = 2 |
| 136 | + try: |
| 137 | + with patch.object( |
| 138 | + loop, "call_soon_threadsafe", wraps=loop.call_soon_threadsafe |
| 139 | + ) as schedule: |
| 140 | + for event in (room_event, _stream_event("audio_stream_event", 1), other_capture): |
| 141 | + queue.put(event) |
| 142 | + |
| 143 | + # Neither other events nor another capture's callback should wake the capture up. |
| 144 | + assert schedule.call_count == 0 |
| 145 | + finally: |
| 146 | + callback = proto_ffi.FfiEvent() |
| 147 | + callback.capture_audio_frame.async_id = 1 |
| 148 | + queue.put(callback) |
| 149 | + await asyncio.wait_for(capture, 1) |
| 150 | + await source.aclose() |
| 151 | + |
| 152 | + |
| 153 | +async def test_capture_frame_receives_callback_sent_before_request_returns( |
| 154 | + queue: FfiQueue[proto_ffi.FfiEvent], monkeypatch: pytest.MonkeyPatch |
| 155 | +) -> None: |
| 156 | + instance = FfiClient._instance |
| 157 | + assert instance is not None |
| 158 | + create = instance.request |
| 159 | + |
| 160 | + def request(req: proto_ffi.FfiRequest) -> proto_ffi.FfiResponse: |
| 161 | + response = create(req) |
| 162 | + if req.WhichOneof("message") == "capture_audio_frame": |
| 163 | + # the native capture can complete before the request that started it returns |
| 164 | + callback = proto_ffi.FfiEvent() |
| 165 | + callback.capture_audio_frame.async_id = response.capture_audio_frame.async_id |
| 166 | + queue.put(callback) |
| 167 | + return response |
| 168 | + |
| 169 | + monkeypatch.setattr(instance, "request", request) |
| 170 | + source = rtc.AudioSource(48000, 1) |
| 171 | + await asyncio.wait_for(source.capture_frame(rtc.AudioFrame.create(48000, 1, 480)), 1) |
| 172 | + await source.aclose() |
0 commit comments