v0.99.1: Boost Volume no longer re-encodes: it raises an MP3's own gain setting (mp3gain's method, 1.5 dB steps, bit-exact and reversible) toward a typical song's loudness, never clipping; Get Info only, and only for MP3s

This commit is contained in:
2026-11-19 23:14:30 -08:00
parent a7d061b200
commit 6797910d76
7 changed files with 456 additions and 292 deletions
+117 -61
View File
@@ -1,14 +1,9 @@
"""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.
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
@@ -93,7 +88,7 @@ SUMMARY = """[Parsed_ebur128_0 @ 0x1] Summary:
"""
# ---- 1 & 2 ----
# ---- measuring and the plan ----
class TestMeasureAndPlan:
def test_parses_loudness_and_true_peak(self):
@@ -102,54 +97,108 @@ class TestMeasureAndPlan:
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_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_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_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_already_loud_is_not_worth_it(self):
assert not boost.plan(-9.0, -0.2, -10.0).worth_it
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
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?
# ---- 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)
# ---- 3 ----
def test_amplify_reaches_the_target_and_keeps_tags_and_art(tmp_path):
src = _quiet_mp3(tmp_path / "in" / "q.mp3")
@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()
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)
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_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)
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 ----
@@ -175,7 +224,7 @@ def test_in_place_swap_keeps_the_path_and_undoes(qapp, tmp_path, fake_trash):
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)
boost.boost_file(Path(location), staged, 6)
assert manager.replace_track_files([(1, staged)], label="Boost Volume",
in_place=True) == []
@@ -183,7 +232,7 @@ def test_in_place_swap_keeps_the_path_and_undoes(qapp, tmp_path, fake_trash):
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
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()
@@ -238,22 +287,29 @@ def test_the_player_ignores_the_old_adjustment(qapp, tmp_path):
# ---- 6 ----
def test_get_info_has_the_button_not_the_slider(qapp, tmp_path):
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")
library.tracks[2] = Track(track_id=2, name="B")
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")
for ids in ([1], [1, 2]):
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)
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]
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):
@@ -265,7 +321,7 @@ def test_window_flow_boosts_and_undoes(qapp, tmp_path, fake_trash, monkeypatch):
seen = []
monkeypatch.setattr(window, "_ask_boost",
lambda plans: seen.append(plans) or
{t: p.clean_gain for t, p in plans.items()})
{t: p.steps for t, p in plans.items()})
try:
window._boost_volume([1])
deadline = time.time() + 30
@@ -273,7 +329,7 @@ def test_window_flow_boosts_and_undoes(qapp, tmp_path, fake_trash, monkeypatch):
qapp.processEvents()
time.sleep(0.02)
assert window._boost is None
assert seen and seen[0][1].worth_it
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