forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB6f8f2a3Tahinli6 days ago3950 commits

aac_score.py111 lines, 4.0 KiBHistoryRawDownload
1#!/usr/bin/env python3
2"""Objective comparison of two AAC encodes of one reference clip.
3
4Usage:
5 aac_score.py <ref.f32le> <channels> <label>=<decoded.f32le>:<encoded.aac> [...]
6
7`ref.f32le` is the reference PCM (interleaved f32le, 48 kHz). Each decoded file is the
8same clip after decoding the encoder's output with ffmpeg. The decoder delay is removed
9per encoder by cross-correlating the mono mix over the first five seconds (lag 0..4096).
10
11Metrics, all over the aligned overlap, per channel then averaged:
12 snr_db global signal-to-error ratio, 10 log10(sum ref^2 / sum err^2).
13 segsnr_db mean of per-frame SNR over 2048-sample frames, each clipped to [-10, 35] dB.
14 nsr_db band noise-to-signal proxy for NMR: STFT (2048 Hann, hop 2048), 20 log-spaced
15 bands from 100 Hz to 20 kHz, per-band 10 log10(noise / signal), clipped to
16 [-40, 10] dB, averaged over frames and bands. Lower is better. It has no
17 psychoacoustic masking threshold, so it is a proxy, not a standard NMR.
18 kbps encoded size over the reference duration, ADTS headers included.
19"""
20
21import sys
22
23import numpy as np
24
25FRAME = 2048
26BANDS = np.geomspace(100.0, 20000.0, 21)
27
28
29def load(path, channels):
30 x = np.fromfile(path, dtype="<f4")
31 n = len(x) // channels
32 return x[: n * channels].reshape(n, channels).astype(np.float64)
33
34
35def align(ref, dec):
36 """Lag (samples, >= 0) that best matches dec to ref on the first five seconds."""
37 span = min(len(ref), len(dec), 5 * 48000)
38 max_lag = min(4096, len(dec) - span)
39 a = ref[:span].mean(axis=1)
40 b = dec[: span + max_lag].mean(axis=1)
41 size = 1 << int(np.ceil(np.log2(len(b) + span)))
42 corr = np.fft.irfft(np.fft.rfft(b, size) * np.conj(np.fft.rfft(a, size)), size)
43 lags = corr[: max_lag + 1]
44 return int(np.argmax(lags))
45
46
47def metrics(ref, dec):
48 lag = align(ref, dec)
49 n = min(len(ref), len(dec) - lag)
50 r = ref[:n]
51 d = dec[lag : lag + n]
52 snr, segs, nsr = [], [], []
53 window = np.hanning(FRAME)
54 freqs = np.fft.rfftfreq(FRAME, 1.0 / 48000)
55 edges = np.searchsorted(freqs, BANDS)
56 for c in range(r.shape[1]):
57 rc, dc = r[:, c], d[:, c]
58 err = rc - dc
59 snr.append(10 * np.log10(max(np.sum(rc**2), 1e-20) / max(np.sum(err**2), 1e-20)))
60 frames = n // FRAME
61 rf = rc[: frames * FRAME].reshape(frames, FRAME)
62 ef = err[: frames * FRAME].reshape(frames, FRAME)
63 pr = np.sum(rf**2, axis=1)
64 pe = np.sum(ef**2, axis=1)
65 keep = pr > 1e-10
66 seg = 10 * np.log10(np.maximum(pr[keep], 1e-20) / np.maximum(pe[keep], 1e-20))
67 segs.append(np.mean(np.clip(seg, -10, 35)))
68 R = np.abs(np.fft.rfft(rf * window, axis=1)) ** 2
69 E = np.abs(np.fft.rfft(ef * window, axis=1)) ** 2
70 rows = []
71 for b in range(len(BANDS) - 1):
72 lo, hi = edges[b], max(edges[b + 1], edges[b] + 1)
73 s = np.sum(R[:, lo:hi], axis=1)
74 e = np.sum(E[:, lo:hi], axis=1)
75 rows.append(10 * np.log10(np.maximum(e, 1e-20) / np.maximum(s, 1e-20)))
76 nsr.append(np.mean(np.clip(np.array(rows), -40, 10)))
77 return {
78 "lag": lag,
79 "snr_db": float(np.mean(snr)),
80 "segsnr_db": float(np.mean(segs)),
81 "nsr_db": float(np.mean(nsr)),
82 }
83
84
85def main(argv):
86 if len(argv) < 4:
87 print(__doc__, file=sys.stderr)
88 return 2
89 ref_path, channels = argv[1], int(argv[2])
90 ref = load(ref_path, channels)
91 duration = len(ref) / 48000.0
92 for spec in argv[3:]:
93 label, rest = spec.split("=", 1)
94 dec_path, enc_path = rest.split(":", 1)
95 m = metrics(ref, load(dec_path, channels))
96 kbps = os_size(enc_path) * 8 / duration / 1000.0
97 print(
98 f"{label} lag={m['lag']} snr={m['snr_db']:.2f} segsnr={m['segsnr_db']:.2f} "
99 f"nsr={m['nsr_db']:.2f} kbps={kbps:.2f}"
100 )
101 return 0
102
103
104def os_size(path):
105 import os
106
107 return os.path.getsize(path)
108
109
110if __name__ == "__main__":
111 sys.exit(main(sys.argv))