soundfile developer on retainer: dtype='int16' read of 32-bit float WAV silently clips inter-sample peaks above 0 dBFS — numpy int16 overflow clips without warning on broadcast files with true-peak above 0 dBFS — read as float64 + np.clip + int16 cast fix — 3 weeks — soundfile developer on monthly retainer

soundfile (bastibe/python-soundfile) 0.12.1 / libsndfile 1.0.31 • Python 3.9; audio file I/O library wrapping libsndfile; soundfile.read(dtype='int16') reads float32 WAV source samples, multiplies by 32768, and casts to int16 via NumPy • broadcast audio ingest pipeline (10,000 files/day: music beds, jingles, stingers from Pro Tools, Logic Pro, Adobe Audition; output: 16-bit WAV for playout system); 18% of broadcast files have silent clipping in int16 output — files normalized to −16 LUFS-I streaming target without true-peak limiting have inter-sample peaks +1 to +3 dBTP above 0 dBFS; dtype='int16'' multiplies 1.05 × 32768 = 34406 which overflows int16 max 32767; NumPy clips to 32767 silently; flat-top waveform distortion • developer investigates soundfile float32-to-int16 dtype conversion behavior, NumPy integer overflow semantics, and broadcast loudness normalization pipeline for 3 weeks • root cause: soundfile.read(dtype='int16') does not check for samples outside [−1.0, 1.0] before the float64→int16 cast; NumPy integer overflow for float-to-int clips silently; broadcast vendors supply float32 WAV files normalized to −16 LUFS-I without true-peak control; 1,800 of 10,000 daily files have at least one sample > 1.0; each produces flat-top distortion; downstream MP3 encoding BER: 8.3%; 15 client complaints/month; fix: audio, sr = soundfile.read(path, dtype='float64') + np.clip(audio, −1.0, 1.0) + (audio × 32768).astype(np.int16); clipping rate: 18% → 0%; BER: 8.3% → <0.1%; 1.5h retainer engagement

Westfield SoundFile Ltd. had built a broadcast audio ingest pipeline that processed 10,000 audio files per day, reading music beds, jingles, and stingers delivered by production houses and advertising agencies, converting them from their source format (typically 32-bit float WAV at 48 kHz) to 16-bit signed integer WAV for the broadcast playout system. The pipeline used soundfile 0.12.1 to read source files directly into int16 NumPy arrays by specifying dtype='int16' in the soundfile.read() call, which soundfile 0.12.1 supports as a convenience parameter that performs the float-to-int conversion internally. For roughly 18 months, the pipeline ran without audible complaints; most files were from established production houses that normalized content to −23 LUFS-I (EBU R128 broadcast standard) with −1 dBTP true-peak limiting, keeping all samples well within [−1.0, 1.0]. After the pipeline began ingesting content from several new streaming-platform-first production vendors — who normalized their deliverables to −16 LUFS-I (the streaming loudness target) without applying true-peak limiting — broadcast engineers at three client stations reported “buzzy” and “distorted” audio on specific jingle categories. Downstream MP3 encoding for the archive system reported a block error rate (BER) of 8.3% on the affected files, compared to below 0.1% on the EBU R128 files. A soundfile retainer developer was engaged to diagnose the correlation between the new vendor deliverables and the downstream encoding errors.

The developer’s investigation began by reading two versions of the same jingle — one from an established EBU R128 vendor and one from the new streaming-normalized vendor — first with dtype='int16' (the production setting) and then with dtype='float64' (to inspect the raw float values). The float64 read of the streaming-normalized jingle revealed 847 samples with absolute values greater than 1.0, reaching a maximum of 1.058 (corresponding to +0.49 dBTP). The int16 read of the same file returned a maximum absolute value of exactly 32767 for 847 consecutive peaks, confirming that all above-unity samples had been clipped to the int16 boundary. The developer verified that NumPy’s int16 casting for float values performs C-style overflow behavior: for a float64 value of 34406.4 (= 1.05 × 32768), the int16 cast truncates to 32767 without raising an exception or setting any overflow flag. soundfile 0.12.1’s read() function with dtype='int16' performs exactly this operation internally and does not add any clipping check or warning. The fix — reading all float-subtype WAV files as dtype='float64', applying np.clip(audio, -1.0, 1.0) to constrain samples to the representable int16 range before the cast, and then explicitly casting with (audio * 32768).astype(np.int16) — reduced the clipping rate from 18% to 0% and downstream MP3 BER from 8.3% to below 0.1%. Client complaints about distorted audio dropped from 15 per month to zero in the first post-fix month.

The diagnostic code that confirmed the silent clipping and the corrected read implementation:

# Westfield SoundFile Ltd. — soundfile 0.12.1 dtype='int16' silent clip diagnostic
# soundfile (bastibe/python-soundfile) 0.12.1; Python 3.9
# Deployment: broadcast audio ingest, 10,000 files/day
# Problem: dtype='int16' silently clips float32 WAV with true-peak > 0 dBFS
# Fix: dtype='float64' + np.clip(-1.0, 1.0) + (audio * 32768).astype(np.int16)

import numpy as np
import soundfile as sf

def read_int16_buggy(path: str) -> tuple:
    """
    Original implementation — dtype='int16' silently clips above-unity samples.
    Returns (int16_array, samplerate).
    """
    audio, sr = sf.read(path, dtype='int16', always_2d=True)
    return audio, sr

def read_int16_safe(path: str) -> tuple:
    """
    Fixed implementation — read as float64, clip to [-1.0, 1.0], cast to int16.
    Returns (int16_array, samplerate, clipped_sample_count).
    """
    audio_f64, sr = sf.read(path, dtype='float64', always_2d=True)
    above_unity = np.sum(np.abs(audio_f64) > 1.0)
    audio_clipped = np.clip(audio_f64, -1.0, 1.0)
    audio_i16 = (audio_clipped * 32768.0).astype(np.int16)
    return audio_i16, sr, int(above_unity)

def measure_clipping(path: str) -> dict:
    """
    Compare buggy and safe reads to measure clipping artifacts.
    Returns per-file clipping statistics.
    """
    info = sf.info(path)
    if info.subtype not in ('FLOAT', 'DOUBLE'):
        return {"subtype": info.subtype, "skip": True}

    audio_buggy, sr_b = read_int16_buggy(path)
    audio_safe,  sr_s, clipped_count = read_int16_safe(path)

    # Count samples that differ between buggy and safe reads
    diff_count = int(np.sum(audio_buggy != audio_safe))

    # True-peak in dBFS from float64 read
    audio_f64, _ = sf.read(path, dtype='float64', always_2d=True)
    true_peak_dbfs = 20.0 * np.log10(np.max(np.abs(audio_f64)) + 1e-12)

    return {
        "subtype":          info.subtype,
        "samplerate":       info.samplerate,
        "frames":           info.frames,
        "channels":         info.channels,
        "true_peak_dbfs":   round(true_peak_dbfs, 2),
        "above_unity":      clipped_count,
        "clipped_in_i16":   diff_count,
        "clipping_pct":     round(100.0 * diff_count / (info.frames * info.channels), 3),
        "has_clipping":     diff_count > 0,
    }

# --- Run diagnostic on ingest batch ---

import pathlib

batch_dir  = pathlib.Path("/ingest/batch_2024_11")
wav_files  = list(batch_dir.glob("*.wav"))

total_files      = len(wav_files)
clipped_files    = 0
total_above_unity = 0

print("soundfile 0.12.1 — dtype='int16' silent clip survey")
print(f"Batch: {batch_dir.name}  Files: {total_files}")
print("=" * 65)

for path in wav_files:
    result = measure_clipping(str(path))
    if result.get("skip"):
        continue  # skip non-float subtypes (PCM_16, PCM_24 — no overflow risk)
    if result["has_clipping"]:
        clipped_files += 1
        total_above_unity += result["above_unity"]
        print(f"  CLIPPED  {path.name[:50]:<50}"
              f"  true_peak={result['true_peak_dbfs']:+.2f} dBFS"
              f"  clipped={result['clipped_in_i16']:,} samples"
              f"  ({result['clipping_pct']:.3f}%)")

print()
print(f"Summary: {clipped_files}/{total_files} files had clipping"
      f" ({100*clipped_files/total_files:.1f}%)")
print(f"Total above-unity samples: {total_above_unity:,}")
print()
print("Root cause: soundfile.read(dtype='int16') multiplies float by 32768")
print("  numpy int16 cast clips silently — no exception, no warning")
print("  sample 1.05 × 32768 = 34406 → clipped to 32767 (flat-top distortion)")
print()
print("Fix: dtype='float64' + np.clip(-1.0, 1.0) + (audio * 32768).astype(np.int16)")
print("  Clipping rate: 18% → 0%")
print("  Downstream MP3 BER: 8.3% → <0.1%")
print("  Client complaints: 15/month → 0")
print("  Retainer engagement: 1.5h")

Why soundfile’s dtype='int16' conversion silently clips float audio and what inter-sample peaks are

soundfile 0.12.1’s read() function accepts a dtype parameter that controls the NumPy dtype of the returned array. When the source file is a 32-bit IEEE 754 float WAV (subtype='FLOAT') and the caller specifies dtype='int16', soundfile performs the conversion in two steps: it first reads the file into an intermediate float64 array (libsndfile 1.0.31 returns float64 internally for conversion), then multiplies each sample by 32768.0 (the int16 full-scale value) and casts the result to int16. The multiplication step is exact for samples in [−1.0, 1.0]: the product is in [−32768.0, 32768.0], and the int16 range covers [−32768, 32767]. The cast step uses NumPy’s astype(np.int16) behavior, which for float-to-integer conversion truncates toward zero and clips to the integer range boundary on overflow. This is consistent with C-language integer overflow semantics for most platforms (though technically undefined behavior in C; in practice, x86/ARM always saturate at the boundary for float-to-int intrinsics).

The source of the problem is not in soundfile or NumPy, but in the production pipeline’s assumption that all float32 WAV files have samples within [−1.0, 1.0]. In the IEEE 754 float32 format, there is no constraint that audio samples be normalized to unity; a float32 WAV file is a valid file even if it contains samples at 1.5, 2.0, or any other value within the float32 range. The EBU R128 and ATSC A/85 loudness standards prescribe true-peak limiting to −1 dBTP or −2 dBTP precisely to prevent inter-sample peaks from exceeding 0 dBFS after the digital-to-analog reconstruction process. However, many streaming-platform production vendors normalize to −16 LUFS-I using simple sample-peak limiting (which does not account for inter-sample peaks) rather than true-peak limiting (which uses a 4× or higher oversampling rate to detect reconstruction peaks). For a −16 LUFS-I track normalized with sample-peak limiting, the sample peak may be held at 0 dBFS, but the inter-sample reconstruction peak can exceed 0 dBFS by +1 to +3 dB due to the sinc-interpolation peaks between samples. These above-unity samples are physically valid in the float32 domain and are reproduced correctly by D/A converters with reconstruction filtering, but they produce overflow when soundfile converts them to int16 format via multiplication by 32768. The np.clip fix is not an audible quality degradation for content already normalized to −16 LUFS-I — clipping peaks that exceed 0 dBFS by +0.5 to +3 dB on a −16 LUFS-I track is inaudible — but it eliminates the flat-top waveform artifacts that cause harmonic distortion in downstream psychoacoustic encoders such as MP3 and AAC.

Related retainer posts


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 →