diff --git a/CLAUDE.md b/CLAUDE.md index 471bce8..93f585e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -815,8 +815,29 @@ Two independent apps that talk over HTTP: target; up and down, a raise stopping at the TRUE-PEAK ceiling (outcome `capped`, `short_by`); a peak already over the ceiling at/below target is left alone (`hot_peak_left`); MP3 in whole steps of 2^(1/4) (1.505 dB), - rounding a raise DOWN under the ceiling; ALAC/AAC/Ogg `unsupported` (AAC - is Phase 5). `core/level_edit.py` writes a NEW file: MP3 by the lossless + rounding a raise DOWN under the ceiling — and AAC (`.m4a`/`.mp4`, stem + files) in the SAME steps; Ogg/Opus/WMA `unsupported`. **AAC-LC by + `core/aac_gain.py`** (aacgain's edit, decided 2026-10-19 after a spike): + every channel's 8-bit `global_gain` +n scales the decode by exactly + 2^(n/4) (scalefactors and PNS energies are coded from it, intensity is a + ratio). Finding a channel pair's second `global_gain` means WALKING the + first channel — section data, scalefactors, pulse, TNS and the Huffman + spectrum (codeword lengths, plus the unsigned books' sign bits and book + 11's escapes) — with the standard's codebooks in `core/aac_tables.py` + (GENERATED from FFmpeg n7.1 `aactab.c`, every book checked a complete + prefix code; do not hand-edit), in numba (~1 s per five-stream stem + file). The MP4 side follows `stsz`/`stsc`/`stco|co64` to every frame of + EVERY audio track, so a stem file's five streams move alike. Proof per + frame: a raw_data_block must end in its last byte, else the file is + refused; refused too: HE-AAC/SBR/PS (the ASC, implicit SBR, an SBR FIL), + LTP/Main/SSR, 960-sample frames, CCE/PCE, scalefactors out of range. No + undo tag (one would grow `moov`); the edit is exactly reversed by the + opposite steps. Spike: exact (<= 1e-6 of peak) on every stream of FFmpeg + and Apple M4As, generated and 44 commercial stem files, and PNS / + intensity / M/S / TNS / mono / 22-48 kHz edge cases. `level_edit.verify` + decodes EVERY audio stream. Because only the file can say "HE-AAC", the + export copies such a file UNLEVELLED (gain 0, its auto gain from the + source) rather than failing. `core/level_edit.py` writes a NEW file: MP3 by the lossless frame-gain edit (mp3gain's `global_gain`, CRC-16 recomputed on protected frames, the Xing/Info/VBRI frame untouched, mp3gain's APEv2 `MP3GAIN_UNDO`/`MINMAX` tag, accumulating); WAV/AIFF scaled IN their @@ -1663,8 +1684,17 @@ serialization path.** It enforces: their size and every other chunk byte-identical, 24-bit rounded not dithered, 16-bit dithered reproducibly; FLAC 16/24 keeps depth, rate, tags and picture. +- `test_aac_gain.py` — the AAC-LC edit on GENERATED files (FFmpeg stereo / + mono / 48 / 22.05 kHz, 48 kb/s with PNS + intensity + M/S, TNS; Apple + `aac_at` where present): every frame walked, the decode exact at -2/+3 + steps, same size, only global_gain bytes differ; a generated stem file's + five streams alike, the opposite steps restoring it byte for byte; + `level_edit` applying and verifying it, and catching one stream at another + level; refusals leaving nothing (HE-AAC, ALAC, out-of-range steps, an + existing target, a non-step gain); and the user's kit 4 / kit 5 / Kit Bulk + files when present. - `test_normalize.py` — through the routes on temp collections pointed at - generated MP3/FLAC/WAV: unmeasured tracks counted to measure first; MP3 + generated MP3/FLAC/WAV/M4A: unmeasured tracks counted to measure first; MP3 gains whole steps; a raise held by the ceiling; the preview's lossless count; the run = the preview, the SAVED collection untouched, each file at its own path = the original at the gain with the original parked unchanged, @@ -1687,7 +1717,9 @@ serialization path.** It enforces: options; a same-level re-export keeps every file (same inodes); a new target re-writes only the copy whose gain changed; Normalise off restores the source bytes with the gain from the source's LUFS; Auto gain off writes - none; a levelled copy has its own waveform-cache key. + none; a levelled copy has its own waveform-cache key; and a file that + cannot be levelled (as HE-AAC) is copied unchanged at gain 0 without + failing the export. - `test_auto_hotcues.py` — Auto Hotcues in three layers: `structure.analyse` on SYNTHETIC audio with known sections (the intro with a kick is not a drop; no breakdown after the last drop), `plan`'s outcomes and beat-counted offsets diff --git a/backend/konduktor/core/aac_gain.py b/backend/konduktor/core/aac_gain.py new file mode 100644 index 0000000..90b3fda --- /dev/null +++ b/backend/konduktor/core/aac_gain.py @@ -0,0 +1,654 @@ +"""Lossless gain for AAC-LC in an MP4 (an `.m4a`, a stem file): aacgain's edit. + +Every channel of every AAC frame carries an 8-bit `global_gain`, the start of +its scalefactors: the decoder scales that channel's spectrum by 2^(g/4), so +adding n to every `global_gain` scales the decoded audio by EXACTLY 2^(n/4) +(1.505 dB per step) with no re-encode — like MP3's frame-gain edit +(`level_edit`), and in the same steps. Spectral scalefactors, the noise +energies of PNS and the intensity positions are all coded RELATIVE to it (the +first two from it, intensity as a ratio between channels), so they follow. + +Finding the field is the hard part: a channel pair holds the SECOND channel's +`global_gain` after the whole first channel — its section data, scalefactors, +TNS and Huffman-coded spectrum — so each frame is WALKED, never decoded: +codewords are looked up only for their lengths (and, in the unsigned books, +the values that decide sign bits and escapes). `aac_tables` holds the +standard's codebooks. The walk runs in numba (a dependency already, through +librosa): ~10 M codewords for a stereo track. + +The walk proves itself on every frame: a raw_data_block must end in its last +byte (an END element, then byte alignment), so a mis-parse is caught, and the +whole file is refused, rather than written. `level_edit.verify` decodes the +result on top. What is refused (`AacGainError`): anything but AAC-LC +(HE-AAC/SBR, PS, LTP, Main, SSR), 960-sample frames, a coupling channel or a +program config element, a scalefactor pushed out of 0..255. + +Measured 2026-10-19 on FFmpeg- and Apple-encoded files and commercial stem +files (`test_aac_gain.py`, and the spike numbers in the gain discussion). +""" +from __future__ import annotations + +import struct +from dataclasses import dataclass +from pathlib import Path + +import numpy as np + +from . import aac_tables as T + +#: A stem file's streams all share one ladder: one step = 2^(1/4) in amplitude. +STEP_DB = 20.0 * np.log10(2.0 ** 0.25) + + +class AacGainError(ValueError): + """A file this edit will not touch; the message is user-facing.""" + + +# ---- the MP4 side: where every AAC frame of every audio track is ------------------ + +@dataclass +class AacTrack: + """One audio track: its config and each frame's byte range in the file.""" + + index: int # the audio stream's order among the file's audio tracks + object_type: int # 2 = AAC-LC + sf_index: int + channels: int + offsets: np.ndarray # int64, each sample's file offset + sizes: np.ndarray # int64 + + +_CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"udta"} + + +def _boxes(data: bytes, start: int, end: int): + pos = start + while pos + 8 <= end: + size, kind = struct.unpack_from(">I4s", data, pos) + head = 8 + if size == 1: + size = struct.unpack_from(">Q", data, pos + 8)[0] + head = 16 + elif size == 0: + size = end - pos + if size < head or pos + size > end: + raise AacGainError("not an MP4 file this edit can read (a broken box)") + yield kind, pos + head, pos + size + pos += size + + +def _find(data: bytes, start: int, end: int, kind: bytes): + for k, s, e in _boxes(data, start, end): + if k == kind: + return s, e + return None + + +def _descriptor(data: bytes, pos: int) -> tuple[int, int, int]: + """(tag, body start, body end) of an MPEG-4 descriptor at `pos`.""" + tag = data[pos] + pos += 1 + size = 0 + for _ in range(4): + b = data[pos] + pos += 1 + size = (size << 7) | (b & 0x7F) + if not b & 0x80: + break + return tag, pos, pos + size + + +def _audio_specific_config(data: bytes, s: int, e: int) -> tuple[int, int, int, bool]: + """(object type, sampling-frequency index, channel config, has SBR) from + an `esds` box body (version/flags first).""" + tag, ds, de = _descriptor(data, s + 4) + if tag != 3: + raise AacGainError("an MP4 audio track without an ES descriptor") + pos = ds + 2 + flags = data[pos] + pos += 1 + if flags & 0x80: + pos += 2 + if flags & 0x40: + pos += 1 + data[pos] + if flags & 0x20: + pos += 2 + while pos < de: + tag, bs, be = _descriptor(data, pos) + if tag == 4: # DecoderConfigDescriptor + if data[bs] != 0x40: + raise AacGainError("not an AAC track") + p = bs + 13 + while p < be: + t2, s2, e2 = _descriptor(data, p) + if t2 == 5: + return _parse_asc(data[s2:e2]) + p = e2 + pos = be + raise AacGainError("an AAC track with no AudioSpecificConfig") + + +def _parse_asc(asc: bytes) -> tuple[int, int, int, bool]: + bits = int.from_bytes(asc, "big") + n = len(asc) * 8 + pos = 0 + + def read(k: int) -> int: + nonlocal pos + v = (bits >> (n - pos - k)) & ((1 << k) - 1) + pos += k + return v + + aot = read(5) + if aot == 31: + aot = 32 + read(6) + sfi = read(4) + if sfi == 15: + freq = read(24) + rates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350] + sfi = min(range(len(rates)), key=lambda i: abs(rates[i] - freq)) + channels = read(4) + sbr = aot in (5, 29) + if aot == 2: + frame_length_flag = read(1) + if frame_length_flag: + raise AacGainError("AAC with 960-sample frames is not handled") + if read(1): # dependsOnCoreCoder + read(14) + read(1) # extensionFlag + # Implicit SBR signalling (a sync extension after the GA config) = HE-AAC. + if n - pos >= 16 and read(11) == 0x2B7 and read(5) == 5 and n - pos >= 1 and read(1): + sbr = True + return aot, sfi, channels, sbr + + +def tracks(path: Path | str) -> list[AacTrack]: + """Every audio track's AAC frames, in the file's audio-stream order.""" + data = Path(path).read_bytes() + moov = _find(data, 0, len(data), b"moov") + if moov is None: + raise AacGainError("not an MP4 file") + out = [] + for kind, ts, te in _boxes(data, *moov): + if kind != b"trak": + continue + mdia = _find(data, ts, te, b"mdia") + hdlr = _find(data, *mdia, b"hdlr") if mdia else None + if hdlr is None or data[hdlr[0] + 8:hdlr[0] + 12] != b"soun": + continue + stbl = _find(data, *_find(data, *mdia, b"minf"), b"stbl") + stsd = _find(data, *stbl, b"stsd") + entry = stsd[0] + 8 + esize, ekind = struct.unpack_from(">I4s", data, entry) + if ekind != b"mp4a": + raise AacGainError(f"an audio track in {ekind.decode('latin-1')}, not AAC") + esds = _find(data, entry + 36, entry + esize, b"esds") + if esds is None: + raise AacGainError("an AAC track with no esds") + aot, sfi, channels, sbr = _audio_specific_config(data, *esds) + if aot != 2 or sbr: + raise AacGainError("only AAC-LC can be changed losslessly (this is HE-AAC or another profile)") + stsz = _find(data, *stbl, b"stsz") + uniform, count = struct.unpack_from(">II", data, stsz[0] + 4) + sizes = (np.full(count, uniform, np.int64) if uniform else + np.frombuffer(data, ">u4", count, stsz[0] + 12).astype(np.int64)) + co = _find(data, *stbl, b"stco") + if co is not None: + n = struct.unpack_from(">I", data, co[0] + 4)[0] + chunks = np.frombuffer(data, ">u4", n, co[0] + 8).astype(np.int64) + else: + co = _find(data, *stbl, b"co64") + n = struct.unpack_from(">I", data, co[0] + 4)[0] + chunks = np.frombuffer(data, ">u8", n, co[0] + 8).astype(np.int64) + stsc = _find(data, *stbl, b"stsc") + m = struct.unpack_from(">I", data, stsc[0] + 4)[0] + runs = np.frombuffer(data, ">u4", m * 3, stsc[0] + 8).reshape(m, 3).astype(np.int64) + offsets = np.empty(count, np.int64) + i = 0 + for r in range(m): + first = runs[r, 0] - 1 + last = (runs[r + 1, 0] - 1) if r + 1 < m else len(chunks) + per = runs[r, 1] + for c in range(first, last): + pos = chunks[c] + for _ in range(per): + if i >= count: + break + offsets[i] = pos + pos += sizes[i] + i += 1 + if i != count: + raise AacGainError("an MP4 sample table this edit cannot follow") + out.append(AacTrack(len(out), aot, sfi, channels, offsets, sizes)) + if not out: + raise AacGainError("no AAC audio track") + return out + + +# ---- the walk --------------------------------------------------------------------- + +def _lut(codes, bits, width: int) -> np.ndarray: + """A lookup on the next `width` bits: (length << 16) | index, 0 = invalid.""" + lut = np.zeros(1 << width, np.int32) + for idx, (c, b) in enumerate(zip(codes, bits)): + lo = c << (width - b) + lut[lo:lo + (1 << (width - b))] = (b << 16) | idx + return lut + + +_SPEC = np.stack([_lut(c, b, 16) for c, b in T.SPECTRAL]) +_SF = _lut(T.SF_CODES, T.SF_BITS, 19) +_LONG = np.zeros((13, 64), np.int32) +_SHORT = np.zeros((13, 32), np.int32) +_NLONG = np.zeros(13, np.int32) +_NSHORT = np.zeros(13, np.int32) +for _i in range(13): + _LONG[_i, :len(T.SWB_LONG[_i])] = T.SWB_LONG[_i] + _SHORT[_i, :len(T.SWB_SHORT[_i])] = T.SWB_SHORT[_i] + _NLONG[_i] = len(T.SWB_LONG[_i]) - 1 + _NSHORT[_i] = len(T.SWB_SHORT[_i]) - 1 + +try: + from numba import njit +except ImportError: # pragma: no cover — numba ships with librosa + def njit(*_a, **_k): + return lambda f: f + + +@njit(cache=True) +def _read(buf, pos, n): + v = 0 + for i in range(n): + p = pos + i + v = (v << 1) | ((buf[p >> 3] >> (7 - (p & 7))) & 1) + return v + + +@njit(cache=True) +def _peek(buf, pos, n, end): + v = 0 + for i in range(n): + p = pos + i + bit = 0 + if p < end: + bit = (buf[p >> 3] >> (7 - (p & 7))) & 1 + v = (v << 1) | bit + return v + + +@njit(cache=True) +def _walk(buf, offsets, sizes, sfi, spec, sflut, long_swb, short_swb, nlong, nshort): + """Every frame's global_gain bit positions; out[0] = status (0 ok, else the + failing frame + 1, negated by reason), plus the scalefactor range.""" + n_frames = offsets.shape[0] + gpos = np.empty(n_frames * 8, np.int64) + ng = 0 + sf_lo = 1 << 30 + sf_hi = -(1 << 30) + nz_lo = 1 << 30 + nz_hi = -(1 << 30) + sfb_cb = np.zeros((8, 64), np.int32) + group_len = np.zeros(8, np.int32) + status = 0 + for f in range(n_frames): + start = offsets[f] * 8 + end = start + sizes[f] * 8 + pos = start + ok = True + common_ws = 0 + common_max_sfb = 0 + common_groups = 0 + while ok: + if pos + 3 > end: + ok = False + break + elem = _read(buf, pos, 3) + pos += 3 + if elem == 7: # END + break + if elem == 0 or elem == 3 or elem == 1: # SCE, LFE, CPE + pos += 4 # element_instance_tag + n_ch = 1 + common = 0 + if elem == 1: + n_ch = 2 + common = _read(buf, pos, 1) + pos += 1 + if common: + _r = _read(buf, pos, 1) # reserved + common_ws = _read(buf, pos + 1, 2) + pos += 4 + if common_ws == 2: + common_max_sfb = _read(buf, pos, 4) + grouping = _read(buf, pos + 4, 7) + pos += 11 + common_groups = 1 + group_len[:] = 0 + group_len[0] = 1 + for b in range(6, -1, -1): + if (grouping >> b) & 1: + group_len[common_groups - 1] += 1 + else: + group_len[common_groups] = 1 + common_groups += 1 + else: + common_max_sfb = _read(buf, pos, 6) + pos += 6 + if _read(buf, pos, 1): # predictor data (not LC) + status = -(f + 1) + return gpos[:0], status, 0, 0, 0, 0 + pos += 1 + common_groups = 1 + group_len[0] = 1 + ms = _read(buf, pos, 2) + pos += 2 + if ms == 1: + pos += common_groups * common_max_sfb + for ch in range(n_ch): + gpos[ng] = pos + ng += 1 + gg = _read(buf, pos, 8) + pos += 8 + if common: + ws = common_ws + max_sfb = common_max_sfb + groups = common_groups + else: + pos += 1 + ws = _read(buf, pos, 2) + pos += 3 + if ws == 2: + max_sfb = _read(buf, pos, 4) + grouping = _read(buf, pos + 4, 7) + pos += 11 + groups = 1 + group_len[:] = 0 + group_len[0] = 1 + for b in range(6, -1, -1): + if (grouping >> b) & 1: + group_len[groups - 1] += 1 + else: + group_len[groups] = 1 + groups += 1 + else: + max_sfb = _read(buf, pos, 6) + pos += 6 + if _read(buf, pos, 1): + status = -(f + 1) + return gpos[:0], status, 0, 0, 0, 0 + pos += 1 + groups = 1 + group_len[0] = 1 + short = ws == 2 + nswb = nshort[sfi] if short else nlong[sfi] + if max_sfb > nswb: + ok = False + break + # section_data + sbits = 3 if short else 5 + esc = (1 << sbits) - 1 + for g in range(groups): + k = 0 + while k < max_sfb: + cb = _read(buf, pos, 4) + pos += 4 + if cb == 12: + ok = False + break + length = 0 + while True: + inc = _read(buf, pos, sbits) + pos += sbits + length += inc + if inc != esc: + break + if pos > end: + break + if k + length > max_sfb or pos > end: + ok = False + break + for s in range(k, k + length): + sfb_cb[g, s] = cb + k += length + if not ok: + break + if not ok: + break + # scale_factor_data + sf = gg + noise = gg - 90 + noise_first = True + for g in range(groups): + for s in range(max_sfb): + cb = sfb_cb[g, s] + if cb == 0: + continue + if cb == 13 and noise_first: + noise_first = False + noise += _read(buf, pos, 9) - 256 + pos += 9 + if noise < nz_lo: + nz_lo = noise + if noise > nz_hi: + nz_hi = noise + continue + e = sflut[_peek(buf, pos, 19, end)] + if e == 0: + ok = False + break + pos += e >> 16 + delta = (e & 0xFFFF) - 60 + if cb == 13: + noise += delta + if noise < nz_lo: + nz_lo = noise + if noise > nz_hi: + nz_hi = noise + elif cb == 14 or cb == 15: + pass # intensity: relative between channels + else: + sf += delta + if sf < sf_lo: + sf_lo = sf + if sf > sf_hi: + sf_hi = sf + if not ok: + break + if not ok: + break + # pulse_data + if _read(buf, pos, 1): + pos += 1 + if short: + ok = False + break + npulse = _read(buf, pos, 2) + pos += 8 + (npulse + 1) * 9 + else: + pos += 1 + # tns_data + if _read(buf, pos, 1): + pos += 1 + nwin = 8 if short else 1 + for w in range(nwin): + nfilt = _read(buf, pos, 1 if short else 2) + pos += 1 if short else 2 + if nfilt: + res = _read(buf, pos, 1) + pos += 1 + for _q in range(nfilt): + pos += 4 if short else 6 + order = _read(buf, pos, 3 if short else 5) + pos += 3 if short else 5 + if order: + pos += 1 + compress = _read(buf, pos, 1) + pos += 1 + pos += order * (3 + res - compress) + else: + pos += 1 + # gain_control_data (SSR only) + if _read(buf, pos, 1): + ok = False + break + pos += 1 + # spectral_data + for g in range(groups): + glen = group_len[g] + for s in range(max_sfb): + cb = sfb_cb[g, s] + if cb == 0 or cb >= 13: + continue + if short: + width = short_swb[sfi, s + 1] - short_swb[sfi, s] + else: + width = long_swb[sfi, s + 1] - long_swb[sfi, s] + dim = 4 if cb <= 4 else 2 + n_words = glen * width // dim + for _w in range(n_words): + e = spec[cb - 1, _peek(buf, pos, 16, end)] + if e == 0: + ok = False + break + pos += e >> 16 + idx = e & 0xFFFF + if cb == 3 or cb == 4: + v0 = idx // 27 + v1 = (idx // 9) % 3 + v2 = (idx // 3) % 3 + v3 = idx % 3 + pos += (v0 != 0) + (v1 != 0) + (v2 != 0) + (v3 != 0) + elif cb >= 7: + mod = 8 if cb <= 8 else (13 if cb <= 10 else 17) + y = idx // mod + z = idx % mod + pos += (y != 0) + (z != 0) + if cb == 11: + for v in (y, z): + if v == 16: + nesc = 0 + while _read(buf, pos, 1) == 1: + pos += 1 + nesc += 1 + if nesc > 8: + break + pos += 1 + if nesc > 8: + ok = False + break + pos += nesc + 4 + if pos > end or not ok: + ok = False + break + if not ok: + break + if not ok: + break + if not ok: + break + if not ok: + break + elif elem == 4: # DSE + pos += 4 + align = _read(buf, pos, 1) + pos += 1 + count = _read(buf, pos, 8) + pos += 8 + if count == 255: + count += _read(buf, pos, 8) + pos += 8 + if align: + pos = start + ((pos - start + 7) // 8) * 8 + pos += count * 8 + elif elem == 6: # FIL + count = _read(buf, pos, 4) + pos += 4 + if count == 15: + count += _read(buf, pos, 8) - 1 + pos += 8 + if count > 0: + ext = _read(buf, pos, 4) + if ext == 13 or ext == 14: # SBR: HE-AAC + status = -(f + 1) + return gpos[:0], status, 0, 0, 0, 0 + pos += count * 8 + else: # CCE, PCE: not handled + ok = False + break + if pos > end: + ok = False + # The block must end in its last byte: END, then byte alignment. + if not ok or pos > end or end - pos >= 8: + status = f + 1 + return gpos[:0], status, 0, 0, 0, 0 + return gpos[:ng], 0, sf_lo, sf_hi, nz_lo, nz_hi + + +@dataclass +class Scan: + """Where every global_gain is, per audio track, and how far it may move.""" + + tracks: list[AacTrack] + positions: list[np.ndarray] # bit offsets in the file, per track + min_step: int # the most negative n every track allows + max_step: int + + +def scan(path: Path | str) -> Scan: + path = Path(path) + found = tracks(path) + buf = np.frombuffer(path.read_bytes(), np.uint8) + positions = [] + lo_all, hi_all = -255, 255 + for t in found: + if t.sf_index > 12: + raise AacGainError("an AAC sampling rate this edit does not know") + gpos, status, sf_lo, sf_hi, nz_lo, nz_hi = _walk( + buf, t.offsets, t.sizes, t.sf_index, _SPEC, _SF, _LONG, _SHORT, _NLONG, _NSHORT) + if status < 0: + raise AacGainError("only AAC-LC can be changed losslessly (this frame uses another tool)") + if status > 0: + raise AacGainError(f"an AAC frame this edit cannot follow (frame {status - 1} of stream {t.index})") + g = _read_all(buf, gpos) + if gpos.size: + lo_all = max(lo_all, -int(g.min()), -int(sf_lo) if sf_lo < (1 << 29) else -255) + hi_all = min(hi_all, 255 - int(g.max()), 255 - int(sf_hi) if sf_hi > -(1 << 29) else 255) + if nz_lo < (1 << 29): + lo_all = max(lo_all, -155 - int(nz_lo)) + hi_all = min(hi_all, 100 - int(nz_hi)) + positions.append(gpos) + return Scan(found, positions, lo_all, hi_all) + + +def _read_all(buf: np.ndarray, gpos: np.ndarray) -> np.ndarray: + """The 8-bit values at each position (vectorised: a 16-bit window).""" + byte = gpos >> 3 + shift = gpos & 7 + word = (buf[byte].astype(np.int64) << 8) | buf[np.minimum(byte + 1, buf.size - 1)].astype(np.int64) + return (word >> (8 - shift)) & 0xFF + + +def apply(src: Path | str, dst: Path | str, steps: int, scanned: Scan | None = None) -> None: + """Write `src` with every audio track's frames `steps` gain steps louder + (negative: quieter) to `dst`, which must not exist. Same size, every byte + outside the global_gain fields identical.""" + src, dst = Path(src), Path(dst) + if dst.exists(): + raise AacGainError(f"{dst.name} already exists") + found = scanned or scan(src) + if not found.min_step <= steps <= found.max_step: + raise AacGainError(f"{steps:+d} steps would take the AAC scalefactors out of range") + data = np.frombuffer(src.read_bytes(), np.uint8).copy() + for gpos in found.positions: + values = _read_all(data, gpos) + steps + byte = gpos >> 3 + shift = gpos & 7 + hi_mask = 0xFF >> shift # the field's bits in the first byte + lo_mask = (0xFF << (8 - shift)) & 0xFF # …and in the second + first = (values >> shift) & 0xFF + second = (values << (8 - shift)) & 0xFF + data[byte] = (data[byte] & ~hi_mask & 0xFF) | (first & hi_mask) + nxt = byte + 1 + has = shift > 0 + data[nxt[has]] = (data[nxt[has]] & ~lo_mask[has] & 0xFF) | (second[has] & lo_mask[has]) + dst.write_bytes(data.tobytes()) diff --git a/backend/konduktor/core/aac_tables.py b/backend/konduktor/core/aac_tables.py new file mode 100644 index 0000000..d42f079 --- /dev/null +++ b/backend/konduktor/core/aac_tables.py @@ -0,0 +1,301 @@ +"""The AAC-LC bitstream tables `aac_gain` needs to WALK a raw_data_block +(never to decode audio): the eleven spectral Huffman codebooks and the +scalefactor codebook of ISO/IEC 14496-3 (subpart 4, Annex 4.A), and the +scalefactor-band offsets per sampling-frequency index. + +Generated, not hand-typed: extracted from FFmpeg n7.1 `libavcodec/aactab.c` +(LGPL-2.1-or-later; the values are the standard's own) on 2026-10-19, and +checked when generated that every codebook is a complete prefix code (Kraft +sum exactly 1) with no duplicate codewords. Do not edit by hand. +""" + +CODES1 = ( + 2040, 497, 2045, 1013, 104, 1008, 2039, 492, 2037, 1009, 114, 1012, 116, 17, 118, 491, + 108, 1014, 2044, 481, 2033, 496, 97, 502, 2034, 490, 2043, 498, 105, 493, 119, 23, + 111, 486, 100, 485, 103, 21, 98, 18, 0, 20, 101, 22, 109, 489, 99, 484, + 107, 19, 113, 483, 112, 499, 2046, 487, 2035, 495, 96, 494, 2032, 482, 2042, 1011, + 106, 488, 117, 16, 115, 500, 110, 1015, 2038, 480, 2041, 1010, 102, 501, 2047, 503, + 2036, +) +BITS1 = ( + 11, 9, 11, 10, 7, 10, 11, 9, 11, 10, 7, 10, 7, 5, 7, 9, + 7, 10, 11, 9, 11, 9, 7, 9, 11, 9, 11, 9, 7, 9, 7, 5, + 7, 9, 7, 9, 7, 5, 7, 5, 1, 5, 7, 5, 7, 9, 7, 9, + 7, 5, 7, 9, 7, 9, 11, 9, 11, 9, 7, 9, 11, 9, 11, 10, + 7, 9, 7, 5, 7, 9, 7, 10, 11, 9, 11, 10, 7, 9, 11, 9, + 11, +) +CODES2 = ( + 499, 111, 509, 235, 35, 234, 503, 232, 506, 242, 45, 112, 32, 6, 43, 110, + 40, 233, 505, 102, 248, 231, 27, 241, 500, 107, 501, 236, 42, 108, 44, 10, + 39, 103, 26, 245, 36, 8, 31, 9, 0, 7, 29, 11, 48, 239, 28, 100, + 30, 12, 41, 243, 47, 240, 508, 113, 498, 244, 33, 230, 247, 104, 504, 238, + 34, 101, 49, 2, 38, 237, 37, 106, 507, 114, 510, 105, 46, 246, 511, 109, + 502, +) +BITS2 = ( + 9, 7, 9, 8, 6, 8, 9, 8, 9, 8, 6, 7, 6, 5, 6, 7, + 6, 8, 9, 7, 8, 8, 6, 8, 9, 7, 9, 8, 6, 7, 6, 5, + 6, 7, 6, 8, 6, 5, 6, 5, 3, 5, 6, 5, 6, 8, 6, 7, + 6, 5, 6, 8, 6, 8, 9, 7, 9, 8, 6, 8, 8, 7, 9, 8, + 6, 7, 6, 4, 6, 8, 6, 7, 9, 7, 9, 7, 6, 8, 9, 7, + 9, +) +CODES3 = ( + 0, 9, 239, 11, 25, 240, 491, 486, 1010, 10, 53, 495, 52, 55, 489, 493, + 487, 1011, 494, 1005, 8186, 492, 498, 2041, 2040, 1016, 4088, 8, 56, 1014, 54, 117, + 1009, 1003, 1004, 4084, 24, 118, 2036, 57, 116, 1007, 499, 500, 2038, 488, 1002, 8188, + 242, 497, 4091, 1013, 2035, 4092, 238, 1015, 32766, 496, 2037, 32765, 8187, 16378, 65535, 241, + 1008, 16380, 490, 1006, 16379, 4086, 4090, 32764, 2034, 4085, 65534, 1012, 2039, 32763, 4087, 4089, + 32762, +) +BITS3 = ( + 1, 4, 8, 4, 5, 8, 9, 9, 10, 4, 6, 9, 6, 6, 9, 9, + 9, 10, 9, 10, 13, 9, 9, 11, 11, 10, 12, 4, 6, 10, 6, 7, + 10, 10, 10, 12, 5, 7, 11, 6, 7, 10, 9, 9, 11, 9, 10, 13, + 8, 9, 12, 10, 11, 12, 8, 10, 15, 9, 11, 15, 13, 14, 16, 8, + 10, 14, 9, 10, 14, 12, 12, 15, 11, 12, 16, 10, 11, 15, 12, 12, + 15, +) +CODES4 = ( + 7, 22, 246, 24, 8, 239, 495, 243, 2040, 25, 23, 237, 21, 1, 226, 240, + 112, 1008, 494, 241, 2042, 238, 228, 1010, 2038, 1007, 2045, 5, 20, 242, 9, 4, + 229, 244, 232, 1012, 6, 2, 231, 3, 0, 107, 227, 105, 499, 235, 230, 1014, + 110, 106, 500, 1004, 496, 1017, 245, 236, 2043, 234, 111, 1015, 2041, 1011, 4095, 233, + 109, 1016, 108, 104, 501, 1006, 498, 2036, 2039, 1009, 4094, 1005, 497, 2037, 2046, 1013, + 2044, +) +BITS4 = ( + 4, 5, 8, 5, 4, 8, 9, 8, 11, 5, 5, 8, 5, 4, 8, 8, + 7, 10, 9, 8, 11, 8, 8, 10, 11, 10, 11, 4, 5, 8, 4, 4, + 8, 8, 8, 10, 4, 4, 8, 4, 4, 7, 8, 7, 9, 8, 8, 10, + 7, 7, 9, 10, 9, 10, 8, 8, 11, 8, 7, 10, 11, 10, 12, 8, + 7, 10, 7, 7, 9, 10, 9, 11, 11, 10, 12, 10, 9, 11, 11, 10, + 11, +) +CODES5 = ( + 8191, 4087, 2036, 2024, 1009, 2030, 2041, 4088, 8189, 4093, 2033, 1000, 488, 240, 492, 1006, + 2034, 4090, 4084, 1007, 498, 232, 112, 236, 496, 1002, 2035, 2027, 491, 234, 26, 8, + 25, 238, 495, 2029, 1008, 242, 115, 11, 0, 10, 113, 243, 2025, 2031, 494, 239, + 24, 9, 27, 235, 489, 2028, 2038, 1003, 499, 237, 114, 233, 497, 1005, 2039, 4086, + 2032, 1001, 493, 241, 490, 1004, 2040, 4089, 8188, 4092, 4085, 2026, 1011, 1010, 2037, 4091, + 8190, +) +BITS5 = ( + 13, 12, 11, 11, 10, 11, 11, 12, 13, 12, 11, 10, 9, 8, 9, 10, + 11, 12, 12, 10, 9, 8, 7, 8, 9, 10, 11, 11, 9, 8, 5, 4, + 5, 8, 9, 11, 10, 8, 7, 4, 1, 4, 7, 8, 11, 11, 9, 8, + 5, 4, 5, 8, 9, 11, 11, 10, 9, 8, 7, 8, 9, 10, 11, 12, + 11, 10, 9, 8, 9, 10, 11, 12, 13, 12, 12, 11, 10, 10, 11, 12, + 13, +) +CODES6 = ( + 2046, 1021, 497, 491, 500, 490, 496, 1020, 2045, 1014, 485, 234, 108, 113, 104, 240, + 486, 1015, 499, 239, 50, 39, 40, 38, 49, 235, 503, 488, 111, 46, 8, 4, + 6, 41, 107, 494, 495, 114, 45, 2, 0, 3, 47, 115, 506, 487, 110, 43, + 7, 1, 5, 44, 109, 492, 505, 238, 48, 36, 42, 37, 51, 236, 498, 1016, + 484, 237, 106, 112, 105, 116, 241, 1018, 2047, 1017, 502, 493, 504, 489, 501, 1019, + 2044, +) +BITS6 = ( + 11, 10, 9, 9, 9, 9, 9, 10, 11, 10, 9, 8, 7, 7, 7, 8, + 9, 10, 9, 8, 6, 6, 6, 6, 6, 8, 9, 9, 7, 6, 4, 4, + 4, 6, 7, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 7, 6, + 4, 4, 4, 6, 7, 9, 9, 8, 6, 6, 6, 6, 6, 8, 9, 10, + 9, 8, 7, 7, 7, 7, 8, 10, 11, 10, 9, 9, 9, 9, 9, 10, + 11, +) +CODES7 = ( + 0, 5, 55, 116, 242, 491, 1005, 2039, 4, 12, 53, 113, 236, 238, 494, 501, + 54, 52, 114, 234, 241, 489, 499, 1013, 115, 112, 235, 240, 497, 496, 1004, 1018, + 243, 237, 488, 495, 1007, 1009, 1017, 2043, 493, 239, 490, 498, 1011, 1016, 2041, 2044, + 1006, 492, 500, 1012, 1015, 2040, 4093, 4094, 2038, 1008, 1010, 1014, 2042, 2045, 4092, 4095, +) +BITS7 = ( + 1, 3, 6, 7, 8, 9, 10, 11, 3, 4, 6, 7, 8, 8, 9, 9, + 6, 6, 7, 8, 8, 9, 9, 10, 7, 7, 8, 8, 9, 9, 10, 10, + 8, 8, 9, 9, 10, 10, 10, 11, 9, 8, 9, 9, 10, 10, 11, 11, + 10, 9, 9, 10, 10, 11, 12, 12, 11, 10, 10, 10, 11, 11, 12, 12, +) +CODES8 = ( + 14, 5, 16, 48, 111, 241, 506, 1022, 3, 0, 4, 18, 44, 106, 117, 248, + 15, 2, 6, 20, 46, 105, 114, 245, 47, 17, 19, 42, 50, 108, 236, 250, + 113, 43, 45, 49, 109, 112, 242, 505, 239, 104, 51, 107, 110, 238, 249, 1020, + 504, 116, 115, 237, 240, 246, 502, 509, 1021, 243, 244, 247, 503, 507, 508, 1023, +) +BITS8 = ( + 5, 4, 5, 6, 7, 8, 9, 10, 4, 3, 4, 5, 6, 7, 7, 8, + 5, 4, 4, 5, 6, 7, 7, 8, 6, 5, 5, 6, 6, 7, 8, 8, + 7, 6, 6, 6, 7, 7, 8, 9, 8, 7, 6, 7, 7, 8, 8, 10, + 9, 7, 7, 8, 8, 8, 9, 9, 10, 8, 8, 8, 9, 9, 9, 10, +) +CODES9 = ( + 0, 5, 55, 231, 478, 974, 985, 1992, 1997, 4040, 4061, 8164, 8172, 4, 12, 53, + 114, 234, 237, 482, 977, 979, 992, 2008, 4047, 4053, 54, 52, 113, 232, 236, 481, + 975, 989, 987, 2000, 4039, 4052, 4068, 230, 112, 233, 477, 483, 978, 988, 1996, 1994, + 2014, 4056, 4074, 8155, 479, 235, 476, 486, 981, 990, 1995, 2013, 2012, 4045, 4066, 4071, + 8161, 976, 480, 484, 982, 1989, 2001, 2011, 4050, 2016, 4057, 4075, 8163, 8169, 1988, 485, + 983, 1990, 1999, 2010, 4043, 4058, 4067, 4073, 8166, 8179, 8183, 2003, 984, 993, 2004, 2009, + 4051, 4062, 8157, 8153, 8162, 8170, 8177, 8182, 2002, 980, 986, 1991, 2007, 2018, 4046, 4059, + 8152, 8174, 16368, 8180, 16370, 2017, 991, 1993, 2006, 4042, 4048, 4069, 4070, 8171, 8175, 16371, + 16372, 16373, 4064, 1998, 2005, 4038, 4049, 4065, 8160, 8168, 8176, 16369, 16376, 16374, 32764, 4072, + 2015, 4041, 4055, 4060, 8156, 8159, 8173, 8181, 16377, 16379, 32765, 32766, 8167, 4044, 4054, 4063, + 8158, 8154, 8165, 8178, 16378, 16375, 16380, 16381, 32767, +) +BITS9 = ( + 1, 3, 6, 8, 9, 10, 10, 11, 11, 12, 12, 13, 13, 3, 4, 6, + 7, 8, 8, 9, 10, 10, 10, 11, 12, 12, 6, 6, 7, 8, 8, 9, + 10, 10, 10, 11, 12, 12, 12, 8, 7, 8, 9, 9, 10, 10, 11, 11, + 11, 12, 12, 13, 9, 8, 9, 9, 10, 10, 11, 11, 11, 12, 12, 12, + 13, 10, 9, 9, 10, 11, 11, 11, 12, 11, 12, 12, 13, 13, 11, 9, + 10, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 11, 10, 10, 11, 11, + 12, 12, 13, 13, 13, 13, 13, 13, 11, 10, 10, 11, 11, 11, 12, 12, + 13, 13, 14, 13, 14, 11, 10, 11, 11, 12, 12, 12, 12, 13, 13, 14, + 14, 14, 12, 11, 11, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15, 12, + 11, 12, 12, 12, 13, 13, 13, 13, 14, 14, 15, 15, 13, 12, 12, 12, + 13, 13, 13, 13, 14, 14, 14, 14, 15, +) +CODES10 = ( + 34, 8, 29, 38, 95, 211, 463, 976, 983, 1005, 2032, 2038, 4093, 7, 0, 1, + 9, 32, 84, 96, 213, 220, 468, 973, 990, 2023, 28, 2, 6, 12, 30, 40, + 91, 205, 217, 462, 476, 985, 1009, 37, 11, 10, 13, 36, 87, 97, 204, 221, + 460, 478, 979, 999, 93, 33, 31, 35, 39, 89, 100, 216, 223, 466, 482, 989, + 1006, 209, 85, 41, 86, 88, 98, 206, 224, 226, 474, 980, 995, 2027, 457, 94, + 90, 92, 99, 202, 218, 455, 458, 480, 987, 1000, 2028, 483, 210, 203, 208, 215, + 219, 454, 469, 472, 970, 986, 2026, 2033, 481, 212, 207, 214, 222, 225, 464, 470, + 977, 981, 1010, 2030, 2043, 1001, 461, 456, 459, 465, 471, 479, 975, 992, 1007, 2022, + 2040, 4090, 1003, 477, 467, 473, 475, 978, 972, 988, 1002, 2029, 2035, 2041, 4089, 2034, + 974, 484, 971, 984, 982, 994, 997, 2024, 2036, 2037, 2039, 4091, 2042, 1004, 991, 993, + 996, 998, 1008, 2025, 2031, 4088, 4094, 4092, 4095, +) +BITS10 = ( + 6, 5, 6, 6, 7, 8, 9, 10, 10, 10, 11, 11, 12, 5, 4, 4, + 5, 6, 7, 7, 8, 8, 9, 10, 10, 11, 6, 4, 5, 5, 6, 6, + 7, 8, 8, 9, 9, 10, 10, 6, 5, 5, 5, 6, 7, 7, 8, 8, + 9, 9, 10, 10, 7, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 10, + 10, 8, 7, 6, 7, 7, 7, 8, 8, 8, 9, 10, 10, 11, 9, 7, + 7, 7, 7, 8, 8, 9, 9, 9, 10, 10, 11, 9, 8, 8, 8, 8, + 8, 9, 9, 9, 10, 10, 11, 11, 9, 8, 8, 8, 8, 8, 9, 9, + 10, 10, 10, 11, 11, 10, 9, 9, 9, 9, 9, 9, 10, 10, 10, 11, + 11, 12, 10, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 12, 11, + 10, 9, 10, 10, 10, 10, 10, 11, 11, 11, 11, 12, 11, 10, 10, 10, + 10, 10, 10, 11, 11, 12, 12, 12, 12, +) +CODES11 = ( + 0, 6, 25, 61, 156, 198, 423, 912, 962, 991, 2022, 2035, 4091, 2028, 4090, 4094, + 910, 5, 1, 8, 20, 55, 66, 146, 175, 401, 421, 437, 926, 960, 930, 973, + 2006, 174, 23, 7, 9, 24, 57, 64, 142, 163, 184, 409, 428, 449, 945, 918, + 958, 970, 157, 60, 21, 22, 26, 59, 68, 145, 165, 190, 406, 430, 441, 929, + 913, 933, 981, 148, 154, 54, 56, 58, 65, 140, 155, 176, 195, 414, 427, 444, + 927, 911, 937, 975, 147, 191, 62, 63, 67, 69, 158, 167, 185, 404, 418, 442, + 451, 934, 935, 955, 980, 159, 416, 143, 141, 144, 152, 166, 182, 196, 415, 431, + 447, 921, 959, 948, 969, 999, 168, 438, 171, 164, 170, 178, 194, 197, 408, 420, + 440, 908, 932, 964, 966, 989, 1000, 173, 943, 402, 189, 188, 398, 407, 410, 419, + 433, 909, 920, 951, 979, 977, 987, 2013, 180, 990, 425, 411, 412, 417, 426, 429, + 435, 907, 946, 952, 974, 993, 992, 2002, 2021, 183, 2019, 443, 424, 422, 432, 434, + 439, 923, 922, 954, 949, 982, 2007, 996, 2008, 2026, 186, 2024, 928, 445, 436, 906, + 452, 914, 938, 944, 956, 983, 2004, 2012, 2011, 2005, 2032, 193, 2043, 968, 931, 917, + 925, 940, 942, 965, 984, 994, 998, 2020, 2023, 2016, 2025, 2039, 400, 2034, 915, 446, + 448, 916, 919, 941, 963, 961, 978, 2010, 2009, 2015, 2027, 2036, 2042, 405, 2040, 957, + 924, 939, 936, 947, 953, 976, 995, 997, 2018, 2014, 2029, 2033, 2041, 2044, 403, 4093, + 988, 950, 967, 972, 971, 985, 986, 2003, 2017, 2030, 2031, 2037, 2038, 4092, 4095, 413, + 450, 181, 161, 150, 151, 149, 153, 160, 162, 172, 169, 177, 179, 187, 192, 399, + 4, +) +BITS11 = ( + 4, 5, 6, 7, 8, 8, 9, 10, 10, 10, 11, 11, 12, 11, 12, 12, + 10, 5, 4, 5, 6, 7, 7, 8, 8, 9, 9, 9, 10, 10, 10, 10, + 11, 8, 6, 5, 5, 6, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, + 10, 10, 8, 7, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 10, + 10, 10, 10, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, + 10, 10, 10, 10, 8, 8, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, + 9, 10, 10, 10, 10, 8, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, + 9, 10, 10, 10, 10, 10, 8, 9, 8, 8, 8, 8, 8, 8, 9, 9, + 9, 10, 10, 10, 10, 10, 10, 8, 10, 9, 8, 8, 9, 9, 9, 9, + 9, 10, 10, 10, 10, 10, 10, 11, 8, 10, 9, 9, 9, 9, 9, 9, + 9, 10, 10, 10, 10, 10, 10, 11, 11, 8, 11, 9, 9, 9, 9, 9, + 9, 10, 10, 10, 10, 10, 11, 10, 11, 11, 8, 11, 10, 9, 9, 10, + 9, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 8, 11, 10, 10, 10, + 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 9, 11, 10, 9, + 9, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 11, 10, + 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 12, + 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 12, 12, 9, + 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, + 5, +) +SF_CODES = ( + 262120, 262118, 262119, 262117, 524277, 524273, 524269, 524278, 524270, 524271, 524272, 524284, 524285, 524287, 524286, 524279, + 524280, 524283, 524281, 262116, 524282, 262115, 131055, 131056, 65525, 131054, 65522, 65523, 65524, 65521, 32758, 32759, + 16377, 16373, 16375, 16371, 16374, 16370, 8183, 8181, 4089, 4087, 4086, 2041, 4084, 2040, 1017, 1015, + 1013, 504, 503, 250, 248, 246, 121, 58, 56, 26, 11, 4, 0, 10, 12, 27, + 57, 59, 120, 122, 247, 249, 502, 505, 1012, 1014, 1016, 2037, 2036, 2038, 2039, 4085, + 4088, 8180, 8182, 8184, 16376, 16372, 65520, 32756, 65526, 32757, 262114, 524249, 524250, 524251, 524252, 524253, + 524254, 524248, 524242, 524243, 524244, 524245, 524246, 524274, 524255, 524263, 524264, 524265, 524266, 524267, 524262, 524256, + 524257, 524258, 524259, 524260, 524261, 524247, 524268, 524276, 524275, +) +SF_BITS = ( + 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, + 19, 19, 19, 18, 19, 18, 17, 17, 16, 17, 16, 16, 16, 16, 15, 15, + 14, 14, 14, 14, 14, 14, 13, 13, 12, 12, 12, 11, 12, 11, 10, 10, + 10, 9, 9, 8, 8, 8, 7, 6, 6, 5, 4, 3, 1, 4, 4, 5, + 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 10, 11, 11, 11, 11, 12, + 12, 13, 13, 13, 14, 14, 16, 15, 16, 15, 18, 19, 19, 19, 19, 19, + 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, + 19, 19, 19, 19, 19, 19, 19, 19, 19, +) +SWB_1024_96 = ( + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, + 72, 80, 88, 96, 108, 120, 132, 144, 156, 172, 188, 212, 240, 276, 320, 384, + 448, 512, 576, 640, 704, 768, 832, 896, 960, 1024, +) +SWB_1024_64 = ( + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, + 72, 80, 88, 100, 112, 124, 140, 156, 172, 192, 216, 240, 268, 304, 344, 384, + 424, 464, 504, 544, 584, 624, 664, 704, 744, 784, 824, 864, 904, 944, 984, 1024, +) +SWB_1024_48 = ( + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, + 88, 96, 108, 120, 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, + 416, 448, 480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800, 832, 864, 896, + 928, 1024, +) +SWB_1024_32 = ( + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, + 88, 96, 108, 120, 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, + 416, 448, 480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800, 832, 864, 896, + 928, 960, 992, 1024, +) +SWB_1024_24 = ( + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76, + 84, 92, 100, 108, 116, 124, 136, 148, 160, 172, 188, 204, 220, 240, 260, 284, + 308, 336, 364, 396, 432, 468, 508, 552, 600, 652, 704, 768, 832, 896, 960, 1024, +) +SWB_1024_16 = ( + 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, + 148, 160, 172, 184, 196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, + 456, 492, 532, 572, 616, 664, 716, 772, 832, 896, 960, 1024, +) +SWB_1024_8 = ( + 0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 172, 188, + 204, 220, 236, 252, 268, 288, 308, 328, 348, 372, 396, 420, 448, 476, 508, 544, + 580, 620, 664, 712, 764, 820, 880, 944, 1024, +) +SWB_128_96 = ( + 0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128, +) +SWB_128_48 = ( + 0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128, +) +SWB_128_24 = ( + 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128, +) +SWB_128_16 = ( + 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128, +) +SWB_128_8 = ( + 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 60, 72, 88, 108, 128, +) +SPECTRAL = ((CODES1, BITS1), (CODES2, BITS2), (CODES3, BITS3), (CODES4, BITS4), (CODES5, BITS5), (CODES6, BITS6), (CODES7, BITS7), (CODES8, BITS8), (CODES9, BITS9), (CODES10, BITS10), (CODES11, BITS11)) +#: Per sampling-frequency index (0 = 96 kHz … 12 = 7.35 kHz), as FFmpeg's ff_swb_offset_1024/_128. +SWB_LONG = (SWB_1024_96, SWB_1024_96, SWB_1024_64, SWB_1024_48, SWB_1024_48, SWB_1024_32, SWB_1024_24, SWB_1024_24, SWB_1024_16, SWB_1024_16, SWB_1024_16, SWB_1024_8, SWB_1024_8) +SWB_SHORT = (SWB_128_96, SWB_128_96, SWB_128_96, SWB_128_48, SWB_128_48, SWB_128_48, SWB_128_24, SWB_128_24, SWB_128_16, SWB_128_16, SWB_128_16, SWB_128_8, SWB_128_8) diff --git a/backend/konduktor/core/level_edit.py b/backend/konduktor/core/level_edit.py index 2d46b18..72abfc2 100644 --- a/backend/konduktor/core/level_edit.py +++ b/backend/konduktor/core/level_edit.py @@ -49,8 +49,10 @@ def apply(src: Path | str, dst: Path | str, gain_db: float) -> None: raise LevelEditError(f"{dst.name} already exists") suffix = src.suffix.lower() try: - if suffix in STEPPED: + if suffix == ".mp3": _mp3(src, dst, gain_db) + elif suffix in STEPPED: + _aac(src, dst, gain_db) elif suffix in (".wav", ".wave"): shutil.copyfile(src, dst) _scale_chunk(dst, _wav_layout(dst), gain_db) @@ -198,6 +200,21 @@ def _mp3gain_tag(path: Path, steps: int, lo: int, hi: int) -> None: tag.save(str(path)) +# ---- AAC (an .m4a, a stem file): the same edit, in `aac_gain` ----------------- + +def _aac(src: Path, dst: Path, gain_db: float) -> None: + """Every audio stream of the MP4 (a stem file's five alike) moved by the + same steps. No undo tag: one would grow `moov` and shift every sample + offset; the edit is exactly reversed by the opposite steps.""" + from . import aac_gain + + steps = mp3_steps(gain_db) + try: + aac_gain.apply(src, dst, steps) + except aac_gain.AacGainError as ex: + raise LevelEditError(f"{src.name}: {ex}") from ex + + # ---- WAV / AIFF: the samples scaled in their own chunk ------------------------ class _Layout: @@ -375,13 +392,20 @@ def _flac(src: Path, dst: Path, gain_db: float) -> None: # ---- verification --------------------------------------------------------------- -def _frames(path: Path): +def _audio_streams(path: Path) -> int: + from . import pyav + + with pyav.open_input(path) as c: + return len(c.streams.audio) + + +def _frames(path: Path, index: int = 0): import av from . import pyav with pyav.open_input(path) as c: - stream = c.streams.audio[0] + stream = c.streams.audio[index] rs = av.AudioResampler(format="fltp", layout="stereo" if stream.codec_context.channels > 1 else "mono", rate=int(stream.codec_context.sample_rate)) for frame in c.decode(stream): @@ -393,9 +417,18 @@ def _frames(path: Path): def verify(src: Path | str, dst: Path | str, gain_db: float, *, tolerance: float = 1e-3) -> None: """Decode both and check `dst` == `src` x 10^(g/20), to within `tolerance` - of the source's peak (16-bit dither is ~3e-5). Raises `LevelEditError`.""" + of the source's peak (16-bit dither is ~3e-5) — EVERY audio stream (a + stem file's five). Raises `LevelEditError`.""" + n_src, n_dst = _audio_streams(Path(src)), _audio_streams(Path(dst)) + if n_src != n_dst: + raise LevelEditError(f"{Path(dst).name}: the number of audio streams changed") + for index in range(n_src): + _verify_stream(Path(src), Path(dst), gain_db, tolerance, index) + + +def _verify_stream(src: Path, dst: Path, gain_db: float, tolerance: float, index: int) -> None: factor = 10.0 ** (gain_db / 20.0) - a_iter, b_iter = _frames(Path(src)), _frames(Path(dst)) + a_iter, b_iter = _frames(src, index), _frames(dst, index) a_buf = b_buf = None worst = peak = 0.0 length_a = length_b = 0 diff --git a/backend/konduktor/core/level_plan.py b/backend/konduktor/core/level_plan.py index 04ad663..db180d1 100644 --- a/backend/konduktor/core/level_plan.py +++ b/backend/konduktor/core/level_plan.py @@ -32,8 +32,10 @@ STEP_DB = 20.0 * math.log10(2.0 ** 0.25) #: Rewritten exactly (PCM scaled, same bit depth). EXACT = frozenset({".wav", ".wave", ".aif", ".aiff", ".flac"}) -#: Rewritten by the lossless frame-gain edit, in `STEP_DB` steps. -STEPPED = frozenset({".mp3"}) +#: Rewritten by a lossless frame-gain edit, in `STEP_DB` steps: MP3's +#: (`level_edit`) and AAC-LC's (`aac_gain` — an `.m4a`, a stem file; a file +#: that turns out to be HE-AAC is refused when it is rewritten). +STEPPED = frozenset({".mp3", ".m4a", ".mp4"}) #: Closer than this to the target (lossless) is "already there". _EXACT_TOLERANCE_DB = 0.05 diff --git a/backend/konduktor/exporter.py b/backend/konduktor/exporter.py index 22a7576..4797e9b 100644 --- a/backend/konduktor/exporter.py +++ b/backend/konduktor/exporter.py @@ -620,17 +620,26 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle, *, # The file to READ: on this machine that is the source itself; # on a library held by a server, a downloaded copy of it. local = adapter.audio_path(planned.track_id) or planned.source_path + levelled = False if planned.gain_db: from .core import level_edit handle.progress(message=f"Normalising {planned.title} ({planned.gain_db:+.1f} dB)") - level_edit.apply(local, partial, planned.gain_db) - handle.raise_if_cancelled() - # A copy carried to a gig must be the source at the gain, - # nothing else: decode both and compare. - level_edit.verify(local, partial, planned.gain_db) - advance(planned.size) - else: + try: + level_edit.apply(local, partial, planned.gain_db) + handle.raise_if_cancelled() + # A copy carried to a gig must be the source at the + # gain, nothing else: decode both and compare. + level_edit.verify(local, partial, planned.gain_db) + levelled = True + advance(planned.size) + except level_edit.LevelEditError as ex: + # Only the file says some things (HE-AAC in an .m4a): + # such a copy goes as it is, never fails the export. + log.warning("copying %s unlevelled: %s", planned.title, ex) + partial.unlink(missing_ok=True) + planned.gain_db, planned.level_outcome = 0.0, "unsupported" + if not levelled: copy_file(local, partial, handle, advance) os.replace(partial, target) payload_tracks.append( diff --git a/backend/run_tests.sh b/backend/run_tests.sh index ff1c151..5ea38f0 100755 --- a/backend/run_tests.sh +++ b/backend/run_tests.sh @@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")" source .venv/bin/activate fail=0 -for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_key_detect.py test_loudness.py test_loudness_store.py test_level_plan.py test_level_edit.py test_normalize.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_prefs.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_export_level.py test_device_export.py test_phase3.py test_history.py test_discard.py test_remote_protocol.py test_remote_server.py test_remote_adapter.py test_remote_stems.py test_remote_normalize.py; do +for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_key_detect.py test_loudness.py test_loudness_store.py test_level_plan.py test_level_edit.py test_aac_gain.py test_normalize.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_prefs.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_export_level.py test_device_export.py test_phase3.py test_history.py test_discard.py test_remote_protocol.py test_remote_server.py test_remote_adapter.py test_remote_stems.py test_remote_normalize.py; do echo "──────────────────────────────────────────" echo "▶ $t" echo "──────────────────────────────────────────" diff --git a/backend/test_aac_gain.py b/backend/test_aac_gain.py new file mode 100644 index 0000000..41dd890 --- /dev/null +++ b/backend/test_aac_gain.py @@ -0,0 +1,218 @@ +"""AAC-LC's lossless gain edit (`core/aac_gain.py`) on GENERATED files, plus the +user's real ones when present (kits 4 and 5, Kit Bulk's commercial stems). + +What would fail silently: a mis-walked frame writing a "global_gain" that is +really spectral data (the walk must end in each frame's last byte, and the +decode of EVERY stream must be the source x 2^(n/4)); a byte changed that is +not a global_gain; a stem file's streams levelled unevenly; HE-AAC (whose SBR +part this edit does not scale) or a non-AAC MP4 treated as AAC-LC. +""" +from __future__ import annotations + +import sys +import tempfile +import warnings +from pathlib import Path + +warnings.filterwarnings("ignore") + +import av # noqa: E402 +import numpy as np # noqa: E402 + +from konduktor.core import aac_gain, level_edit, pyav # noqa: E402 +from konduktor.core import stem_file as sf # noqa: E402 +from stem_test_support import make_mp3 # noqa: E402 + +failed = False + + +def check(label, cond, detail=""): + global failed + print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else "")) + if not cond: + failed = True + + +def signal(sr, ch, seconds=5, seed=1): + t = np.arange(int(sr * seconds)) / sr + rng = np.random.default_rng(seed) + beat = np.sin(2 * np.pi * 2 * t) > 0.6 + x = [0.3 * (0.5 * np.sin(2 * np.pi * 90 * t) * beat + 0.3 * np.sin(2 * np.pi * (440 + 30 * c) * t) + + 0.2 * rng.standard_normal(t.size)) for c in range(ch)] + if ch == 2: + x[1] = 0.8 * x[0] + 0.2 * x[1] # correlated: invites M/S and intensity stereo + return np.vstack(x).astype(np.float32) + + +def encode(path: Path, codec: str, sr: int, ch: int, bit_rate: int, options=None, profile=None) -> Path | None: + layout = "stereo" if ch == 2 else "mono" + x = signal(sr, ch) + try: + with av.open(str(path), "w", format="ipod") as c: + s = c.add_stream(codec, rate=sr, layout=layout) + s.bit_rate = bit_rate + if options: + s.options = options + if profile: + s.codec_context.profile = profile + for o in range(0, x.shape[1], 1024): + f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, o:o + 1024]), format="fltp", layout=layout) + f.sample_rate, f.pts = sr, o + for p in s.encode(f): + c.mux(p) + for p in s.encode(None): + c.mux(p) + except Exception: # noqa: BLE001 — an encoder this machine lacks (aac_at off macOS) + path.unlink(missing_ok=True) + return None + return path + + +def decode(path: Path, index: int) -> np.ndarray: + with pyav.open_input(path) as c: + s = c.streams.audio[index] + rs = av.AudioResampler(format="fltp", layout="stereo" if s.codec_context.channels > 1 else "mono", + rate=int(s.codec_context.sample_rate)) + out = [o.to_ndarray() for fr in c.decode(s) for o in rs.resample(fr)] + out += [o.to_ndarray() for o in rs.resample(None)] + return np.concatenate(out, axis=1).astype(np.float64) + + +def exact(src: Path, dst: Path, steps: int, streams: int) -> tuple[bool, str]: + worst = 0.0 + for i in range(streams): + a, b = decode(src, i), decode(dst, i) + if a.shape != b.shape: + return False, f"stream {i}: {a.shape} vs {b.shape}" + worst = max(worst, float(np.abs(b - a * 2 ** (steps / 4)).max() / max(np.abs(a).max(), 1e-12))) + return worst < 1e-5, f"{worst:.1e}" + + +def only_global_gains(src: Path, dst: Path, scanned) -> bool: + a = np.frombuffer(src.read_bytes(), np.uint8) + b = np.frombuffer(dst.read_bytes(), np.uint8) + allowed = set() + for gpos in scanned.positions: + allowed.update((gpos >> 3).tolist()) + allowed.update(((gpos >> 3) + 1).tolist()) + return a.size == b.size and set(np.nonzero(a != b)[0].tolist()) <= allowed + + +ROOT = Path(tempfile.mkdtemp(prefix="konduktor-aacgain-")) +CASES = [ + ("FFmpeg stereo 44.1 kHz", "aac", 44100, 2, 192000, None), + ("FFmpeg mono", "aac", 44100, 1, 96000, None), + ("FFmpeg 48 kHz", "aac", 48000, 2, 160000, None), + ("FFmpeg 22.05 kHz", "aac", 22050, 2, 64000, None), + ("FFmpeg 48 kb/s, PNS + intensity + M/S", "aac", 44100, 2, 48000, {"aac_pns": "1", "aac_is": "1", "aac_ms": "1"}), + ("FFmpeg with TNS", "aac", 44100, 2, 128000, {"aac_tns": "1"}), + ("Apple (aac_at) 128 kb/s", "aac_at", 44100, 2, 128000, None), + ("Apple (aac_at) mono 64 kb/s", "aac_at", 44100, 1, 64000, None), +] + +print("== generated AAC-LC: the decode is the source x 2^(n/4), only global_gain bytes change ==") +for label, codec, sr, ch, br, opts in CASES: + src = encode(ROOT / f"{len(list(ROOT.iterdir()))}.m4a", codec, sr, ch, br, opts) + if src is None: + print(f" [SKIP] {label}: no {codec} encoder here") + continue + scanned = aac_gain.scan(src) + check(f"{label}: every frame walked", len(scanned.positions[0]) == len(scanned.tracks[0].sizes) * ch, + f"{len(scanned.positions[0])} for {len(scanned.tracks[0].sizes)} frames") + for steps in (-2, 3): + dst = ROOT / f"{src.stem}{steps:+d}.m4a" + aac_gain.apply(src, dst, steps, scanned) + ok, detail = exact(src, dst, steps, 1) + check(f"{label} {steps:+d}: exact", ok, detail) + check(f"{label} {steps:+d}: same size, only global_gain bytes differ", only_global_gains(src, dst, scanned)) + +print("== a stem file: all five streams by the same steps ==") +source = make_mp3(ROOT / "stem-source.mp3", seconds=5) +stem = ROOT / "track.stem.m4a" +sf.build(source, stem, lambda pcm: [pcm * g for g in (0.5, 0.25, -0.2, 0.1)]) +scanned = aac_gain.scan(stem) +check("five AAC streams found", len(scanned.tracks) == 5, str(len(scanned.tracks))) +out = ROOT / "track-2.stem.m4a" +aac_gain.apply(stem, out, -2, scanned) +ok, detail = exact(stem, out, -2, 5) +check("every stream decodes at exactly -2 steps", ok, detail) +check("…the stem box and every other byte untouched", only_global_gains(stem, out, scanned) + and sf.is_stem_file(out)) +back = ROOT / "track-back.stem.m4a" +aac_gain.apply(out, back, 2) +check("the opposite steps give the original back, byte for byte", back.read_bytes() == stem.read_bytes()) + +print("== through level_edit: the generic path ==") +dst = ROOT / "via-level-edit.stem.m4a" +level_edit.apply(stem, dst, -2 * aac_gain.STEP_DB) +try: + level_edit.verify(stem, dst, -2 * aac_gain.STEP_DB) + ok = True +except level_edit.LevelEditError as ex: + ok = str(ex) +check("level_edit applies and verifies an .m4a (all five streams)", ok is True, str(ok)) +# One stream levelled unlike the others must fail verification. +part = ROOT / "part.stem.m4a" +one = aac_gain.Scan(scanned.tracks, [p if i == 2 else p[:0] for i, p in enumerate(scanned.positions)], + scanned.min_step, scanned.max_step) +aac_gain.apply(dst, part, 2, one) # stream 2 back up: now it differs from the rest +try: + level_edit.verify(stem, part, -2 * aac_gain.STEP_DB) + caught = False +except level_edit.LevelEditError: + caught = True +check("…and a stem file with one stream at another level fails verification", caught) +try: + level_edit.apply(stem, ROOT / "half.stem.m4a", -2.0) + refused = False +except level_edit.LevelEditError: + refused = True +check("a gain that is not a whole number of steps is refused", refused and not (ROOT / "half.stem.m4a").exists()) + +print("== refusals leave nothing ==") +he = encode(ROOT / "he.m4a", "aac_at", 44100, 2, 64000, profile="HE-AAC") +if he is None: + print(" [SKIP] no HE-AAC encoder here") +else: + try: + aac_gain.scan(he) + check("HE-AAC is refused (its SBR part is not scaled by global_gain)", False) + except aac_gain.AacGainError: + check("HE-AAC is refused (its SBR part is not scaled by global_gain)", True) +alac = encode(ROOT / "alac.m4a", "alac", 44100, 2, 0) +if alac is not None: + try: + aac_gain.scan(alac) + check("ALAC in an .m4a is refused", False) + except aac_gain.AacGainError: + check("ALAC in an .m4a is refused", True) +try: + aac_gain.apply(stem, ROOT / "far.m4a", scanned.max_step + 1, scanned) + refused = False +except aac_gain.AacGainError: + refused = True +check("steps that would push a scalefactor out of range are refused, leaving no file", + refused and not (ROOT / "far.m4a").exists()) +try: + aac_gain.apply(stem, out, -1) + refused = False +except aac_gain.AacGainError: + refused = True +check("an existing target is never overwritten", refused) + +print("== real files on this machine (skipped when absent) ==") +kits = Path.home() / "Music" / "Konduktor Stem Test" +real = [kits / "Kit 4" / "K4-8 aac ffmpeg.m4a", kits / "Kit 4" / "K4-9 aac apple.m4a", + *sorted((kits / "Kit 5").glob("*.stem.m4a"))[:2], *sorted((kits / "Kit Bulk").glob("*.stem.m4a"))[:3]] +for f in real: + if not f.is_file(): + continue + s = aac_gain.scan(f) + dst = ROOT / f"real-{f.name}" + aac_gain.apply(f, dst, -2, s) + ok, detail = exact(f, dst, -2, len(s.tracks)) + check(f"{f.name}: every stream exact at -2 steps", ok, detail) + dst.unlink() + +print("\nRESULT:", "FAILED" if failed else "ALL PASSED") +sys.exit(1 if failed else 0) diff --git a/backend/test_export_level.py b/backend/test_export_level.py index 9110b90..60186cc 100644 --- a/backend/test_export_level.py +++ b/backend/test_export_level.py @@ -241,6 +241,22 @@ with TestClient(main.app) as c: check("no LOUDNESS in the exported collection", all(v is None for v in traktor_gains(dest).values())) check("no auto gain in the Rekordbox Library", all(v is None for v in rekordbox_gains(dest).values())) + print("== a file only the file says cannot be levelled (HE-AAC) is copied as it is ==") + real_apply = level_edit.apply + + def refuse(src, dst, gain_db): + raise level_edit.LevelEditError(f"{Path(src).name}: only AAC-LC can be changed losslessly") + + level_edit.apply = refuse + j = wait(c, c.post(f"/api/exports/{s['id']}/run", json={"normalise": True, "auto_gain": True}).json()["id"]) + level_edit.apply = real_apply + check("the export still completes", j["state"] == "done" and j["result"]["normalised"] == 0, str(j.get("error"))) + check("…every copy byte-identical to its source, recorded at no gain", + all(sha(dest / "Contents" / p.name) == before[p.name] for p in sources) + and all(g == 0.0 for g in manifest_gains(dest).values())) + check("…and the auto gain from the SOURCE's level", + all(abs(traktor_gains(dest)[p.name] - (-9.2 - entries[str(p)].values.lufs)) < 1e-3 for p in sources)) + print("== the waveform cache is keyed by the level ==") p = exporter.PlannedTrack(track_id="t", title="t", source_path=Path("/x.mp3"), destination=None, size=10, mtime_ns=1) diff --git a/backend/test_level_plan.py b/backend/test_level_plan.py index ab00ac7..1c2e759 100644 --- a/backend/test_level_plan.py +++ b/backend/test_level_plan.py @@ -35,7 +35,11 @@ check("a quiet one goes up exactly when the peak allows", (s.outcome, s.gain_db) s = plan(L(-9.02, -2.0)) check("within 0.05 dB is at target (lossless)", s.outcome == "at_target" and not s.writes, str(s)) check("no measurement: unmeasured", plan(None).outcome == "unmeasured") -check("ALAC / AAC / Ogg: unsupported", all(plan(L(-6, 0), x).outcome == "unsupported" for x in (".m4a", ".ogg", ".opus"))) +check("Ogg / Opus / WMA: unsupported", all(plan(L(-6, 0), x).outcome == "unsupported" for x in (".ogg", ".opus", ".wma"))) +s = plan(L(-6.0, -3.0), ".m4a") +check("AAC (.m4a, a stem file) is planned in whole steps, like MP3 (aac_gain)", + s.outcome == "apply" and abs(s.gain_db / STEP_DB - round(s.gain_db / STEP_DB)) < 1e-6 + and plan(L(-6.0, -3.0), ".mp4").gain_db == s.gain_db, str(s)) check("the suffix is case-blind", plan(L(-6.0, 1.0), ".FLAC").outcome == "apply") print("== the ceiling (a raise never clips) ==") diff --git a/backend/test_normalize.py b/backend/test_normalize.py index 00c2b0b..d28fb10 100644 --- a/backend/test_normalize.py +++ b/backend/test_normalize.py @@ -79,16 +79,33 @@ def make_mp3(path: Path, amp: float): c.mux(p) +def make_m4a(path: Path, amp: float): + x = music(amp=amp) + with av.open(str(path), "w", format="ipod") as c: + s = c.add_stream("aac", rate=44100, layout="stereo") + s.bit_rate = 192_000 + for o in range(0, x.shape[1], 1024): + f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, o:o + 1024]), format="fltp", layout="stereo") + f.sample_rate, f.pts = 44100, o + for p in s.encode(f): + c.mux(p) + for p in s.encode(None): + c.mux(p) + + def make(path: Path, amp: float): path.parent.mkdir(parents=True, exist_ok=True) if path.suffix == ".mp3": make_mp3(path, amp) + elif path.suffix == ".m4a": + make_m4a(path, amp) else: sf.write(str(path), music(amp=amp).T, 44100, subtype="PCM_16") return path -FILES = [("hot.mp3", 0.9), ("quiet.flac", 0.03), ("hot.wav", 0.8), ("close.mp3", 0.12)] +FILES = [("hot.mp3", 0.9), ("quiet.flac", 0.03), ("hot.wav", 0.8), ("close.mp3", 0.12), ("hot.m4a", 0.8)] +LOSSLESS = {".flac", ".wav"} def library(name: str): @@ -160,13 +177,15 @@ with TestClient(main.app) as c: gains = {files[i].name: rows[t].get("gain_db") for i, t in enumerate(ids)} check("measured: every track has a plan", all(rows[t].get("outcome") for t in ids), str(pv["rows"])) + check("an AAC file (.m4a) is levelled in the same whole steps (aac_gain)", + abs(gains["hot.m4a"] / STEP_DB - round(gains["hot.m4a"] / STEP_DB)) < 1e-6 and gains["hot.m4a"] < 0, str(gains)) check("an MP3's gain is a whole number of 1.505 dB steps", abs(gains["hot.mp3"] / STEP_DB - round(gains["hot.mp3"] / STEP_DB)) < 1e-6 and gains["hot.mp3"] < 0, str(gains)) check("the quiet FLAC is raised, but only to the ceiling", rows[ids[1]]["outcome"] in ("apply", "capped") and gains["quiet.flac"] > 0 and before["quiet.flac"].true_peak + gains["quiet.flac"] <= -1.0 + 1e-6, str(rows[ids[1]])) check("lossless files are counted (Save makes their change permanent)", - pv["lossless"] == sum(1 for i, t in enumerate(ids) if files[i].suffix != ".mp3" and rows[t]["gain_db"]), + pv["lossless"] == sum(1 for i, t in enumerate(ids) if files[i].suffix in LOSSLESS and rows[t]["gain_db"]), str(pv["lossless"])) print("== run: new files in place, originals parked, library follows ==") @@ -191,7 +210,7 @@ with TestClient(main.app) as c: state = c.get("/api/state").json() check("Save is due: the library is dirty and the pending change is named", state["dirty"] and state["pending_gain"]["tracks"] == len(changed) - and state["pending_gain"]["lossless"] == sum(1 for p in changed if p.suffix != ".mp3"), str(state)) + and state["pending_gain"]["lossless"] == sum(1 for p in changed if p.suffix in LOSSLESS), str(state)) vals = c.post("/api/loudness", json={"track_ids": ids}).json()["values"] tracks = {t["id"]: t for t in c.get("/api/tracks", params={"limit": 20000}).json()["items"]} for p in changed: