v0.99.0: Boost Volume amplifies a quiet song's file up to a typical song's loudness (says how many dB and whether it clips; Edit ▸ Undo puts the original back), replacing the per-song Volume Adjustment, which could never play past full volume

This commit is contained in:
2026-11-19 22:51:16 -08:00
parent f52dd7f567
commit a7d061b200
10 changed files with 783 additions and 196 deletions
+284
View File
@@ -0,0 +1,284 @@
"""Round 131: Boost Volume (lintunes/boost.py) replaces the per-track Volume
Adjustment, which could never play past full volume.
1. Measuring: integrated loudness + true peak from ffmpeg's ebur128.
2. The plan: up to a typical song's loudness, and how far it can go clean.
3. Amplifying writes the same format, tags and art kept, the source only read.
4. The library swaps the file in place as one undo step (original to the
trash; undo puts it back at the same path).
5. The player reopens the playing song where it was, without a new listen.
6. Get Info has a Boost Volume… button and no slider; the right-click menu
and the window run the whole thing.
"""
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
"""
# ---- 1 & 2 ----
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_a_quiet_song_with_room_goes_all_the_way_clean(self):
p = boost.plan(-28.7, -18.9, -14.0)
assert p.target_db == 14.7 and not p.clips and p.clean_gain == 14.7
def test_when_typical_needs_more_than_the_headroom_it_clips(self):
p = boost.plan(-28.7, -18.9, -10.0)
assert p.target_db == 18.7 and p.clips
assert p.clean_gain == pytest.approx(17.9) # true peak to -1 dBTP
def test_already_loud_is_not_worth_it(self):
assert not boost.plan(-9.0, -0.2, -10.0).worth_it
assert not boost.plan(None, None, -10.0).measurable
def test_a_near_silent_file_is_capped(self):
assert boost.plan(-70.0 + 15, -50.0, -10.0).target_db == boost.MAX_BOOST_DB
def test_formats(self):
assert boost.encoder_args(Path("a.mp3"), "mp3")[:2] == ["-c:a", "libmp3lame"]
assert boost.encoder_args(Path("a.m4a"), "alac") == ["-c:a", "alac"]
assert boost.encoder_args(Path("a.m4a"), "aac")[1] == "aac"
assert boost.encoder_args(Path("a.m4p"), "aac") is None
assert boost.encoder_args(Path("a.m4a"), None) is None # protected?
# ---- 3 ----
def test_amplify_reaches_the_target_and_keeps_tags_and_art(tmp_path):
src = _quiet_mp3(tmp_path / "in" / "q.mp3")
before = src.read_bytes()
lufs, peak = boost.measure(str(src))
p = boost.plan(lufs, peak, -14.0)
assert not p.clips
dest = tmp_path / "out" / "q.mp3"
dest.parent.mkdir()
boost.amplify(src, dest, p.clean_gain)
after, _ = boost.measure(str(dest))
assert after == pytest.approx(-14.0, abs=0.5)
assert src.read_bytes() == before # only read
tags = tagging.read_tags(dest)
assert tags["name"] == "Salivate-ish" and tags["artist"] == "Quiet Band"
assert tagging.read_embedded_artwork(dest)
def test_amplify_refuses_what_it_cant_rewrite(tmp_path):
odd = tmp_path / "x.wma"
odd.write_bytes(b"x")
with pytest.raises(OSError):
boost.amplify(odd, tmp_path / "y.wma", 3.0)
# ---- 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.amplify(Path(location), staged, 10.0)
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] + 9
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_has_the_button_not_the_slider(qapp, tmp_path):
from PyQt6.QtWidgets import QPushButton, QSlider
from lintunes.gui.info_dialog import InfoDialog
library = Library()
library.tracks[1] = Track(track_id=1, name="A")
library.tracks[2] = Track(track_id=2, name="B")
manager = LibraryManager(library, tmp_path / "data")
for ids in ([1], [1, 2]):
dialog = InfoDialog(manager, ids)
assert not dialog.findChildren(QSlider)
button = next(b for b in dialog.findChildren(QPushButton)
if b.text() == "Boost Volume…")
asked = []
dialog.boost_requested.connect(asked.append)
button.click()
assert asked == [ids]
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.clean_gain 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].worth_it
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()