Skip to content

Local video editor for coding agents: 42 FFmpeg tools with a machine-readable contract and an MCP server, for Claude Code, Cursor and Codex. Cut, captions, reframe, loudness, platform exports. No cloud, no API keys.

doctor: add font-availability detection for drawtext defaults (#71)

Shogo Kajiyama335ec73856b7
diff --git a/docs/contract.md b/docs/contract.md
index 7832fe1..191cdb6 100644
--- a/docs/contract.md
+++ b/docs/contract.md
@@ -220,6 +220,17 @@ encode, which this introspection never runs). No tool declares or requires a GPU
the same honest yes/no/unknown question about GPU support that filter/encoder detection already
answers for everything else, without a tool here needing to use one.
+`doctor`'s `fonts` field reports whether the default drawtext font (`caption.py`'s
+`--animate`/`--karaoke`, `graphics.py`'s templates — `BRAND_DEFAULTS["font"]`, `"DejaVu Sans"`)
+is actually installed — `{"default_font": "...", "status": "available"|"missing"|"unknown",
+"detail": "..."}`. drawtext's `font=` is a fontconfig name lookup, and fontconfig silently
+substitutes the closest match for *any* name, known or not — a missing font never fails the
+encode, so drawtext's own exit code cannot detect it. `fc-match` is queried instead: `available`
+when it resolves the name to itself, `missing` when it substitutes a different family, `unknown`
+when `fc-match` itself is not on PATH or fails. Like `gpu_encoders`, this is purely informational
+and never affects `ok` or any tool's `usable` — a substituted font is not a broken tool, just a
+typeface the caller didn't ask for.
+
## Invocation
Structured arguments are the canonical way to call a tool, on the CLI or through MCP.
diff --git a/scripts/_contract.py b/scripts/_contract.py
index ac1575d..1fad428 100644
--- a/scripts/_contract.py
+++ b/scripts/_contract.py
@@ -477,6 +477,44 @@ def _whisper_available() -> bool:
return importlib.util.find_spec("faster_whisper") is not None or importlib.util.find_spec("whisper") is not None
+def _default_font() -> str:
+ from _common import BRAND_DEFAULTS
+ return str(BRAND_DEFAULTS["font"])
+
+
+def _font_available(font_name: str) -> Dict[str, Any]:
+ """Whether `font_name` (a fontconfig family name, as passed to drawtext's `font=`) is actually
+ installed, distinct from silently resolving to a substitute.
+
+ This cannot be answered by running drawtext and checking its exit code: fontconfig substitutes
+ the closest match for ANY name, known or not, so `ffmpeg -vf drawtext=font='<garbage>'` still
+ exits 0 (verified against this repo's own sandbox ffmpeg -- a deliberately bogus family name
+ produces the same success exit code as "DejaVu Sans"). That is exactly the "false success" this
+ capability exists to catch (see issue #66): a missing font never fails the encode, it just
+ silently renders with a different typeface. `fc-match` is queried instead, since it reports the
+ family fontconfig actually resolved to; that only equals the request when the font is installed.
+ """
+ exe = shutil.which("fc-match")
+ if not exe:
+ return {"status": "unknown", "detail": "fc-match not on PATH; drawtext succeeding proves nothing (fontconfig substitutes silently), so availability cannot be verified"}
+ try:
+ proc = subprocess.run([exe, "--format=%{family}\n", font_name], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=_DETECT_TIMEOUT)
+ except subprocess.TimeoutExpired:
+ return {"status": "unknown", "detail": f"fc-match did not exit within {_DETECT_TIMEOUT}s"}
+ except OSError as e:
+ return {"status": "unknown", "detail": f"fc-match: {e}"}
+ if proc.returncode != 0:
+ tail = " ".join(proc.stderr.strip().splitlines()[-2:])
+ return {"status": "unknown", "detail": f"fc-match exited {proc.returncode}: {tail}"}
+ lines = [l for l in proc.stdout.splitlines() if l.strip()]
+ resolved = lines[0].strip() if lines else ""
+ if not resolved:
+ return {"status": "unknown", "detail": "fc-match produced no output"}
+ if resolved.lower() == font_name.lower():
+ return {"status": "available", "detail": f"fc-match resolves '{font_name}' to itself"}
+ return {"status": "missing", "detail": f"fc-match substitutes '{resolved}' for '{font_name}' -- '{font_name}' is not installed"}
+
+
def required_capabilities() -> Dict[str, List[str]]:
req: set = set()
opt: set = set()
@@ -507,6 +545,13 @@ def doctor() -> Dict[str, Any]:
still assumes CPU x264/x265 -- so `gpu_encoders` never affects `ok` or any tool's `usable`. It
only proves the build shipped the capability, never that the GPU/driver on this machine will
actually accept a job (that needs a real encode, which this introspection never runs).
+
+ `fonts` is the same kind of informational answer for the default drawtext font (caption.py's
+ --animate/--karaoke, graphics.py's templates -- see issue #66): available/missing/unknown for
+ whether BRAND_DEFAULTS["font"] ("DejaVu Sans") is actually installed, not silently substituted
+ by fontconfig. It never affects `ok` or a tool's `usable` -- a missing font is not a broken
+ tool, drawtext still runs and still writes an artifact, it may just render with a different
+ typeface than requested (which is why this exists: that substitution is otherwise invisible).
"""
listings = {
"encoders": _ff_listing("ffmpeg", "-encoders"),
@@ -560,9 +605,16 @@ def doctor() -> Dict[str, Any]:
"ok": not missing_required and not unknown_required,
"tools": _tool_usability(state),
"gpu_encoders": _gpu_encoders(listings["encoders"]),
+ "fonts": _fonts_capability(),
}
+def _fonts_capability() -> Dict[str, Any]:
+ font = _default_font()
+ result = _font_available(font)
+ return {"default_font": font, "status": result["status"], "detail": result["detail"]}
+
+
def _capability_fix_hint(cap: str) -> str:
"""One-line, plain-language remedy for a single missing/unknown capability."""
if cap in ("ffmpeg", "ffprobe"):
@@ -881,6 +933,8 @@ def main() -> int:
gpu = d["gpu_encoders"]
if gpu["status"] == "parsed":
print(f"GPU-backed encoders in this build: {', '.join(gpu['present']) or 'none'} (no tool here uses one yet; this build-presence check does not prove the GPU/driver will accept a job)")
+ fonts = d["fonts"]
+ print(f"default drawtext font '{fonts['default_font']}': {fonts['status']} ({fonts['detail']})")
for err in d["errors"]:
print(f"detection error: {err}", file=sys.stderr)
if d["ok"]:
diff --git a/tests/test_contract.py b/tests/test_contract.py
index 893cf07..d23d0f3 100644
--- a/tests/test_contract.py
+++ b/tests/test_contract.py
@@ -1088,6 +1088,74 @@ class DoctorDetectionTests(unittest.TestCase):
self.assertNotEqual(d_fail["gpu_encoders"]["status"], "parsed")
self.assertEqual(d_fail["gpu_encoders"]["present"], [])
+ # ------------------------------------------------------------------- font availability (issue #66)
+ def _fc_match_shim(self, script_body):
+ """PATH with a fake fc-match on it, real ffmpeg/ffprobe/everything else untouched."""
+ shim = self.work / "fcshim"
+ shim.mkdir(exist_ok=True)
+ (shim / "fc-match").write_text("#!/bin/sh\n" + script_body)
+ (shim / "fc-match").chmod(0o755)
+ return dict(os.environ, PATH=f"{shim}:{os.environ['PATH']}")
+
+ def test_default_drawtext_font_matches_this_sandboxs_real_fc_match(self):
+ """Exercises the genuine, unmocked fc-match path end to end -- but this repo's own CI only
+ installs fonts-dejavu-core on the Linux leg (see issue #66 this detector was built for), so
+ DejaVu Sans is only actually present on Linux; macOS/Windows CI resolve it to a substituted
+ family. Rather than hardcode "available" (which is only true on one of three CI platforms
+ and would make this very test repeat the issue's own bug), ask fc-match directly for the
+ ground truth and assert doctor's classification matches reality on whichever platform this
+ runs on."""
+ if shutil.which("fc-match") is None:
+ self.skipTest("no fontconfig on this machine")
+ d, code = self._doctor("ffmpeg_filters_6.1.txt")
+ self.assertEqual(d["fonts"]["default_font"], "DejaVu Sans")
+ resolved = subprocess.run(["fc-match", "--format=%{family}\n", "DejaVu Sans"],
+ stdout=subprocess.PIPE, text=True).stdout.splitlines()[0].strip()
+ expected = "available" if resolved == "DejaVu Sans" else "missing"
+ self.assertEqual(d["fonts"]["status"], expected, d["fonts"])
+ self.assertIn(resolved, d["fonts"]["detail"])
+ # informational only: a missing/available font never affects ok or any tool's usable
+ self.assertTrue(d["ok"])
+
+ def test_missing_font_is_reported_missing_not_unknown(self):
+ """A real fc-match that substitutes a different family for the request: reported `missing`,
+ the same "silent substitution is the risk" case drawtext's own exit code can never catch."""
+ env = self._fc_match_shim("echo 'Liberation Sans'\nexit 0\n")
+ proc = sh(sys.executable, SCRIPTS / "_contract.py", "doctor", "--json", env=env, check=False)
+ d = json.loads(proc.stdout)
+ self.assertEqual(d["fonts"]["status"], "missing")
+ self.assertIn("Liberation Sans", d["fonts"]["detail"])
+ self.assertIn("DejaVu Sans", d["fonts"]["detail"])
+ self.assertTrue(d["ok"], "a missing default font never fails doctor's ok -- caption/graphics still run, just with a substituted typeface")
+
+ def test_font_detection_failure_is_unknown_not_missing(self):
+ """fc-match exiting non-zero, or absent entirely, is `unknown` -- never folded into `missing`
+ (same three-state invariant as every other capability doctor detects)."""
+ env = self._fc_match_shim("exit 1\n")
+ proc = sh(sys.executable, SCRIPTS / "_contract.py", "doctor", "--json", env=env, check=False)
+ d = json.loads(proc.stdout)
+ self.assertEqual(d["fonts"]["status"], "unknown")
+
+ # fc-match not on PATH at all
+ stripped = os.pathsep.join(p for p in os.environ["PATH"].split(os.pathsep) if not (Path(p) / "fc-match").exists())
+ env2 = dict(os.environ, PATH=stripped)
+ proc2 = sh(sys.executable, SCRIPTS / "_contract.py", "doctor", "--json", env=env2, check=False)
+ d2 = json.loads(proc2.stdout)
+ self.assertEqual(d2["fonts"]["status"], "unknown")
+ self.assertIn("fc-match", d2["fonts"]["detail"])
+
+ def test_font_capability_is_informational_like_gpu_encoders(self):
+ """fonts, like gpu_encoders, is reported but never gates ok/usable -- it answers a question
+ none of the required/optional capabilities ask."""
+ declared = set(_contract.required_capabilities()["required"] + _contract.required_capabilities()["optional"])
+ self.assertFalse(any(c.startswith("font:") for c in declared), "font availability is informational, not a required/optional capability")
+ env = self._fc_match_shim("echo 'Liberation Sans'\nexit 0\n")
+ proc = sh(sys.executable, SCRIPTS / "_contract.py", "doctor", "--json", env=env, check=False)
+ d = json.loads(proc.stdout)
+ self.assertTrue(d["ok"])
+ for tool_name in ("caption", "graphics"):
+ self.assertEqual(d["tools"][tool_name]["usable"], "yes")
+
if __name__ == "__main__":
unittest.main(verbosity=2)