Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: name FFmpeg when a video GGUF can't decode, and shrink clips with the ffmpeg llama-server uses (#16098)
Leo Borcherdingf4c7a8f19c60
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex cb74f8b53aa..62ccb618fe4 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -83,6 +83,7 @@ from core.inference.context_window import (turn_is_servable,)from core.inference.llama_tool_schema import llama_grammar_tools+from core.inference.llama_video_input import video_toolsfrom core.inference.lookup_tables import (HOST_FORCED_TABLE_ARCHS as _HOST_FORCED_TABLE_ARCHS,HOST_FORCED_TABLE_MARKER as _HOST_FORCED_TABLE_MARKER,@@ -5676,6 +5677,7 @@ _LLAMA_VIDEO_FPS = "1"_VIDEO_FPS_ENV_VAR = "LLAMA_ARG_VIDEO_FPS"_LLAMA_SERVER_DEFAULT_VIDEO_FPS = 4.0_VIDEO_TIMESTAMP_ENV_VAR = "LLAMA_ARG_VIDEO_TIMESTAMP_INTERVAL"+_VIDEO_FFMPEG_DIR_ENV_VAR = "LLAMA_ARG_VIDEO_FFMPEG_DIR"def _video_fps_flags(@@ -5711,6 +5713,33 @@ def _video_fps_flags(return flags+def _video_ffmpeg_dir_flags(+ server_caps: Mapping[str, object],+ env: Optional[Mapping[str, str]] = None,+ extra_args: Optional[Sequence[str]] = None,+) -> tuple[list[str], Optional[str]]:+ if not server_caps.get("supports_video_ffmpeg_dir"):+ return [], None+ source = os.environ if env is None else env+ try:+ chosen = _last_flag_value(extra_args, frozenset({"--video-ffmpeg-dir"}), preserve_raw = True)+ except ValueError:+ chosen = None+ chosen = chosen or source.get(_VIDEO_FFMPEG_DIR_ENV_VAR) or None+ if chosen:+ return [], chosen+ # CreateProcess searches the server's directory before PATH.+ if sys.platform == "win32":+ return [], None+ tools = video_tools()+ if tools is None:+ return [], None+ ffmpeg_dir = os.path.dirname(tools[0])+ if os.path.dirname(tools[1]) != ffmpeg_dir:+ return [], None+ return ["--video-ffmpeg-dir", ffmpeg_dir], ffmpeg_dir++def requested_video_fps(extra_args: Optional[Sequence[str]] = None, env: Optional[Mapping[str, str]] = None) -> Optional[float]:@@ -5736,25 +5765,35 @@ def requested_video_fps(return rate if rate > 0 else None+def _video_tools_search(+ cmd: Sequence[str],+ env: Optional[Mapping[str, str]] = None,+ cwd: Optional[str] = None,+ supports_ffmpeg_dir: bool = True,+) -> str:+ source = os.environ if env is None else env+ bin_dir = _last_flag_value(cmd, frozenset({"--video-ffmpeg-dir"}), preserve_raw = True)+ search = bin_dir or (source.get(_VIDEO_FFMPEG_DIR_ENV_VAR) if supports_ffmpeg_dir else None)+ if not search:+ search = source.get("PATH", os.defpath)+ if sys.platform == "win32":+ launch_dir = os.path.dirname(str(cmd[0])) if cmd else ""+ search = os.pathsep.join(d for d in (launch_dir, cwd or os.getcwd(), search) if d)+ return search++def _video_tools_reachable(cmd: Sequence[str],env: Optional[Mapping[str, str]] = None,cwd: Optional[str] = None,+ supports_ffmpeg_dir: bool = True,) -> bool:"""Whether the child can launch ffmpeg and ffprobe, which /props' video modality never checks (#16065)."""- source = os.environ if env is None else envtry:- bin_dir = _last_flag_value(cmd, frozenset({"--video-ffmpeg-dir"}))+ search = _video_tools_search(cmd, env, cwd, supports_ffmpeg_dir)except Exception:return True- search = bin_dir or source.get("LLAMA_ARG_VIDEO_FFMPEG_DIR")names = ("ffmpeg.exe", "ffprobe.exe") if sys.platform == "win32" else ("ffmpeg", "ffprobe")- if not search:- search = source.get("PATH", os.defpath)- if sys.platform == "win32":- # CreateProcess also searches the binary's folder and the working directory.- launch_dir = os.path.dirname(str(cmd[0])) if cmd else ""- search = os.pathsep.join(d for d in (launch_dir, cwd or os.getcwd(), search) if d)return all(shutil.which(name, path = search) for name in names)@@ -8433,6 +8472,8 @@ class LlamaCppBackend:self._has_audio_input: bool = False# Needs mmproj, build and ffmpeg to align; the GGUF alone cannot tell.self._has_video_input: bool = False+ self._video_needs_ffmpeg: bool = False+ self._video_ffmpeg_dir: Optional[str] = Noneself._mmproj_has_audio: bool = False # clip.has_audio_encoder, set at load# clip.projector_type set at load; the family whose image-token ceiling KV admission sizes images against.self._mmproj_projector_type: Optional[str] = None@@ -10162,6 +10203,7 @@ class LlamaCppBackend:"supports_trace_verbosity": False,"supports_video_fps": False,"supports_video_timestamp_interval": False,+ "supports_video_ffmpeg_dir": None,"supports_load_mode": False,"supports_moe_cache": False,"supports_moe_cache_auto": False,@@ -10232,6 +10274,7 @@ class LlamaCppBackend:supports_no_mmproj_offload = Falsesupports_video_fps = Falsesupports_video_timestamp_interval = False+ supports_video_ffmpeg_dir = Nonesupports_load_mode = Falsesupports_moe_cache = Falsesupports_moe_cache_auto = False@@ -10441,6 +10484,9 @@ class LlamaCppBackend:supports_no_mmproj_offload = _is_real("--no-mmproj-offload")supports_video_fps = _is_real("--video-fps")supports_video_timestamp_interval = _is_real("--video-timestamp-interval")+ supports_video_ffmpeg_dir = (+ _is_real("--video-ffmpeg-dir") if probe_ok and blocks else None+ )# --load-mode supersedes --mlock / --no-mmap, which are deprecated.# Pre-initialised above: a failed probe must fall back, not raise.supports_load_mode = _is_real("--load-mode")@@ -10555,6 +10601,7 @@ class LlamaCppBackend:"supports_trace_verbosity": supports_trace_verbosity,"supports_video_fps": supports_video_fps,"supports_video_timestamp_interval": supports_video_timestamp_interval,+ "supports_video_ffmpeg_dir": supports_video_ffmpeg_dir,"supports_load_mode": supports_load_mode,"supports_moe_cache": supports_moe_cache,"supports_moe_cache_auto": supports_moe_cache_auto,@@ -28440,6 +28487,10 @@ class LlamaCppBackend:# On every launch, not only where Studio emits --mmproj: a projector# from the extras or LLAMA_ARG_MMPROJ takes video too.cmd.extend(_video_fps_flags(server_caps, extra_args = extra_args))+ _ffmpeg_flags, self._video_ffmpeg_dir = _video_ffmpeg_dir_flags(+ server_caps, extra_args = extra_args+ )+ cmd.extend(_ffmpeg_flags)# Report the public model id, not the raw -m path.from core.inference.model_ids import public_model_id@@ -32615,10 +32666,22 @@ class LlamaCppBackend:# -- the length --fit chose, or a --parallel slot split -- so the# Adopt the context the server allocated (--fit or slot split); clear video state first, or a swap to a model without video inherits the old answer.self._has_video_input = False+ self._video_needs_ffmpeg = False# Use _extra_args_as_requested: the drafter-drop snapshot would restore the Metal zero-context strip.self._reconcile_effective_ctx_with_server(ctx_override or 0)if self._has_video_input:- self._has_video_input = _video_tools_reachable(_last_spawn_cmd, env, _spawn_cwd)+ _supports_dir = server_caps.get("supports_video_ffmpeg_dir") is not False+ self._has_video_input = _video_tools_reachable(+ _last_spawn_cmd, env, _spawn_cwd, supports_ffmpeg_dir = _supports_dir+ )+ self._video_needs_ffmpeg = not self._has_video_input+ if self._has_video_input:+ try:+ self._video_ffmpeg_dir = _video_tools_search(+ _last_spawn_cmd, env, _spawn_cwd, supports_ffmpeg_dir = _supports_dir+ )+ except Exception:+ passif not self._has_video_input:logger.warning("Video input disabled: llama-server decodes video with ffmpeg and "@@ -33618,6 +33681,7 @@ class LlamaCppBackend:self._audio_probed = Falseself._has_audio_input = Falseself._has_video_input = False+ self._video_needs_ffmpeg = Falseself._mmproj_has_audio = Falseself._mmproj_accepts_image = Trueself._port = Nonediff --git a/studio/backend/core/inference/llama_video_input.py b/studio/backend/core/inference/llama_video_input.pyindex 66c4d1d39fd..55503da3e7f 100644--- a/studio/backend/core/inference/llama_video_input.py+++ b/studio/backend/core/inference/llama_video_input.py@@ -11,9 +11,10 @@ import jsonimport loggingimport shutilimport subprocess+import sysimport tempfilefrom pathlib import Path-from typing import Optional+from typing import Mapping, Optionalfrom utils.native_path_leases import child_env_without_native_path_secretfrom utils.subprocess_compat import windows_hidden_subprocess_kwargs@@ -30,19 +31,34 @@ _PROBE_TIMEOUT_S = 30_SHRINK_TIMEOUT_S = 300-def _run(argv: list[str], timeout: float) -> subprocess.CompletedProcess:+def video_tools(ffmpeg_dir: Optional[str] = None) -> Optional[tuple[str, str]]:+ names = ("ffmpeg.exe", "ffprobe.exe") if sys.platform == "win32" else ("ffmpeg", "ffprobe")+ if ffmpeg_dir:+ found = [shutil.which(name, path = ffmpeg_dir) for name in names]+ else:+ found = [shutil.which(name) for name in names]+ return (found[0], found[1]) if found[0] and found[1] else None+++def _run(+ argv: list[str],+ timeout: float,+ env: Optional[Mapping[str, str]] = None,+) -> subprocess.CompletedProcess:return subprocess.run(argv,stdin = subprocess.DEVNULL,capture_output = True,timeout = timeout,- env = child_env_without_native_path_secret(),+ env = child_env_without_native_path_secret(env),**windows_hidden_subprocess_kwargs(),)def _frame_geometry(- ffprobe: str, clip: Path+ ffprobe: str,+ clip: Path,+ env: Optional[Mapping[str, str]] = None,) -> tuple[Optional[int], Optional[float], Optional[float]]:"""Any field is None when ffprobe cannot answer; the caller then leaves the clip alone."""result = _run(@@ -64,6 +80,7 @@ def _frame_geometry(str(clip),],_PROBE_TIMEOUT_S,+ env = env,)if result.returncode != 0:return None, None, None@@ -85,11 +102,15 @@ def _frame_geometry(except (TypeError, ValueError):duration = Noneif duration is None:- duration = _packet_duration(ffprobe, clip)+ duration = _packet_duration(ffprobe, clip, env = env)return area, _frame_rate(streams[0].get("avg_frame_rate")), duration-def _packet_duration(ffprobe: str, clip: Path) -> Optional[float]:+def _packet_duration(+ ffprobe: str,+ clip: Path,+ env: Optional[Mapping[str, str]] = None,+) -> Optional[float]:"""Duration from packet timestamps, for containers that carry none: a rawelementary stream has no `format.duration`, so the sub-second floor never firedon one. Bounded to twice the floor, past which a clip is long enough anyway."""@@ -111,6 +132,7 @@ def _packet_duration(ffprobe: str, clip: Path) -> Optional[float]:str(clip),],_PROBE_TIMEOUT_S,+ env = env,)if result.returncode != 0:return None@@ -186,6 +208,8 @@ def shrink_video_for_llama(max_bytes: int,max_pixels: int = MAX_FRAME_PIXELS,sampled_fps: Optional[float] = None,+ ffmpeg_dir: Optional[str] = None,+ env: Optional[Mapping[str, str]] = None,) -> str:"""Make a clip cheap and safe for llama-server to sample, as bare base64.@@ -200,15 +224,15 @@ def shrink_video_for_llama(return video_b64# Before the tool check: without ffmpeg the clip still reaches llama-server's own FFmpeg.refuse_playlist(raw)- ffmpeg = shutil.which("ffmpeg")- ffprobe = shutil.which("ffprobe")- if not ffmpeg or not ffprobe:+ tools = video_tools(ffmpeg_dir)+ if tools is None:return video_b64+ ffmpeg, ffprobe = toolstry:with tempfile.TemporaryDirectory(prefix = "unsloth-video-") as tmp:source = Path(tmp) / "clip"source.write_bytes(raw)- area, rate, duration = _frame_geometry(ffprobe, source)+ area, rate, duration = _frame_geometry(ffprobe, source, env = env)if area is None:return video_b64oversized = area > max_pixels@@ -249,6 +273,7 @@ def shrink_video_for_llama(str(shrunk),],_SHRINK_TIMEOUT_S,+ env = env,)if result.returncode != 0 or not shrunk.is_file() or shrunk.stat().st_size == 0:logger.warning(diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 7ed08280275..1ab5bc82e1c 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -27027,6 +27027,11 @@ def _llama_passthrough_audio(raw: bytes) -> Optional[tuple[str, float]]:_VIDEO_INPUT_REFUSAL = ("Video input is only supported on a local GGUF or MLX model with video support.")+_VIDEO_NEEDS_FFMPEG_DETAIL = (+ "This model takes video, but ffmpeg and ffprobe were not found in llama-server's search path. "+ "Install FFmpeg so both are on PATH, or correct --video-ffmpeg-dir / "+ "LLAMA_ARG_VIDEO_FFMPEG_DIR if configured. Then restart Unsloth and reload the model."+)def _local_video_clips(payload, model_info) -> list[str]:@@ -27298,12 +27303,20 @@ def _request_video_rejection(payload) -> Optional[tuple[int, str]]:async def _shrink_clip_for_llama(video_b64: str, llama_backend) -> str:"""Transcodes before llama-server samples frames, so the explicit rate must reach the transcode."""+ process_env = getattr(llama_backend, "_process_env", None)+ child_env = (+ process_env[1]+ if process_env is not None and process_env[0] is getattr(llama_backend, "_process", None)+ else None+ )try:return await asyncio.to_thread(shrink_video_for_llama,video_b64,_MAX_VIDEO_BYTES,sampled_fps = requested_video_fps(getattr(llama_backend, "extra_args", None)),+ ffmpeg_dir = getattr(llama_backend, "_video_ffmpeg_dir", None),+ env = child_env,)except Exception as e:# The helper absorbs ffmpeg errors, so a raw 500 would leak the monitor row; reject with a 400.@@ -31780,6 +31793,8 @@ async def produce_openai_chat_completions(video_b64 = Noneif _request_has_video(payload):if not getattr(llama_backend, "_has_video_input", False):+ if getattr(llama_backend, "_video_needs_ffmpeg", False):+ raise _reject(400, _VIDEO_NEEDS_FFMPEG_DETAIL)raise _reject(400,"Video provided but the current GGUF model cannot take video input. "diff --git a/studio/backend/tests/test_llama_video_ffmpeg.py b/studio/backend/tests/test_llama_video_ffmpeg.pynew file mode 100644index 00000000000..9706ecde812--- /dev/null+++ b/studio/backend/tests/test_llama_video_ffmpeg.py@@ -0,0 +1,305 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++from __future__ import annotations++import asyncio+import json+import os+import shutil+import stat+import subprocess+import sys+from pathlib import Path+from types import SimpleNamespace++import pytest++_TESTS_DIR = Path(__file__).resolve().parent+if str(_TESTS_DIR) not in sys.path:+ sys.path.insert(0, str(_TESTS_DIR))++pytest.importorskip("torch")++import core.inference.llama_cpp as llama_mod # noqa: E402+from core.inference import llama_video_input # noqa: E402+from core.inference.llama_cpp import LlamaCppBackend, _video_ffmpeg_dir_flags # noqa: E402+from core.inference.llama_video_input import video_tools # noqa: E402++from test_llama_flag_catalog import _probe_with_help # noqa: E402+from test_llama_video_frame_budget import _clip, _probe, _video_backend, needs_ffmpeg # noqa: E402+from test_mmproj_placement_policy import _launch # noqa: E402+from test_video_needs_ffmpeg import _load_with_video_props, _tools_dir as _bin # noqa: E402++_CAPS = {"supports_video_ffmpeg_dir": True}+_EXE = ".exe" if os.name == "nt" else ""+++def _tool_dir(tmp_path, *names):+ folder = tmp_path / "ffmpeg-bin"+ folder.mkdir(exist_ok = True)+ for name in names:+ exe = folder / f"{name}{_EXE}"+ exe.write_bytes(b"")+ exe.chmod(exe.stat().st_mode | stat.S_IXUSR)+ return folder+++def _tools_at(monkeypatch, ffmpeg, ffprobe):+ monkeypatch.setattr(llama_mod, "video_tools", lambda _dir = None: (ffmpeg, ffprobe))+++def _no_tools(monkeypatch):+ monkeypatch.setattr(llama_mod, "video_tools", lambda _dir = None: None)+++def test_a_launch_pins_the_ffmpeg_studio_found(monkeypatch):+ _tools_at(monkeypatch, "/opt/bin/ffmpeg", "/opt/bin/ffprobe")+ if sys.platform == "win32":+ assert _video_ffmpeg_dir_flags(_CAPS, env = {}) == ([], None)+ return+ assert _video_ffmpeg_dir_flags(_CAPS, env = {}) == (+ ["--video-ffmpeg-dir", "/opt/bin"],+ "/opt/bin",+ )+++def test_tools_in_two_folders_are_left_to_path(monkeypatch):+ _tools_at(monkeypatch, "/a/ffmpeg", "/b/ffprobe")+ assert _video_ffmpeg_dir_flags(_CAPS, env = {}) == ([], None)+++def test_no_ffmpeg_or_an_older_build_sends_no_flag(monkeypatch):+ _no_tools(monkeypatch)+ assert _video_ffmpeg_dir_flags(_CAPS, env = {}) == ([], None)+ _tools_at(monkeypatch, "/opt/bin/ffmpeg", "/opt/bin/ffprobe")+ assert _video_ffmpeg_dir_flags({}, env = {}) == ([], None)+++def test_a_hand_typed_or_inherited_folder_is_kept(monkeypatch):+ _tools_at(monkeypatch, "/opt/bin/ffmpeg", "/opt/bin/ffprobe")+ assert _video_ffmpeg_dir_flags(_CAPS, env = {}, extra_args = ["--video-ffmpeg-dir", "/mine"]) == (+ [],+ "/mine",+ )+ assert _video_ffmpeg_dir_flags(_CAPS, env = {"LLAMA_ARG_VIDEO_FFMPEG_DIR": "/env"}) == (+ [],+ "/env",+ )+++def test_an_older_build_ignores_the_inherited_folder_so_the_check_does_too(monkeypatch):+ _tools_at(monkeypatch, "/opt/bin/ffmpeg", "/opt/bin/ffprobe")+ assert _video_ffmpeg_dir_flags({}, env = {"LLAMA_ARG_VIDEO_FFMPEG_DIR": "/env"}) == ([], None)+++def test_the_launch_command_carries_the_folder(tmp_path, monkeypatch):+ monkeypatch.delenv("LLAMA_ARG_VIDEO_FFMPEG_DIR", raising = False)+ _tools_at(monkeypatch, "/opt/bin/ffmpeg", "/opt/bin/ffprobe")+ backend, gguf = _video_backend(tmp_path, supports_video_ffmpeg_dir = True)+ cmd = _launch(backend, gguf)["cmd"]+ if sys.platform == "win32":+ assert "--video-ffmpeg-dir" not in cmd+ return+ assert cmd[cmd.index("--video-ffmpeg-dir") + 1] == "/opt/bin"+ assert backend._video_ffmpeg_dir == "/opt/bin"+++def test_the_probe_reads_the_flag_from_help(monkeypatch, tmp_path):+ caps = _probe_with_help(+ monkeypatch,+ tmp_path,+ "--video-ffmpeg-dir DIR path to the directory containing ffmpeg and ffprobe\n",+ )+ assert caps["supports_video_ffmpeg_dir"] is True+++def test_video_tools_needs_both_binaries_in_the_folder(tmp_path):+ assert video_tools(str(_tool_dir(tmp_path, "ffmpeg"))) is None+ folder = _tool_dir(tmp_path, "ffmpeg", "ffprobe")+ ffmpeg, ffprobe = video_tools(str(folder))+ assert Path(ffmpeg).parent == folder == Path(ffprobe).parent++[email protected](sys.platform != "win32", reason = "Windows PATHEXT lookup")+def test_command_wrappers_do_not_hide_native_ffmpeg(tmp_path, monkeypatch):+ shims = tmp_path / "shims"+ shims.mkdir()+ for name in ("ffmpeg", "ffprobe"):+ (shims / f"{name}.cmd").write_text("@exit /b 0\n", encoding = "utf-8")+ native = _tool_dir(tmp_path, "ffmpeg", "ffprobe")+ monkeypatch.setenv("PATH", os.pathsep.join((str(shims), str(native))))+ monkeypatch.setenv("PATHEXT", ".COM;.EXE;.BAT;.CMD")+ monkeypatch.delenv("LLAMA_ARG_VIDEO_FFMPEG_DIR", raising = False)+ tools = video_tools()+ assert tools is not None+ assert all(Path(tool).parent == native for tool in tools)+ assert _video_ffmpeg_dir_flags(_CAPS) == ([], None)++[email protected](sys.platform != "win32", reason = "Windows application-directory search")+def test_automatic_pinning_does_not_replace_server_local_tools(tmp_path, monkeypatch):+ system = _bin(tmp_path / "system", "ffmpeg", "ffprobe")+ bundled = _bin(tmp_path / "server", "ffmpeg", "ffprobe")+ monkeypatch.setenv("PATH", str(system))+ monkeypatch.delenv("LLAMA_ARG_VIDEO_FFMPEG_DIR", raising = False)+ flags, _ = _video_ffmpeg_dir_flags(_CAPS)+ search = llama_mod._video_tools_search(+ [str(bundled / "llama-server.exe"), *flags], {"PATH": str(system)}, str(tmp_path)+ )+ tools = video_tools(search)+ assert tools is not None+ assert all(Path(tool).parent == bundled for tool in tools)+++def test_the_shrink_uses_the_same_folder(tmp_path, monkeypatch):+ seen = []+ monkeypatch.setattr(llama_video_input, "video_tools", lambda d = None: seen.append(d))+ llama_video_input.shrink_video_for_llama("AAAA", 1024, ffmpeg_dir = "/custom/ffmpeg")+ assert seen == ["/custom/ffmpeg"]+++def test_an_older_build_ignores_the_ffmpeg_dir_env_after_load(tmp_path):+ good = _bin(tmp_path / "good", "ffmpeg", "ffprobe")+ stale = _bin(tmp_path / "stale")+ env = {"PATH": str(good), "LLAMA_ARG_VIDEO_FFMPEG_DIR": str(stale)}+ assert llama_mod._video_tools_reachable(["llama-server"], env, supports_ffmpeg_dir = False)+ assert not llama_mod._video_tools_reachable(["llama-server"], env)+++def test_a_load_without_ffprobe_flags_the_missing_tools(tmp_path, monkeypatch):+ backend = _load_with_video_props(tmp_path, monkeypatch, _bin(tmp_path / "bin", "ffmpeg"))+ assert backend._has_video_input is False+ assert backend._video_needs_ffmpeg is True+++def test_a_load_with_both_tools_does_not_blame_ffmpeg(tmp_path, monkeypatch):+ backend = _load_with_video_props(+ tmp_path, monkeypatch, _bin(tmp_path / "bin", "ffmpeg", "ffprobe")+ )+ assert backend._has_video_input is True+ assert backend._video_needs_ffmpeg is False+++def test_the_shrink_searches_where_the_loaded_child_found_ffmpeg(tmp_path, monkeypatch):+ bin_dir = _bin(tmp_path / "bin", "ffmpeg", "ffprobe")+ backend = _load_with_video_props(tmp_path, monkeypatch, bin_dir)+ monkeypatch.setenv("PATH", str(tmp_path / "elsewhere"))+ ffmpeg, ffprobe = video_tools(backend._video_ffmpeg_dir)+ assert Path(ffmpeg).parent == bin_dir == Path(ffprobe).parent+++def test_the_child_search_follows_the_older_build_rule(tmp_path):+ env = {"PATH": str(tmp_path / "path"), "LLAMA_ARG_VIDEO_FFMPEG_DIR": str(tmp_path / "env")}+ assert llama_mod._video_tools_search(["llama-server"], env) == str(tmp_path / "env")+ search = llama_mod._video_tools_search(["llama-server"], env, supports_ffmpeg_dir = False)+ assert str(tmp_path / "path") in search.split(os.pathsep)+ assert str(tmp_path / "env") not in search.split(os.pathsep)++[email protected]("probe_result", ["timeout", "partial", "empty"])+def test_an_inconclusive_probe_keeps_the_inherited_directory(tmp_path, monkeypatch, probe_result):+ binary = tmp_path / "llama-server"+ binary.write_bytes(b"probe fixture")+ binary.chmod(0o755)++ def run_probe(*args, **kwargs):+ if probe_result == "timeout":+ raise subprocess.TimeoutExpired(args[0], 10)+ return SimpleNamespace(+ stdout = "--top-k N top-k sampling\n" if probe_result == "partial" else "",+ stderr = "",+ returncode = 1 if probe_result == "partial" else 0,+ )++ with monkeypatch.context() as probe_patch:+ probe_patch.setattr(llama_mod.subprocess, "run", run_probe)+ caps = LlamaCppBackend.probe_server_capabilities(str(binary))+ tools = _bin(tmp_path / "tools", "ffmpeg", "ffprobe")+ monkeypatch.setenv("PATH", str(tmp_path / "empty"))+ monkeypatch.setenv("LLAMA_ARG_VIDEO_FFMPEG_DIR", str(tools))+ model_dir = tmp_path / "model"+ model_dir.mkdir()+ backend, gguf = _video_backend(+ model_dir, supports_video_ffmpeg_dir = caps["supports_video_ffmpeg_dir"]+ )+ backend._query_server_props = lambda: {+ "modalities": {"vision": True, "video": True},+ "default_generation_settings": {"n_ctx": 4096},+ }+ _launch(backend, gguf)+ assert backend._has_video_input is True+ assert caps["supports_video_ffmpeg_dir"] is None++[email protected](sys.platform == "win32", reason = "POSIX directory ending in a space")[email protected]("explicit", [False, True])+def test_video_directory_whitespace_is_preserved(tmp_path, monkeypatch, explicit):+ tools = _bin(tmp_path / "tools ", "ffmpeg", "ffprobe")+ monkeypatch.setenv("PATH", str(tools))+ monkeypatch.delenv("LLAMA_ARG_VIDEO_FFMPEG_DIR", raising = False)+ args = ["--video-ffmpeg-dir", str(tools)] if explicit else []+ flags, _ = _video_ffmpeg_dir_flags(_CAPS, extra_args = args)+ assert llama_mod._video_tools_reachable(["llama-server", *flags, *args])++[email protected](sys.platform != "linux", reason = "Linux ELF loader environment")+@needs_ffmpeg+def test_preprocessing_uses_the_running_servers_loader_environment(tmp_path):+ from routes.inference import _shrink_clip_for_llama++ compiler = shutil.which("cc")+ if compiler is None:+ pytest.skip("a C compiler is required for the shared-library fixture")+ ffmpeg, ffprobe = video_tools()+ tools = tmp_path / "bin"+ tools.mkdir()+ marker = tmp_path / "marker.c"+ marker.write_text("int fixture_marker(void) { return 734; }\n", encoding = "utf-8")+ forward = tmp_path / "forward.c"+ forward.write_text(+ "#include <string.h>\n#include <unistd.h>\nextern int fixture_marker(void);\n"+ "int main(int argc, char **argv) {\n"+ "if (fixture_marker() != 734) return 7;\n"+ 'const char *tool = strstr(argv[0], "ffprobe") ? '+ + json.dumps(ffprobe)+ + " : "+ + json.dumps(ffmpeg)+ + ";\nargv[0] = (char *)tool; execv(tool, argv); return 9; }\n",+ encoding = "utf-8",+ )+ subprocess.run(+ [compiler, "-shared", "-fPIC", str(marker), "-o", str(tools / "libffmpeg_fixture.so")],+ check = True,+ capture_output = True,+ )+ subprocess.run(+ [+ compiler,+ str(forward),+ "-L" + str(tools),+ "-lffmpeg_fixture",+ "-o",+ str(tools / "ffmpeg"),+ ],+ check = True,+ capture_output = True,+ )+ shutil.copy2(tools / "ffmpeg", tools / "ffprobe")+ (tools / "llama-server").write_bytes(b"fixture")+ env = LlamaCppBackend._llama_server_env_for_binary(+ str(tools / "llama-server"), use_system_rocm = False+ )+ clip = _clip(tmp_path, "input.mp4", "1280x720")+ process = object()+ backend = SimpleNamespace(+ _process = process,+ _process_env = (process, env),+ _video_ffmpeg_dir = str(tools),+ extra_args = None,+ )+ shrunk = asyncio.run(_shrink_clip_for_llama(clip, backend))+ geometry = _probe(tmp_path, shrunk)+ assert (geometry["width"], geometry["height"]) == (640, 360)+ backend._process_env = (object(), env)+ assert asyncio.run(_shrink_clip_for_llama(clip, backend)) == clipdiff --git a/studio/backend/tests/test_llama_video_frame_budget.py b/studio/backend/tests/test_llama_video_frame_budget.pyindex 8c51999ff2f..5b71f5528bb 100644--- a/studio/backend/tests/test_llama_video_frame_budget.py+++ b/studio/backend/tests/test_llama_video_frame_budget.py@@ -485,7 +485,11 @@ def test_a_machine_without_ffmpeg_forwards_the_clip_untouched(monkeypatch):def test_a_timed_out_shrink_forwards_the_clip_untouched(monkeypatch):monkeypatch.setattr(llama_video_input.shutil, "which", lambda name: f"/bin/{name}")- def timeout(argv, _timeout):+ def timeout(+ argv,+ _timeout,+ env = None,+ ):raise subprocess.TimeoutExpired(argv, _timeout)monkeypatch.setattr(llama_video_input, "_run", timeout)diff --git a/studio/backend/tests/test_media_decode_protocols.py b/studio/backend/tests/test_media_decode_protocols.pyindex 35aa1e1ba5f..96c51b8e395 100644--- a/studio/backend/tests/test_media_decode_protocols.py+++ b/studio/backend/tests/test_media_decode_protocols.py@@ -122,9 +122,13 @@ def test_chat_video_ffmpeg_and_ffprobe_get_a_file_only_whitelist(monkeypatch):):self.returncode, self.stdout, self.stderr = returncode, stdout, b""- def run(argv, _timeout):+ def run(+ argv,+ _timeout,+ env = None,+ ):calls.append(list(argv))- if Path(argv[0]).name == "ffprobe":+ if Path(argv[0]).stem == "ffprobe":geometry = {"streams": [{"width": 4000, "height": 4000, "avg_frame_rate": "10/1"}],"format": {"duration": "5.0"},@@ -138,7 +142,7 @@ def test_chat_video_ffmpeg_and_ffprobe_get_a_file_only_whitelist(monkeypatch):clip = base64.b64encode(b"not really a video").decode("ascii")assert llama_video_input.shrink_video_for_llama(clip, 1 << 20) == clip- assert [Path(argv[0]).name for argv in calls] == ["ffprobe", "ffmpeg"]+ assert [Path(argv[0]).stem for argv in calls] == ["ffprobe", "ffmpeg"]for argv in calls:i = argv.index("-protocol_whitelist")assert argv[i + 1] == "file"diff --git a/studio/backend/tests/test_video_chat_completions_behaviour.py b/studio/backend/tests/test_video_chat_completions_behaviour.pyindex dcd4fe1661f..90761278bfe 100644--- a/studio/backend/tests/test_video_chat_completions_behaviour.py+++ b/studio/backend/tests/test_video_chat_completions_behaviour.py@@ -31,8 +31,14 @@ class _VideoGguf(FakeLlamaCppBackend):is_vision = True_has_video_input = True- def __init__(self, *, has_video = True):+ def __init__(+ self,+ *,+ has_video = True,+ needs_ffmpeg = False,+ ):self._has_video_input = has_video+ self._video_needs_ffmpeg = needs_ffmpegself.dispatched: list[dict] = []def generate_chat_completion(self, **kwargs):@@ -231,6 +237,17 @@ def test_a_gguf_without_a_video_projector_refuses_either_spelling(monkeypatch, bassert "cannot take video input" in _detail(response)[email protected]("body", [_part_body(_DATA_URI), _field_body()])+def test_a_video_model_without_ffmpeg_is_refused_naming_ffmpeg(monkeypatch, body):+ backend = _VideoGguf(has_video = False, needs_ffmpeg = True)+ with _client(monkeypatch, backend) as client:+ response = client.post("/v1/chat/completions", json = body)+ assert response.status_code == 400+ assert "ffmpeg and ffprobe were not found" in _detail(response)+ assert "--video-ffmpeg-dir" in _detail(response)+ assert backend.dispatched == []++@pytest.mark.parametrize("body", [_part_body(_DATA_URI), _field_body()])def test_a_non_gguf_backend_is_offered_the_clip_rather_than_refused_outright(monkeypatch, body):"""A blanket not using_gguf refusal would break working MLX and transformers video on macOS."""@@ -774,6 +791,8 @@ def test_a_part_carried_clip_is_transcoded_like_the_legacy_field(monkeypatch):cap,*,sampled_fps = None,+ ffmpeg_dir = None,+ env = None,):seen.append(clip)return "SHRUNK"