media: linear loudness gain, ceiling first, and peaks
Plan 3 Task 5. audio-aac measures the source with loudnorm in a pass that reads exactly what the encode reads, and applies one gain: min(-16 - I, (-1.5 - 0.5) - TP), rounded down to the hundredth, none when the loudness is -inf, under -70 LUFS or not a number. The pass runs at -loglevel info, so its stderr (the source's tags) stays in memory and is never logged (F19); the report is taken only after a newline-anchored loudnorm prefix, so a tag cannot forge it. peaks.json: a mono 8 kHz mix with the same gain, 1,000 equal slices, min(255, (max|s|*255 + 16383)/32767), written exactly in key order. The raw mix is refused if it is not a regular file. Real-binary tests on Debian's ffmpeg 7.1.5 cover target, ceiling, attenuation, under-the-gate, silence and a forged report; fixtures and their provenance in testdata/loudnorm. New log lines are in the copy deck, pending a Luna pass.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
11 files changed,
+1,526
−19
docs/superpowers/notes/media-conversion-copy-deck.md+12 −4internal/mediahandler/ffmpeg.go+43 −14internal/mediahandler/loudness.go+153 −0internal/mediahandler/loudness_linux_test.go+514 −0internal/mediahandler/loudness_test.go+271 −0internal/mediahandler/peaks.go+167 −0internal/mediahandler/peaks_test.go+265 −0internal/mediahandler/probe.go+9 −1internal/mediahandler/testdata/loudnorm/peaky-forged-tags.stderr+36 −0internal/mediahandler/testdata/loudnorm/provenance.txt+28 −0internal/mediahandler/testdata/loudnorm/silence.stderr+28 −0
diff --git a/docs/superpowers/notes/media-conversion-copy-deck.md b/docs/superpowers/notes/media-conversion-copy-deck.md| index 54bd870bf..8d35efc78 100644 |
| --- a/docs/superpowers/notes/media-conversion-copy-deck.md |
| +++ b/docs/superpowers/notes/media-conversion-copy-deck.md |
| @@ -563,7 +563,15 @@ prints nothing. |
| | `engine.probe.no_duration` | `codec: the source has no duration in its header or its packets` (pending Luna pass; plan 3 Task 3) | |
| | `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`; `%q` is the last 4 KiB of ffmpeg's stderr at `-loglevel error`, quoted so it stays one line | |
| -| `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` | |
| -| `engine.encode.empty` | `codec: ffmpeg wrote no sample to %s` (pending Luna pass; plan 3 Task 4). `%s` is `video.mp4` or `audio.mp4` | |
| -| `engine.encode.unusable` | `codec: %s: %s` (pending Luna pass; plan 3 Task 4). The first `%s` is an output's name or `the output directory`; the second is the system's error or one of readFMP4's fixed reasons (a box type and a byte offset, never the file's bytes) | |
| +| `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.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 | |
diff --git a/internal/mediahandler/ffmpeg.go b/internal/mediahandler/ffmpeg.go| index cbbbefd32..729852750 100644 |
| --- a/internal/mediahandler/ffmpeg.go |
| +++ b/internal/mediahandler/ffmpeg.go |
| @@ -194,23 +194,39 @@ func posterArgs(cfg Config, f probeFacts, p media.Payload, demuxer string) []str |
| // 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 { |
| - layout, rate := "stereo", "128k" |
| - if f.Channels == 1 { |
| - layout, rate = "mono", "64k" |
| - } |
| - if math.IsNaN(gainDB) || math.IsInf(gainDB, 0) { |
| - gainDB = 0 |
| - } |
| + layout, rate := audioLayout(f) |
| args := ffmpegInputArgs(cfg, demuxer) |
| 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,volume="+strconv.FormatFloat(gainDB, 'f', 2, 64)+"dB", |
| + "-af", "aformat=channel_layouts="+layout+":sample_rates=48000,"+volumeFilter(gainDB), |
| "-c:a", "aac", "-b:a", rate, |
| "-f", "mp4", "-movflags", audioMovflags, "-frag_duration", fragmentMicros, |
| outPath(cfg, audioNames[0])) |
| } |
| +// audioLayout is audio-aac's output layout and bitrate: mono at 64k for |
| +// a mono source, else stereo at 128k. Any other channel count, 0 (which |
| +// ffprobe answers when it cannot tell) included, is stereo: the count |
| +// is only compared, never divided by, and ffmpeg's decoder, not the |
| +// probe, decides whether the stream decodes. The loudness pass measures |
| +// the same layout the encode writes (measureArgs). |
| +func audioLayout(f probeFacts) (layout, bitrate string) { |
| + if f.Channels == 1 { |
| + return "mono", "64k" |
| + } |
| + return "stereo", "128k" |
| +} |
| + |
| +// volumeFilter is the one linear gain, in dB with two decimals; a gain |
| +// that is not a finite number is none. |
| +func volumeFilter(gainDB float64) string { |
| + if math.IsNaN(gainDB) || math.IsInf(gainDB, 0) { |
| + gainDB = 0 |
| + } |
| + return "volume=" + strconv.FormatFloat(gainDB, 'f', 2, 64) + "dB" |
| +} |
| + |
| // encodeVideo runs video-720p's two encodes through runChild: the |
| // video, then the poster. A poster sought past the end of the video |
| // stream (a header duration longer than the video's) finds no frame: |
| @@ -252,7 +268,15 @@ func encodeAudio(ctx context.Context, cfg Config, p media.Payload, demuxer strin |
| const encodeLogTail = 4 << 10 |
| // encode runs one ffmpeg encode (what names it in the log) in |
| -// <scratch>/tmp and maps its outcome: |
| +// <scratch>/tmp and maps its outcome with ffmpegOutcome, logging the |
| +// stderr tail of a failure. |
| +func encode(ctx context.Context, cfg Config, what string, args []string) error { |
| + tail, err := runChild(ctx, cfg, cfg.FFmpeg, args, filepath.Join(cfg.Scratch, "tmp")) |
| + return ffmpegOutcome(ctx, cfg, what, err, tail, true) |
| +} |
| + |
| +// ffmpegOutcome maps one ffmpeg run's outcome (what names it in the |
| +// log): |
| // |
| // - a clean exit: nil; |
| // - ctx ending (the task stopping): ctx's error; |
| @@ -262,11 +286,12 @@ const encodeLogTail = 4 << 10 |
| // kernel's OOM killer (the task's memory, not the source, is what |
| // ran out), and the operator, not the tenant, has to act; |
| // - any other failure, a crash by another signal included: |
| -// unreadable, logged with the last encodeLogTail bytes of ffmpeg's |
| -// stderr (quoted, so it stays one line), which -loglevel error |
| -// keeps to errors, never the source's metadata (preflight F19). |
| -func encode(ctx context.Context, cfg Config, what string, args []string) error { |
| - tail, err := runChild(ctx, cfg, cfg.FFmpeg, args, filepath.Join(cfg.Scratch, "tmp")) |
| +// unreadable. With logTail, the log line carries the last |
| +// encodeLogTail bytes of ffmpeg's stderr (quoted, so it stays one |
| +// line), which -loglevel error keeps to errors, never the source's |
| +// metadata (preflight F19). A run at a louder level (the loudness |
| +// pass) passes logTail false, and nothing of its stderr is logged. |
| +func ffmpegOutcome(ctx context.Context, cfg Config, what string, err error, tail []byte, logTail bool) error { |
| var je jobError |
| switch { |
| case err == nil: |
| @@ -279,6 +304,10 @@ func encode(ctx context.Context, cfg Config, what string, args []string) error { |
| // engine.encode.killed (pending Luna pass). |
| cfg.Logf("codec: ffmpeg (%s) was killed by SIGKILL, likely out of memory", what) |
| return jobError{media.CodeEngineFailed} |
| + case !logTail: |
| + // engine.encode.failed_unlogged (pending Luna pass). |
| + cfg.Logf("codec: ffmpeg (%s) failed; its output is not logged", what) |
| + return jobError{media.CodeUnreadable} |
| } |
| // engine.encode.failed (pending Luna pass). |
| cfg.Logf("codec: ffmpeg (%s) failed: %q", what, tail[max(0, len(tail)-encodeLogTail):]) |
diff --git a/internal/mediahandler/loudness.go b/internal/mediahandler/loudness.go| new file mode 100644 |
| index 000000000..b710430b0 |
| --- /dev/null |
| +++ b/internal/mediahandler/loudness.go |
| @@ -0,0 +1,153 @@ |
| +package mediahandler |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "math" |
| + "path/filepath" |
| + "strconv" |
| + |
| + "github.com/carlosframework/platform/internal/media" |
| +) |
| + |
| +// audio-aac's loudness (spec §5.1, astra R6-5): one linear gain, the |
| +// smaller of the gain that brings the integrated loudness to targetLUFS |
| +// and the gain that brings the true peak to ceilingDBTP less |
| +// 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). |
| +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. |
| +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" |
| + |
| +// 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). |
| +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, |
| + "-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 |
| +// 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...)) |
| + 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") |
| + } |
| + if report.InputI == nil || report.InputTP == nil { |
| + return 0, 0, false, errors.New("the loudnorm report has no input_i or input_tp") |
| + } |
| + 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") |
| + } |
| + 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. |
| +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 |
| +} |
| + |
| +// 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. |
| +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 |
| +} |
| + |
| +// 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")) |
| + defer clear(tail) |
| + if err := ffmpegOutcome(ctx, cfg, "loudness", err, tail, false); err != nil { |
| + return 0, err |
| + } |
| + inputI, inputTP, measurable, err := parseLoudnorm(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} |
| + } |
| + 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) |
| + return gain, nil |
| +} |
diff --git a/internal/mediahandler/loudness_linux_test.go b/internal/mediahandler/loudness_linux_test.go| new file mode 100644 |
| index 000000000..71dec637c |
| --- /dev/null |
| +++ b/internal/mediahandler/loudness_linux_test.go |
| @@ -0,0 +1,514 @@ |
| +//go:build linux |
| + |
| +package mediahandler |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "math" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "slices" |
| + "strconv" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/media" |
| +) |
| + |
| +// fakeTags is what a fake loudness pass prints as the source's tags, |
| +// as ffmpeg does at -loglevel info: none of it may reach the log. |
| +const fakeTags = "Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '/scratch/in/source':\n Metadata:\n" + |
| + " 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. |
| + 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", |
| + } { |
| + fakeScenarios[name] = func([]string) int { |
| + fmt.Fprint(os.Stderr, stderr) |
| + if strings.HasSuffix(name, "-fails") { |
| + return 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 { |
| + f, err := os.OpenFile(args[len(args)-1], os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) |
| + if err == nil { |
| + _, err = f.Write(s16le(fakePeakSamples())) |
| + err = errors.Join(err, f.Close()) |
| + } |
| + if err != nil { |
| + fmt.Fprintln(os.Stderr, "fake:", err) |
| + return 1 |
| + } |
| + return 0 |
| + } |
| + // peaks-none exits 0 having written nothing. |
| + fakeScenarios["peaks-none"] = func([]string) int { return 0 } |
| + // peaks-link-outside leaves the raw file a symlink to a file of |
| + // samples outside the scratch, made by the test; |
| + // peaks-link-inside, to one it writes beside it, which os.Root |
| + // alone would follow. |
| + fakeScenarios["peaks-link-outside"] = func(args []string) int { |
| + return fakeLink(os.Getenv("MEDIA_FAKE_LINK_TARGET"), args[len(args)-1]) |
| + } |
| + fakeScenarios["peaks-link-inside"] = func(args []string) int { |
| + raw := args[len(args)-1] |
| + if err := os.WriteFile(raw+".other", s16le(fakePeakSamples()), 0o600); err != nil { |
| + fmt.Fprintln(os.Stderr, "fake:", err) |
| + return 1 |
| + } |
| + return fakeLink(filepath.Base(raw)+".other", raw) |
| + } |
| +} |
| + |
| +// fakeLink makes link a symlink to target. |
| +func fakeLink(target, link string) int { |
| + if err := os.Symlink(target, link); err != nil { |
| + fmt.Fprintln(os.Stderr, "fake:", err) |
| + return 1 |
| + } |
| + return 0 |
| +} |
| + |
| +// fakePeakSamples are the fake peaks pass's samples: 3,000, each |
| +// slice's three a ramp to i·32 in magnitude. |
| +func fakePeakSamples() []int16 { |
| + s := make([]int16, 3000) |
| + for i := range s { |
| + v := int16((i / 3) * 32) |
| + if i%2 == 1 { |
| + v = -v |
| + } |
| + s[i] = v |
| + } |
| + return s |
| +} |
| + |
| +// 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)} |
| + return p, probeFacts{VideoIndex: -1, AudioIndex: 0, AudioCodec: "aac", Channels: channels, DurationMS: 3000} |
| +} |
| + |
| +// 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). |
| +func TestMeasureLoudnessOutcomes(t *testing.T) { |
| + for _, c := range []struct { |
| + scenario string |
| + channels int |
| + 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}, |
| + // 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}, |
| + {"die-sigsegv", 2, media.CodeUnreadable, 0}, |
| + {"die-sigkill", 2, media.CodeEngineFailed, 0}, |
| + } { |
| + name := fmt.Sprintf("%s, %d channels", c.scenario, c.channels) |
| + 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(c.channels) |
| + gain, err := measureLoudness(context.Background(), cfg, p, "mov", f) |
| + if codeOf(err) != c.want || gain != c.gain { |
| + t.Errorf("%s: gain %v, %s; want %v, %s", name, gain, codeOf(err), c.gain, c.want) |
| + } |
| + runs := fakeRuns(t, record) |
| + layout, _ := audioLayout(f) |
| + if len(runs) != 1 || !slices.Equal(runs[0].Args, measureArgs(cfg, f, p, "mov", layout)) { |
| + t.Errorf("%s: runs %+v", name, runs) |
| + } |
| + all := strings.Join(logs, "\n") |
| + if strings.Contains(all, "SECRET") || strings.Contains(all, "48.8584") || strings.Contains(all, "Metadata") { |
| + t.Errorf("%s: the source's tags were logged: %q", name, logs) |
| + } |
| + if len(logs) == 0 { |
| + t.Errorf("%s: nothing logged", name) |
| + } |
| + } |
| + cfg, _ := fakeConfig(t, "block") |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + cancel() |
| + p, f := audioJob(2) |
| + if _, err := measureLoudness(ctx, cfg, p, "mov", f); !errors.Is(err, context.Canceled) { |
| + t.Errorf("a stopping task: %v", err) |
| + } |
| +} |
| + |
| +// 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 |
| +// run that wrote nothing is unreadable; a raw file left as a symlink is |
| +// refused, not followed (engine_failed), as is an existing peaks.json; |
| +// a failed run is unreadable and writes no peaks.json. |
| +func TestMakePeaks(t *testing.T) { |
| + p, f := audioJob(2) |
| + cfg, record := fakeConfig(t, "peaks") |
| + raw := filepath.Join(cfg.Scratch, "tmp", peaksRaw) |
| + if err := os.WriteFile(raw, []byte("stale"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := makePeaks(context.Background(), cfg, p, "mov", f, -3.5, 2999); err != nil { |
| + t.Fatal(err) |
| + } |
| + runs := fakeRuns(t, record) |
| + if len(runs) != 1 || !slices.Equal(runs[0].Args, peaksArgs(cfg, f, p, "mov", -3.5)) { |
| + t.Errorf("runs %+v", runs) |
| + } |
| + got, err := os.ReadFile(outPath(cfg, "peaks.json")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + peaks, err := computePeaks(bytes.NewReader(s16le(fakePeakSamples())), 3000) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var want bytes.Buffer |
| + if err := writePeaks(&want, 2999, peaks); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !bytes.Equal(got, want.Bytes()) { |
| + t.Errorf("peaks.json %.120s", got) |
| + } |
| + // Slice i holds samples 3i..3i+2, magnitudes i·32: 999 → 249. |
| + if peaks[0] != 0 || peaks[999] != 249 { |
| + t.Errorf("peaks %d %d", peaks[0], peaks[999]) |
| + } |
| + if _, err := os.Lstat(raw); !errors.Is(err, os.ErrNotExist) { |
| + t.Errorf("peaks.raw left behind: %v", err) |
| + } |
| + // peaks.json is created, never overwritten. |
| + runs0 := len(fakeRuns(t, record)) |
| + if err := makePeaks(context.Background(), cfg, p, "mov", f, 0, 2999); codeOf(err) != media.CodeEngineFailed { |
| + t.Errorf("existing peaks.json: %s", codeOf(err)) |
| + } |
| + if n := len(fakeRuns(t, record)); n != runs0+1 { |
| + t.Errorf("%d runs", n-runs0) |
| + } |
| + |
| + for _, c := range []struct{ scenario, want string }{ |
| + {"peaks-none", media.CodeUnreadable}, |
| + {"peaks-link-outside", media.CodeEngineFailed}, |
| + {"peaks-link-inside", media.CodeEngineFailed}, |
| + {"fail", media.CodeUnreadable}, |
| + {"die-sigkill", media.CodeEngineFailed}, |
| + } { |
| + cfg, _ := fakeConfig(t, c.scenario) |
| + target := filepath.Join(t.TempDir(), "outside") |
| + if err := os.WriteFile(target, s16le([]int16{32767, 32767}), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + cfg.extraEnv = append(cfg.extraEnv, "MEDIA_FAKE_LINK_TARGET="+target) |
| + if err := makePeaks(context.Background(), cfg, p, "mov", f, 0, 1000); codeOf(err) != c.want { |
| + t.Errorf("%s: %s, want %s", c.scenario, codeOf(err), c.want) |
| + } |
| + if _, err := os.Lstat(outPath(cfg, "peaks.json")); !errors.Is(err, os.ErrNotExist) { |
| + t.Errorf("%s: peaks.json written: %v", c.scenario, err) |
| + } |
| + } |
| +} |
| + |
| +// Real-binary tests (realffmpeg_test.go says how they skip). The |
| +// sources are made here by the real ffmpeg from aevalsrc, so their |
| +// loudness is known; testdata/loudnorm/provenance.txt records the |
| +// 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). |
| +var loudnessSources = []struct { |
| + name, expr string |
| + layout string // "" for aevalsrc's mono |
| + seconds int |
| + i, tp float64 |
| + 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"}, |
| + // 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"}, |
| +} |
| + |
| +// makeAudioSource writes a FLAC of expr, seconds long (and tags, |
| +// name=value), to the scratch's source with the real ffmpeg, arguments |
| +// unsplit. |
| +func makeAudioSource(t *testing.T, cfg Config, expr, layout string, seconds int, tags ...string) { |
| + t.Helper() |
| + _ = os.Remove(sourcePath(cfg)) |
| + src := "aevalsrc=" + expr + ":s=48000:d=" + strconv.Itoa(seconds) |
| + if layout != "" { |
| + src += ":c=" + layout |
| + } |
| + args := []string{"-hide_banner", "-loglevel", "error", "-nostdin", "-f", "lavfi", "-i", src} |
| + for _, tag := range tags { |
| + args = append(args, "-metadata", tag) |
| + } |
| + args = append(args, "-c:a", "flac", "-f", "flac", sourcePath(cfg)) |
| + cmd := exec.Command(cfg.FFmpeg, args...) |
| + var stderr bytes.Buffer |
| + cmd.Stderr = &stderr |
| + if err := cmd.Run(); err != nil { |
| + t.Fatalf("ffmpeg %q: %v\n%s", args, err, stderr.String()) |
| + } |
| +} |
| + |
| +// 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). |
| +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", |
| +} |
| + |
| +// audioPayload is an audio-aac payload with the class's limits. |
| +func audioPayload() media.Payload { |
| + return media.Payload{Preset: media.PresetAudioAAC, Limits: limitsFor(media.PresetAudioAAC)} |
| +} |
| + |
| +// TestRegenerateLoudnormFixtures rewrites testdata/loudnorm from the |
| +// real loudness pass when CARLOS_MEDIA_REGEN_FIXTURES=1: the whole |
| +// stderr (not only runChild's tail) of measureArgs over "peaky" with |
| +// forgedTags, and over "silence". |
| +func TestRegenerateLoudnormFixtures(t *testing.T) { |
| + if os.Getenv(regenEnv) != "1" { |
| + 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] |
| + var tags []string |
| + if src == 0 { |
| + tags = forgedTags |
| + } |
| + makeAudioSource(t, cfg, s.expr, s.layout, s.seconds, tags...) |
| + f, err := probe(context.Background(), cfg, "flac", media.PresetAudioAAC) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + layout, _ := audioLayout(f) |
| + tail, err := runChild(context.Background(), cfg, cfg.FFmpeg, measureArgs(cfg, f, audioPayload(), "flac", layout), "") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + // The test's scratch path is the machine's: write the default. |
| + tail = bytes.ReplaceAll(tail, []byte(cfg.Scratch), []byte(DefaultScratch)) |
| + if err := os.WriteFile(filepath.Join("testdata", "loudnorm", file), tail, 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| +} |
| + |
| +// ebur128 measures path's audio independently of loudnorm: integrated |
| +// loudness and true peak, from ebur128's 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", "-") |
| + field := func(name string) float64 { |
| + at := strings.LastIndex(out, "\n "+name+":") |
| + if at < 0 { |
| + t.Fatalf("no %s in ebur128's summary", name) |
| + } |
| + return parseFloat(t, strings.Fields(out[at+len(name)+6:])[0]) |
| + } |
| + 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. |
| +func TestRealLoudness(t *testing.T) { |
| + cfg := realConfig(t) |
| + for _, s := range loudnessSources { |
| + t.Run(s.name, func(t *testing.T) { |
| + var logs []string |
| + cfg.Logf = func(format string, args ...any) { logs = append(logs, fmt.Sprintf(format, args...)) } |
| + makeAudioSource(t, cfg, s.expr, s.layout, s.seconds, forgedTags...) |
| + for _, n := range audioNames { |
| + _ = os.Remove(outPath(cfg, n)) |
| + } |
| + p := audioPayload() |
| + f, err := probe(context.Background(), cfg, "flac", media.PresetAudioAAC) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := check(f, p.Preset, p.Limits); err != nil { |
| + t.Fatal(err) |
| + } |
| + gain, err := measureLoudness(context.Background(), cfg, p, "flac", f) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if gain != s.gain { |
| + t.Errorf("gain %v, want %v (%s)", gain, s.gain, s.wins) |
| + } |
| + // The arithmetic from the table's measurements. |
| + 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) |
| + } |
| + } |
| + all := strings.Join(logs, "\n") |
| + if strings.Contains(all, "SECRET") || strings.Contains(all, "Parsed_loudnorm_9") || len(logs) != 1 { |
| + t.Errorf("logged %q", logs) |
| + } |
| + |
| + if err := encodeAudio(context.Background(), cfg, p, "flac", f, gain); err != nil { |
| + t.Fatal(err) |
| + } |
| + 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": |
| + 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 "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 { |
| + t.Errorf("output I %v TP %v, want as quiet as the source", oi, otp) |
| + } |
| + } |
| + |
| + durationMS := int64(s.seconds) * 1000 |
| + if err := makePeaks(context.Background(), cfg, p, "flac", f, gain, durationMS); err != nil { |
| + t.Fatal(err) |
| + } |
| + b, err := os.ReadFile(outPath(cfg, "peaks.json")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var pj struct { |
| + Version int `json:"version"` |
| + DurationMS int64 `json:"duration_ms"` |
| + Peaks []uint8 `json:"peaks"` |
| + } |
| + 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 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). |
| +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 } |
| + near := func(what string, got uint8, want, tol float64) { |
| + if math.Abs(float64(got)-want) > tol { |
| + 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. |
| + 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) { |
| + near(fmt.Sprintf("slice %d", i), v, level(0.02), 1) |
| + } |
| + } |
| + 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) |
| + } |
| + default: // antiphase stereo, under the gate, silence |
| + for i, v := range peaks { |
| + if v != 0 { |
| + t.Errorf("%s: slice %d is %d, want 0", name, i, v) |
| + break |
| + } |
| + } |
| + } |
| +} |
| + |
| +// 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. |
| +func TestRealZeroChannels(t *testing.T) { |
| + cfg := realConfig(t) |
| + makeAudioSource(t, cfg, "0.1*sin(2*PI*440*t)", "", 6) |
| + var b bytes.Buffer |
| + cmd := exec.Command(cfg.FFmpeg, "-hide_banner", "-loglevel", "error", "-nostdin", "-f", "flac", "-i", sourcePath(cfg), |
| + "-c:a", "pcm_s16le", "-f", "wav", "pipe:1") |
| + cmd.Stdout = &b |
| + if err := cmd.Run(); err != nil { |
| + t.Fatal(err) |
| + } |
| + wav := b.Bytes() |
| + at := bytes.Index(wav, []byte("fmt ")) |
| + if at < 0 { |
| + t.Fatal("no fmt chunk") |
| + } |
| + wav[at+10], wav[at+11] = 0, 0 // channels |
| + if err := os.WriteFile(sourcePath(cfg), wav, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := probe(context.Background(), cfg, "wav", media.PresetAudioAAC); codeOf(err) != media.CodeUnreadable { |
| + t.Errorf("probe: %s", codeOf(err)) |
| + } |
| + f := probeFacts{VideoIndex: -1, AudioIndex: 0, AudioCodec: "pcm_s16le", Channels: 0, DurationMS: 6000} |
| + if _, err := measureLoudness(context.Background(), cfg, audioPayload(), "wav", f); codeOf(err) != media.CodeUnreadable { |
| + t.Errorf("loudness: %s", codeOf(err)) |
| + } |
| +} |
diff --git a/internal/mediahandler/loudness_test.go b/internal/mediahandler/loudness_test.go| new file mode 100644 |
| index 000000000..8739cad89 |
| --- /dev/null |
| +++ b/internal/mediahandler/loudness_test.go |
| @@ -0,0 +1,271 @@ |
| +package mediahandler |
| + |
| +import ( |
| + "math" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "strconv" |
| + "strings" |
| + "testing" |
| + |
| + "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. |
| +func TestGainTable(t *testing.T) { |
| + inf := math.Inf(-1) |
| + for _, c := range []struct { |
| + name string |
| + i, tp float64 |
| + 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. |
| + {"quiet, little peak", -20, -10, 4, "target"}, |
| + // min(-16 - -10, -2 - 0) = min(-6, -2) = -6: -16 LUFS, peak -6. |
| + {"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. |
| + {"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"}, |
| + // 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, |
| + // 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). |
| + {"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"}, |
| + // Not measurable: no gain. |
| + {"silence", inf, inf, 0, "none"}, |
| + {"below the gate, peak heard", inf, -77.96, 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"}, |
| + {"a loudness that is not a number", math.NaN(), -10, 0, "none"}, |
| + {"+inf", math.Inf(1), -10, 0, "none"}, |
| + } { |
| + got := gainDB(c.i, c.tp, isMeasurable(c.i, c.tp)) |
| + if got != c.want { |
| + t.Errorf("%s (I %v, TP %v): gain %v, want %v (%s wins)", c.name, c.i, c.tp, got, c.want, c.whyWinner) |
| + } |
| + // The volume= argument never asks for more than the exact gain. |
| + if c.whyWinner != "none" { |
| + exact := min(targetLUFS-c.i, ceilingDBTP-codecHeadroomDB-c.tp) |
| + arg := strings.TrimSuffix(strings.TrimPrefix(volumeFilter(got), "volume="), "dB") |
| + v, err := strconv.ParseFloat(arg, 64) |
| + if err != nil || v > exact+1e-9 { |
| + t.Errorf("%s: volume=%s over the exact gain %v", c.name, arg, exact) |
| + } |
| + } |
| + } |
| + // 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) |
| + } |
| + // 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}} { |
| + 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 |
| +// stderr from the loudness pass (provenance.txt). |
| +func loudnormFixture(t *testing.T, name string) []byte { |
| + t.Helper() |
| + b, err := os.ReadFile(filepath.Join("testdata", "loudnorm", name)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + 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") |
| + } |
| + i, tp, ok, err := parseLoudnorm(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 { |
| + t.Errorf("real tail: I %v TP %v", i, tp) |
| + } |
| + // Cut anywhere before the block'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_") |
| + for _, cut := range []int{1, 100, start - 1} { |
| + if gi, gtp, _, err := parseLoudnorm(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 { |
| + 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 { |
| + 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") |
| + } |
| + |
| + silence := loudnormFixture(t, "silence.stderr") |
| + i, tp, ok, err = parseLoudnorm(silence) |
| + if err != nil || ok || !math.IsInf(i, -1) || !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}, |
| + // 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}, |
| + {"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}, |
| + } { |
| + i, tp, ok, err := parseLoudnorm([]byte(c.tail)) |
| + if (err != nil) != c.err { |
| + t.Errorf("%s: err %v", c.name, err) |
| + continue |
| + } |
| + if c.err { |
| + continue |
| + } |
| + if ok != c.ok || (c.name != "nan" && (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") { |
| + t.Errorf("error %v", err) |
| + } |
| + } |
| +} |
| + |
| +// 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). |
| +func TestMeasureArgs(t *testing.T) { |
| + cfg := Config{Scratch: "/srv/scratch-7"} |
| + p := media.Payload{Preset: media.PresetAudioAAC, Limits: limitsFor(media.PresetAudioAAC)} |
| + p.Limits.GrantedMS = 90500 |
| + f := probeFacts{VideoIndex: -1, AudioIndex: 3, AudioCodec: "opus", Channels: 1, DurationMS: 90000} |
| + in := ffmpegInputArgs(cfg, "matroska") |
| + 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", |
| + "-f", "null", "-") |
| + got := measureArgs(cfg, f, p, "matroska", "mono") |
| + if !slices.Equal(got, want) { |
| + t.Errorf("\n got %q\nwant %q", got, want) |
| + } |
| + 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. |
| + 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]) |
| + measHead[slices.Index(measHead, "-loglevel")+1] = "error" |
| + 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]) |
| + } |
| + // Every other ffmpeg run stays at -loglevel error. |
| + for _, args := range [][]string{audioArgs(cfg, f, p, "matroska", 0), peaksArgs(cfg, f, p, "matroska", 0)} { |
| + if argAfter(args, "-loglevel") != "error" { |
| + t.Errorf("-loglevel %q", argAfter(args, "-loglevel")) |
| + } |
| + } |
| +} |
| + |
| +// TestMeasureLayoutMatchesTheEncode: whatever the channel count, 0 and |
| +// a negative one included, the pass measures the layout the encode |
| +// writes. |
| +func TestMeasureLayoutMatchesTheEncode(t *testing.T) { |
| + cfg := Config{Scratch: "/scratch"} |
| + p := media.Payload{Preset: media.PresetAudioAAC, Limits: limitsFor(media.PresetAudioAAC)} |
| + for _, ch := range []int{-1, 0, 1, 2, 6, 64} { |
| + f := probeFacts{VideoIndex: -1, AudioIndex: 0, AudioCodec: "flac", Channels: ch, DurationMS: 1000} |
| + 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," |
| + if !strings.HasPrefix(m, want) || !strings.HasPrefix(e, want) { |
| + t.Errorf("%d channels: measure %q, encode %q", ch, m, e) |
| + } |
| + if (ch == 1) != (layout == "mono") { |
| + t.Errorf("%d channels: %s", ch, layout) |
| + } |
| + } |
| +} |
diff --git a/internal/mediahandler/peaks.go b/internal/mediahandler/peaks.go| new file mode 100644 |
| index 000000000..d664189c0 |
| --- /dev/null |
| +++ b/internal/mediahandler/peaks.go |
| @@ -0,0 +1,167 @@ |
| +package mediahandler |
| + |
| +import ( |
| + "context" |
| + "encoding/binary" |
| + "errors" |
| + "io" |
| + "io/fs" |
| + "os" |
| + "path/filepath" |
| + "strconv" |
| + |
| + "github.com/carlosframework/platform/internal/media" |
| +) |
| + |
| +// audio-aac's waveform (spec §5.1): peaks.json holds peakCount values, |
| +// each the peak absolute amplitude of the normalised mono mix in one of |
| +// peakCount equal slices, scaled to 0..255. |
| +const peakCount = 1000 |
| + |
| +// peaksRate is the sample rate of the mono mix the peaks are read from. |
| +const peaksRate = "8000" |
| + |
| +// peaksRaw is the mix's file, under <scratch>/tmp: raw 16-bit |
| +// little-endian samples. |
| +const peaksRaw = "peaks.raw" |
| + |
| +// peaksArgs are the waveform's pass: the stream audioArgs encodes, with |
| +// the same strip, grant and gain, mixed to mono at peaksRate, as raw |
| +// 16-bit samples to <scratch>/tmp/peaks.raw (preflight F21). |
| +func peaksArgs(cfg Config, f probeFacts, p media.Payload, demuxer string, gainDB float64) []string { |
| + args := ffmpegInputArgs(cfg, demuxer) |
| + args = append(args, "-map", "0:"+strconv.Itoa(f.AudioIndex), "-vn") |
| + args = append(args, stripArgs(p)...) |
| + return append(args, |
| + "-af", "aformat=channel_layouts=mono:sample_rates="+peaksRate+","+volumeFilter(gainDB), |
| + "-f", "s16le", "-c:a", "pcm_s16le", filepath.Join(cfg.Scratch, "tmp", peaksRaw)) |
| +} |
| + |
| +// computePeaks reads samples 16-bit little-endian samples from r and |
| +// answers the peaks: slice i covers samples [i·N/1000, (i+1)·N/1000), |
| +// and its value is min(255, (max|s|·255 + 16383)/32767), the peak |
| +// rounded to the nearest of 0..255 (-32768 is 255); an empty slice (N |
| +// under 1,000) is 0. Fewer bytes than N samples, or a negative N, is |
| +// an error; nothing past N samples is read. Slice i's end, (i+1)·N/1000, |
| +// is computed only as i passes that many samples read, so it cannot |
| +// overflow on any file that exists (8 h at peaksRate is 230,400,000). |
| +func computePeaks(r io.Reader, samples int64) ([peakCount]uint8, error) { |
| + var out [peakCount]uint8 |
| + if samples < 0 { |
| + return out, errors.New("negative sample count") |
| + } |
| + level := func(peak int64) uint8 { return uint8(min(255, (peak*255+16383)/32767)) } |
| + buf := make([]byte, 64<<10) |
| + slice, end := 0, samples/peakCount // slice 0 is [0, N/1000) |
| + var peak, i int64 |
| + for i < samples { |
| + n := min(int64(len(buf)/2), samples-i) |
| + if _, err := io.ReadFull(r, buf[:2*n]); err != nil { |
| + return out, errors.New("fewer samples than the file's size") |
| + } |
| + for k := range n { |
| + s := int64(int16(binary.LittleEndian.Uint16(buf[2*k:]))) |
| + for i >= end && slice < peakCount-1 { |
| + out[slice], peak = level(peak), 0 |
| + slice++ |
| + end = int64(slice+1) * samples / peakCount |
| + } |
| + peak = max(peak, s, -s) |
| + i++ |
| + } |
| + } |
| + for ; slice < peakCount; slice++ { |
| + out[slice], peak = level(peak), 0 |
| + } |
| + return out, nil |
| +} |
| + |
| +// writePeaks writes peaks.json exactly: {"version":1,"duration_ms":N, |
| +// "peaks":[…]}, those keys in that order, no space, 1,000 integers. |
| +// durationMS is the converted duration (the handler's, plan 3 Task 6); |
| +// a negative one is an error. |
| +func writePeaks(w io.Writer, durationMS int64, p [peakCount]uint8) error { |
| + if durationMS < 0 { |
| + return errors.New("negative duration") |
| + } |
| + b := make([]byte, 0, 64+4*peakCount) |
| + b = append(b, `{"version":1,"duration_ms":`...) |
| + b = strconv.AppendInt(b, durationMS, 10) |
| + b = append(b, `,"peaks":[`...) |
| + for i, v := range p { |
| + if i > 0 { |
| + b = append(b, ',') |
| + } |
| + b = strconv.AppendUint(b, uint64(v), 10) |
| + } |
| + b = append(b, "]}"...) |
| + _, err := w.Write(b) |
| + return err |
| +} |
| + |
| +// makePeaks runs the waveform's pass (peaksArgs, with the job's gain) |
| +// and writes <scratch>/out/peaks.json for durationMS. Failures: |
| +// |
| +// - the run failing: as encode maps it; |
| +// - a run that exited 0 and left no peaks.raw: unreadable (it decoded |
| +// nothing); |
| +// - peaks.raw not a regular file (the child and every descendant are |
| +// dead, so nothing changes it after the Lstat, but it may have left |
| +// a link, even one to a file inside the scratch), unreadable to the |
| +// handler, or shorter than its size says; peaks.json not writable |
| +// or already there: engine_failed. |
| +// |
| +// peaks.raw is removed before the run (ffmpeg, never given -y, would |
| +// refuse to overwrite it) and after. |
| +func makePeaks(ctx context.Context, cfg Config, p media.Payload, demuxer string, f probeFacts, gainDB float64, durationMS int64) error { |
| + tmp, err := os.OpenRoot(filepath.Join(cfg.Scratch, "tmp")) |
| + if err != nil { |
| + return packageFailed(cfg, "the scratch tmp directory", err) |
| + } |
| + defer tmp.Close() |
| + if err := tmp.Remove(peaksRaw); err != nil && !errors.Is(err, fs.ErrNotExist) { |
| + return packageFailed(cfg, peaksRaw, err) |
| + } |
| + if err := encode(ctx, cfg, "peaks", peaksArgs(cfg, f, p, demuxer, gainDB)); err != nil { |
| + return err |
| + } |
| + defer func() { _ = tmp.Remove(peaksRaw) }() |
| + lfi, err := tmp.Lstat(peaksRaw) |
| + if errors.Is(err, fs.ErrNotExist) { |
| + // engine.encode.empty (pending Luna pass). |
| + cfg.Logf("codec: ffmpeg wrote no sample to %s", peaksRaw) |
| + return jobError{media.CodeUnreadable} |
| + } |
| + if err != nil { |
| + return packageFailed(cfg, peaksRaw, err) |
| + } |
| + if !lfi.Mode().IsRegular() { |
| + return packageFailed(cfg, peaksRaw, errors.New("not a regular file")) |
| + } |
| + raw, err := tmp.Open(peaksRaw) |
| + if err != nil { |
| + return packageFailed(cfg, peaksRaw, err) |
| + } |
| + defer raw.Close() |
| + peaks, err := computePeaks(raw, lfi.Size()/2) |
| + if err != nil { |
| + return packageFailed(cfg, peaksRaw, err) |
| + } |
| + out, err := os.OpenRoot(filepath.Join(cfg.Scratch, "out")) |
| + if err != nil { |
| + return packageFailed(cfg, "the output directory", err) |
| + } |
| + defer out.Close() |
| + w, err := out.OpenFile(audioNames[2], os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) |
| + if err != nil { |
| + return packageFailed(cfg, audioNames[2], err) |
| + } |
| + err = writePeaks(w, durationMS, peaks) |
| + if cerr := w.Close(); err == nil { |
| + err = cerr |
| + } |
| + if err != nil { |
| + return packageFailed(cfg, audioNames[2], err) |
| + } |
| + return nil |
| +} |
diff --git a/internal/mediahandler/peaks_test.go b/internal/mediahandler/peaks_test.go| new file mode 100644 |
| index 000000000..a992bfc05 |
| --- /dev/null |
| +++ b/internal/mediahandler/peaks_test.go |
| @@ -0,0 +1,265 @@ |
| +package mediahandler |
| + |
| +import ( |
| + "bytes" |
| + "encoding/binary" |
| + "encoding/json" |
| + "io" |
| + "math" |
| + "slices" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/media" |
| +) |
| + |
| +// s16le encodes samples as peaks.raw holds them. |
| +func s16le(samples []int16) []byte { |
| + b := make([]byte, 2*len(samples)) |
| + for i, s := range samples { |
| + binary.LittleEndian.PutUint16(b[2*i:], uint16(s)) |
| + } |
| + return b |
| +} |
| + |
| +// referencePeaks is computePeaks written the slow, obvious way: slice i |
| +// covers samples [i·N/1000, (i+1)·N/1000); its value is |
| +// min(255, (max|s|·255 + 16383)/32767); an empty slice is 0. |
| +func referencePeaks(samples []int16) [peakCount]uint8 { |
| + var out [peakCount]uint8 |
| + n := int64(len(samples)) |
| + for i := range int64(peakCount) { |
| + var m int64 |
| + for _, s := range samples[i*n/peakCount : (i+1)*n/peakCount] { |
| + m = max(m, abs64(int64(s))) |
| + } |
| + out[i] = uint8(min(255, (m*255+16383)/32767)) |
| + } |
| + return out |
| +} |
| + |
| +func abs64(v int64) int64 { |
| + if v < 0 { |
| + return -v |
| + } |
| + return v |
| +} |
| + |
| +// TestComputePeaksSlices: each slice's peak in equal slices of N. |
| +func TestComputePeaksSlices(t *testing.T) { |
| + check := func(name string, samples []int16, want [peakCount]uint8) { |
| + t.Helper() |
| + got, err := computePeaks(bytes.NewReader(s16le(samples)), int64(len(samples))) |
| + if err != nil { |
| + t.Fatalf("%s: %v", name, err) |
| + } |
| + if got != want { |
| + for i := range got { |
| + if got[i] != want[i] { |
| + t.Errorf("%s: slice %d is %d, want %d", name, i, got[i], want[i]) |
| + break |
| + } |
| + } |
| + } |
| + if ref := referencePeaks(samples); ref != got { |
| + t.Errorf("%s: differs from the reference", name) |
| + } |
| + } |
| + |
| + // A ramp over N = 1000: slice i is sample i alone, i·32: the value |
| + // is (i·32·255 + 16383)/32767, so 0 → 0, 2 (64: 32,703/32,767) → 0, |
| + // 3 (96: 40,863/32,767) → 1, 999 (31,968: 8,168,223/32,767) → 249. |
| + ramp := make([]int16, 1000) |
| + var want [peakCount]uint8 |
| + for i := range ramp { |
| + ramp[i] = int16(i * 32) |
| + want[i] = uint8((i*32*255 + 16383) / 32767) |
| + } |
| + if want[0] != 0 || want[2] != 0 || want[3] != 1 || want[999] != 249 { |
| + t.Fatalf("ramp arithmetic: %v %v %v %v", want[0], want[2], want[3], want[999]) |
| + } |
| + check("ramp, N = 1000", ramp, want) |
| + |
| + // N = 999: slice i covers [i·999/1000, (i+1)·999/1000), so slice 0 |
| + // is empty ([0, 0)) and slice i ≥ 1 holds sample i-1 alone. |
| + s999 := make([]int16, 999) |
| + for i := range s999 { |
| + s999[i] = 32767 |
| + } |
| + want = [peakCount]uint8{} |
| + for i := 1; i < peakCount; i++ { |
| + want[i] = 255 // (32767·255 + 16383)/32767 = 255 |
| + } |
| + check("N = 999, slice 0 empty", s999, want) |
| + |
| + // N = 3: slices 333, 666 and 999 each take one sample |
| + // (333·3/1000 = 0 to 334·3/1000 = 1, and so on); the rest are empty. |
| + want = [peakCount]uint8{} |
| + want[333], want[666], want[999] = 255, (16384*255+16383)/32767, 1 |
| + check("N = 3", []int16{-32767, 16384, 129}, want) |
| + |
| + // N = 2,500,000: 2,500 samples a slice. Each slice's one loud |
| + // sample sits at its last position, a slice boundary away from the |
| + // next slice's. |
| + big := make([]int16, 2_500_000) |
| + want = [peakCount]uint8{} |
| + for i := range peakCount { |
| + v := int16((i % 256) * 128) |
| + big[(i+1)*2500-1] = v |
| + big[i*2500] = -v / 2 |
| + want[i] = uint8(min(255, (int(v)*255+16383)/32767)) |
| + } |
| + check("N = 2,500,000", big, want) |
| + |
| + // All-zero silence: 1,000 zeros. |
| + check("silence", make([]int16, 48_000), [peakCount]uint8{}) |
| + // N = 0: 1,000 zeros. |
| + check("N = 0", nil, [peakCount]uint8{}) |
| + |
| + // -32768, whose magnitude is over int16's: 255, not a wrap. |
| + neg := make([]int16, 2000) |
| + neg[1234] = math.MinInt16 |
| + want = [peakCount]uint8{} |
| + want[617] = 255 // 1234 in [617·2, 618·2) |
| + check("a -32768 sample", neg, want) |
| +} |
| + |
| +// TestComputePeaksRefuses: fewer bytes than N samples (an N far past |
| +// them included) or a negative N is an error; bytes past N are not |
| +// read. |
| +func TestComputePeaksRefuses(t *testing.T) { |
| + if _, err := computePeaks(bytes.NewReader(make([]byte, 1999)), 1000); err == nil { |
| + t.Error("short by one byte: no error") |
| + } |
| + if _, err := computePeaks(bytes.NewReader(nil), -1); err == nil { |
| + t.Error("negative N: no error") |
| + } |
| + if _, err := computePeaks(strings.NewReader("\x01\x00"), math.MaxInt64); err == nil { |
| + t.Error("N of MaxInt64: no error") |
| + } |
| + r := bytes.NewReader(append(s16le([]int16{100, 200}), 0xff, 0x7f)) |
| + got, err := computePeaks(r, 2) |
| + if err != nil || got[999] != 2 || got[499] != 1 { |
| + t.Errorf("extra bytes: %v %v %v", got[499], got[999], err) |
| + } |
| + if r.Len() != 2 { |
| + t.Errorf("read %d bytes past N", 2-r.Len()) |
| + } |
| +} |
| + |
| +// FuzzComputePeaks: never panics; for any N within the bytes it agrees |
| +// with the reference; past them it is an error. |
| +func FuzzComputePeaks(f *testing.F) { |
| + f.Add([]byte{0x00, 0x80, 0xff, 0x7f}, int64(2)) |
| + f.Add(make([]byte, 3000), int64(1500)) |
| + f.Add([]byte{1}, int64(1)) |
| + f.Add([]byte{}, int64(0)) |
| + f.Fuzz(func(t *testing.T, b []byte, n int64) { |
| + got, err := computePeaks(bytes.NewReader(b), n) |
| + if n < 0 || n > int64(len(b)/2) { |
| + if err == nil { |
| + t.Fatalf("N %d over %d bytes: no error", n, len(b)) |
| + } |
| + return |
| + } |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + samples := make([]int16, n) |
| + for i := range samples { |
| + samples[i] = int16(binary.LittleEndian.Uint16(b[2*i:])) |
| + } |
| + if want := referencePeaks(samples); got != want { |
| + t.Fatalf("N %d: differs from the reference", n) |
| + } |
| + }) |
| +} |
| + |
| +// TestPeaksJSONShape: exactly {"version":1,"duration_ms":N,"peaks":[…]} |
| +// with the keys in that order and exactly 1,000 integers 0..255, within |
| +// peaks.json's 64 KiB bound. |
| +func TestPeaksJSONShape(t *testing.T) { |
| + var p [peakCount]uint8 |
| + for i := range p { |
| + p[i] = uint8(i * 7) |
| + } |
| + p[999] = 255 |
| + var b bytes.Buffer |
| + if err := writePeaks(&b, 90500, p); err != nil { |
| + t.Fatal(err) |
| + } |
| + s := b.String() |
| + if !strings.HasPrefix(s, `{"version":1,"duration_ms":90500,"peaks":[0,7,14,21,`) || !strings.HasSuffix(s, `,255]}`) { |
| + t.Errorf("shape %.80q … %q", s, s[len(s)-20:]) |
| + } |
| + dec := json.NewDecoder(strings.NewReader(s)) |
| + dec.UseNumber() |
| + var keys []string |
| + tok := func() json.Token { |
| + tk, err := dec.Token() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return tk |
| + } |
| + if tok() != json.Delim('{') { |
| + t.Fatal("not an object") |
| + } |
| + var peaks []json.Number |
| + for dec.More() { |
| + k := tok().(string) |
| + keys = append(keys, k) |
| + switch k { |
| + case "version", "duration_ms": |
| + tok() |
| + case "peaks": |
| + if err := dec.Decode(&peaks); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + } |
| + if !slices.Equal(keys, []string{"version", "duration_ms", "peaks"}) { |
| + t.Errorf("keys %q", keys) |
| + } |
| + if len(peaks) != 1000 { |
| + t.Fatalf("%d peaks", len(peaks)) |
| + } |
| + for i, n := range peaks { |
| + v, err := n.Int64() |
| + if err != nil || v != int64(p[i]) || strings.ContainsAny(n.String(), ".eE-") { |
| + t.Fatalf("peak %d: %s", i, n) |
| + } |
| + } |
| + // The worst case is far under the bound: 1,000 three-digit values |
| + // and the longest duration. |
| + for i := range p { |
| + p[i] = 255 |
| + } |
| + b.Reset() |
| + if err := writePeaks(&b, math.MaxInt64, p); err != nil || b.Len() > 64<<10 { |
| + t.Errorf("worst case %d bytes, %v", b.Len(), err) |
| + } |
| + if err := writePeaks(io.Discard, -1, p); err == nil { |
| + t.Error("a negative duration: no error") |
| + } |
| +} |
| + |
| +// TestPeaksArgs: the chosen audio stream, stripped and granted as the |
| +// encode is, mixed to mono at 8 kHz with the job's gain, as raw 16-bit |
| +// samples to <scratch>/tmp/peaks.raw (preflight F21). |
| +func TestPeaksArgs(t *testing.T) { |
| + cfg := Config{Scratch: "/srv/scratch-7"} |
| + p := media.Payload{Preset: media.PresetAudioAAC, Limits: limitsFor(media.PresetAudioAAC)} |
| + p.Limits.GrantedMS = 4000 |
| + f := probeFacts{VideoIndex: -1, AudioIndex: 1, AudioCodec: "aac", Channels: 6, DurationMS: 4000} |
| + want := append(ffmpegInputArgs(cfg, "mov"), |
| + "-map", "0:1", "-vn", "-sn", "-dn", "-map_metadata", "-1", "-map_chapters", "-1", "-t", "4.000", |
| + "-af", "aformat=channel_layouts=mono:sample_rates=8000,volume=-6.50dB", |
| + "-f", "s16le", "-c:a", "pcm_s16le", "/srv/scratch-7/tmp/peaks.raw") |
| + if got := peaksArgs(cfg, f, p, "mov", -6.5); !slices.Equal(got, want) { |
| + t.Errorf("\n got %q\nwant %q", got, want) |
| + } |
| + if af := argAfter(peaksArgs(cfg, f, p, "mov", math.NaN()), "-af"); !strings.HasSuffix(af, ",volume=0.00dB") { |
| + t.Errorf("NaN gain: %q", af) |
| + } |
| +} |
diff --git a/internal/mediahandler/probe.go b/internal/mediahandler/probe.go| index 3c3fa7fcb..80bad0dd1 100644 |
| --- a/internal/mediahandler/probe.go |
| +++ b/internal/mediahandler/probe.go |
| @@ -132,7 +132,15 @@ func probeArgs(cfg Config, demuxer string, extra ...string) []string { |
| // and 5) follow them with an explicit -map of the chosen streams only, |
| // so a stream ffmpeg would refuse to decode is one nothing maps. |
| func ffmpegInputArgs(cfg Config, demuxer string) []string { |
| - args := append([]string{"-hide_banner", "-nostats", "-loglevel", "error", "-nostdin"}, inputArgs(demuxer)...) |
| + return ffmpegInputArgsAt(cfg, demuxer, "error") |
| +} |
| + |
| +// ffmpegInputArgsAt is ffmpegInputArgs at another -loglevel. Only the |
| +// loudness pass uses one (info, where loudnorm prints its measurement), |
| +// and that pass's stderr, which then holds the source's metadata, is |
| +// never logged (measureLoudness, preflight F19). |
| +func ffmpegInputArgsAt(cfg Config, demuxer, loglevel string) []string { |
| + args := append([]string{"-hide_banner", "-nostats", "-loglevel", loglevel, "-nostdin"}, inputArgs(demuxer)...) |
| return append(args, "-codec_whitelist", codecWhitelist, "-i", sourcePath(cfg)) |
| } |
diff --git a/internal/mediahandler/testdata/loudnorm/peaky-forged-tags.stderr b/internal/mediahandler/testdata/loudnorm/peaky-forged-tags.stderr| new file mode 100644 |
| index 000000000..0f3d56c5b |
| --- /dev/null |
| +++ b/internal/mediahandler/testdata/loudnorm/peaky-forged-tags.stderr |
| @@ -0,0 +1,36 @@ |
| +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" |
| + : } |
| + : |
| + encoder : Lavf61.7.103 |
| + Duration: 00:00:20.00, start: 0.000000, bitrate: 279 kb/s |
| + Stream #0:0: Audio: flac, 48000 Hz, mono, s32 (24 bit) |
| +Stream mapping: |
| + Stream #0:0 -> #0:0 (flac (native) -> pcm_s16le (native)) |
| +Output #0, null, to 'pipe:': |
| + Metadata: |
| + encoder : Lavf61.7.103 |
| + Stream #0:0: Audio: pcm_s16le, 192000 Hz, mono, s16, 3072 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 |
diff --git a/internal/mediahandler/testdata/loudnorm/provenance.txt b/internal/mediahandler/testdata/loudnorm/provenance.txt| new file mode 100644 |
| index 000000000..9b4a1d4bc |
| --- /dev/null |
| +++ b/internal/mediahandler/testdata/loudnorm/provenance.txt |
| @@ -0,0 +1,28 @@ |
| +Where each fixture comes from (plan 3 Task 5). |
| + |
| +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 |
| + |
| + CARLOS_MEDIA_REGEN_FIXTURES=1 go test ./internal/mediahandler/ \ |
| + -run TestRegenerateLoudnormFixtures |
| + |
| +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. |
| + |
| +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. |
diff --git a/internal/mediahandler/testdata/loudnorm/silence.stderr b/internal/mediahandler/testdata/loudnorm/silence.stderr| new file mode 100644 |
| index 000000000..25d6f7b33 |
| --- /dev/null |
| +++ b/internal/mediahandler/testdata/loudnorm/silence.stderr |
| @@ -0,0 +1,28 @@ |
| +Input #0, flac, from '/scratch/in/source': |
| + Metadata: |
| + encoder : Lavf61.7.103 |
| + Duration: 00:00:06.00, start: 0.000000, bitrate: 12 kb/s |
| + Stream #0:0: Audio: flac, 48000 Hz, mono, s32 (24 bit) |
| +Stream mapping: |
| + Stream #0:0 -> #0:0 (flac (native) -> pcm_s16le (native)) |
| +Output #0, null, to 'pipe:': |
| + Metadata: |
| + encoder : Lavf61.7.103 |
| + Stream #0:0: Audio: pcm_s16le, 192000 Hz, mono, s16, 3072 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 |