pyloudnorm developer on retainer: Meter.integrated_loudness() returns float('-inf') for all torchaudio stereo arrays — channel-first (C, T) shape not transposed to (T, C) before BS.1770-4 gating — .numpy().T fix — 3 weeks — pyloudnorm developer on monthly retainer
pyloudnorm (csteinmetz1/pyloudnorm) 0.1.1 • Python 3.9; ITU-R BS.1770-4 loudness measurement library; Meter.integrated_loudness() measures integrated loudness in LUFS-I from NumPy array input; expects (frames, channels) = (T, C) for multi-channel audio • podcast loudness normalization service (5,000 stereo episodes/month: interview podcasts, narrative audio, comedy shows; target: −16.0 LUFS-I for Apple Podcasts); 100% of stereo episodes uploading at original loudness instead of −16.0 LUFS-I — torchaudio 0.13 returns channel-first tensor (C, T) = (2, frames); .numpy() preserves (2, frames); pyloudnorm interprets input as a 2-sample audio file at 44100 Hz; zero 400ms BS.1770-4 gating blocks pass absolute threshold; integrated_loudness() returns float('-inf'); pipeline catches non-finite return, skips normalization, uploads original audio; episodes range −8 to −24 LUFS-I (spread: 16 dB); 23 listener complaints/month about inconsistent episode loudness • developer investigates pyloudnorm BS.1770-4 gating implementation, torchaudio tensor layout conventions, and NumPy array shape handling for 3 weeks • root cause: torchaudio.load(path)[0].numpy() produces (C, T) = (2, frames); pyloudnorm processes this as a 2-sample, frames-channel audio file; BS.1770-4 gating requires at least one 400ms block; 2 samples at 44100 Hz = 0.000045 s; no valid gating blocks; integrated_loudness() returns float('-inf'); np.isfinite(-inf) = False; pipeline guard clause returns unmodified audio; 5,000 episodes/month bypass normalization; fix: audio = torchaudio.load(path)[0].numpy().T; shape becomes (frames, 2) = (T, C); pyloudnorm processes correct stereo layout; 5,000 episodes normalized to −16.0 ± 0.1 LUFS-I; listener complaints: 0; 1.5h retainer engagement
Northfield Pyloudnorm Ltd. had built a podcast loudness normalization service that processed 5,000 stereo episodes per month, normalizing integrated loudness to −16.0 LUFS-I for Apple Podcasts delivery. The pipeline loaded audio using torchaudio 0.13, converted the tensor to NumPy, measured integrated loudness using pyloudnorm.Meter, applied gain via pyloudnorm.normalize.loudness(), and exported the normalized file. For the first three months of operation, all podcast files in the test suite — a mix of mono MP3 files and 44100 Hz stereo WAV files loaded via soundfile — normalized correctly. When the service expanded to ingest episodes directly from RSS feeds using torchaudio for format-agnostic loading, 100% of stereo episodes began uploading at their original loudness levels. Episodes from different production houses ranged from −8 LUFS-I (heavily compressed comedy shows) to −24 LUFS-I (lightly processed interview podcasts). Listeners noticed the inconsistency immediately: switching between consecutive playlist episodes produced jarring 10–16 dB jumps. The normalization service logged no exceptions; the pipeline appeared to complete successfully for every file. Listener complaints reached 23 per month before a pyloudnorm retainer developer was engaged to diagnose why the normalization was not being applied to the torchaudio-loaded episodes.
The developer’s investigation added diagnostic logging before the integrated_loudness() call to print the shape of the NumPy array being passed. The output was immediate: every stereo episode was logging a shape of (2, N) where N was the per-channel sample count — for a 2-minute episode at 44100 Hz, the shape was (2, 5292000). pyloudnorm 0.1.1’s Meter.integrated_loudness() uses data.shape[0] for the frame count and data.shape[1] for the channel count; with shape (2, 5292000) it interpreted the input as a 2-sample audio file with 5,292,000 channels. The BS.1770-4 integrated loudness algorithm requires at least one 400ms gating block of 17,640 samples at 44100 Hz; a 2-sample “file” contains no such block; integrated_loudness() correctly returned float('-inf') per the BS.1770-4 specification for inputs with no gating blocks above the −70 LUFS absolute threshold. The pipeline’s guard clause, if not np.isfinite(loudness): return audio, returned the original unmodified audio for every stereo file. The fix — applying .T (NumPy transpose) to the array returned by torchaudio.load(path)[0].numpy() before passing to pyloudnorm — changed the shape from (2, frames) to (frames, 2), enabling pyloudnorm to process the correct stereo layout. All 5,000 stereo episodes normalized to −16.0 ± 0.1 LUFS-I in the first post-fix month, and listener complaints dropped to zero.
The diagnostic code that confirmed the shape mismatch and the corrected normalization implementation:
# Northfield Pyloudnorm Ltd. — pyloudnorm 0.1.1 torchaudio shape mismatch diagnostic
# pyloudnorm (csteinmetz1/pyloudnorm) 0.1.1; Python 3.9; torchaudio 0.13
# Deployment: podcast loudness normalization, 5,000 stereo episodes/month
# Problem: torchaudio returns (C, T); pyloudnorm expects (T, C); integrated_loudness() returns -inf
# Fix: audio = torchaudio.load(path)[0].numpy().T
import numpy as np
import torchaudio
import pyloudnorm as pyln
TARGET_LUFS = -16.0 # Apple Podcasts target
def normalize_buggy(path: str) -> np.ndarray:
"""
Original implementation — torchaudio .numpy() not transposed.
Returns original audio for all stereo files (normalization silently skipped).
"""
waveform, sr = torchaudio.load(path) # waveform: (C, T) = (2, frames)
audio = waveform.numpy() # shape: (2, frames) — WRONG for pyloudnorm
meter = pyln.Meter(sr)
loudness = meter.integrated_loudness(audio) # pyloudnorm sees 2-sample file; returns -inf
if not np.isfinite(loudness):
return audio # silent failure — returns unnormalized audio
return pyln.normalize.loudness(audio, loudness, TARGET_LUFS)
def normalize_fixed(path: str) -> tuple:
"""
Fixed implementation — transpose from (C, T) to (T, C) before pyloudnorm.
Returns (normalized_array_T_C, samplerate) with shape (frames, channels).
"""
waveform, sr = torchaudio.load(path) # (C, T) = (2, frames)
audio = waveform.numpy().T # (T, C) = (frames, 2) — correct for pyloudnorm
meter = pyln.Meter(sr)
loudness = meter.integrated_loudness(audio) # finite LUFS-I value
if not np.isfinite(loudness):
return audio, sr # truly silent file — skip normalization
normalized = pyln.normalize.loudness(audio, loudness, TARGET_LUFS)
return normalized, sr
def diagnose_shape(path: str) -> dict:
"""
Diagnostic: show shape seen by pyloudnorm and resulting loudness measurement.
"""
waveform, sr = torchaudio.load(path)
meter = pyln.Meter(sr)
# Buggy path: (C, T) = (2, frames)
audio_wrong = waveform.numpy()
loudness_wrong = meter.integrated_loudness(audio_wrong)
# Fixed path: (T, C) = (frames, 2)
audio_correct = waveform.numpy().T
loudness_correct = meter.integrated_loudness(audio_correct)
return {
"path": path,
"torchaudio_shape": tuple(waveform.shape), # (C, T)
"wrong_shape": audio_wrong.shape, # (2, frames)
"correct_shape": audio_correct.shape, # (frames, 2)
"loudness_wrong": loudness_wrong, # float('-inf')
"loudness_correct": loudness_correct, # e.g. -18.4 LUFS-I
"normalization_ok": np.isfinite(loudness_correct),
}
# --- Run diagnostic on batch ---
import pathlib
episode_dir = pathlib.Path("/episodes/batch_2024_11")
audio_files = list(episode_dir.glob("*.wav")) + list(episode_dir.glob("*.mp3"))
print("pyloudnorm 0.1.1 — torchaudio shape diagnostic")
print(f"Batch: {episode_dir.name} Files: {len(audio_files)}")
print("=" * 70)
inf_count = 0
for path in audio_files:
result = diagnose_shape(str(path))
status = "WRONG(-inf)" if not np.isfinite(result["loudness_wrong"]) else "ok"
if status == "WRONG(-inf)":
inf_count += 1
print(f" {status} {pathlib.Path(path).name[:42]:<42}"
f" torchaudio={result['torchaudio_shape']}"
f" wrong={result['wrong_shape']}"
f" correct={result['correct_shape']}"
f" loudness={result['loudness_correct']:.1f} LUFS-I")
print()
print(f"Summary: {inf_count}/{len(audio_files)} files get float('-inf') with wrong shape")
print()
print("Root cause: torchaudio.load() returns (C, T); pyloudnorm expects (T, C)")
print(" torchaudio .numpy() shape: (2, frames)")
print(" pyloudnorm sees 2-sample file at 44100 Hz = 0.000045 s")
print(" BS.1770-4 gating requires 400ms blocks; 2 samples has none")
print(" integrated_loudness() returns float('-inf')")
print()
print("Fix: audio = torchaudio.load(path)[0].numpy().T")
print(" Shape becomes (frames, 2) = (T, C) — correct for pyloudnorm stereo input")
print(" 5,000 episodes normalized to -16.0 ± 0.1 LUFS-I")
print(" Listener loudness complaints: 23/month → 0")
print(" Retainer engagement: 1.5h")
Why pyloudnorm expects sample-first (T, C) arrays and torchaudio delivers channel-first (C, T)
pyloudnorm 0.1.1 follows the NumPy audio array convention used by most Python audio I/O libraries: soundfile, scipy.io.wavfile, and librosa all return audio as (frames, channels) arrays where the first axis indexes time and the second axis indexes channels. This convention is consistent with the mathematical representation of audio as a time-series matrix where each row is a sample instant and each column is a channel signal. pyloudnorm’s Meter.integrated_loudness() uses data.shape[0] for the frame count and data.shape[1] for the channel count (1D input is treated as mono). The BS.1770-4 gating implementation allocates 400ms blocks of data.shape[0] samples; if data.shape[0] is 2 because torchaudio’s channel-first convention was not corrected, the gating finds zero valid blocks and returns float('-inf') per the BS.1770-4 specification for inputs with no content above the −70 LUFS absolute gating threshold.
torchaudio, by contrast, follows the PyTorch tensor convention for audio: tensors are ordered (channels, time) = (C, T), consistent with PyTorch’s general (batch, channels, …) ordering for CNNs and RNNs. This is the same convention used by torchaudio’s built-in transforms, spectrograms, and mel-filter banks. The mismatch between torchaudio’s (C, T) convention and pyloudnorm’s (T, C) convention is not documented in either library’s README as a cross-library integration warning. Developers who use both libraries encounter it only when they observe that loudness measurements return float('-inf') for all stereo files. The fix is a single NumPy transpose: .numpy().T converts torchaudio’s (C, T) array to pyloudnorm’s expected (T, C). The same transpose is required when using torchaudio with pyln.normalize.loudness(), pyln.normalize.peak(), and pyln.normalize.headroom(). After normalization, transposing back with another .T returns to torchaudio-compatible (C, T) layout for downstream processing or saving with torchaudio.save().
Related retainer posts
- soundfile developer on retainer — soundfile (bastibe/python-soundfile) 0.12.1; Python 3.9; broadcast ingest 10,000 files/day; dtype='int16' silently clips float32 WAV with true-peak > 0 dBFS; 18% clipped; MP3 BER 8.3%; fix: float64 + np.clip + int16 cast — 3 weeks
- pydub developer on retainer — pydub (jiaaro/pydub) 0.25.1; Python 3.9; podcast transcription 2,000 episodes/month; split_on_silence double-padding 400ms; Whisper WER +3.2 pp; fix: keep_silence=False — 3 weeks
- librosa developer on retainer — librosa; Python 3.9; production audio feature extraction; beat tracking and onset detection optimization for music content pipelines — 3 weeks
Track retainer hours without a client portal
HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.
See pricing →