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: fifth audit -- bit depth, mono, replace-audio length, None durations, karaoke, render copy guards, 5.1 joins, multicam length, version fallback, freeze subtitles, natural frame order (#187)

claude[bot]c1d943c2befa
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b541c37..b8b75cf 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,7 +4,9 @@
## Unreleased
-(nothing yet)
+- Fifth audit (100 items; 33 confirmed, 5 recorded decisions, 62 not reproduced). Fixed: `bit_depth` read `yuv410p` as 10-bit (the depth is the number that ends the pixel-format name); `audio.py --mono` halved an already-mono track (-6 dB) and now leaves 1-channel input alone and downmixes >2 channels through swresample; `sync.py --replace-audio` cut the reference to the length of a shorter or head-trimmed second file (`-t <reference>` + `apad` instead of `-shortest`); 25+ tools raised TypeError formatting a missing duration after a successful encode (`fmt_secs()`); energy karaoke gave the last word a negative `\kf` on a cue shorter than 5 cs per word; the karaoke energy decode ran outside `--timeout`; `render.py`'s final copy bypassed the output-path, overwrite and temp-staging guards (`place_output()`); the video `join.py` forced stereo and dropped the centre/LFE of 5.1 clips (the audio-only join already kept the widest layout); `multicam.py -shortest` could end before the cut list; ffprobe output that is not JSON is a `kind: ffmpeg` document, not a traceback; a git/vendor `ffprobe version N-...` string is mapped from the libavutil major (59 -> 7) instead of reading as 0.0, which on 7.1 skipped the BT.709 tagging workaround.
+- `freeze.py --mode insert` drops a stream-copied subtitle track (its cues after the freeze fired early) and reports `dropped_non_av_streams`, as `fit.py --method speed` does; `sequence.py` sorts globbed frames naturally (`img2` before `img10`); `cut.py --segments` refuses a negative start; `speedramp.py --segment` accepts `mm:ss`; one `MEDIA_EXT` list (adds `.mxf`, `.m2ts`, `.3gp`, `.wmv`, `.aif`, `.caf`, `.wma`, `.webp`, so `verify` probes them); a colour alpha above 1 (`red@2`) is refused before ffmpeg; `--pad-fill blur` clamps the radius to what boxblur accepts on a tiny frame.
+- Not changed, recorded decisions: BT.2020-primaries SDR takes the HDR path until 2.0 (docs/design-decisions.md); `join.py`/`broll.py` keep the HDR path for mixed inputs; `escape_drawtext` drops `'` and `%`; `--overwrite` warns until 2.0.
## 1.4.11
diff --git a/README.md b/README.md
index 18a6a3b..1ad5808 100644
--- a/README.md
+++ b/README.md
@@ -143,7 +143,7 @@ These are the rules the skill file gives the agent and the code enforces. Togeth
1. **Probe first.** No tool decides from the file name. `probe.py` measures duration, fps (with variable-frame-rate detection), resolution, rotation, bit depth, HDR format including Dolby Vision, colour tags and every audio stream before anything is cut.
2. **Lossless when possible.** `cut.py`, `join.py` and `loudness.py` stream-copy what they do not need to touch. Re-encoding happens only when it must: frame-accurate cuts, filters, format changes, or a keyframe farther than the tolerance.
-3. **Plan before render.** Every tool takes `--dry-run` (print the ffmpeg command lines, write nothing), `--json` (structured result with a probe of the output), `--fast` (preview quality), `--progress` (percent and ETA), `--timeout` (a hung ffmpeg is killed and reported, never waited on forever) and `--overwrite` (explicit consent before an existing output is replaced). A test runs every tool under `--dry-run` behind a fake ffmpeg and asserts that no ffmpeg call happened and no file appeared.
+3. **Plan before render.** Every tool takes `--dry-run` (print the ffmpeg command lines, write nothing), `--json` (structured result with a probe of the output), `--fast` (preview quality), `--progress` (percent and ETA), `--timeout` (a hung ffmpeg is killed and reported, never waited on forever; Ctrl-C or SIGTERM likewise stops the running ffmpeg, removes its partial output and reports `kind: interrupted`) and `--overwrite` (explicit consent before an existing output is replaced). A test runs every tool under `--dry-run` behind a fake ffmpeg and asserts that no ffmpeg call happened and no file appeared.
4. **Machine-readable contract.** `contract --json` describes all 42 tools: input schema generated from the parser, output schema, role, required and conditional FFmpeg capabilities, dry-run support, the verification tools to run afterwards, whether a visual check is required, `mutates_input: false`. `provides` lists all 42 by a cross-repository Capability id (`ffmpeg-skill.cut`, `ffmpeg-skill.loudness`, ...) for [`kajisho5/AI-video-production-OS`](https://github.com/kajisho5/AI-video-production-OS)'s `CapabilityContract.provides` — see `docs/contract.md`.
5. **Contract-derived MCP.** `mcp/server.py` builds its `tools/list` from the contract. Tool names, order and `inputSchema` cannot drift from the scripts; a test keeps the two byte-identical.
6. **Capability detection.** `doctor` reads `ffmpeg -encoders / -filters / -bsfs` and reports which of the components the tools need are present on this build (libx264, libass, zscale, loudnorm, xfade, …), before a job fails inside ffmpeg.
@@ -168,7 +168,7 @@ These are the rules the skill file gives the agent and the code enforces. Togeth
| Tool | What it does |
|---|---|
| `cut.py` | In/out or multi-segment cuts, lossless `-c copy` first, re-encode fallback, `--accurate` for frame-exact video and sample-exact audio; reports `precision` |
-| `join.py` | Concatenate clips with xfade transitions, normalising size, fps and audio; audio-only inputs are joined as audio |
+| `join.py` | Concatenate clips with xfade transitions, normalising size, fps, sample rate and channel layout (the widest clip's, or `--channels`); audio-only inputs are joined as audio |
| `silence.py` | Detect and remove dead air (jump cuts) with a margin around speech; list or export the cut list |
| `fit.py` | Fit to a duration (pitch-preserving speed change or trim, smooth slow-mo) and/or aspect ratio (pad or crop, with `--crop-x`/`--crop-y` to keep an off-centre subject) and/or exact `--width`/`--height`; rotate 90/180/270, flip h/v; force constant fps |
| `crop.py` | Crop to an exact pixel rectangle (`--x --y --width --height`) — distinct from `fit.py --fit crop`, which crops to an aspect ratio it computes itself |
@@ -198,7 +198,7 @@ These are the rules the skill file gives the agent and the code enforces. Togeth
|---|---|
| `audio.py` | Voice clean-up chain, FFT denoise, typed compressor / limiter / gate, music bed with sidechain ducking, fades, 5.1 → stereo, track replacement, extraction (`-o out.wav`), `--audio-stream N` |
| `sync.py` | Offset between two recordings by audio cross-correlation (1 ms, pure Python), clock-drift correction; aligned video or audio out (audio-to-audio only — no lip-sync/face detection) |
-| `loudness.py` | Two-pass EBU R128 `loudnorm` to −14 LUFS / −1 dBTP or any target, video stream-copied; `--measure-only` |
+| `loudness.py` | Two-pass EBU R128 `loudnorm` to −14 LUFS / −1 dBTP or any target, video stream-copied; the written file is measured again and re-encoded until it meets `--tp` (lossy encoders overshoot); `--measure-only` |
**Picture**
diff --git a/references/scripts.md b/references/scripts.md
index ba31a16..c2fe796 100644
--- a/references/scripts.md
+++ b/references/scripts.md
@@ -225,7 +225,8 @@ run time.
sequence.py --dir DIR --pattern "frame_%04d.png"|"*.png" --fps N
[--start-number N] [--width W] [--height H] [-o OUT]
```
-Turns a numbered or glob-matched set of still images into a video. The match
+Turns a numbered or glob-matched set of still images into a video. Glob
+matches are ordered naturally (`img2` before `img10`). The match
is checked on disk before ffmpeg runs (an empty match or a missing first
frame is refused here, not discovered from an opaque ffmpeg error).
@@ -251,7 +252,10 @@ how long the freeze lasts. `--mode insert` (default) inserts the hold at
extend` only works with `--at` at (or past) the clip's end and just makes
the last frame last `--hold` seconds longer, with nothing pushed. Audio is
silent during the held frame in `--mode insert` (there is no source audio
-for a frozen moment that didn't exist before).
+for a frozen moment that didn't exist before). `--mode insert` drops a
+subtitle/data track rather than copy it with timestamps that no longer match
+the pushed picture (`dropped_non_av_streams: true` in the result), as
+`fit.py --method speed` does; `--mode extend` keeps it.
### pad.py — add black/silent padding at the start/end
```
@@ -260,7 +264,7 @@ pad.py INPUT [--start T] [--end T] [--color C] [-o OUT]
Distinct from `fit.py --fit pad`, which pads the *frame* (letterbox/
pillarbox bars around each existing frame) -- this pads the *timeline*:
extra seconds of solid colour and silence before and/or after the clip's
-existing content. At least one of `--start`/`--end` must be > 0.
+existing content (seconds or `mm:ss`). At least one of `--start`/`--end` must be > 0.
### speedramp.py — step through different speeds across a clip
```
@@ -272,7 +276,8 @@ pieces (repeatable) covering the clip start to end with no gaps or
overlaps, each played at its own constant speed (pitch-preserving audio,
matching `fit.py`), then concatenates them: "speed up, then slow way down
for the punch, then speed back up," built from a few constant segments
-rather than a continuous curve. `FACTOR` is 0.05..20 (2.0 = twice as fast,
+rather than a continuous curve. `START`/`END` take seconds or `mm:ss`;
+`FACTOR` is 0.05..20 (2.0 = twice as fast,
0.5 = half speed). Picking exactly where a ramp should ease in or out is a
judgement call for the calling agent, made concrete here as the segment
boundaries it supplies.
@@ -352,8 +357,9 @@ to `-45`; noisy ones `-30`. Always tell the user how many seconds were removed.
join.py CLIP1 CLIP2 [...] [--transition fade|dissolve|wipeleft|slideleft|fadeblack|fadewhite|circleopen|none]
[--duration 0.5] [--width W --height H] [--fps N] [--fit pad|crop] [-o OUT]
```
-Normalises every clip to one frame size, fps, `yuv420p` and 48 kHz stereo
-(silent track generated for clips without audio), then chains `xfade` +
+Normalises every clip to one frame size, fps, `yuv420p`, 48 kHz and one
+channel layout (the widest clip's -- a 5.1 clip keeps 5.1 -- or `--channels`;
+silent track generated for clips without audio), then chains `xfade` +
`acrossfade`. Output length = sum of clips − transition × (n−1). Clips must be
longer than 2 × the transition. Use `--transition none` for a plain cut.
@@ -529,7 +535,9 @@ sync.py REFERENCE SECOND [--json] [--max-offset 30] [--analyze-seconds 120] [--f
Cross-correlates loudness envelopes: coarse FFT search (20 ms), then a direct
1 ms refinement (pure Python, a 2-minute window takes ~1-3 s). Positive offset
= the second recording started later. `--replace-audio` writes the reference
-video with the second file's audio aligned (video stream copied).
+video with the second file's audio aligned (video stream copied); the output
+keeps the reference's full length -- a shorter or head-trimmed second file is
+padded with silence, never allowed to cut the picture.
`--trim-second` writes the second file shifted to the reference timeline.
`--fix-drift` measures the offset again near the end of the overlap, reports
the clock difference in ppm, and resamples the second file so a 60-minute
@@ -586,7 +594,9 @@ audio.py INPUT [--voice | --denoise [--denoise-strength 25]] [--gain dB]
`--voice` = highpass 80 Hz → de-esser → FFT denoise → gentle compressor, the
standard talking-head chain. `--duck` uses a sidechain compressor keyed by the
speech so music dips under dialogue and swells in pauses. `--downmix` uses the
-ITU centre/LFE weights for 5.1/7.1 → stereo. Video is always stream-copied.
+ITU centre/LFE weights for 5.1/7.1 → stereo. `--mono` averages a stereo pair,
+leaves a 1-channel input untouched and downmixes >2 channels through
+swresample. Video is always stream-copied.
Run `loudness.py` after this for final levels.
### loudness.py — EBU R128 normalisation
diff --git a/scripts/_common.py b/scripts/_common.py
index d0f873b..5ef97d4 100755
--- a/scripts/_common.py
+++ b/scripts/_common.py
@@ -43,12 +43,11 @@ INSTALL_HINTS = {
}
-# `kind` (below) has been the only machine-readable failure axis since 0.1: a flat, 4-value
-# vocabulary (input / missing_tool / ffmpeg / output) set at the ~7 call sites that ever pass one
-# explicitly, defaulting to "input" everywhere else. `ERROR_CODE` is an additive, purely
-# informational refinement layered on top for agents that want a stable enum to switch on instead
-# of pattern-matching `kind` strings -- it is a static 1:1 relabelling of the exact same 4 buckets,
-# not a new taxonomy. It intentionally does NOT introduce categories this codebase cannot actually
+# `kind` (below) is the machine-readable failure axis: input / missing_tool / ffmpeg / output
+# since 0.1, plus timeout (1.3), verification (1.4.3) and interrupted (1.4.10). `ERROR_CODE` is an
+# additive, purely informational refinement layered on top for agents that want a stable enum to
+# switch on instead of pattern-matching `kind` strings -- a static 1:1 relabelling of the same
+# buckets, not a new taxonomy. It intentionally does NOT introduce categories this codebase cannot actually
# distinguish today (e.g. a separate ffprobe-vs-ffmpeg code, or an environment-vs-content-cause
# split of ffmpeg failures): every ffmpeg subprocess failure is currently one undifferentiated
# bucket regardless of whether ffmpeg rejected a bad filter argument or died from a full disk,
@@ -113,6 +112,17 @@ def ffmpeg_version() -> "Tuple[int, int]":
m = re.search(r"ffprobe version\s+n?(\d+)\.(\d+)", out)
if m:
_FFMPEG_VERSION = (int(m.group(1)), int(m.group(2)))
+ else:
+ # git / vendor builds print "N-115000-g..." or a date, never major.minor; the
+ # libavutil major is still there and maps one-to-one onto the FFmpeg major
+ # (56=4, 57=5, 58=6, 59=7, 60=8). Without this every version branch took the
+ # oldest spelling on such builds: on 7.1 that skipped bt709_tag_args()'s
+ # workaround and an untagged source got a real matrix conversion.
+ m = re.search(r"^libavutil\s+(\d+)\.", out, re.M)
+ if m:
+ major = int(m.group(1)) - 52
+ if major >= 4:
+ _FFMPEG_VERSION = (major, 0)
except (OSError, subprocess.TimeoutExpired):
# (0, 0) = unknown: every version branch then takes the older, universally accepted
# spelling, the same "unknown is not missing" stance doctor takes.
@@ -139,7 +149,9 @@ def pad_filters(out_w: int, out_h: int, fill: str, color: str, blur: int) -> str
then boxblur'ed, the other scaled to fit, overlaid centred. Only `filter:boxblur` is
needed beyond the usual scale/pad set, and that is already required by redact.py."""
if fill == "blur":
- radius = max(1, int(blur))
+ # boxblur rejects a radius larger than half the smaller dimension ("radius 20, must be
+ # <= 8" on a 16 px target); clamp instead of failing an otherwise valid request
+ radius = max(1, min(int(blur), max(1, min(out_w, out_h) // 2 - 1)))
return (f"split[__fitfg][__fitbg];"
f"[__fitbg]scale={out_w}:{out_h}:force_original_aspect_ratio=increase,crop={out_w}:{out_h},"
f"boxblur={radius}:2[__fitbgb];"
@@ -839,7 +851,8 @@ def ffmpeg_base(overwrite: bool = True) -> List[str]:
return cmd
-MEDIA_EXT = {".mp4", ".mov", ".mkv", ".webm", ".m4v", ".avi", ".ts", ".mts", ".gif", ".wav", ".flac", ".mp3", ".m4a", ".aac", ".ogg", ".opus", ".png", ".jpg", ".jpeg"}
+MEDIA_EXT = {".mp4", ".mov", ".mkv", ".webm", ".m4v", ".avi", ".ts", ".mts", ".m2ts", ".mxf", ".3gp", ".wmv", ".gif",
+ ".wav", ".flac", ".mp3", ".m4a", ".aac", ".ogg", ".opus", ".aif", ".aiff", ".caf", ".wma", ".png", ".jpg", ".jpeg", ".webp"}
def _output_failed(path: str, why: str) -> "None":
@@ -902,7 +915,12 @@ def probe(path: str, role: str = "input") -> Dict[str, Any]:
if role == "output":
_output_failed(path, f"ffprobe cannot read it:\n{proc.stderr.strip()}")
die(f"ffprobe failed on {path}:\n{proc.stderr.strip()}")
- raw = json.loads(proc.stdout or "{}")
+ try:
+ raw = json.loads(proc.stdout or "{}")
+ except ValueError as e:
+ if role == "output":
+ _output_failed(path, f"ffprobe printed unreadable JSON: {e}")
+ die(f"ffprobe printed unreadable JSON for {path}: {e}", kind="ffmpeg")
fmt = raw.get("format", {})
streams = raw.get("streams", [])
video = next((s for s in streams if s.get("codec_type") == "video" and s.get("disposition", {}).get("attached_pic", 0) == 0), None)
@@ -981,7 +999,7 @@ def probe(path: str, role: str = "input") -> Dict[str, Any]:
"avg_frame_rate": video.get("avg_frame_rate"),
"variable_frame_rate_suspected": vfr,
"pix_fmt": video.get("pix_fmt"),
- "bit_depth": 10 if "10" in pix else (12 if "12" in pix else 8),
+ "bit_depth": _bit_depth(pix),
"hdr": hdr,
"hdr_format": (("Dolby Vision %s" % (("profile %s" % dovi["profile"]) if dovi and dovi.get("profile") is not None else "")).strip() if dovi else
"HDR10/PQ" if trc == "smpte2084" else "HLG" if trc == "arib-std-b67" else "BT.2020 SDR" if hdr else None),
@@ -1037,6 +1055,53 @@ def concat_list_line(path: str) -> str:
return f"file '{escaped}'"
+def _bit_depth(pix_fmt: Optional[str]) -> int:
+ """Bits per component from a pixel format name. `"10" in pix` used to read yuv410p (4:1:0
+ chroma) as 10-bit; the depth is the number that ends the name (before an le/be suffix):
+ yuv420p10le -> 10, gbrp12be -> 12, gray16le -> 16, yuv410p / yuv420p / rgb24 -> 8."""
+ m = re.search(r"(\d{1,2})(?:le|be)?$", pix_fmt or "")
+ if not m:
+ return 8
+ n = int(m.group(1))
+ if n in (24, 32): # packed 8-bit rgb24/bgr32/rgb0 etc.
+ return 8
+ if n in (48, 64): # packed 16-bit rgb48/rgba64
+ return 16
+ return n if 8 <= n <= 16 else 8
+
+
+def fmt_secs(value: Optional[float]) -> str:
+ """`12.345s`, or `?s` when the probe had no duration (MPEG-TS without a duration tag, a
+ stream whose container and streams all omit it). Every writing tool prints the duration
+ of what it wrote; formatting None with :.3f used to raise TypeError after a successful
+ encode, in 25+ scripts."""
+ return "?s" if value is None else f"{value:.3f}s"
+
+
+def place_output(src: str, dst: str) -> None:
+ """Deliver an already-rendered file to `dst` under the same rules as an ffmpeg output:
+ the path is checked, an existing file is only replaced through a sibling temp so a
+ failed copy never costs the caller what was there, and the result is remembered as ours.
+ render.py's final `copyfile()` used to bypass all three."""
+ import shutil
+ cmd = ["ffmpeg", dst]
+ _check_output_path(cmd)
+ _check_existing_output(cmd)
+ d, base = os.path.split(dst)
+ stem, ext = os.path.splitext(base)
+ tmp = os.path.join(d, f".{stem}.ffskill-{os.getpid()}{ext}")
+ try:
+ shutil.copyfile(src, tmp)
+ os.replace(tmp, dst)
+ except OSError as e:
+ try:
+ os.remove(tmp)
+ except OSError:
+ pass
+ die(f"could not place {dst}: {e}", kind="output")
+ _remember_output(cmd)
+
+
def parse_time(value: str, fps: Optional[float] = None) -> float:
"""Accept seconds ('12.5'), mm:ss ('1:30'), hh:mm:ss(.ms) ('00:01:30.250'), SRT '00:01:30,250',
or -- when `fps` is given -- SMPTE non-drop-frame timecode 'hh:mm:ss:ff' ('00:01:30:15')."""
@@ -1468,7 +1533,7 @@ def color_hex(value: str) -> str:
return v.upper()
-_COLOR_TOKEN_RE = re.compile(r"^(0[xX][0-9A-Fa-f]{6,8}|#[0-9A-Fa-f]{6,8}|[A-Za-z][A-Za-z0-9]*)(@[0-9.]+)?$")
+_COLOR_TOKEN_RE = re.compile(r"^(0[xX][0-9A-Fa-f]{6,8}|#[0-9A-Fa-f]{6,8}|[A-Za-z][A-Za-z0-9]*)(@(?:0(?:\.\d+)?|1(?:\.0+)?|\.\d+))?$") # alpha is 0..1; "red@2" used to reach ffmpeg
def validate_color(value: str, flag: str = "--color") -> str:
diff --git a/scripts/audio.py b/scripts/audio.py
index ff808d8..6a36712 100755
--- a/scripts/audio.py
+++ b/scripts/audio.py
@@ -20,7 +20,7 @@ import argparse
import sys
from typing import List
-from _common import STATE, add_common, apply_common, audio_codec_for, db_to_linear, default_output, die, emit, ffmpeg_base, info, is_audio_output, probe, run
+from _common import STATE, add_common, apply_common, audio_codec_for, db_to_linear, default_output, die, emit, ffmpeg_base, info, is_audio_output, probe, run, fmt_secs
VOICE_CHAIN = "highpass=f=80,deesser=i=0.4,afftdn=nf=-25:tn=1,acompressor=threshold=-18dB:ratio=3:attack=5:release=80:makeup=2"
@@ -164,7 +164,12 @@ def main() -> int:
if args.limit:
fx.append(dynamics_filter("alimiter", args))
if args.mono:
- fx.append("pan=mono|c0=0.5*c0+0.5*c1")
+ in_ch = (meta.get("audio") or {}).get("channels") or 2
+ if in_ch == 2:
+ fx.append("pan=mono|c0=0.5*c0+0.5*c1")
+ elif in_ch > 2:
+ fx.append("aformat=channel_layouts=mono") # swresample's standard downmix (centre/LFE weighted)
+ # 1 channel: already mono; the stereo pan used to halve it (-6 dB) because c1 was silence
elif args.stereo:
fx.append("aformat=channel_layouts=stereo")
@@ -227,7 +232,7 @@ def main() -> int:
a = r["audio"]
if r.get("video") and audio_out and not STATE.dry_run:
die(f"{output} unexpectedly contains a video stream")
- info(f"wrote {output} ({r['duration']:.3f}s, audio {a['codec']} {a['channels']}ch {a['sample_rate']}Hz"
+ info(f"wrote {output} ({fmt_secs(r['duration'])}, audio {a['codec']} {a['channels']}ch {a['sample_rate']}Hz"
+ (", video stream-copied" if has_video and not audio_out else ", video dropped" if has_video else "") + ")")
emit(output, video=bool(has_video and not audio_out), audio_stream=args.audio_stream,
dynamics=[f for f in (args.gate and "agate", args.compress and "acompressor", args.limit and "alimiter") if f])
diff --git a/scripts/background.py b/scripts/background.py
index 0775024..bb23057 100644
--- a/scripts/background.py
+++ b/scripts/background.py
@@ -14,7 +14,7 @@ import argparse
import math
import sys
-from _common import add_common, apply_common, die, emit, ffmpeg_base, info, parse_time, probe, run, validate_color, video_args, X264_PRESETS, time_arg
+from _common import add_common, apply_common, die, emit, ffmpeg_base, info, parse_time, probe, run, validate_color, video_args, X264_PRESETS, time_arg, fmt_secs
def main() -> int:
@@ -73,7 +73,7 @@ def main() -> int:
result = probe(output, role="output")
v = result["video"]
- info(f"wrote {output} ({result['duration']:.3f}s, {v['width']}x{v['height']}, {v['fps']:g}fps)")
+ info(f"wrote {output} ({fmt_secs(result['duration'])}, {v['width']}x{v['height']}, {v['fps']:g}fps)")
emit(output)
return 0
diff --git a/scripts/batch.py b/scripts/batch.py
index 292e00b..060652c 100755
--- a/scripts/batch.py
+++ b/scripts/batch.py
@@ -31,11 +31,10 @@ import time
from pathlib import Path
from typing import Any, Dict, List
-from _common import STATE, add_common, apply_common, child_args, die, emit, info, run_tool, read_text_or_die
+from _common import STATE, add_common, apply_common, child_args, die, emit, info, run_tool, read_text_or_die, MEDIA_EXT as _MEDIA_EXT
HERE = Path(__file__).resolve().parent
-MEDIA_EXT = {".mp4", ".mov", ".m4v", ".mkv", ".webm", ".avi", ".mts", ".m2ts", ".mxf", ".ts", ".gif",
- ".wav", ".m4a", ".mp3", ".flac", ".aac", ".ogg", ".opus", ".aif", ".aiff"}
+MEDIA_EXT = {e for e in _MEDIA_EXT if e not in (".png", ".jpg", ".jpeg", ".webp")} # one list (_common); a batch walks media, not stills
# recipe steps name the script to run as plain, untrusted JSON -- run_step() joins it onto HERE
# with the `/` operator, which silently ignores the left side when the right side is itself an
# absolute path (Path("/scripts") / "/tmp/evil.py" == Path("/tmp/evil.py")), and does nothing to
diff --git a/scripts/broll.py b/scripts/broll.py
index e606e68..1e42320 100755
--- a/scripts/broll.py
+++ b/scripts/broll.py
@@ -21,7 +21,7 @@ import argparse
import sys
from typing import Any, Dict, List
-from _common import STATE, add_common, aac_args, apply_common, cfr_args, default_output, die, emit, ffmpeg_base, info, parse_time, probe, run, validate_color, video_args, X264_PRESETS
+from _common import STATE, add_common, aac_args, apply_common, cfr_args, default_output, die, emit, ffmpeg_base, info, parse_time, probe, run, validate_color, video_args, X264_PRESETS, fmt_secs
def main() -> int:
@@ -143,7 +143,7 @@ def main() -> int:
result = probe(output, role="output")
if not STATE.dry_run and dur_a and abs((result.get("duration") or 0.0) - dur_a) > max(0.1, 1.5 / fps):
- die(f"output is {result.get('duration'):.3f}s but the A-roll is {dur_a:.3f}s -- a cutaway must not change the length", kind="output")
+ die(f"output is {fmt_secs(result.get('duration'))} but the A-roll is {dur_a:.3f}s -- a cutaway must not change the length", kind="output")
info(f"wrote {output} ({result.get('duration', 0):.3f}s, {len(cutaways)} cutaway(s), audio={args.audio})")
emit(output, cutaways=[{"insert": c["path"], "at": c["at"], "end": c["at"] + c["length"], "from": c["from"]} for c in cutaways], audio=args.audio)
return 0
diff --git a/scripts/caption.py b/scripts/caption.py
index 8616980..565a55e 100755
--- a/scripts/caption.py
+++ b/scripts/caption.py
@@ -36,7 +36,7 @@ import sys
from pathlib import Path
from typing import List, Optional, Tuple
-from _common import STATE, color_hex, load_brand, video_args, add_common, apply_common, emit, aac_args, cfr_args, default_output, die, escape_filter_path, ffmpeg_base, fmt_srt_time, fmt_smpte_time, info, MissingFpsError, parse_time, probe, run, x264_args, X264_PRESETS, read_text_or_die
+from _common import STATE, color_hex, load_brand, video_args, add_common, apply_common, emit, aac_args, cfr_args, default_output, die, escape_filter_path, ffmpeg_base, fmt_srt_time, fmt_smpte_time, info, MissingFpsError, parse_time, probe, run, x264_args, X264_PRESETS, read_text_or_die, fmt_secs
ALIGN = {"bottom": 2, "top": 8, "center": 5, "bottom-left": 1, "bottom-right": 3, "top-left": 7, "top-right": 9}
@@ -231,15 +231,14 @@ def word_durations_from_audio(video: str, start: float, end: float, n_words: int
Falls back to an even split when the window is silent or too short.
"""
import struct
- import subprocess as sp
- from _common import require_tool
+ from _common import require_tool, run_analysis
total_cs = max(1, int(round((end - start) * 100)))
if n_words <= 1:
return [total_cs]
ffmpeg = require_tool("ffmpeg")
cmd = [ffmpeg, "-hide_banner", "-loglevel", "error", "-nostdin", "-ss", f"{start:.3f}", "-i", video,
"-map", f"0:a:{audio_stream}", "-t", f"{end - start:.3f}", "-vn", "-ac", "1", "-ar", "8000", "-f", "s16le", "-"]
- proc = sp.run(cmd, stdout=sp.PIPE, stderr=sp.PIPE)
+ proc = run_analysis(cmd, check=False, text=False) # under --timeout like every other measurement
n = len(proc.stdout) // 2
if proc.returncode != 0 or n < 800:
per = total_cs // n_words
@@ -274,10 +273,23 @@ def word_durations_from_audio(video: str, start: float, end: float, n_words: int
out.append(cs)
prev = b
out.append(max(5, total_cs - sum(out)))
- # normalise to the exact cue length
+ # normalise to the exact cue length. A cue too short for 5 cs per word (0.5 s, 20 words)
+ # used to push the remainder into the last word as a negative \kf; split evenly instead,
+ # and never let the last word go below 1 cs.
+ if total_cs < 5 * n_words:
+ per = max(1, total_cs // n_words)
+ out = [per] * (n_words - 1) + [max(1, total_cs - per * (n_words - 1))]
+ return out
scale = total_cs / max(1, sum(out))
out = [max(5, int(round(x * scale))) for x in out]
out[-1] += total_cs - sum(out)
+ while out[-1] < 1:
+ i = max(range(len(out) - 1), key=lambda j: out[j])
+ take = min(out[i] - 5, 1 - out[-1]) if out[i] > 5 else 0
+ if take <= 0:
+ break
+ out[i] -= take
+ out[-1] += take
return out
@@ -524,7 +536,7 @@ def main() -> int:
cmd += [output]
run(cmd)
result = probe(output, role="output")
- info(f"wrote {output} ({result.get('duration'):.3f}s, mux, subtitle codec {codec})")
+ info(f"wrote {output} ({fmt_secs(result.get('duration'))}, mux, subtitle codec {codec})")
emit(output)
return 0
@@ -576,7 +588,7 @@ def main() -> int:
cmd += (aac_args() if meta.get("audio") else ["-an"]) + [output]
run(cmd)
result = probe(output, role="output")
- info(f"wrote {output} ({result.get('duration'):.3f}s)")
+ info(f"wrote {output} ({fmt_secs(result.get('duration'))})")
emit(output)
return 0
diff --git a/scripts/color.py b/scripts/color.py
index 33507d9..68e1540 100755
--- a/scripts/color.py
+++ b/scripts/color.py
@@ -22,7 +22,7 @@ import os
import sys
from typing import List
-from _common import add_common, analyze_levels, apply_common, emit, aac_args, cfr_args, default_output, die, escape_filter_path, ffmpeg_base, info, probe, run, run_keeping_subtitles, x264_args, X264_PRESETS
+from _common import add_common, analyze_levels, apply_common, emit, aac_args, cfr_args, default_output, die, escape_filter_path, ffmpeg_base, info, probe, run, run_keeping_subtitles, x264_args, X264_PRESETS, fmt_secs
TONEMAPS = ["hable", "mobius", "reinhard", "bt2390", "clip", "linear", "gamma"]
@@ -315,7 +315,7 @@ def main() -> int:
cmd += x264_args(args.crf, args.preset) + cfr_args(meta) + (aac_args() if has_audio else [])
dropped_streams = run_keeping_subtitles(cmd, output)
r = probe(output, role="output")
- info(f"wrote {output} ({r['duration']:.3f}s, {r['video']['width']}x{r['video']['height']}, "
+ info(f"wrote {output} ({fmt_secs(r['duration'])}, {r['video']['width']}x{r['video']['height']}, "
f"{r['video']['color_transfer']}/{r['video']['color_primaries']}, {tag})")
extra = {"dropped_non_av_streams": dropped_streams}
if measurements is not None:
diff --git a/scripts/crop.py b/scripts/crop.py
index 56cdbb9..ed258f6 100644
--- a/scripts/crop.py
+++ b/scripts/crop.py
@@ -21,7 +21,7 @@ Examples:
import argparse
import sys
-from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run, video_args, X264_PRESETS
+from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run, video_args, X264_PRESETS, fmt_secs
def main() -> int:
@@ -72,7 +72,7 @@ def main() -> int:
result = probe(output, role="output")
v = result["video"]
- info(f"wrote {output} ({result['duration']:.3f}s, {v['width']}x{v['height']})")
+ info(f"wrote {output} ({fmt_secs(result['duration'])}, {v['width']}x{v['height']})")
emit(output)
return 0
diff --git a/scripts/cut.py b/scripts/cut.py
index e046cfb..959cd80 100755
--- a/scripts/cut.py
+++ b/scripts/cut.py
@@ -30,7 +30,7 @@ import sys
import tempfile
from typing import List, Tuple
-from _common import video_args, STATE, add_common, apply_common, audio_codec_for, emit, aac_args, cfr_args, default_output, die, ffmpeg_base, info, is_audio_output, parse_time, probe, run, X264_PRESETS, keyframes_near, MissingFpsError, concat_list_line, refuse_output_is_input
+from _common import video_args, STATE, add_common, apply_common, audio_codec_for, emit, aac_args, cfr_args, default_output, die, ffmpeg_base, info, is_audio_output, parse_time, probe, run, X264_PRESETS, keyframes_near, MissingFpsError, concat_list_line, refuse_output_is_input, fmt_secs
# keyframe timestamps found next to a requested cut that the tolerance turned into a re-encode
# (reported so the caller can choose a lossless cut at one of them next time)
@@ -56,6 +56,8 @@ def parse_segments(spec: str, fps=None) -> List[Tuple[float, float]]:
die(f"segment '{raw}' must look like START-END (e.g. 0:05-0:12)")
a, b = raw.rsplit("-", 1)
start, end = _t(a, fps), _t(b, fps)
+ if start < 0:
+ die(f"segment '{raw}': start must be >= 0")
if end <= start:
die(f"segment '{raw}': end must be after start")
segs.append((start, end))
@@ -225,7 +227,7 @@ def main() -> int:
# lossless but the keyframe snap exceeded --tolerance so this segment silently re-encoded instead)
mode = "copy" if not reencoded else ("accurate" if args.accurate else "hybrid")
keyframe_snapped = precision == "packet"
- info(f"wrote {output} ({got:.3f}s, expected ~{expected:.3f}s, "
+ info(f"wrote {output} ({fmt_secs(got)}, expected ~{expected:.3f}s, "
+ ("re-encoded" if reencoded else "lossless stream copy") + f", {precision} precision)")
emit(output, expected_duration=round(expected, 6), duration_error_ms=error_ms, precision=precision, reencoded=reencoded,
requested_start=round(segments[0][0], 6) if len(segments) == 1 else None,
diff --git a/scripts/deinterlace.py b/scripts/deinterlace.py
index 15c1794..3c72280 100644
--- a/scripts/deinterlace.py
+++ b/scripts/deinterlace.py
@@ -22,7 +22,7 @@ Examples:
import argparse
import sys
-from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, video_args, X264_PRESETS
+from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, video_args, X264_PRESETS, fmt_secs
MODES = {"frame": 0, "field": 1}
PARITIES = {"auto": -1, "tff": 0, "bff": 1}
@@ -76,7 +76,7 @@ def main() -> int:
result = probe(output, role="output")
v = result["video"]
- info(f"wrote {output} ({result['duration']:.3f}s, {v['width']}x{v['height']}, {v['fps']:g}fps, mode={args.mode})")
+ info(f"wrote {output} ({fmt_secs(result['duration'])}, {v['width']}x{v['height']}, {v['fps']:g}fps, mode={args.mode})")
emit(output, dropped_non_av_streams=dropped_streams)
return 0
diff --git a/scripts/denoise.py b/scripts/denoise.py
index 74a1f45..e10c83f 100644
--- a/scripts/denoise.py
+++ b/scripts/denoise.py
@@ -18,7 +18,7 @@ Examples:
import argparse
import sys
-from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, video_args, X264_PRESETS
+from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, video_args, X264_PRESETS, fmt_secs
# hqdn3d's own AVOptions default to 0 (off); these tested presets are the light/medium/heavy
# starting points its own documentation and common usage recommend (spatial then temporal,
@@ -85,7 +85,7 @@ def main() -> int:
result = probe(output, role="output")
v = result["video"]
- info(f"wrote {output} ({result['duration']:.3f}s, {v['width']}x{v['height']}, strength={args.strength})")
+ info(f"wrote {output} ({fmt_secs(result['duration'])}, {v['width']}x{v['height']}, strength={args.strength})")
emit(output, dropped_non_av_streams=dropped_streams)
return 0
diff --git a/scripts/export.py b/scripts/export.py
index a05cd17..f990d6c 100755
--- a/scripts/export.py
+++ b/scripts/export.py
@@ -26,7 +26,7 @@ import sys
from pathlib import Path
from typing import Dict, List
-from _common import STATE, add_common, apply_common, bt709_tag_args, emit, cfr_args, default_output, die, ffmpeg_base, info, probe, run, validate_color, pad_filters, add_pad_fill_args
+from _common import STATE, add_common, apply_common, bt709_tag_args, emit, cfr_args, default_output, die, ffmpeg_base, info, probe, run, validate_color, pad_filters, add_pad_fill_args, fmt_secs
PRESETS: Dict[str, Dict] = {
"youtube": {"w": 1920, "h": 1080, "ext": "mp4", "video": ["-c:v", "libx264", "-preset", "slow", "-crf", "18", "-profile:v", "high", "-pix_fmt", "yuv420p"], "audio": ["-c:a", "aac", "-b:a", "192k", "-ar", "48000"], "max": None, "desc": "1080p H.264, AAC 192k"},
"youtube4k": {"w": 3840, "h": 2160, "ext": "mp4", "video": ["-c:v", "libx264", "-preset", "slow", "-crf", "18", "-profile:v", "high", "-pix_fmt", "yuv420p"], "audio": ["-c:a", "aac", "-b:a", "192k", "-ar", "48000"], "max": None, "desc": "2160p H.264, AAC 192k"},
@@ -120,7 +120,7 @@ def main() -> int:
run(cmd)
result = probe(output, role="output")
v = result["video"]
- info(f"wrote {output} ({result['duration']:.3f}s, {v['width']}x{v['height']}, {v['codec']})")
+ info(f"wrote {output} ({fmt_secs(result['duration'])}, {v['width']}x{v['height']}, {v['codec']})")
emit(output)
return 0
diff --git a/scripts/fit.py b/scripts/fit.py
index 2aced2a..bcaf92b 100755
--- a/scripts/fit.py
+++ b/scripts/fit.py
@@ -38,7 +38,7 @@ import sys
from fractions import Fraction
from typing import List
-from _common import video_args, STATE, add_common, apply_common, emit, aac_args, cfr_args, default_output, die, ffmpeg_base, info, parse_time, probe, run, run_keeping_subtitles, validate_color, x264_args, pad_filters, add_pad_fill_args, X264_PRESETS, time_arg
+from _common import video_args, STATE, add_common, apply_common, emit, aac_args, cfr_args, default_output, die, ffmpeg_base, info, parse_time, probe, run, run_keeping_subtitles, validate_color, x264_args, pad_filters, add_pad_fill_args, X264_PRESETS, time_arg, fmt_secs
ASPECT_PRESETS = {"16:9": Fraction(16, 9), "9:16": Fraction(9, 16), "1:1": Fraction(1, 1), "4:5": Fraction(4, 5), "4:3": Fraction(4, 3), "21:9": Fraction(21, 9)}
@@ -251,7 +251,7 @@ def main() -> int:
dropped_streams = run_keeping_subtitles(cmd, output)
result = probe(output, role="output")
- msg = f"wrote {output} ({result['duration']:.3f}s, {result['video']['width']}x{result['video']['height']})"
+ msg = f"wrote {output} ({fmt_secs(result['duration'])}, {result['video']['width']}x{result['video']['height']})"
if abs(factor - 1.0) > 1e-4:
msg += f", speed {factor:.3f}x"
info(msg)
diff --git a/scripts/freeze.py b/scripts/freeze.py
index b9e85e7..c42b497 100644
--- a/scripts/freeze.py
+++ b/scripts/freeze.py
@@ -19,7 +19,7 @@ Examples:
import argparse
import sys
-from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, video_args, X264_PRESETS, MissingFpsError, parse_time
+from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, video_args, X264_PRESETS, MissingFpsError, parse_time, fmt_secs, run
def main() -> int:
@@ -101,11 +101,18 @@ def main() -> int:
cmd += aac_args()
else:
cmd += ["-an"]
- dropped_streams = run_keeping_subtitles(cmd, output)
+ if args.mode == "insert":
+ # the picture gains `hold` seconds at `at`; a stream-copied subtitle track would keep its
+ # old timestamps and every cue after the freeze would fire early (same reasoning as
+ # fit.py --method speed). Drop it rather than ship captions that lie.
+ run(cmd + [output])
+ dropped_streams = bool(meta.get("subtitle_streams") or meta.get("data_streams"))
+ else:
+ dropped_streams = run_keeping_subtitles(cmd, output)
result = probe(output, role="output")
v = result["video"]
- info(f"wrote {output} ({result['duration']:.3f}s, {v['width']}x{v['height']}, froze {args.hold:g}s at {at:g}s, mode={args.mode})")
+ info(f"wrote {output} ({fmt_secs(result['duration'])}, {v['width']}x{v['height']}, froze {args.hold:g}s at {at:g}s, mode={args.mode})")
emit(output, dropped_non_av_streams=dropped_streams)
return 0
diff --git a/scripts/graphics.py b/scripts/graphics.py
index 8fd2443..e46ba54 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_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, drawtext_boxborderw, X264_PRESETS, time_arg
+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, drawtext_boxborderw, X264_PRESETS, time_arg, fmt_secs
TEMPLATES = ["lower-third", "title", "chapter", "progress", "countdown", "bug"]
@@ -169,7 +169,7 @@ def main() -> int:
cmd += aac_args() if meta.get("audio") else ["-an"]
dropped_streams = run_keeping_subtitles(cmd, output)
r = probe(output, role="output")
- info(f"wrote {output} ({r['duration']:.3f}s, {args.template})")
+ info(f"wrote {output} ({fmt_secs(r['duration'])}, {args.template})")
emit(output, template=args.template, dropped_non_av_streams=dropped_streams)
return 0
diff --git a/scripts/grid.py b/scripts/grid.py
index 66b9cd5..472ff3a 100644
--- a/scripts/grid.py
+++ b/scripts/grid.py
@@ -25,7 +25,7 @@ import argparse
import os
import sys
-from _common import add_common, apply_common, aac_args, cfr_args, default_font_file, default_output, die, emit, X264_PRESETS, \
+from _common import add_common, apply_common, aac_args, cfr_args, default_font_file, default_output, die, emit, X264_PRESETS, fmt_secs, \
escape_drawtext, escape_filter_path, ffmpeg_base, info, probe, run, validate_color, video_args
LABEL_MARGIN = 10
@@ -137,7 +137,7 @@ def main() -> int:
result = probe(output, role="output")
v = result["video"]
- info(f"wrote {output} ({result['duration']:.3f}s, {v['width']}x{v['height']}, {args.cols}x{args.rows} grid, "
+ info(f"wrote {output} ({fmt_secs(result['duration'])}, {v['width']}x{v['height']}, {args.cols}x{args.rows} grid, "
f"{n} clips, {'padded to longest' if args.pad else 'stopped at shortest'})")
emit(output, cols=args.cols, rows=args.rows, clips=n)
return 0
diff --git a/scripts/insert.py b/scripts/insert.py
index abb040b..194fb8c 100644
--- a/scripts/insert.py
+++ b/scripts/insert.py
@@ -27,7 +27,7 @@ import argparse
import math
import sys
-from _common import add_common, apply_common, default_output, die, emit, ffmpeg_base, info, parse_time, probe, run, video_args, X264_PRESETS, time_arg
+from _common import add_common, apply_common, default_output, die, emit, ffmpeg_base, info, parse_time, probe, run, video_args, X264_PRESETS, time_arg, fmt_secs
def even(n: float) -> int:
@@ -119,7 +119,7 @@ def main() -> int:
result = probe(output, role="output")
v = result["video"]
- info(f"wrote {output} ({result['duration']:.3f}s, {v['width']}x{v['height']}, {v['fps']:g}fps)")
+ info(f"wrote {output} ({fmt_secs(result['duration'])}, {v['width']}x{v['height']}, {v['fps']:g}fps)")
emit(output)
return 0
diff --git a/scripts/join.py b/scripts/join.py
index 3d4b067..f828b74 100755
--- a/scripts/join.py
+++ b/scripts/join.py
@@ -23,7 +23,7 @@ import argparse
import sys
from typing import List
-from _common import STATE, video_args, aac_args, add_common, apply_common, audio_codec_for, default_output, die, emit, ffmpeg_base, info, is_audio_output, probe, run, validate_color, X264_PRESETS
+from _common import STATE, video_args, aac_args, add_common, apply_common, audio_codec_for, default_output, die, emit, ffmpeg_base, info, is_audio_output, probe, run, validate_color, X264_PRESETS, fmt_secs
TRANSITIONS = ["fade", "dissolve", "wipeleft", "wiperight", "wipeup", "wipedown", "slideleft", "slideright",
"circleopen", "circleclose", "fadeblack", "fadewhite", "smoothleft", "smoothright", "radial", "none"]
@@ -75,7 +75,7 @@ def join_audio(args: argparse.Namespace, metas: List[dict]) -> int:
die(f"{output} unexpectedly contains a video stream")
if a.get("sample_rate") != rate or a.get("channels") != channels:
die(f"{output} is {a.get('sample_rate')} Hz {a.get('channels')} ch, expected {rate} Hz {channels} ch")
- info(f"wrote {output} ({r['duration']:.3f}s, expected ~{expected:.3f}s, audio {a.get('codec')} {channels}ch {rate}Hz, {n} clips, "
+ info(f"wrote {output} ({fmt_secs(r['duration'])}, expected ~{expected:.3f}s, audio {a.get('codec')} {channels}ch {rate}Hz, {n} clips, "
+ ("crossfade" if d else "butt join") + ")")
emit(output, mode="audio", clips=n, transition=args.transition if d else "none", expected_duration=round(expected, 3),
sample_rate=rate, channels=channels, video=False)
@@ -172,9 +172,18 @@ def main() -> int:
# first clip used to drag an HDR second clip down to 8-bit without a tone map.
hdr_meta = next((m for m in metas if (m.get("video") or {}).get("hdr")), None)
pixfmt = "yuv420p10le" if hdr_meta else "yuv420p"
+ # the audio-only join keeps the widest layout; the video join used to force stereo and
+ # silently dropped the centre/LFE of 5.1 material
+ chans = [(m.get("audio") or {}).get("channels") or 2 for m in metas]
+ channels = args.channels or max(chans)
+ layout = LAYOUTS.get(channels)
+ if layout is None:
+ die(f"{channels}-channel output has no standard layout here (1, 2, 6 or 8); pass --channels")
+ if len(set(chans)) > 1:
+ info(f"channel counts differ ({', '.join(str(c) for c in chans)}); every clip becomes {layout}")
for i in range(n):
parts.append(f"[{i}:v]{geo},setsar=1,fps={fps:g},format={pixfmt},settb=AVTB[v{i}]")
- parts.append(f"[{audio_src[i]}]aformat=sample_rates=48000:channel_layouts=stereo,asetpts=PTS-STARTPTS[a{i}]")
+ parts.append(f"[{audio_src[i]}]aformat=sample_rates=48000:channel_layouts={layout},asetpts=PTS-STARTPTS[a{i}]")
if args.transition == "none":
chain = "".join(f"[v{i}][a{i}]" for i in range(n))
@@ -196,7 +205,7 @@ def main() -> int:
run(cmd)
expected = sum(durs) - d * (n - 1)
r = probe(output, role="output")
- info(f"wrote {output} ({r['duration']:.3f}s, expected ~{expected:.3f}s, {w}x{h} @ {fps:g}fps, {n} clips, {args.transition})")
+ info(f"wrote {output} ({fmt_secs(r['duration'])}, expected ~{expected:.3f}s, {w}x{h} @ {fps:g}fps, {n} clips, {args.transition})")
emit(output, mode="video", clips=n, transition=args.transition, expected_duration=round(expected, 3))
return 0
diff --git a/scripts/loop.py b/scripts/loop.py
index dafc8de..59bb922 100644
--- a/scripts/loop.py
+++ b/scripts/loop.py
@@ -18,7 +18,7 @@ import argparse
import math
import sys
-from _common import add_common, aac_args, apply_common, cfr_args, default_output, die, emit, ffmpeg_base, info, parse_time, probe, run, video_args, X264_PRESETS, time_arg
+from _common import add_common, aac_args, apply_common, cfr_args, default_output, die, emit, ffmpeg_base, info, parse_time, probe, run, video_args, X264_PRESETS, time_arg, fmt_secs
def main() -> int:
@@ -71,7 +71,7 @@ def main() -> int:
result = probe(output, role="output")
v = result["video"]
- info(f"wrote {output} ({result['duration']:.3f}s, {v['width']}x{v['height']}, source {src_dur:.3f}s looped)")
+ info(f"wrote {output} ({fmt_secs(result['duration'])}, {v['width']}x{v['height']}, source {src_dur:.3f}s looped)")
emit(output)
return 0
diff --git a/scripts/multicam.py b/scripts/multicam.py
index f9c10f6..f7e9432 100755
--- a/scripts/multicam.py
+++ b/scripts/multicam.py
@@ -29,7 +29,7 @@ import argparse
import sys
from typing import List, Tuple
-from _common import video_args, aac_args, add_common, apply_common, default_output, die, emit, ffmpeg_base, info, parse_time, probe, run, x264_args, X264_PRESETS
+from _common import video_args, aac_args, add_common, apply_common, default_output, die, emit, ffmpeg_base, info, parse_time, probe, run, x264_args, X264_PRESETS, fmt_secs
from sync import measure_offset
@@ -203,10 +203,10 @@ def main() -> int:
output = args.output or default_output(args.inputs[0], "multicam", "mp4")
cmd += ["-filter_complex", ";".join(parts), "-map", "[vout]", "-map", "[aout]"]
- cmd += video_args(metas[0], args.crf, args.preset) + aac_args() + ["-shortest", output]
+ cmd += video_args(metas[0], args.crf, args.preset) + aac_args() + ["-t", f"{ref_dur:.3f}", output]
run(cmd)
r = probe(output, role="output")
- info(f"wrote {output} ({r['duration']:.3f}s, {len(filled)} cuts, audio from input {a})")
+ info(f"wrote {output} ({fmt_secs(r['duration'])}, {len(filled)} cuts, audio from input {a})")
emit(output, cuts=[[round(s, 3), round(e, 3), c] for s, e, c in filled], **report)
return 0
diff --git a/scripts/overlay.py b/scripts/overlay.py
index bddf092..a73d3f6 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, 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, validate_color, x264_args, X264_PRESETS, time_arg
+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, validate_color, x264_args, X264_PRESETS, time_arg, fmt_secs
POS = {
"top-left": ("{m}", "{m}"),
@@ -267,7 +267,7 @@ def main() -> int:
dropped_streams = run_keeping_subtitles(cmd, output)
if not STATE.dry_run:
result = probe(output, role="output")
- info(f"wrote {output} ({result['duration']:.3f}s)")
+ info(f"wrote {output} ({fmt_secs(result['duration'])})")
emit(output, dropped_non_av_streams=dropped_streams)
return 0
diff --git a/scripts/pad.py b/scripts/pad.py
index a767c76..37ed0ee 100644
--- a/scripts/pad.py
+++ b/scripts/pad.py
@@ -16,7 +16,7 @@ Examples:
import argparse
import sys
-from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, validate_color, video_args, X264_PRESETS, time_arg
+from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, validate_color, video_args, X264_PRESETS, time_arg, fmt_secs
def main() -> int:
@@ -61,7 +61,7 @@ def main() -> int:
result = probe(output, role="output")
v = result["video"]
- info(f"wrote {output} ({result['duration']:.3f}s, {v['width']}x{v['height']}, +{args.start:g}s start / +{args.end:g}s end)")
+ info(f"wrote {output} ({fmt_secs(result['duration'])}, {v['width']}x{v['height']}, +{args.start:g}s start / +{args.end:g}s end)")
emit(output, dropped_non_av_streams=dropped_streams)
return 0
diff --git a/scripts/proxy.py b/scripts/proxy.py
index 7f66074..191acaf 100644
--- a/scripts/proxy.py
+++ b/scripts/proxy.py
@@ -25,7 +25,7 @@ Examples:
import argparse
import sys
-from _common import add_common, apply_common, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run, video_args
+from _common import add_common, apply_common, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run, video_args, fmt_secs
def even(n: float) -> int:
@@ -73,7 +73,7 @@ def main() -> int:
result = probe(output)
v = result["video"]
- info(f"wrote {output} ({result['duration']:.3f}s, {v['width']}x{v['height']}, {v['codec']}, crf {args.crf})")
+ info(f"wrote {output} ({fmt_secs(result['duration'])}, {v['width']}x{v['height']}, {v['codec']}, crf {args.crf})")
emit(output)
return 0
diff --git a/scripts/redact.py b/scripts/redact.py
index 01dd72c..f6331e3 100644
--- a/scripts/redact.py
+++ b/scripts/redact.py
@@ -20,7 +20,7 @@ Examples:
import argparse
import sys
-from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, video_args, X264_PRESETS
+from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, video_args, X264_PRESETS, fmt_secs
def main() -> int:
@@ -91,7 +91,7 @@ def main() -> int:
result = probe(output, role="output")
v = result["video"]
- info(f"wrote {output} ({result['duration']:.3f}s, {v['width']}x{v['height']}, {args.mode} at x={args.x} y={args.y} {args.width}x{args.height})")
+ info(f"wrote {output} ({fmt_secs(result['duration'])}, {v['width']}x{v['height']}, {args.mode} at x={args.x} y={args.y} {args.width}x{args.height})")
emit(output, dropped_non_av_streams=dropped_streams)
return 0
diff --git a/scripts/render.py b/scripts/render.py
index d7fedd2..55301a2 100755
--- a/scripts/render.py
+++ b/scripts/render.py
@@ -55,7 +55,7 @@ import sys
from pathlib import Path
from typing import Any, Dict, List
-from _common import STATE, add_common, apply_common, child_args, die, emit, info, probe, run_tool
+from _common import STATE, add_common, apply_common, child_args, die, emit, info, probe, run_tool, place_output
HERE = Path(__file__).resolve().parent
@@ -350,8 +350,7 @@ def main() -> int:
stages_done.append("export")
else:
if not STATE.dry_run:
- import shutil
- shutil.copyfile(current, output)
+ place_output(current, output)
info(f"copied final stage to {output}")
current = output
diff --git a/scripts/reverse.py b/scripts/reverse.py
index 1cca0dc..4e0169d 100644
--- a/scripts/reverse.py
+++ b/scripts/reverse.py
@@ -14,7 +14,7 @@ Examples:
import argparse
import sys
-from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run, video_args, X264_PRESETS
+from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run, video_args, X264_PRESETS, fmt_secs
def main() -> int:
@@ -47,7 +47,7 @@ def main() -> int:
run(cmd)
result = probe(output, role="output")
- info(f"wrote {output} ({result['duration']:.3f}s, {result['video']['width']}x{result['video']['height']})")
+ info(f"wrote {output} ({fmt_secs(result['duration'])}, {result['video']['width']}x{result['video']['height']})")
emit(output)
return 0
diff --git a/scripts/sequence.py b/scripts/sequence.py
index fb5a048..66a5956 100644
--- a/scripts/sequence.py
+++ b/scripts/sequence.py
@@ -1,3 +1,4 @@
+import re
#!/usr/bin/env python3
"""Turn a numbered image sequence into a video.
@@ -19,7 +20,7 @@ import sys
import tempfile
from pathlib import Path
-from _common import add_common, apply_common, default_output, die, emit, ffmpeg_base, info, probe, run, video_args, X264_PRESETS, concat_list_line
+from _common import add_common, apply_common, default_output, die, emit, ffmpeg_base, info, probe, run, video_args, X264_PRESETS, concat_list_line, fmt_secs
def even(n: float) -> int:
@@ -31,6 +32,11 @@ def _concat_list_line(path: Path) -> str:
return concat_list_line(str(path))
+def natural_key(name: str) -> list:
+ """img2 < img10: digit runs compare as numbers, the rest case-insensitively."""
+ return [int(t) if t.isdigit() else t.lower() for t in re.split(r"(\d+)", name)]
+
+
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--dir", required=True, help="directory containing the frames")
@@ -54,7 +60,9 @@ def main() -> int:
is_glob = "%" not in args.pattern
if is_glob:
- frames = sorted(directory.glob(args.pattern))
+ # natural order: img2 before img10 (a lexical sort put every img1x before img2 and the
+ # frames came out shuffled); a printf pattern never had this problem
+ frames = sorted(directory.glob(args.pattern), key=lambda p: natural_key(p.name))
if not frames:
die(f"no files in {args.dir} match glob '{args.pattern}'")
info(f"found {len(frames)} frames matching '{args.pattern}'")
@@ -113,7 +121,7 @@ def main() -> int:
result = probe(output, role="output")
v = result["video"]
- info(f"wrote {output} ({result['duration']:.3f}s, {v['width']}x{v['height']}, {v['fps']:g}fps)")
+ info(f"wrote {output} ({fmt_secs(result['duration'])}, {v['width']}x{v['height']}, {v['fps']:g}fps)")
emit(output)
return 0
diff --git a/scripts/silence.py b/scripts/silence.py
index 511eacb..4d7020c 100755
--- a/scripts/silence.py
+++ b/scripts/silence.py
@@ -17,7 +17,7 @@ import re
import sys
from typing import List, Tuple
-from _common import STATE, video_args, add_common, apply_common, audio_codec_for, cfr_args, default_output, die, emit, ffmpeg_base, info, is_audio_output, print_json, probe, require_tool, run, x264_args, X264_PRESETS, measured_level_dbfs, run_analysis, dry_run_input_pending
+from _common import STATE, video_args, add_common, apply_common, audio_codec_for, cfr_args, default_output, die, emit, ffmpeg_base, info, is_audio_output, print_json, probe, require_tool, run, x264_args, X264_PRESETS, measured_level_dbfs, run_analysis, dry_run_input_pending, fmt_secs
SIL_RE = re.compile(r"silence_(start|end): ([0-9.]+)")
@@ -134,7 +134,7 @@ def main() -> int:
cmd += ["-af", af] + audio_codec_for(output) + [output]
run(cmd)
r = probe(output, role="output")
- info(f"wrote {output} ({r['duration']:.3f}s, expected ~{kept:.3f}s)")
+ info(f"wrote {output} ({fmt_secs(r['duration'])}, expected ~{kept:.3f}s)")
emit(output, **summary)
return 0
diff --git a/scripts/speedramp.py b/scripts/speedramp.py
index 5a68745..9b9e24c 100644
--- a/scripts/speedramp.py
+++ b/scripts/speedramp.py
@@ -19,7 +19,7 @@ import argparse
import sys
from typing import List, Tuple
-from _common import add_common, apply_common, aac_args, default_output, die, emit, ffmpeg_base, info, probe, run, video_args, X264_PRESETS
+from _common import add_common, apply_common, aac_args, default_output, die, emit, ffmpeg_base, info, probe, run, video_args, X264_PRESETS, fmt_secs, parse_time
MAX_SPEED = 20.0
MIN_SPEED = 0.05
@@ -41,11 +41,11 @@ def atempo_chain(factor: float) -> str:
def parse_segment(raw: str) -> Tuple[float, float, float]:
try:
- span, factor_s = raw.split(":")
- start_s, end_s = span.split("-")
- start, end, factor = float(start_s), float(end_s), float(factor_s)
+ span, factor_s = raw.rsplit(":", 1)
+ start_s, end_s = span.rsplit("-", 1)
+ start, end, factor = parse_time(start_s), parse_time(end_s), float(factor_s)
except ValueError:
- die(f"--segment must look like START-END:FACTOR, got '{raw}'")
+ die(f"--segment must look like START-END:FACTOR (times in seconds or mm:ss), got '{raw}'")
if end <= start:
die(f"--segment {raw}: END must be after START")
if not MIN_SPEED <= factor <= MAX_SPEED:
@@ -114,7 +114,7 @@ def main() -> int:
result = probe(output, role="output")
v = result["video"]
- info(f"wrote {output} ({result['duration']:.3f}s, {v['width']}x{v['height']}, {len(segments)} speed segments)")
+ info(f"wrote {output} ({fmt_secs(result['duration'])}, {v['width']}x{v['height']}, {len(segments)} speed segments)")
emit(output)
return 0
diff --git a/scripts/sphere.py b/scripts/sphere.py
index 97a1548..7182625 100644
--- a/scripts/sphere.py
+++ b/scripts/sphere.py
@@ -31,7 +31,7 @@ Examples:
import argparse
import sys
-from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, video_args, X264_PRESETS
+from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, video_args, X264_PRESETS, fmt_secs
# v360's own AVOption names for the input projections real 360 cameras/exports actually
# produce (ffmpeg -h filter=v360 documents 24 total; this is the subset a caller is likely
@@ -117,7 +117,7 @@ def main() -> int:
result = probe(output, role="output")
v = result["video"]
- info(f"wrote {output} ({result['duration']:.3f}s, {v['width']}x{v['height']}, yaw={args.yaw:g} pitch={args.pitch:g})")
+ info(f"wrote {output} ({fmt_secs(result['duration'])}, {v['width']}x{v['height']}, yaw={args.yaw:g} pitch={args.pitch:g})")
emit(output, dropped_non_av_streams=dropped_streams)
return 0
diff --git a/scripts/stabilize.py b/scripts/stabilize.py
index 3c56a67..683fb45 100644
--- a/scripts/stabilize.py
+++ b/scripts/stabilize.py
@@ -27,7 +27,7 @@ import sys
import tempfile
from pathlib import Path
-from _common import STATE, add_common, apply_common, aac_args, cfr_args, default_output, die, emit, escape_filter_path, ffmpeg_base, info, probe, require_tool, run, video_args, X264_PRESETS, run_analysis, dry_run_input_pending
+from _common import STATE, add_common, apply_common, aac_args, cfr_args, default_output, die, emit, escape_filter_path, ffmpeg_base, info, probe, require_tool, run, video_args, X264_PRESETS, run_analysis, dry_run_input_pending, fmt_secs
def main() -> int:
@@ -94,7 +94,7 @@ def main() -> int:
run(cmd)
result = probe(output, role="output")
- info(f"wrote {output} ({result['duration']:.3f}s, {result['video']['width']}x{result['video']['height']})")
+ info(f"wrote {output} ({fmt_secs(result['duration'])}, {result['video']['width']}x{result['video']['height']})")
emit(output)
return 0
diff --git a/scripts/straighten.py b/scripts/straighten.py
index 580ce1c..e485a05 100644
--- a/scripts/straighten.py
+++ b/scripts/straighten.py
@@ -22,7 +22,7 @@ import argparse
import math
import sys
-from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, validate_color, video_args, X264_PRESETS
+from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, validate_color, video_args, X264_PRESETS, fmt_secs
def main() -> int:
@@ -88,7 +88,7 @@ def main() -> int:
result = probe(output, role="output")
v = result["video"]
- info(f"wrote {output} ({result['duration']:.3f}s, {v['width']}x{v['height']}, degrees={args.degrees:g}, fit={args.fit})")
+ info(f"wrote {output} ({fmt_secs(result['duration'])}, {v['width']}x{v['height']}, degrees={args.degrees:g}, fit={args.fit})")
emit(output, dropped_non_av_streams=dropped_streams)
return 0
diff --git a/scripts/sync.py b/scripts/sync.py
index a73dd45..98c320f 100755
--- a/scripts/sync.py
+++ b/scripts/sync.py
@@ -291,10 +291,13 @@ def main() -> int:
if head_trim > 0:
cmd += ["-ss", f"{head_trim:.4f}"]
cmd += ["-i", args.second, "-map", "0:v:0", "-map", "1:a:0", "-c:v", "copy"]
- af_parts = drift_af + ([f"adelay={delay_ms}:all=1"] if delay_ms > 0 else [])
- if af_parts:
- cmd += ["-af", ",".join(af_parts)]
- cmd += aac_args() + ["-shortest", output]
+ # the reference picture is the deliverable: pad the (possibly trimmed) second audio to
+ # its length instead of -shortest, which cut the reference's tail whenever the second
+ # file started earlier (head_trim > 0) or was simply shorter
+ ref_dur = probe(args.reference).get("duration")
+ af_parts = drift_af + ([f"adelay={delay_ms}:all=1"] if delay_ms > 0 else []) + ["apad"]
+ cmd += ["-af", ",".join(af_parts)]
+ cmd += aac_args() + (["-t", f"{ref_dur:.3f}"] if ref_dur else ["-shortest"]) + [output]
proc = run(cmd, check=False)
if proc.returncode != 0:
cmd = [c for c in cmd if c != "copy"]
diff --git a/scripts/waveform.py b/scripts/waveform.py
index 09aeca7..e2bb158 100644
--- a/scripts/waveform.py
+++ b/scripts/waveform.py
@@ -22,7 +22,7 @@ Examples:
import argparse
import sys
-from _common import add_common, apply_common, aac_args, default_output, die, emit, ffmpeg_base, info, probe, run, validate_color, X264_PRESETS
+from _common import add_common, apply_common, aac_args, default_output, die, emit, ffmpeg_base, info, probe, run, validate_color, X264_PRESETS, fmt_secs
WAVEFORM_MODES = ["point", "line", "p2p", "cline"]
@@ -88,7 +88,7 @@ def main() -> int:
result = probe(output, role="output")
v = result["video"]
- info(f"wrote {output} ({result['duration']:.3f}s, {v['width']}x{v['height']}, {args.style})")
+ info(f"wrote {output} ({fmt_secs(result['duration'])}, {v['width']}x{v['height']}, {args.style})")
emit(output)
return 0
diff --git a/tests/test_contract.py b/tests/test_contract.py
index 7f8ce51..9da4970 100644
--- a/tests/test_contract.py
+++ b/tests/test_contract.py
@@ -1521,6 +1521,91 @@ class ContractTests(unittest.TestCase):
self.assertFalse((bdir / "bdir").exists(), "outdir was doubled")
self.assertTrue((bdir / "out").is_dir(), "default outdir is <folder>/out")
+ def test_fifth_audit_regressions(self):
+ """Pins from the fifth audit (100 items, 2026-09-12). Confirmed and fixed here: yuv410p
+ read as 10-bit (#2); audio --mono halved an already-mono track (#3); sync --replace-audio
+ cut the reference to the shorter second (#4); 25+ tools raised TypeError formatting a
+ None duration after a successful encode (#5); energy karaoke gave the last word a
+ negative \kf on a short cue (#6); the energy decode ran outside --timeout (#7); render's
+ final copy bypassed the output guards (#8); the video join forced stereo (#10); multicam
+ -shortest (#12); ffprobe JSON parse without a guard (#14); git-build version strings read
+ as 0.0 (#15); freeze --mode insert desynced copied subtitles (#31); sequence globbed
+ frames lexically (#98); negative --segments start (#18); speedramp refused mm:ss (#29);
+ two MEDIA_EXT lists (#55); colour alpha > 1 reached ffmpeg (#69); blur radius > frame (#57)."""
+ # 2, 5, 55, 69, 57 -- helpers
+ for pix, depth in (("yuv410p", 8), ("yuv420p", 8), ("yuv420p10le", 10), ("gbrp12be", 12), ("gray16le", 16), ("rgb24", 8), ("rgb48le", 16)):
+ self.assertEqual(_common._bit_depth(pix), depth, pix)
+ self.assertEqual(_common.fmt_secs(None), "?s")
+ self.assertEqual(_common.fmt_secs(1.5), "1.500s")
+ leftovers = [p.name for p in SCRIPTS.glob("*.py") if re.search(r"duration['\"]\]:\.3f\}s|duration['\"]\):\.3f\}s", p.read_text(encoding="utf-8"))]
+ self.assertEqual(leftovers, [], "a script still formats a possibly-None duration with :.3f")
+ self.assertIn(".mxf", _common.MEDIA_EXT)
+ import batch as batch_mod # noqa: E402
+ self.assertTrue(batch_mod.MEDIA_EXT <= _common.MEDIA_EXT)
+ self.assertEqual(_common.validate_color("[email protected]"), "[email protected]")
+ with self.assertRaises(SystemExit):
+ _common.validate_color("red@2")
+ self.assertIn("boxblur=7:2", _common.pad_filters(16, 16, "blur", "black", 20))
+ import sequence as seq_mod # noqa: E402
+ self.assertEqual(sorted(["img10.png", "img2.png", "img1.png"], key=seq_mod.natural_key), ["img1.png", "img2.png", "img10.png"])
+ # 6 -- karaoke never emits a non-positive word length
+ import caption as cap_mod # noqa: E402
+ words = cap_mod.word_durations_from_audio(str(self.src), 0.0, 0.5, 20)
+ self.assertEqual((len(words), sum(words), min(words) >= 1), (20, 50, True), words)
+ # 3 -- mono input, --mono: no stereo pan
+ mono = self.out("mono_in.mp4")
+ ffmpeg("-f", "lavfi", "-i", "sine=f=440:r=48000:d=2", "-f", "lavfi", "-i", "testsrc2=size=64x64:rate=30", "-t", "2", "-ac", "1", "-c:a", "aac", "-c:v", "libx264", "-preset", "veryfast", mono)
+ doc = json.loads(tool("audio", mono, "--mono", "--dry-run", "--json", "-o", self.out("mono_out.mp4")).stdout)
+ self.assertNotIn("pan=mono", " ".join(map(str, doc["commands"])))
+ # 10 -- 5.1 + stereo video join keeps 5.1
+ six = self.out("six.mp4")
+ ffmpeg("-f", "lavfi", "-i", "sine=f=440:r=48000:d=2", "-f", "lavfi", "-i", "testsrc2=size=64x64:rate=30", "-t", "2", "-af", "aformat=channel_layouts=5.1", "-c:a", "aac", "-c:v", "libx264", "-preset", "veryfast", six)
+ doc = json.loads(tool("join", six, mono, "--transition", "none", "--dry-run", "--json", "-o", self.out("join51.mp4")).stdout)
+ self.assertIn("channel_layouts=5.1", " ".join(map(str, doc["commands"])))
+ self.assertNotIn("channel_layouts=stereo", " ".join(map(str, doc["commands"])))
+ # 12 -- multicam trims to the cut list, not the shortest stream
+ doc = json.loads(tool("multicam", self.src, self.src, "--auto", "2", "--dry-run", "--json", "-o", self.out("mc.mp4")).stdout)
+ cmd = " ".join(map(str, doc["commands"]))
+ self.assertNotIn("-shortest", cmd)
+ self.assertIn("-t 6.000", cmd)
+ # 4 -- replace-audio keeps the reference's length when the second is shorter
+ short = self.out("second_short.mp4")
+ ffmpeg("-ss", "1", "-t", "3", "-i", self.src, "-c", "copy", short)
+ doc = json.loads(tool("sync", self.src, short, "--replace-audio", "--json", "-o", self.out("synced_short.mp4")).stdout)
+ self.assertAlmostEqual(doc["probe"]["duration"], 6.0, delta=0.15, msg=doc.get("meaning"))
+ # 18, 29 -- time grammar
+ proc = tool("cut", self.src, "--segments=-1-2", "--json", "-o", self.out("neg.mp4"), check=False)
+ self.assertEqual(json.loads(proc.stdout)["error"]["kind"], "input")
+ doc = json.loads(tool("speedramp", self.src, "--segment", "0-0:03:2", "--segment", "0:03-0:06:1", "--dry-run", "--json", "-o", self.out("ramp.mp4")).stdout)
+ self.assertEqual(doc["status"], "completed")
+ # 31 -- freeze --mode insert drops a copied subtitle track instead of desyncing it
+ srt = self.out("fz.srt"); srt.write_text("1\n00:00:00,500 --> 00:00:01,000\na\n\n2\n00:00:02,000 --> 00:00:02,500\nb\n\n", encoding="utf-8")
+ mkv = self.out("fz_in.mkv")
+ ffmpeg("-i", self.src, "-i", srt, "-map", "0", "-map", "1", "-c", "copy", "-c:s", "srt", mkv)
+ doc = json.loads(tool("freeze", mkv, "--at", "1", "--hold", "1", "--mode", "insert", "--fast", "--json", "-o", self.out("fz_out.mkv")).stdout)
+ self.assertTrue(doc["dropped_non_av_streams"])
+ self.assertEqual(doc["probe"].get("subtitle_streams") or 0, 0)
+ # 8 -- render's final copy goes through the output guards (existing file replaced via a temp, nothing left behind)
+ out = self.out("rend_out.mp4"); shutil.copyfile(self.src, out)
+ proj = self.out("rend.json"); proj.write_text(json.dumps({"output": str(out), "clips": [{"src": str(self.src), "in": 0, "out": 1}]}))
+ doc = json.loads(tool("render", proj, "--fast", "--json").stdout)
+ self.assertEqual(doc["status"], "completed")
+ self.assertAlmostEqual(doc["probe"]["duration"], 1.0, delta=0.15)
+ self.assertEqual([p.name for p in out.parent.glob(".rend_out.ffskill-*")], [])
+
+ @unittest.skipIf(platform.system() == "Windows", "the fake ffprobe is a #!/bin/sh shim on a POSIX-only PATH")
+ def test_ffmpeg_version_falls_back_to_libavutil_on_git_builds(self):
+ """Fifth audit #15: `ffprobe version N-115000-g...` has no major.minor, so the version was
+ (0, 0) and every version branch took the oldest spelling -- on a 7.1 git build that skipped
+ bt709_tag_args()'s workaround. The libavutil major maps onto the FFmpeg major."""
+ shim = self.out("verprobe_shim"); shim.mkdir(exist_ok=True)
+ (shim / "ffprobe").write_text("#!/bin/sh\nprintf 'ffprobe version N-115000-g1234abcd Copyright (c) 2007-2025\\nlibavutil 59. 39.100 / 59. 39.100\\n'\n")
+ (shim / "ffprobe").chmod(0o755)
+ code = ("import sys; sys.path.insert(0, %r); import _common; print(_common.ffmpeg_version())" % str(SCRIPTS))
+ env = dict(os.environ, PATH=f"{shim}{os.pathsep}{os.environ['PATH']}")
+ out = subprocess.run([sys.executable, "-c", code], env=env, stdout=subprocess.PIPE, text=True, check=True).stdout
+ self.assertEqual(out.strip(), "(7, 0)")
+
def test_cut_segments_refuses_output_equal_to_input(self):
"""Fourth review, P0: `cut.py in.mp4 --segments 0-1,2-3 -o in.mp4` replaced the source
with the 2 s join. The run() guard compares the ffmpeg command's -i paths with its output,