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.

render.py: the stages before an encoding export use x264 veryfast (#355)

Shogo Kajiyamab321d454990e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 71dcd94..e23d331 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,7 +4,9 @@
## Unreleased
-(nothing yet)
+### Changed
+
+- **`render.py` encodes the stages before an encoding export with x264/x265 `veryfast`** (`--intermediate-preset`, default `veryfast`; `medium` restores the old behaviour). export.py re-encodes them and its own preset sets the delivered quality, so a 30 s 1080p reels render took 41.7 s instead of 51.8 s on FFmpeg 8.0.1, with SSIM 0.997 between the two deliveries. Not applied without an export stage, with `--stop-after` before it, with `--fast`, or for a `copy` export; the result reports `intermediate_preset`.
## 2.14.0
diff --git a/docs/design-decisions.md b/docs/design-decisions.md
index dbc8468..c088aa5 100644
--- a/docs/design-decisions.md
+++ b/docs/design-decisions.md
@@ -44,6 +44,7 @@ exists. When a decision changes, edit the entry in the same PR.
- [2.10.9 — doctor's FFmpeg advisory and the Python 3.9 deprecation](#2109--doctors-ffmpeg-advisory-and-the-python-39-deprecation)
- [2.11.0–2.12.0 — nothing happens silently](#21102120--nothing-happens-silently)
- [2.14.0 — the FFmpeg 5.x deprecation](#2140--the-ffmpeg-5x-deprecation)
+- [2.15.0 — render.py's intermediate stages encode with veryfast](#2150--renderpys-intermediate-stages-encode-with-veryfast)
<!-- contents:end -->
## Time limits
@@ -2067,3 +2068,17 @@ What was decided there:
reads 5.x, never a key in `doctor --json` and never a failure. A git snapshot's version is not a
release number and gets no line, the same rule as the security advisory. Tests:
`test_ffmpeg_5_is_deprecated_on_every_surface`, `test_doctor_prints_the_ffmpeg_5_warning_on_stderr_only`.
+
+## 2.15.0 — render.py's intermediate stages encode with veryfast
+
+- **Only a stage whose output an encoding export re-encodes gets the faster preset.** (x265 on
+ the HDR path takes the same `--preset` and the same reasoning.) What a
+ caller keeps is export.py's encode, at its own preset; an x264 stage before it at `medium`
+ spent about twice the time for detail the export re-encodes anyway. Measured on a 30 s 1080p
+ reels render: 51.8 s → 41.7 s on FFmpeg 8.0.1, SSIM 0.997 between the two deliveries. Without
+ an export stage, with `--stop-after` before it, or with a `copy` export, a stage's output is
+ what the caller keeps, so it stays at the stage's own default. `--fast` (veryfast everywhere)
+ and a stage's own `--preset` still win, and `--intermediate-preset medium` turns it off. The
+ preset is part of each stage's arguments, so a `--cache` entry made at `medium` is not reused
+ for a `veryfast` run. Code: `render.sh()`, `INTERMEDIATE`. Test:
+ `test_render_intermediate_stages_use_veryfast_only_before_an_encoding_export`.
diff --git a/references/gotchas.md b/references/gotchas.md
index a88c0e6..caf8702 100644
--- a/references/gotchas.md
+++ b/references/gotchas.md
@@ -301,7 +301,8 @@ the contact sheet (`--sheet`) before treating the picks as final.
Anything chained by hand through three re-encodes should be one `render.py`
project instead, so the plan is one file and the user can change one number.
Re-encodes use x264 `medium`; for long files add `--preset veryfast` to
-intermediates and keep the default for the final export. On Apple Silicon,
+intermediates and keep the default for the final export. `render.py` does that by itself since
+2.15 when its project ends in an encoding export (`--intermediate-preset medium` turns it off). On Apple Silicon,
`--hw` (or `FFMPEG_SKILL_HW=1` for the machine) moves h264/hevc/prores encodes to
VideoToolbox: 2–7× faster, 1.1–2.9× the bytes at the same quality (1.9–3.5× on HDR). The variable
leaves `export.py`'s delivery presets on the CPU, which is the usual split (GPU
diff --git a/references/scripts.md b/references/scripts.md
index b9a3e35..ee21a7a 100644
--- a/references/scripts.md
+++ b/references/scripts.md
@@ -717,7 +717,17 @@ render.py project.json [--fast] [--dry-run] [--stop-after STAGE] [--work DIR --k
render.py project.json --cache DIR [--from STAGE] # reuse identical stages from a previous run
render.py plan.json [--audit-log FILE] # execute a plan written by <tool> --plan plan.json
render.py project.json --export-timeline edit.fcpxml|edit.edl|edit.otio # the cut for an editor, nothing rendered
-```
+render.py project.json --intermediate-preset medium # the stages' own encoder preset instead of veryfast
+```
+`--intermediate-preset` (2.15, default `veryfast`): when the project has an export stage that
+re-encodes (any preset but `copy`) and the run goes that far (no `--stop-after` before it), the
+stages before it that encode with x264 or x265 (clips, fit, join, silence, captions, graphics,
+overlays, audiogram; x265 on the HDR path) encode with this preset instead of `medium`. export.py re-encodes their output and its own
+preset sets the delivered quality, so the earlier `medium` passes cost time the file does not
+keep: a 30 s 1080p reels render took 41.7 s instead of 51.8 s on FFmpeg 8.0.1 (SSIM 0.997
+between the two deliveries). `medium` restores the stages' default; `--fast` still overrides
+everything; a stage given its own `--preset` keeps it. The result names it as
+`intermediate_preset` (`null` when not applied).
`--export-timeline FILE` (2.1) writes the project's cut as an editor timeline instead of
rendering it: `.fcpxml` (FCPXML 1.10: Final Cut Pro, DaVinci Resolve), `.edl` (CMX 3600:
Premiere, Resolve, Avid) or `.otio` (OpenTimelineIO JSON: Resolve natively, others through
diff --git a/scripts/render.py b/scripts/render.py
index f6ca577..04487e6 100755
--- a/scripts/render.py
+++ b/scripts/render.py
@@ -74,7 +74,7 @@ from typing import Any, Dict, List, Optional, Sequence
from export import PRESETS, PLATFORM_OF
from _platforms import PLATFORMS, caption_defaults, resolve as resolve_platform
-from _common import STATE, add_common, aspect_ratio, brand_caption_style, load_brand, apply_common, child_args, die, emit, info, probe, require_tool, run, run_tool, place_output, refuse_output_is_input, _check_existing_output, _check_output_path, fingerprint, PLAN_VERSION, ffmpeg_version, ffmpeg_exe
+from _common import STATE, add_common, aspect_ratio, brand_caption_style, load_brand, apply_common, child_args, die, emit, info, probe, require_tool, run, run_tool, place_output, refuse_output_is_input, _check_existing_output, _check_output_path, fingerprint, PLAN_VERSION, ffmpeg_version, ffmpeg_exe, X264_PRESETS
from _common.runner import HW_ENV, HW_FORCED_ENV, add_hw_orchestrator_args
from _common.emit import absorb_stage, audit, record_fallback, record_skip, refuse, warn
import subprocess
@@ -353,7 +353,8 @@ def render_pack(names: List[str], args) -> int:
argv = [str(HERE / "render.py"), args.input, "--template", name, "-o", dest_out]
for flag, value in (("--cues", args.cues), ("--srt", args.srt), ("--logo", args.logo),
("--title", args.title), ("--brand", args.brand), ("--fit", args.fit),
- ("--chapters", args.chapters), ("--image", args.image)):
+ ("--chapters", args.chapters), ("--image", args.image),
+ ("--intermediate-preset", args.intermediate_preset)):
if value:
argv += [flag, str(value)]
info(f"→ pack: {name}")
@@ -545,6 +546,13 @@ def sh(script: str, *argv: Any, extra: List[str] = None, stage: str = None) -> s
cache instead of re-encoded. `stages_done` is unchanged either way: a cached stage is still
a stage that happened.
"""
+ if (INTERMEDIATE["preset"] and script in _X264_STAGES
+ and "--preset" not in [str(a) for a in argv] + (extra or [])):
+ extra = (extra or []) + ["--preset", INTERMEDIATE["preset"]]
+ if not INTERMEDIATE["applied"]:
+ info(f"intermediate stages: preset {INTERMEDIATE['preset']} (the export re-encodes them; "
+ "--intermediate-preset medium for the stages' own default)")
+ INTERMEDIATE["applied"] = True
full = [str(a) for a in argv] + (extra or [])
dest = full[full.index("-o") + 1] if "-o" in full[:-1] else None
key = None
@@ -627,6 +635,21 @@ def _fresh_cache() -> "Dict[str, Any]":
# inherit each other's hit/miss lists.
CACHE: Dict[str, Any] = _fresh_cache()
+# The stages whose x264 encode (x265 on the HDR path, which takes the same --preset) is an
+# intermediate when an encoding export follows: export.py
+# re-encodes their output, so their own `medium` pass bought nothing the delivery keeps. Measured
+# on a 30 s 1080p reels render (4 cores): fit 18 s and captions 27 s of a 70 s run at `medium`;
+# `veryfast` at the same CRF encodes in about half the time (SSIM 0.997 against `medium`) and
+# the export, still `medium`, sets the delivered quality. `--intermediate-preset medium` restores it.
+_X264_STAGES = frozenset({"cut.py", "fit.py", "join.py", "silence.py", "caption.py", "graphics.py", "overlay.py", "waveform.py"})
+INTERMEDIATE: Dict[str, Any] = {"preset": None, "applied": False}
+
+
+def _intermediate_used() -> Optional[str]:
+ """The preset `intermediate_preset` reports: only once a stage actually received it (a project
+ whose only encode is the export reports null)."""
+ return INTERMEDIATE["preset"] if INTERMEDIATE["applied"] else None
+
def _content_hash(path: str) -> str:
"""The same cheap content fingerprint batch.py caches on: name, size, mtime, first and last
@@ -1043,6 +1066,10 @@ def main() -> int:
help="append the audit records of this run (a refused plan, a lock taken over, ...) to FILE as JSON lines; "
"default for a refused plan: <plan>.audit.jsonl next to it. A record that cannot be written is a "
"warning, never a failure")
+ ap.add_argument("--intermediate-preset", default="veryfast", choices=X264_PRESETS,
+ help="x264/x265 preset of the stages before an encoding export (default veryfast: the export "
+ "re-encodes them, and its own preset sets the delivered quality); medium = the stages' own default. "
+ "Not used without an export stage, with --stop-after before it, with --fast, or for a copy export")
ap.add_argument("--stop-after", choices=["clips", "join", "silence", "fit", "captions", "graphics", "overlays", "audio", "loudness", "export"], help="stop after this stage (for iterating)")
tpl = ap.add_argument_group("delivery templates (one command per destination)")
tpl.add_argument("--template", metavar="NAME", help="render INPUT with a shipped template: " + ", ".join(template_names())
@@ -1175,6 +1202,13 @@ def main() -> int:
# unchanged -- it never gets a --platform it did not ask for.
dest = str(((proj.get("check") or {}).get("platform") or "")) if proj.get("template") else ""
platform_args: List[str] = ["--platform", dest] if dest in PLATFORMS and PLATFORMS[dest].get("frame") else []
+ ex_cfg = proj.get("export")
+ # a malformed "export" is refused by the export stage with its own message; here it only means
+ # "no encoding export", never a traceback before that refusal
+ ex_preset = str(ex_cfg.get("preset") or "") if isinstance(ex_cfg, dict) else ""
+ if (ex_preset and "copy" not in PRESETS.get(ex_preset, {}).get("video", [])
+ and args.stop_after in (None, "export") and args.intermediate_preset != "medium" and not STATE.fast):
+ INTERMEDIATE["preset"] = args.intermediate_preset
stages_done: List[str] = []
# what the caption stage reported (wrapped/split counts and the fit-size keys), so a caller
# reading render.py's JSON can see whether the type was shrunk to fit or a cue was split.
@@ -1306,7 +1340,7 @@ def main() -> int:
stages_done.append("audiogram")
if args.stop_after == "clips":
- emit(current, stages=stages_done)
+ emit(current, stages=stages_done, intermediate_preset=_intermediate_used())
return 0
# ---- join
@@ -1322,7 +1356,7 @@ def main() -> int:
sh("join.py", *argv, stage="join")
stages_done.append("join")
if args.stop_after == "join":
- emit(current, stages=stages_done)
+ emit(current, stages=stages_done, intermediate_preset=_intermediate_used())
return 0
# ---- silence
@@ -1337,7 +1371,7 @@ def main() -> int:
current = nxt
stages_done.append("silence")
if args.stop_after == "silence":
- emit(current, stages=stages_done)
+ emit(current, stages=stages_done, intermediate_preset=_intermediate_used())
return 0
# ---- fit (duration and/or frame)
@@ -1374,7 +1408,7 @@ def main() -> int:
current = nxt
stages_done.append("fit")
if args.stop_after == "fit":
- emit(current, stages=stages_done)
+ emit(current, stages=stages_done, intermediate_preset=_intermediate_used())
return 0
# ---- captions
@@ -1403,7 +1437,7 @@ def main() -> int:
current = nxt
stages_done.append("captions")
if args.stop_after == "captions":
- emit(current, stages=stages_done)
+ emit(current, stages=stages_done, intermediate_preset=_intermediate_used())
return 0
# ---- graphics
@@ -1422,7 +1456,7 @@ def main() -> int:
if "graphics" not in stages_done:
stages_done.append("graphics")
if args.stop_after == "graphics":
- emit(current, stages=stages_done)
+ emit(current, stages=stages_done, intermediate_preset=_intermediate_used())
return 0
# ---- overlays
@@ -1453,7 +1487,7 @@ def main() -> int:
if "overlays" not in stages_done:
stages_done.append("overlays")
if args.stop_after == "overlays":
- emit(current, stages=stages_done)
+ emit(current, stages=stages_done, intermediate_preset=_intermediate_used())
return 0
# ---- audio
@@ -1490,7 +1524,7 @@ def main() -> int:
current = nxt
stages_done.append("audio")
if args.stop_after == "audio":
- emit(current, stages=stages_done)
+ emit(current, stages=stages_done, intermediate_preset=_intermediate_used())
return 0
# ---- loudness
@@ -1506,7 +1540,7 @@ def main() -> int:
current = nxt
stages_done.append("loudness")
if args.stop_after == "loudness":
- emit(current, stages=stages_done)
+ emit(current, stages=stages_done, intermediate_preset=_intermediate_used())
return 0
# ---- export
@@ -1612,7 +1646,7 @@ def main() -> int:
snap_report = dict(snap_reports[0])
snap_report["clips"] = snap_reports
emit(output, stages=stages_done, check=check_result, snap=snap_report, cache=cache_report,
- caption=caption_report,
+ caption=caption_report, intermediate_preset=_intermediate_used(),
verification=[{"step": "check", "ok": True, "platform": ck.get("platform")}] if check_result else [])
return 0
diff --git a/tests/fixtures/mcp_tools.json b/tests/fixtures/mcp_tools.json
index ffcb425..706735b 100644
--- a/tests/fixtures/mcp_tools.json
+++ b/tests/fixtures/mcp_tools.json
@@ -915,6 +915,7 @@
"hw",
"image",
"init",
+ "intermediate_preset",
"json_brief",
"keep",
"list_templates",
diff --git a/tests/test_orchestration.py b/tests/test_orchestration.py
index 0cc52e1..870d669 100644
--- a/tests/test_orchestration.py
+++ b/tests/test_orchestration.py
@@ -1011,6 +1011,53 @@ class OrchestrationTests(MediaFixtures):
self.assertEqual(plan["status"], "completed")
self.assertIn("export", plan["stages"])
+ def test_render_intermediate_stages_use_veryfast_only_before_an_encoding_export(self):
+ """2.15: the x264 stages before an encoding export run at --intermediate-preset (default
+ veryfast): export.py re-encodes them and its own preset sets the delivered quality. Kept
+ at the stages' medium when nothing re-encodes after them: --stop-after before the
+ export, a copy export, or --intermediate-preset medium. --fast still wins."""
+ proj = OUT / "ip_project.json"
+ script("render.py", self.src, "--template", "reels", "--cues", self.cues,
+ "--write-project", proj, "-o", OUT / "ip_out.mp4", "--json")
+
+ def presets(project, *extra):
+ doc = json.loads(script("render.py", project, "--dry-run", "--json", *extra).stdout)
+ x264 = [re.search(r"-preset (\S+)", c).group(1) for c in doc["commands"] if "-c:v libx264" in c]
+ return doc.get("intermediate_preset"), x264
+
+ used, x264 = presets(proj)
+ self.assertEqual(used, "veryfast")
+ self.assertEqual(x264[-1], "medium", "the export keeps its preset")
+ self.assertTrue(x264[:-1] and set(x264[:-1]) == {"veryfast"}, x264)
+ self.assertEqual(presets(proj, "--intermediate-preset", "medium"), (None, ["medium"] * len(x264)))
+ used, x264_fast = presets(proj, "--fast")
+ self.assertIsNone(used, "--fast decides every stage's preset, not --intermediate-preset")
+ self.assertEqual(set(x264_fast), {"veryfast"})
+ doc_stop = json.loads(script("render.py", proj, "--dry-run", "--json", "--stop-after", "captions").stdout)
+ self.assertIn("intermediate_preset", doc_stop, "an early stop reports the key too, as null")
+ used, x264_stop = presets(proj, "--stop-after", "captions")
+ self.assertIsNone(used)
+ self.assertEqual(set(x264_stop), {"medium"}, "a --stop-after output is what the caller keeps")
+ loaded = json.loads(proj.read_text())
+ loaded["export"] = {"preset": "copy"}
+ loaded.pop("check", None)
+ copy_proj = OUT / "ip_project_copy.json"
+ copy_proj.write_text(json.dumps(loaded), encoding="utf-8")
+ used, x264_copy = presets(copy_proj)
+ self.assertIsNone(used)
+ self.assertEqual(set(x264_copy), {"medium"}, "a copy export keeps the stages' encode")
+ # a project whose only encode is the export: nothing received the preset, so null
+ bare = OUT / "ip_project_bare.json"
+ bare.write_text(json.dumps({"clips": [{"src": str(self.src)}], "export": {"preset": "youtube"},
+ "output": str(OUT / "ip_bare.mp4")}), encoding="utf-8")
+ used, x264_bare = presets(bare)
+ self.assertIsNone(used, x264_bare)
+ # a pack runs one render per destination: each gets the caller's choice
+ pack = json.loads(script("render.py", self.src, "--template", "reels,shorts", "--cues", self.cues,
+ "--intermediate-preset", "medium", "-o", OUT / "ip_pack" / "x.mp4",
+ "--dry-run", "--json").stdout)
+ self.assertEqual(set(re.findall(r"-preset (\w+)", " ".join(pack["commands"]))), {"medium"})
+
# --------------------------------------------- 1.17.1: the template path fits the caption size
def _cw1_cues(self):
cues = OUT / "cues_cw1.txt"