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:
@@ -245,6 +245,16 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal
|
|||||||
panel draws the cover to the outline's centre and the 1 px line over it
|
panel draws the cover to the outline's centre and the 1 px line over it
|
||||||
in the lists' grey (`frame_color`); inset by half a pixel, the clip
|
in the lists' grey (`frame_color`); inset by half a pixel, the clip
|
||||||
left a pale blend that read as a 2 px border on vivid covers.
|
left a pale blend that read as a 2 px border on vivid covers.
|
||||||
|
**The timeline has two looks** (Round 133, pref `timeline`, Preferences ›
|
||||||
|
Appearance): `plain` is Fusion's; `waveform` makes `SeekSlider` paint
|
||||||
|
itself — an embossed groove, the played part a `TINT` of the highlight,
|
||||||
|
and over it the song's waveform in the highlight, centred, only left of
|
||||||
|
the handle. `waveform.py` decodes the whole file once (ffmpeg, mono
|
||||||
|
22,050 Hz, streamed) into ~5.8 ms bins of peak + RMS, cached in
|
||||||
|
`$XDG_CACHE_HOME/lintunes/waveforms/`; each paint width is an exact
|
||||||
|
reduction of them (`columns`) into a device-pixel image whose bar ends
|
||||||
|
are partial pixels (`coverage`), rebuilt on resize. Time maps onto the
|
||||||
|
handle *centre's* travel. Nothing is decoded while the look is plain.
|
||||||
The now-playing panel (`transport.NowPlayingPanel`, Round 110) is a
|
The now-playing panel (`transport.NowPlayingPanel`, Round 110) is a
|
||||||
Go to Current Song button while a song is on (not in DJ mode): raised
|
Go to Current Song button while a song is on (not in DJ mode): raised
|
||||||
in the hover face under the cursor, sunk and darker while held. Its
|
in the hover face under the cursor, sunk and darker while held. Its
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
"""LinTunes — iTunes-style music library manager and player for Linux."""
|
"""LinTunes — iTunes-style music library manager and player for Linux."""
|
||||||
|
|
||||||
__version__ = "0.100.0"
|
__version__ = "0.101.0"
|
||||||
|
|||||||
@@ -639,6 +639,20 @@ class PreferencesDialog(QDialog):
|
|||||||
else:
|
else:
|
||||||
form.addRow("Menu bar:", self._menu_bar_check)
|
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,
|
# Highlight color: a radio per slot, and beside it the slot's swatch,
|
||||||
# which opens a full color picker; the color picked replaces that
|
# which opens a full color picker; the color picked replaces that
|
||||||
# slot's (right-click the swatch to put the original back).
|
# slot's (right-click the swatch to put the original back).
|
||||||
|
|||||||
+162
-2
@@ -6,7 +6,7 @@ from PyQt6.QtWidgets import (
|
|||||||
)
|
)
|
||||||
from PyQt6.QtCore import Qt, QTimer, QEvent, QPoint, QPointF, QRect, QSize, pyqtSignal
|
from PyQt6.QtCore import Qt, QTimer, QEvent, QPoint, QPointF, QRect, QSize, pyqtSignal
|
||||||
from PyQt6.QtGui import (QColor, QFont, QFontInfo, QFontMetrics, QIcon,
|
from PyQt6.QtGui import (QColor, QFont, QFontInfo, QFontMetrics, QIcon,
|
||||||
QPainter, QPen, QPixmap)
|
QPainter, QPalette, QPen, QPixmap)
|
||||||
|
|
||||||
from lintunes.tap_tempo import TapTempo
|
from lintunes.tap_tempo import TapTempo
|
||||||
from lintunes.gui.icons import transport_icon
|
from lintunes.gui.icons import transport_icon
|
||||||
@@ -503,7 +503,134 @@ class ClickJumpSlider(QSlider):
|
|||||||
|
|
||||||
class SeekSlider(ClickJumpSlider):
|
class SeekSlider(ClickJumpSlider):
|
||||||
"""Timeline slider: clicking anywhere jumps the handle (and playhead)
|
"""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):
|
class BpmButton(QPushButton):
|
||||||
@@ -903,6 +1030,8 @@ class TransportBar(QWidget):
|
|||||||
player.playing_changed.connect(self._on_playing_changed)
|
player.playing_changed.connect(self._on_playing_changed)
|
||||||
player.position_changed.connect(self._on_position_changed)
|
player.position_changed.connect(self._on_position_changed)
|
||||||
player.duration_changed.connect(self._on_duration_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:
|
if cast is not None:
|
||||||
# While casting, the visualizer panel *is* the cast indicator —
|
# While casting, the visualizer panel *is* the cast indicator —
|
||||||
# there is no spectrum to show, so a click there stops casting.
|
# 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))
|
box.setStyleSheet(_box_style(box_bg))
|
||||||
self._apply_now_playing_bg()
|
self._apply_now_playing_bg()
|
||||||
self._apply_now_playing_font()
|
self._apply_now_playing_font()
|
||||||
|
self._apply_timeline_look()
|
||||||
self._apply_dj_button_style()
|
self._apply_dj_button_style()
|
||||||
self._on_dj_button_icon(self.dj_button.isChecked())
|
self._on_dj_button_icon(self.dj_button.isChecked())
|
||||||
for button in (self._theme_btn, self._speakers_btn, self._identify_btn):
|
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):
|
def _on_track_changed(self, track):
|
||||||
self._current_track = track
|
self._current_track = track
|
||||||
|
self._request_waveform()
|
||||||
self._now_playing.set_clickable(track is not None and not self._dj_on)
|
self._now_playing.set_clickable(track is not None and not self._dj_on)
|
||||||
if self._dj_on:
|
if self._dj_on:
|
||||||
return # the panel names the decks' songs meanwhile
|
return # the panel names the decks' songs meanwhile
|
||||||
@@ -1368,6 +1499,35 @@ class TransportBar(QWidget):
|
|||||||
if duration > 0:
|
if duration > 0:
|
||||||
self._remaining_label.setText("-" + (format_time(duration - position) or "0:00"))
|
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 ----
|
# ---- scrubbing ----
|
||||||
|
|
||||||
def _on_scrub_start(self):
|
def _on_scrub_start(self):
|
||||||
|
|||||||
@@ -51,6 +51,7 @@ DEFAULTS = {
|
|||||||
# tint per mode — a hue laid over the grays at tint_level percent.
|
# tint per mode — a hue laid over the grays at tint_level percent.
|
||||||
"dark_mode": False,
|
"dark_mode": False,
|
||||||
"menu_bar": "always", # always | alt (hidden until Alt; gui/menu_bar.py)
|
"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_color": "#3584E4",
|
||||||
"tint_level": 0,
|
"tint_level": 0,
|
||||||
"dark_tint_color": "#3584E4",
|
"dark_tint_color": "#3584E4",
|
||||||
|
|||||||
@@ -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)
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
"""Round 133: the timeline's Waveform look."""
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from lintunes import waveform
|
||||||
|
|
||||||
|
|
||||||
|
def test_bins_hold_each_stretchs_peak_and_rms():
|
||||||
|
pcm = np.zeros(waveform.BIN * 3 + 10, np.int16)
|
||||||
|
pcm[5] = 16384 # bin 0: one half-scale spike
|
||||||
|
pcm[waveform.BIN:2 * waveform.BIN] = 32767 # bin 1: full scale, steady
|
||||||
|
bins = waveform.bins_from_pcm(pcm)
|
||||||
|
assert bins.shape == (2, 4) # a short last bin counts
|
||||||
|
assert bins[0, 0] == 128 and bins[1, 0] == round(0.5 / np.sqrt(128) * 255)
|
||||||
|
assert bins[0, 1] == 255 and bins[1, 1] == 255
|
||||||
|
assert bins[0, 2] == 0 and bins[0, 3] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_columns_are_exact_reductions_at_any_width():
|
||||||
|
rng = np.random.default_rng(1)
|
||||||
|
bins = np.vstack([rng.integers(0, 256, 1000)] * 2).astype(np.uint8)
|
||||||
|
bins[1] //= 2
|
||||||
|
duration = 1000 * waveform.BIN_MS
|
||||||
|
for width in (1, 7, 333, 1000, 2500):
|
||||||
|
peak, rms = waveform.columns(bins, duration, width)
|
||||||
|
assert peak.shape == (width,)
|
||||||
|
loudest = bins[0].max()
|
||||||
|
for i in (0, width // 2, width - 1):
|
||||||
|
s = int(np.floor(i * 1000 / width))
|
||||||
|
e = max(s + 1, int(np.floor((i + 1) * 1000 / width)))
|
||||||
|
assert peak[i] == pytest.approx(bins[0, s:e].max() / loudest)
|
||||||
|
want = np.sqrt(np.mean(bins[1, s:e].astype(float) ** 2)) / loudest
|
||||||
|
assert rms[i] == pytest.approx(want, rel=1e-5)
|
||||||
|
|
||||||
|
|
||||||
|
def test_time_past_the_decoded_audio_is_silence():
|
||||||
|
bins = np.full((2, 100), 200, np.uint8)
|
||||||
|
peak, _ = waveform.columns(bins, 200 * waveform.BIN_MS, 10)
|
||||||
|
assert (peak[:5] == 1).all() and (peak[5:] == 0).all()
|
||||||
|
|
||||||
|
|
||||||
|
def test_coverage_leaves_the_bar_ends_as_partial_pixels():
|
||||||
|
cov = waveform.coverage(np.array([0.0, 1.25, 5.0]), 10)
|
||||||
|
assert cov[:, 0].sum() == 0
|
||||||
|
assert cov[:, 1].sum() == pytest.approx(2.5)
|
||||||
|
assert cov[3, 1] == pytest.approx(0.25) and cov[4, 1] == 1
|
||||||
|
assert cov[:, 2].sum() == 10
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.skipif(not shutil.which("ffmpeg"), reason="needs ffmpeg")
|
||||||
|
def test_decode_and_cache(tmp_path, qapp):
|
||||||
|
song = tmp_path / "tone.wav"
|
||||||
|
subprocess.run(["ffmpeg", "-v", "error", "-f", "lavfi", "-i",
|
||||||
|
"sine=f=220:d=2", str(song)], check=True)
|
||||||
|
bins = waveform.decode_bins(str(song))
|
||||||
|
assert abs(bins.shape[1] * waveform.BIN_MS - 2000) < 2 * waveform.BIN_MS
|
||||||
|
assert 28 < bins[0, 10] < 36 # lavfi sine: 1/8 of full scale
|
||||||
|
loader = waveform.WaveformLoader(cache_dir=tmp_path / "cache",
|
||||||
|
decode=lambda p: bins)
|
||||||
|
got = []
|
||||||
|
loader.ready.connect(lambda p, b: got.append((p, b)))
|
||||||
|
loader.request(str(song))
|
||||||
|
for _ in range(200):
|
||||||
|
qapp.processEvents()
|
||||||
|
if got:
|
||||||
|
break
|
||||||
|
import time; time.sleep(0.01)
|
||||||
|
assert got and got[0][1] is bins
|
||||||
|
fresh = waveform.WaveformLoader(cache_dir=tmp_path / "cache",
|
||||||
|
decode=lambda p: pytest.fail("decoded twice"))
|
||||||
|
assert (fresh.cached(str(song)) == bins).all()
|
||||||
|
|
||||||
|
|
||||||
|
def test_undecodable_file_is_none(tmp_path):
|
||||||
|
junk = tmp_path / "junk.mp3"
|
||||||
|
junk.write_bytes(b"not audio")
|
||||||
|
if shutil.which("ffmpeg"):
|
||||||
|
assert waveform.decode_bins(str(junk)) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_waveform_look_paints_the_played_part_only(qapp):
|
||||||
|
from PyQt6.QtGui import QColor
|
||||||
|
from lintunes.gui.transport import SeekSlider
|
||||||
|
slider = SeekSlider()
|
||||||
|
slider.setProperty("tall", True)
|
||||||
|
slider.resize(400, slider.sizeHint().height())
|
||||||
|
slider.setRange(0, 10000)
|
||||||
|
slider.setValue(5000)
|
||||||
|
slider.set_look("waveform")
|
||||||
|
slider.set_bins(np.full((2, int(10000 / waveform.BIN_MS) + 1), 255, np.uint8))
|
||||||
|
image = slider.grab().toImage()
|
||||||
|
highlight = slider.palette().color(slider.palette().ColorRole.Highlight)
|
||||||
|
mid = image.height() // 2
|
||||||
|
left, right = QColor(image.pixel(100, mid)), QColor(image.pixel(320, mid))
|
||||||
|
assert left == highlight # a full-scale song fills the middle
|
||||||
|
assert right != highlight
|
||||||
|
# A resize rebuilds the picture at the new width, in device pixels.
|
||||||
|
first = slider._image_key
|
||||||
|
slider.resize(500, slider.height())
|
||||||
|
slider.grab()
|
||||||
|
assert slider._image_key != first
|
||||||
|
assert slider._image.width() == round(slider._image_key[0])
|
||||||
|
slider.set_look("plain")
|
||||||
|
slider.grab() # Fusion's own paint again
|
||||||
|
|
||||||
|
|
||||||
|
def test_pref_switches_the_look_and_asks_only_while_shown(qapp, tmp_path):
|
||||||
|
from pathlib import Path
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from lintunes.preferences import Preferences
|
||||||
|
from lintunes.gui import transport
|
||||||
|
prefs = Preferences(Path(tmp_path))
|
||||||
|
assert prefs.get("timeline") == "plain"
|
||||||
|
asked = []
|
||||||
|
|
||||||
|
class Loader:
|
||||||
|
def __init__(self, **_):
|
||||||
|
self.ready = SimpleNamespace(connect=lambda f: None)
|
||||||
|
|
||||||
|
def request(self, path):
|
||||||
|
asked.append(path)
|
||||||
|
|
||||||
|
bar = SimpleNamespace(_prefs=prefs, _slider=transport.SeekSlider(),
|
||||||
|
_waveforms=None,
|
||||||
|
_current_track=SimpleNamespace(location="/x/song.mp3"))
|
||||||
|
bar._request_waveform = lambda: transport.TransportBar._request_waveform(bar)
|
||||||
|
bar._on_waveform_ready = lambda *a: None
|
||||||
|
import lintunes.waveform as wf
|
||||||
|
original = wf.WaveformLoader
|
||||||
|
wf.WaveformLoader = Loader
|
||||||
|
try:
|
||||||
|
transport.TransportBar._apply_timeline_look(bar)
|
||||||
|
assert asked == [] and bar._slider.look() == "plain"
|
||||||
|
prefs.set("timeline", "waveform")
|
||||||
|
transport.TransportBar._apply_timeline_look(bar)
|
||||||
|
assert bar._slider.look() == "waveform"
|
||||||
|
if wf.ffmpeg_available():
|
||||||
|
assert asked == ["/x/song.mp3"]
|
||||||
|
finally:
|
||||||
|
wf.WaveformLoader = original
|
||||||
Reference in New Issue
Block a user