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
+1 -1
View File
@@ -1,3 +1,3 @@
"""LinTunes — iTunes-style music library manager and player for Linux."""
__version__ = "0.100.0"
__version__ = "0.101.0"
+14
View File
@@ -639,6 +639,20 @@ class PreferencesDialog(QDialog):
else:
form.addRow("Menu bar:", self._menu_bar_check)
# The timeline (seek bar): Fusion's sunk groove, or embossed with
# the song's waveform revealed under the handle (Round 133).
self._timeline_combo = QComboBox()
for label, value in (("Plain", "plain"), ("Waveform", "waveform")):
self._timeline_combo.addItem(label, value)
self._timeline_combo.setToolTip(
"Waveform: the played part of the timeline shows the song's "
"waveform in the highlight color")
self._timeline_combo.setCurrentIndex(
max(0, self._timeline_combo.findData(self._prefs.get("timeline", "plain"))))
self._timeline_combo.currentIndexChanged.connect(
lambda _i: self._prefs.set("timeline", self._timeline_combo.currentData()))
form.addRow("Timeline:", self._timeline_combo)
# Highlight color: a radio per slot, and beside it the slot's swatch,
# which opens a full color picker; the color picked replaces that
# slot's (right-click the swatch to put the original back).
+162 -2
View File
@@ -6,7 +6,7 @@ from PyQt6.QtWidgets import (
)
from PyQt6.QtCore import Qt, QTimer, QEvent, QPoint, QPointF, QRect, QSize, pyqtSignal
from PyQt6.QtGui import (QColor, QFont, QFontInfo, QFontMetrics, QIcon,
QPainter, QPen, QPixmap)
QPainter, QPalette, QPen, QPixmap)
from lintunes.tap_tempo import TapTempo
from lintunes.gui.icons import transport_icon
@@ -503,7 +503,134 @@ class ClickJumpSlider(QSlider):
class SeekSlider(ClickJumpSlider):
"""Timeline slider: clicking anywhere jumps the handle (and playhead)
straight to the clicked spot instead of paging; dragging scrubs."""
straight to the clicked spot instead of paging; dragging scrubs.
Two looks (pref ``timeline``, Round 133). ``plain`` is Fusion's sunk
groove. ``waveform`` paints the groove itself: embossed like a button,
the played part a light tint of the highlight, and over that tint the
song's waveform (``lintunes/waveform.py``) in the highlight itself,
centred on the groove — revealed as the handle passes. Time maps onto
where the handle's *centre* travels, so what's under it is now. The
picture is an image in device pixels, rebuilt from the bins on any
resize, so it is exact at every width; columns hold the stretch's
peak (lighter) and RMS (solid), the bar's ends partial pixels."""
TINT = 0.45 # the fill: this much highlight over the groove
PEAK_ALPHA = 0.45 # the peaks, under the solid RMS
INSET = 2 # px between the groove's edge and the waveform
def __init__(self, parent=None):
super().__init__(parent)
self._look = "plain"
self._bins = None
self._image = None
self._image_key = None
def look(self) -> str:
return self._look
def set_look(self, look: str):
look = "waveform" if look == "waveform" else "plain"
if look != self._look:
self._look = look
self.update()
def set_bins(self, bins):
"""The playing song's bins (None: none yet, or no song)."""
self._bins = bins
self._image = self._image_key = None
self.update()
def has_bins(self) -> bool:
return self._bins is not None
def _geometry(self):
"""(option, groove, x at the start, x at the end)."""
option = QStyleOptionSlider()
self.initStyleOption(option)
style = self.style()
CC, SC = QStyle.ComplexControl.CC_Slider, QStyle.SubControl
groove = style.subControlRect(CC, option, SC.SC_SliderGroove, self)
ends = []
for value in (self.minimum(), self.maximum()):
at = QStyleOptionSlider(option)
at.sliderPosition = at.sliderValue = value
ends.append(style.subControlRect(
CC, at, SC.SC_SliderHandle, self).center().x() + 0.5)
return option, groove, ends[0], ends[1]
def waveform_image(self, x0: float, x1: float, height: float):
"""The waveform at this span, in device pixels (cached)."""
from PyQt6.QtGui import QImage
import numpy as np
from lintunes import waveform
dpr = self.devicePixelRatioF()
width_px = max(0, round((x1 - x0) * dpr))
height_px = max(0, round(height * dpr))
color = self.palette().color(QPalette.ColorRole.Highlight)
key = (width_px, height_px, self.maximum(), color.rgba(), dpr)
if self._image is not None and key == self._image_key:
return self._image
self._image_key = key
if self._bins is None or not width_px or not height_px \
or self.maximum() <= 0:
self._image = None
return None
peak, rms = waveform.columns(self._bins, self.maximum(), width_px)
half = height_px / 2
peak_cov = waveform.coverage(peak * half, height_px)
rms_cov = waveform.coverage(rms * half, height_px)
alpha = rms_cov + peak_cov * self.PEAK_ALPHA * (1 - rms_cov)
alpha *= color.alphaF()
rgba = np.empty((height_px, width_px, 4), np.uint8) # BGRA, premul.
for i, channel in enumerate((color.blue(), color.green(), color.red())):
rgba[..., i] = np.round(alpha * channel)
rgba[..., 3] = np.round(alpha * 255)
image = QImage(rgba.tobytes(), width_px, height_px, width_px * 4,
QImage.Format.Format_ARGB32_Premultiplied).copy()
image.setDevicePixelRatio(dpr)
self._image = image
return image
def paintEvent(self, event):
if self._look != "waveform":
return super().paintEvent(event)
from PyQt6.QtCore import QRectF, QPointF
from PyQt6.QtGui import QPainterPath
option, groove, x0, x1 = self._geometry()
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
rect = QRectF(groove).adjusted(0.5, 0.5, -0.5, -0.5)
radius = min(theme.BUTTON_RADIUS, rect.height() / 2)
palette = self.palette()
base = palette.color(QPalette.ColorRole.Button)
path = theme.paint_emboss(painter, rect, base, radius, like=rect.height())
if self.maximum() > self.minimum():
span = self.maximum() - self.minimum()
done = x0 + (x1 - x0) * (self.sliderPosition() - self.minimum()) / span
highlight = palette.color(QPalette.ColorRole.Highlight)
tint = QColor.fromRgbF(
*(h * self.TINT + b * (1 - self.TINT) for h, b in zip(
highlight.getRgbF()[:3], base.getRgbF()[:3])))
painter.save()
played = QPainterPath()
played.addRect(QRectF(rect.left() - 1, rect.top() - 1,
done - rect.left() + 1, rect.height() + 2))
painter.setClipPath(path.intersected(played))
theme.paint_emboss(painter, rect, tint, radius, like=rect.height())
inner = rect.adjusted(self.INSET - 0.5, self.INSET - 0.5,
-(self.INSET - 0.5), -(self.INSET - 0.5))
image = self.waveform_image(x0, x1, inner.height())
if image is not None:
painter.setClipRect(QRectF(x0, inner.top(), done - x0,
inner.height()),
Qt.ClipOperation.IntersectClip)
painter.drawImage(QPointF(x0, inner.top()), image)
painter.restore()
option.subControls = QStyle.SubControl.SC_SliderHandle
self.style().drawComplexControl(QStyle.ComplexControl.CC_Slider,
option, painter, self)
painter.end()
class BpmButton(QPushButton):
@@ -903,6 +1030,8 @@ class TransportBar(QWidget):
player.playing_changed.connect(self._on_playing_changed)
player.position_changed.connect(self._on_position_changed)
player.duration_changed.connect(self._on_duration_changed)
self._waveforms = None # made the first time it's wanted
self._apply_timeline_look()
if cast is not None:
# While casting, the visualizer panel *is* the cast indicator —
# there is no spectrum to show, so a click there stops casting.
@@ -1297,6 +1426,7 @@ class TransportBar(QWidget):
box.setStyleSheet(_box_style(box_bg))
self._apply_now_playing_bg()
self._apply_now_playing_font()
self._apply_timeline_look()
self._apply_dj_button_style()
self._on_dj_button_icon(self.dj_button.isChecked())
for button in (self._theme_btn, self._speakers_btn, self._identify_btn):
@@ -1340,6 +1470,7 @@ class TransportBar(QWidget):
def _on_track_changed(self, track):
self._current_track = track
self._request_waveform()
self._now_playing.set_clickable(track is not None and not self._dj_on)
if self._dj_on:
return # the panel names the decks' songs meanwhile
@@ -1368,6 +1499,35 @@ class TransportBar(QWidget):
if duration > 0:
self._remaining_label.setText("-" + (format_time(duration - position) or "0:00"))
# ---- the timeline's look (Round 133) ----
def _apply_timeline_look(self):
look = self._prefs.get("timeline", "plain")
was = self._slider.look()
self._slider.set_look(look)
if self._slider.look() != was:
self._request_waveform()
def _request_waveform(self):
"""Ask for the playing song's waveform — only while it's shown."""
track = getattr(self, "_current_track", None)
path = getattr(track, "location", None) if track is not None else None
self._waveform_path = path
self._slider.set_bins(None)
if not path or self._slider.look() != "waveform":
return
from lintunes import waveform
if self._waveforms is None:
if not waveform.ffmpeg_available():
return # plain-looking groove; nothing to draw
self._waveforms = waveform.WaveformLoader(parent=self)
self._waveforms.ready.connect(self._on_waveform_ready)
self._waveforms.request(str(path))
def _on_waveform_ready(self, path, bins):
if path == str(self._waveform_path or ""):
self._slider.set_bins(bins)
# ---- scrubbing ----
def _on_scrub_start(self):
+1
View File
@@ -51,6 +51,7 @@ DEFAULTS = {
# tint per mode — a hue laid over the grays at tint_level percent.
"dark_mode": False,
"menu_bar": "always", # always | alt (hidden until Alt; gui/menu_bar.py)
"timeline": "plain", # plain | waveform (the seek bar; waveform.py)
"tint_color": "#3584E4",
"tint_level": 0,
"dark_tint_color": "#3584E4",
+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)