Files
lintunes/tests/test_round133.py
T

144 lines
5.6 KiB
Python

"""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