carlos / platform Public

media: ebur128 meter, float downmix, ceiling held after encode

Plan 3 Task 5 fix round 1.

The loudness pass and the audio-aac encode both mix down in planar
float (aformat sample_fmts=fltp): 5.1 and 7.1 integer-PCM sources
were measured 7.7 and 10 dB under what was encoded.

The meter is ebur128=peak=true:framelog=quiet, not loudnorm, whose
first pass counts its lookahead twice (a 6 s clip read -28.01 LUFS
for a true -15.1 and came out at -14.3). I is measurable only over
-70.0; the true peak gets half the meter's 0.1 unit (0.05 dB)
before the ceiling term. Its stderr is still never logged.

encodeAudioUnderCeiling meters audio.mp4 and, when its true peak is
over -1.5 dBTP, encodes once more with the gain lowered by the excess
plus 0.3 dB; a second overshoot is kept and logged. It returns the
gain used, for the peaks.

Real-binary tests: multichannel s32 FLAC and s16 WAV, b18 and the
6 s burst at -16 +/- 0.5 LUFS, and noise bursts that overshoot the
first encode. Copy deck rows updated, pending a Luna pass.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 67fee4c9b6921d06b47f2418683fc5280c5d4be9 parent 1bd1d95
9 files changed, +678 −342
  • docs/superpowers/notes/media-conversion-copy-deck.md +9 −9
  • internal/mediahandler/ffmpeg.go +3 −2
  • internal/mediahandler/ffmpeg_test.go +2 −2
  • internal/mediahandler/loudness.go +182 −87
  • internal/mediahandler/loudness_linux_test.go +283 −83
  • internal/mediahandler/loudness_test.go +137 −103
  • internal/mediahandler/testdata/loudnorm/peaky-forged-tags.stderr +24 −21
  • internal/mediahandler/testdata/loudnorm/provenance.txt +21 −19
  • internal/mediahandler/testdata/loudnorm/silence.stderr +17 −16

CI passed — run details

diff --git a/docs/superpowers/notes/media-conversion-copy-deck.md b/docs/superpowers/notes/media-conversion-copy-deck.md
index 8d35efc78..e033b2f05 100644
--- a/docs/superpowers/notes/media-conversion-copy-deck.md
+++ b/docs/superpowers/notes/media-conversion-copy-deck.md
@@ -564,14 +564,14 @@ prints nothing.
| `engine.child.failed` | `codec: child process: %s: %s`, or without the second `%s` (pending Luna pass; plan 3 Task 3). The first `%s` is one of `cannot become a subreaper`, `no pipe`, `cannot start <binary path>`, `the child outlived SIGKILL`, `descendants outlived the cleanup`, `a pipe stayed open`, `wait failed`; the second is the system's error |
| `engine.child.unsupported` | `codec: child processes need Linux` (pending Luna pass; plan 3 Task 3). Only off Linux, where the handler never runs |
| `engine.encode.failed` | `codec: ffmpeg (%s) failed: %q` (pending Luna pass; plan 3 Task 4). `%s` is one of `video`, `poster`, `poster from the first frame`, `audio`, `peaks` (Task 5); `%q` is the last 4 KiB of ffmpeg's stderr at `-loglevel error`, quoted so it stays one line |
-| `engine.encode.failed_unlogged` | `codec: ffmpeg (%s) failed; its output is not logged` (pending Luna pass; plan 3 Task 5). `%s` is `loudness`: that pass runs at `-loglevel info`, where ffmpeg prints the source's tags, so none of its stderr is logged (preflight F19) |
-| `engine.encode.killed` | `codec: ffmpeg (%s) was killed by SIGKILL, likely out of memory` (pending Luna pass; plan 3 Task 4). `%s` as `engine.encode.failed`, or `loudness` (Task 5) |
+| `engine.encode.failed_unlogged` | `codec: ffmpeg (%s) failed; its output is not logged` (pending Luna pass; plan 3 Task 5). `%s` is `loudness` or `output meter` (fix 1): those passes run at `-loglevel info`, where ffmpeg prints the input's tags, so none of their stderr is logged (preflight F19) |
+| `engine.encode.killed` | `codec: ffmpeg (%s) was killed by SIGKILL, likely out of memory` (pending Luna pass; plan 3 Task 4). `%s` as `engine.encode.failed`, or `loudness` or `output meter` (Task 5) |
| `engine.encode.empty` | `codec: ffmpeg wrote no sample to %s` (pending Luna pass; plan 3 Task 4). `%s` is `video.mp4`, `audio.mp4` or `peaks.raw` (Task 5) |
| `engine.encode.unusable` | `codec: %s: %s` (pending Luna pass; plan 3 Task 4). The first `%s` is an output's name, `the output directory`, or (Task 5) `peaks.raw` or `the scratch tmp directory`; the second is the system's error, one of readFMP4's fixed reasons (a box type and a byte offset, never the file's bytes), or (Task 5) `not a regular file`, `fewer samples than the file's size`, `negative sample count`, `negative duration` |
-| `engine.loudness.unmeasured` | `codec: ffmpeg (loudness) gave no measurement: %s` (pending Luna pass; plan 3 Task 5). `%s` is one of `engine.loudness.reason.*`, never the stderr |
-| `engine.loudness.reason.none` | `no loudnorm report` (pending Luna pass; plan 3 Task 5) |
-| `engine.loudness.reason.truncated` | `the loudnorm report is truncated` (pending Luna pass; plan 3 Task 5) |
-| `engine.loudness.reason.undecodable` | `the loudnorm report does not decode` (pending Luna pass; plan 3 Task 5) |
-| `engine.loudness.reason.fields` | `the loudnorm report has no input_i or input_tp` (pending Luna pass; plan 3 Task 5) |
-| `engine.loudness.reason.number` | `the loudnorm report's input_i is not a number`, and the same with `input_tp` (pending Luna pass; plan 3 Task 5) |
-| `engine.loudness.gain` | `codec: loudness %.2f LUFS, true peak %.2f dBTP, measurable %t; gain %.2f dB` (pending Luna pass; plan 3 Task 5). Numbers only: the measurement and the one gain applied |
+| `engine.loudness.unmeasured` | `codec: ffmpeg (%s) gave no measurement: %s` (pending Luna pass; plan 3 Task 5, fix 1). The first `%s` is `loudness` or `output meter`; the second is one of `engine.loudness.reason.*`, never the stderr |
+| `engine.loudness.reason.none` | `no ebur128 summary` (pending Luna pass; plan 3 Task 5, fix 1) |
+| `engine.loudness.reason.fields` | `the ebur128 summary has no I or no true peak` (pending Luna pass; plan 3 Task 5, fix 1) |
+| `engine.loudness.reason.number` | `the ebur128 summary's I is not a number`, `the ebur128 summary's true peak is not a number` (pending Luna pass; plan 3 Task 5, fix 1) |
+| `engine.loudness.gain` | `codec: loudness %.1f LUFS, true peak %.1f dBTP, measurable %t; gain %.2f dB` (pending Luna pass; plan 3 Task 5, fix 1: one decimal, the meter's). Numbers only: the measurement and the gain the first encode uses |
+| `engine.loudness.over_ceiling` | `codec: audio.mp4 peaks %.2f dB over the %.1f dBTP ceiling; encoding again at %.2f dB` (pending Luna pass; plan 3 Task 5, fix 1). The excess (true peak plus 0.05 over -1.5), the ceiling, and the second encode's gain |
+| `engine.loudness.still_over` | `codec: audio.mp4 still peaks %.2f dB over the ceiling after the second encode; kept` (pending Luna pass; plan 3 Task 5, fix 1). Never a third encode |
diff --git a/internal/mediahandler/ffmpeg.go b/internal/mediahandler/ffmpeg.go
index 729852750..307589d54 100644
--- a/internal/mediahandler/ffmpeg.go
+++ b/internal/mediahandler/ffmpeg.go
@@ -190,7 +190,8 @@ func posterArgs(cfg Config, f probeFacts, p media.Payload, demuxer string) []str
// audioArgs are audio-aac's encode: the chosen audio stream, at most
// the granted duration, at 48 kHz, mono for a mono source and stereo
-// otherwise (more channels mixed down), with the one linear gain
+// otherwise (more channels mixed down in planar float, as the loudness
+// pass mixes them: measureFormat), with the one linear gain
// gainDB (plan 3 Task 5; a gain that is not a finite number is none),
// to AAC-LC at 64 or 128 kbit/s in <scratch>/out/audio.mp4 (spec §5.1).
func audioArgs(cfg Config, f probeFacts, p media.Payload, demuxer string, gainDB float64) []string {
@@ -199,7 +200,7 @@ func audioArgs(cfg Config, f probeFacts, p media.Payload, demuxer string, gainDB
args = append(args, "-map", "0:"+strconv.Itoa(f.AudioIndex), "-vn")
args = append(args, stripArgs(p)...)
return append(args,
- "-af", "aformat=channel_layouts="+layout+":sample_rates=48000,"+volumeFilter(gainDB),
+ "-af", "aformat=channel_layouts="+layout+measureFormat+","+volumeFilter(gainDB),
"-c:a", "aac", "-b:a", rate,
"-f", "mp4", "-movflags", audioMovflags, "-frag_duration", fragmentMicros,
outPath(cfg, audioNames[0]))
diff --git a/internal/mediahandler/ffmpeg_test.go b/internal/mediahandler/ffmpeg_test.go
index 49ef6e369..94b073a66 100644
--- a/internal/mediahandler/ffmpeg_test.go
+++ b/internal/mediahandler/ffmpeg_test.go
@@ -254,7 +254,7 @@ func TestAudioArgsMonoAndStereo(t *testing.T) {
f := probeFacts{VideoIndex: -1, AudioIndex: 2, AudioCodec: "flac", Channels: 1, DurationMS: 5000}
want := append(inputPrefix("matroska"),
"-map", "0:2", "-vn", "-sn", "-dn", "-map_metadata", "-1", "-map_chapters", "-1", "-t", "7200.000",
- "-af", "aformat=channel_layouts=mono:sample_rates=48000,volume=-3.25dB",
+ "-af", "aformat=channel_layouts=mono:sample_rates=48000:sample_fmts=fltp,volume=-3.25dB",
"-c:a", "aac", "-b:a", "64k",
"-f", "mp4", "-movflags", "+empty_moov+default_base_moof+skip_trailer", "-frag_duration", "4000000",
"/scratch/out/audio.mp4")
@@ -264,7 +264,7 @@ func TestAudioArgsMonoAndStereo(t *testing.T) {
for _, ch := range []int{2, 6, 0} {
f.Channels = ch
got := audioArgs(cfg, f, p, "matroska", 1)
- if af := argAfter(got, "-af"); af != "aformat=channel_layouts=stereo:sample_rates=48000,volume=1.00dB" {
+ if af := argAfter(got, "-af"); af != "aformat=channel_layouts=stereo:sample_rates=48000:sample_fmts=fltp,volume=1.00dB" {
t.Errorf("%d channels: -af %q", ch, af)
}
if br := argAfter(got, "-b:a"); br != "128k" {
diff --git a/internal/mediahandler/loudness.go b/internal/mediahandler/loudness.go
index b710430b0..939410abd 100644
--- a/internal/mediahandler/loudness.go
+++ b/internal/mediahandler/loudness.go
@@ -3,11 +3,13 @@ package mediahandler
import (
"bytes"
"context"
- "encoding/json"
"errors"
+ "io/fs"
"math"
+ "os"
"path/filepath"
"strconv"
+ "strings"
"github.com/carlosframework/platform/internal/media"
)
@@ -18,136 +20,229 @@ import (
// codecHeadroomDB, the true peak the AAC encode may add. The ceiling
// wins, so a quiet source with a loud moment ends below the target, and
// dynamics are never compressed. codecHeadroomDB is provisional until
-// plan 1's spike measures it (plan 3 Task 5).
+// plan 1's spike measures it (plan 3 Task 5). The headroom cannot stop
+// every overshoot (the native AAC encoder adds 0.6 to 5 dB on some
+// transients), so encodeAudioUnderCeiling measures the encoded file
+// and encodes once more, lower, when it is over the ceiling (fix 1).
const (
targetLUFS = -16.0
ceilingDBTP = -1.5
codecHeadroomDB = 0.5
)
-// gateLUFS is the quietest integrated loudness that is measurable:
-// BS.1770's absolute gate. loudnorm answers -inf under it.
+// gateLUFS is BS.1770's absolute gate: ebur128 answers it (-70.0) for
+// a source with nothing over it, so only a loudness over it is
+// measurable.
const gateLUFS = -70.0
-// loudnormFilter measures; its targets are never applied (the pass
-// writes to the null muxer), only its print_format=json report of the
-// input is read.
-const loudnormFilter = "loudnorm=I=-16:TP=-1.5:LRA=11:print_format=json"
+// meterPrecisionDB is half a unit of the meter's summary, which prints
+// one decimal: a true peak printed -2.9 may be -2.85, so every true
+// peak is taken that much higher before the ceiling is compared with
+// it (fix 1).
+const meterPrecisionDB = 0.05
+
+// reencodeMarginDB is how much further than the measured excess the
+// second encode lowers the gain.
+const reencodeMarginDB = 0.3
+
+// meterFilter is the loudness meter: BS.1770 integrated loudness and
+// true peak (4x oversampled), printed once, as a summary, when the
+// graph ends. Not loudnorm: its first pass counts its 3 s lookahead
+// twice, so a short clip with gated quiet parts measured up to 9 LU off
+// (fix 1).
+const meterFilter = "ebur128=peak=true:framelog=quiet"
+
+// measureFormat makes the measure pass and the encode mix down alike:
+// planar float, where swresample does not normalise the downmix matrix.
+// Without it an integer-PCM source (s16 WAV, s32 FLAC) with more than
+// two channels negotiated an integer downmix in the measure pass,
+// normalised, and measured 7.66 dB (5.1) or 9.95 dB (7.1) quieter than
+// the encode mixed it (fix 1). audioArgs uses it too.
+const measureFormat = ":sample_rates=48000:sample_fmts=fltp"
// measureArgs are the loudness pass: what audioArgs encodes (the same
-// input, stream, strip and grant, the same layout at 48 kHz), through
-// loudnorm into the null muxer. -loglevel info, because loudnorm prints
-// its report at that level; at that level ffmpeg also prints the
-// source's metadata, so measureLoudness never logs this run's stderr
-// (preflight F19). layout is audioLayout's. Every path is cfg's
-// (preflight F21).
+// input, stream, strip and grant, the same layout, rate and sample
+// format), through meterFilter into the null muxer. -loglevel info,
+// because ebur128 prints its summary at that level; at that level
+// ffmpeg also prints the source's metadata, so measureLoudness never
+// logs this run's stderr (preflight F19). layout is audioLayout's.
+// Every path is cfg's (preflight F21).
func measureArgs(cfg Config, f probeFacts, p media.Payload, demuxer, layout string) []string {
args := ffmpegInputArgsAt(cfg, demuxer, "info")
args = append(args, "-map", "0:"+strconv.Itoa(f.AudioIndex), "-vn")
args = append(args, stripArgs(p)...)
return append(args,
- "-af", "aformat=channel_layouts="+layout+":sample_rates=48000,"+loudnormFilter,
+ "-af", "aformat=channel_layouts="+layout+measureFormat+","+meterFilter,
"-f", "null", "-")
}
-// loudnormPrefix begins the log line loudnorm prints before its JSON
-// report: "[Parsed_loudnorm_<n> @ 0x…] ".
-var loudnormPrefix = []byte("[Parsed_loudnorm_")
-
-// parseLoudnorm reads loudnorm's report from the loudness pass's
-// stderr: the JSON object that follows the last line beginning with
-// loudnormPrefix, of which it reads input_i (integrated loudness, LUFS)
-// and input_tp (true peak, dBTP), both strings of numbers, "-inf" for
-// none. Only a line's start counts, after a newline: ffmpeg prints the
-// source's tags indented, a tag's every line included, so a tag cannot
-// forge the report; and the stderr's first byte, where runChild's tail
-// may have cut a tag's line, is not a line's start. loudnorm prints
-// its report when the filter graph ends, after the source has been
-// read, so the last such line is the report. measurable is
-// isMeasurable's. A missing, truncated or malformed report is an
+// outputMeterArgs meter the encoded <scratch>/out/audio.mp4 as the
+// loudness pass meters the source: its one audio stream, through
+// meterFilter, at -loglevel info. The file is ffmpeg's own output, but
+// ffmpeg has read hostile input, so it gets the same input options as
+// the source (the mov demuxer forced, no external references) and an
+// AAC-only decoder list.
+func outputMeterArgs(cfg Config) []string {
+ args := append([]string{"-hide_banner", "-nostats", "-loglevel", "info", "-nostdin"}, inputArgs("mov")...)
+ return append(args, "-codec_whitelist", "aac", "-i", outPath(cfg, audioNames[0]),
+ "-map", "0:a:0", "-vn", "-sn", "-dn", "-af", meterFilter, "-f", "null", "-")
+}
+
+// meterPrefix begins the log line ebur128 prints its summary under:
+// "[Parsed_ebur128_<n> @ 0x…] Summary:".
+var meterPrefix = []byte("[Parsed_ebur128_")
+
+// parseMeter reads ebur128's summary from a pass's stderr: the lines
+// after the last line beginning with meterPrefix, up to the next line
+// that is not indented, of which it reads "I: <n> LUFS" (integrated
+// loudness) and, under "True peak:", "Peak: <n> dBFS" (the true peak,
+// dBTP). "-inf" is a number here; "nan" is not. Only a line's start counts, after a
+// newline: ffmpeg prints the source's tags indented, a tag's every line
+// included, so a tag cannot forge the summary; and the stderr's first
+// byte, where runChild's tail may have cut a tag's line, is not a
+// line's start. ebur128 prints when the graph ends, after the source
+// has been read, so the last such line is the summary. measurable is
+// isMeasurable's. A missing, truncated or malformed summary is an
// error; no error quotes the stderr, which holds the source's tags.
-func parseLoudnorm(stderr []byte) (inputI, inputTP float64, measurable bool, err error) {
- at := bytes.LastIndex(stderr, append([]byte{'\n'}, loudnormPrefix...))
+func parseMeter(stderr []byte) (inputI, inputTP float64, measurable bool, err error) {
+ at := bytes.LastIndex(stderr, append([]byte{'\n'}, meterPrefix...))
if at < 0 {
- return 0, 0, false, errors.New("no loudnorm report")
- }
- at++
- nl := bytes.IndexByte(stderr[at:], '\n')
- if nl < 0 {
- return 0, 0, false, errors.New("the loudnorm report is truncated")
- }
- // The report is the JSON object on the lines after it: anything else
- // there does not decode into it, or leaves its fields unset.
- rest := stderr[at+nl+1:]
- var report struct {
- InputI *string `json:"input_i"`
- InputTP *string `json:"input_tp"`
- }
- if json.NewDecoder(bytes.NewReader(rest)).Decode(&report) != nil {
- // A json error can quote the input: never pass it on.
- return 0, 0, false, errors.New("the loudnorm report does not decode")
+ return 0, 0, false, errors.New("no ebur128 summary")
}
- if report.InputI == nil || report.InputTP == nil {
- return 0, 0, false, errors.New("the loudnorm report has no input_i or input_tp")
+ lines := strings.Split(string(stderr[at+1:]), "\n")
+ var gotI, gotTP, truePeak bool
+ for _, line := range lines[1:] {
+ if line != "" && line[0] != ' ' {
+ break // the summary's end: the next log line
+ }
+ fields := strings.Fields(line)
+ switch {
+ case len(fields) == 2 && fields[0] == "True" && fields[1] == "peak:":
+ truePeak = true
+ case len(fields) == 3 && fields[0] == "I:" && fields[2] == "LUFS" && !gotI:
+ if inputI, err = strconv.ParseFloat(fields[1], 64); err != nil || math.IsNaN(inputI) {
+ return 0, 0, false, errors.New("the ebur128 summary's I is not a number")
+ }
+ gotI = true
+ case len(fields) == 3 && fields[0] == "Peak:" && fields[2] == "dBFS" && truePeak && !gotTP:
+ if inputTP, err = strconv.ParseFloat(fields[1], 64); err != nil || math.IsNaN(inputTP) {
+ return 0, 0, false, errors.New("the ebur128 summary's true peak is not a number")
+ }
+ gotTP = true
+ }
}
- if inputI, err = strconv.ParseFloat(*report.InputI, 64); err != nil {
- return 0, 0, false, errors.New("the loudnorm report's input_i is not a number")
- }
- if inputTP, err = strconv.ParseFloat(*report.InputTP, 64); err != nil {
- return 0, 0, false, errors.New("the loudnorm report's input_tp is not a number")
+ if !gotI || !gotTP {
+ return 0, 0, false, errors.New("the ebur128 summary has no I or no true peak")
}
return inputI, inputTP, isMeasurable(inputI, inputTP), nil
}
// isMeasurable reports whether a source has a loudness to normalise:
-// an integrated loudness that is a number at or over gateLUFS, and a
-// true peak that is a number. Silence (-inf), anything under the gate,
-// and a missing peak are not: such a source gets no gain.
+// an integrated loudness that is a number strictly over gateLUFS, and
+// a true peak that is a number. Silence (-70.0 and -inf), anything at
+// or under the gate, and a missing peak are not: such a source gets no
+// gain.
func isMeasurable(inputI, inputTP float64) bool {
finite := func(v float64) bool { return !math.IsNaN(v) && !math.IsInf(v, 0) }
- return finite(inputI) && finite(inputTP) && inputI >= gateLUFS
+ return finite(inputI) && finite(inputTP) && inputI > gateLUFS
}
// gainDB is the one linear gain, in dB: 0 when the source is not
-// measurable, else min(targetLUFS − I, (ceilingDBTP − codecHeadroomDB) −
-// TP), rounded down to the hundredth so the two-decimal volume= that
-// carries it never asks for more than the ceiling allows. The tiny
-// epsilon keeps a gain that is a whole number of hundredths, as
-// loudnorm's two-decimal report gives, from losing one to float error.
+// measurable, else min(targetLUFS − I, (ceilingDBTP − codecHeadroomDB)
+// − (TP + meterPrecisionDB)), rounded down to the hundredth so the
+// two-decimal volume= that carries it never asks for more than the
+// ceiling allows. The tiny epsilon keeps a gain that is a whole number
+// of hundredths from losing one to float error.
func gainDB(inputI, inputTP float64, measurable bool) float64 {
if !measurable || !isMeasurable(inputI, inputTP) {
return 0
}
- g := min(targetLUFS-inputI, (ceilingDBTP-codecHeadroomDB)-inputTP)
- return math.Floor(g*100+1e-9) / 100
+ g := min(targetLUFS-inputI, (ceilingDBTP-codecHeadroomDB)-(inputTP+meterPrecisionDB))
+ return floorHundredth(g)
}
-// measureLoudness runs the loudness pass on the source and answers the
-// gain for audioArgs and peaksArgs. Failures:
-//
-// - the run failing: as ffmpegOutcome maps it, with nothing of its
-// stderr logged (it was run at -loglevel info and holds the
-// source's tags, a location among them: preflight F19);
-// - no usable report in a run that exited 0: unreadable.
-//
-// The stderr stays in this function's memory and is dropped on return;
-// what is logged is the measurement and the gain, numbers only.
-func measureLoudness(ctx context.Context, cfg Config, p media.Payload, demuxer string, f probeFacts) (float64, error) {
- layout, _ := audioLayout(f)
- tail, err := runChild(ctx, cfg, cfg.FFmpeg, measureArgs(cfg, f, p, demuxer, layout), filepath.Join(cfg.Scratch, "tmp"))
+// floorHundredth rounds g down to the hundredth.
+func floorHundredth(g float64) float64 { return math.Floor(g*100+1e-9) / 100 }
+
+// meter runs one meter pass (what names it in the log) and answers
+// ebur128's summary. Nothing of its stderr, at -loglevel info, is
+// logged: a failed run as ffmpegOutcome maps it, quietly; no summary in
+// a run that exited 0 is unreadable. The stderr is dropped on return.
+func meter(ctx context.Context, cfg Config, what string, args []string) (inputI, inputTP float64, measurable bool, err error) {
+ tail, err := runChild(ctx, cfg, cfg.FFmpeg, args, filepath.Join(cfg.Scratch, "tmp"))
defer clear(tail)
- if err := ffmpegOutcome(ctx, cfg, "loudness", err, tail, false); err != nil {
- return 0, err
+ if err := ffmpegOutcome(ctx, cfg, what, err, tail, false); err != nil {
+ return 0, 0, false, err
}
- inputI, inputTP, measurable, err := parseLoudnorm(tail)
+ inputI, inputTP, measurable, err = parseMeter(tail)
if err != nil {
// engine.loudness.unmeasured (pending Luna pass). err is one of
- // parseLoudnorm's fixed reasons.
- cfg.Logf("codec: ffmpeg (loudness) gave no measurement: %v", err)
- return 0, jobError{media.CodeUnreadable}
+ // parseMeter's fixed reasons.
+ cfg.Logf("codec: ffmpeg (%s) gave no measurement: %v", what, err)
+ return 0, 0, false, jobError{media.CodeUnreadable}
+ }
+ return inputI, inputTP, measurable, nil
+}
+
+// measureLoudness runs the loudness pass on the source and answers the
+// gain for encodeAudioUnderCeiling. Failures are meter's: the source's
+// tags, a location among them, are never logged (preflight F19). What
+// is logged is the measurement and the gain, numbers only.
+func measureLoudness(ctx context.Context, cfg Config, p media.Payload, demuxer string, f probeFacts) (float64, error) {
+ layout, _ := audioLayout(f)
+ inputI, inputTP, measurable, err := meter(ctx, cfg, "loudness", measureArgs(cfg, f, p, demuxer, layout))
+ if err != nil {
+ return 0, err
}
gain := gainDB(inputI, inputTP, measurable)
// engine.loudness.gain (pending Luna pass).
- cfg.Logf("codec: loudness %.2f LUFS, true peak %.2f dBTP, measurable %t; gain %.2f dB", inputI, inputTP, measurable, gain)
+ cfg.Logf("codec: loudness %.1f LUFS, true peak %.1f dBTP, measurable %t; gain %.2f dB", inputI, inputTP, measurable, gain)
return gain, nil
}
+
+// encodeAudioUnderCeiling runs audio-aac's encode with gainDB, then
+// meters audio.mp4's true peak. When that, plus meterPrecisionDB, is
+// over ceilingDBTP, it encodes once more with the gain lowered by the
+// excess plus reencodeMarginDB, still one linear gain and no
+// compression; should that one still be over, it is kept and logged,
+// never encoded a third time. It applies to every source, one given no
+// gain included: the ceiling wins (astra R6-5). It answers the gain
+// audio.mp4 was encoded with, which peaks.json must use too (Task 6:
+// measureLoudness, this, packageOutput, makePeaks).
+func encodeAudioUnderCeiling(ctx context.Context, cfg Config, p media.Payload, demuxer string, f probeFacts, gain float64) (float64, error) {
+ if err := encodeAudio(ctx, cfg, p, demuxer, f, gain); err != nil {
+ return gain, err
+ }
+ over, err := outputOverCeiling(ctx, cfg)
+ if err != nil || over <= 0 {
+ return gain, err
+ }
+ second := floorHundredth(gain - over - reencodeMarginDB)
+ // engine.loudness.over_ceiling (pending Luna pass).
+ cfg.Logf("codec: audio.mp4 peaks %.2f dB over the %.1f dBTP ceiling; encoding again at %.2f dB", over, ceilingDBTP, second)
+ if err := os.Remove(outPath(cfg, audioNames[0])); err != nil && !errors.Is(err, fs.ErrNotExist) {
+ return gain, packageFailed(cfg, audioNames[0], err)
+ }
+ if err := encodeAudio(ctx, cfg, p, demuxer, f, second); err != nil {
+ return second, err
+ }
+ if over, err = outputOverCeiling(ctx, cfg); err != nil {
+ return second, err
+ }
+ if over > 0 {
+ // engine.loudness.still_over (pending Luna pass).
+ cfg.Logf("codec: audio.mp4 still peaks %.2f dB over the ceiling after the second encode; kept", over)
+ }
+ return second, nil
+}
+
+// outputOverCeiling meters audio.mp4 and answers how far its true peak,
+// plus meterPrecisionDB, is over ceilingDBTP (0 or less: not over; a
+// silent file's -inf is not over).
+func outputOverCeiling(ctx context.Context, cfg Config) (float64, error) {
+ _, tp, _, err := meter(ctx, cfg, "output meter", outputMeterArgs(cfg))
+ if err != nil {
+ return 0, err
+ }
+ return tp + meterPrecisionDB - ceilingDBTP, nil
+}
diff --git a/internal/mediahandler/loudness_linux_test.go b/internal/mediahandler/loudness_linux_test.go
index 71dec637c..2a8b48e22 100644
--- a/internal/mediahandler/loudness_linux_test.go
+++ b/internal/mediahandler/loudness_linux_test.go
@@ -26,17 +26,13 @@ const fakeTags = "Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '/scratch/in/source':\
" title : TITLE-SECRET-7\n location : +48.8584+002.2945/\n"
func init() {
- report := func(i, tp string) string {
- return "[Parsed_loudnorm_1 @ 0x7f00] \n{\n\t\"input_i\" : \"" + i + "\",\n\t\"input_tp\" : \"" + tp + "\",\n\t\"input_lra\" : \"0.00\"\n}\n" +
- "[out#0/null @ 0x5600] video:0KiB audio:2250KiB\nsize=N/A time=00:00:03.00 bitrate=N/A\n"
- }
- // loudnorm-<case> print the tags, then (or not) a report, as the
- // loudness pass does, and exit 0, or 1 for -fails.
+ // meter-<case> print the tags, then (or not) an ebur128 summary, as
+ // the loudness pass does, and exit 0, or 1 for -fails.
for name, stderr := range map[string]string{
- "loudnorm-ceiling": fakeTags + report("-30.00", "-3.00"),
- "loudnorm-silence": fakeTags + report("-inf", "-inf"),
- "loudnorm-none": fakeTags + "[out#0/null @ 0x5600] Output file is empty\n",
- "loudnorm-fails": fakeTags + "[aist#0:0/aac @ 0x5600] Error while decoding stream: TITLE-SECRET-7\n",
+ "meter-ceiling": fakeTags + summary("-30.0", "-3.0"),
+ "meter-silence": fakeTags + summary("-70.0", "-inf"),
+ "meter-none": fakeTags + "[out#0/null @ 0x5600] Output file is empty\n",
+ "meter-fails": fakeTags + "[aist#0:0/aac @ 0x5600] Error while decoding stream: TITLE-SECRET-7\n",
} {
fakeScenarios[name] = func([]string) int {
fmt.Fprint(os.Stderr, stderr)
@@ -46,6 +42,30 @@ func init() {
return 0
}
}
+ // ceiling-<case> encode as "encode" does (one byte to the output,
+ // which must not exist) and answer the n-th output meter run with
+ // the n-th true peak, or no summary past the list.
+ for name, peaks := range map[string][]string{
+ "ceiling-under": {"-1.6"},
+ "ceiling-edge": {"-1.5", "-2.0"},
+ "ceiling-over": {"-1.1", "-1.9"},
+ "ceiling-still": {"-1.0", "-1.2"},
+ "ceiling-silent": {"-inf"},
+ "ceiling-nosummary": nil,
+ } {
+ fakeScenarios[name] = func(args []string) int {
+ if !slices.Contains(args, "null") {
+ return fakeWriteOutput(args)
+ }
+ n := fakeMeterRuns()
+ if n < 1 || n > len(peaks) {
+ fmt.Fprintln(os.Stderr, "[out#0/null @ 0x5600] no summary")
+ return 0
+ }
+ fmt.Fprint(os.Stderr, summary("-20.0", peaks[n-1]))
+ return 0
+ }
+ }
// peaks writes fakePeakSamples to its last argument, the raw file,
// which must not exist (ffmpeg without -y).
fakeScenarios["peaks"] = func(args []string) int {
@@ -102,6 +122,22 @@ func fakePeakSamples() []int16 {
return s
}
+// fakeMeterRuns counts the recorded runs into the null muxer, this
+// one included (runFake records before it runs the scenario).
+func fakeMeterRuns() int {
+ b, err := os.ReadFile(os.Getenv(fakeRecordEnv))
+ if err != nil {
+ return 0
+ }
+ n := 0
+ for _, line := range strings.Split(string(b), "\n") {
+ if strings.Contains(line, `"null"`) {
+ n++
+ }
+ }
+ return n
+}
+
// audioJob is an audio-aac payload and facts for the fakes.
func audioJob(channels int) (media.Payload, probeFacts) {
p := media.Payload{Preset: media.PresetAudioAAC, Limits: limitsFor(media.PresetAudioAAC)}
@@ -109,10 +145,11 @@ func audioJob(channels int) (media.Payload, probeFacts) {
}
// TestMeasureLoudnessOutcomes: one run of measureArgs; the gain from
-// its report (I -30, TP -3: min(14, 1) = +1); no gain for silence; no
-// report, or a failed run, is unreadable; SIGKILL is engine_failed; a
-// stopping task is its context's error. Whatever happens, nothing of
-// the run's stderr, which holds the source's tags, is logged (F19).
+// its summary (I -30, TP -3: min(14, -2 - -2.95 = 0.95) = +0.95); no
+// gain for silence; no summary, or a failed run, is unreadable;
+// SIGKILL is engine_failed; a stopping task is its context's error.
+// Whatever happens, nothing of the run's stderr, which holds the
+// source's tags, is logged (F19).
func TestMeasureLoudnessOutcomes(t *testing.T) {
for _, c := range []struct {
scenario string
@@ -120,15 +157,15 @@ func TestMeasureLoudnessOutcomes(t *testing.T) {
want string
gain float64
}{
- {"loudnorm-ceiling", 2, "nil", 1},
- {"loudnorm-ceiling", 1, "nil", 1},
- {"loudnorm-ceiling", 0, "nil", 1},
- {"loudnorm-silence", 2, "nil", 0},
- {"loudnorm-none", 2, media.CodeUnreadable, 0},
- {"loudnorm-fails", 2, media.CodeUnreadable, 0},
+ {"meter-ceiling", 2, "nil", 0.95},
+ {"meter-ceiling", 1, "nil", 0.95},
+ {"meter-ceiling", 0, "nil", 0.95},
+ {"meter-silence", 2, "nil", 0},
+ {"meter-none", 2, media.CodeUnreadable, 0},
+ {"meter-fails", 2, media.CodeUnreadable, 0},
// No channel count the probe answers is divided by: a run that
// cannot decode is unreadable like any other.
- {"loudnorm-fails", 0, media.CodeUnreadable, 0},
+ {"meter-fails", 0, media.CodeUnreadable, 0},
{"die-sigsegv", 2, media.CodeUnreadable, 0},
{"die-sigkill", 2, media.CodeEngineFailed, 0},
} {
@@ -163,6 +200,65 @@ func TestMeasureLoudnessOutcomes(t *testing.T) {
}
}
+// TestEncodeAudioUnderCeiling: the encode, then the output meter; when
+// the true peak plus 0.05 is over -1.5 dBTP, audio.mp4 is removed and
+// encoded once more with the gain lowered by the excess plus 0.3, and
+// metered again; a second overshoot is kept and logged, never a third
+// encode. Each expected gain is worked out beside it, from a first
+// gain of +1 (or 0).
+func TestEncodeAudioUnderCeiling(t *testing.T) {
+ for _, c := range []struct {
+ scenario string
+ gain, final float64
+ runs int
+ want, log string
+ }{
+ // -1.6 + 0.05 = -1.55: not over.
+ {"ceiling-under", 1, 1, 2, "nil", ""},
+ // -1.5 + 0.05 = -1.45: 0.05 over; 1 - 0.05 - 0.3 = 0.65.
+ {"ceiling-edge", 1, 0.65, 4, "nil", "encoding again at 0.65 dB"},
+ // -1.1 + 0.05 = -1.05: 0.45 over; 1 - 0.45 - 0.3 = 0.25.
+ {"ceiling-over", 1, 0.25, 4, "nil", "encoding again at 0.25 dB"},
+ // A source given no gain is held to the ceiling too:
+ // 0 - 0.45 - 0.3 = -0.75.
+ {"ceiling-over", 0, -0.75, 4, "nil", "encoding again at -0.75 dB"},
+ // -1.0: 0.55 over, 1 - 0.85 = 0.15; then -1.2: still 0.35 over,
+ // kept.
+ {"ceiling-still", 1, 0.15, 4, "nil", "still peaks 0.35 dB over"},
+ // Silence is never over.
+ {"ceiling-silent", 1, 1, 2, "nil", ""},
+ {"ceiling-nosummary", 1, 1, 2, media.CodeUnreadable, "gave no measurement"},
+ {"fail", 1, 1, 1, media.CodeUnreadable, "ffmpeg (audio) failed"},
+ } {
+ name := fmt.Sprintf("%s at %v dB", c.scenario, c.gain)
+ cfg, record := fakeConfig(t, c.scenario)
+ var logs []string
+ cfg.Logf = func(format string, args ...any) { logs = append(logs, fmt.Sprintf(format, args...)) }
+ p, f := audioJob(2)
+ final, err := encodeAudioUnderCeiling(context.Background(), cfg, p, "mov", f, c.gain)
+ if codeOf(err) != c.want || (err == nil && final != c.final) {
+ t.Errorf("%s: %v, %s; want %v, %s", name, final, codeOf(err), c.final, c.want)
+ }
+ runs := fakeRuns(t, record)
+ if len(runs) != c.runs {
+ t.Fatalf("%s: %d runs, want %d", name, len(runs), c.runs)
+ }
+ want := [][]string{audioArgs(cfg, f, p, "mov", c.gain), outputMeterArgs(cfg), audioArgs(cfg, f, p, "mov", c.final), outputMeterArgs(cfg)}
+ for i, r := range runs {
+ if !slices.Equal(r.Args, want[i]) {
+ t.Errorf("%s: run %d:\n got %q\nwant %q", name, i, r.Args, want[i])
+ }
+ }
+ all := strings.Join(logs, "\n")
+ if c.log == "" && strings.Contains(all, "ceiling") {
+ t.Errorf("%s: logged %q", name, logs)
+ }
+ if c.log != "" && !strings.Contains(all, c.log) {
+ t.Errorf("%s: logged %q, want %q", name, logs, c.log)
+ }
+ }
+}
+
// TestMakePeaks: one run of peaksArgs with the gain; peaks.json is
// writePeaks of computePeaks over what it wrote, for the duration
// given; peaks.raw is gone after. A stale peaks.raw is removed first. A
@@ -242,8 +338,8 @@ func TestMakePeaks(t *testing.T) {
// commands and the binary.
// loudnessSources are aevalsrc expressions at 48 kHz, with what
-// Debian's 7.1.5 loudnorm measures for each and the gain that follows:
-// min(-16 - I, -2 - TP).
+// Debian's 7.1.5 meter (ebur128, one decimal) measures for each and the
+// gain that follows: min(-16 - I, -2 - (TP + 0.05)).
var loudnessSources = []struct {
name, expr string
layout string // "" for aevalsrc's mono
@@ -252,22 +348,46 @@ var loudnessSources = []struct {
gain float64
wins string
}{
- // A quiet tone, 20 s, with a loud 50 ms burst at 3 s: I -31.51, TP
- // -2.86: min(15.51, 0.86) = +0.86, ending about -30.7 LUFS with its
- // peak at -2 dBTP: the ceiling wins.
- {"peaky", "0.02*sin(2*PI*440*t)+if(between(t\\,3\\,3.05)\\,0.7*sin(2*PI*1000*t)\\,0)", "", 20, -31.51, -2.86, 0.86, "ceiling"},
- // A quiet steady tone: I -29.75, TP -26.02: min(13.75, 24.02) = +13.75.
- {"quiet", "0.05*sin(2*PI*440*t)", "", 6, -29.75, -26.02, 13.75, "target"},
+ // A quiet tone, 20 s, with a loud 50 ms burst at 3 s: I -31.0, TP
+ // -2.9: min(15.0, -2 - -2.85 = 0.85) = +0.85, ending about -30 LUFS
+ // with its peak near -2 dBTP: the ceiling wins.
+ {"peaky", "0.02*sin(2*PI*440*t)+if(between(t\\,3\\,3.05)\\,0.7*sin(2*PI*1000*t)\\,0)", "", 20, -31, -2.9, 0.85, "ceiling"},
+ // The same in 6 s, where the tone falls under BS.1770's relative
+ // gate and only the burst counts: I -15.1, TP -2.9:
+ // min(-0.9, 0.85) = -0.9. loudnorm measured -28.01 here and the
+ // output came out at -14.3 LUFS (fix 1).
+ {"peaky-6s", "0.02*sin(2*PI*440*t)+if(between(t\\,3\\,3.05)\\,0.7*sin(2*PI*1000*t)\\,0)", "", 6, -15.1, -2.9, -0.9, "target"},
+ // The reviewer's "b18": the tone with a 1 s burst at 0.18 over
+ // 10 s: I -19.0, TP -14.0: min(3.0, 11.95) = +3.
+ {"b18", "0.02*sin(2*PI*440*t)+if(between(t\\,4\\,5)\\,0.18*sin(2*PI*1000*t)\\,0)", "", 10, -19, -14, 3, "target"},
+ // A quiet steady tone: I -29.7, TP -26.0: min(13.7, 23.95) = +13.7.
+ {"quiet", "0.05*sin(2*PI*440*t)", "", 6, -29.7, -26, 13.7, "target"},
// The same in stereo, one channel in antiphase (a mono mix of it
- // would cancel; the stereo layout is measured): I -26.75, TP
- // -26.02: min(10.75, 24.02) = +10.75.
- {"quiet-stereo", "0.05*sin(2*PI*440*t)|-0.05*sin(2*PI*440*t)", "stereo", 6, -26.75, -26.02, 10.75, "target"},
- // A hot tone: I -4.15, TP -0.45: min(-11.85, -1.55) = -11.85.
- {"hot", "0.95*sin(2*PI*440*t)", "", 6, -4.15, -0.45, -11.85, "target"},
- // Under the gate: -inf, TP -79.99: no gain.
- {"under-the-gate", "0.0001*sin(2*PI*440*t)", "", 6, math.Inf(-1), -79.99, 0, "none"},
- // Silence: -inf, -inf: no gain.
- {"silence", "0", "", 6, math.Inf(-1), math.Inf(-1), 0, "none"},
+ // would cancel; the stereo layout is measured): I -26.7, TP -26.0:
+ // min(10.7, 23.95) = +10.7.
+ {"quiet-stereo", "0.05*sin(2*PI*440*t)|-0.05*sin(2*PI*440*t)", "stereo", 6, -26.7, -26, 10.7, "target"},
+ // A hot tone: I -4.1, TP -0.4: min(-11.9, -1.65) = -11.9.
+ {"hot", "0.95*sin(2*PI*440*t)", "", 6, -4.1, -0.4, -11.9, "target"},
+ // 50 ms noise bursts every 0.5 s: I -16.7, TP -0.9: min(0.7, -1.15)
+ // = -1.15. The AAC encode overshoots its -2 dBTP aim to about -1.1,
+ // so it is encoded again, lower (fix 1's ruling).
+ {"noise-bursts", "0.02*sin(2*PI*440*t)+if(lt(mod(t\\,0.5)\\,0.05)\\,0.5*(2*random(0)-1)\\,0)", "", 6, -16.7, -0.9, -1.15, "ceiling, encoded again"},
+ // Under the gate: -70.0, TP -80.0: no gain.
+ {"under-the-gate", "0.0001*sin(2*PI*440*t)", "", 6, -70, -80, 0, "none"},
+ // Silence: -70.0, -inf: no gain.
+ {"silence", "0", "", 6, -70, math.Inf(-1), 0, "none"},
+}
+
+// loudnessSource is the loudnessSources row named name.
+func loudnessSource(t *testing.T, name string) int {
+ t.Helper()
+ for i, s := range loudnessSources {
+ if s.name == name {
+ return i
+ }
+ }
+ t.Fatalf("no source %s", name)
+ return -1
}
// makeAudioSource writes a FLAC of expr, seconds long (and tags,
@@ -280,11 +400,17 @@ func makeAudioSource(t *testing.T, cfg Config, expr, layout string, seconds int,
if layout != "" {
src += ":c=" + layout
}
- args := []string{"-hide_banner", "-loglevel", "error", "-nostdin", "-f", "lavfi", "-i", src}
+ args := []string{"-f", "lavfi", "-i", src}
for _, tag := range tags {
args = append(args, "-metadata", tag)
}
- args = append(args, "-c:a", "flac", "-f", "flac", sourcePath(cfg))
+ runFFmpegArgs(t, cfg, append(args, "-c:a", "flac", "-f", "flac", sourcePath(cfg))...)
+}
+
+// runFFmpegArgs runs the real ffmpeg with args, unsplit, quietly.
+func runFFmpegArgs(t *testing.T, cfg Config, args ...string) {
+ t.Helper()
+ args = append([]string{"-hide_banner", "-loglevel", "error", "-nostdin", "-y"}, args...)
cmd := exec.Command(cfg.FFmpeg, args...)
var stderr bytes.Buffer
cmd.Stderr = &stderr
@@ -293,11 +419,11 @@ func makeAudioSource(t *testing.T, cfg Config, expr, layout string, seconds int,
}
}
-// forgedTags are a title and a comment whose lines forge a loudnorm
-// report of I -5, TP -60 (gain min(-11, 58) = -11, were it taken).
+// forgedTags are a title and a comment whose lines forge an ebur128
+// summary of I -5, TP -60 (gain min(-11, 57.95) = -11, were it taken).
var forgedTags = []string{
"title=TITLE-SECRET-7",
- "comment=x\n[Parsed_loudnorm_9 @ 0x1] \n{\n\t\"input_i\" : \"-5.00\",\n\t\"input_tp\" : \"-60.00\"\n}\n",
+ "comment=x\n[Parsed_ebur128_9 @ 0x1] Summary:\n\n Integrated loudness:\n I: -5.0 LUFS\n\n True peak:\n Peak: -60.0 dBFS\n",
}
// audioPayload is an audio-aac payload with the class's limits.
@@ -314,10 +440,10 @@ func TestRegenerateLoudnormFixtures(t *testing.T) {
t.Skipf("set %s=1 to rewrite testdata/loudnorm", regenEnv)
}
cfg := realConfig(t)
- for file, src := range map[string]int{"peaky-forged-tags.stderr": 0, "silence.stderr": 5} {
- s := loudnessSources[src]
+ for file, name := range map[string]string{"peaky-forged-tags.stderr": "peaky", "silence.stderr": "silence"} {
+ s := loudnessSources[loudnessSource(t, name)]
var tags []string
- if src == 0 {
+ if name == "peaky" {
tags = forgedTags
}
makeAudioSource(t, cfg, s.expr, s.layout, s.seconds, tags...)
@@ -338,8 +464,9 @@ func TestRegenerateLoudnormFixtures(t *testing.T) {
}
}
-// ebur128 measures path's audio independently of loudnorm: integrated
-// loudness and true peak, from ebur128's summary.
+// ebur128 measures path's audio with ffmpeg's ebur128 directly, not
+// through the handler: integrated loudness and true peak, from its
+// summary.
func ebur128(t *testing.T, cfg Config, path string) (i, tp float64) {
t.Helper()
out := ffmpegInfo(t, cfg, "-i", path, "-map", "0:a", "-af", "ebur128=peak=true", "-f", "null", "-")
@@ -353,15 +480,14 @@ func ebur128(t *testing.T, cfg Config, path string) (i, tp float64) {
return field("I"), field("Peak")
}
-// TestRealLoudness: for each source, the real loudness pass measures
-// what the table says (and what ebur128 measures, within 0.6: the two
-// meters differ by up to 0.5 LU on the burst), the
-// gain is the table's (the arithmetic is worked beside each row), and
-// the encoded audio.mp4 either measures -16 LUFS within 0.5 LU, or is
-// quieter with its true peak within 0.5 dB under the ceiling's -2 dBTP
-// target; none is over -1.5 dBTP (spec §9). Silence stays silent. A
-// forged report in the tags is not taken, and nothing is logged but
-// the measurement.
+// TestRealLoudness: for each source, the gain is the table's (the
+// arithmetic is worked beside each row, from what the meter measures),
+// and audio.mp4, after encodeAudioUnderCeiling, either measures -16
+// LUFS within 0.5 LU, or is quieter with its true peak near the
+// ceiling; none is over -1.5 dBTP (spec §9). Silence stays silent. A
+// forged summary in the tags is not taken, and nothing is logged but
+// the measurement (and, for the source the encode overshoots, the
+// second encode).
func TestRealLoudness(t *testing.T) {
cfg := realConfig(t)
for _, s := range loudnessSources {
@@ -391,32 +517,34 @@ func TestRealLoudness(t *testing.T) {
if want := gainDB(s.i, s.tp, isMeasurable(s.i, s.tp)); want != s.gain {
t.Errorf("table: gainDB(%v, %v) = %v, not %v", s.i, s.tp, want, s.gain)
}
- if s.wins != "none" {
- ei, etp := ebur128(t, cfg, sourcePath(cfg))
- if math.Abs(ei-s.i) > 0.6 || math.Abs(etp-s.tp) > 0.2 {
- t.Errorf("ebur128 measures I %v TP %v; loudnorm's table %v %v", ei, etp, s.i, s.tp)
- }
+ if want := fmt.Sprintf("codec: loudness %.1f LUFS, true peak %.1f dBTP", s.i, s.tp); len(logs) != 1 || !strings.HasPrefix(logs[0], want) {
+ t.Errorf("logged %q, want %q", logs, want)
+ }
+
+ final, err := encodeAudioUnderCeiling(context.Background(), cfg, p, "flac", f, gain)
+ if err != nil {
+ t.Fatal(err)
}
all := strings.Join(logs, "\n")
- if strings.Contains(all, "SECRET") || strings.Contains(all, "Parsed_loudnorm_9") || len(logs) != 1 {
+ if strings.Contains(all, "SECRET") || strings.Contains(all, "Parsed_ebur128_9") {
t.Errorf("logged %q", logs)
}
-
- if err := encodeAudio(context.Background(), cfg, p, "flac", f, gain); err != nil {
- t.Fatal(err)
+ again := strings.HasSuffix(s.wins, "encoded again")
+ if again != (final != gain) || again != strings.Contains(all, "encoding again") || strings.Contains(all, "still peaks") {
+ t.Errorf("gain %v, then %v: logged %q", gain, final, logs)
}
oi, otp := ebur128(t, cfg, outPath(cfg, "audio.mp4"))
- t.Logf("output: I %.1f LUFS, true peak %.1f dBTP", oi, otp)
- switch s.wins {
- case "target":
+ t.Logf("output: I %.1f LUFS, true peak %.1f dBTP, gain %.2f dB", oi, otp, final)
+ switch {
+ case s.wins == "target":
if math.Abs(oi-targetLUFS) > 0.5 || otp > ceilingDBTP {
t.Errorf("output I %v TP %v, want -16 LUFS under -1.5 dBTP", oi, otp)
}
- case "ceiling":
- if oi >= targetLUFS || otp > ceilingDBTP || otp < ceilingDBTP-codecHeadroomDB-0.5 {
- t.Errorf("output I %v TP %v, want under -16 LUFS with its peak at the ceiling", oi, otp)
+ case strings.HasPrefix(s.wins, "ceiling"):
+ if oi >= targetLUFS || otp > ceilingDBTP || otp < ceilingDBTP-codecHeadroomDB-reencodeMarginDB-1 {
+ t.Errorf("output I %v TP %v, want under -16 LUFS with its peak near the ceiling", oi, otp)
}
- case "none":
+ case s.wins == "none":
// No gain: as quiet as the source, give or take the AAC
// quantisation at -80 dBFS (about 1 dB).
if oi > gateLUFS || otp > s.tp+1.5 {
@@ -425,7 +553,7 @@ func TestRealLoudness(t *testing.T) {
}
durationMS := int64(s.seconds) * 1000
- if err := makePeaks(context.Background(), cfg, p, "flac", f, gain, durationMS); err != nil {
+ if err := makePeaks(context.Background(), cfg, p, "flac", f, final, durationMS); err != nil {
t.Fatal(err)
}
b, err := os.ReadFile(outPath(cfg, "peaks.json"))
@@ -440,14 +568,15 @@ func TestRealLoudness(t *testing.T) {
if err := json.Unmarshal(b, &pj); err != nil || pj.Version != 1 || pj.DurationMS != durationMS || len(pj.Peaks) != 1000 {
t.Fatalf("peaks.json %.100s: %v", b, err)
}
- checkRealPeaks(t, s.name, gain, pj.Peaks)
+ checkRealPeaks(t, s.name, final, pj.Peaks)
})
}
}
// checkRealPeaks holds a source's peaks to what its expression and gain
// give: amplitude a after the gain is a·10^(gain/20)·255 (the mono mix
-// of antiphase stereo cancels).
+// of antiphase stereo cancels). A burst of 1 kHz sampled at 8 kHz may
+// peak up to 8% under its amplitude.
func checkRealPeaks(t *testing.T, name string, gain float64, peaks []uint8) {
t.Helper()
level := func(a float64) float64 { return a * math.Pow(10, gain/20) * 255 }
@@ -456,22 +585,39 @@ func checkRealPeaks(t *testing.T, name string, gain float64, peaks []uint8) {
t.Errorf("%s: %s peak %d, want %.1f", name, what, got, want)
}
}
- switch name {
- case "peaky":
- // The burst, 3 s to 3.05 s of 20 s, is in slices 150 to 152; the
- // rest is the tone.
+ // burst checks a tone at 0.02 with a burst at 0.7 or 0.18 added in
+ // slices [from, to], two slices either side left out.
+ burst := func(a float64, from, to int) {
for i, v := range peaks {
- if i >= 150 && i <= 152 {
- near(fmt.Sprintf("burst slice %d", i), v, level(0.7), 8)
- } else if i > 2 && (i < 148 || i > 154) {
+ switch {
+ case i >= from && i <= to:
+ near(fmt.Sprintf("burst slice %d", i), v, level(a+0.02)*0.96, level(a+0.02)*0.05+1)
+ case i > 2 && (i < from-2 || i > to+2):
near(fmt.Sprintf("slice %d", i), v, level(0.02), 1)
}
}
+ }
+ switch name {
+ case "peaky": // 3 s to 3.05 s of 20 s
+ burst(0.7, 150, 152)
+ case "peaky-6s": // 3 s to 3.05 s of 6 s
+ burst(0.7, 500, 508)
+ case "b18": // 4 s to 5 s of 10 s
+ burst(0.18, 400, 499)
case "quiet", "hot":
a := map[string]float64{"quiet": 0.05, "hot": 0.95}[name]
for i, v := range peaks[2:998] {
near(fmt.Sprintf("slice %d", i+2), v, level(a), 2)
}
+ case "noise-bursts":
+ // A burst starts every 0.5 s, slice k·1000/12, and lasts 8
+ // slices; each is far over the tone's level(0.02), about 4 (the
+ // 8 kHz mix keeps under half of the noise's peak).
+ for k := range 12 {
+ if i := k*1000/12 + 2; peaks[i] < 5*uint8(level(0.02)) {
+ t.Errorf("%s: burst slice %d peak %d", name, k*1000/12+2, peaks[k*1000/12+2])
+ }
+ }
default: // antiphase stereo, under the gate, silence
for i, v := range peaks {
if v != 0 {
@@ -482,6 +628,60 @@ func checkRealPeaks(t *testing.T, name string, gain float64, peaks []uint8) {
}
}
+// TestRealMultichannelMeasuredAsEncoded (fix 1, Critical): a 5.1 and a
+// 7.1 source in integer PCM, s32 FLAC and s16 WAV, are measured at the
+// level they are encoded at: the loudness pass's I is what ebur128
+// measures of audio.mp4 encoded at 0 dB, within 0.2 LU, and its true
+// peak is that of the encode's own downmix (its aformat, written as
+// float PCM), within 0.1 dB. audio.mp4's true peak is not compared: on
+// these tones, with unequal channel levels, the native AAC encoder
+// itself raises it by 2.2 to 4.4 dB, which encodeAudioUnderCeiling,
+// not the measurement, answers for. Before planar float was forced on
+// both, the measure pass mixed an integer downmix, normalised, 7.66 dB
+// (5.1) or 9.95 dB (7.1) under the encode's.
+func TestRealMultichannelMeasuredAsEncoded(t *testing.T) {
+ cfg := realConfig(t)
+ pan := map[string]string{
+ "5.1": "pan=5.1|c0=c0|c1=0.8*c0|c2=0.6*c0|c3=0.4*c0|c4=0.7*c0|c5=0.5*c0",
+ "7.1": "pan=7.1|c0=c0|c1=0.8*c0|c2=0.6*c0|c3=0.4*c0|c4=0.7*c0|c5=0.5*c0|c6=0.9*c0|c7=0.3*c0",
+ }
+ for _, c := range []struct{ layout, demuxer, codec, sampleFmt, muxer string }{
+ {"5.1", "flac", "flac", "s32", "flac"},
+ {"5.1", "wav", "pcm_s16le", "s16", "wav"},
+ {"7.1", "flac", "flac", "s32", "flac"},
+ {"7.1", "wav", "pcm_s16le", "s16", "wav"},
+ } {
+ name := c.layout + " " + c.codec
+ _ = os.Remove(sourcePath(cfg))
+ _ = os.Remove(outPath(cfg, "audio.mp4"))
+ runFFmpegArgs(t, cfg, "-f", "lavfi", "-i", "aevalsrc=0.1*sin(2*PI*440*t):s=48000:d=6", "-af", pan[c.layout],
+ "-c:a", c.codec, "-sample_fmt", c.sampleFmt, "-f", c.muxer, sourcePath(cfg))
+ p := audioPayload()
+ f, err := probe(context.Background(), cfg, c.demuxer, media.PresetAudioAAC)
+ if err != nil {
+ t.Fatalf("%s: %v", name, err)
+ }
+ layout, _ := audioLayout(f)
+ mi, mtp, _, err := meter(context.Background(), cfg, "loudness", measureArgs(cfg, f, p, c.demuxer, layout))
+ if err != nil {
+ t.Fatalf("%s: %v", name, err)
+ }
+ if err := encodeAudio(context.Background(), cfg, p, c.demuxer, f, 0); err != nil {
+ t.Fatalf("%s: %v", name, err)
+ }
+ oi, otp := ebur128(t, cfg, outPath(cfg, "audio.mp4"))
+ // The encode's downmix, before the codec.
+ af := argAfter(audioArgs(cfg, f, p, c.demuxer, 0), "-af")
+ mix := filepath.Join(t.TempDir(), "mix.wav")
+ runFFmpegArgs(t, cfg, "-i", sourcePath(cfg), "-af", af, "-c:a", "pcm_f32le", "-f", "wav", mix)
+ _, dtp := ebur128(t, cfg, mix)
+ t.Logf("%s: measured I %.1f TP %.1f; downmix TP %.1f; audio.mp4 at 0 dB: I %.1f TP %.1f", name, mi, mtp, dtp, oi, otp)
+ if math.Abs(mi-oi) > 0.2 || math.Abs(mtp-dtp) > 0.1 {
+ t.Errorf("%s: measured I %v TP %v, but encoded at I %v, downmix TP %v", name, mi, mtp, oi, dtp)
+ }
+ }
+}
+
// TestRealZeroChannels: a WAV whose header says 0 channels is
// unreadable at the probe, and the loudness pass, run on it anyway,
// is unreadable too: nothing divides by the count.
diff --git a/internal/mediahandler/loudness_test.go b/internal/mediahandler/loudness_test.go
index 8739cad89..ca0a87b4e 100644
--- a/internal/mediahandler/loudness_test.go
+++ b/internal/mediahandler/loudness_test.go
@@ -1,6 +1,7 @@
package mediahandler
import (
+ "fmt"
"math"
"os"
"path/filepath"
@@ -12,13 +13,14 @@ import (
"github.com/carlosframework/platform/internal/media"
)
-// TestGainTable: the one linear gain is min(-16 - I, (-1.5 - 0.5) - TP),
-// the target's gain or the ceiling's, whichever is smaller, so the
-// ceiling wins and a quiet source with a loud moment ends below -16
-// LUFS; no gain for a source with no measurable loudness. Each expected
-// value is worked out beside it. The gain is rounded down to the
-// hundredth, so the two-decimal volume= ffmpeg is given never exceeds
-// it.
+// TestGainTable: the one linear gain is
+// min(-16 - I, (-1.5 - 0.5) - (TP + 0.05)), the target's gain or the
+// ceiling's, whichever is smaller, so the ceiling wins and a quiet
+// source with a loud moment ends below -16 LUFS; no gain for a source
+// with no measurable loudness. The 0.05 is half the meter's 0.1 unit:
+// a true peak printed -3.0 may be -2.95. Each expected value is worked
+// out beside it. The gain is rounded down to the hundredth, so the
+// two-decimal volume= ffmpeg is given never exceeds it.
func TestGainTable(t *testing.T) {
inf := math.Inf(-1)
for _, c := range []struct {
@@ -27,42 +29,47 @@ func TestGainTable(t *testing.T) {
want float64
whyWinner string
}{
- // min(-16 - -30, -2 - -3) = min(14, 1) = +1: the output is about
- // -29 LUFS with its peak at -2 dBTP, quieter than -16 because
- // the ceiling wins.
- {"quiet with a loud moment", -30, -3, 1, "ceiling"},
- // min(-16 - -20, -2 - -10) = min(4, 8) = +4: -16 LUFS, peak -6.
+ // min(-16 - -30, -2 - (-3 + 0.05)) = min(14, 0.95) = +0.95: the
+ // output is about -29 LUFS with its peak at -2 dBTP, quieter than
+ // -16 because the ceiling wins.
+ {"quiet with a loud moment", -30, -3, 0.95, "ceiling"},
+ // min(-16 - -20, -2 - -9.95) = min(4, 7.95) = +4: -16 LUFS.
{"quiet, little peak", -20, -10, 4, "target"},
- // min(-16 - -10, -2 - 0) = min(-6, -2) = -6: -16 LUFS, peak -6.
+ // min(-16 - -10, -2 - 0.05) = min(-6, -2.05) = -6: -16 LUFS.
{"too loud", -10, 0, -6, "target"},
- // min(-16 - -14, -2 - 1) = min(-2, -3) = -3: a source just over
- // the target with its peak over full scale is turned down to the
- // ceiling, and ends at -17 LUFS, under the target.
- {"loud, peak over full scale", -14, 1, -3, "ceiling"},
- // A float source clipping over full scale: min(-16 - -8, -2 - 3)
- // = min(-8, -5) = -8.
+ // min(-16 - -14, -2 - 1.05) = min(-2, -3.05) = -3.05: a source
+ // just over the target with its peak over full scale is turned
+ // down to the ceiling, and ends at -17.05 LUFS.
+ {"loud, peak over full scale", -14, 1, -3.05, "ceiling"},
+ // A float source clipping over full scale: min(-16 - -8,
+ // -2 - 3.05) = min(-8, -5.05) = -8.
{"over full scale", -8, 3, -8, "target"},
- // Exactly at the target, peak at the ceiling: no change.
- {"already right", -16, -2, 0, "both"},
- // The quietest measurable: min(-16 - -70, -2 - -60) = min(54, 58)
- // = +54.
- {"at the gate", -70, -60, 54, "target"},
+ // At the target, peak under the ceiling: min(0, -2 - -2.05) =
+ // min(0, 0.05) = 0.
+ {"already right", -16, -2.1, 0, "target"},
+ // The quietest measurable: min(-16 - -69.9, -2 - -59.95) =
+ // min(53.9, 57.95) = +53.9.
+ {"just over the gate", -69.9, -60, 53.9, "target"},
// Fractions are rounded down to the hundredth:
- // min(-16 - -29.37, -2 - -3.333) = min(13.37, 1.333) = 1.33;
- {"rounded down", -29.37, -3.333, 1.33, "ceiling"},
- // min(13.37, -2 - -2.996 = 0.996) = 0.99, not the nearest 1.00,
+ // min(-16 - -29.37, -2 - -3.283) = min(13.37, 1.283) = 1.28;
+ {"rounded down", -29.37, -3.333, 1.28, "ceiling"},
+ // min(13.37, -2 - -2.896 = 0.896) = 0.89, not the nearest 0.90,
// which would be 0.004 dB over the ceiling;
- {"never rounded up", -29.37, -2.996, 0.99, "ceiling"},
- // min(-16 - -10.004, -2 - -1) = min(-5.996, -1) = -6.00 (down).
+ {"never rounded up", -29.37, -2.946, 0.89, "ceiling"},
+ // min(-16 - -10.004, -2 - -0.95) = min(-5.996, -1.05) = -6.00
+ // (down).
{"negative rounded down", -10.004, -1, -6, "target"},
- // Loudness given exactly in hundredths, as loudnorm reports it, is
- // not lost to the float error of the subtraction:
- // min(-16 - -69.99, -2 - -60) = min(53.99, 58) = 53.99, where
- // float gives 53.989999999999995, which a bare floor makes 53.98.
- {"hundredths kept", -69.99, -60, 53.99, "target"},
+ // The meter's one-decimal values are not lost to the float error
+ // of the subtraction: min(-16 - -69.6, -2 - -59.95) =
+ // min(53.6, 57.95) = 53.6, where float gives 53.599999999999994,
+ // which a bare floor makes 53.59.
+ {"hundredths kept", -69.6, -60, 53.6, "target"},
+ // -2 - (-3.3 + 0.05) is 1.2499999999999996 in float: 1.25.
+ {"tenths plus the half unit kept", -20, -3.3, 1.25, "ceiling"},
// Not measurable: no gain.
- {"silence", inf, inf, 0, "none"},
- {"below the gate, peak heard", inf, -77.96, 0, "none"},
+ {"silence", -70, inf, 0, "none"},
+ {"at the gate", -70, -60, 0, "none"},
+ {"below the gate, peak heard", inf, -77.9, 0, "none"},
{"under -70", -75, -60, 0, "none"},
{"a peak that is not a number", -20, math.NaN(), 0, "none"},
{"no peak", -20, inf, 0, "none"},
@@ -75,7 +82,7 @@ func TestGainTable(t *testing.T) {
}
// The volume= argument never asks for more than the exact gain.
if c.whyWinner != "none" {
- exact := min(targetLUFS-c.i, ceilingDBTP-codecHeadroomDB-c.tp)
+ exact := min(targetLUFS-c.i, ceilingDBTP-codecHeadroomDB-(c.tp+meterPrecisionDB))
arg := strings.TrimSuffix(strings.TrimPrefix(volumeFilter(got), "volume="), "dB")
v, err := strconv.ParseFloat(arg, 64)
if err != nil || v > exact+1e-9 {
@@ -83,25 +90,26 @@ func TestGainTable(t *testing.T) {
}
}
}
- // The constants themselves (spec §5.1; the headroom is the spike's).
- if targetLUFS != -16 || ceilingDBTP != -1.5 || codecHeadroomDB != 0.5 {
- t.Errorf("constants %v %v %v", targetLUFS, ceilingDBTP, codecHeadroomDB)
+ // The constants themselves (spec §5.1; the headroom is the spike's;
+ // half the meter's unit; fix 1's margin).
+ if targetLUFS != -16 || ceilingDBTP != -1.5 || codecHeadroomDB != 0.5 || meterPrecisionDB != 0.05 || reencodeMarginDB != 0.3 {
+ t.Errorf("constants %v %v %v %v %v", targetLUFS, ceilingDBTP, codecHeadroomDB, meterPrecisionDB, reencodeMarginDB)
}
// measurable false is no gain whatever the numbers.
if g := gainDB(-30, -3, false); g != 0 {
t.Errorf("not measurable: %v", g)
}
// A measurable flag set on numbers that are not is still no gain.
- for _, c := range [][2]float64{{math.Inf(-1), -3}, {-30, math.NaN()}, {-75, -3}} {
+ for _, c := range [][2]float64{{math.Inf(-1), -3}, {-30, math.NaN()}, {-75, -3}, {-70, -3}} {
if g := gainDB(c[0], c[1], true); g != 0 {
t.Errorf("I %v TP %v forced measurable: %v", c[0], c[1], g)
}
}
}
-// loudnormFixture reads testdata/loudnorm/<name>, the real ffmpeg's
+// meterFixture reads testdata/loudnorm/<name>, the real ffmpeg's
// stderr from the loudness pass (provenance.txt).
-func loudnormFixture(t *testing.T, name string) []byte {
+func meterFixture(t *testing.T, name string) []byte {
t.Helper()
b, err := os.ReadFile(filepath.Join("testdata", "loudnorm", name))
if err != nil {
@@ -110,85 +118,95 @@ func loudnormFixture(t *testing.T, name string) []byte {
return b
}
-// TestParseLoudnormTail: the measurement is the JSON object after the
-// last line that begins with loudnorm's log prefix. The fixture is the
-// real ffmpeg's whole stderr for a source whose tags hold a forged
-// loudnorm block: ffmpeg prints tags indented, so the forgery is not
-// taken. A truncated block, no block, a block missing a field or with a
-// value that is not a number is an error; -inf is not measurable.
-func TestParseLoudnormTail(t *testing.T) {
- real := loudnormFixture(t, "peaky-forged-tags.stderr")
- if !strings.Contains(string(real), `"input_i" : "-5.00"`) {
- t.Fatal("the fixture lost its forged block")
+// summary is an ebur128 summary as the real one is laid out, with I and
+// the true peak given, after a line of noise and before the muxer's
+// lines.
+func summary(i, tp string) string {
+ return "noise before\n[Parsed_ebur128_1 @ 0x7f00] Summary:\n\n Integrated loudness:\n I: " + i +
+ " LUFS\n Threshold: -30.0 LUFS\n\n Loudness range:\n LRA: 0.0 LU\n Threshold: -40.0 LUFS\n" +
+ " LRA low: -20.0 LUFS\n LRA high: -20.0 LUFS\n\n True peak:\n Peak: " + tp +
+ " dBFS\n[out#0/null @ 0x5600] video:0KiB audio:2250KiB\nsize=N/A time=00:00:03.00\n"
+}
+
+// TestParseMeterTail: the measurement is the summary after the last
+// line that begins with ebur128's log prefix. The fixture is the real
+// ffmpeg's whole stderr for a source whose tags hold a forged summary:
+// ffmpeg prints tags indented, so the forgery is not taken. A truncated
+// summary, none, one missing I or the true peak, or with a value that
+// is not a number is an error; I at the gate or a -inf peak is not
+// measurable.
+func TestParseMeterTail(t *testing.T) {
+ real := meterFixture(t, "peaky-forged-tags.stderr")
+ if !strings.Contains(string(real), "I: -5.0 LUFS") {
+ t.Fatal("the fixture lost its forged summary")
}
- i, tp, ok, err := parseLoudnorm(real)
+ i, tp, ok, err := parseMeter(real)
if err != nil || !ok {
t.Fatalf("real tail: %v %v", ok, err)
}
- // The real block (provenance.txt), not the forged -5.00/-60.00.
- if i != -31.51 || tp != -2.86 {
+ // The real summary (provenance.txt), not the forged -5.0/-60.0.
+ if i != -31 || tp != -2.9 {
t.Errorf("real tail: I %v TP %v", i, tp)
}
- // Cut anywhere before the block's start, as runChild's 64 KiB tail
+ // Cut anywhere before the summary's start, as runChild's 64 KiB tail
// may cut a long input dump, it parses the same.
- start := strings.LastIndex(string(real), "[Parsed_loudnorm_")
+ start := strings.LastIndex(string(real), "[Parsed_ebur128_")
for _, cut := range []int{1, 100, start - 1} {
- if gi, gtp, _, err := parseLoudnorm(real[cut:]); err != nil || gi != i || gtp != tp {
+ if gi, gtp, _, err := parseMeter(real[cut:]); err != nil || gi != i || gtp != tp {
t.Errorf("cut at %d: %v %v %v", cut, gi, gtp, err)
}
}
- // Cut exactly at the block's prefix: the first byte is not a line's
- // start, so an error.
- if _, _, _, err := parseLoudnorm(real[start:]); err == nil {
+ // Cut exactly at the summary's prefix: the first byte is not a
+ // line's start, so an error.
+ if _, _, _, err := parseMeter(real[start:]); err == nil {
t.Error("a tail starting at the prefix: no error")
}
- // Truncated inside the block: an error, never the forged block.
- end := strings.LastIndex(string(real), "}")
- for _, cut := range []int{end, end - 20, start + 40} {
- if _, _, _, err := parseLoudnorm(real[:cut]); err == nil {
+ // Truncated before the true peak: an error, never the forged one.
+ peak := strings.LastIndex(string(real), " Peak:")
+ for _, cut := range []int{peak, peak - 20, start + 40} {
+ if _, _, _, err := parseMeter(real[:cut]); err == nil {
t.Errorf("truncated at %d: no error", cut)
}
}
- // The forged block alone (loudnorm printed nothing): an error.
- if _, _, _, err := parseLoudnorm(real[:start]); err == nil {
- t.Error("only the forged, indented block: no error")
+ // The forged summary alone (ebur128 printed nothing): an error.
+ if _, _, _, err := parseMeter(real[:start]); err == nil {
+ t.Error("only the forged, indented summary: no error")
}
- silence := loudnormFixture(t, "silence.stderr")
- i, tp, ok, err = parseLoudnorm(silence)
- if err != nil || ok || !math.IsInf(i, -1) || !math.IsInf(tp, -1) {
+ silence := meterFixture(t, "silence.stderr")
+ i, tp, ok, err = parseMeter(silence)
+ if err != nil || ok || i != -70 || !math.IsInf(tp, -1) {
t.Errorf("silence: I %v TP %v measurable %v err %v", i, tp, ok, err)
}
- block := func(i, tp string) string {
- return "noise before\n[Parsed_loudnorm_1 @ 0x7f00] \n{\n\t\"input_i\" : \"" + i + "\",\n\t\"input_tp\" : \"" + tp +
- "\",\n\t\"input_lra\" : \"0.00\"\n}\n[out#0/null @ 0x5600] video:0KiB audio:2250KiB\nsize=N/A time=00:00:03.00\n"
- }
for _, c := range []struct {
name, tail string
i, tp float64
ok bool
err bool
}{
- {"plain", block("-20.50", "-10.25"), -20.5, -10.25, true, false},
- {"under the gate", block("-75.00", "-60.00"), -75, -60, false, false},
- {"exactly the gate", block("-70.00", "-60.00"), -70, -60, true, false},
- {"below the gate, peak heard", block("-inf", "-77.96"), math.Inf(-1), -77.96, false, false},
- {"two blocks: the last", block("-1", "-1") + block("-30.00", "-3.00"), -30, -3, true, false},
+ {"plain", summary("-20.5", "-10.2"), -20.5, -10.2, true, false},
+ {"at the gate", summary("-70.0", "-60.0"), -70, -60, false, false},
+ {"just over the gate", summary("-69.9", "-60.0"), -69.9, -60, true, false},
+ {"under the gate", summary("-inf", "-77.9"), math.Inf(-1), -77.9, false, false},
+ {"no peak", summary("-20.0", "-inf"), -20, math.Inf(-1), false, false},
+ {"two summaries: the last", summary("-1.0", "-1.0") + summary("-30.0", "-3.0"), -30, -3, true, false},
// The tail's first byte may be mid-line (a cut tag): not a
// line's start.
- {"at the very start", strings.TrimPrefix(block("-30.00", "-3.00"), "noise before\n"), 0, 0, false, true},
- {"not a number", block("loud", "-3.00"), 0, 0, false, true},
- {"empty", block("", "-3.00"), 0, 0, false, true},
- {"nan", block("nan", "-3.00"), 0, 0, false, false},
- {"no input_tp", "\n[Parsed_loudnorm_0 @ 0x1] \n{\n\"input_i\" : \"-20.00\"\n}\n", 0, 0, false, true},
- {"numbers, not strings", "\n[Parsed_loudnorm_0 @ 0x1] \n{\n\"input_i\" : -20, \"input_tp\" : -3\n}\n", 0, 0, false, true},
- {"no object after the prefix", "\n[Parsed_loudnorm_0 @ 0x1] \nsize=N/A\n{\"input_i\":\"-1\",\"input_tp\":\"-1\"}\n", 0, 0, false, true},
- {"prefix not at a line start", "\n [Parsed_loudnorm_0 @ 0x1] \n{\"input_i\":\"-1\",\"input_tp\":\"-1\"}\n", 0, 0, false, true},
+ {"at the very start", strings.TrimPrefix(summary("-30.0", "-3.0"), "noise before\n"), 0, 0, false, true},
+ {"not a number", summary("loud", "-3.0"), 0, 0, false, true},
+ {"a peak that is not a number", summary("-20.0", "x"), 0, 0, false, true},
+ {"nan", summary("nan", "-3.0"), 0, 0, false, true},
+ {"nan peak", summary("-20.0", "nan"), 0, 0, false, true},
+ {"empty", summary("", "-3.0"), 0, 0, false, true},
+ {"no true peak section", strings.Replace(summary("-20.0", "-3.0"), " True peak:\n", "", 1), 0, 0, false, true},
+ {"a sample peak only", strings.Replace(summary("-20.0", "-3.0"), "True peak:", "Sample peak:", 1), 0, 0, false, true},
+ {"after the summary's end", "\n[Parsed_ebur128_1 @ 0x1] Summary:\n[out#0/null @ 0x1] x\n I: -20.0 LUFS\n True peak:\n Peak: -3.0 dBFS\n", 0, 0, false, true},
+ {"prefix not at a line start", "\n [Parsed_ebur128_0 @ 0x1] Summary:\n I: -1.0 LUFS\n True peak:\n Peak: -1.0 dBFS\n", 0, 0, false, true},
{"nothing", "", 0, 0, false, true},
- {"truncated", "\n[Parsed_loudnorm_0 @ 0x1] \n{\n\t\"input_i\" : \"-20.00\",\n\t\"input_t", 0, 0, false, true},
+ {"truncated", "\n[Parsed_ebur128_0 @ 0x1] Summary:\n\n Integrated loudness:\n I: -20.0 LUFS\n True pe", 0, 0, false, true},
} {
- i, tp, ok, err := parseLoudnorm([]byte(c.tail))
+ i, tp, ok, err := parseMeter([]byte(c.tail))
if (err != nil) != c.err {
t.Errorf("%s: err %v", c.name, err)
continue
@@ -196,13 +214,13 @@ func TestParseLoudnormTail(t *testing.T) {
if c.err {
continue
}
- if ok != c.ok || (c.name != "nan" && (i != c.i || tp != c.tp)) {
+ if ok != c.ok || i != c.i || tp != c.tp {
t.Errorf("%s: I %v TP %v measurable %v, want %v %v %v", c.name, i, tp, ok, c.i, c.tp, c.ok)
}
}
// No error quotes the tail (it holds the source's tags).
- for _, tail := range []string{block("SECRET-7", "-3"), "\n[Parsed_loudnorm_0 @ 0x1] \n{\"input_i\":\"SECRET-7\"", "SECRET-7"} {
- if _, _, _, err := parseLoudnorm([]byte(tail)); err == nil || strings.Contains(err.Error(), "SECRET") {
+ for _, tail := range []string{summary("SECRET-7", "-3.0"), summary("-1.0", "SECRET-7"), "\n[Parsed_ebur128_0 @ 0x1] SECRET-7", "SECRET-7"} {
+ if _, _, _, err := parseMeter([]byte(tail)); err == nil || strings.Contains(err.Error(), "SECRET") {
t.Errorf("error %v", err)
}
}
@@ -210,8 +228,9 @@ func TestParseLoudnormTail(t *testing.T) {
// TestMeasureArgs: the loudness pass reads exactly what the audio
// encode reads (the same input, map, strip and grant, the same layout
-// at 48 kHz) at -loglevel info, where loudnorm prints, into the null
-// muxer; every path is under cfg.Scratch (preflight F21).
+// at 48 kHz in planar float) at -loglevel info, where ebur128 prints,
+// into the null muxer; every path is under cfg.Scratch (preflight
+// F21).
func TestMeasureArgs(t *testing.T) {
cfg := Config{Scratch: "/srv/scratch-7"}
p := media.Payload{Preset: media.PresetAudioAAC, Limits: limitsFor(media.PresetAudioAAC)}
@@ -221,7 +240,7 @@ func TestMeasureArgs(t *testing.T) {
in[slices.Index(in, "-loglevel")+1] = "info"
want := append(in,
"-map", "0:3", "-vn", "-sn", "-dn", "-map_metadata", "-1", "-map_chapters", "-1", "-t", "90.500",
- "-af", "aformat=channel_layouts=mono:sample_rates=48000,loudnorm=I=-16:TP=-1.5:LRA=11:print_format=json",
+ "-af", "aformat=channel_layouts=mono:sample_rates=48000:sample_fmts=fltp,ebur128=peak=true:framelog=quiet",
"-f", "null", "-")
got := measureArgs(cfg, f, p, "matroska", "mono")
if !slices.Equal(got, want) {
@@ -230,7 +249,8 @@ func TestMeasureArgs(t *testing.T) {
if !slices.Contains(got, "/srv/scratch-7/in/source") {
t.Error("input not under cfg.Scratch")
}
- // The encode's arguments, from the input to the -af, are the same.
+ // The encode's arguments, from the input to the -af's aformat, are
+ // the same.
enc := audioArgs(cfg, f, p, "matroska", 0)
ei, mi := slices.Index(enc, "-af"), slices.Index(got, "-af")
encHead, measHead := slices.Clone(enc[:ei]), slices.Clone(got[:mi])
@@ -238,8 +258,9 @@ func TestMeasureArgs(t *testing.T) {
if !slices.Equal(encHead, measHead) {
t.Errorf("measure reads other than the encode:\n%q\n%q", measHead, encHead)
}
- if !strings.HasPrefix(enc[ei+1], "aformat=channel_layouts=mono:sample_rates=48000,") {
- t.Errorf("encode -af %q", enc[ei+1])
+ aformat := "aformat=channel_layouts=mono:sample_rates=48000:sample_fmts=fltp,"
+ if !strings.HasPrefix(enc[ei+1], aformat) || !strings.HasPrefix(got[mi+1], aformat) {
+ t.Errorf("encode -af %q, measure -af %q", enc[ei+1], got[mi+1])
}
// Every other ffmpeg run stays at -loglevel error.
for _, args := range [][]string{audioArgs(cfg, f, p, "matroska", 0), peaksArgs(cfg, f, p, "matroska", 0)} {
@@ -249,9 +270,22 @@ func TestMeasureArgs(t *testing.T) {
}
}
+// TestOutputMeterArgs: audio.mp4's one audio stream, under cfg.Scratch,
+// with the source's input options and AAC alone decoded, through the
+// same meter.
+func TestOutputMeterArgs(t *testing.T) {
+ want := []string{"-hide_banner", "-nostats", "-loglevel", "info", "-nostdin",
+ "-protocol_whitelist", "file", "-f", "mov", "-enable_drefs", "0", "-max_pixels", fmt.Sprint(maxDecodePixels),
+ "-codec_whitelist", "aac", "-i", "/srv/scratch-7/out/audio.mp4",
+ "-map", "0:a:0", "-vn", "-sn", "-dn", "-af", "ebur128=peak=true:framelog=quiet", "-f", "null", "-"}
+ if got := outputMeterArgs(Config{Scratch: "/srv/scratch-7"}); !slices.Equal(got, want) {
+ t.Errorf("\n got %q\nwant %q", got, want)
+ }
+}
+
// TestMeasureLayoutMatchesTheEncode: whatever the channel count, 0 and
-// a negative one included, the pass measures the layout the encode
-// writes.
+// a negative one included, the pass measures the layout and sample
+// format the encode writes.
func TestMeasureLayoutMatchesTheEncode(t *testing.T) {
cfg := Config{Scratch: "/scratch"}
p := media.Payload{Preset: media.PresetAudioAAC, Limits: limitsFor(media.PresetAudioAAC)}
@@ -260,7 +294,7 @@ func TestMeasureLayoutMatchesTheEncode(t *testing.T) {
layout, _ := audioLayout(f)
m := argAfter(measureArgs(cfg, f, p, "flac", layout), "-af")
e := argAfter(audioArgs(cfg, f, p, "flac", 0), "-af")
- want := "aformat=channel_layouts=" + layout + ":sample_rates=48000,"
+ want := "aformat=channel_layouts=" + layout + ":sample_rates=48000:sample_fmts=fltp,"
if !strings.HasPrefix(m, want) || !strings.HasPrefix(e, want) {
t.Errorf("%d channels: measure %q, encode %q", ch, m, e)
}
diff --git a/internal/mediahandler/testdata/loudnorm/peaky-forged-tags.stderr b/internal/mediahandler/testdata/loudnorm/peaky-forged-tags.stderr
index 0f3d56c5b..a1fa25401 100644
--- a/internal/mediahandler/testdata/loudnorm/peaky-forged-tags.stderr
+++ b/internal/mediahandler/testdata/loudnorm/peaky-forged-tags.stderr
@@ -2,11 +2,13 @@ Input #0, flac, from '/scratch/in/source':
Metadata:
title : TITLE-SECRET-7
comment : x
- : [Parsed_loudnorm_9 @ 0x1]
- : {
- : "input_i" : "-5.00",
- : "input_tp" : "-60.00"
- : }
+ : [Parsed_ebur128_9 @ 0x1] Summary:
+ :
+ : Integrated loudness:
+ : I: -5.0 LUFS
+ :
+ : True peak:
+ : Peak: -60.0 dBFS
:
encoder : Lavf61.7.103
Duration: 00:00:20.00, start: 0.000000, bitrate: 279 kb/s
@@ -16,21 +18,22 @@ Stream mapping:
Output #0, null, to 'pipe:':
Metadata:
encoder : Lavf61.7.103
- Stream #0:0: Audio: pcm_s16le, 192000 Hz, mono, s16, 3072 kb/s
+ Stream #0:0: Audio: pcm_s16le, 48000 Hz, mono, s16, 768 kb/s
Metadata:
encoder : Lavc61.19.101 pcm_s16le
-[Parsed_loudnorm_1 @ 0x7f3648005140]
-{
- "input_i" : "-31.51",
- "input_tp" : "-2.86",
- "input_lra" : "14.00",
- "input_thresh" : "-41.51",
- "output_i" : "-20.23",
- "output_tp" : "-1.50",
- "output_lra" : "5.90",
- "output_thresh" : "-31.13",
- "normalization_type" : "dynamic",
- "target_offset" : "4.23"
-}
-[out#0/null @ 0x564ab911ee00] video:0KiB audio:7500KiB subtitle:0KiB other streams:0KiB global headers:0KiB muxing overhead: unknown
-size=N/A time=00:00:20.00 bitrate=N/A speed=54.8x
+[Parsed_ebur128_1 @ 0x7f6f180050c0] Summary:
+
+ Integrated loudness:
+ I: -31.0 LUFS
+ Threshold: -41.0 LUFS
+
+ Loudness range:
+ LRA: 14.0 LU
+ Threshold: -50.5 LUFS
+ LRA low: -37.7 LUFS
+ LRA high: -23.7 LUFS
+
+ True peak:
+ Peak: -2.9 dBFS
+[out#0/null @ 0x55d89fb6fd40] video:0KiB audio:1875KiB subtitle:0KiB other streams:0KiB global headers:0KiB muxing overhead: unknown
+size=N/A time=00:00:20.00 bitrate=N/A speed= 505x
diff --git a/internal/mediahandler/testdata/loudnorm/provenance.txt b/internal/mediahandler/testdata/loudnorm/provenance.txt
index 9b4a1d4bc..12527cf56 100644
--- a/internal/mediahandler/testdata/loudnorm/provenance.txt
+++ b/internal/mediahandler/testdata/loudnorm/provenance.txt
@@ -1,12 +1,14 @@
-Where each fixture comes from (plan 3 Task 5).
+Where each fixture comes from (plan 3 Task 5, fix round 1).
-Each file is the whole stderr of the loudness pass (measureArgs, so
--loglevel info, loudnorm=I=-16:TP=-1.5:LRA=11:print_format=json into
-the null muxer) of Debian 13's ffmpeg 7.1.5 (7.1.5-0+deb13u1, amd64,
-unpacked without root: plan 3 Task 3 fix 1), with the test's scratch
-path replaced by /scratch. The sources are 48 kHz mono FLAC made by the
-same ffmpeg from aevalsrc; loudnessSources in loudness_linux_test.go
-holds the expressions, and
+The directory keeps its first name; since fix 1 the meter is ebur128,
+not loudnorm. Each file is the whole stderr of the loudness pass
+(measureArgs: -loglevel info, aformat to the layout at 48 kHz in planar
+float, then ebur128=peak=true:framelog=quiet into the null muxer) of
+Debian 13's ffmpeg 7.1.5 (7.1.5-0+deb13u1, amd64, unpacked without
+root: plan 3 Task 3 fix 1), with the test's scratch path replaced by
+/scratch. The sources are 48 kHz mono FLAC made by the same ffmpeg from
+aevalsrc; loudnessSources in loudness_linux_test.go holds the
+expressions, and
CARLOS_MEDIA_REGEN_FIXTURES=1 go test ./internal/mediahandler/ \
-run TestRegenerateLoudnormFixtures
@@ -14,15 +16,15 @@ holds the expressions, and
rewrites both (the 0x… addresses in the log prefixes change each run).
peaky-forged-tags.stderr "peaky": 0.02·sin(2π·440t), with
- 0.7·sin(2π·1000t) from 3 s to 3.05 s, 20 s;
- tagged with a title (TITLE-SECRET-7) and a
- comment whose lines forge a loudnorm report
- (I -5.00, TP -60.00). ffmpeg prints the tags
- indented, every line of each.
-silence.stderr "silence": aevalsrc=0, 6 s, no tags. I and TP
- are both -inf.
+ 0.7·sin(2π·1000t) added from 3 s to 3.05 s,
+ 20 s; tagged with a title (TITLE-SECRET-7)
+ and a comment whose lines forge an ebur128
+ summary (I -5.0, Peak -60.0). ffmpeg prints
+ the tags indented, every line of each.
+silence.stderr "silence": aevalsrc=0, 6 s, no tags. I -70.0
+ (the gate), Peak -inf.
-The real report in peaky-forged-tags.stderr reads input_i -31.51 and
-input_tp -2.86 (gain min(-16 + 31.51, -2 + 2.86) = +0.86, the
-ceiling's); TestParseLoudnormTail holds parseLoudnorm to those numbers
-and not the forged ones.
+The real summary in peaky-forged-tags.stderr reads I -31.0 LUFS and
+true peak -2.9 dBFS (gain min(-16 + 31.0, -2 - (-2.9 + 0.05)) = +0.85,
+the ceiling's); TestParseMeterTail holds parseMeter to those numbers and
+not the forged ones.
diff --git a/internal/mediahandler/testdata/loudnorm/silence.stderr b/internal/mediahandler/testdata/loudnorm/silence.stderr
index 25d6f7b33..2b4f0b216 100644
--- a/internal/mediahandler/testdata/loudnorm/silence.stderr
+++ b/internal/mediahandler/testdata/loudnorm/silence.stderr
@@ -8,21 +8,22 @@ Stream mapping:
Output #0, null, to 'pipe:':
Metadata:
encoder : Lavf61.7.103
- Stream #0:0: Audio: pcm_s16le, 192000 Hz, mono, s16, 3072 kb/s
+ Stream #0:0: Audio: pcm_s16le, 48000 Hz, mono, s16, 768 kb/s
Metadata:
encoder : Lavc61.19.101 pcm_s16le
-[Parsed_loudnorm_1 @ 0x7fc30c005140]
-{
- "input_i" : "-inf",
- "input_tp" : "-inf",
- "input_lra" : "0.00",
- "input_thresh" : "-70.00",
- "output_i" : "-inf",
- "output_tp" : "-inf",
- "output_lra" : "0.00",
- "output_thresh" : "-70.00",
- "normalization_type" : "dynamic",
- "target_offset" : "inf"
-}
-[out#0/null @ 0x55edd8decf00] video:0KiB audio:2250KiB subtitle:0KiB other streams:0KiB global headers:0KiB muxing overhead: unknown
-size=N/A time=00:00:06.00 bitrate=N/A speed=39.7x
+[Parsed_ebur128_1 @ 0x7fc9440050c0] Summary:
+
+ Integrated loudness:
+ I: -70.0 LUFS
+ Threshold: 0.0 LUFS
+
+ Loudness range:
+ LRA: 0.0 LU
+ Threshold: 0.0 LUFS
+ LRA low: 0.0 LUFS
+ LRA high: 0.0 LUFS
+
+ True peak:
+ Peak: -inf dBFS
+[out#0/null @ 0x5647dd2d0f00] video:0KiB audio:562KiB subtitle:0KiB other streams:0KiB global headers:0KiB muxing overhead: unknown
+size=N/A time=00:00:06.00 bitrate=N/A speed= 472x