v0.101.0: the timeline can show the song's waveform (Preferences › Appearance › Timeline: Waveform) — an embossed bar whose played part reveals the waveform in the highlight color, drawn exactly at whatever width the window is

This commit is contained in:
2026-11-23 12:01:28 -08:00
parent 5f6f01d91c
commit 224ecfd291
7 changed files with 574 additions and 3 deletions
+243
View File
@@ -0,0 +1,243 @@
"""The song's waveform under the timeline (Round 133, Preferences ›
Appearance › Timeline: Waveform).
The whole file is decoded once, when its song starts, by the ``ffmpeg`` CLI
(mono, 22,050 Hz, streamed — an hour-long mix never sits in memory) into
**bins** of ``BIN`` samples (~5.8 ms): each bin's peak and RMS, as bytes of
full scale. That is far finer than any timeline is wide, so drawing it at a
width is a reduction, never an interpolation: a device-pixel column takes
the max peak and the true RMS (√ of the mean square) of the bins its stretch
of the song covers (`columns`). A resize just reduces again.
Bins are cached by path + size + mtime in
``$XDG_CACHE_HOME/lintunes/waveforms/`` (machine-local, rebuilt on demand),
the newest ``CACHE_FILES`` kept. Shaped like ``loudness.py``: pure helpers,
then the subprocess, then a QObject that works on a daemon thread.
"""
from __future__ import annotations
import hashlib
import logging
import os
import queue
import shutil
import subprocess
import threading
from pathlib import Path
import numpy as np
from PyQt6.QtCore import QObject, pyqtSignal
from lintunes import paths
log = logging.getLogger(__name__)
RATE = 22050
BIN = 128 # samples per bin: ~5.8 ms
BIN_MS = BIN * 1000 / RATE
CACHE_FILES = 300 # ~100 KB per 5-minute song
_VERSION = "v1"
# ---- pure ----
def bins_from_pcm(samples: np.ndarray) -> np.ndarray:
"""(2, n) uint8: each ``BIN``-sample bin's peak and RMS, 255 = full
scale. ``samples`` is int16 mono; a short last bin counts as a bin."""
if samples.size == 0:
return np.zeros((2, 0), np.uint8)
x = samples.astype(np.float32) / 32768.0
n = -(-x.size // BIN)
padded = np.zeros(n * BIN, np.float32)
padded[:x.size] = x
frames = padded.reshape(n, BIN)
peak = np.abs(frames).max(axis=1)
counts = np.full(n, BIN, np.float32)
counts[-1] = x.size - (n - 1) * BIN
rms = np.sqrt((frames * frames).sum(axis=1) / counts)
out = np.empty((2, n), np.uint8)
out[0] = np.clip(np.round(peak * 255), 0, 255)
out[1] = np.clip(np.round(rms * 255), 0, 255)
return out
def columns(bins: np.ndarray, duration_ms: float, width: int):
"""(peak, rms) per column, each 0..1 of the song's loudest peak, for
``width`` columns spanning ``duration_ms``. Column i covers the bins
whose start falls in [i, i+1) × duration / width — at least one, so a
timeline wider than the song has bins still draws every column. Time
past the decoded audio is silence."""
peak = np.zeros(max(width, 0), np.float32)
rms = np.zeros_like(peak)
n = bins.shape[1] if bins.ndim == 2 else 0
if width <= 0 or n == 0 or duration_ms <= 0:
return peak, rms
bins_per_col = duration_ms / BIN_MS / width
# (the 1e-9 keeps a boundary that is a whole bin from flooring short)
edges = np.floor(np.arange(width + 1) * bins_per_col + 1e-9).astype(np.int64)
starts = edges[:-1]
ends = np.maximum(starts + 1, edges[1:])
live = starts < n
if not live.any():
return peak, rms
s, e = starts[live], np.minimum(ends[live], n)
p = bins[0].astype(np.float32)
# max over [s_i, e_i): reduceat on the interleaved bounds, every even
# slot one column (a sentinel makes e_i == n a valid index)
bounds = np.column_stack([s, e]).ravel()
peak[live] = np.maximum.reduceat(np.append(p, 0), bounds)[::2]
sq = np.concatenate([[0.0], np.cumsum(bins[1].astype(np.float64) ** 2)])
rms[live] = np.sqrt((sq[e] - sq[s]) / (e - s))
loudest = p.max()
if loudest > 0:
peak /= loudest
rms /= loudest
return peak, np.minimum(rms, peak)
def coverage(halves: np.ndarray, height: int) -> np.ndarray:
"""(height, width) 0..1: how much of each pixel a bar centred on the
middle row line reaches into, ``halves`` (pixels) above and below it —
the bar's ends are partial pixels, never rounded to whole ones."""
rows = np.arange(height, dtype=np.float32)[:, None]
c = height / 2.0
top = c - halves[None, :]
bottom = c + halves[None, :]
return np.clip(np.minimum(rows + 1, bottom) - np.maximum(rows, top), 0, 1)
# ---- ffmpeg ----
def ffmpeg_available() -> bool:
return shutil.which("ffmpeg") is not None
def decode_bins(path: str) -> np.ndarray | None:
"""The whole file's bins, or None when it can't be decoded."""
try:
proc = subprocess.Popen(
["ffmpeg", "-nostdin", "-v", "error", "-i", path, "-map", "0:a:0",
"-ac", "1", "-ar", str(RATE), "-f", "s16le", "-"],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
except OSError as exc:
log.info("waveform: couldn't run ffmpeg on %s: %s", path, exc)
return None
chunk = BIN * 4096 * 2 # bytes: whole bins, ~24 s
parts, rest = [], b""
try:
while True:
data = proc.stdout.read(chunk)
if not data:
break
data = rest + data
whole = len(data) - len(data) % (BIN * 2)
if whole:
parts.append(bins_from_pcm(np.frombuffer(data[:whole], "<i2")))
rest = data[whole:]
if len(rest) >= 2:
parts.append(bins_from_pcm(
np.frombuffer(rest[:len(rest) - len(rest) % 2], "<i2")))
finally:
proc.stdout.close()
code = proc.wait()
if code != 0 or not parts:
return None
return np.concatenate(parts, axis=1)
# ---- cache + worker ----
def default_cache_dir() -> Path:
return paths.cache_dir() / "waveforms"
def cache_key(path: str) -> str | None:
try:
st = os.stat(path)
except OSError:
return None
raw = f"{_VERSION}|{path}|{st.st_size}|{st.st_mtime_ns}"
return hashlib.sha1(raw.encode("utf-8", "surrogateescape")).hexdigest()
class WaveformLoader(QObject):
"""Bins by file path, decoded on a daemon thread, newest request first.
``ready(path, bins)`` arrives on the GUI thread; bins is None when the
file couldn't be decoded."""
ready = pyqtSignal(str, object)
def __init__(self, cache_dir: Path | None = None, decode=decode_bins,
parent=None):
super().__init__(parent)
self._dir = cache_dir or default_cache_dir()
self._decode = decode
self._memory: dict[str, np.ndarray] = {}
self._queue: queue.Queue = queue.Queue()
self._thread = None
def cached(self, path: str):
key = cache_key(path)
if key is None:
return None
if key in self._memory:
return self._memory[key]
file = self._dir / f"{key}.npy"
try:
bins = np.load(file)
os.utime(file) # newest-used survives the prune
except (OSError, ValueError):
return None
if bins.ndim != 2 or bins.shape[0] != 2:
return None
self._remember(key, bins)
return bins
def request(self, path: str):
"""Emits ``ready`` at once if cached, else when decoded."""
bins = self.cached(path)
if bins is not None:
self.ready.emit(path, bins)
return
# Only the newest song matters: drop anything still waiting.
try:
while True:
self._queue.get_nowait()
except queue.Empty:
pass
self._queue.put(path)
if self._thread is None:
self._thread = threading.Thread(target=self._run, daemon=True,
name="waveform")
self._thread.start()
def _remember(self, key, bins):
self._memory[key] = bins
while len(self._memory) > 8:
self._memory.pop(next(iter(self._memory)))
def _run(self):
while True:
path = self._queue.get()
key = cache_key(path)
bins = self._decode(path)
if bins is not None and key is not None:
self._remember(key, bins)
self._store(key, bins)
try:
self.ready.emit(path, bins)
except RuntimeError: # the QObject went away
return
def _store(self, key, bins):
try:
self._dir.mkdir(parents=True, exist_ok=True)
tmp = self._dir / f"{key}.tmp.npy"
np.save(tmp, bins)
os.replace(tmp, self._dir / f"{key}.npy")
files = sorted(self._dir.glob("*.npy"),
key=lambda f: f.stat().st_mtime, reverse=True)
for old in files[CACHE_FILES:]:
old.unlink(missing_ok=True)
except OSError as exc:
log.info("waveform: couldn't cache %s: %s", key, exc)