uppercut-ffmpeg-loudness 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,8 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.egg-info/
4
+ dist/
5
+ build/
6
+ .pytest_cache/
7
+ .DS_Store
8
+ uv.lock
@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.5
2
+ Name: uppercut-ffmpeg-loudness
3
+ Version: 0.1.0
4
+ Summary: Measure integrated loudness and true peak with ffmpeg, then apply gain or normalize to a target.
5
+ Project-URL: Source, https://github.com/uppercut-labs/py-kit/tree/main/packages/uppercut-ffmpeg-loudness
6
+ Author-email: Uppercut Labs <packages@uppercut-labs.com>
7
+ License-Expression: MIT
8
+ Keywords: ebur128,ffmpeg,loudness,loudnorm,lufs,true-peak
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Multimedia :: Sound/Audio
13
+ Classifier: Typing :: Typed
14
+ Requires-Python: >=3.10
15
+ Description-Content-Type: text/markdown
16
+
17
+ # uppercut-ffmpeg-loudness
18
+
19
+ Measures integrated loudness (LUFS), loudness range and true peak of an audio or video file with ffmpeg's `ebur128` filter, plans a gain against a loudness target and a true-peak ceiling, and writes a normalized copy. It uses only the Python standard library and an `ffmpeg` binary on `PATH`. Parsing of ffmpeg output and filter-string building are pure functions you can test without ffmpeg.
20
+
21
+ ## Install
22
+
23
+ ```sh
24
+ pip install uppercut-ffmpeg-loudness
25
+ ```
26
+
27
+ ## Example
28
+
29
+ ```python
30
+ from uppercut_ffmpeg_loudness import measure, normalize
31
+
32
+ before = measure("mix.wav")
33
+ print(before.integrated, before.true_peak)
34
+
35
+ result = normalize("mix.wav", "mix-14.wav", target_lufs=-14.0, true_peak=-1.0)
36
+ print(result.gain_db, result.limited_by, result.reached_target)
37
+ ```
38
+
39
+ Command line:
40
+
41
+ ```sh
42
+ uppercut-ffmpeg-loudness a.wav b.mp4 --target -14 --tp -1
43
+ uppercut-ffmpeg-loudness a.wav --normalize out.wav --target -16 --mode loudnorm
44
+ ```
45
+
46
+ Measuring exits with 1 when a file is more than 1 LU from `--target` or its true peak is above `--tp`.
47
+
48
+ ## Functions
49
+
50
+ | Function | What it does |
51
+ | --- | --- |
52
+ | `measure(path, audio_stream=0)` | Returns `Measure(integrated, true_peak, lra)`. Silence reads as `-inf`. |
53
+ | `measure_loudnorm(path, target_lufs, true_peak, lra)` | First `loudnorm` pass; returns the parsed JSON values. |
54
+ | `parse_ebur128_summary(log)` | Parses the final `Summary:` block of an `ebur128` run. |
55
+ | `parse_loudnorm_json(log)` | Parses the JSON block printed by `loudnorm=print_format=json`. |
56
+ | `plan_gain(measure, target_lufs, true_peak_ceiling, headroom_db=0.0, max_gain_db=None)` | Returns `(gain_db, limited_by)`; the smallest of the gain to the target, the gain to the peak ceiling minus headroom, and the cap. `limited_by` is `"target"`, `"peak"` or `"cap"`. |
57
+ | `common_target(measures, target_lufs, true_peak_ceiling)` | The loudness a batch of clips can share without any clip exceeding the peak ceiling. |
58
+ | `apply_gain(src, dst, gain_db, extra_filters=(), copy_video=True, codec=None, bitrate=192000, rate=48000)` | Writes `dst` with a gain applied. Video is copied. The codec follows the output suffix unless given. |
59
+ | `normalize(src, dst, target_lufs=-14.0, true_peak=-1.0, mode="gain", headroom_db=0.5, max_gain_db=12.0, retries=3, ...)` | Normalizes to the target and re-measures the output. If the true peak is still over the ceiling, it lowers the gain and encodes again, up to `retries` times. Returns `NormalizeResult(gain_db, limited_by, before, after, attempts, reached_target)`. |
60
+ | `loudnorm_filter(...)`, `limiter_filter(limit_dbfs, sample_rate=48000, oversample=4)`, `volume_filter(gain_db)` | Build filter strings. |
61
+
62
+ `mode="gain"` applies one linear gain. `mode="loudnorm"` runs two-pass `loudnorm` in linear mode, then trims any remaining peak overshoot.
63
+
64
+ ## Errors
65
+
66
+ | Error | Raised when |
67
+ | --- | --- |
68
+ | `FfmpegNotFoundError` | `ffmpeg` is not on `PATH`. |
69
+ | `LoudnessError` | ffmpeg fails, the output cannot be parsed, the input is silent, `dst` equals `src`, or the true peak stays over the ceiling after all retries. |
70
+
71
+ ## License
72
+
73
+ MIT
@@ -0,0 +1,57 @@
1
+ # uppercut-ffmpeg-loudness
2
+
3
+ Measures integrated loudness (LUFS), loudness range and true peak of an audio or video file with ffmpeg's `ebur128` filter, plans a gain against a loudness target and a true-peak ceiling, and writes a normalized copy. It uses only the Python standard library and an `ffmpeg` binary on `PATH`. Parsing of ffmpeg output and filter-string building are pure functions you can test without ffmpeg.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ pip install uppercut-ffmpeg-loudness
9
+ ```
10
+
11
+ ## Example
12
+
13
+ ```python
14
+ from uppercut_ffmpeg_loudness import measure, normalize
15
+
16
+ before = measure("mix.wav")
17
+ print(before.integrated, before.true_peak)
18
+
19
+ result = normalize("mix.wav", "mix-14.wav", target_lufs=-14.0, true_peak=-1.0)
20
+ print(result.gain_db, result.limited_by, result.reached_target)
21
+ ```
22
+
23
+ Command line:
24
+
25
+ ```sh
26
+ uppercut-ffmpeg-loudness a.wav b.mp4 --target -14 --tp -1
27
+ uppercut-ffmpeg-loudness a.wav --normalize out.wav --target -16 --mode loudnorm
28
+ ```
29
+
30
+ Measuring exits with 1 when a file is more than 1 LU from `--target` or its true peak is above `--tp`.
31
+
32
+ ## Functions
33
+
34
+ | Function | What it does |
35
+ | --- | --- |
36
+ | `measure(path, audio_stream=0)` | Returns `Measure(integrated, true_peak, lra)`. Silence reads as `-inf`. |
37
+ | `measure_loudnorm(path, target_lufs, true_peak, lra)` | First `loudnorm` pass; returns the parsed JSON values. |
38
+ | `parse_ebur128_summary(log)` | Parses the final `Summary:` block of an `ebur128` run. |
39
+ | `parse_loudnorm_json(log)` | Parses the JSON block printed by `loudnorm=print_format=json`. |
40
+ | `plan_gain(measure, target_lufs, true_peak_ceiling, headroom_db=0.0, max_gain_db=None)` | Returns `(gain_db, limited_by)`; the smallest of the gain to the target, the gain to the peak ceiling minus headroom, and the cap. `limited_by` is `"target"`, `"peak"` or `"cap"`. |
41
+ | `common_target(measures, target_lufs, true_peak_ceiling)` | The loudness a batch of clips can share without any clip exceeding the peak ceiling. |
42
+ | `apply_gain(src, dst, gain_db, extra_filters=(), copy_video=True, codec=None, bitrate=192000, rate=48000)` | Writes `dst` with a gain applied. Video is copied. The codec follows the output suffix unless given. |
43
+ | `normalize(src, dst, target_lufs=-14.0, true_peak=-1.0, mode="gain", headroom_db=0.5, max_gain_db=12.0, retries=3, ...)` | Normalizes to the target and re-measures the output. If the true peak is still over the ceiling, it lowers the gain and encodes again, up to `retries` times. Returns `NormalizeResult(gain_db, limited_by, before, after, attempts, reached_target)`. |
44
+ | `loudnorm_filter(...)`, `limiter_filter(limit_dbfs, sample_rate=48000, oversample=4)`, `volume_filter(gain_db)` | Build filter strings. |
45
+
46
+ `mode="gain"` applies one linear gain. `mode="loudnorm"` runs two-pass `loudnorm` in linear mode, then trims any remaining peak overshoot.
47
+
48
+ ## Errors
49
+
50
+ | Error | Raised when |
51
+ | --- | --- |
52
+ | `FfmpegNotFoundError` | `ffmpeg` is not on `PATH`. |
53
+ | `LoudnessError` | ffmpeg fails, the output cannot be parsed, the input is silent, `dst` equals `src`, or the true peak stays over the ceiling after all retries. |
54
+
55
+ ## License
56
+
57
+ MIT
@@ -0,0 +1,33 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.25"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "uppercut-ffmpeg-loudness"
7
+ version = "0.1.0"
8
+ description = "Measure integrated loudness and true peak with ffmpeg, then apply gain or normalize to a target."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ authors = [{ name = "Uppercut Labs", email = "packages@uppercut-labs.com" }]
13
+ dependencies = []
14
+ keywords = ["ffmpeg", "loudness", "lufs", "ebur128", "loudnorm", "true-peak"]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Intended Audience :: Developers",
18
+ "Programming Language :: Python :: 3",
19
+ "Topic :: Multimedia :: Sound/Audio",
20
+ "Typing :: Typed",
21
+ ]
22
+
23
+ [project.urls]
24
+ Source = "https://github.com/uppercut-labs/py-kit/tree/main/packages/uppercut-ffmpeg-loudness"
25
+
26
+ [project.scripts]
27
+ uppercut-ffmpeg-loudness = "uppercut_ffmpeg_loudness.cli:main"
28
+
29
+ [tool.hatch.build.targets.wheel]
30
+ packages = ["src/uppercut_ffmpeg_loudness"]
31
+
32
+ [tool.hatch.build.targets.sdist]
33
+ include = ["src", "tests", "README.md"]
@@ -0,0 +1,42 @@
1
+ """Measure loudness with ffmpeg and bring audio to a target level."""
2
+
3
+ from .core import (
4
+ DEFAULT_TARGET_LUFS,
5
+ DEFAULT_TRUE_PEAK_DBTP,
6
+ FfmpegNotFoundError,
7
+ LoudnessError,
8
+ Measure,
9
+ NormalizeResult,
10
+ apply_gain,
11
+ common_target,
12
+ limiter_filter,
13
+ loudnorm_filter,
14
+ measure,
15
+ measure_loudnorm,
16
+ normalize,
17
+ parse_ebur128_summary,
18
+ parse_loudnorm_json,
19
+ plan_gain,
20
+ volume_filter,
21
+ )
22
+
23
+ __all__ = [
24
+ "DEFAULT_TARGET_LUFS",
25
+ "DEFAULT_TRUE_PEAK_DBTP",
26
+ "FfmpegNotFoundError",
27
+ "LoudnessError",
28
+ "Measure",
29
+ "NormalizeResult",
30
+ "apply_gain",
31
+ "common_target",
32
+ "limiter_filter",
33
+ "loudnorm_filter",
34
+ "measure",
35
+ "measure_loudnorm",
36
+ "normalize",
37
+ "parse_ebur128_summary",
38
+ "parse_loudnorm_json",
39
+ "plan_gain",
40
+ "volume_filter",
41
+ ]
42
+ __version__ = "0.1.0"
@@ -0,0 +1,77 @@
1
+ """Command line: measure files or normalize one."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import math
8
+ import sys
9
+ from typing import Sequence
10
+
11
+ from .core import (
12
+ DEFAULT_TARGET_LUFS,
13
+ DEFAULT_TRUE_PEAK_DBTP,
14
+ LoudnessError,
15
+ Measure,
16
+ measure,
17
+ normalize,
18
+ )
19
+
20
+
21
+ def _finite(value: float) -> float | None:
22
+ return value if math.isfinite(value) else None
23
+
24
+
25
+ def _record(path: str, m: Measure) -> dict[str, object]:
26
+ return {
27
+ "file": path,
28
+ "integrated_lufs": _finite(m.integrated),
29
+ "true_peak_dbtp": _finite(m.true_peak),
30
+ "lra": None if m.lra is None else _finite(m.lra),
31
+ }
32
+
33
+
34
+ def main(argv: Sequence[str] | None = None) -> int:
35
+ parser = argparse.ArgumentParser(
36
+ prog="uppercut-ffmpeg-loudness",
37
+ description="Measure loudness with ffmpeg, or normalize a file to a target.",
38
+ )
39
+ parser.add_argument("files", nargs="+", help="files to measure; with --normalize, the source")
40
+ parser.add_argument("--target", type=float, help="target integrated LUFS")
41
+ parser.add_argument("--tp", type=float, default=DEFAULT_TRUE_PEAK_DBTP, help="true-peak ceiling, dBTP")
42
+ parser.add_argument("--normalize", metavar="OUT", help="write a normalized copy of the one source file")
43
+ parser.add_argument("--mode", choices=["gain", "loudnorm"], default="gain")
44
+ parser.add_argument("--json", action="store_true", help="print JSON records")
45
+ args = parser.parse_args(argv)
46
+ try:
47
+ if args.normalize:
48
+ if len(args.files) != 1:
49
+ parser.error("--normalize takes exactly one source file")
50
+ target = DEFAULT_TARGET_LUFS if args.target is None else args.target
51
+ result = normalize(args.files[0], args.normalize, target, args.tp, mode=args.mode)
52
+ records = [_record(args.normalize, result.after)]
53
+ records[0]["gain_db"] = result.gain_db
54
+ records[0]["limited_by"] = result.limited_by
55
+ records[0]["reached_target"] = result.reached_target
56
+ failed = not result.reached_target
57
+ else:
58
+ measures = [(f, measure(f)) for f in args.files]
59
+ records = [_record(f, m) for f, m in measures]
60
+ failed = False
61
+ if args.target is not None:
62
+ failed = any(
63
+ abs(m.integrated - args.target) > 1.0 or m.true_peak > args.tp for _, m in measures
64
+ )
65
+ except LoudnessError as error:
66
+ print(f"error: {error}", file=sys.stderr)
67
+ return 2
68
+ if args.json:
69
+ print(json.dumps(records, indent=2, allow_nan=False))
70
+ else:
71
+ for r in records:
72
+ print(f"{r['file']}: {r['integrated_lufs']} LUFS, {r['true_peak_dbtp']} dBTP, LRA {r['lra']}")
73
+ return 1 if failed else 0
74
+
75
+
76
+ if __name__ == "__main__":
77
+ sys.exit(main())
@@ -0,0 +1,385 @@
1
+ """ffmpeg loudness measurement and gain helpers.
2
+
3
+ Everything that parses ffmpeg output or builds a filter string is a pure function.
4
+ Only `measure`, `measure_loudnorm`, `apply_gain` and `normalize` run ffmpeg.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import math
11
+ import re
12
+ import shutil
13
+ import subprocess
14
+ from dataclasses import dataclass
15
+ from pathlib import Path
16
+ from typing import Literal, Sequence
17
+
18
+ DEFAULT_TARGET_LUFS = -14.0
19
+ DEFAULT_TRUE_PEAK_DBTP = -1.0
20
+ REACHED_TOLERANCE_LU = 0.5
21
+
22
+ _NUMBER = r"(-?\d+(?:\.\d+)?|-inf|inf)"
23
+ _AUDIO_ONLY_SUFFIXES = {".wav", ".flac", ".mp3", ".ogg", ".opus", ".aiff", ".aif"}
24
+ _CODEC_BY_SUFFIX = {
25
+ ".wav": "pcm_s24le",
26
+ ".aiff": "pcm_s24le",
27
+ ".aif": "pcm_s24le",
28
+ ".flac": "flac",
29
+ ".mp3": "libmp3lame",
30
+ ".ogg": "libvorbis",
31
+ ".opus": "libopus",
32
+ }
33
+
34
+
35
+ class LoudnessError(Exception):
36
+ """Measurement or normalization failed; the message says why."""
37
+
38
+
39
+ class FfmpegNotFoundError(LoudnessError):
40
+ """ffmpeg is not on PATH."""
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class Measure:
45
+ """Result of an EBU R128 measurement. Silence reads as -inf."""
46
+
47
+ integrated: float
48
+ true_peak: float
49
+ lra: float | None = None
50
+
51
+ @property
52
+ def is_silent(self) -> bool:
53
+ return self.true_peak == -math.inf or self.integrated == -math.inf
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class NormalizeResult:
58
+ """What `normalize` did: the gain applied, what limited it, and both measurements."""
59
+
60
+ gain_db: float
61
+ limited_by: str
62
+ before: Measure
63
+ after: Measure
64
+ attempts: int
65
+ reached_target: bool
66
+
67
+
68
+ def _to_float(text: str) -> float:
69
+ if text == "-inf":
70
+ return -math.inf
71
+ if text == "inf":
72
+ return math.inf
73
+ return float(text)
74
+
75
+
76
+ def parse_ebur128_summary(log: str) -> Measure:
77
+ """Read the final `Summary:` block that ffmpeg's ebur128 filter prints.
78
+
79
+ Running per-100 ms lines before the summary are ignored. Raises LoudnessError
80
+ when there is no summary (for example, the input had no audio stream).
81
+ """
82
+ index = log.rfind("Summary:")
83
+ if index < 0:
84
+ raise LoudnessError("ffmpeg printed no ebur128 summary")
85
+ summary = log[index:]
86
+ integrated = re.search(r"\bI:\s+" + _NUMBER + r"\s+LUFS", summary)
87
+ if integrated is None:
88
+ raise LoudnessError("ebur128 summary has no integrated loudness")
89
+ peak = re.search(r"True peak:\s*Peak:\s+" + _NUMBER + r"\s+dBFS", summary)
90
+ if peak is None:
91
+ raise LoudnessError("ebur128 summary has no true peak; run with peak=true")
92
+ lra = re.search(r"\bLRA:\s+" + _NUMBER + r"\s+LU", summary)
93
+ return Measure(
94
+ integrated=_to_float(integrated.group(1)),
95
+ true_peak=_to_float(peak.group(1)),
96
+ lra=_to_float(lra.group(1)) if lra else None,
97
+ )
98
+
99
+
100
+ def parse_loudnorm_json(log: str) -> dict[str, float | str]:
101
+ """Read the JSON block printed by `loudnorm=print_format=json`.
102
+
103
+ Numeric fields come back as floats (`input_i`, `input_tp`, `input_lra`,
104
+ `input_thresh`, `output_*`, `target_offset`); `normalization_type` stays a string.
105
+ """
106
+ end = log.rfind("}")
107
+ start = log.rfind("{", 0, end + 1) if end >= 0 else -1
108
+ if start < 0 or end < 0:
109
+ raise LoudnessError("ffmpeg printed no loudnorm JSON")
110
+ try:
111
+ raw = json.loads(log[start : end + 1])
112
+ except json.JSONDecodeError as error:
113
+ raise LoudnessError(f"loudnorm JSON is malformed: {error}") from error
114
+ out: dict[str, float | str] = {}
115
+ for key, value in raw.items():
116
+ out[key] = str(value) if key == "normalization_type" else _to_float(str(value))
117
+ for needed in ("input_i", "input_tp", "input_lra", "input_thresh", "target_offset"):
118
+ if needed not in out:
119
+ raise LoudnessError(f"loudnorm JSON lacks {needed}")
120
+ return out
121
+
122
+
123
+ def plan_gain(
124
+ before: Measure,
125
+ target_lufs: float = DEFAULT_TARGET_LUFS,
126
+ true_peak_ceiling: float = DEFAULT_TRUE_PEAK_DBTP,
127
+ headroom_db: float = 0.0,
128
+ max_gain_db: float | None = None,
129
+ ) -> tuple[float, str]:
130
+ """One linear gain in dB and what limited it: "target", "peak" or "cap".
131
+
132
+ The gain is the smallest of: what reaches the target loudness, what keeps the
133
+ true peak under the ceiling minus `headroom_db`, and `max_gain_db` when given.
134
+ Raises LoudnessError for silent input, which has no meaningful gain.
135
+ """
136
+ if before.is_silent:
137
+ raise LoudnessError("input is silent; there is no gain to plan")
138
+ limits: dict[str, float] = {
139
+ "target": target_lufs - before.integrated,
140
+ "peak": true_peak_ceiling - headroom_db - before.true_peak,
141
+ }
142
+ if max_gain_db is not None:
143
+ limits["cap"] = max_gain_db
144
+ limited_by = min(limits, key=lambda name: limits[name])
145
+ return round(limits[limited_by], 2), limited_by
146
+
147
+
148
+ def common_target(
149
+ measures: Sequence[Measure],
150
+ target_lufs: float = DEFAULT_TARGET_LUFS,
151
+ true_peak_ceiling: float = DEFAULT_TRUE_PEAK_DBTP,
152
+ ) -> float:
153
+ """The loudness a batch can share without any clip passing the peak ceiling.
154
+
155
+ Returns the lowest of `target_lufs` and, for each non-silent clip, the loudness it
156
+ would have after being raised as far as its true peak allows. Clips are never
157
+ pushed past their peaks; the batch is lowered to the value returned.
158
+ """
159
+ reachable = [
160
+ m.integrated + (true_peak_ceiling - m.true_peak) for m in measures if not m.is_silent
161
+ ]
162
+ if not reachable:
163
+ raise LoudnessError("no measurable clips")
164
+ return round(min([target_lufs, *reachable]), 2)
165
+
166
+
167
+ def volume_filter(gain_db: float) -> str:
168
+ return f"volume={gain_db:.2f}dB"
169
+
170
+
171
+ def limiter_filter(limit_dbfs: float, sample_rate: int = 48000, oversample: int = 4) -> str:
172
+ """An `alimiter` chain that limits peaks while working at a higher sample rate.
173
+
174
+ alimiter takes a linear limit, so the dB value is converted (alimiter accepts
175
+ 0.0625 to 1). The audio is resampled up by `oversample`, limited, and returned to
176
+ `sample_rate`.
177
+ """
178
+ if oversample < 1:
179
+ raise ValueError("oversample must be at least 1")
180
+ if limit_dbfs > 0:
181
+ raise ValueError("limit_dbfs must be 0 or below")
182
+ limit = max(10 ** (limit_dbfs / 20), 0.0625)
183
+ chain = []
184
+ if oversample > 1:
185
+ chain.append(f"aresample={sample_rate * oversample}")
186
+ chain.append(f"alimiter=limit={limit:.6f}:level=disabled:attack=5:release=50")
187
+ if oversample > 1:
188
+ chain.append(f"aresample={sample_rate}")
189
+ return ",".join(chain)
190
+
191
+
192
+ def loudnorm_filter(
193
+ target_lufs: float = DEFAULT_TARGET_LUFS,
194
+ true_peak: float = DEFAULT_TRUE_PEAK_DBTP,
195
+ lra: float = 11.0,
196
+ measured: dict[str, float | str] | None = None,
197
+ print_json: bool = False,
198
+ ) -> str:
199
+ """Build a `loudnorm` filter. With `measured` (from parse_loudnorm_json) it is the
200
+ second, linear pass; without it, a first pass or a dynamic single pass."""
201
+ parts = [f"I={target_lufs:g}", f"TP={true_peak:g}", f"LRA={lra:g}"]
202
+ if measured is not None:
203
+ parts += [
204
+ f"measured_I={measured['input_i']}",
205
+ f"measured_TP={measured['input_tp']}",
206
+ f"measured_LRA={measured['input_lra']}",
207
+ f"measured_thresh={measured['input_thresh']}",
208
+ f"offset={measured['target_offset']}",
209
+ "linear=true",
210
+ ]
211
+ if print_json:
212
+ parts.append("print_format=json")
213
+ return "loudnorm=" + ":".join(parts)
214
+
215
+
216
+ def _require_ffmpeg() -> str:
217
+ path = shutil.which("ffmpeg")
218
+ if path is None:
219
+ raise FfmpegNotFoundError("ffmpeg was not found on PATH")
220
+ return path
221
+
222
+
223
+ def _run(args: list[str]) -> subprocess.CompletedProcess[str]:
224
+ return subprocess.run(args, capture_output=True, text=True, check=False)
225
+
226
+
227
+ def measure(path: str | Path, audio_stream: int = 0) -> Measure:
228
+ """Integrated loudness, true peak and loudness range of a file's audio (ebur128)."""
229
+ ffmpeg = _require_ffmpeg()
230
+ done = _run(
231
+ [ffmpeg, "-nostdin", "-hide_banner", "-nostats", "-i", str(path)]
232
+ + ["-map", f"0:a:{audio_stream}", "-af", "ebur128=peak=true", "-f", "null", "-"]
233
+ )
234
+ if done.returncode != 0:
235
+ raise LoudnessError(f"ffmpeg could not measure {path}: {done.stderr.strip()[-400:]}")
236
+ return parse_ebur128_summary(done.stderr)
237
+
238
+
239
+ def measure_loudnorm(
240
+ path: str | Path,
241
+ target_lufs: float = DEFAULT_TARGET_LUFS,
242
+ true_peak: float = DEFAULT_TRUE_PEAK_DBTP,
243
+ lra: float = 11.0,
244
+ ) -> dict[str, float | str]:
245
+ """First loudnorm pass: the `input_*` measurements and `target_offset`."""
246
+ ffmpeg = _require_ffmpeg()
247
+ flt = loudnorm_filter(target_lufs, true_peak, lra, print_json=True)
248
+ done = _run(
249
+ [ffmpeg, "-nostdin", "-hide_banner", "-i", str(path), "-vn", "-af", flt, "-f", "null", "-"]
250
+ )
251
+ if done.returncode != 0:
252
+ raise LoudnessError(f"ffmpeg loudnorm failed on {path}: {done.stderr.strip()[-400:]}")
253
+ return parse_loudnorm_json(done.stderr)
254
+
255
+
256
+ def _output_args(dst: Path, copy_video: bool, codec: str | None, bitrate: int, rate: int) -> list[str]:
257
+ suffix = dst.suffix.lower()
258
+ chosen = codec or _CODEC_BY_SUFFIX.get(suffix, "aac")
259
+ if suffix in _AUDIO_ONLY_SUFFIXES or suffix in {".m4a", ".aac"}:
260
+ args = ["-map", "0:a:0", "-vn"]
261
+ elif copy_video:
262
+ args = ["-map", "0:v?", "-map", "0:a:0", "-c:v", "copy"]
263
+ else:
264
+ args = ["-map", "0:a:0", "-vn"]
265
+ args += ["-c:a", chosen]
266
+ if chosen in {"aac", "libmp3lame", "libopus", "libvorbis"}:
267
+ args += ["-b:a", str(bitrate)]
268
+ args += ["-ar", str(rate)]
269
+ if suffix in {".mp4", ".m4a", ".mov"}:
270
+ args += ["-movflags", "+faststart"]
271
+ return args
272
+
273
+
274
+ def _encode(
275
+ src: Path,
276
+ dst: Path,
277
+ chain: str,
278
+ copy_video: bool,
279
+ codec: str | None,
280
+ bitrate: int,
281
+ rate: int,
282
+ ) -> None:
283
+ ffmpeg = _require_ffmpeg()
284
+ args = [ffmpeg, "-nostdin", "-v", "error", "-y", "-i", str(src), "-af", chain]
285
+ args += _output_args(dst, copy_video, codec, bitrate, rate) + [str(dst)]
286
+ done = _run(args)
287
+ if done.returncode != 0:
288
+ dst.unlink(missing_ok=True)
289
+ raise LoudnessError(f"ffmpeg failed: {done.stderr.strip()[-400:]}")
290
+
291
+
292
+ def apply_gain(
293
+ src: str | Path,
294
+ dst: str | Path,
295
+ gain_db: float,
296
+ *,
297
+ extra_filters: Sequence[str] = (),
298
+ copy_video: bool = True,
299
+ codec: str | None = None,
300
+ bitrate: int = 192_000,
301
+ rate: int = 48_000,
302
+ ) -> None:
303
+ """Write `dst` with `gain_db` applied to the first audio stream.
304
+
305
+ Video is copied unchanged when `copy_video` is true and `dst` is a video container.
306
+ The audio codec follows the output suffix (AAC for mp4/mov, PCM for wav) unless
307
+ `codec` is given. `extra_filters` run after the gain, for example a limiter.
308
+ """
309
+ chain = ",".join([volume_filter(gain_db), *extra_filters])
310
+ _encode(Path(src), Path(dst), chain, copy_video, codec, bitrate, rate)
311
+
312
+
313
+ def normalize(
314
+ src: str | Path,
315
+ dst: str | Path,
316
+ target_lufs: float = DEFAULT_TARGET_LUFS,
317
+ true_peak: float = DEFAULT_TRUE_PEAK_DBTP,
318
+ *,
319
+ mode: Literal["gain", "loudnorm"] = "gain",
320
+ headroom_db: float = 0.5,
321
+ max_gain_db: float | None = 12.0,
322
+ retries: int = 3,
323
+ lra: float = 11.0,
324
+ copy_video: bool = True,
325
+ codec: str | None = None,
326
+ bitrate: int = 192_000,
327
+ rate: int = 48_000,
328
+ ) -> NormalizeResult:
329
+ """Bring `src` to `target_lufs` while keeping the true peak at or under `true_peak`.
330
+
331
+ mode="gain": one linear gain from `plan_gain`. After encoding, the output is measured;
332
+ if its true peak is over the ceiling, the gain drops by the excess plus 0.1 dB and the
333
+ file is encoded again, up to `retries` times, then LoudnessError.
334
+
335
+ mode="loudnorm": two-pass ffmpeg loudnorm (measure, then linear correction), then the
336
+ same measure-and-trim loop for any remaining peak overshoot.
337
+
338
+ Silent input is refused with LoudnessError.
339
+ """
340
+ if mode not in ("gain", "loudnorm"):
341
+ raise ValueError("mode must be 'gain' or 'loudnorm'")
342
+ src, dst = Path(src), Path(dst)
343
+ if src.resolve() == dst.resolve():
344
+ raise LoudnessError("dst must differ from src")
345
+ before = measure(src)
346
+ if before.is_silent:
347
+ raise LoudnessError(f"{src} is silent; nothing to normalize")
348
+ dst.parent.mkdir(parents=True, exist_ok=True)
349
+ shared = {"copy_video": copy_video, "codec": codec, "bitrate": bitrate, "rate": rate}
350
+ gain = 0.0
351
+ limited_by = "target"
352
+ attempts = 0
353
+ if mode == "loudnorm":
354
+ stats = measure_loudnorm(src, target_lufs, true_peak, lra)
355
+ chain = loudnorm_filter(target_lufs, true_peak, lra, measured=stats)
356
+ _encode(src, dst, chain, **shared) # type: ignore[arg-type]
357
+ attempts = 1
358
+ after = measure(dst)
359
+ trim_file = dst.with_name(dst.stem + ".trim" + dst.suffix)
360
+ while after.true_peak > true_peak and attempts <= retries:
361
+ excess = round(after.true_peak - true_peak + 0.1, 2)
362
+ apply_gain(dst, trim_file, -excess, **shared) # type: ignore[arg-type]
363
+ trim_file.replace(dst)
364
+ gain -= excess
365
+ limited_by = "peak"
366
+ attempts += 1
367
+ after = measure(dst)
368
+ gain = round(gain, 2)
369
+ else:
370
+ gain, limited_by = plan_gain(before, target_lufs, true_peak, headroom_db, max_gain_db)
371
+ after = before
372
+ for attempts in range(1, retries + 1):
373
+ apply_gain(src, dst, gain, **shared) # type: ignore[arg-type]
374
+ after = measure(dst)
375
+ if after.true_peak <= true_peak:
376
+ break
377
+ gain = round(gain - (after.true_peak - true_peak) - 0.1, 2)
378
+ limited_by = "peak"
379
+ if after.true_peak > true_peak:
380
+ dst.unlink(missing_ok=True)
381
+ raise LoudnessError(
382
+ f"true peak stayed over {true_peak} dBTP ({after.true_peak}) after {attempts} encodes"
383
+ )
384
+ reached = abs(after.integrated - target_lufs) <= REACHED_TOLERANCE_LU
385
+ return NormalizeResult(gain, limited_by, before, after, attempts, reached)
@@ -0,0 +1,304 @@
1
+ import json
2
+ import math
3
+ import shutil
4
+ import subprocess
5
+
6
+ import pytest
7
+
8
+ from uppercut_ffmpeg_loudness import (
9
+ LoudnessError,
10
+ Measure,
11
+ apply_gain,
12
+ common_target,
13
+ limiter_filter,
14
+ loudnorm_filter,
15
+ measure,
16
+ measure_loudnorm,
17
+ normalize,
18
+ parse_ebur128_summary,
19
+ parse_loudnorm_json,
20
+ plan_gain,
21
+ volume_filter,
22
+ )
23
+ from uppercut_ffmpeg_loudness.cli import main as cli_main
24
+
25
+ SUMMARY = """\
26
+ [Parsed_ebur128_0 @ 0x1] t: 1.9 TARGET:-23 LUFS M: -21.8 S:-120.7 I: -50.0 LUFS LRA: 9.0 LU
27
+ [Parsed_ebur128_0 @ 0x1] Summary:
28
+
29
+ Integrated loudness:
30
+ I: -21.8 LUFS
31
+ Threshold: -31.8 LUFS
32
+
33
+ Loudness range:
34
+ LRA: 3.5 LU
35
+ Threshold: 0.0 LUFS
36
+ LRA low: 0.0 LUFS
37
+ LRA high: 0.0 LUFS
38
+
39
+ True peak:
40
+ Peak: -18.1 dBFS
41
+ [out#0/null @ 0x2] video:0KiB audio:172KiB
42
+ """
43
+
44
+ LOUDNORM = """\
45
+ [Parsed_loudnorm_0 @ 0x77]
46
+ {
47
+ \t"input_i" : "-21.75",
48
+ \t"input_tp" : "-18.06",
49
+ \t"input_lra" : "0.00",
50
+ \t"input_thresh" : "-31.75",
51
+ \t"output_i" : "-16.05",
52
+ \t"output_tp" : "-12.31",
53
+ \t"output_lra" : "0.00",
54
+ \t"output_thresh" : "-26.05",
55
+ \t"normalization_type" : "linear",
56
+ \t"target_offset" : "0.05"
57
+ }
58
+ [out#0/null @ 0x7] video:0KiB audio:750KiB
59
+ """
60
+
61
+
62
+ # ---- pure parsing and planning -------------------------------------------------
63
+
64
+
65
+ def test_parse_summary_uses_final_block_only():
66
+ m = parse_ebur128_summary(SUMMARY)
67
+ assert m == Measure(integrated=-21.8, true_peak=-18.1, lra=3.5)
68
+
69
+
70
+ def test_parse_summary_handles_silence():
71
+ text = SUMMARY.replace("-21.8 LUFS\n Threshold", "-inf LUFS\n Threshold").replace(
72
+ "-18.1 dBFS", "-inf dBFS"
73
+ )
74
+ m = parse_ebur128_summary(text)
75
+ assert m.integrated == -math.inf and m.true_peak == -math.inf
76
+ assert m.is_silent
77
+
78
+
79
+ def test_parse_summary_errors():
80
+ with pytest.raises(LoudnessError, match="no ebur128 summary"):
81
+ parse_ebur128_summary("nothing here")
82
+ with pytest.raises(LoudnessError, match="true peak"):
83
+ parse_ebur128_summary("Summary:\n I: -20.0 LUFS\n")
84
+ with pytest.raises(LoudnessError, match="integrated"):
85
+ parse_ebur128_summary("Summary:\n True peak:\n Peak: -1.0 dBFS\n")
86
+
87
+
88
+ def test_parse_summary_without_lra():
89
+ text = "Summary:\n I: -20.0 LUFS\n True peak:\n Peak: -3.0 dBFS\n"
90
+ assert parse_ebur128_summary(text).lra is None
91
+
92
+
93
+ def test_parse_loudnorm_json():
94
+ data = parse_loudnorm_json(LOUDNORM)
95
+ assert data["input_i"] == -21.75
96
+ assert data["target_offset"] == 0.05
97
+ assert data["normalization_type"] == "linear"
98
+
99
+
100
+ def test_parse_loudnorm_json_errors():
101
+ with pytest.raises(LoudnessError, match="no loudnorm JSON"):
102
+ parse_loudnorm_json("no braces")
103
+ with pytest.raises(LoudnessError, match="malformed"):
104
+ parse_loudnorm_json("{ not json }")
105
+ with pytest.raises(LoudnessError, match="lacks"):
106
+ parse_loudnorm_json('{"input_i": "-20"}')
107
+
108
+
109
+ def test_plan_gain_limited_by_target():
110
+ gain, why = plan_gain(Measure(-20.0, -12.0), -14.0, -1.0)
111
+ assert (gain, why) == (6.0, "target")
112
+
113
+
114
+ def test_plan_gain_limited_by_peak():
115
+ gain, why = plan_gain(Measure(-20.0, -4.0), -14.0, -1.0)
116
+ assert (gain, why) == (3.0, "peak")
117
+
118
+
119
+ def test_plan_gain_headroom_and_cap():
120
+ gain, why = plan_gain(Measure(-40.0, -30.0), -14.0, -1.0, headroom_db=0.5, max_gain_db=12.0)
121
+ assert (gain, why) == (12.0, "cap")
122
+ gain, why = plan_gain(Measure(-20.0, -4.0), -14.0, -1.0, headroom_db=0.5)
123
+ assert (gain, why) == (2.5, "peak")
124
+
125
+
126
+ def test_plan_gain_can_lower():
127
+ gain, why = plan_gain(Measure(-8.0, -0.5), -14.0, -1.0)
128
+ assert gain == -6.0 and why == "target"
129
+
130
+
131
+ def test_plan_gain_silent_raises():
132
+ with pytest.raises(LoudnessError):
133
+ plan_gain(Measure(-math.inf, -math.inf))
134
+
135
+
136
+ def test_common_target_is_lowest_reachable():
137
+ clips = [Measure(-20.0, -6.0), Measure(-18.0, -2.0), Measure(-30.0, -20.0)]
138
+ # clip 2 can reach -18 + (-1 - -2) = -17; clip 1 -15; clip 3 -11; target -14 -> min is -17
139
+ assert common_target(clips, -14.0, -1.0) == -17.0
140
+ assert common_target(clips[:1], -14.0, -1.0) == -15.0
141
+ assert common_target([Measure(-30.0, -25.0)], -14.0, -1.0) == -14.0
142
+
143
+
144
+ def test_common_target_skips_silent_and_rejects_empty():
145
+ silent = Measure(-math.inf, -math.inf)
146
+ assert common_target([silent, Measure(-30.0, -25.0)], -14.0, -1.0) == -14.0
147
+ with pytest.raises(LoudnessError):
148
+ common_target([silent])
149
+ with pytest.raises(LoudnessError):
150
+ common_target([])
151
+
152
+
153
+ def test_filters():
154
+ assert volume_filter(-3.456) == "volume=-3.46dB"
155
+ assert loudnorm_filter(-16, -1.5) == "loudnorm=I=-16:TP=-1.5:LRA=11"
156
+ flt = loudnorm_filter(-16, -1.5, measured=parse_loudnorm_json(LOUDNORM))
157
+ assert "measured_I=-21.75" in flt and flt.endswith("linear=true")
158
+ assert loudnorm_filter(print_json=True).endswith("print_format=json")
159
+ limiter = limiter_filter(-1.0)
160
+ assert limiter.startswith("aresample=192000,alimiter=limit=0.891251")
161
+ assert limiter.endswith("aresample=48000")
162
+ assert limiter_filter(-1.0, oversample=1).startswith("alimiter=")
163
+ assert "limit=0.062500" in limiter_filter(-60.0)
164
+ with pytest.raises(ValueError):
165
+ limiter_filter(-1.0, oversample=0)
166
+ with pytest.raises(ValueError):
167
+ limiter_filter(3.0)
168
+
169
+
170
+ # ---- tests that need ffmpeg ------------------------------------------------------
171
+
172
+ needs_ffmpeg = pytest.mark.skipif(shutil.which("ffmpeg") is None, reason="ffmpeg not on PATH")
173
+
174
+
175
+ def _sine(path, volume_db=0.0, seconds=3, video=False):
176
+ cmd = ["ffmpeg", "-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", f"aevalsrc=sin(2*PI*440*t):d={seconds}:s=48000"]
177
+ if video:
178
+ cmd += ["-f", "lavfi", "-i", f"color=c=black:s=64x64:d={seconds}:r=10"]
179
+ cmd += ["-af", f"volume={volume_db}dB"]
180
+ if video:
181
+ cmd += ["-c:v", "mpeg4", "-c:a", "aac", "-shortest"]
182
+ cmd.append(str(path))
183
+ subprocess.run(cmd, check=True)
184
+ return path
185
+
186
+
187
+ @needs_ffmpeg
188
+ def test_measure_matches_expected_level(tmp_path):
189
+ src = _sine(tmp_path / "a.wav", -20.0)
190
+ m = measure(src)
191
+ assert -26.0 < m.integrated < -22.0
192
+ assert m.true_peak == pytest.approx(-20.0, abs=0.5)
193
+ assert m.lra is not None
194
+
195
+
196
+ @needs_ffmpeg
197
+ def test_measure_missing_file_and_no_audio(tmp_path):
198
+ with pytest.raises(LoudnessError):
199
+ measure(tmp_path / "missing.wav")
200
+ video = tmp_path / "v.mp4"
201
+ subprocess.run(
202
+ ["ffmpeg", "-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "color=c=black:s=64x64:d=1:r=10",
203
+ "-c:v", "mpeg4", str(video)],
204
+ check=True,
205
+ )
206
+ with pytest.raises(LoudnessError):
207
+ measure(video)
208
+
209
+
210
+ @needs_ffmpeg
211
+ def test_measure_loudnorm_first_pass(tmp_path):
212
+ src = _sine(tmp_path / "a.wav", -10.0)
213
+ stats = measure_loudnorm(src, -16.0, -1.5)
214
+ assert stats["input_tp"] == pytest.approx(-10.0, abs=0.6)
215
+
216
+
217
+ @needs_ffmpeg
218
+ def test_apply_gain_changes_level(tmp_path):
219
+ src = _sine(tmp_path / "a.wav", -20.0)
220
+ dst = tmp_path / "b.wav"
221
+ apply_gain(src, dst, 6.0)
222
+ assert measure(dst).integrated - measure(src).integrated == pytest.approx(6.0, abs=0.3)
223
+
224
+
225
+ @needs_ffmpeg
226
+ def test_normalize_gain_mode_hits_target(tmp_path):
227
+ src = _sine(tmp_path / "a.wav", -24.0, seconds=4)
228
+ dst = tmp_path / "out" / "b.wav"
229
+ result = normalize(src, dst, target_lufs=-16.0, true_peak=-1.0)
230
+ assert result.reached_target
231
+ assert result.after.integrated == pytest.approx(-16.0, abs=0.5)
232
+ assert result.after.true_peak <= -1.0
233
+ assert result.limited_by == "target"
234
+
235
+
236
+ @needs_ffmpeg
237
+ def test_normalize_respects_peak_ceiling(tmp_path):
238
+ src = _sine(tmp_path / "a.wav", -3.0)
239
+ dst = tmp_path / "b.wav"
240
+ # a sine peaking at -3 dBFS sits near -6 LUFS; a -6 dBTP ceiling is below it, so the peak decides
241
+ result = normalize(src, dst, target_lufs=-5.0, true_peak=-6.0)
242
+ assert result.limited_by == "peak"
243
+ assert result.after.true_peak <= -6.0
244
+
245
+
246
+ @needs_ffmpeg
247
+ def test_normalize_loudnorm_mode(tmp_path):
248
+ src = _sine(tmp_path / "a.wav", -24.0, seconds=4)
249
+ dst = tmp_path / "b.wav"
250
+ result = normalize(src, dst, target_lufs=-16.0, true_peak=-1.5, mode="loudnorm")
251
+ assert result.after.true_peak <= -1.5
252
+ assert result.after.integrated == pytest.approx(-16.0, abs=1.0)
253
+
254
+
255
+ @needs_ffmpeg
256
+ def test_normalize_keeps_video_stream(tmp_path):
257
+ src = _sine(tmp_path / "a.mp4", -24.0, seconds=3, video=True)
258
+ dst = tmp_path / "b.mp4"
259
+ result = normalize(src, dst, target_lufs=-16.0, true_peak=-1.0)
260
+ probe = subprocess.run(["ffmpeg", "-hide_banner", "-i", str(dst)], capture_output=True, text=True).stderr
261
+ assert "Video:" in probe and "Audio:" in probe
262
+ assert result.after.true_peak <= -1.0
263
+
264
+
265
+ @needs_ffmpeg
266
+ def test_normalize_refuses_silence_and_same_path(tmp_path):
267
+ silent = tmp_path / "s.wav"
268
+ subprocess.run(
269
+ ["ffmpeg", "-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "anullsrc=d=2", str(silent)], check=True
270
+ )
271
+ with pytest.raises(LoudnessError, match="silent"):
272
+ normalize(silent, tmp_path / "o.wav")
273
+ with pytest.raises(LoudnessError, match="differ"):
274
+ normalize(silent, silent)
275
+
276
+
277
+ def test_normalize_rejects_bad_mode(tmp_path):
278
+ with pytest.raises(ValueError):
279
+ normalize(tmp_path / "a.wav", tmp_path / "b.wav", mode="nope") # type: ignore[arg-type]
280
+
281
+
282
+ def test_measure_without_ffmpeg(monkeypatch, tmp_path):
283
+ from uppercut_ffmpeg_loudness import core
284
+
285
+ monkeypatch.setattr(core.shutil, "which", lambda name: None)
286
+ with pytest.raises(core.FfmpegNotFoundError):
287
+ measure(tmp_path / "x.wav")
288
+
289
+
290
+ @needs_ffmpeg
291
+ def test_cli_measure_json(tmp_path, capsys):
292
+ src = _sine(tmp_path / "a.wav", -20.0)
293
+ code = cli_main([str(src), "--json", "--target", "-14"])
294
+ out = json.loads(capsys.readouterr().out)
295
+ assert out[0]["file"] == str(src)
296
+ assert code == 1 # far from the target
297
+
298
+
299
+ def test_cli_reports_missing_ffmpeg(monkeypatch, tmp_path, capsys):
300
+ from uppercut_ffmpeg_loudness import core
301
+
302
+ monkeypatch.setattr(core.shutil, "which", lambda name: None)
303
+ assert cli_main([str(tmp_path / "x.wav")]) == 2
304
+ assert "ffmpeg" in capsys.readouterr().err