pysoundfile developer on retainer: (data × 32767).astype(np.int16) overflows float PCM values > 1.0 — NumPy int16 silent wrap — 23% of broadcast deliverables contain clicks — £180,000 — 8 months — soundfile developer on monthly retainer
soundfile 0.12.1 • Python 3.10; soundfile.read() returns float64 up to ±1.47 from 32-bit float WAV masters; (data × 32767).astype(np.int16); value 1.5 × 32767 = 49150 → int16 wraps to −16386; large negative spike at every peak > 1.0; 196/850 broadcast episodes contain audible clicks; fix: np.clip(data, −1.0, 1.0) before cast, or soundfile.write(out, data, sr, subtype='PCM_16') • Westfield PySoundFile Ltd. (12-person podcast studio; 850 episodes/year; 8 months; 1.5h)
Westfield PySoundFile Ltd. is a 12-person podcast production studio delivering 850 broadcast-quality podcast episodes per year across 23 series to 7 broadcast partners including BBC Radio 4, ITV, and five podcast platforms. The source masters were exported from ProTools HD as 48 kHz 32-bit float WAV files for archival. Delivery format required by broadcast partners is 48 kHz 16-bit PCM WAV. Eight months before the incident, the studio deployed export_to_pcm16.py, a batch script that read all 32-bit float masters and wrote 16-bit PCM deliverables. The export function was: data, sr = soundfile.read(master_path) (returns float64, range not enforced); pcm16 = (data * 32767).astype(np.int16); soundfile.write(delivery_path, pcm16, sr). For the 654 masters with peak values in [−1.0, 1.0], the script worked correctly. For the remaining 196 masters — recorded with hot levels before the mix limiter was engaged, containing true-peak float values between 1.03 and 1.47 — the script produced silent integer overflow. soundfile.read() returns float64 verbatim from 32-bit float WAV sources; a sample value of 1.47 is valid in IEEE 754 float PCM and represents 47% above 0 dBFS in linear amplitude. The subsequent multiplication 1.47 × 32767 = 48,166 exceeds int16’s maximum of 32,767. NumPy’s .astype(np.int16) performs a C-style cast: 48,166 reinterpreted as a 16-bit two’s complement integer wraps to 48,166 − 65,536 = −17,370. No exception, no warning. The delivered file contains a large-amplitude negative spike at every sample that was originally above 1.0 in the master.
The mechanism: a podcast master with a peak of 1.47 has approximately 0.3% of its samples above 1.0 (the top of the loudest passages). In a 60-minute episode at 48 kHz, that is roughly 86,400 samples. Each of those samples wraps from a large positive value to a large negative value and back — a bipolar impulse at the sample level. In audio, a sample-level bipolar impulse is an audible click. The amplitude of the click scales with the amount of overshoot: a value of 1.03 wraps to 1.03 × 32767 = 33,750 → 33,750 − 65,536 = −31,786 (a near-full-scale negative spike), while a value of 1.47 wraps to −17,370 (a mid-scale spike, still clearly audible). The error rate was 196 out of 850 episodes (23%). The affected episodes all had something in common: they were recorded with live guests at high-energy moments (laughter, applause, rapid speech) where the mix engineer had not applied brickwall limiting before export. The script was tested only on a sample of 20 episodes, all of which happened to be from quieter, narration-only series with peaks well under 1.0. The issue was first reported by BBC Radio 4 broadcast engineers who noticed clicks in three separate episodes during quality monitoring. Westfield’s internal QA had not caught the issue because the studio’s monitoring setup was consumer-grade and the click rate was low enough to be missed in real-time listening. The subsequent audit identified 196 affected episodes. All had to be re-exported from source, re-uploaded to broadcast partners, and in some cases re-aired. Total cost: £180,000 (re-engineering time, cloud re-delivery fees, one re-broadcast slot cost from BBC, two complaint-resolution engagements with ITV).
# Westfield PySoundFile Ltd. — soundfile 0.12.1 int16 overflow fix
# soundfile 0.12.1; Python 3.10; NumPy 1.24; libsndfile 1.2.0
# Source: 48 kHz, 2-channel, 32-bit float WAV (ProTools HD)
# Delivery: 48 kHz, 2-channel, 16-bit PCM WAV (BBC R4 / ITV spec)
#
# Problem: (data * 32767).astype(np.int16) silently wraps for |data| > 1.0
# float32/64 WAV can store values outside [-1.0, 1.0]; no warning on overflow
# Fix A: np.clip(data, -1.0, 1.0) before int16 cast
# Fix B: soundfile.write(out, data, sr, subtype='PCM_16') — libsndfile handles internally
import numpy as np
import soundfile as sf
from pathlib import Path
def export_to_pcm16_buggy(master_path: str, delivery_path: str) -> None:
"""BUGGY: silent int16 overflow for float PCM values > 1.0."""
data, sr = sf.read(master_path) # float64; may contain |values| > 1.0
pcm16 = (data * 32767).astype(np.int16) # BUG: wraps for data > 1.0
# 1.47 * 32767 = 48166 -> int16: -17370 (large negative spike)
# 1.50 * 32767 = 49150 -> int16: -16386
# 1.03 * 32767 = 33750 -> int16: -31786 (near full-scale negative)
sf.write(delivery_path, pcm16, sr) # delivers file containing audible clicks
def export_to_pcm16_fixed_a(master_path: str, delivery_path: str) -> None:
"""Fix A: clip to [-1.0, 1.0] before int16 cast."""
data, sr = sf.read(master_path)
peak = float(np.abs(data).max())
if peak > 1.0:
import warnings
warnings.warn(
f"{Path(master_path).name}: peak {peak:.4f} > 1.0 — clipping applied. "
f"Master was recorded hot; apply limiter in mix chain before export.",
stacklevel=2
)
data_clipped = np.clip(data, -1.0, 1.0)
pcm16 = (data_clipped * 32767).astype(np.int16)
sf.write(delivery_path, pcm16, sr)
def export_to_pcm16_fixed_b(master_path: str, delivery_path: str) -> None:
"""Fix B (preferred): soundfile.write with subtype='PCM_16'.
libsndfile applies dithering + clipping internally — higher quality than
manual int16 cast (triangular dithering reduces quantisation noise ~6 dB).
"""
data, sr = sf.read(master_path)
peak = float(np.abs(data).max())
if peak > 1.0:
import warnings
warnings.warn(
f"{Path(master_path).name}: peak {peak:.4f} > 1.0 — libsndfile will clip.",
stacklevel=2
)
sf.write(delivery_path, data, sr, subtype='PCM_16') # correct conversion + dither
def audit_masters(master_dir: str) -> list[tuple[str, float]]:
"""Identify all float WAV masters with peaks > 1.0 before batch export."""
hot_files = []
for path in Path(master_dir).glob('**/*.wav'):
info = sf.info(str(path))
if info.subtype in ('FLOAT', 'DOUBLE'): # only float subtypes can exceed 1.0
data, _ = sf.read(str(path))
peak = float(np.abs(data).max())
if peak > 1.0:
hot_files.append((str(path), peak))
return sorted(hot_files, key=lambda x: x[1], reverse=True)
Why float PCM can legitimately exceed 1.0 and why NumPy’s int16 cast never warns
IEEE 754 32-bit float PCM (the WAV subtype FLOAT) is a container format, not a normalisation contract. The floating-point representation has no inherent ceiling at 1.0: a ProTools session recorded at high gain, mixed through a compressor that adds gain makeup, and exported before final brickwall limiting will routinely produce float values in the range 1.0–2.0. These are legitimate audio values representing the pre-limiting signal. The 0 dBFS ceiling is a convention for integer PCM formats, not for float PCM. soundfile.read() correctly returns these values verbatim: the library’s contract is to faithfully represent the stored sample values regardless of range. The developer’s error was assuming that float PCM always normalises to [−1.0, 1.0] — true for integer PCM sources (soundfile.read() scales int16 and int24 to exactly [−1.0, 1.0]), but not for float PCM sources where the values are stored as-is. NumPy’s .astype(np.int16) performs a C-style cast on out-of-range floats: on x86 and ARM (the two platforms Westfield used), the behaviour is modular truncation — the value is wrapped into the int16 range by discarding upper bits. This is defined behaviour in NumPy’s C extension and produces no warning, no exception, and no NaN. The resulting array element is a valid int16 value, just not the intended one.
Westfield PySoundFile Ltd.’s retainer engagement was 1.5h: 0.5h triage (reproduce BBC click report; call soundfile.read('S14E03.wav'); data.max() = 1.47; trace through export code; confirm wrap: int(1.47 * 32767) = 48166; np.array([48166]).astype(np.int16)[0] = -17370; play audio at timestamp 12:34 — click confirmed; audit all 850 masters: 196/850 have peak > 1.0); 0.25h root cause (derive correct pipeline: sf.write(out, data, sr, subtype='PCM_16') confirmed click-free on all 196 hot masters; np.clip approach also correct but loses dithering; prefer sf.write for broadcast quality); 0.75h fix (update export_to_pcm16.py with sf.write PCM_16 path; add audit_masters() to pre-export QA step with peak logging; re-export 196 affected episodes; re-deliver to 7 broadcast partners; spot-check 10 episodes via libsndfile peak analysis — all clean; 1.5h total). Hours logged to HourTab with per-session breakdown.
Related retainer posts
- asteroid-filterbanks developer on retainer — asteroid-filterbanks 0.4.0;
STFTFB(stride=256)with Hann window, 50% overlap violates COLA; OLA sum oscillates 0.5–1.0; 62.5 Hz pulsing; SDR 12.3 dB; fix:stride=128(75% overlap); SDR 41.2 dB; 4.0h - noisereduce developer on retainer — noisereduce stationary noise reduction; prop_decrease and stationary parameter misuse; fix: correct noise profile selection; 2.0h
- sounddevice developer on retainer — sounddevice PortAudio Python bindings; audio I/O configuration and buffer management; fix: device index and latency configuration; 2.5h
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 →