From 585680069cb5de9c41d5daa1c0dedf87d4d48822 Mon Sep 17 00:00:00 2001 From: Raphael Hehl <7577984+RaHehl@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:00:49 +0100 Subject: [PATCH 1/2] Resolve the ffmpeg input again for each restart A restart of ffmpeg reused the first command line, so a camera URL with an expiring token never recovered. Restarts now resolve the input again. A failing or hanging resolver counts as a failed start, and stop() cancels it. --- pyhap/media/ffmpeg.py | 74 ++++++- tests/test_media_ffmpeg_provider.py | 326 +++++++++++++++++++++++++++- 2 files changed, 387 insertions(+), 13 deletions(-) diff --git a/pyhap/media/ffmpeg.py b/pyhap/media/ffmpeg.py index c122957f..87523e0d 100644 --- a/pyhap/media/ffmpeg.py +++ b/pyhap/media/ffmpeg.py @@ -96,7 +96,9 @@ class FFmpegSourceProvider: (also by name, e.g. ``"medium"``), to ffmpeg input arguments or an :class:`FFmpegInput`; an identifier wins over a quality. It can instead be an async callable that resolves a tier to the same, or None when - nothing fits. Tiers with the same input share one ffmpeg. + nothing fits. Tiers with the same input share one ffmpeg. A restart of + ffmpeg, after an exit or for a keyframe request, calls it again: the + input may have expired meanwhile, e.g. a URL with a token. Video ``video_map`` is copied with ``dump_extra`` so every IRAP picture carries its parameter sets (an Annex B input such as RTSP; MP4 needs @@ -113,7 +115,9 @@ class FFmpegSourceProvider: ``restart_delay``), and for a keyframe request only when no IRAP picture came for twice the GOP and ffmpeg runs at least that long: a copied stream gets its next IRAP picture with the next GOP anyway. The GOP is - the one the source measures, until then ``gop``. + the one the source measures, until then ``gop``. A restart whose input + cannot be resolved counts as a failed start and is tried again after the + backoff, which keyframe requests while no ffmpeg runs do not cut short. """ def __init__( @@ -255,15 +259,23 @@ async def lease_channel( audio = audio_tier or hksv3.DEFAULT_AUDIO_TIER command = partial( self.command, - found, audio_bitrate=audio.target_bitrate, packet_time=audio.packet_time, ) gop = found.gop or self.gop + async def restart_command(rtp_input: tuple[str, int, int]) -> list[str]: + # The input found above may have expired by now. + return command(await self.input_for(video_tier), rtp_input) + def make_pull() -> FFmpegPull: pull = FFmpegPull( - command, name, gop, self.restart_delay, on_error=self._pull_error + partial(command, found), + name, + gop, + self.restart_delay, + on_error=self._pull_error, + restart_command=restart_command, ) self._pulls[name] = pull return pull @@ -319,11 +331,16 @@ def __init__( gop: float, restart_delay: float, on_error: Callable[[str, str], None] | None = None, + restart_command: Callable[[tuple[str, int, int]], Awaitable[list[str]]] + | None = None, ) -> None: """Configure the pull; :meth:`start` runs ffmpeg. ``gop`` is the expected IRAP interval until the source measured one. ``on_error(name, message)`` hears each unexpected exit or failed start. + ``restart_command(rtp_input)``, if given, makes the command of each + restart instead of ``command``, e.g. on an input resolved again; + :meth:`stop` cancels it. """ self.name = name self.gop = gop @@ -333,9 +350,12 @@ def __init__( self.last_error: str | None = None self._failures = 0 self._command = command + self._restart_command = restart_command + self._rtp_input: tuple[str, int, int] = ("", 0, 0) self._argv: list[str] = [] self._process: asyncio.subprocess.Process | None = None self._watcher: asyncio.Task[None] | None = None + self._resolving: asyncio.Future[list[str]] | None = None self._started = 0.0 self._running = False self._restart_now = asyncio.Event() @@ -348,6 +368,7 @@ def pid(self) -> int | None: async def start(self, rtp_input: tuple[str, int, int]) -> None: """Run ffmpeg and keep it running until :meth:`stop`.""" + self._rtp_input = rtp_input self._argv = self._command(rtp_input) self._running = True try: @@ -355,14 +376,25 @@ async def start(self, rtp_input: tuple[str, int, int]) -> None: except BaseException as err: self._running = False if isinstance(err, OSError): - message = f"could not start: {err}" + message = _start_error(err) logger.warning("ffmpeg for %s %s", self.name, message) self._report(message) raise self._watcher = asyncio.ensure_future(self._watch()) - async def _spawn(self) -> None: + async def _spawn(self, restart: bool = False) -> None: self._restart_now.clear() + if restart and self._restart_command is not None: + # In a task, so that stop() can cancel it. + self._resolving = asyncio.ensure_future( + self._restart_command(self._rtp_input) + ) + try: + self._argv = await self._resolving + finally: + self._resolving = None + if not self._running: + return self._process = await asyncio.create_subprocess_exec( *self._argv, stdin=asyncio.subprocess.DEVNULL, @@ -395,11 +427,20 @@ async def _watch(self) -> None: ) while self._running: try: - await self._spawn() - except OSError as err: + await self._spawn(restart=True) + except (Exception, asyncio.CancelledError) as err: + # A CancelledError of the command's own is a failed start. + task = asyncio.current_task() + if task is not None and task.cancelling(): + raise + if not self._running: + # stop() cancelled the command. + return # No new process: back off further before the next try. - await self._back_off(f"could not start: {err}") + await self._back_off(_start_error(err)) continue + if not self._running: + return self.restarts += 1 break @@ -431,8 +472,12 @@ def keyframe_requested(self, age: float | None, gop: float | None) -> None: ``gop`` is the IRAP interval the source measured, if it did. """ limit = 2 * (gop or self.gop) + process = self._process if not self._running or self._restart_now.is_set(): return + if process is None or process.returncode is not None: + # A restart is pending already; its backoff decides when. + return if age is not None and age <= limit: return running = time.monotonic() - self._started @@ -445,13 +490,15 @@ def keyframe_requested(self, age: float | None, gop: float | None) -> None: "-" if age is None else f"{age:.1f}", ) self._restart_now.set() - if self._process is not None and self._process.returncode is None: - self._process.terminate() + process.terminate() async def stop(self) -> None: """Stop ffmpeg, killing it if it does not exit in time.""" self._running = False self._restart_now.set() + if self._resolving is not None: + # The command of a restart may hang, e.g. on an unreachable camera. + self._resolving.cancel() await self._terminate() if self._watcher is not None: await self._watcher @@ -481,6 +528,11 @@ async def _terminate(self) -> None: await process.wait() +def _start_error(err: BaseException) -> str: + """Why ffmpeg was not started; the error of a resolver may hold a URL.""" + return f"could not start: {redact_urls(str(err)) or type(err).__name__}" + + async def _log_output(name: str, process: asyncio.subprocess.Process) -> str | None: """Log ffmpeg's output line by line, URLs redacted; progress ends with CR. diff --git a/tests/test_media_ffmpeg_provider.py b/tests/test_media_ffmpeg_provider.py index c11a85c3..8e62a7b7 100644 --- a/tests/test_media_ffmpeg_provider.py +++ b/tests/test_media_ffmpeg_provider.py @@ -3,7 +3,8 @@ from __future__ import annotations import asyncio -from collections.abc import Callable +from collections.abc import Awaitable, Callable, Mapping, Sequence +import contextlib import logging import os from pathlib import Path @@ -20,8 +21,10 @@ FFmpegInput, FFmpegPull, FFmpegSourceProvider, + InputResolver, redact_urls, ) +from pyhap.media.pool import ChannelLease from pyhap.media.webrtc_delegate import WebRTCMediaDelegate from .media_fakes import ( @@ -321,6 +324,266 @@ async def test_provider_diagnostics() -> None: await lease.release() +class TokenResolver: + """An input resolver whose input holds the number of the call as a token. + + ``failing`` maps the number of a call to the resolver answering it + instead. + """ + + def __init__(self, failing: Mapping[int, InputResolver] | None = None) -> None: + """Start without a call.""" + self.failing = failing or {} + self.calls = 0 + + async def __call__( + self, tier: hksv3.VideoStreamTier + ) -> Sequence[str] | FFmpegInput | None: + """Count the call and answer it.""" + self.calls += 1 + answer: InputResolver = self.failing.get(self.calls, self._resolve) + return await answer(tier) + + async def _resolve(self, _tier: hksv3.VideoStreamTier) -> FFmpegInput: + return FFmpegInput(("-i", f"cam?token={self.calls}")) + + +async def raise_error(_tier: hksv3.VideoStreamTier) -> None: + """An input resolver failing with the camera URL in its error.""" + raise RuntimeError("rtsp://user:pw@10.0.0.2/T0k3n: 401") + + +async def time_out(_tier: hksv3.VideoStreamTier) -> None: + """An input resolver failing with an error without a text.""" + raise TimeoutError + + +async def find_nothing(_tier: hksv3.VideoStreamTier) -> None: + """An input resolver without an input for the tier.""" + + +async def cancel(_tier: hksv3.VideoStreamTier) -> None: + """An input resolver raising CancelledError while nothing cancels it.""" + raise asyncio.CancelledError + + +def after(gate: asyncio.Event) -> InputResolver: + """An input resolver answering once ``gate`` is set.""" + + async def resolve(_tier: hksv3.VideoStreamTier) -> FFmpegInput: + await gate.wait() + return FFmpegInput(("-i", "cam?token=late")) + + return resolve + + +def started(fake_ffmpeg: Path) -> list[str]: + """The arguments of each start of the fake ffmpeg.""" + log = fake_ffmpeg.parent / "starts.log" + return log.read_text().splitlines() if log.exists() else [] + + +def tokens(fake_ffmpeg: Path) -> list[str]: + """The token in the input of each start of the fake ffmpeg.""" + return [line.partition("token=")[2].split()[0] for line in started(fake_ffmpeg)] + + +def exit_ffmpeg(pull: FFmpegPull, _lease: ChannelLease) -> None: + """End the running ffmpeg, as when the camera drops its connection.""" + os.kill(cast(int, pull.pid), signal.SIGTERM) + + +def request_keyframe(pull: FFmpegPull, lease: ChannelLease) -> None: + """Request an IRAP picture long after the last one.""" + pull._started -= 100 + lease.keyframe_requested(None, None) + + +async def test_first_start_runs_on_the_input_of_the_lease(fake_ffmpeg: Path) -> None: + """Verify the first start does not ask the resolver again, which may hang.""" + resolver = TokenResolver({2: after(asyncio.Event())}) + worker = FakeWorker() + provider = FFmpegSourceProvider( + resolver, worker=cast(Any, worker), ffmpeg=str(fake_ffmpeg) + ) + lease = await provider.lease_channel(MEDIUM, AUDIO) + + # It holds the lock of the channel, which release() and close() need too. + await asyncio.wait_for(lease.activate(), 2) + await wait_until(lambda: len(started(fake_ffmpeg)) == 1) + await asyncio.wait_for(lease.release(), 2) + await asyncio.wait_for(provider.close(), 2) + + assert tokens(fake_ffmpeg) == ["1"] + assert resolver.calls == 1 + assert worker.sources[0].closed + + +@pytest.mark.parametrize( + "restart", [exit_ffmpeg, request_keyframe], ids=["exit", "keyframe"] +) +async def test_ffmpeg_provider_resolves_for_each_restart( + fake_ffmpeg: Path, restart: Callable[[FFmpegPull, ChannelLease], None] +) -> None: + """Verify a restarted ffmpeg runs on a newly resolved input.""" + resolver = TokenResolver() + provider = FFmpegSourceProvider( + resolver, + worker=cast(Any, FakeWorker()), + ffmpeg=str(fake_ffmpeg), + restart_delay=0.01, + ) + lease = await provider.lease_channel(MEDIUM, AUDIO) + await lease.activate() + await wait_until(lambda: len(started(fake_ffmpeg)) == 1) + + restart(provider._pulls["medium"], lease) + await wait_until(lambda: len(started(fake_ffmpeg)) == 2) + await lease.release() + await provider.close() + + assert tokens(fake_ffmpeg) == ["1", "2"] + assert resolver.calls == 2 + + +@pytest.mark.parametrize( + ("failing", "message"), + [ + (raise_error, "could not start: rtsp://10.0.0.2/ 401"), + (time_out, "could not start: TimeoutError"), + (find_nothing, "could not start: No ffmpeg input for tier"), + (cancel, "could not start: CancelledError"), + ], + ids=["error", "error-without-text", "no-input", "cancelled"], +) +async def test_ffmpeg_provider_retries_a_failed_resolve( + fake_ffmpeg: Path, + caplog: pytest.LogCaptureFixture, + failing: InputResolver, + message: str, +) -> None: + """Verify a resolver failing for a restart is reported and asked again.""" + caplog.set_level(logging.DEBUG, "pyhap.media.ffmpeg") + errors: list[str] = [] + worker = FakeWorker() + provider = FFmpegSourceProvider( + TokenResolver({2: failing, 3: failing}), + worker=cast(Any, worker), + ffmpeg=str(fake_ffmpeg), + restart_delay=0.01, + on_error=lambda _channel, text: errors.append(text), + ) + lease = await provider.lease_channel(MEDIUM, AUDIO) + await lease.activate() + pull = provider._pulls["medium"] + await wait_until(lambda: len(started(fake_ffmpeg)) == 1) + + exit_ffmpeg(pull, lease) + await wait_until(lambda: pull.restarts == 1) + await wait_until(lambda: len(started(fake_ffmpeg)) == 2) + await lease.release() + await provider.close() + + assert errors[0].startswith("exited with") + assert [error.startswith(message) for error in errors[1:]] == [True, True] + assert tokens(fake_ffmpeg) == ["1", "4"] + assert worker.sources[0].closed + assert "T0k3n" not in caplog.text + + +@pytest.mark.parametrize( + ("restart", "failing", "calls", "message"), + [ + (exit_ffmpeg, {}, 1, "exited with"), + (request_keyframe, {2: raise_error}, 2, "could not start"), + ], + ids=["exit", "failed-start"], +) +async def test_keyframe_requests_keep_the_backoff( + fake_ffmpeg: Path, + restart: Callable[[FFmpegPull, ChannelLease], None], + failing: dict[int, InputResolver], + calls: int, + message: str, +) -> None: + """Verify keyframe requests while no ffmpeg runs do not restart it early.""" + errors: list[str] = [] + resolver = TokenResolver(failing) + provider = FFmpegSourceProvider( + resolver, + worker=cast(Any, FakeWorker()), + ffmpeg=str(fake_ffmpeg), + gop=0.05, + restart_delay=10.0, + on_error=lambda _channel, text: errors.append(text), + ) + lease = await provider.lease_channel(MEDIUM, AUDIO) + await lease.activate() + pull = provider._pulls["medium"] + await wait_until(lambda: len(started(fake_ffmpeg)) == 1) + restart(pull, lease) + await wait_until(lambda: bool(errors)) + + # Each after twice the GOP, which a running ffmpeg would restart for. + for _ in range(5): + await asyncio.sleep(0.15) + lease.keyframe_requested(None, None) + await lease.release() + await provider.close() + + assert resolver.calls == calls + assert len(started(fake_ffmpeg)) == 1 + assert [error.startswith(message) for error in errors] == [True] + + +async def release_lease(lease: ChannelLease, _provider: FFmpegSourceProvider) -> None: + """End the last session of the channel.""" + await lease.release() + + +async def close_provider(_lease: ChannelLease, provider: FFmpegSourceProvider) -> None: + """Shut the provider down.""" + await provider.close() + + +@pytest.mark.parametrize( + "stop", [release_lease, close_provider], ids=["release", "close"] +) +async def test_stop_does_not_wait_for_a_resolve( + fake_ffmpeg: Path, + stop: Callable[[ChannelLease, FFmpegSourceProvider], Awaitable[None]], +) -> None: + """Verify ffmpeg stops at once while a restart is resolved, and for good.""" + gate = asyncio.Event() + errors: list[str] = [] + worker = FakeWorker() + resolver = TokenResolver({2: after(gate)}) + provider = FFmpegSourceProvider( + resolver, + worker=cast(Any, worker), + ffmpeg=str(fake_ffmpeg), + restart_delay=0.01, + on_error=lambda _channel, text: errors.append(text), + ) + lease = await provider.lease_channel(MEDIUM, AUDIO) + await lease.activate() + pull = provider._pulls["medium"] + await wait_until(lambda: len(started(fake_ffmpeg)) == 1) + exit_ffmpeg(pull, lease) + await wait_until(lambda: resolver.calls == 2) + + await asyncio.wait_for(stop(lease, provider), 2) + gate.set() + await asyncio.sleep(0.1) + await lease.release() + await provider.close() + + assert worker.sources[0].closed + assert (pull.pid, pull.restarts, len(started(fake_ffmpeg))) == (None, 0, 1) + # Only the exit: the cut resolve is no failed start. + assert [error.startswith("exited with") for error in errors] == [True] + + def pull_on(fake_ffmpeg: Path, gop: float = 10.0) -> FFmpegPull: """An ffmpeg pull running the fake ffmpeg.""" return FFmpegPull( @@ -395,7 +658,9 @@ async def test_ffmpeg_pull_backs_off_failed_starts( assert pull.restarts == 0 -async def test_failed_first_start_reaches_on_error(tmp_path: Path) -> None: +async def test_failed_first_start_reaches_on_error( + tmp_path: Path, caplog: pytest.LogCaptureFixture +) -> None: """Verify a missing ffmpeg raises and is reported to on_error.""" errors: list[tuple[str, str]] = [] pull = FFmpegPull( @@ -411,6 +676,7 @@ async def test_failed_first_start_reaches_on_error(tmp_path: Path) -> None: assert errors[0][1].startswith("could not start") assert pull.last_error == errors[0][1] assert pull.pid is None + assert f"ffmpeg for medium {errors[0][1]}" in caplog.messages @pytest.mark.parametrize( @@ -458,3 +724,59 @@ async def test_ffmpeg_pull_restarts_for_a_keyframe( assert pull.pid != pid await pull.stop() + + +async def test_command_resolved_as_the_pull_stops_is_not_run( + fake_ffmpeg: Path, +) -> None: + """Verify a restart whose command comes as stop() begins runs no ffmpeg.""" + stopping: list[asyncio.Future[None]] = [] + + async def stop_and_answer(_rtp_input: tuple[str, int, int]) -> list[str]: + stopping.append(asyncio.ensure_future(pull.stop())) + return [str(fake_ffmpeg)] + + pull = FFmpegPull( + lambda _rtp_input: [str(fake_ffmpeg)], + "medium", + 10.0, + restart_delay=0.01, + restart_command=stop_and_answer, + ) + await pull.start(("127.0.0.1", 1, 2)) + process = pull._process + os.kill(cast(int, pull.pid), signal.SIGTERM) + await wait_until(lambda: bool(stopping)) + await stopping[0] + + assert (pull._process, pull.restarts) == (process, 0) + + +async def test_cancelled_watcher_ends_during_a_resolve(fake_ffmpeg: Path) -> None: + """Verify a watcher cancelled while a restart resolves ends, e.g. on shutdown.""" + resolving = asyncio.Event() + + async def hang(_rtp_input: tuple[str, int, int]) -> list[str]: + resolving.set() + await asyncio.Event().wait() + return [str(fake_ffmpeg)] + + pull = FFmpegPull( + lambda _rtp_input: [str(fake_ffmpeg)], + "medium", + 10.0, + restart_delay=0.01, + restart_command=hang, + ) + await pull.start(("127.0.0.1", 1, 2)) + os.kill(cast(int, pull.pid), signal.SIGTERM) + await resolving.wait() + watcher = cast(asyncio.Task[None], pull._watcher) + + watcher.cancel() + await asyncio.wait({watcher}, timeout=2) + # Raises the watcher's cancellation; ends a watcher that went on instead. + with contextlib.suppress(asyncio.CancelledError): + await pull.stop() + + assert watcher.cancelled() From 99786cecd54a99e4d874533e6f1aa9aa40a386b4 Mon Sep 17 00:00:00 2001 From: Raphael Hehl <7577984+RaHehl@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:48:12 +0100 Subject: [PATCH 2/2] Share an ffmpeg channel between inputs with the same key A URL that changes with every resolve gave every session its own ffmpeg. FFmpegInput.key lets such inputs share one channel. --- docs/source/media/architecture.rst | 6 ++- pyhap/media/ffmpeg.py | 21 +++++++-- tests/test_media_ffmpeg_provider.py | 70 +++++++++++++++++++++++++++-- 3 files changed, 90 insertions(+), 7 deletions(-) diff --git a/docs/source/media/architecture.rst b/docs/source/media/architecture.rst index 69273a13..80b79cf8 100644 --- a/docs/source/media/architecture.rst +++ b/docs/source/media/architecture.rst @@ -39,7 +39,11 @@ Channels and sessions channel One media input of a camera, identified by any hashable key. Tiers that - resolve to the same input share a channel. + resolve to the same input share a channel. The ffmpeg provider resolves + the input for every lease and again for every restart of its process, so + an input whose URL changes, for example with a token that expires, names + its channel with the ``key`` of :class:`~pyhap.media.ffmpeg.FFmpegInput` + to stay shared. session One HomeKit stream session. It attaches to the channel's source as a diff --git a/pyhap/media/ffmpeg.py b/pyhap/media/ffmpeg.py index 87523e0d..7822b076 100644 --- a/pyhap/media/ffmpeg.py +++ b/pyhap/media/ffmpeg.py @@ -13,7 +13,7 @@ from __future__ import annotations import asyncio -from collections.abc import Awaitable, Callable, Mapping, Sequence +from collections.abc import Awaitable, Callable, Hashable, Mapping, Sequence import contextlib from dataclasses import dataclass, replace from functools import partial @@ -75,6 +75,15 @@ class FFmpegInput: when set: ``video_map`` and ``audio_map`` select the streams, ``audio`` turns audio off for inputs without it, and ``gop`` is the expected interval between IRAP pictures until the source has measured it. + + ``key`` stands for ``args`` when channels are shared: inputs that differ + only in ``args`` and ``gop`` share one source and one ffmpeg if their + keys are equal; ffmpeg runs on the input resolved for the tier that + opened the channel. Without a key only inputs equal but for ``gop`` + share, so an input whose arguments change from one resolve to the next, + such as a URL with a token that expires, needs a key to be shared. A key + must name one stream of the camera, not the camera: tiers of one channel + share its source, so switching a session between them changes nothing. """ args: tuple[str, ...] @@ -82,6 +91,7 @@ class FFmpegInput: audio_map: str | None = None audio: bool | None = None gop: float | None = None + key: Hashable | None = None InputResolver = Callable[ @@ -98,7 +108,10 @@ class FFmpegSourceProvider: be an async callable that resolves a tier to the same, or None when nothing fits. Tiers with the same input share one ffmpeg. A restart of ffmpeg, after an exit or for a keyframe request, calls it again: the - input may have expired meanwhile, e.g. a URL with a token. + input may have expired meanwhile, e.g. a URL with a token. Inputs with + the same ``key`` (see :class:`FFmpegInput`) share one ffmpeg too: give + such an input a key, or each lease with a new URL opens a channel with + an ffmpeg of its own. Video ``video_map`` is copied with ``dump_extra`` so every IRAP picture carries its parameter sets (an Annex B input such as RTSP; MP4 needs @@ -185,6 +198,7 @@ async def input_for(self, tier: hksv3.VideoStreamTier) -> FFmpegInput: found.audio_map or self.audio_map, self.audio if found.audio is None else found.audio, found.gop or self.gop, + found.key, ) def channel_name(self, tier: hksv3.VideoStreamTier) -> str: @@ -281,7 +295,8 @@ def make_pull() -> FFmpegPull: return pull return await self.pool.lease( - replace(found, gop=None), + # A key stands for the arguments, which may change with each resolve. + replace(found, args=() if found.key is not None else found.args, gop=None), make_pull, audio=bool(found.audio), name=name, diff --git a/tests/test_media_ffmpeg_provider.py b/tests/test_media_ffmpeg_provider.py index 8e62a7b7..61c8b991 100644 --- a/tests/test_media_ffmpeg_provider.py +++ b/tests/test_media_ffmpeg_provider.py @@ -328,12 +328,15 @@ class TokenResolver: """An input resolver whose input holds the number of the call as a token. ``failing`` maps the number of a call to the resolver answering it - instead. + instead; ``fields`` are further fields of the inputs. """ - def __init__(self, failing: Mapping[int, InputResolver] | None = None) -> None: + def __init__( + self, failing: Mapping[int, InputResolver] | None = None, /, **fields: Any + ) -> None: """Start without a call.""" self.failing = failing or {} + self.fields = fields self.calls = 0 async def __call__( @@ -345,7 +348,7 @@ async def __call__( return await answer(tier) async def _resolve(self, _tier: hksv3.VideoStreamTier) -> FFmpegInput: - return FFmpegInput(("-i", f"cam?token={self.calls}")) + return FFmpegInput(("-i", f"cam?token={self.calls}"), **self.fields) async def raise_error(_tier: hksv3.VideoStreamTier) -> None: @@ -584,6 +587,67 @@ async def test_stop_does_not_wait_for_a_resolve( assert [error.startswith("exited with") for error in errors] == [True] +@pytest.mark.parametrize( + ("fields", "expected"), + [({"key": "main-stream"}, ["1"]), ({}, ["1", "2"])], + ids=["key", "no-key"], +) +async def test_ffmpeg_provider_shares_a_channel_by_key( + fake_ffmpeg: Path, fields: dict[str, str], expected: list[str] +) -> None: + """Verify inputs that differ share a source and an ffmpeg only by a key.""" + worker = FakeWorker() + resolver = TokenResolver(**fields) + provider = FFmpegSourceProvider( + resolver, worker=cast(Any, worker), ffmpeg=str(fake_ffmpeg) + ) + first = await provider.lease_channel(MEDIUM, AUDIO) + await first.activate() + second = await provider.lease_channel(MEDIUM, AUDIO) + await second.activate() + await wait_until(lambda: len(started(fake_ffmpeg)) == len(expected)) + await first.release() + await second.release() + await provider.close() + + assert len(worker.sources) == len(expected) + assert (first.source, second.source) == (worker.sources[0], worker.sources[-1]) + # Each ffmpeg starts on the input of the lease that opened its channel. + assert sorted(tokens(fake_ffmpeg)) == expected + assert resolver.calls == 2 + + +@pytest.mark.parametrize( + ("fields", "shared"), + [ + ({}, True), + ({"gop": 4.0}, True), + ({"audio": False}, False), + ({"video_map": "0:v:1"}, False), + ], + ids=["args", "gop", "audio", "video-map"], +) +async def test_ffmpeg_provider_key_stands_for_args_only( + fields: dict[str, Any], shared: bool +) -> None: + """Verify a key shares a channel only between inputs differing in args.""" + worker = FakeWorker() + provider = FFmpegSourceProvider( + { + "low": FFmpegInput(("-i", "cam?token=1"), key="main-stream", **fields), + "medium": FFmpegInput(("-i", "cam?token=2"), key="main-stream"), + }, + worker=cast(Any, worker), + ) + first = await provider.lease_channel(LOW, AUDIO) + second = await provider.lease_channel(MEDIUM, AUDIO) + await first.release() + await second.release() + + assert (first.source is second.source) == shared + assert second.source.has_audio + + def pull_on(fake_ffmpeg: Path, gop: float = 10.0) -> FFmpegPull: """An ffmpeg pull running the fake ffmpeg.""" return FFmpegPull(