main
John Lauer adom-audio: audio player with spectrum analyzer + Premiere-style waveform; tools/audio-viz.py 4c588a4
#!/usr/bin/env python3
"""Precompute the waveform and spectrum data that <adom-audio> draws.

    audio-viz.py voice.wav                      # writes voice.viz.json next to it
    audio-viz.py voice.mp3 -o out.viz.json --fps 30 --bands 64

Reads any format ffmpeg reads (WAV 16/24/32-bit float, MP3, M4A, FLAC, OGG). Output, all compact:
  peaks:    "min/max per column" over the whole clip (int8 pairs, base64), for the Premiere-style waveform
  rms:      loudness per column (uint8, base64), drawn as the inner, brighter body of the waveform
  spectrum: one row of `bands` log-spaced levels (uint8, base64) per frame at `fps`, for the analyzer
  meta:     duration, sample rate, channels, integrated loudness estimate
Point the widget at it with viz="/OWNER/SLUG/render/voice.viz.json". On a private page use --manifest to write
a voice.audio.json manifest with the viz inlined, and embed it as src="/OWNER/SLUG/render/voice.audio.json".
"""
import argparse, base64, json, math, os, subprocess, sys

import numpy as np


def decode(path, sr):
    cmd = ['ffmpeg', '-v', 'error', '-i', path, '-ac', '1', '-ar', str(sr), '-f', 'f32le', '-']
    raw = subprocess.run(cmd, capture_output=True, check=True).stdout
    return np.frombuffer(raw, dtype=np.float32)


def probe(path):
    out = subprocess.run(['ffprobe', '-v', 'error', '-select_streams', 'a:0', '-show_entries',
                          'stream=sample_rate,channels,codec_name,bits_per_raw_sample,sample_fmt:format=duration',
                          '-of', 'json', path], capture_output=True, text=True).stdout
    j = json.loads(out or '{}')
    s = (j.get('streams') or [{}])[0]
    return {'duration': float(j.get('format', {}).get('duration', 0) or 0), 'sampleRate': int(s.get('sample_rate', 0) or 0),
            'channels': int(s.get('channels', 0) or 0), 'codec': s.get('codec_name', ''), 'sampleFormat': s.get('sample_fmt', '')}


def b64(a):
    return base64.b64encode(a.tobytes()).decode()


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument('audio')
    ap.add_argument('-o', '--out')
    ap.add_argument('--cols', type=int, default=2400, help='waveform columns (default 2400)')
    ap.add_argument('--fps', type=int, default=30, help='spectrum frames per second (default 30)')
    ap.add_argument('--bands', type=int, default=64, help='spectrum bands, log-spaced (default 64)')
    ap.add_argument('--fmin', type=float, default=50)
    ap.add_argument('--fmax', type=float, default=14000)
    ap.add_argument('--manifest', metavar='AUDIO_URL', help='write a widget manifest {audio, title, viz} instead (for src=, which the wiki inlines: works on private pages)')
    ap.add_argument('--title', help='title for the manifest')
    a = ap.parse_args()

    sr = 32000
    x = decode(a.audio, sr)
    if not len(x):
        sys.exit('no audio decoded')
    meta = probe(a.audio)
    meta['duration'] = meta['duration'] or len(x) / sr

    # waveform: min/max and RMS per column, scaled to the clip's own peak so quiet takes still read
    n = a.cols
    edges = np.linspace(0, len(x), n + 1).astype(int)
    mn = np.zeros(n, np.float32); mx = np.zeros(n, np.float32); rms = np.zeros(n, np.float32)
    for i in range(n):
        seg = x[edges[i]:max(edges[i + 1], edges[i] + 1)]
        mn[i] = seg.min(); mx[i] = seg.max(); rms[i] = math.sqrt(float(np.mean(seg * seg)))
    peak = max(float(np.max(np.abs(x))), 1e-6)
    pk = np.empty(2 * n, np.int8)
    pk[0::2] = np.clip(np.round(mn / peak * 127), -127, 127)
    pk[1::2] = np.clip(np.round(mx / peak * 127), -127, 127)
    rmsq = np.clip(np.round(rms / peak * 255), 0, 255).astype(np.uint8)

    # spectrum: Hann FFT at fps, log-spaced bands, dB mapped to 0..255 against the clip's own range
    hop = sr // a.fps
    win = 2048
    w = np.hanning(win).astype(np.float32)
    pad = np.concatenate([np.zeros(win // 2, np.float32), x, np.zeros(win, np.float32)])
    frames = int(math.ceil(len(x) / hop))
    freqs = np.fft.rfftfreq(win, 1 / sr)
    be = np.geomspace(a.fmin, a.fmax, a.bands + 1)
    idx = [np.where((freqs >= be[b]) & (freqs < be[b + 1]))[0] for b in range(a.bands)]
    idx = [ix if len(ix) else np.array([np.argmin(np.abs(freqs - be[b]))]) for b, ix in enumerate(idx)]
    spec = np.zeros((frames, a.bands), np.float32)
    for f in range(frames):
        s = pad[f * hop:f * hop + win]
        if len(s) < win:
            s = np.pad(s, (0, win - len(s)))
        mag = np.abs(np.fft.rfft(s * w))
        spec[f] = [mag[ix].max() for ix in idx]
    db = 20 * np.log10(spec + 1e-9)
    # tilt so speech highs show (voice energy falls ~4.5 dB/octave)
    db += 4.5 * np.log2(np.sqrt(be[:-1] * be[1:]) / 200.0)[None, :].clip(0)
    # scale against loud speech frames only (silence would drag the range down), 45 dB of range
    loud = db[db.max(axis=1) > np.percentile(db.max(axis=1), 40)]
    top = np.percentile(loud, 99.5); floor = top - 45
    sq = np.clip((db - floor) / (top - floor), 0, 1)
    sq = np.round(sq ** 1.15 * 255).astype(np.uint8)

    out = {
        'v': 1, 'meta': meta, 'peak': round(peak, 6),
        'waveform': {'cols': n, 'peaks': b64(pk), 'rms': b64(rmsq)},
        'spectrum': {'fps': a.fps, 'bands': a.bands, 'fmin': a.fmin, 'fmax': a.fmax, 'frames': frames, 'data': b64(sq)},
    }
    if a.manifest:
        out = {'audio': a.manifest, 'title': a.title or os.path.basename(a.audio), 'viz': out}
    dst = a.out or os.path.splitext(a.audio)[0] + ('.audio.json' if a.manifest else '.viz.json')
    with open(dst, 'w') as fh:
        json.dump(out, fh, separators=(',', ':'))
    print(f'OK: {dst}  {os.path.getsize(dst) // 1024} KB  ({meta["duration"]:.1f} s, {frames} spectrum frames x {a.bands} bands, {n} waveform columns)')


if __name__ == '__main__':
    main()