Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
fix: gate short transient sounds by one peak-aware loudness rule
Soohong Kimc5a6f41de74e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f3e12a5..accf717 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,7 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the## Unreleased+- Bump audio processing recipe to version 4, measure BS.1770-4 loudness over normalized PCM frames and gated blocks, support a peak-limited loudness goal, normalize loudnorm-unanalysable short clips via limiter passes instead of refusing them, encode AAC using `-aac_coder fast`, record `normalization.pcm_lufs` and `pcm_true_peak_dbtp` required by bundle loaders, and reject recipe version 1-3 bundles while reusing cached provider audio.- Bump audio processing recipe to version 3, require `ffprobe` on `PATH`, export M4A with `-movie_timescale 48000`, and validate AAC stream duration with `ffprobe`.- Add bounded one-frame decoded length tolerance, preserving loop duration, trimming one-shots, and rejecting shorter buffers and undersized overlaps at export.- Configure loop playback in `createAudioSource` using an internally cached L+1 guard frame buffer while preserving `prepareAudioBuffer` frame contracts.diff --git a/docs/game-pack.md b/docs/game-pack.mdindex 67421c0..a178b1f 100644--- a/docs/game-pack.md+++ b/docs/game-pack.md@@ -181,7 +181,7 @@ Game packs support optional bundled audio declared in pack recipes via `request.- `duration_seconds`: Final prepared playback duration `(end_frame - start_frame - overlap_frames) / sample_rate`.- `target_lufs`: Target integrated loudness.- `playback`: Integer coordinate object (`version`, `sample_rate`, `start_frame`, `end_frame`, `overlap_frames`) preserved exactly from source `sound.json`.- - `files`: Format dictionary for `ogg` and `m4a` containing relative paths (`audio-<id>.ogg`, `audio-<id>.m4a`), `sha256`, decoded `duration_seconds`, `lufs`, and `true_peak_dbfs` (`encode_passes` and `pcm_peak_limit_dbtp` exist only in `sound.json` and are stripped on load).+ - `files`: Format dictionary for `ogg` and `m4a` containing relative paths (`audio-<id>.ogg`, `audio-<id>.m4a`), `sha256`, decoded `duration_seconds`, `lufs`, and `true_peak_dbfs` (`encode_passes` and `pcm_peak_limit_dbtp` exist only in `sound.json` and are stripped on load). Source `sound.json` manifests must carry the `normalization` record of processing version 4 and satisfy the [loudness rule](sound.md#loudness-rule). For a peak-limited sound, `lufs` sits below `target_lufs`.- `player`: Runtime helper descriptor:```json{diff --git a/docs/sound.md b/docs/sound.mdindex 041e069..3ab0357 100644--- a/docs/sound.md+++ b/docs/sound.md@@ -35,15 +35,32 @@ Raw paid audio is stored in SQLite keyed by provider parameter digest. Tuning `-## Audio DSP, Looping, and Quality Gates-1. **Export and Normalization**: Provider audio decodes to 48kHz stereo PCM. Normalization uses two-pass [FFmpeg Loudnorm](https://ffmpeg.org/ffmpeg-filters.html#loudnorm) targeting -2 dBTP with repeating loop context. Up to three per-format offline encode/measure passes correct codec reconstruction overshoot using measured gain and tighter oversampled [FFmpeg Alimiter](https://ffmpeg.org/ffmpeg-filters.html#alimiter) (192kHz, auto-gain off, latency compensated) without triggering provider retries.-2. **Export Formats**: Outputs complete normalized audio in 48kHz stereo Opus in OGG (`sound.ogg`, `libopus`, 160 kbps) and AAC in M4A (`sound.m4a`, `aac`, 192 kbps). The exporter exports M4A with `-movie_timescale 48000`, equal to the normalized source sample rate (setting the movie header box time scale; see [FFmpeg Formats](https://ffmpeg.org/ffmpeg-formats.html#mov_002c-mp4_002c-ismv)), preserving fractional-millisecond source lengths without introducing declared tail padding. Export files remove all pre-encode crossfades, loop splices, and 5ms boundary zero-tapers; the complete normalized source is preserved intact in encoded audio.-3. **Quality Gates**: Output formats must decode to the integrated loudness target within +/-1 LU and true peak <= -1 dBTP. After every AAC encode, the exporter invokes `ffprobe` and requires first audio stream `time_base=1/48000` and `duration_ts=end_frame-start_frame`; mismatch or unreadable duration fails clearly before publishing. Silence or unmeasurable audio fails. Numeric checks do not judge musical beat alignment.+1. **Export and Normalization**: Provider audio decodes to 48kHz stereo PCM. Normalization first runs two-pass [FFmpeg Loudnorm](https://ffmpeg.org/ffmpeg-filters.html#loudnorm) (`method: "loudnorm-two-pass"`). When loudnorm's first pass reports no finite second-pass offset, decoded PCM bypasses the second pass to limiter passes (`method: "limiter"`). Normalization applies up to three gain passes through an oversampled lookahead limiter ([FFmpeg Alimiter](https://ffmpeg.org/ffmpeg-filters.html#alimiter) at 192 kHz, auto-gain off, latency compensated, ceiling -2 dBTP) until the PCM is within 0.2 LU of the target with a true peak at or under -1.8 dBTP. Up to three per-format offline encode passes correct codec reconstruction overshoot using measured gain and tighter limiter settings without triggering provider retries.+2. **Export Formats**: Outputs complete normalized audio in 48kHz stereo Opus in OGG (`sound.ogg`, `libopus`, 160 kbps) and AAC in M4A (`sound.m4a`, `aac`, 192 kbps, `-aac_coder fast`). The exporter exports M4A with `-movie_timescale 48000`, equal to the normalized source sample rate (setting the movie header box time scale; see [FFmpeg Formats](https://ffmpeg.org/ffmpeg-formats.html#mov_002c-mp4_002c-ismv)), preserving fractional-millisecond source lengths without introducing declared tail padding. Export files remove all pre-encode crossfades, loop splices, and 5ms boundary zero-tapers; the complete normalized source is preserved intact in encoded audio.+3. **Quality Gates**: Output formats must decode finite, within 1 LU of the [loudness goal](#loudness-rule), with true peak <= -1 dBTP. After every AAC encode, the exporter invokes `ffprobe` and requires first audio stream `time_base=1/48000` and `duration_ts=end_frame-start_frame`; mismatch or unreadable duration fails clearly before publishing. Silence or unmeasurable audio fails. Numeric checks do not judge musical beat alignment.4. **Looping and Playback Quality**: Crossfading is deferred to runtime preparation. Because playback overlap blending can alter loudness, applications must validate prepared and rendered audio output. No claim is made that all signals are perceptually seamless or beat aligned.5. **Boundary Continuity Verification**: Computes loop boundary continuity by measuring the wrap delta and subtracting the difference between adjacent samples in the same decoded/resampled buffer at the decoded sample rate, evaluated separately for prepared buffers and rendered output. Artificial control discontinuities must fail; there is no absolute near-zero endpoint sample criterion. Tests verify numeric waveforms rather than subjective listening.+### Loudness Rule++Loudness evaluation uses a unified rule across exporter passes and bundle loading:++- **Measurement** (`sprite_gen/audio/processing.py` `measure`):+ - Integrated loudness follows [ITU-R BS.1770-4](https://www.itu.int/rec/R-REC-BS.1770): double-precision FFmpeg `biquad` K-weighting at 48 kHz, 400 ms gating blocks every 100 ms, absolute gate at -70 LUFS, relative gate 10 LU under absolute-gated loudness. Audio shorter than 400 ms contains no gating block, is unmeasurable, and is refused.+ - True peak is the sample peak after 4x oversampling to 192 kHz (`aresample=192000` then `astats` peak level).+ - Encoded files are measured over normalized PCM frames `[0, N)` (first `N` decoded frames; MP4 edit lists remove AAC priming and Ogg headers remove Opus pre-skip) and over the blocks kept by the PCM's gating. Loops are measured on three repetitions. Reusing PCM gating prevents codec gating shifts: on synthetic FFmpeg 5.1 tests, a 0.6 s hit normalized to -18.15 LUFS had blocks at -18.15, -33.05, and -44.81 LUFS (the second 0.15 LU below the gate); standalone AAC decode lifted that block across the gate to read -21.5 LUFS (Opus: -18.3 LUFS), but reads -18.6 LUFS when measured over PCM blocks.+- **Loudness Goal and Passes** (`loudness_goal`, `meets`):+ - Goal: `--target-lufs` (default -18 LUFS for sfx, -20 LUFS for bgm), unless the normalized PCM is peak-limited (loudness > 0.2 LU below target and true peak within 0.2 dB of the -2 dBTP ceiling, at or above -2.2 dBTP, after gain passes). A peak-limited sound's goal is its PCM loudness (`pcm_lufs`).+ - Every encoded file must measure finite, within 1 LU of the goal, and with true peak <= -1 dBTP.+ - Up to three offline encode passes run per format without provider requests. A pass that misses tightens the PCM limiter by measured overshoot plus 0.5 dB, applies gain `goal - measured loudness`, and re-encodes.+- **Transient Peak Limiting Rationale**: Millisecond transients (clicks, sharp hits) cannot reach integrated loudness targets under a -2 dBTP ceiling without limiter distortion. Synthetic example: a 0.5 s click ends normalization at -24.8 LUFS and -1.8 dBTP after three limiter passes; its OGG measures -25.0 LUFS and M4A -25.4 LUFS, both within 1 LU of that goal.+- **Refusal Criteria**: Refuses silent or unmeasurable audio, true peaks exceeding -1 dBTP, files more than 1 LU from the goal, quiet audio with headroom whose PCM peak never reached the ceiling, and files decoded quieter than their peak-limited PCM.+- **Rejected Alternatives**: Measuring one-shots on repeated context counts a single hit as if it repeated and its repeated blocks still cross the gate together; a separate short-clip measure (maximum momentary loudness, or ungated loudness) would change what the target means for every short sound, and ungated loudness also counts trailing silence.+- **AAC Encoder Configuration**: M4A encodes AAC 192 kbps with [`-aac_coder fast`](https://ffmpeg.org/ffmpeg-codecs.html#aac) ("Worse with low bitrates (less than 64kbps), but is better and much faster at higher bitrates."). In synthetic FFmpeg 5.1 tests, the default `twoloop` coder decoded up to 3.6 dB above PCM true peak (90th percentile 1.4 dB over 320 hits), prompting correction passes that cut transient loudness (a synthetic 0.6 s thud ended at -20.2 LUFS, -2.3 dBTP, and was refused). On a 27-hit sample, `fast` remained within 1.1 dB of PCM true peak (median -0.3 dB) compared to 1.9 dB for `twoloop`.+## Manifest Schema and Coordinates-Outputs `sound.json` (version 2, `kind="sprite-gen-sound"`, `recipe.processing_version=3`, independent of `playback` version 2). Existing output directories generated with recipe versions 1 or 2 are rejected; specify a new `--out-dir`. Original provider request cache keys and blobs remain unchanged; reprocessing cached audio needs no key or new paid request. Provider APIs, caching, and retry behaviors remain unchanged.+Outputs `sound.json` (version 2, `kind="sprite-gen-sound"`, `recipe.processing_version=4`, independent of `playback` version 2). Existing output directories generated with recipe versions 1, 2, or 3 are rejected; specify a new `--out-dir`. Original provider request cache keys and blobs remain unchanged; reprocessing cached audio needs no key or new paid request. Provider APIs, caching, and retry behaviors remain unchanged.### Manifest Properties@@ -68,7 +85,8 @@ Outputs `sound.json` (version 2, `kind="sprite-gen-sound"`, `recipe.processing_v- For looping audio (`loop: true`), `2 <= M < N / 2` (see [helper mapping](#export-signatures) for the export minimum).- Manifest `duration_seconds` is `(N - M) / sample_rate`.- The CLI `--crossfade` parameter (seconds) is converted to integer frame count `M`, defaulting to `min(0.25, requested_duration / 8)`.-- `files`: Format dictionary for `ogg` and `m4a` containing `path`, decoded `duration_seconds` (full decoded file duration, which may include codec priming/tail padding), `lufs`, `true_peak_dbfs`, `sha256`, `encode_passes`, and `pcm_peak_limit_dbtp`.+- `files`: Format dictionary for `ogg` and `m4a` containing `path`, decoded `duration_seconds` (full decoded file duration, which may include codec priming/tail padding), `lufs` (integrated loudness measured over normalized PCM frames and gated blocks; sits below `target_lufs` for peak-limited sounds), `true_peak_dbfs` (true peak level), `sha256`, `encode_passes`, and `pcm_peak_limit_dbtp`.+- `normalization`: Record containing `method` (`"loudnorm-two-pass"` or `"limiter"`), `peak_limit_dbtp` (`-2.0`), `gain_limiter_passes`, `pcm_lufs`, and `pcm_true_peak_dbtp`. The bundle loader requires `pcm_lufs` and `pcm_true_peak_dbtp` to validate against the loudness rule and rejects bundles without them.- **Removed Fields**: `codec_taper_seconds`, `loop_start_seconds`, `loop_end_seconds`, and `crossfade_seconds` are removed from output manifest metadata (the recipe still accepts `--crossfade` in seconds).## Client Playback Helper: sprite-gen-audio-v2.mjsdiff --git a/sprite_gen/audio/manifest.py b/sprite_gen/audio/manifest.pyindex a3aef5f..c61fc2d 100644--- a/sprite_gen/audio/manifest.py+++ b/sprite_gen/audio/manifest.py@@ -8,7 +8,7 @@ import mathfrom pathlib import Pathimport re-from sprite_gen.audio import playback+from sprite_gen.audio import playback, processingdef event_name(value):@@ -40,6 +40,12 @@ def load(path, max_bytes):files = value.get('files')if not isinstance(files, dict) or set(files) != {'ogg', 'm4a'}:raise ValueError('audio source requires ogg and m4a files')+ level = value.get('normalization')+ if not isinstance(level, dict) or not {'pcm_lufs', 'pcm_true_peak_dbtp'} <= set(level):+ raise ValueError('audio source predates sound processing version 4; make it again with sprite-gen sound '+ 'into a new --out-dir (its cached provider audio is reused)')+ goal = processing.loudness_goal(result['target_lufs'], _number(level['pcm_lufs'], 'PCM LUFS', -70, 0),+ _number(level['pcm_true_peak_dbtp'], 'PCM true peak', -100, 0))payloads, sources, size = {}, {path}, 0for fmt in ('ogg', 'm4a'):file = files[fmt]@@ -59,8 +65,8 @@ def load(path, max_bytes):'duration_seconds': _number(file.get('duration_seconds'), 'file duration', frames['end_frame']/frames['sample_rate'], 602),'lufs': _number(file.get('lufs'), 'LUFS', -70, 0),'true_peak_dbfs': _number(file.get('true_peak_dbfs'), 'true peak', -100, -1)}- if abs(record['lufs'] - result['target_lufs']) > 1:- raise ValueError('audio loudness does not match target')+ if not processing.meets(record['lufs'], record['true_peak_dbfs'], goal):+ raise ValueError('audio loudness does not match its target or its peak-limited PCM')result['files'][fmt] = recordpayloads[fmt] = datasources.add(source)diff --git a/sprite_gen/audio/processing.py b/sprite_gen/audio/processing.pyindex e701d40..6f7c080 100644--- a/sprite_gen/audio/processing.py+++ b/sprite_gen/audio/processing.py@@ -15,7 +15,18 @@ from sprite_gen._deps import npfrom sprite_gen.audio import playbackRATE = 48000-PROCESSING_VERSION = 3+PROCESSING_VERSION = 4+PCM_PEAK_DBTP = -2.0 # the normalizer's limiter ceiling+FILE_PEAK_DBTP = -1.0 # no encoded file may decode above this true peak+SETTLED = .2 # normalization stops this close (LU) to the target with its peak this close (dB) to the ceiling+TOLERANCE_LU = 1.0 # an encoded file's loudness may sit this far from its goal+BLOCK, HOP = RATE*2//5, RATE//10 # ITU-R BS.1770-4 gating blocks: 400 ms long, one every 100 ms+# ITU-R BS.1770-4 K-weighting at 48 kHz (the high shelf, then the RLB high-pass), filtered in double precision.+K_WEIGHTING = ('aformat=sample_fmts=dblp,'+ 'biquad=b0=1.53512485958697:b1=-2.69169618940638:b2=1.19839281085285:'+ 'a0=1:a1=-1.69065929318241:a2=0.73248077421585,'+ 'biquad=b0=1:b1=-2:b2=1:a0=1:a1=-1.99004745483398:a2=0.99007225036621,'+ 'aformat=sample_fmts=flt')def require_tools():@@ -63,8 +74,9 @@ def _check_m4a_duration(path, frames):raise ValueError(f'm4a container duration must match the declared {frames} frames at {RATE} Hz')-def measure(samples, target=-18):- result = _ffmpeg([*_pcm_args(), '-af', f'loudnorm=I={target}:TP=-2:LRA=11:print_format=json',+def _loudnorm(samples, target):+ """loudnorm's own first-pass analysis, the parameters of its second pass."""+ result = _ffmpeg([*_pcm_args(), '-af', f'loudnorm=I={target}:TP={PCM_PEAK_DBTP:g}:LRA=11:print_format=json','-f', 'null', '-'], samples.astype('<f4').tobytes())matches = re.findall(r'\{\s*"input_i".*?\}', result.stderr.decode(errors='replace'), re.S)if not matches:@@ -73,6 +85,62 @@ def measure(samples, target=-18):return {k: float(v) for k, v in values.items() if k != 'normalization_type'}+def _block_power(samples):+ """K-weighted mean square of every complete gating block, summed over both channels."""+ result = _ffmpeg([*_pcm_args(), '-af', K_WEIGHTING, '-f', 'f32le', 'pipe:1'], samples.astype('<f4').tobytes())+ weighted = np.frombuffer(result.stdout, dtype='<f4').reshape(-1, 2)+ hops = np.array([np.square(weighted[i:i+HOP], dtype=np.float64).sum()+ for i in range(0, len(weighted) - HOP + 1, HOP)])+ # Four 100 ms hops make one 400 ms block; a clip shorter than one block has none.+ return (hops[:-3] + hops[1:-2] + hops[2:-1] + hops[3:]) / BLOCK+++def _true_peak(samples):+ """Sample peak (dBTP) after 4x oversampling to 192 kHz, as loudnorm reports true peak."""+ result = _ffmpeg([*_pcm_args(), '-af', 'aresample=192000,astats=measure_perchannel=none:measure_overall=Peak_level',+ '-f', 'null', '-'], samples.astype('<f4').tobytes())+ peaks = re.findall(r'Peak level dB:\s*(\S+)', result.stderr.decode(errors='replace'))+ if not peaks:+ raise ValueError('ffmpeg did not report a true peak')+ return float(peaks[-1])+++def measure(samples, gate=None):+ """ITU-R BS.1770-4 integrated loudness (LUFS) and true peak (dBTP) of 48 kHz stereo PCM.++ `gate` is the block selection of the PCM a file was encoded from. The file is then measured+ over the same frames and the same blocks as its PCM: a short clip has two or three blocks,+ and a codec that moves one of them a tenth of a dB across the relative gate would otherwise+ move the file's loudness by whole LU."""+ power = _block_power(samples)+ if gate is None:+ gate = power > 10 ** ((-70 + .691) / 10) # absolute gate, -70 LUFS+ if gate.any():+ gate &= power > power[gate].mean() / 10 # relative gate, 10 LU under the absolute-gated loudness+ elif len(gate) != len(power):+ raise ValueError('an encoded file must be measured over the frames of its PCM')+ mean = power[gate].mean() if gate.any() else 0.+ return {'lufs': -.691 + 10 * math.log10(mean) if mean > 0 else -math.inf,+ 'true_peak': _true_peak(samples), 'gate': gate}+++def loudness_goal(target, pcm_lufs, pcm_peak):+ """The integrated loudness every encoded file of a sound must reach, within TOLERANCE_LU.++ Normalization gains a sound toward the target until its true peak meets the PCM ceiling. A+ sound it leaves short of the target with its peak at that ceiling (a click, a short hit)+ cannot get louder without the limiter rewriting its transient, so its files must match the+ loudness its PCM reached. Every other sound must reach the target."""+ if pcm_lufs < target - SETTLED and pcm_peak >= PCM_PEAK_DBTP - SETTLED:+ return pcm_lufs+ return target+++def meets(lufs, peak, goal):+ """The one loudness check of an encoded file."""+ return math.isfinite(lufs) and abs(lufs - goal) <= TOLERANCE_LU and peak <= FILE_PEAK_DBTP++def limit_gain(samples, gain, ceiling, loop):context = np.tile(samples, (3, 1)) if loop else sampleslimit = 10 ** (ceiling / 20)@@ -85,31 +153,36 @@ def limit_gain(samples, gain, ceiling, loop):def normalize(samples, target, loop):+ """The PCM to encode, its manifest `normalization` record, and its measure."""# Repeated context avoids loudnorm's startup/lookahead envelope at the loop boundary.source = np.tile(samples, (3, 1)) if loop else samples- measured = measure(source, target)- if not all(math.isfinite(measured[k]) for k in ('input_i', 'input_tp', 'input_thresh', 'target_offset')):+ if not math.isfinite(measure(source)['lufs']):raise ValueError('silent or unmeasurable audio cannot be loudness normalized')- filt = (f'loudnorm=I={target}:TP=-2:LRA=11:measured_I={measured["input_i"]}:'- f'measured_TP={measured["input_tp"]}:measured_LRA={measured["input_lra"]}:'- f'measured_thresh={measured["input_thresh"]}:offset={measured["target_offset"]}:linear=true')- result = _ffmpeg([*_pcm_args(), '-af', filt, '-ar', str(RATE), '-f', 'f32le', 'pipe:1'],- source.astype('<f4').tobytes())- output = np.frombuffer(result.stdout, dtype='<f4').reshape(-1, 2).copy()- output = output[len(samples):2*len(samples)] if loop else output[:len(samples)]+ measured, output, method = _loudnorm(source, target), samples, 'limiter'+ # loudnorm's first pass over some short clips measures its own output at -inf LUFS, so it+ # has no second-pass offset; such a clip starts the limiter passes below as decoded.+ if all(math.isfinite(measured[k]) for k in ('input_i', 'input_tp', 'input_thresh', 'target_offset')):+ filt = (f'loudnorm=I={target}:TP={PCM_PEAK_DBTP:g}:LRA=11:measured_I={measured["input_i"]}:'+ f'measured_TP={measured["input_tp"]}:measured_LRA={measured["input_lra"]}:'+ f'measured_thresh={measured["input_thresh"]}:offset={measured["target_offset"]}:linear=true')+ result = _ffmpeg([*_pcm_args(), '-af', filt, '-ar', str(RATE), '-f', 'f32le', 'pipe:1'],+ source.astype('<f4').tobytes())+ output = np.frombuffer(result.stdout, dtype='<f4').reshape(-1, 2).copy()+ output = output[len(samples):2*len(samples)] if loop else output[:len(samples)]+ method = 'loudnorm-two-pass'corrections = 0# A short transient can make loudnorm stop at the peak ceiling below the LUFS target.# Measure the actual playback, then apply gain with an oversampled lookahead limiter.# These are local DSP passes over the paid source, never provider retries.- for _ in range(3):- context = np.tile(output, (3, 1)) if loop else output- stats = measure(context, target)- if abs(stats['input_i'] - target) <= .2 and stats['input_tp'] <= -1.8:+ while True:+ stats = measure(np.tile(output, (3, 1)) if loop else output)+ if corrections == 3 or (abs(stats['lufs'] - target) <= SETTLED and+ stats['true_peak'] <= PCM_PEAK_DBTP + SETTLED):break- gain = target - stats['input_i']- output = limit_gain(output, gain, -2, loop)+ output = limit_gain(output, target - stats['lufs'], PCM_PEAK_DBTP, loop)corrections += 1- return output, corrections+ return output, {'method': method, 'peak_limit_dbtp': PCM_PEAK_DBTP, 'gain_limiter_passes': corrections,+ 'pcm_lufs': stats['lufs'], 'pcm_true_peak_dbtp': stats['true_peak']}, statsdef export(source: Path, out_dir: Path, *, target_lufs, loop, crossfade):@@ -117,13 +190,16 @@ def export(source: Path, out_dir: Path, *, target_lufs, loop, crossfade):frames = playback.validate({'version': playback.VERSION, 'sample_rate': RATE,'start_frame': 0, 'end_frame': len(samples),'overlap_frames': round(crossfade*RATE) if loop else 0}, loop)- samples, corrections = normalize(samples, target_lufs, loop)+ samples, normalization, pcm = normalize(samples, target_lufs, loop)+ goal = loudness_goal(target_lufs, pcm['lufs'], pcm['true_peak'])files = {}+ # The twoloop AAC coder rebuilds a limited transient up to several dB over its PCM true peak;+ # FFmpeg documents the fast coder as the better one above 64 kbps (docs/sound.md).for fmt, codec in (('ogg', ['-c:a', 'libopus', '-b:a', '160k']),- ('m4a', ['-c:a', 'aac', '-b:a', '192k', '-movflags', '+faststart',+ ('m4a', ['-c:a', 'aac', '-aac_coder', 'fast', '-b:a', '192k', '-movflags', '+faststart','-movie_timescale', str(RATE)])):path = out_dir / f'sound.{fmt}'- encoded_samples, ceiling = samples, -2.0+ encoded_samples, ceiling = samples, PCM_PEAK_DBTPfor attempt in range(3):_ffmpeg([*_pcm_args(), '-map_metadata', '-1', *codec, str(path)], encoded_samples.astype('<f4').tobytes())if fmt == 'm4a':@@ -132,19 +208,20 @@ def export(source: Path, out_dir: Path, *, target_lufs, loop, crossfade):if len(decoded) < len(samples):raise ValueError(f'{fmt} truncated the audio')interval = decoded[:len(samples)] # AAC may retain a final partial codec frame.- measured = measure(np.tile(interval, (3, 1)) if loop else interval, target_lufs)- lufs, peak = measured['input_i'], measured['input_tp']- if math.isfinite(lufs) and abs(lufs - target_lufs) <= 1 and peak <= -1:+ measured = measure(np.tile(interval, (3, 1)) if loop else interval, pcm['gate'])+ lufs, peak = measured['lufs'], measured['true_peak']+ if meets(lufs, peak, goal):breakif not math.isfinite(lufs) or attempt == 2:- raise ValueError(f'{fmt} failed loudness/peak check ({lufs:g} LUFS, {peak:g} dBTP); cached source retained')+ raise ValueError(f'{fmt} failed loudness/peak check ({lufs:g} LUFS, {peak:g} dBTP; needs {goal:g} '+ f'+/-{TOLERANCE_LU:g} LUFS at <= {FILE_PEAK_DBTP:g} dBTP); cached source retained')# Lossy codec reconstruction can overshoot PCM peaks. Tighten the PCM limiter# by the measured overshoot plus headroom, then encode and measure again.- ceiling -= max(0, peak + 1.5) if peak > -1 else 0- encoded_samples = limit_gain(encoded_samples, target_lufs - lufs, ceiling, loop)+ ceiling -= max(0, peak + 1.5) if peak > FILE_PEAK_DBTP else 0+ encoded_samples = limit_gain(encoded_samples, goal - lufs, ceiling, loop)files[fmt] = {'path': path.name, 'duration_seconds': len(decoded)/RATE,'lufs': lufs, 'true_peak_dbfs': peak, 'encode_passes': attempt + 1,'pcm_peak_limit_dbtp': ceiling,'sha256': hashlib.sha256(path.read_bytes()).hexdigest()}return {'files': files, 'duration_seconds': playback.duration(frames), 'playback': frames,- 'normalization': {'method': 'loudnorm-two-pass', 'peak_limit_dbtp': -2, 'gain_limiter_passes': corrections}}+ 'normalization': normalization}diff --git a/tests/audio/test_sound.py b/tests/audio/test_sound.pyindex e225197..5c210e0 100644--- a/tests/audio/test_sound.py+++ b/tests/audio/test_sound.py@@ -3,6 +3,7 @@ from concurrent.futures import ThreadPoolExecutorimport ioimport http.clientimport json+import reimport subprocessimport threadingimport urllib.error@@ -12,6 +13,7 @@ import numpy as npimport pytestfrom sprite_gen.audio import cache, provider, processing, sound+from sprite_gen.audio.manifest import load as load_soundfrom sprite_gen.gen import retry@@ -33,6 +35,159 @@ def wav_bytes(seconds=3):return data.getvalue()+def stereo_wav(x, rate=48000):+ data = io.BytesIO()+ with wave.open(data, 'wb') as f:+ f.setnchannels(2)+ f.setsampwidth(2)+ f.setframerate(rate)+ f.writeframes((np.clip(x, -1, 1) * 32767).astype('<i2').tobytes())+ return data.getvalue()+++def hit(seconds, body_hz, body_tau, sweep, knock_hz, knock_tau, knock_gain, noise_tau, noise_gain, smooth, stereo, seed):+ """A synthetic hit: a pitch-dropping body, a knock and a noise burst decaying from one onset."""+ t = np.arange(round(seconds * 48000)) / 48000+ body = np.sin(2*np.pi*np.cumsum(body_hz*(1 + sweep*np.exp(-t/.03)))/48000) * np.exp(-t/body_tau)+ knock = knock_gain * np.sin(2*np.pi*knock_hz*t) * np.exp(-t/knock_tau)+ noise = np.random.default_rng(seed).standard_normal((len(t), 2))+ noise[:, 1] = (1-stereo)*noise[:, 0] + stereo*noise[:, 1]+ if smooth > 1:+ noise = np.stack([np.convolve(n, np.ones(smooth)/smooth, 'same') for n in noise.T], axis=1) * np.sqrt(smooth)+ x = .25 * ((body + knock)[:, None] + noise*(noise_gain*np.exp(-t/noise_tau))[:, None])+ x[:16] *= np.linspace(0, 1, 16)[:, None]+ return stereo_wav(x)+++HITS = {+ # A thud whose AAC reconstruction overshoots the limited PCM peak by several dB.+ 'thud': dict(seconds=.6, body_hz=77.19, body_tau=.1322, sweep=.3641, knock_hz=704.9, knock_tau=.03642,+ knock_gain=.8461, noise_tau=.04146, noise_gain=.881, smooth=2, stereo=.7, seed=634996),+ # A few milliseconds of energy: at the -2 dBTP limiter ceiling it cannot reach -18 LUFS.+ 'click': dict(seconds=.5, body_hz=900, body_tau=.003, sweep=0, knock_hz=2500, knock_tau=.002,+ knock_gain=.5, noise_tau=.002, noise_gain=1, smooth=1, stereo=0, seed=7),+ # loudnorm's dynamic analysis of this short hit reports no output loudness.+ 'unanalysable': dict(seconds=.6, body_hz=55.03, body_tau=.09572, sweep=2.822, knock_hz=692.4, knock_tau=.01984,+ knock_gain=.2113, noise_tau=.01464, noise_gain=.8967, smooth=1, stereo=.3, seed=212970),+}+++def bundle(tmp_path, monkeypatch, name, seconds):+ monkeypatch.setattr(provider, 'generate', lambda req: (hit(**HITS[name]), {}))+ return sound.generate(kind='sfx', prompt='synthetic hit', duration=seconds, event='hit',+ cache_dir=tmp_path/'cache', out_dir=tmp_path/'out')++[email protected]('name', HITS)+def test_short_hits_pass_the_one_loudness_rule(tmp_path, monkeypatch, name):+ result = bundle(tmp_path, monkeypatch, name, HITS[name]['seconds'])+ level = result['normalization']+ goal = processing.loudness_goal(-18, level['pcm_lufs'], level['pcm_true_peak_dbtp'])+ if name == 'click':+ assert level['pcm_true_peak_dbtp'] >= -2.2 and goal == level['pcm_lufs'] < -19+ else:+ assert goal == -18+ if name == 'unanalysable':+ assert level['method'] == 'limiter'+ for file in result['files'].values():+ assert processing.meets(file['lufs'], file['true_peak_dbfs'], goal)+ assert file['true_peak_dbfs'] <= -1+ load_sound(tmp_path/'out'/'sound.json', 50_000_000)+++def test_a_bundle_is_refused_when_its_files_miss_the_rule(tmp_path, monkeypatch):+ bundle(tmp_path, monkeypatch, 'click', .5)+ path = tmp_path/'out'/'sound.json'+ original = json.loads(path.read_text())+ headroom = json.loads(path.read_text())+ headroom['normalization']['pcm_true_peak_dbtp'] = -8 # quiet with headroom: the goal is the target+ hot = json.loads(path.read_text())+ hot['files']['m4a']['true_peak_dbfs'] = -.5+ old = json.loads(path.read_text())+ del old['normalization']+ for manifest, refusal in ((headroom, 'does not match'), (hot, 'invalid audio true peak'), (old, 'version 4')):+ path.write_text(json.dumps(manifest))+ with pytest.raises(ValueError, match=refusal):+ load_sound(path, 50_000_000)+ path.write_text(json.dumps(original))+ load_sound(path, 50_000_000)+++def test_the_rule_needs_a_peak_reason_and_never_relaxes_the_peak():+ assert processing.loudness_goal(-18, -24, -8) == -18 # quiet with headroom+ assert processing.loudness_goal(-18, -18.1, -2) == -18 # normalized to the target+ assert processing.loudness_goal(-18, -24, -2.1) == -24 # peak-limited+ assert processing.meets(-24.3, -1.9, -24) and not processing.meets(-25.2, -1.9, -24)+ assert not processing.meets(-24, -.5, -24) and not processing.meets(-18, -.9, -18)+ assert not processing.meets(float('-inf'), -50, -18)++[email protected]('case', ['headroom', 'hot'])+def test_export_refuses_a_quiet_file_with_headroom_and_a_hot_peak(tmp_path, monkeypatch, case):+ t = np.arange(48000) / 48000+ pcm = np.stack([np.sin(2*np.pi*440*t)]*2, axis=1) * (.01 if case == 'headroom' else .1365)+ if case == 'hot':+ pcm[24000:24048] = .94 # about -18 LUFS with a -0.5 dBTP spike+ stats = processing.measure(pcm)+ record = {'pcm_lufs': stats['lufs'], 'pcm_true_peak_dbtp': stats['true_peak']}+ decode = processing.decode+ monkeypatch.setattr(processing, 'decode', lambda path: pcm.copy() if path.name == 'source' else decode(path))+ monkeypatch.setattr(processing, 'normalize', lambda samples, target, loop: (samples, record, stats))+ monkeypatch.setattr(processing, 'limit_gain', lambda samples, *a: samples) # no correction can rescue it+ with pytest.raises(ValueError, match='ogg failed loudness/peak check') as refusal:+ processing.export(tmp_path/'source', tmp_path, target_lufs=-18, loop=False, crossfade=0)+ lufs, peak = map(float, re.search(r'\(([-\d.]+) LUFS, ([-\d.]+) dBTP', str(refusal.value)).groups())+ if case == 'headroom':+ assert lufs < -30 and peak < -30+ else:+ assert abs(lufs + 18) <= 1 and peak > -1++[email protected]('seconds', [0, .3])+def test_silent_or_unmeasurable_audio_is_refused(tmp_path, seconds):+ source = tmp_path/'source.wav'+ t = np.arange(round(seconds*48000) or 48000) / 48000+ source.write_bytes(stereo_wav(np.stack([np.sin(2*np.pi*440*t)*(seconds > 0)*.5]*2, axis=1)))+ with pytest.raises(ValueError, match='silent or unmeasurable'): # 0.3 s is shorter than one 400 ms block+ processing.export(source, tmp_path, target_lufs=-18, loop=False, crossfade=0)+++def test_formats_are_measured_over_their_pcm_frames_and_blocks(tmp_path, monkeypatch):+ frames, at = 28800, (6000, 17000)+ x = np.zeros((frames, 2))+ k = np.arange(-64, 65)+ for frame in at:+ x[frame-64:frame+65] += (.5*np.sinc(k/2.5)*np.hanning(len(k)))[:, None]+ source = tmp_path/'source.wav'+ source.write_bytes(stereo_wav(x))+ measure, seen, pcm = processing.measure, [], {}+ def spy(samples, gate=None):+ seen.append((samples.copy(), gate))+ return measure(samples, gate)+ def settled(samples, target, loop):+ pcm.update(measure(samples))+ return samples, {'pcm_lufs': pcm['lufs'], 'pcm_true_peak_dbtp': pcm['true_peak']}, pcm+ monkeypatch.setattr(processing, 'measure', spy)+ monkeypatch.setattr(processing, 'normalize', settled)+ target = measure(processing.decode(source))['lufs'] # two clicks; their own loudness is the goal+ result = processing.export(source, tmp_path, target_lufs=target, loop=False, crossfade=0)+ assert {file['encode_passes'] for file in result['files'].values()} == {1} and len(seen) == 2+ for samples, gate in seen:+ assert gate is pcm['gate'] and len(samples) == frames+ peaks = [int(np.argmax(np.abs(samples[f-1000:f+1000, 0]))) + f - 1000 for f in at]+ assert all(abs(p - f) <= 2 for p, f in zip(peaks, at)), peaks+++def test_a_block_at_the_relative_gate_cannot_move_a_file_by_whole_lu():+ t = np.arange(28800) / 48000+ level = np.where(t < .1, 1, np.where(t < .5, .107, .0333)) # the last block sits 0.2 dB under the gate+ pcm = np.stack([np.sin(2*np.pi*1000*t)*level*.3]*2, axis=1)+ codec = pcm * np.where(t < .5, 1, 2.5)[:, None] # a change in the last 100 ms lifts it over the gate+ reference = processing.measure(pcm)+ assert abs(processing.measure(codec)['lufs'] - reference['lufs']) > 1+ assert abs(processing.measure(codec, reference['gate'])['lufs'] - reference['lufs']) < .05++def test_provider_contract_and_safe_retry(monkeypatch, capsys):requests = []class Answer:@@ -207,9 +362,9 @@ def test_export_keeps_source_frames_until_browser_preparation(tmp_path, monkeypaseen = []def normalize(samples, target, loop):seen.append(samples.copy())- return samples, 0+ return samples, {}, {'lufs': -20, 'true_peak': -2, 'gate': None}monkeypatch.setattr(processing, 'normalize', normalize)- monkeypatch.setattr(processing, 'measure', lambda *a: {'input_i': -20, 'input_tp': -2})+ monkeypatch.setattr(processing, 'measure', lambda *a: {'lufs': -20, 'true_peak': -2, 'gate': None})processing.export(tmp_path/'source', tmp_path, target_lufs=-20, loop=True, crossfade=.25)np.testing.assert_array_equal(seen[0], x)@@ -265,7 +420,7 @@ def test_missing_ffprobe_preflights_before_generation(tmp_path, monkeypatch):cache_dir=tmp_path/'cache', out_dir=tmp_path/'out')[email protected]('old_version', [1, 2])[email protected]('old_version', [1, 2, 3])def test_old_processed_output_is_rejected_but_raw_cache_survives(tmp_path, monkeypatch, old_version):calls = []monkeypatch.setattr(provider, 'generate', lambda req: (calls.append(req) or wav_bytes(), {}))@@ -273,7 +428,7 @@ def test_old_processed_output_is_rejected_but_raw_cache_survives(tmp_path, monkecache_dir=tmp_path/'cache', out_dir=tmp_path/'out')result = sound.generate(**kw)assert result['version'] == 2- assert result['recipe']['processing_version'] == 3+ assert result['recipe']['processing_version'] == 4old = {**result, 'version': old_version, 'recipe': {**result['recipe'], 'processing_version': old_version}}(kw['out_dir']/'sound.json').write_text(json.dumps(old))with pytest.raises(ValueError, match='different sound'):diff --git a/tests/compose/test_game_pack_audio.py b/tests/compose/test_game_pack_audio.pyindex dd54fc5..f520f1a 100644--- a/tests/compose/test_game_pack_audio.py+++ b/tests/compose/test_game_pack_audio.py@@ -22,6 +22,7 @@ def inputs(tmp_path):'true_peak_dbfs':-2, 'sha256':hashlib.sha256(data).hexdigest()}manifest = {'kind':'sprite-gen-sound','version':2,'event':'combat.hit', 'audio_kind':'sfx','loop':False,'duration_seconds':1,'target_lufs':-18,'files':files,+ 'normalization': {'pcm_lufs':-18, 'pcm_true_peak_dbtp':-2},'playback': {'version':2, 'sample_rate':48000, 'start_frame':0,'end_frame':48000, 'overlap_frames':0}}(source/'sound.json').write_text(json.dumps(manifest))@@ -57,7 +58,8 @@ def test_optional_audio_preserves_image_only_bytes_and_packs_events(tmp_path):assert not (tmp_path/'small').exists()[email protected]('defect', ['duplicate', 'traversal', 'digest', 'nonfinite', 'badloop', 'old', 'fraction', 'overlap'])[email protected]('defect', ['duplicate', 'traversal', 'digest', 'nonfinite', 'badloop', 'old', 'fraction', 'overlap',+ 'prerule', 'quiet'])def test_broken_audio_cannot_publish_a_partial_pack(tmp_path, defect):path, request, manifest = inputs(tmp_path)request['audio'] = [{'id':'hit','source':'audio/sound.json'}]@@ -69,6 +71,8 @@ def test_broken_audio_cannot_publish_a_partial_pack(tmp_path, defect):if defect == 'old': manifest['version'] = 1if defect == 'fraction': manifest['playback']['end_frame'] = 48000.5if defect == 'overlap': manifest['playback']['overlap_frames'] = 24000+ if defect == 'prerule': del manifest['normalization']+ if defect == 'quiet': manifest['files']['m4a']['lufs'] = -19.5 # under the target, its PCM not peak-limitedpath.write_text(json.dumps(request))(tmp_path/'audio'/'sound.json').write_text(json.dumps(manifest))with pytest.raises(ValueError): pack(path, tmp_path/'bad')