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.

fix drawtext crash on Windows fontconfig resolution (#101)

Shogo Kajiyama87c84f23b454
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d868ffa..b1a3d47 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,37 @@
(nothing yet)
+## 0.12.5 — fix Windows `drawtext` crash (#100), and 4 smaller review findings
+
+`look.py`, `scenes.py --sheet`, `overlay.py --text` and `graphics.py` could crash on real Windows
+FFmpeg builds (confirmed on winget's gyan.dev 9.x): `drawtext`'s own fontconfig resolution dies
+with an access violation whenever it has to resolve a font by family name, with or without a
+valid `fonts.conf` — and `doctor` reported `missing required: none`, since `-filters` correctly
+lists `drawtext` as present; the crash only ever surfaced as a runtime failure, the exact thing
+the step-0 capability check exists to prevent.
+
+- All four tools now resolve a concrete font file by default (`default_font_file()` in
+ `_common.py`: a well-known system font path on Windows, `fc-match` on Linux/macOS) and emit
+ `fontfile=` instead of `font=` whenever one can be found — `fontfile=` skips fontconfig
+ entirely, the one form confirmed not to crash. `font=` remains the fallback when nothing can be
+ resolved, unchanged from before.
+- `doctor` now actually renders one frame through `drawtext` instead of trusting the `-filters`
+ listing alone. A confirmed crash (killed by signal on POSIX, an access-violation-style exit on
+ Windows) downgrades `filter:drawtext` from "listed" to `missing`, with the crash detail in
+ `errors[]`; an ordinary nonzero exit proves nothing either way and leaves the listing-based
+ result standing (same "unknown is not missing" principle used everywhere else in capability
+ detection).
+- `scenes.py --sheet` gained `--no-timecode`, matching `look.py`, as a way out if drawtext is
+ ever genuinely unusable on a machine.
+- Fixed a `SyntaxWarning: invalid escape sequence '\;'` in `_common.py`'s `shell_quote()` (a stray
+ backslash before an already-unescaped character; harmless today, an error in a future Python).
+- README's Quick Start script examples now note that Windows/Git Bash needs `python`, not
+ `python3` (`bin/install.js` and `doctor`/`contract` already handled this; the raw examples
+ didn't say so).
+- SKILL.md's Gotchas section documents the crash and the fixes above.
+
+Thanks to [@willy92wins](https://github.com/willy92wins) for the detailed repro in #100.
+
## 0.12.4 — `stabilize.py` gains `--tripod` and `--crop` (#96)
A follow-on audit of the same class of gap 0.12.3 closed in `color.py --correct`: scripts that
diff --git a/CRITICAL_ISSUES.md b/CRITICAL_ISSUES.md
index f5805f1..9514712 100644
--- a/CRITICAL_ISSUES.md
+++ b/CRITICAL_ISSUES.md
@@ -1,37 +1,34 @@
# Identified Issues for ffmpeg-skill
## Summary
-Found 5 issues during code review. Issue #100 (Windows drawtext crash) is already reported.
+Found 5 issues during code review, overlapping with #100 (Windows drawtext crash). All five are now addressed.
-## New Issues to Create
+## Issues
-### Issue 1: Python 3.14+ SyntaxWarning on invalid escape sequence
+### Issue 1: Python 3.14+ SyntaxWarning on invalid escape sequence — Fixed
- **File**: `_common.py:342`
- **Problem**: `" \t\\"'\\;|&<>()[]{}$*?"` contains invalid escape sequence `\;`
- **Severity**: Medium (will become error in Python 3.14+)
-- **Fix**: Use raw string or properly escape
+- **Fix**: dropped the stray backslash before `;` (it was already a plain, unescaped character everywhere else in that string)
-### Issue 2: Windows Python documentation gap
-- **Location**: README examples, SKILL.md
+### Issue 2: Windows Python documentation gap — Fixed
+- **Location**: README examples
- **Problem**: Examples show `python3` but Windows Git Bash only recognizes `python`
-- **Severity**: Low (confuses Windows users)
-- **Note**: `bin/install.js` handles this correctly; docs should too
+- **Fix**: added a note next to the Quick Start script examples pointing Windows/Git Bash users at `python` instead; `bin/install.js` and `doctor`/`contract` already handled this, only the raw script-example block needed it spelled out
-### Issue 3: FFmpeg capability detection incomplete for drawtext
-- **Problem**: `doctor` reports `missing required: none` but `drawtext` crashes at runtime on Windows
-- **Severity**: High (violates design principle of early failure detection)
-- **Suggested fix**: Add runtime probe to `doctor` for drawtext
+### Issue 3: FFmpeg capability detection incomplete for drawtext — Fixed
+- **Problem**: `doctor` reported `missing required: none` but `drawtext` crashes at runtime on Windows
+- **Fix**: `doctor` now actually renders one frame through `drawtext` (`_drawtext_probe()` in `scripts/_contract.py`) instead of trusting the `-filters` listing alone. A crash (killed by signal on POSIX, an access-violation-style exit on Windows) downgrades `filter:drawtext` from "listed" to `missing`, with the crash detail surfaced in `errors[]`; an ordinary nonzero exit (including every existing fixture-driven test's fake ffmpeg) leaves the listing-based result standing, since that proves nothing either way
-### Issue 4: Font error messages lack context
+### Issue 4: Font error messages lack context — Mitigated, not directly fixed
- **Problem**: Fontconfig errors don't indicate actual cause (missing fontfile, invalid fonts.conf)
-- **Severity**: Medium (hard to debug)
- **Impact**: All drawtext tools (look.py, scenes.py, overlay.py, graphics.py)
+- **What changed**: all four tools now resolve a concrete `--font-file` by default (`default_font_file()` in `_common.py`) and emit `fontfile=` instead of `font=` whenever one can be found — this is the root-cause fix for #100 (fontconfig's own resolution is what crashes; `fontfile=` skips it entirely), so in practice the fontconfig error path this issue describes should rarely be hit anymore. The underlying ffmpeg/fontconfig error text itself is unchanged when it does still occur.
-### Issue 5: SKILL.md missing Windows drawtext limitations
+### Issue 5: SKILL.md missing Windows drawtext limitations — Fixed
- **Location**: SKILL.md Gotchas section
- **Problem**: No mention of Windows-specific `drawtext` + fontconfig issues
-- **Severity**: Medium (Windows users encounter Issue #100 with no warning)
-- **Suggested addition**: Document fontfile= requirement on Windows
+- **Fix**: added a Gotchas entry describing the crash, the automatic `fontfile=` default that now covers it, and the `--font-file` / `doctor` escape hatches if it still happens
## Related
-- Issue #100: "drawtext access-violates on Windows" (currently open)
+- Issue #100: "drawtext access-violates on Windows" — the root-cause fix (fontfile= by default across look/scenes/overlay/graphics, plus doctor's real drawtext probe) closes this.
diff --git a/README.md b/README.md
index 67e360a..fb2fbf0 100644
--- a/README.md
+++ b/README.md
@@ -100,6 +100,8 @@ python3 $S/fit.py input.mp4 --duration 60 --aspect 9:16 --dry-run # print the
python3 $S/export.py input.mp4 --preset reels --json # structured result with a probe of the output
```
+On Windows in Git Bash, `python3` is only on PATH if Python was installed from the Microsoft Store; a python.org install exposes `python` (or the `py` launcher) instead — replace `python3` with `python` above if you see a "command not found". `bin/install.js` and `doctor`/`contract` already handle this for you; only the raw script examples above need it spelled out manually.
+
More requests and the commands behind them: [examples/README.md](examples/README.md). To see everything run end-to-end on generated footage: `npm run demo`.
## How it works
diff --git a/SKILL.md b/SKILL.md
index dc6c936..3a47bf0 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -299,6 +299,18 @@ Every script prints `{"status": "failed", "error": {"kind": input | ffmpeg | out
`caption.py --fonts-dir ./fonts --font "Noto Sans CJK JP"`). Without a
matching font you get boxes, not an error. Install: `apt install fonts-noto-cjk`,
`brew install --cask font-noto-sans-cjk`.
+- **Windows drawtext crashes on some real builds.** On certain Windows ffmpeg
+ builds (e.g. winget's gyan.dev), `drawtext` crashes with an access violation
+ whenever it resolves a font by family name through fontconfig, even with a
+ valid `fonts.conf` (#100). `look.py`, `scenes.py --sheet`, `overlay.py --text`
+ and `graphics.py` all resolve a concrete `--font-file` by default when one is
+ available (`fontfile=` skips fontconfig entirely and is the form confirmed
+ not to crash), so this should already be handled automatically. If a
+ drawtext tool still crashes, pass `--font-file` explicitly rather than
+ relying on `--font`/`font=` resolution; `doctor` also runs a real one-frame
+ drawtext probe and reports `filter:drawtext` missing (with the crash detail
+ in `errors[]`) rather than a false "available" from the `-filters` listing
+ alone.
- **Keyframe cuts.** A lossless `cut.py` result may start up to one GOP (often
1–10 s) earlier than requested; the script re-encodes automatically when the
deviation exceeds 0.5 s. If the user insists on lossless output, pass
diff --git a/docs/contract.md b/docs/contract.md
index 80a7a59..588b4c7 100644
--- a/docs/contract.md
+++ b/docs/contract.md
@@ -21,7 +21,7 @@ The contract is derived from the code that runs, not maintained beside it:
| Field | Meaning | Changes when |
|---|---|---|
| `contract_version` | shape of this document (`1.0`) | a key is renamed, removed or changes meaning |
-| `skill.version` | the npm / package.json version (`0.12.4`) | any release |
+| `skill.version` | the npm / package.json version (`0.12.5`) | any release |
A release that adds a tool or a flag keeps `contract_version`; a breaking change to the
ToolSpec shape bumps it. Consumers pin on `contract_version` and read `skill.version`
@@ -39,7 +39,7 @@ drifting silently.
```json
{
"contract_version": "1.0",
- "skill": {"id": "ffmpeg-skill", "version": "0.12.4", "execution_mode": "local", "kind": "execution",
+ "skill": {"id": "ffmpeg-skill", "version": "0.12.5", "execution_mode": "local", "kind": "execution",
"entrypoints": {"cli": "...", "mcp": "...", "contract": "...", "doctor": "..."},
"not_provided": ["AI reasoning", "decisions", "production plans", "project IR", "approvals", "network access", "transcription engine"]},
"requirements": {"python": ">=3.9 (standard library only)", "ffmpeg": ">=5.0", "ffprobe": ">=5.0"},
diff --git a/package.json b/package.json
index 25d158c..44407c3 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "ffmpeg-skill",
- "version": "0.12.4",
+ "version": "0.12.5",
"description": "Agent Skill that gives coding agents (Claude Code, Cursor, Codex) a local video editor: 28 FFmpeg tools with a machine-readable contract, contract-derived MCP server, FFmpeg capability detection, probe-first / verify-last workflow. Cut, join, silence removal, fit, captions and karaoke, overlays, motion graphics, HDR to SDR, LUTs, audio clean-up and typed dynamics, sync with drift correction, multicam, loudness, delivery checks, project rendering, batch. No API keys, no cloud, no dependencies.",
"keywords": [
"ffmpeg",
diff --git a/scripts/_common.py b/scripts/_common.py
index 26f3401..bb5d9cb 100755
--- a/scripts/_common.py
+++ b/scripts/_common.py
@@ -339,7 +339,7 @@ def _run_with_progress(cmd: List[str], check: bool) -> subprocess.CompletedProce
def shell_quote(s: str) -> str:
- if not s or any(ch in s for ch in " \t\"'\;|&<>()[]{}$*?"):
+ if not s or any(ch in s for ch in " \t\\\"';|&<>()[]{}$*?"):
return "'" + s.replace("'", "'\\''") + "'"
return s
@@ -598,6 +598,43 @@ def escape_filter_path(path: str) -> str:
return p
+def default_font_file(font_name: str) -> Optional[str]:
+ """Resolve `font_name` to a concrete on-disk font file, so a caller can tell drawtext
+ `fontfile=<path>` instead of `font=<name>`, when possible.
+
+ On some real Windows ffmpeg builds (winget's gyan.dev 9.x), drawtext's own fontconfig
+ resolution crashes with an access violation whenever it has to resolve a font by family name
+ -- with or without a valid fonts.conf on FONTCONFIG_FILE. `fontfile=` is the only form
+ confirmed not to crash (#100), since it never touches fontconfig at all. `font_name` itself is
+ ignored on Windows for that reason: a fixed, near-universally-present system font is used
+ instead of trying to resolve the requested family (which would crash the same way).
+
+ On Linux/macOS this is best-effort and uses the real requested family: `fc-match` reports the
+ same file fontconfig would resolve `font_name` to anyway, so a caller gets the identical font,
+ just already resolved to a path -- fontfile= skips a redundant fontconfig lookup and equally
+ sidesteps the same class of crash if it exists on some build there too, but the fallback below
+ (returning None) is exercised routinely there, not just on failure.
+
+ Returns None when nothing could be resolved (fc-match missing/unavailable, or no well-known
+ Windows font file present); the caller falls back to font=<font_name>, the prior behaviour.
+ """
+ if platform.system() == "Windows":
+ windir = os.environ.get("WINDIR", "C:\\Windows")
+ candidate = Path(windir) / "Fonts" / "arial.ttf"
+ return str(candidate) if candidate.exists() else None
+ exe = shutil.which("fc-match")
+ if not exe:
+ return None
+ try:
+ proc = subprocess.run([exe, "--format=%{file}\n", font_name], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=5)
+ except (subprocess.TimeoutExpired, OSError):
+ return None
+ if proc.returncode != 0:
+ return None
+ path = proc.stdout.splitlines()[0].strip() if proc.stdout.strip() else ""
+ return path if path and os.path.exists(path) else None
+
+
def escape_drawtext(text: str) -> str:
return (
text.replace("\\", "\\\\")
diff --git a/scripts/_contract.py b/scripts/_contract.py
index 04e797b..1d985a2 100644
--- a/scripts/_contract.py
+++ b/scripts/_contract.py
@@ -483,6 +483,50 @@ def _default_font() -> str:
return str(BRAND_DEFAULTS["font"])
+def _drawtext_probe() -> Dict[str, Any]:
+ """Actually render one frame through drawtext, rather than trusting `-filters` alone.
+
+ `-filters` only reports whether this ffmpeg build was compiled with the filter; it never
+ proves drawtext can actually execute. On some real Windows ffmpeg builds (winget's gyan.dev
+ 9.x), drawtext crashes with an access violation whenever it has to resolve a font through
+ fontconfig -- with or without a valid fonts.conf -- so `-filters` correctly reports drawtext
+ present and doctor used to report the capability `available` anyway; every tool that actually
+ used it (look, scenes --sheet, overlay --text, graphics) then crashed on first real use (#100).
+
+ This runs the cheapest real drawtext render there is: a one-frame synthetic clip, no font=
+ given at all (ffmpeg's own default resolution -- the same path that crashed). A clean exit
+ means drawtext genuinely works here. Anything that could not prove either way (no ffmpeg,
+ timeout, an ordinary nonzero exit with a real ffmpeg error) is `unknown`, same "unknown is not
+ missing" principle as every other capability here. A crash specifically -- killed by signal on
+ POSIX, or an unhandled access violation surfacing as a huge unsigned exit code on Windows -- is
+ the one case this function exists to catch, and folds into `missing`: the filter is present in
+ the build but cannot actually be used as ffmpeg's own default would use it.
+ """
+ exe = shutil.which("ffmpeg")
+ if not exe:
+ return {"status": "unknown", "detail": "ffmpeg not on PATH"}
+ try:
+ proc = subprocess.run(
+ [exe, "-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "color=c=black:s=64x64:d=1",
+ "-vf", "drawtext=text=x", "-frames:v", "1", "-f", "null", "-"],
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=_DETECT_TIMEOUT,
+ )
+ except subprocess.TimeoutExpired:
+ return {"status": "unknown", "detail": f"drawtext probe did not exit within {_DETECT_TIMEOUT}s"}
+ except OSError as e:
+ return {"status": "unknown", "detail": f"drawtext probe: {e}"}
+ if proc.returncode == 0:
+ return {"status": "available", "detail": "one-frame drawtext render succeeded"}
+ if proc.returncode < 0 or proc.returncode >= 0x80000000:
+ return {"status": "missing",
+ "detail": f"drawtext render crashed (exit {proc.returncode}) instead of failing cleanly -- "
+ "the filter is present in this build but cannot be used as-is, likely a fontconfig "
+ "resolution crash (see https://github.com/kajisho5/ffmpeg-skill/issues/100); "
+ "pass an explicit --font-file to every drawtext tool as a workaround"}
+ tail = " ".join(proc.stderr.strip().splitlines()[-2:])
+ return {"status": "unknown", "detail": f"drawtext probe exited {proc.returncode}: {tail}"}
+
+
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.
@@ -562,6 +606,7 @@ def doctor() -> Dict[str, Any]:
sets = {k: set(v["names"]) for k, v in listings.items()}
state: Dict[str, str] = {} # capability -> available | missing | unknown
wanted = required_capabilities()
+ drawtext_probe: Optional[Dict[str, Any]] = None
def _from(kind: str, name: str) -> str:
lst = listings[kind]
@@ -578,6 +623,23 @@ def doctor() -> Dict[str, Any]:
state[cap] = "available" if shutil.which("ffprobe") else "missing"
elif cap.startswith("encoder:"):
state[cap] = _from("encoders", cap[8:])
+ elif cap == "filter:drawtext":
+ listing_state = _from("filters", "drawtext")
+ if listing_state == "available":
+ # Only escalate an "available" listing to "missing" on an unambiguous crash --
+ # an ordinary nonzero exit (a real ffmpeg's own -h/-filters-only build variance, or
+ # in tests a fake ffmpeg shim that only implements -filters/-encoders/-bsfs/-version)
+ # proves nothing either way, so it leaves the listing-based result standing rather
+ # than downgrading it; see _drawtext_probe()'s own docstring for why a crash alone
+ # is the one case this exists to catch.
+ probe = _drawtext_probe()
+ if probe["status"] == "missing":
+ drawtext_probe = probe
+ state[cap] = "missing"
+ else:
+ state[cap] = "available"
+ else:
+ state[cap] = listing_state
elif cap.startswith("filter:"):
state[cap] = _from("filters", cap[7:])
elif cap.startswith("bsf:"):
@@ -592,6 +654,8 @@ def doctor() -> Dict[str, Any]:
unknown = sorted(c for c, st in state.items() if st == "unknown")
unknown_required = [c for c in unknown if c in wanted["required"]]
errors = [f"{k}: {v['detail']}" for k, v in listings.items() if v["status"] in ("unparsed", "failed")]
+ if drawtext_probe is not None and drawtext_probe["status"] != "available":
+ errors.append(f"filter:drawtext: {drawtext_probe['detail']}")
return {
"version": skill_version(),
"python": ".".join(str(x) for x in sys.version_info[:3]),
@@ -631,6 +695,12 @@ def _capability_fix_hint(cap: str) -> str:
full_hint = "install/build ffmpeg with it enabled"
if cap.startswith("encoder:"):
return f"this ffmpeg build has no {cap[8:]} encoder; {full_hint}"
+ if cap == "filter:drawtext":
+ return ("drawtext crashed instead of rendering a frame (see errors[] for the exit detail) -- "
+ "every drawtext tool already resolves a concrete font file automatically when one can "
+ "be found (#100); if it still crashes, use --no-timecode with look.py or scenes.py "
+ "--sheet to skip drawtext entirely, or pass --font-file explicitly to overlay.py/"
+ "graphics.py (the two that accept it) rather than relying on font= resolution")
if cap.startswith("filter:"):
return f"this ffmpeg build has no {cap[7:]} filter; {full_hint}"
if cap.startswith("bsf:"):
diff --git a/scripts/graphics.py b/scripts/graphics.py
index 7ffd1b4..3732157 100755
--- a/scripts/graphics.py
+++ b/scripts/graphics.py
@@ -21,7 +21,7 @@ import argparse
import sys
from typing import List, Optional
-from _common import aac_args, add_common, apply_common, cfr_args, color_hex, default_output, die, emit, escape_drawtext, escape_filter_path, ffmpeg_base, info, load_brand, parse_time, probe, run, run_keeping_subtitles, video_args
+from _common import aac_args, add_common, apply_common, cfr_args, color_hex, default_font_file, default_output, die, emit, escape_drawtext, escape_filter_path, ffmpeg_base, info, load_brand, parse_time, probe, run, run_keeping_subtitles, video_args
TEMPLATES = ["lower-third", "title", "chapter", "progress", "countdown", "bug"]
@@ -33,6 +33,9 @@ def ff_color(hex_rgb: str, alpha: float = 1.0) -> str:
def font_opts(brand: dict, font: Optional[str], font_file: Optional[str]) -> str:
if font_file or brand.get("font_file"):
return f"fontfile={escape_filter_path(font_file or brand['font_file'])}"
+ resolved = default_font_file(font or brand.get("font", "DejaVu Sans"))
+ if resolved:
+ return f"fontfile={escape_filter_path(resolved)}"
return f"font='{font or brand.get('font', 'DejaVu Sans')}'"
diff --git a/scripts/look.py b/scripts/look.py
index 5bfec8f..be76586 100755
--- a/scripts/look.py
+++ b/scripts/look.py
@@ -15,7 +15,7 @@ import sys
from pathlib import Path
from typing import List
-from _common import add_common, apply_common, die, emit, escape_drawtext, ffmpeg_base, info, parse_time, probe, run
+from _common import add_common, apply_common, default_font_file, die, emit, escape_drawtext, escape_filter_path, ffmpeg_base, info, parse_time, probe, run
FONT = "fontcolor=white:fontsize=h/18:box=1:[email protected]:boxborderw=6:x=8:y=8"
@@ -26,8 +26,8 @@ def fmt_hms(sec: float) -> str:
return f"{int(h):02d}:{int(m):02d}:{s_:06.3f}"
-def timecode_filter() -> str:
- return f"drawtext=text='%{{pts\\:hms}}':{FONT}"
+def timecode_filter(font_prefix: str) -> str:
+ return f"drawtext=text='%{{pts\\:hms}}':{font_prefix}{FONT}"
def main() -> int:
@@ -49,7 +49,12 @@ def main() -> int:
dur = meta.get("duration") or 0.0
stem = Path(args.input).stem
outdir = str(Path(args.output).parent) if args.output else str(Path(args.input).parent)
- tc = "" if args.no_timecode else "," + timecode_filter()
+ # a resolvable font file, given as fontfile=, is the only form confirmed not to crash drawtext's
+ # own fontconfig resolution on some real Windows ffmpeg builds (#100); font= is the fallback when
+ # nothing can be resolved, unchanged from before this existed.
+ default_font = default_font_file("DejaVu Sans")
+ font_prefix = f"fontfile={escape_filter_path(default_font)}:" if default_font else ""
+ tc = "" if args.no_timecode else "," + timecode_filter(font_prefix)
# HDR sources: tone-map for the PNG so the agent judges representative colours, not raw HLG/PQ
if meta["video"].get("hdr"):
v = meta["video"]
@@ -67,8 +72,8 @@ def main() -> int:
sec = parse_time(t)
out = args.output or os.path.join(outdir, f"{stem}_vs_{Path(args.compare).stem}_{sec:.3f}s.png")
half = args.width // 2
- stamp = "" if args.no_timecode else f",drawtext=text='{escape_drawtext(fmt_hms(sec))}':{FONT}"
- tcs = tc.replace("," + timecode_filter(), "") + stamp
+ stamp = "" if args.no_timecode else f",drawtext=text='{escape_drawtext(fmt_hms(sec))}':{font_prefix}{FONT}"
+ tcs = tc.replace("," + timecode_filter(font_prefix), "") + stamp
fc = (f"[0:v]scale={half}:-2{tcs}[a];[1:v]scale={half}:-2{tcs}[b];"
f"[a][b]scale2ref=w=iw:h=ih[a2][b2];[a2][b2]hstack=inputs=2[out]")
cmd = ffmpeg_base() + ["-ss", f"{sec:.3f}", "-i", args.input, "-ss", f"{sec:.3f}", "-i", args.compare,
@@ -81,8 +86,8 @@ def main() -> int:
if dur and sec > dur:
die(f"--at {t} is beyond the duration ({dur:.2f}s)")
out = os.path.join(outdir, f"{args.output and Path(args.output).stem or stem}_{sec:.3f}s.png")
- stamp = "" if args.no_timecode else f",drawtext=text='{escape_drawtext(fmt_hms(sec))}':{FONT}"
- cmd = ffmpeg_base() + ["-ss", f"{sec:.3f}", "-i", args.input, "-vf", f"scale={args.width}:-2{tc.replace(',' + timecode_filter(), '')}{stamp}", "-frames:v", "1", out]
+ stamp = "" if args.no_timecode else f",drawtext=text='{escape_drawtext(fmt_hms(sec))}':{font_prefix}{FONT}"
+ cmd = ffmpeg_base() + ["-ss", f"{sec:.3f}", "-i", args.input, "-vf", f"scale={args.width}:-2{tc.replace(',' + timecode_filter(font_prefix), '')}{stamp}", "-frames:v", "1", out]
run(cmd)
outputs.append(out)
else:
diff --git a/scripts/overlay.py b/scripts/overlay.py
index 15250b4..22a0b57 100755
--- a/scripts/overlay.py
+++ b/scripts/overlay.py
@@ -24,7 +24,7 @@ import argparse
import sys
from typing import List, Optional
-from _common import STATE, load_brand, video_args, add_common, apply_common, emit, aac_args, cfr_args, default_output, die, escape_drawtext, escape_filter_path, ffmpeg_base, info, parse_time, probe, run, run_keeping_subtitles, x264_args
+from _common import STATE, load_brand, video_args, add_common, apply_common, default_font_file, emit, aac_args, cfr_args, default_output, die, escape_drawtext, escape_filter_path, ffmpeg_base, info, parse_time, probe, run, run_keeping_subtitles, x264_args
POS = {
"top-left": ("{m}", "{m}"),
@@ -144,6 +144,8 @@ def main() -> int:
args.font = brand.get("font", args.font)
if not args.font_file and brand.get("font_file"):
args.font_file = brand["font_file"]
+ if not args.font_file:
+ args.font_file = default_font_file(args.font)
meta = probe(args.input)
if not meta.get("video"):
die("input has no video stream")
diff --git a/scripts/scenes.py b/scripts/scenes.py
index 27558a7..1ee4ca4 100755
--- a/scripts/scenes.py
+++ b/scripts/scenes.py
@@ -26,7 +26,7 @@ import subprocess
import sys
from typing import Dict, List, Tuple
-from _common import add_common, apply_common, die, emit, ffmpeg_base, info, print_json, probe, require_tool, run
+from _common import add_common, apply_common, default_font_file, die, emit, escape_filter_path, ffmpeg_base, info, print_json, probe, require_tool, run
SCORE_RE = re.compile(r"frame:(\d+)\s+pts:\d+\s+pts_time:([0-9.]+)")
@@ -107,6 +107,7 @@ def main() -> int:
ap.add_argument("--max-scene", type=float, default=15.0, help="cap a highlight range at this many seconds (default 15)")
ap.add_argument("--edl", help="write highlight ranges as START-END lines (cut.py --segments format)")
ap.add_argument("--sheet", help="write a contact sheet PNG with the first frame of every scene")
+ ap.add_argument("--no-timecode", action="store_true", help="--sheet without the burnt-in timecode stamp (a way out if drawtext itself is unusable, see doctor)")
add_common(ap)
args = ap.parse_args()
apply_common(args)
@@ -183,7 +184,12 @@ def main() -> int:
# exactly one frame per scene: the frame index at the scene start
fps = meta["video"].get("fps") or 30.0
expr = "+".join(f"eq(n\\,{int(round(sc['start'] * fps))})" for sc in scenes)
- vf = (f"select='{expr}',scale={tile_w}:-2,drawtext=text='%{{pts\\:hms}}':fontcolor=white:fontsize=h/14:box=1:[email protected]:boxborderw=4:x=6:y=6,"
+ stamp = ""
+ if not args.no_timecode:
+ default_font = default_font_file("DejaVu Sans")
+ font_prefix = f"fontfile={escape_filter_path(default_font)}:" if default_font else ""
+ stamp = f",drawtext=text='%{{pts\\:hms}}':{font_prefix}fontcolor=white:fontsize=h/14:box=1:[email protected]:boxborderw=4:x=6:y=6"
+ vf = (f"select='{expr}',scale={tile_w}:-2{stamp},"
f"tile={cols}x{rows}:padding=2:margin=2:color=0x202020")
run(ffmpeg_base() + ["-i", args.input, "-vf", vf, "-frames:v", "1", "-fps_mode", "vfr", args.sheet])
info(f"wrote {args.sheet}")
diff --git a/tests/test_all.py b/tests/test_all.py
index de7414f..527f31b 100644
--- a/tests/test_all.py
+++ b/tests/test_all.py
@@ -17,7 +17,7 @@ ROOT = Path(__file__).resolve().parent.parent
SCRIPTS = ROOT / "scripts"
OUT = Path(os.environ.get("OUT", ROOT / "tests" / "out"))
sys.path.insert(0, str(SCRIPTS))
-from _common import escape_filter_path, probe # noqa: E402
+from _common import default_font_file, escape_filter_path, probe, shell_quote # noqa: E402
TONES = ("0.6*sin(2*PI*440*t)*gt(sin(2*PI*0.37*t)\\,0.3)+0.4*sin(2*PI*880*t)*gt(sin(2*PI*0.53*t+1)\\,0.6)"
"+0.3*sin(2*PI*220*t)*gt(sin(2*PI*0.21*t+2)\\,0.7)")
@@ -1073,6 +1073,50 @@ class FFmpegSkillTests(unittest.TestCase):
script("look.py", self.src, "--compare", self.src, "--at", "1", "-o", cmp_png)
self.assertEqual(png_size(cmp_png)[0], 1280)
+ def test_shell_quote_quotes_backslashes(self):
+ """CodeRabbit (#101): fixing the invalid-escape-sequence SyntaxWarning in shell_quote()'s
+ character set (a stray `\\` before an already-unescaped `;`) accidentally dropped a real,
+ load-bearing backslash from the quoting trigger set -- the original `\\;` literal, due to
+ Python keeping an unrecognised escape's backslash, actually matched on `\\` OR `;`, not just
+ `;`. Without a backslash trigger, a Windows path like `C:\\media\\clip.mp4` would render
+ unquoted in --dry-run/--json command output. Assert the fixed version still quotes it."""
+ self.assertEqual(shell_quote("C:\\media\\clip.mp4"), "'C:\\media\\clip.mp4'")
+ self.assertEqual(shell_quote("plain.mp4"), "plain.mp4")
+ self.assertEqual(shell_quote("has;semicolon"), "'has;semicolon'")
+
+ def test_look_scenes_overlay_graphics_prefer_fontfile_over_font_when_resolvable(self):
+ """#100: drawtext's own fontconfig resolution (font=<name>) crashed with an access violation
+ on some real Windows ffmpeg builds, with or without a valid fonts.conf; fontfile=<path> is
+ the only form confirmed not to crash, since it never touches fontconfig at all. Every
+ drawtext-using tool now resolves a concrete font file (default_font_file() in _common.py)
+ and prefers fontfile= whenever one can be found, falling back to font= only when nothing
+ resolves. This sandbox has fc-match + DejaVu Sans, so a file is always resolvable here --
+ skip rather than false-fail on a machine where it genuinely cannot be (no fc-match, no
+ fonts installed), since font= is still the documented, correct fallback there."""
+ if not default_font_file("DejaVu Sans"):
+ self.skipTest("no resolvable default font on this machine (no fc-match / no fonts) -- font= fallback is correct here")
+
+ out = OUT / "fontfile_look.png"
+ proc = script("look.py", self.src, "--at", "1", "-o", out, "--json")
+ data = json.loads(proc.stdout)
+ self.assertTrue(any("fontfile=" in c for c in data["commands"]), data["commands"])
+
+ scenes_sheet = OUT / "fontfile_scenes.png"
+ proc = subprocess.run([sys.executable, str(SCRIPTS / "scenes.py"), str(self.src), "--sheet", str(scenes_sheet), "--json"],
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ self.assertEqual(proc.returncode, 0, proc.stderr)
+ self.assertIn("fontfile=", proc.stderr, "scenes.py --sheet should log a drawtext with fontfile=")
+
+ out2 = OUT / "fontfile_overlay.mp4"
+ proc = script("overlay.py", self.src, "--text", "hi", "-o", out2, "--json")
+ data2 = json.loads(proc.stdout)
+ self.assertTrue(any("fontfile=" in c for c in data2["commands"]), data2["commands"])
+
+ out3 = OUT / "fontfile_gfx.mp4"
+ proc = script("graphics.py", self.src, "--template", "title", "--title", "hi", "-o", out3, "--json")
+ data3 = json.loads(proc.stdout)
+ self.assertTrue(any("fontfile=" in c for c in data3["commands"]), data3["commands"])
+
def test_silence_removal(self):
gappy = OUT / "gappy.mp4"
sh("ffmpeg", "-y", "-hide_banner", "-loglevel", "error",
diff --git a/tests/test_contract.py b/tests/test_contract.py
index 7c9e55a..9313035 100644
--- a/tests/test_contract.py
+++ b/tests/test_contract.py
@@ -1226,6 +1226,43 @@ class DoctorDetectionTests(unittest.TestCase):
self.assertEqual(d["ok"], not expected_missing, name)
self.assertEqual(code, 1 if expected_missing else 0, name)
+ def test_drawtext_crash_downgrades_a_listed_filter_to_missing(self):
+ """#100: `-filters` correctly lists drawtext (this ffmpeg build was compiled with it), but
+ a real one-frame render crashes -- an access-violation-style bug on some real Windows
+ builds. doctor must not repeat "missing required: none" in that case; it has to actually
+ run the probe and report drawtext missing, not just trust the listing."""
+ shim = self.work / "shim"
+ shim.mkdir(exist_ok=True)
+ script = "#!/bin/sh\ncase \"$2\" in\n"
+ for flag, name, code in (("-filters", "ffmpeg_filters_6.1.txt", 0), ("-encoders", "ffmpeg_encoders_6.1.txt", 0), ("-bsfs", "ffmpeg_bsfs_6.1.txt", 0)):
+ script += f" {flag}) cat '{self.FIX / name}'; exit {code};;\n"
+ script += "esac\ncase \"$1\" in -version) echo 'ffmpeg version 8.0-fixture'; exit 0;; esac\n"
+ # simulate the real Windows crash: killed by a signal, so subprocess.run reports a negative
+ # returncode (the only portable way to reproduce "crashed" from a POSIX shell shim -- the
+ # real bug is a huge positive exit code on Windows, but this class only runs on POSIX)
+ script += "case \"$*\" in *drawtext=text=x*) kill -s SEGV $$;; esac\nexit 1\n"
+ (shim / "ffmpeg").write_text(script)
+ (shim / "ffmpeg").chmod(0o755)
+ env = dict(os.environ, PATH=f"{shim}:{os.environ['PATH']}")
+ proc = sh(sys.executable, SCRIPTS / "_contract.py", "doctor", "--json", env=env, check=False)
+ d = json.loads(proc.stdout)
+ self.assertIn("filter:drawtext", d["missing"])
+ self.assertNotIn("filter:drawtext", d["available"])
+ self.assertTrue(any("filter:drawtext" in e and "crashed" in e for e in d["errors"]), d["errors"])
+ self.assertFalse(d["ok"])
+ self.assertEqual(proc.returncode, 1)
+
+ def test_drawtext_ordinary_failure_does_not_downgrade_a_listed_filter(self):
+ """An ordinary nonzero exit from the drawtext probe -- not a crash -- proves nothing either
+ way, so it must leave a listed-available drawtext alone rather than reporting it missing.
+ This is also what every _doctor() fixture call above relies on: their shim's drawtext-probe
+ invocation always falls through to the catch-all `exit 1`, not a real render."""
+ d, code = self._doctor("ffmpeg_filters_6.1.txt")
+ self.assertIn("filter:drawtext", d["available"])
+ self.assertNotIn("filter:drawtext", d["missing"])
+ self.assertTrue(d["ok"])
+ self.assertEqual(code, 0)
+
def test_unparsed_listing_is_unknown_not_missing(self):
"""Output no parser understands: filters become `unknown`, `ok` is false, exit 2, and nothing is claimed available."""
d, code = self._doctor("ffmpeg_filters_garbage.txt")