wavinfo developer on retainer: fmt_chunk.sample_width returns bits (16) — developer treats it as bytes — computed duration 8× too short — 2,700 chapter marks silently dropped across 150-episode podcast library — wavinfo developer on monthly retainer

wavinfo 0.2.1 • Python 3.9; WavInfoReader reads fmt_chunk.sample_width = 16 (bits per sample); developer computes duration = data_chunk.byte_count / (sample_rate × channel_count × sample_width); sample_width=16 (bits) treated as 16 bytes/sample → denominator 8× too large; 60-minute episode computed as 7.5 minutes; editorial tool validates: if marker_time > computed_duration → DROP; all chapter marks beyond 7:30 silently discarded; 2,700 marks lost across 150 episodes; 6 weeks undetected; fix: sample_width // 8 or use data_chunk.frame_count • Northfield Wavinfo Ltd. (podcast editorial platform; 44.1 kHz stereo 16-bit; 60-minute interviews; 6 weeks; 2.0h)

Northfield Wavinfo Ltd. built a podcast editorial platform for a mid-size production company with 150 published episodes. The editorial workflow: upload a WAV file, the platform reads its duration with wavinfo.WavInfoReader, editors watch the audio player and click to place named chapter marks (e.g., “Introduction”, “Guest Background”, “Main Interview”, “Q&A”, “Closing”) at specific timestamps, the platform stores those timestamps and titles in a PostgreSQL table, and the podcast feed generator later reads that table to embed chapter marks in the MP3 RSS output. Interviews ran 55–75 minutes. All WAV files were 44.1 kHz stereo 16-bit PCM, delivered from an Audacity export pipeline. The duration calculation in the platform used: duration_s = info.data_chunk.byte_count / (info.fmt_chunk.sample_rate * info.fmt_chunk.channel_count * info.fmt_chunk.sample_width). For a typical 60-minute episode: data_chunk.byte_count = 635,040,000 bytes; sample_rate = 44,100; channel_count = 2; sample_width = 16. Computed duration: 635,040,000 ÷ (44,100 × 2 × 16) = 450 seconds = 7.5 minutes. The edit timeline in the platform displayed “Duration: 07:30” for every episode. Editors clicked to place marks while the audio player ran at the correct speed (the player used the browser’s native audio element, not the wavinfo duration). No error was raised when an editor clicked past 7:30 — the UI accepted the click and confirmed “Chapter mark saved.” The platform backend then validated: if marker_time > computed_duration: continue and silently skipped the INSERT. After 6 weeks and 150 episodes, the chapter marks table had approximately 1,350 entries (those placed in the first 7.5 minutes) instead of the expected ~4,050 (150 episodes × ~27 chapter marks each for a 60-minute interview with marks every ~2 minutes). The RSS feed contained chapters only for the opening segment of every episode. Listener feedback about the chapter navigation being “incomplete” triggered a support investigation.

The mechanism: wavinfo.WavInfoReader.fmt_chunk.sample_width returns the bits per sample as stored in the RIFF-WAVE wBitsPerSample field of the fmt chunk. This is the unambiguous PCM specification: 16-bit PCM has wBitsPerSample = 16, 24-bit PCM has wBitsPerSample = 24, 32-bit PCM or IEEE float has wBitsPerSample = 32. The number of bytes per sample is sample_width // 8: 16 ÷ 8 = 2 bytes, 24 ÷ 8 = 3 bytes, 32 ÷ 8 = 4 bytes. The RIFF-WAVE spec also defines nBlockAlign = nChannels × wBitsPerSample / 8, exposed by wavinfo as fmt_chunk.block_align (in bytes). The correct manual duration formula is: duration_s = data_chunk.byte_count / (fmt_chunk.sample_rate * fmt_chunk.channel_count * (fmt_chunk.sample_width // 8)). wavinfo also pre-computes this in data_chunk.frame_count as byte_count // block_align, so duration_s = data_chunk.frame_count / fmt_chunk.sample_rate avoids the bytes-vs-bits ambiguity entirely. The developer’s formula without the // 8 produced a denominator 8× too large (for 16-bit audio), so the computed duration was 8× too short. The UI confirmed “saved” because the INSERT attempt looked syntactically valid; the silent filter ran on the backend after the UI acknowledgment, in a separate validation step. The editor had no way to see that the mark had not been persisted: the edit timeline displayed the saved marks correctly for the marks that were within 7:30, and showed nothing (no error) for marks beyond 7:30 since those marks were never stored. This is a classic silent data-loss pattern: validate too late, acknowledge too early.

# Northfield Wavinfo Ltd. — wavinfo 0.2.1 duration fix
# wavinfo 0.2.1; Python 3.9
# 44100 Hz stereo 16-bit WAV; 60-minute interviews
# Podcast editorial platform; chapter mark validation
#
# Problem: fmt_chunk.sample_width = 16 (bits per sample, NOT bytes)
#          buggy formula divides by 16 instead of 2
#          computed duration = 450s (7.5 min) for 60-min episode
#          validation: if marker_time > computed_duration → DROP
#          marks beyond 7:30 silently discarded; no error raised
# Fix:     use data_chunk.frame_count / sample_rate
#          or add // 8 to sample_width in manual formula

from wavinfo import WavInfoReader


def wav_duration_buggy(path: str) -> float:
    """BUGGY: sample_width is bits, not bytes."""
    info = WavInfoReader(path)
    # BUG: sample_width = 16 (bits); treated as 16 bytes/sample
    # denominator = 44100 × 2 × 16 = 1,411,200  (should be 176,400)
    # for 60-min file: duration = 635,040,000 / 1,411,200 = 450 s (7.5 min)
    return info.data_chunk.byte_count / (
        info.fmt_chunk.sample_rate
        * info.fmt_chunk.channel_count
        * info.fmt_chunk.sample_width   # WRONG: bits, not bytes
    )


def wav_duration(path: str) -> float:
    """FIXED option 1: use pre-computed frame_count."""
    info = WavInfoReader(path)
    # data_chunk.frame_count = byte_count // block_align
    # block_align = channel_count × (sample_width // 8)
    # frame_count is always correct regardless of bit depth
    return info.data_chunk.frame_count / info.fmt_chunk.sample_rate


def wav_duration_manual(path: str) -> float:
    """FIXED option 2: manual formula with explicit bits-to-bytes conversion."""
    info = WavInfoReader(path)
    bytes_per_sample = info.fmt_chunk.sample_width // 8   # 16 bits → 2 bytes
    return info.data_chunk.byte_count / (
        info.fmt_chunk.sample_rate
        * info.fmt_chunk.channel_count
        * bytes_per_sample   # 2 bytes, not 16 bits
    )


def wav_duration_with_sanity(path: str, expected_duration_s: float | None = None,
                              tolerance: float = 0.01) -> float:
    """
    FIXED with sanity check: raise if duration deviates >1% from expected.
    Use when the recording duration is known from production metadata
    (e.g., recording software writes expected duration to file name or sidecar).
    """
    info = WavInfoReader(path)
    duration_s = info.data_chunk.frame_count / info.fmt_chunk.sample_rate

    if expected_duration_s is not None:
        relative_error = abs(duration_s - expected_duration_s) / expected_duration_s
        if relative_error > tolerance:
            raise ValueError(
                f"{path}: computed duration {duration_s:.1f}s deviates "
                f"{relative_error:.1%} from expected {expected_duration_s:.1f}s. "
                f"Check: sample_rate={info.fmt_chunk.sample_rate}, "
                f"channel_count={info.fmt_chunk.channel_count}, "
                f"sample_width={info.fmt_chunk.sample_width} bits (bytes: "
                f"{info.fmt_chunk.sample_width // 8}), "
                f"byte_count={info.data_chunk.byte_count}, "
                f"frame_count={info.data_chunk.frame_count}."
            )

    return duration_s


def save_chapter_mark(path: str, marker_time_s: float, title: str,
                      db_cursor) -> None:
    """
    Save a chapter mark after validating against the CORRECT file duration.
    Raises ValueError before the DB INSERT rather than silently dropping.
    """
    duration_s = wav_duration(path)

    # Validate before INSERT, not after: raise immediately so the UI knows
    if marker_time_s > duration_s:
        raise ValueError(
            f"Chapter mark '{title}' at {marker_time_s:.1f}s is beyond "
            f"file duration {duration_s:.1f}s ({path}). "
            f"This is likely a duration calculation error — check that "
            f"sample_width is treated as bits (÷8 for bytes)."
        )
    if marker_time_s < 0:
        raise ValueError(f"Chapter mark time cannot be negative: {marker_time_s:.1f}s.")

    db_cursor.execute(
        "INSERT INTO chapter_marks (file_path, time_s, title) VALUES (?, ?, ?)",
        (path, marker_time_s, title)
    )

Why sample_width in bits produces a silent data-loss failure rather than a numeric error or crash

The error is undetectable from the computed number alone. For a 60-minute 44.1 kHz stereo 16-bit WAV, the computed duration of 450 seconds (7.5 minutes) is a plausible positive float — it looks like a short podcast episode, not a corrupted value. The editorial platform’s UI was designed around a web audio element that played the actual file at the correct speed, so editors watching the timeline saw their cursor progress past 7:30 without any visible anomaly in the playback itself. The mismatch between the displayed “Duration: 07:30” and the actual 60-minute playback was visible, but the editorial team attributed it to a cosmetic display bug in the UI clock rather than a data-loss risk in the chapter mark pipeline. The silent DROP instead of an error was a backend design choice — the original developer had reasoned that marks placed “after the file ends” should be ignored gracefully rather than surface an error to the editor. That reasoning was sound for a correct duration calculation; it became a silent data sink when the duration was 8× too short. The fix requires two changes: correct the duration formula, and change the validation from a silent skip to a raised exception that propagates to the UI before the editor sees the “saved” confirmation. Backfilling the 150 episodes required the editors to re-enter all chapter marks beyond 7:30 from the original recording session notes; the marks within 7:30 were already in the database and were kept. The re-entry took two editorial team members approximately 14 hours total.

Northfield Wavinfo Ltd.’s retainer engagement was 2.0h: 0.3h triage (request duration calculation code; info.fmt_chunk.sample_width usage identified immediately; sample_width=16 bits vs 2 bytes = 8× factor confirms computed 450s vs actual 3600s); 0.3h root cause (trace through wavinfo source: fmt_chunk.sample_width = wBitsPerSample from RIFF fmt chunk; data_chunk.frame_count = byte_count // block_align pre-computes correctly; confirm: data_chunk.frame_count / sample_rate = 2,646,000 / 44100 = 60.0s per minute × 60 = 3600s for a 60-min file at 44.1kHz stereo; confirm 150-episode database: 1,350 saved marks vs expected ~4,050 — 2,700 lost); 0.5h fix (replace sample_width with data_chunk.frame_count / sample_rate; change silent DROP to raise ValueError with file path and computed vs actual duration; run on all 150 WAV files in staging: all durations now ≥ 3,500s; reprocess the chapter mark validation logic); 0.9h validation (re-import 2,700 chapter marks from editorial backup notes; spot-check 20 episodes against recording session logs; add duration sanity check to WAV ingest pipeline; deploy to production; 2.0h total). Hours logged to HourTab with per-session breakdown.

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 →