341 lines
13 KiB
Python
341 lines
13 KiB
Python
"""Round 131: Boost Volume (lintunes/boost.py) replaces the per-track Volume
|
|
Adjustment, which could never play past full volume.
|
|
|
|
It raises an MP3's own global_gain (mp3gain's method): nothing is re-encoded,
|
|
the decoded audio is the original times exactly 2^(steps/4), and it never
|
|
clips. Only MP3s get the button, in Get Info.
|
|
"""
|
|
import shutil
|
|
import subprocess
|
|
import time
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
from lintunes import boost, tagging
|
|
from lintunes.library_manager import LibraryManager
|
|
from lintunes.models import Library, Playlist, Track
|
|
from lintunes.preferences import Preferences
|
|
from tests.test_round29 import _player, _local_track, _FakeSink
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _staging_in_tmp(tmp_path, monkeypatch):
|
|
monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path / "cache"))
|
|
monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "config"))
|
|
|
|
|
|
@pytest.fixture
|
|
def fake_trash(tmp_path, monkeypatch):
|
|
bin_ = tmp_path / "trash-bin"
|
|
bin_.mkdir()
|
|
count = iter(range(10**6)) # a name per send, never reused
|
|
|
|
def send(path):
|
|
path = Path(path)
|
|
if not path.exists():
|
|
from lintunes.trash import TrashError
|
|
raise TrashError(f"{path} doesn't exist")
|
|
dest = bin_ / f"{next(count)}-{path.name}"
|
|
shutil.move(str(path), dest)
|
|
return dest
|
|
|
|
def restore(trashed, original):
|
|
Path(original).parent.mkdir(parents=True, exist_ok=True)
|
|
shutil.move(str(trashed), str(original))
|
|
monkeypatch.setattr("lintunes.library_manager.trash.send_to_trash", send)
|
|
monkeypatch.setattr("lintunes.library_manager.trash.restore_from_trash",
|
|
restore)
|
|
return bin_
|
|
|
|
|
|
def _quiet_mp3(path: Path, db: float = -20.0, seconds: int = 3) -> Path:
|
|
if shutil.which("ffmpeg") is None:
|
|
pytest.skip("ffmpeg not available")
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
subprocess.run(["ffmpeg", "-y", "-f", "lavfi", "-i",
|
|
f"sine=f=440:d={seconds},volume={db}dB", "-ac", "2",
|
|
"-c:a", "libmp3lame", "-b:a", "128k", str(path)],
|
|
capture_output=True, check=True)
|
|
tagging.write_tags(path, {"name": "Salivate-ish", "artist": "Quiet Band",
|
|
"album": "Hush", "track_number": 4})
|
|
tagging.write_artwork(path, _jpeg(), "image/jpeg")
|
|
return path
|
|
|
|
|
|
def _jpeg() -> bytes:
|
|
from PyQt6.QtCore import QBuffer, QIODevice
|
|
from PyQt6.QtGui import QColor, QImage
|
|
image = QImage(8, 8, QImage.Format.Format_RGB32)
|
|
image.fill(QColor("red"))
|
|
buffer = QBuffer()
|
|
buffer.open(QIODevice.OpenModeFlag.WriteOnly)
|
|
image.save(buffer, "JPG")
|
|
return bytes(buffer.data())
|
|
|
|
|
|
SUMMARY = """[Parsed_ebur128_0 @ 0x1] Summary:
|
|
|
|
Integrated loudness:
|
|
I: -28.7 LUFS
|
|
Threshold: -39.0 LUFS
|
|
|
|
Loudness range:
|
|
LRA: 5.0 LU
|
|
|
|
True peak:
|
|
Peak: -18.9 dBFS
|
|
"""
|
|
|
|
|
|
# ---- measuring and the plan ----
|
|
|
|
class TestMeasureAndPlan:
|
|
def test_parses_loudness_and_true_peak(self):
|
|
assert boost.parse_measurement(SUMMARY) == (-28.7, -18.9)
|
|
|
|
def test_nothing_to_parse(self):
|
|
assert boost.parse_measurement("garbage") == (None, None)
|
|
|
|
def test_whole_steps_toward_typical(self):
|
|
p = boost.plan(-28.7, -18.9, -14.0) # wants 14.7, room 17.9
|
|
assert p.steps == 9 and p.gain_db == 13.5 and p.reaches_typical
|
|
|
|
def test_never_past_the_ceiling(self):
|
|
p = boost.plan(-28.7, -18.9, -10.0) # wants 18.7, room 17.9
|
|
assert p.steps == 11 and p.gain_db <= 17.9 and not p.reaches_typical
|
|
|
|
def test_nothing_to_do(self):
|
|
assert boost.plan(-9.0, -0.2, -10.0).steps == 0
|
|
assert boost.plan(-20.0, -0.5, -10.0).steps == 0 # no room
|
|
assert not boost.plan(None, None, -10.0).measurable
|
|
|
|
|
|
# ---- the MP3 gain ----
|
|
|
|
def _decode(path):
|
|
import numpy as np
|
|
out = subprocess.run(["ffmpeg", "-v", "error", "-i", str(path), "-f",
|
|
"f32le", "-ac", "1", "-"], capture_output=True).stdout
|
|
return np.frombuffer(out, np.float32)
|
|
|
|
|
|
@pytest.mark.parametrize("args", [
|
|
["-ac", "2", "-b:a", "192k"], # MPEG-1 stereo
|
|
["-ac", "1", "-b:a", "96k"], # MPEG-1 mono
|
|
["-ac", "2", "-ar", "22050", "-b:a", "64k"], # MPEG-2
|
|
["-ac", "1", "-ar", "11025", "-b:a", "32k"], # MPEG-2.5
|
|
])
|
|
def test_gain_is_exact_and_nothing_else_changes(tmp_path, args):
|
|
import numpy as np
|
|
if shutil.which("ffmpeg") is None:
|
|
pytest.skip("ffmpeg not available")
|
|
src = tmp_path / "in.mp3"
|
|
subprocess.run(["ffmpeg", "-y", "-f", "lavfi", "-i", "anoisesrc=d=2:a=0.05",
|
|
*args, "-c:a", "libmp3lame", str(src)],
|
|
capture_output=True, check=True)
|
|
assert boost.supported(str(src))
|
|
before = src.read_bytes()
|
|
dest = tmp_path / "out.mp3"
|
|
boost.boost_file(src, dest, 4) # +6 dB = exactly x2
|
|
assert src.read_bytes() == before # only read
|
|
after = dest.read_bytes()
|
|
assert len(after) == len(before)
|
|
a, b = _decode(src), _decode(dest)
|
|
assert len(a) == len(b)
|
|
assert np.max(np.abs(b - 2 * a)) < 1e-5
|
|
# Undoing the steps gives the original bytes back.
|
|
assert boost.apply_gain(after, -4) == before
|
|
|
|
|
|
def test_silent_granules_are_left_alone():
|
|
"""LAME parks silence at 210/255; those must not count against the
|
|
ceiling, or a quiet song with a silent intro could never be boosted."""
|
|
data = bytearray(_frame_stream(gain=150, frames=20))
|
|
# Make frame 3's first granule silent at gain 255.
|
|
frame = next(f for i, f in enumerate(boost._frames(data)) if i == 3)
|
|
bit = next(boost._gain_bits(frame))
|
|
boost._set8(data, frame.side_offset, bit, 255)
|
|
_set_bits(data, frame.side_offset, bit - 21, 12, 0)
|
|
assert boost.headroom_steps(bytes(data)) == 255 - 150
|
|
boosted = boost.apply_gain(bytes(data), 10)
|
|
assert boost._get8(boosted, frame.side_offset, bit) == 255
|
|
|
|
|
|
def test_what_isnt_supported(tmp_path):
|
|
flac = tmp_path / "a.flac"
|
|
flac.write_bytes(b"fLaC" + bytes(100))
|
|
assert not boost.supported(str(flac))
|
|
crc = tmp_path / "crc.mp3"
|
|
crc.write_bytes(_frame_stream(gain=150, frames=20, crc=True))
|
|
assert not boost.supported(str(crc))
|
|
junk = tmp_path / "junk.mp3"
|
|
junk.write_bytes(bytes(5000))
|
|
assert not boost.supported(str(junk))
|
|
with pytest.raises(boost.Mp3Error):
|
|
boost.apply_gain(bytes(5000), 2)
|
|
|
|
|
|
def _set_bits(buf, base, bit, count, value):
|
|
for i in range(count):
|
|
b = bit + i
|
|
mask = 1 << (7 - b % 8)
|
|
if (value >> (count - 1 - i)) & 1:
|
|
buf[base + b // 8] |= mask
|
|
else:
|
|
buf[base + b // 8] &= ~mask & 0xFF
|
|
|
|
|
|
def _frame_stream(gain: int, frames: int, crc: bool = False) -> bytes:
|
|
"""Hand-made MPEG-1 Layer III stereo frames, 128 kbps 44.1 kHz, each
|
|
granule with some audio data and ``gain``."""
|
|
header = bytes([0xFF, 0xFA if crc else 0xFB, 0x90, 0x00])
|
|
out = bytearray()
|
|
for _ in range(frames):
|
|
frame = bytearray(header) + bytearray(417 - 4)
|
|
f = boost._header(frame + header, 0)
|
|
for bit in boost._gain_bits(f):
|
|
_set_bits(frame, f.side_offset, bit - 21, 12, 100)
|
|
boost._set8(frame, f.side_offset, bit, gain)
|
|
out += frame
|
|
return bytes(out)
|
|
|
|
|
|
# ---- 4 ----
|
|
|
|
def _library(tmp_path):
|
|
path = _quiet_mp3(tmp_path / "media" / "Music" / "Quiet Band" / "Hush"
|
|
/ "04 Salivate-ish.mp3")
|
|
fields = tagging.read_tags(path)
|
|
library = Library(music_folder=str(tmp_path / "media"))
|
|
library.tracks[1] = Track(track_id=1, name="Salivate-ish",
|
|
artist="Quiet Band", album="Hush",
|
|
location=str(path), play_count=9, rating=80,
|
|
size=fields["size"], kind=fields["kind"],
|
|
total_time=fields["total_time"])
|
|
library.playlists["P"] = Playlist(name="Mix", persistent_id="P",
|
|
track_ids=[1])
|
|
return LibraryManager(library, tmp_path / "data")
|
|
|
|
|
|
def test_in_place_swap_keeps_the_path_and_undoes(qapp, tmp_path, fake_trash):
|
|
manager = _library(tmp_path)
|
|
location = manager.library.tracks[1].location
|
|
original = Path(location).read_bytes()
|
|
staged = tmp_path / "cache" / "boosted" / "04 Salivate-ish.mp3"
|
|
staged.parent.mkdir(parents=True)
|
|
boost.boost_file(Path(location), staged, 6)
|
|
|
|
assert manager.replace_track_files([(1, staged)], label="Boost Volume",
|
|
in_place=True) == []
|
|
track = manager.library.tracks[1]
|
|
boosted = Path(location).read_bytes()
|
|
assert track.location == location and boosted != original
|
|
assert boost.measure(location)[0] > boost.measure(
|
|
str(next(fake_trash.iterdir())))[0] + 8
|
|
assert track.play_count == 9 and manager.library.playlists["P"].track_ids == [1]
|
|
assert not staged.exists()
|
|
assert "Boost Volume" in manager.undo_stack.undo_label()
|
|
|
|
manager.undo_stack.undo()
|
|
assert Path(location).read_bytes() == original
|
|
assert manager.library.tracks[1].location == location
|
|
manager.undo_stack.redo()
|
|
assert Path(location).read_bytes() == boosted
|
|
|
|
|
|
def test_a_failed_trash_leaves_the_song_alone(qapp, tmp_path, monkeypatch):
|
|
from lintunes.trash import TrashError
|
|
manager = _library(tmp_path)
|
|
location = manager.library.tracks[1].location
|
|
original = Path(location).read_bytes()
|
|
staged = tmp_path / "staged.mp3"
|
|
staged.write_bytes(original)
|
|
|
|
def refuse(_path):
|
|
raise TrashError("no trash here")
|
|
monkeypatch.setattr("lintunes.library_manager.trash.send_to_trash", refuse)
|
|
failures = manager.replace_track_files([(1, staged)], in_place=True)
|
|
assert len(failures) == 1 and Path(location).read_bytes() == original
|
|
|
|
|
|
# ---- 5 ----
|
|
|
|
def test_reopen_current_keeps_place_and_listen(qapp, tmp_path):
|
|
track = _local_track(tmp_path, 1)
|
|
player = _player(qapp, [track])
|
|
sink = _FakeSink()
|
|
player.set_sink(sink)
|
|
player.play_queue([1], 0)
|
|
sink._position = 61_000
|
|
changed = []
|
|
player.track_changed.connect(changed.append)
|
|
player.reopen_current()
|
|
assert sink.loads[-1] == (1, True, 61_000)
|
|
assert changed == []
|
|
|
|
|
|
def test_the_player_ignores_the_old_adjustment(qapp, tmp_path):
|
|
track = _local_track(tmp_path, 1, volume_adjustment=-255)
|
|
player = _player(qapp, [track])
|
|
sink = _FakeSink()
|
|
player.set_sink(sink)
|
|
player.set_volume(0.6)
|
|
player.play_queue([1], 0)
|
|
assert sink.volume == pytest.approx(0.6)
|
|
|
|
|
|
# ---- 6 ----
|
|
|
|
def test_get_info_offers_it_only_for_mp3s(qapp, tmp_path):
|
|
from PyQt6.QtWidgets import QPushButton, QSlider
|
|
from lintunes.gui.info_dialog import InfoDialog
|
|
mp3 = _quiet_mp3(tmp_path / "a.mp3")
|
|
flac = tmp_path / "b.flac"
|
|
flac.write_bytes(b"fLaC" + bytes(100))
|
|
library = Library()
|
|
library.tracks[1] = Track(track_id=1, name="A", location=str(mp3))
|
|
library.tracks[2] = Track(track_id=2, name="B", location=str(flac))
|
|
manager = LibraryManager(library, tmp_path / "data")
|
|
|
|
def button(dialog):
|
|
return next(b for b in dialog.findChildren(QPushButton)
|
|
if b.text() == "Boost Volume…")
|
|
for ids, shown in (([1], True), ([2], False), ([1, 2], True)):
|
|
dialog = InfoDialog(manager, ids)
|
|
assert not dialog.findChildren(QSlider)
|
|
assert dialog._form.isRowVisible(dialog._boost_row) == shown
|
|
if shown:
|
|
asked = []
|
|
dialog.boost_requested.connect(asked.append)
|
|
button(dialog).click()
|
|
assert asked == [[1]] # only the MP3
|
|
|
|
|
|
def test_window_flow_boosts_and_undoes(qapp, tmp_path, fake_trash, monkeypatch):
|
|
from lintunes.gui.main_window import MainWindow
|
|
manager = _library(tmp_path)
|
|
location = manager.library.tracks[1].location
|
|
original = Path(location).read_bytes()
|
|
window = MainWindow(manager, Preferences(tmp_path / "data"))
|
|
seen = []
|
|
monkeypatch.setattr(window, "_ask_boost",
|
|
lambda plans: seen.append(plans) or
|
|
{t: p.steps for t, p in plans.items()})
|
|
try:
|
|
window._boost_volume([1])
|
|
deadline = time.time() + 30
|
|
while window._boost is not None and time.time() < deadline:
|
|
qapp.processEvents()
|
|
time.sleep(0.02)
|
|
assert window._boost is None
|
|
assert seen and seen[0][1].steps > 0
|
|
assert Path(location).read_bytes() != original
|
|
lufs, _ = boost.measure(location)
|
|
assert lufs > boost.measure(str(next(fake_trash.iterdir())))[0] + 5
|
|
assert not list((tmp_path / "cache").rglob("boost-*")) # staging gone
|
|
manager.undo_stack.undo()
|
|
assert Path(location).read_bytes() == original
|
|
finally:
|
|
window.close()
|