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.

color.py --correct: add gamma, lift/gain, levels, and curves (#95)

Shogo Kajiyamac3a4a5f0ef66
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c926ba5..6d0ff74 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,48 @@
(nothing yet)
+## 0.12.3 — `color.py --correct` gains gamma, lift/gain, levels and curves
+
+Closes a long-standing, documented gap: the downstream `color-grading-skill` has carried
+`GAMMA`/`LIFT`/`GAIN`/`LEVELS`/`CURVES` in its own `UNSUPPORTED_OPERATIONS` because
+"ffmpeg-skill exposes no typed X filter in its public contract". `--correct` gains five more
+typed flags, all folded into the same fixed filter chain the existing `--exposure`/`--contrast`/
+`--saturation`/`--temperature`/`--tint` already build — no new mode, no filter string ever
+accepted from the caller:
+
+- **`--gamma`** (0.1..10, default 1=unchanged): `eq`'s own `gamma` option, added to the same
+ `eq=contrast=...:saturation=...` term contrast/saturation already use, not a second `eq` call.
+- **`--lift` / `--gain`** (-1..1 each, default 0=unchanged): classic three-way colour correction,
+ extending the same `colorbalance` call `--tint` already used for midtones — `--lift` sets the
+ shadow channels (`rs=gs=bs`), `--gain` the highlight channels (`rh=gh=bh`), the same
+ all-three-channels-together convention `--tint` uses for `rm/gm/bm`. Confirmed against
+ `ffmpeg -h filter=colorbalance`: `rs/gs/bs`, `rm/gm/bm`, `rh/gh/bh`, each documented -1..1.
+- **`--levels-in-black` / `--levels-in-white` / `--levels-out-black` / `--levels-out-white`**
+ (0..255 each, defaults 0/255/0/255=unchanged; rejects `in_black >= in_white` or
+ `out_black >= out_white` before ffmpeg runs): `colorlevels`, whose real parameters
+ (`ffmpeg -h filter=colorlevels`) take fractional 0.0..1.0 input/output black/white points, not
+ 0..255 — this tool exposes the familiar 8-bit unit and divides by 255.0 when building the
+ filter, the same "human unit in, filter's native unit out" convention `--temperature` already
+ uses. The `colorlevels=` term is only added to the chain when at least one of the four flags is
+ given; an all-default `--correct` call adds no `colorlevels` term, matching how every stage in
+ this chain is either always present at its own no-op default or (for this new pair) omitted
+ entirely when unused.
+- **`--curves PRESET`** (argparse `choices`, default: none, no `curves=` term added): the `curves`
+ filter's own built-in presets, read from `ffmpeg -h filter=curves` rather than assumed:
+ `color_negative`, `cross_process`, `darker`, `increase_contrast`, `lighter`,
+ `linear_contrast`, `medium_contrast`, `negative`, `strong_contrast`, `vintage` (the filter's own
+ 11th choice, `none`, is omitted from `--curves`'s choices since leaving the flag unset already
+ gets that identity result without adding a filter term for it).
+- Contract: `color`'s optional capabilities gain `filter:colorlevels` (`when: "--correct with any
+ --levels-*"`) and `filter:curves` (`when: "--correct --curves"`). No change to any existing flag,
+ contract field, MCP schema or tool semantics.
+- Tests: 5 real-media tests in `tests/test_all.py` mirroring the existing `--correct` style —
+ gamma/lift/gain run and measurably change signalstats luma, levels narrows the measured dynamic
+ range, curves runs and preserves geometry/duration, and out-of-range or inverted values for
+ every new flag (`--gamma`, `--lift`, `--gain`, `--levels-in-black`/`--levels-in-white` inverted,
+ `--levels-out-black`/`--levels-out-white` inverted, an invalid `--curves` choice) are each
+ refused before ffmpeg ever runs, with no partial output.
+
## 0.12.2 — `caption.py --mode mux` no longer drops the input's existing subtitle track(s)
Found while discussing a real use case (adding both an English and a Japanese soft subtitle
diff --git a/README.md b/README.md
index 1237567..ec6db29 100644
--- a/README.md
+++ b/README.md
@@ -180,7 +180,7 @@ These are the rules the skill file gives the agent and the code enforces. Togeth
| `caption.py` | Burn SRT/ASS with font, size, colour, outline, position; build SRT from timed plain text; animated and word-by-word karaoke timed to the speech energy; optional local transcription |
| `overlay.py` | Logos, watermarks and titles with position, time range, opacity, fades; `--video` for picture-in-picture, `--chromakey` for green-screen compositing |
| `graphics.py` | Lower-thirds, title cards, chapter chips, progress bars, countdowns, corner bugs drawn by FFmpeg from a brand kit |
-| `color.py` | HDR10 / HLG / Dolby Vision → SDR BT.709 tone mapping, DV layer stripping, 3D LUT (.cube), colour-tag rewriting, typed primary correction (exposure/contrast/saturation/white balance) |
+| `color.py` | HDR10 / HLG / Dolby Vision → SDR BT.709 tone mapping, DV layer stripping, 3D LUT (.cube), colour-tag rewriting, typed primary correction (exposure/contrast/saturation/gamma/white balance/lift-gain/levels/curves) |
**Delivery**
diff --git a/docs/contract.md b/docs/contract.md
index 815f408..a62ad71 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.2`) | any release |
+| `skill.version` | the npm / package.json version (`0.12.3`) | 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.2", "execution_mode": "local", "kind": "execution",
+ "skill": {"id": "ffmpeg-skill", "version": "0.12.3", "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 6848c8c..109a490 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "ffmpeg-skill",
- "version": "0.12.2",
+ "version": "0.12.3",
"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/references/scripts.md b/references/scripts.md
index 2602473..e8e7bc0 100644
--- a/references/scripts.md
+++ b/references/scripts.md
@@ -352,7 +352,23 @@ color.py INPUT --to-sdr [--tonemap hable|mobius|reinhard|bt2390] [--peak 1000] [
color.py INPUT --lut grade.cube [--lut-strength 0..1] [-o OUT]
color.py INPUT --retag bt709|bt2020-pq|bt2020-hlg|bt601 [-o OUT] # metadata only, stream copy
color.py INPUT --strip-dovi [-o OUT] # drop the Dolby Vision RPU, keep the HLG/HDR10 base layer (stream copy)
-```
+color.py INPUT --correct [--exposure -3..3] [--contrast 0..2] [--saturation 0..2] [--gamma 0.1..10]
+ [--temperature 2000..12000] [--tint -1..1] [--lift -1..1] [--gain -1..1]
+ [--levels-in-black 0..255] [--levels-in-white 0..255] [--levels-out-black 0..255] [--levels-out-white 0..255]
+ [--curves color_negative|cross_process|darker|increase_contrast|lighter|linear_contrast|medium_contrast|negative|strong_contrast|vintage] [-o OUT]
+```
+`--correct` is typed primary colour correction, no filter string ever accepted:
+`--exposure`/`--contrast`/`--saturation`/`--gamma` (`exposure`/`eq` filters),
+`--temperature`/`--tint`/`--lift`/`--gain` (`colortemperature`/`colorbalance`
+filters — `--tint` sets midtones, `--lift` shadows, `--gain` highlights, a
+classic three-way correction), `--levels-*` (`colorlevels`, 8-bit units
+converted to the filter's own 0..1 range, only added to the chain when at
+least one is given) and `--curves` (the `curves` filter's own built-in
+presets, only added when given). Every flag is range-checked against this
+script's own safe subset of what `ffmpeg -h filter=<name>` documents before
+ffmpeg runs. `--json`'s `measurements` reports `analyze_levels()` (signalstats
+luma/saturation) for input and output side by side.
+
iPhone "HDR" video is Dolby Vision profile 8.4 on an HLG base layer:
`probe.py` reports `hdr_format: Dolby Vision profile 8` and `--to-sdr`
tone-maps it from the HLG base layer. When the user wants to keep HDR but
diff --git a/scripts/_contract.py b/scripts/_contract.py
index 1fad428..04e797b 100644
--- a/scripts/_contract.py
+++ b/scripts/_contract.py
@@ -127,7 +127,8 @@ TOOL_META: Dict[str, Dict[str, Any]] = {
required=FF, optional=[{"capability": X264, "when": "--to-sdr / --lut / --correct"}, {"capability": "filter:zscale", "when": "--to-sdr"}, {"capability": "filter:tonemap", "when": "--to-sdr"},
{"capability": "filter:lut3d", "when": "--lut"}, {"capability": "bsf:filter_units", "when": "--strip-dovi"}, {"capability": X265, "when": "--lut on an HDR source"}, {"capability": AAC, "when": "re-encode"},
{"capability": "filter:exposure", "when": "--correct"}, {"capability": "filter:eq", "when": "--correct"},
- {"capability": "filter:colorbalance", "when": "--correct"}, {"capability": "filter:colortemperature", "when": "--correct"}],
+ {"capability": "filter:colorbalance", "when": "--correct"}, {"capability": "filter:colortemperature", "when": "--correct"},
+ {"capability": "filter:colorlevels", "when": "--correct with any --levels-*"}, {"capability": "filter:curves", "when": "--correct --curves"}],
video_required=True, audio_only=False, visual=True, verify=["probe", "look"], produces_artifact=True, idempotency="content_equivalent", deterministic=True),
"proxy": dict(role="execution", inputs=["video asset"], outputs=["low-resolution, low-bitrate proxy artifact for downstream analysis, preview or editing decisions"],
required=FF + [X264, AAC], optional=[HDR_X265],
diff --git a/scripts/color.py b/scripts/color.py
index 3700921..bb48224 100755
--- a/scripts/color.py
+++ b/scripts/color.py
@@ -2,7 +2,8 @@
"""Colour management: convert HDR (HDR10/PQ, HLG, BT.2020) to SDR BT.709 with
real tone mapping, apply a .cube LUT (Log footage, creative grades), fix wrong
colour tags without re-encoding, or apply typed primary colour correction
-(exposure, contrast, saturation, white balance).
+(exposure, contrast, saturation, gamma, white balance, three-way
+lift/gain, levels, curves).
Examples:
python3 color.py iphone_hdr.mov --to-sdr # PQ/HLG -> BT.709 SDR, hable tonemap
@@ -13,6 +14,8 @@ Examples:
python3 color.py iphone_dv.mov --strip-dovi # drop Dolby Vision RPU, keep HLG base layer
python3 color.py iphone_dv.mov --to-sdr # DV 8.4 = HLG base layer -> tone-mapped SDR
python3 color.py flat.mp4 --correct --exposure 0.3 --contrast 1.1 --saturation 1.05 --temperature 5600 --tint -0.05
+ python3 color.py flat.mp4 --correct --gamma 1.2 --lift 0.04 --gain -0.03 # three-way shadows/gamma/highlights
+ python3 color.py flat.mp4 --correct --levels-in-black 16 --levels-in-white 235 --curves medium_contrast
"""
import argparse
import os
@@ -26,8 +29,11 @@ TONEMAPS = ["hable", "mobius", "reinhard", "bt2390", "clip", "linear", "gamma"]
# Typed primary correction: each flag is one option of one real, always-available libavfilter filter
# (never a caller-supplied filter string). Range is this script's own safe subset of what the filter
# documents (`ffmpeg -h filter=<name>`), not the filter's full technical range. default is each filter's
-# own documented no-op value, so every stage below is always emitted and the chain never depends on
-# which flags were actually given.
+# own documented no-op value, so every stage in this dict is always emitted and the chain never depends
+# on which flags were actually given (exposure/temperature/tint/gamma/lift/gain). `colorlevels` and
+# `curves` (see LEVELS and CURVES_PRESETS below) are the exception: they only add a term to the chain
+# when the caller actually asks for them, because "levels 0..255 in, 0..255 out" and "no curve" are
+# already the identity operation without emitting a no-op filter term for it.
CORRECTION = {
# flag default lo hi unit
"exposure": (0.0, -3.0, 3.0, "stops"), # exposure filter's own full range (linear-domain stops)
@@ -35,8 +41,27 @@ CORRECTION = {
"saturation": (1.0, 0.0, 2.0, "x"), # eq filter; 0=grayscale, 1=unchanged, 2=double saturation
"temperature": (6500.0, 2000.0, 12000.0, "K"), # colortemperature filter; 6500=unchanged (its own default)
"tint": (0.0, -1.0, 1.0, "x"), # mapped to colorbalance midtones, see correction_chain()
+ "gamma": (1.0, 0.1, 10.0, "x"), # eq filter's own gamma option; 1=unchanged (its own default)
+ "lift": (0.0, -1.0, 1.0, "x"), # colorbalance shadows (rs=gs=bs); 0=unchanged
+ "gain": (0.0, -1.0, 1.0, "x"), # colorbalance highlights (rh=gh=bh); 0=unchanged
}
+# colorlevels takes fractional 0.0..1.0 input/output black/white points; this tool exposes the
+# familiar 8-bit 0..255 unit instead and divides by 255.0 when building the filter (same convention
+# as the rest of CORRECTION: a human-friendly CLI unit formatted into the filter's own native unit).
+LEVELS = {
+ # flag default lo hi
+ "levels_in_black": (0, 0, 255),
+ "levels_in_white": (255, 0, 255),
+ "levels_out_black": (0, 0, 255),
+ "levels_out_white": (255, 0, 255),
+}
+
+# curves filter's real built-in presets (`ffmpeg -h filter=curves`), excluding its own "none" (0):
+# omitting --curves already gets that identity result without adding a filter term for it.
+CURVES_PRESETS = ["color_negative", "cross_process", "darker", "increase_contrast", "lighter",
+ "linear_contrast", "medium_contrast", "negative", "strong_contrast", "vintage"]
+
def _checked(args: argparse.Namespace, flag: str) -> float:
_, lo, hi, unit = CORRECTION[flag]
@@ -46,26 +71,65 @@ def _checked(args: argparse.Namespace, flag: str) -> float:
return value
+def _checked_levels(args: argparse.Namespace, flag: str) -> int:
+ _, lo, hi = LEVELS[flag]
+ value = getattr(args, flag)
+ if not (lo <= value <= hi):
+ die(f"--{flag.replace('_', '-')} {value} is outside {lo}..{hi} (8-bit units, scaled to colorlevels' own 0..1 range)")
+ return value
+
+
def correction_chain(args: argparse.Namespace) -> str:
- """Four always-present filter stages, in a fixed order chosen so each stage sees a picture already
- corrected by the previous one: exposure (linear light level) -> white balance (temperature/tint, so
- contrast/saturation act on colour-balanced footage) -> contrast -> saturation (the most creative-
- adjacent stage, applied last). `tint` (-1 green .. +1 magenta) is not a single ffmpeg option: it is
- expressed as colorbalance's three midtone channels (gm=-tint, rm=bm=tint/2) so a positive tint shifts
- midtones toward magenta and a negative one toward green without changing overall midtone lightness,
- the same balanced-axis convention colour tools use for a one-dial tint control."""
+ """Always-present filter stages, in a fixed order chosen so each stage sees a picture already
+ corrected by the previous one: exposure (linear light level) -> white balance (temperature/tint/
+ lift/gain, so contrast/saturation act on colour-balanced footage) -> contrast/saturation/gamma
+ (the most creative-adjacent stage of the always-on chain). `tint` (-1 green .. +1 magenta) is not
+ a single ffmpeg option: it is expressed as colorbalance's three midtone channels (gm=-tint,
+ rm=bm=tint/2) so a positive tint shifts midtones toward magenta and a negative one toward green
+ without changing overall midtone lightness, the same balanced-axis convention colour tools use
+ for a one-dial tint control. `lift` and `gain` extend the same colorbalance call to the shadow
+ (rs=gs=bs=lift) and highlight (rh=gh=bh=gain) channels, giving a classic three-way shadows/
+ midtones/highlights correction in one filter invocation. `gamma` is folded into the same `eq`
+ term contrast/saturation already use, as `eq`'s own `gamma` option. Two further stages are
+ appended only when asked for, since their own identity value would otherwise add a no-op filter
+ term to the chain: `colorlevels` (--levels-*, 8-bit units scaled to the filter's 0..1 range) and
+ `curves` (--curves, one of the filter's own named presets)."""
exposure = _checked(args, "exposure")
contrast = _checked(args, "contrast")
saturation = _checked(args, "saturation")
temperature = _checked(args, "temperature")
tint = _checked(args, "tint")
+ gamma = _checked(args, "gamma")
+ lift = _checked(args, "lift")
+ gain = _checked(args, "gain")
+ in_black = _checked_levels(args, "levels_in_black")
+ in_white = _checked_levels(args, "levels_in_white")
+ out_black = _checked_levels(args, "levels_out_black")
+ out_white = _checked_levels(args, "levels_out_white")
+ if in_black >= in_white:
+ die(f"--levels-in-black {in_black} must be less than --levels-in-white {in_white}")
+ if out_black >= out_white:
+ die(f"--levels-out-black {out_black} must be less than --levels-out-white {out_white}")
+
gm, rm, bm = -tint, tint / 2.0, tint / 2.0
- return ",".join([
+ terms = [
f"exposure=exposure={exposure:g}",
f"colortemperature=temperature={temperature:g}",
- f"colorbalance=rm={rm:g}:gm={gm:g}:bm={bm:g}",
- f"eq=contrast={contrast:g}:saturation={saturation:g}",
- ])
+ f"colorbalance=rs={lift:g}:gs={lift:g}:bs={lift:g}:rm={rm:g}:gm={gm:g}:bm={bm:g}:rh={gain:g}:gh={gain:g}:bh={gain:g}",
+ f"eq=contrast={contrast:g}:saturation={saturation:g}:gamma={gamma:g}",
+ ]
+ if (in_black, in_white, out_black, out_white) != (0, 255, 0, 255):
+ rimin, rimax = in_black / 255.0, in_white / 255.0
+ romin, romax = out_black / 255.0, out_white / 255.0
+ terms.append(
+ f"colorlevels=rimin={rimin:g}:gimin={rimin:g}:bimin={rimin:g}:"
+ f"rimax={rimax:g}:gimax={rimax:g}:bimax={rimax:g}:"
+ f"romin={romin:g}:gomin={romin:g}:bomin={romin:g}:"
+ f"romax={romax:g}:gomax={romax:g}:bomax={romax:g}"
+ )
+ if args.curves:
+ terms.append(f"curves=preset={args.curves}")
+ return ",".join(terms)
def hdr_to_sdr_chain(meta: dict, tonemap: str, peak: float, desat: float) -> str:
@@ -94,7 +158,7 @@ def main() -> int:
mode.add_argument("--lut", help=".cube LUT to apply (3D)")
mode.add_argument("--retag", choices=["bt709", "bt2020-pq", "bt2020-hlg", "bt601"], help="rewrite colour tags only (no re-encode)")
mode.add_argument("--strip-dovi", action="store_true", help="remove the Dolby Vision RPU (profile 8.4 iPhone clips) so players use the plain HLG/HDR10 base layer; stream copy")
- mode.add_argument("--correct", action="store_true", help="typed primary colour correction: --exposure/--contrast/--saturation/--temperature/--tint")
+ mode.add_argument("--correct", action="store_true", help="typed primary colour correction: --exposure/--contrast/--saturation/--temperature/--tint/--gamma/--lift/--gain/--levels-*/--curves")
ap.add_argument("--tonemap", choices=TONEMAPS, default="hable", help="tone-mapping curve (default hable)")
ap.add_argument("--peak", type=float, default=1000.0, help="source peak brightness in nits used for PQ (default 1000)")
ap.add_argument("--desat", type=float, default=0.0, help="tonemap desaturation strength (default 0)")
@@ -105,6 +169,14 @@ def main() -> int:
ap.add_argument("--saturation", type=float, default=CORRECTION["saturation"][0], help="--correct: saturation, 0..2, 1=unchanged (default 1)")
ap.add_argument("--temperature", type=float, default=CORRECTION["temperature"][0], help="--correct: white-balance temperature in Kelvin, 2000..12000, 6500=unchanged (default 6500)")
ap.add_argument("--tint", type=float, default=CORRECTION["tint"][0], help="--correct: green(-1)/magenta(+1) tint, 0=unchanged (default 0)")
+ ap.add_argument("--gamma", type=float, default=CORRECTION["gamma"][0], help="--correct: master gamma (eq filter's own gamma), 0.1..10, 1=unchanged (default 1)")
+ ap.add_argument("--lift", type=float, default=CORRECTION["lift"][0], help="--correct: shadows lift (colorbalance rs/gs/bs), -1..1, 0=unchanged (default 0)")
+ ap.add_argument("--gain", type=float, default=CORRECTION["gain"][0], help="--correct: highlights gain (colorbalance rh/gh/bh), -1..1, 0=unchanged (default 0)")
+ ap.add_argument("--levels-in-black", type=int, default=LEVELS["levels_in_black"][0], help="--correct: colorlevels input black point, 0..255 (default 0, unchanged)")
+ ap.add_argument("--levels-in-white", type=int, default=LEVELS["levels_in_white"][0], help="--correct: colorlevels input white point, 0..255 (default 255, unchanged)")
+ ap.add_argument("--levels-out-black", type=int, default=LEVELS["levels_out_black"][0], help="--correct: colorlevels output black point, 0..255 (default 0, unchanged)")
+ ap.add_argument("--levels-out-white", type=int, default=LEVELS["levels_out_white"][0], help="--correct: colorlevels output white point, 0..255 (default 255, unchanged)")
+ ap.add_argument("--curves", choices=CURVES_PRESETS, default=None, help="--correct: curves filter built-in preset (default: none, no curves term added)")
ap.add_argument("--audio-stream", type=int, default=0,
help="which audio stream of the input to keep, 0-based in file order (probe.py lists them under "
"audio_streams) -- matters on a multi-track input (dubbed languages, M&E stems); default 0, "
diff --git a/tests/test_all.py b/tests/test_all.py
index ec1d323..c27d6aa 100644
--- a/tests/test_all.py
+++ b/tests/test_all.py
@@ -889,6 +889,81 @@ class FFmpegSkillTests(unittest.TestCase):
self.assertIn("outside", proc.stderr, f"{flag} {bad} should be refused as out of range")
self.assertFalse(out.exists(), f"{flag} {bad}: no partial output on refusal")
+ def test_color_correct_gamma_changes_measured_luma(self):
+ brighter = OUT / "correct_gamma_up.mp4"
+ data = json.loads(script("color.py", self.src, "--correct", "--gamma", "1.6", "--preset", "veryfast", "-o", brighter, "--json").stdout)
+ m = data["measurements"]
+ self.assertGreater(m["output"]["y_avg"], m["input"]["y_avg"], "gamma > 1 must raise measured luma")
+
+ darker = OUT / "correct_gamma_down.mp4"
+ data2 = json.loads(script("color.py", self.src, "--correct", "--gamma", "0.5", "--preset", "veryfast", "-o", darker, "--json").stdout)
+ m2 = data2["measurements"]
+ self.assertLess(m2["output"]["y_avg"], m2["input"]["y_avg"], "gamma < 1 must lower measured luma")
+
+ def test_color_correct_lift_and_gain_run_and_shift_measured_levels(self):
+ lifted = OUT / "correct_lift.mp4"
+ data = json.loads(script("color.py", self.src, "--correct", "--lift", "0.3", "--preset", "veryfast", "-o", lifted, "--json").stdout)
+ m = data["measurements"]
+ self.assertGreater(m["output"]["y_min"], m["input"]["y_min"], "positive lift must raise the shadow floor")
+
+ gained = OUT / "correct_gain.mp4"
+ data2 = json.loads(script("color.py", self.src, "--correct", "--gain", "-0.3", "--preset", "veryfast", "-o", gained, "--json").stdout)
+ m2 = data2["measurements"]
+ self.assertLess(m2["output"]["y_avg"], m2["input"]["y_avg"], "negative gain must dim the highlights and lower measured luma")
+ v = probe(str(gained))["video"]
+ self.assertEqual((v["width"], v["height"]), (1280, 720))
+
+ def test_color_correct_levels_narrows_measured_dynamic_range(self):
+ out = OUT / "correct_levels_out.mp4"
+ data = json.loads(script("color.py", self.src, "--correct", "--levels-out-black", "64", "--levels-out-white", "192",
+ "--preset", "veryfast", "-o", out, "--json").stdout)
+ m = data["measurements"]
+ # colorlevels' output remap is an affine map into [romin, romax]: no output pixel can fall
+ # outside it (mod encoder rounding), so this is a mathematical guarantee, not a content guess.
+ self.assertGreaterEqual(m["output"]["y_min"], 64 - 3, "--levels-out-black 64 must floor the output near 64")
+ self.assertLessEqual(m["output"]["y_max"], 192 + 3, "--levels-out-white 192 must ceiling the output near 192")
+ self.assertLess(m["output"]["y_max"] - m["output"]["y_min"], m["input"]["y_max"] - m["input"]["y_min"],
+ "narrowing the output levels must narrow the measured dynamic range")
+
+ out2 = OUT / "correct_levels_in.mp4"
+ script("color.py", self.src, "--correct", "--levels-in-black", "16", "--levels-in-white", "235", "--preset", "veryfast", "-o", out2)
+ v = probe(str(out2))["video"]
+ self.assertEqual((v["width"], v["height"]), (1280, 720))
+ self.assertClose(probe(str(out2))["duration"], 12.0, 0.2)
+
+ # an all-default --levels-* call must not add a colorlevels term to the chain
+ neutral_chain = script("color.py", self.src, "--correct", "--dry-run").stderr
+ self.assertNotIn("colorlevels", neutral_chain)
+
+ def test_color_correct_curves_preset_runs_and_preserves_geometry(self):
+ out = OUT / "correct_curves.mp4"
+ script("color.py", self.src, "--correct", "--curves", "medium_contrast", "--preset", "veryfast", "-o", out)
+ v = probe(str(out))["video"]
+ self.assertEqual((v["width"], v["height"]), (1280, 720))
+ self.assertClose(probe(str(out))["duration"], 12.0, 0.2)
+ # omitting --curves must not add a curves term to the chain
+ neutral_chain = script("color.py", self.src, "--correct", "--dry-run").stderr
+ self.assertNotIn("curves=", neutral_chain)
+ proc = script("color.py", self.src, "--correct", "--curves", "not-a-real-preset", "-o", OUT / "correct_curves_bad.mp4", expect_fail=True)
+ self.assertIn("invalid choice", proc.stderr)
+
+ def test_color_correct_rejects_new_flags_out_of_range(self):
+ for flag, bad in (("--gamma", "0.05"), ("--gamma", "11"), ("--lift", "-1.5"), ("--gain", "1.5")):
+ out = OUT / "correct_reject_new.mp4"
+ proc = script("color.py", self.src, "--correct", flag, bad, "-o", out, expect_fail=True)
+ self.assertIn("outside", proc.stderr, f"{flag} {bad} should be refused as out of range")
+ self.assertFalse(out.exists(), f"{flag} {bad}: no partial output on refusal")
+
+ out = OUT / "correct_reject_levels_in.mp4"
+ proc = script("color.py", self.src, "--correct", "--levels-in-black", "200", "--levels-in-white", "100", "-o", out, expect_fail=True)
+ self.assertIn("must be less than", proc.stderr)
+ self.assertFalse(out.exists())
+
+ out2 = OUT / "correct_reject_levels_out.mp4"
+ proc2 = script("color.py", self.src, "--correct", "--levels-out-black", "200", "--levels-out-white", "100", "-o", out2, expect_fail=True)
+ self.assertIn("must be less than", proc2.stderr)
+ self.assertFalse(out2.exists())
+
def test_export_warns_on_hdr(self):
out = OUT / "hdr_youtube.mp4"
proc = script("export.py", self.hdr, "--preset", "x", "-o", out)