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:
@@ -139,20 +139,22 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal
|
||||
without recursing. Widgets react to its signals (`playlists_changed`,
|
||||
`playlist_content_changed(pid)`, `track_updated(id)`, `track_fields_edited`).
|
||||
|
||||
- **Boost Volume** (Round 131, `boost.py`; Get Info's button and the
|
||||
right-click menu) replaced Round 79's per-track Volume Adjustment, which
|
||||
scaled the slider and so could never play past full — with the slider up
|
||||
it did nothing (normalization has the same ceiling for quiet songs). The
|
||||
file itself is amplified once: ebur128 measures integrated loudness and
|
||||
true peak, the target is a *typical* song (`LoudnessAnalyzer.typical_lufs`,
|
||||
the median measured), the clean limit is the true peak to −1 dBTP; when
|
||||
typical needs more, the warning offers both (clean, or all the way and
|
||||
clipping — trav wants iTunes' clipping boost available). ffmpeg rewrites
|
||||
the same format (MP3 at V0, AAC 320k, lossless as itself), tags and art
|
||||
copied, staged in `lossless.staging_root()`, then
|
||||
`replace_track_files(…, in_place=True)` trashes the original and puts the
|
||||
boosted file at the same path — one undo step. A boost of the playing song
|
||||
`Player.reopen_current()`s it where it was (no new listen).
|
||||
- **Boost Volume** (Round 131, `boost.py`; Get Info's button, shown only
|
||||
for an MP3 it can treat) replaced Round 79's per-track Volume Adjustment,
|
||||
which scaled the slider and so could never play past full — with the
|
||||
slider up it did nothing (normalization has the same ceiling for quiet
|
||||
songs). **Never transcode** (trav's rule, after v0.99.0 re-encoded and
|
||||
was pulled): it adds the same number of units to every granule's 8-bit
|
||||
`global_gain` in the MP3 side info, mp3gain's method — 1.5 dB a unit,
|
||||
decoded audio exactly × 2^(units/4), same length, nothing else changes.
|
||||
Granules with `part2_3_length` 0 are silence (LAME parks them at 210/255)
|
||||
and are skipped; CRC-protected frames make a file unsupported; the
|
||||
Xing/Info frame is left alone (LAME's tag CRCs it). How much: whole units
|
||||
toward a *typical* song (`LoudnessAnalyzer.typical_lufs`), never past −1
|
||||
dBTP true peak — **no clipping, no options**, one Boost/Cancel. A boosted
|
||||
copy is staged, then `replace_track_files(…, in_place=True)` trashes the
|
||||
original and puts the copy at the same path — one undo step. Boosting the
|
||||
playing song `Player.reopen_current()`s it where it was (no new listen).
|
||||
`Track.volume_adjustment` is still imported and stored but nothing reads it.
|
||||
|
||||
- **Volume normalization** (Round 83, `loudness.py`, Controls → Normalize
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
"""LinTunes — iTunes-style music library manager and player for Linux."""
|
||||
|
||||
__version__ = "0.99.0"
|
||||
__version__ = "0.99.1"
|
||||
|
||||
+252
-117
@@ -1,33 +1,38 @@
|
||||
"""Boost Volume (Round 131): make a too-quiet song as loud as the rest, in
|
||||
the file itself.
|
||||
"""Boost Volume (Round 131): make a too-quiet MP3 as loud as the rest
|
||||
**without re-encoding it** — the way ``mp3gain`` does.
|
||||
|
||||
Why in the file: the player can't play louder than the file (Qt's output
|
||||
volume stops at 1.0), so neither iTunes' old per-song Volume Adjustment nor
|
||||
volume normalization could lift a quiet song while the main volume was up —
|
||||
and turning the laptop up for it blasted the next one. So the song's audio is
|
||||
amplified once, by the ``ffmpeg`` CLI, and saved.
|
||||
Why the file and not the player: the player can't play louder than the file
|
||||
(Qt's output volume stops at 1.0), so neither iTunes' old per-song Volume
|
||||
Adjustment nor volume normalization could lift a quiet song while the main
|
||||
volume was up.
|
||||
|
||||
How, losslessly: every MP3 granule carries an 8-bit ``global_gain`` in its
|
||||
side info, the scale the decoder multiplies the whole granule by — one unit
|
||||
is 2^(1/4) in amplitude, **1.5 dB**. Adding the same number of units to every
|
||||
granule makes the decoder play the same audio louder; the compressed audio
|
||||
itself is untouched, so nothing is lost, and taking the units off again gives
|
||||
back the original bytes. Hence boosts come in 1.5 dB steps, and only MP3s
|
||||
(Layer III) get the button: AAC's equivalent sits behind each frame's Huffman
|
||||
data, and re-encoding anything is ruled out (trav's call — never transcode).
|
||||
|
||||
How much: up to a *typical* song's loudness (the median of every song the
|
||||
normalizer has measured, ``LoudnessAnalyzer.typical_lufs``), measured as EBU
|
||||
R128 integrated loudness. How much it can take *cleanly* is its true peak's
|
||||
distance from ``CEILING_DBTP``. When the typical level needs more than that,
|
||||
the caller offers both: as loud as it goes without clipping, or all the way,
|
||||
clipping — iTunes' boost clipped, and sometimes loud is the point.
|
||||
normalizer has measured, ``LoudnessAnalyzer.typical_lufs``, EBU R128 via
|
||||
ffmpeg, which only *reads*), but never past ``CEILING_DBTP`` true peak — a
|
||||
boost never clips. One choice, no options.
|
||||
|
||||
The file keeps its name, format and tags (mutagen copies them and the art,
|
||||
as Convert to MP3 does); a lossy one is re-encoded at a high setting (MP3 at
|
||||
V0) so the second generation costs as little as it can. The library swaps
|
||||
files through ``LibraryManager.replace_track_files``: the original goes to
|
||||
the trash, Edit ▸ Undo puts it back.
|
||||
Frames whose side info is CRC-protected would need their CRC redone, so such
|
||||
a file counts as unsupported. The Xing/Info frame is left alone: its side
|
||||
info is all zeros anyway, and LAME's tag in it carries a CRC over those bytes.
|
||||
|
||||
Shaped like ``loudness.py``: pure parsing and planning first, then the
|
||||
subprocesses, then ``BoostWorker`` on a daemon thread.
|
||||
The library swaps files through ``LibraryManager.replace_track_files``
|
||||
(in place): the original goes to the trash, Edit ▸ Undo puts it back.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import math
|
||||
import re
|
||||
import subprocess
|
||||
import shutil
|
||||
import tempfile
|
||||
import threading
|
||||
from dataclasses import dataclass
|
||||
@@ -40,14 +45,15 @@ from lintunes.importers import lossless
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
CEILING_DBTP = -1.0 # true-peak headroom a clean boost keeps (lossy decoders overshoot)
|
||||
MIN_BOOST_DB = 0.5 # less is inaudible: not worth a re-encode
|
||||
MAX_BOOST_DB = 30.0 # sanity: past this it's a near-silent file, all hiss
|
||||
CEILING_DBTP = -1.0 # true-peak headroom a boost keeps: it never clips
|
||||
STEP_DB = 1.5 # one global_gain unit
|
||||
MAX_STEPS = 20 # 30 dB: past that it's a near-silent file, all hiss
|
||||
|
||||
_INTEGRATED = re.compile(r"Integrated loudness:\s*\n\s*I:\s*(-?[\d.]+|-inf)\s*LUFS")
|
||||
_TRUE_PEAK = re.compile(r"True peak:\s*\n\s*Peak:\s*(-?[\d.]+|-inf)\s*dBFS")
|
||||
|
||||
|
||||
# ---- measuring and planning ----
|
||||
|
||||
def parse_measurement(output: str) -> tuple[float | None, float | None]:
|
||||
"""``(integrated LUFS, true peak dBTP)`` from ffmpeg's ebur128 summary
|
||||
(run with ``peak=true``); either is None when absent or silent."""
|
||||
@@ -64,74 +70,33 @@ class Plan:
|
||||
"""What a boost of one song would do."""
|
||||
lufs: float | None # how loud it is now
|
||||
peak: float | None # its true peak now, dBTP
|
||||
target_db: float # gain to a typical song's loudness
|
||||
clean_db: float # the most it can take without clipping
|
||||
steps: int # global_gain units to add (1.5 dB each)
|
||||
reaches_typical: bool # False when the peak stopped it short
|
||||
|
||||
@property
|
||||
def gain_db(self) -> float:
|
||||
return self.steps * STEP_DB
|
||||
|
||||
@property
|
||||
def measurable(self) -> bool:
|
||||
return self.lufs is not None and self.peak is not None
|
||||
|
||||
@property
|
||||
def clips(self) -> bool:
|
||||
"""Reaching the typical loudness would clip."""
|
||||
return self.target_db > self.clean_db + 0.05
|
||||
|
||||
@property
|
||||
def clean_gain(self) -> float:
|
||||
"""The boost that gets as close to typical as it can, unclipped."""
|
||||
return max(0.0, min(self.target_db, self.clean_db))
|
||||
|
||||
@property
|
||||
def worth_it(self) -> bool:
|
||||
return self.measurable and self.target_db >= MIN_BOOST_DB
|
||||
|
||||
|
||||
def plan(lufs: float | None, peak: float | None, typical_lufs: float) -> Plan:
|
||||
"""As close to ``typical_lufs`` as whole steps get without passing the
|
||||
ceiling (rounded down, so it never overshoots either)."""
|
||||
if lufs is None or peak is None:
|
||||
return Plan(lufs, peak, 0.0, 0.0)
|
||||
target = max(0.0, min(MAX_BOOST_DB, typical_lufs - lufs))
|
||||
clean = max(0.0, min(MAX_BOOST_DB, CEILING_DBTP - peak))
|
||||
return Plan(lufs, peak, round(target, 1), round(clean, 1))
|
||||
return Plan(lufs, peak, 0, False)
|
||||
wanted = typical_lufs - lufs
|
||||
room = CEILING_DBTP - peak
|
||||
steps = max(0, min(MAX_STEPS, math.floor(min(wanted, room) / STEP_DB + 1e-9)))
|
||||
# "Reaches" means within a step of where it was going.
|
||||
return Plan(lufs, peak, steps, wanted - steps * STEP_DB < STEP_DB)
|
||||
|
||||
|
||||
def encoder_args(path: Path, codec: str | None) -> list[str] | None:
|
||||
"""ffmpeg's output codec options to write ``path``'s format again, or
|
||||
None for a format this can't rewrite. Lossy formats get their best
|
||||
setting, since this is a second generation."""
|
||||
suffix = path.suffix.lower()
|
||||
if suffix == ".mp3":
|
||||
return ["-c:a", "libmp3lame", "-q:a", "0", "-id3v2_version", "3"]
|
||||
if suffix in (".m4a", ".mp4", ".aac"):
|
||||
if codec == "alac":
|
||||
return ["-c:a", "alac"]
|
||||
if codec == "aac":
|
||||
return ["-c:a", "aac", "-b:a", "320k"]
|
||||
return None # protected AAC, or something unexpected
|
||||
if suffix == ".flac":
|
||||
return ["-c:a", "flac"]
|
||||
if suffix == ".wav":
|
||||
return ["-c:a", "pcm_s16le"]
|
||||
if suffix in (".aiff", ".aif"):
|
||||
return ["-c:a", "pcm_s16be"]
|
||||
if suffix == ".ogg":
|
||||
return ["-c:a", "libvorbis", "-q:a", "8"]
|
||||
if suffix == ".opus":
|
||||
return ["-c:a", "libopus", "-b:a", "256k"]
|
||||
return None
|
||||
|
||||
|
||||
def ffmpeg_command(src: Path, dest: Path, gain_db: float,
|
||||
codec_args: list[str]) -> list[str]:
|
||||
"""Audio only (art is copied afterwards with the tags), amplified."""
|
||||
return ["ffmpeg", "-nostdin", "-hide_banner", "-loglevel", "error",
|
||||
"-nostats", "-y", "-i", str(src), "-vn", "-map", "0:a:0",
|
||||
"-af", f"volume={gain_db:.2f}dB", *codec_args, str(dest)]
|
||||
|
||||
|
||||
# ---- subprocesses ----
|
||||
|
||||
def measure(path: str) -> tuple[float | None, float | None]:
|
||||
"""Decode the whole file once through ebur128 with true peak."""
|
||||
import subprocess
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["ffmpeg", "-nostdin", "-nostats", "-hide_banner", "-i", path,
|
||||
@@ -144,52 +109,222 @@ def measure(path: str) -> tuple[float | None, float | None]:
|
||||
return parse_measurement(result.stderr)
|
||||
|
||||
|
||||
def probe_codec(path: str) -> str | None:
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["ffprobe", "-v", "error", "-select_streams", "a:0",
|
||||
"-show_entries", "stream=codec_name", "-of", "csv=p=0", path],
|
||||
capture_output=True, text=True, timeout=30)
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
# ---- MP3 frames ----
|
||||
|
||||
class Mp3Error(Exception):
|
||||
"""Not an MP3 whose gain this can change."""
|
||||
|
||||
|
||||
_BITRATES = { # Layer III, kbps by index
|
||||
1: (0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320),
|
||||
2: (0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160),
|
||||
}
|
||||
_RATES = {3: (44100, 48000, 32000), 2: (22050, 24000, 16000),
|
||||
0: (11025, 12000, 8000)} # by the header's version bits
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Frame:
|
||||
offset: int
|
||||
length: int
|
||||
mpeg1: bool
|
||||
channels: int
|
||||
crc: bool
|
||||
|
||||
@property
|
||||
def side_offset(self) -> int:
|
||||
return self.offset + 4 + (2 if self.crc else 0)
|
||||
|
||||
@property
|
||||
def side_length(self) -> int:
|
||||
if self.mpeg1:
|
||||
return 17 if self.channels == 1 else 32
|
||||
return 9 if self.channels == 1 else 17
|
||||
|
||||
|
||||
def _header(data, pos: int) -> _Frame | None:
|
||||
"""The Layer III frame starting at ``pos``, or None if there isn't one."""
|
||||
if pos + 4 > len(data) or data[pos] != 0xFF or (data[pos + 1] & 0xE0) != 0xE0:
|
||||
return None
|
||||
return result.stdout.strip() or None
|
||||
b1, b2, b3 = data[pos + 1], data[pos + 2], data[pos + 3]
|
||||
version = (b1 >> 3) & 3 # 3 MPEG1, 2 MPEG2, 0 MPEG2.5, 1 reserved
|
||||
layer = (b1 >> 1) & 3 # 1 = Layer III
|
||||
if version == 1 or layer != 1:
|
||||
return None
|
||||
br_index, sr_index = b2 >> 4, (b2 >> 2) & 3
|
||||
if br_index in (0, 15) or sr_index == 3:
|
||||
return None # free format, bad, or reserved
|
||||
mpeg1 = version == 3
|
||||
bitrate = _BITRATES[1 if mpeg1 else 2][br_index] * 1000
|
||||
rate = _RATES[version][sr_index]
|
||||
padding = (b2 >> 1) & 1
|
||||
length = (144 if mpeg1 else 72) * bitrate // rate + padding
|
||||
channels = 1 if (b3 >> 6) == 3 else 2
|
||||
return _Frame(pos, length, mpeg1, channels, crc=not (b1 & 1))
|
||||
|
||||
|
||||
def amplify(src: Path, dest: Path, gain_db: float):
|
||||
"""Write ``src`` amplified by ``gain_db`` to ``dest`` (same format),
|
||||
tags and art copied. Raises OSError on failure; ``src`` is only read."""
|
||||
codec_args = encoder_args(src, probe_codec(str(src)))
|
||||
if codec_args is None:
|
||||
raise OSError(f"can't rewrite a {src.suffix or 'suffixless'} file")
|
||||
result = subprocess.run(ffmpeg_command(src, dest, gain_db, codec_args),
|
||||
capture_output=True, text=True, errors="replace",
|
||||
timeout=900)
|
||||
if result.returncode != 0 or not dest.exists():
|
||||
dest.unlink(missing_ok=True)
|
||||
lines = [l for l in result.stderr.splitlines() if l.strip()]
|
||||
raise OSError("ffmpeg failed" + (f": {lines[-1]}" if lines else ""))
|
||||
lossless.copy_tags(src, dest)
|
||||
def _audio_start(data) -> int:
|
||||
"""Past an ID3v2 tag (and its footer), if there is one."""
|
||||
if data[:3] == b"ID3" and len(data) >= 10:
|
||||
size = 0
|
||||
for b in data[6:10]:
|
||||
size = (size << 7) | (b & 0x7F)
|
||||
return 10 + size + (10 if data[5] & 0x10 else 0)
|
||||
return 0
|
||||
|
||||
|
||||
def _frames(data):
|
||||
"""Every Layer III frame, in order. A frame is trusted when the next
|
||||
one starts where it ends (or it's the last); junk between frames is
|
||||
skipped by resyncing on the next pair that chains."""
|
||||
pos = _audio_start(data)
|
||||
end = len(data)
|
||||
if data[-128:-125] == b"TAG":
|
||||
end -= 128
|
||||
synced = False
|
||||
while pos < end - 4:
|
||||
frame = _header(data, pos)
|
||||
if frame is not None and pos + frame.length <= end:
|
||||
following = pos + frame.length
|
||||
if synced or following >= end - 4 or _header(data, following):
|
||||
synced = True
|
||||
yield frame
|
||||
pos = following
|
||||
continue
|
||||
synced = False
|
||||
pos += 1
|
||||
|
||||
|
||||
def _is_info_frame(data, frame: _Frame) -> bool:
|
||||
tag = frame.side_offset + frame.side_length
|
||||
return data[tag:tag + 4] in (b"Xing", b"Info")
|
||||
|
||||
|
||||
def _gain_bits(frame: _Frame):
|
||||
"""Bit offsets of every global_gain in the frame's side info."""
|
||||
if frame.mpeg1:
|
||||
head = 9 + (5 if frame.channels == 1 else 3) + 4 * frame.channels
|
||||
granules, info = 2, 59
|
||||
else:
|
||||
head = 8 + (1 if frame.channels == 1 else 2)
|
||||
granules, info = 1, 63
|
||||
for g in range(granules):
|
||||
for c in range(frame.channels):
|
||||
yield head + (g * frame.channels + c) * info + 21
|
||||
|
||||
|
||||
def _bits(buf, base: int, bit: int, count: int) -> int:
|
||||
value = 0
|
||||
for i in range(bit, bit + count):
|
||||
value = (value << 1) | ((buf[base + i // 8] >> (7 - i % 8)) & 1)
|
||||
return value
|
||||
|
||||
|
||||
def _get8(buf, base: int, bit: int) -> int:
|
||||
byte, shift = base + bit // 8, bit % 8
|
||||
word = (buf[byte] << 8) | buf[byte + 1]
|
||||
return (word >> (8 - shift)) & 0xFF
|
||||
|
||||
|
||||
def _set8(buf, base: int, bit: int, value: int):
|
||||
byte, shift = base + bit // 8, bit % 8
|
||||
word = (buf[byte] << 8) | buf[byte + 1]
|
||||
mask = 0xFF << (8 - shift)
|
||||
word = (word & ~mask & 0xFFFF) | (value << (8 - shift))
|
||||
buf[byte], buf[byte + 1] = word >> 8, word & 0xFF
|
||||
|
||||
|
||||
def _gain_sites(data):
|
||||
"""Every (frame, side-info base, bit offset) whose gain is ours to move.
|
||||
Raises Mp3Error for a file this can't treat."""
|
||||
sites, frames = [], 0
|
||||
for frame in _frames(data):
|
||||
frames += 1
|
||||
if frame.crc:
|
||||
raise Mp3Error("its frames have CRC checks")
|
||||
if _is_info_frame(data, frame):
|
||||
continue
|
||||
for bit in _gain_bits(frame):
|
||||
# A granule with no audio data (part2_3_length 0) is digital
|
||||
# silence: LAME parks its gain at 210 or 255, and it means
|
||||
# nothing — moving it would only hit the 255 ceiling.
|
||||
if _bits(data, frame.side_offset, bit - 21, 12):
|
||||
sites.append((frame.side_offset, bit))
|
||||
if frames < 10 or not sites:
|
||||
raise Mp3Error("no MP3 audio found")
|
||||
return sites
|
||||
|
||||
|
||||
def supported(path: str) -> bool:
|
||||
"""Whether Boost Volume can work on this file: an MP3 (Layer III)
|
||||
without CRC-protected frames. Reads the start of the file only."""
|
||||
if Path(path).suffix.lower() != ".mp3":
|
||||
return False
|
||||
try:
|
||||
with open(path, "rb") as f:
|
||||
head = f.read(10)
|
||||
start = _audio_start(head) if len(head) == 10 else 0
|
||||
f.seek(start)
|
||||
data = f.read(16384)
|
||||
except OSError:
|
||||
return False
|
||||
for pos in range(min(len(data) - 4, 4096)):
|
||||
frame = _header(data, pos)
|
||||
if frame is not None and _header(data, pos + frame.length):
|
||||
return not frame.crc
|
||||
return False
|
||||
|
||||
|
||||
def headroom_steps(data) -> int:
|
||||
"""How many steps fit before some granule's gain would pass 255."""
|
||||
return 255 - max(_get8(data, base, bit) for base, bit in _gain_sites(data))
|
||||
|
||||
|
||||
def apply_gain(data: bytes, steps: int) -> bytes:
|
||||
"""``data`` (a whole MP3 file) with ``steps`` added to every granule's
|
||||
global_gain. Same length; only those bits differ. Raises Mp3Error."""
|
||||
buf = bytearray(data)
|
||||
sites = _gain_sites(buf)
|
||||
if steps > 255 - max(_get8(buf, b, bit) for b, bit in sites):
|
||||
raise Mp3Error("its gain is already near the top")
|
||||
for base, bit in sites:
|
||||
value = _get8(buf, base, bit)
|
||||
_set8(buf, base, bit, max(0, value + steps))
|
||||
return bytes(buf)
|
||||
|
||||
|
||||
def boost_file(src: Path, dest: Path, steps: int):
|
||||
"""Write ``src`` with ``steps`` more gain to ``dest``. ``src`` is only
|
||||
read; ``dest`` is byte for byte the same file but for the gain bits."""
|
||||
data = src.read_bytes()
|
||||
steps = min(steps, headroom_steps(data))
|
||||
if steps <= 0:
|
||||
raise Mp3Error("its gain is already at the top")
|
||||
dest.write_bytes(apply_gain(data, steps))
|
||||
shutil.copystat(src, dest)
|
||||
|
||||
|
||||
# ---- the worker ----
|
||||
|
||||
class BoostWorker(QObject):
|
||||
"""Measures songs, then (once told how much) amplifies them, on a daemon
|
||||
thread. Works from ``(track id, path)`` snapshots, never the library.
|
||||
"""Measures songs, then (once told how much) writes boosted copies, on
|
||||
a daemon thread. Works from ``(track id, path, name)`` snapshots, never
|
||||
the library.
|
||||
|
||||
``measured`` carries ``{track id: Plan}``; ``amplified`` carries
|
||||
``measured`` carries ``{track id: Plan}``; ``boosted`` carries
|
||||
``[(track id, staged file)]`` plus ``[(track id, reason)]`` failures.
|
||||
The caller removes ``tmp_dir`` when it's done with the staged files."""
|
||||
|
||||
measured = pyqtSignal(dict)
|
||||
progress = pyqtSignal(str)
|
||||
amplified = pyqtSignal(list, list)
|
||||
boosted = pyqtSignal(list, list)
|
||||
|
||||
def __init__(self, items: list[tuple[int, str, str]], typical_lufs: float,
|
||||
parent=None, measure_fn=None, amplify_fn=None):
|
||||
parent=None, measure_fn=None):
|
||||
super().__init__(parent)
|
||||
self._items = list(items) # (track id, path, display name)
|
||||
self._items = list(items)
|
||||
self._typical = typical_lufs
|
||||
self._measure = measure_fn or measure
|
||||
self._amplify = amplify_fn or amplify
|
||||
self.tmp_dir: Path | None = None
|
||||
self._busy = False
|
||||
|
||||
@@ -199,8 +334,8 @@ class BoostWorker(QObject):
|
||||
def start_measuring(self):
|
||||
self._start(self._run_measure)
|
||||
|
||||
def start_amplifying(self, gains: dict[int, float]):
|
||||
self._start(lambda: self._run_amplify(gains))
|
||||
def start_boosting(self, steps: dict[int, int]):
|
||||
self._start(lambda: self._run_boost(steps))
|
||||
|
||||
def _start(self, target):
|
||||
self._busy = True
|
||||
@@ -219,25 +354,25 @@ class BoostWorker(QObject):
|
||||
plans[tid] = plan(*self._measure(path), self._typical)
|
||||
self.measured.emit(plans)
|
||||
|
||||
def _run_amplify(self, gains: dict[int, float]):
|
||||
def _run_boost(self, steps: dict[int, int]):
|
||||
root = lossless.staging_root()
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
self.tmp_dir = Path(tempfile.mkdtemp(prefix="boost-", dir=root))
|
||||
done, failed = [], []
|
||||
todo = [item for item in self._items if item[0] in gains]
|
||||
todo = [item for item in self._items if item[0] in steps]
|
||||
for n, (tid, path, name) in enumerate(todo, 1):
|
||||
self.progress.emit(f"Amplifying {self._which(n, name, len(todo))}")
|
||||
self.progress.emit(f"Boosting {self._which(n, name, len(todo))}")
|
||||
src = Path(path)
|
||||
dest = self.tmp_dir / f"{tid}" / src.name
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
self._amplify(src, dest, gains[tid])
|
||||
except Exception as e:
|
||||
boost_file(src, dest, steps[tid])
|
||||
except (OSError, Mp3Error) as e:
|
||||
log.warning("boost: %s: %s", path, e)
|
||||
failed.append((tid, str(e)))
|
||||
continue
|
||||
done.append((tid, dest))
|
||||
self.amplified.emit(done, failed)
|
||||
self.boosted.emit(done, failed)
|
||||
|
||||
def _which(self, n: int, name: str, total: int | None = None) -> str:
|
||||
total = total if total is not None else len(self._items)
|
||||
|
||||
@@ -379,18 +379,23 @@ class InfoDialog(QDialog):
|
||||
form.addRow("", self._stop_row)
|
||||
|
||||
# Boost Volume (Round 131) replaced iTunes' Volume Adjustment slider,
|
||||
# which could never play past full volume. It amplifies the file
|
||||
# itself, at once, as its own undo step; MainWindow does the work.
|
||||
volume_row = QHBoxLayout()
|
||||
# which could never play past full volume. It raises an MP3's own
|
||||
# gain (no re-encode), at once, as its own undo step; MainWindow
|
||||
# does the work. Only shown when a selected song is an MP3 it can
|
||||
# work on.
|
||||
self._boost_row = QWidget()
|
||||
volume_row = QHBoxLayout(self._boost_row)
|
||||
volume_row.setContentsMargins(0, 0, 0, 0)
|
||||
self._boost_button = QPushButton("Boost Volume…")
|
||||
self._boost_button.setToolTip(
|
||||
"Make a quiet song as loud as a typical one by amplifying the "
|
||||
"file itself. Edit ▸ Undo puts the original back.")
|
||||
"Make a quiet MP3 about as loud as a typical song, without "
|
||||
"re-encoding it or clipping. Edit ▸ Undo puts the original back.")
|
||||
self._boost_button.setAutoDefault(False)
|
||||
self._boost_button.clicked.connect(self._on_boost)
|
||||
volume_row.addWidget(self._boost_button)
|
||||
volume_row.addStretch(1)
|
||||
form.addRow("Volume:", volume_row)
|
||||
form.addRow("Volume:", self._boost_row)
|
||||
self._form = form
|
||||
|
||||
self._file_label = QLabel()
|
||||
self._file_label.setStyleSheet("color: gray; font-size: 10px;")
|
||||
@@ -412,6 +417,7 @@ class InfoDialog(QDialog):
|
||||
self._load_multi()
|
||||
else:
|
||||
self._load_current()
|
||||
self._show_boost()
|
||||
|
||||
def _make_time_row(self, title: str):
|
||||
row = QWidget()
|
||||
@@ -603,10 +609,21 @@ class InfoDialog(QDialog):
|
||||
|
||||
# ---- volume ----
|
||||
|
||||
def _on_boost(self):
|
||||
def _boostable_ids(self) -> list[int]:
|
||||
from lintunes import boost
|
||||
ids = (list(self._track_ids) if self._multi
|
||||
else [self._current_track().track_id])
|
||||
self.boost_requested.emit(ids)
|
||||
tracks = self._manager.library.tracks
|
||||
return [tid for tid in ids if tid in tracks and tracks[tid].location
|
||||
and boost.supported(tracks[tid].location)]
|
||||
|
||||
def _show_boost(self):
|
||||
self._form.setRowVisible(self._boost_row, bool(self._boostable_ids()))
|
||||
|
||||
def _on_boost(self):
|
||||
ids = self._boostable_ids()
|
||||
if ids:
|
||||
self.boost_requested.emit(ids)
|
||||
|
||||
def _on_ok(self):
|
||||
saved = self._save_multi() if self._multi else self._save_current()
|
||||
|
||||
+45
-84
@@ -318,7 +318,6 @@ class MainWindow(QMainWindow):
|
||||
# Done or Cancel — which can be after its worker has finished.
|
||||
self._compress = None
|
||||
self._boost = None # boost.BoostWorker while one runs
|
||||
self._boost_typical = 0.0
|
||||
self._compress_reload = QTimer(self)
|
||||
self._compress_reload.setSingleShot(True)
|
||||
self._compress_reload.setInterval(400)
|
||||
@@ -391,7 +390,6 @@ class MainWindow(QMainWindow):
|
||||
view.table.identify_requested.connect(self._identify_tracks)
|
||||
view.table.bpm_requested.connect(self._calculate_bpm)
|
||||
view.table.convert_requested.connect(self._convert_to_mp3)
|
||||
view.table.boost_requested.connect(self._boost_volume)
|
||||
view.table.dj_prepare_requested.connect(self._prepare_for_dj)
|
||||
view.table.remove_from_library_requested.connect(
|
||||
lambda ids: self._delete_tracks(ids, delete_files=False))
|
||||
@@ -1911,13 +1909,13 @@ class MainWindow(QMainWindow):
|
||||
# ---- Boost Volume (Round 131, lintunes/boost.py) ----
|
||||
|
||||
def _boost_volume(self, track_ids: list[int]):
|
||||
"""Right-click or Get Info › Boost Volume…: measure, say what it
|
||||
would do, amplify the files, swap them in as one undo step."""
|
||||
"""Get Info › Boost Volume…: measure, say what it would do, raise
|
||||
the MP3s' own gain (no re-encode), swap them in as one undo step."""
|
||||
from lintunes import boost
|
||||
if not lossless.ffmpeg_available():
|
||||
QMessageBox.warning(
|
||||
QApplication.activeWindow() or self, "Boost Volume",
|
||||
"Boosting needs ffmpeg, which is not installed.\n\n"
|
||||
"Measuring loudness needs ffmpeg, which is not installed.\n\n"
|
||||
"Install your distro's “ffmpeg” package and try again.")
|
||||
return
|
||||
if self._boost is not None:
|
||||
@@ -1926,9 +1924,9 @@ class MainWindow(QMainWindow):
|
||||
return
|
||||
tracks = [self._manager.library.tracks[t] for t in track_ids
|
||||
if t in self._manager.library.tracks]
|
||||
tracks = [t for t in tracks if t.location and Path(t.location).exists()]
|
||||
tracks = [t for t in tracks if t.location and boost.supported(t.location)]
|
||||
if not tracks:
|
||||
self.statusBar().showMessage("No song file to boost", 6000)
|
||||
self.statusBar().showMessage("Only MP3s can be boosted", 6000)
|
||||
return
|
||||
analyzer = getattr(self.player, "loudness", None)
|
||||
typical = (analyzer.typical_lufs() if analyzer is not None
|
||||
@@ -1937,10 +1935,9 @@ class MainWindow(QMainWindow):
|
||||
[(t.track_id, t.location, t.name or Path(t.location).stem)
|
||||
for t in tracks], typical, self)
|
||||
self._boost = worker
|
||||
self._boost_typical = typical
|
||||
worker.progress.connect(lambda text: self.statusBar().showMessage(text))
|
||||
worker.measured.connect(self._on_boost_measured)
|
||||
worker.amplified.connect(self._on_boost_amplified)
|
||||
worker.boosted.connect(self._on_boosted)
|
||||
worker.start_measuring()
|
||||
|
||||
def _boost_end(self, message: str = ""):
|
||||
@@ -1953,98 +1950,62 @@ class MainWindow(QMainWindow):
|
||||
self.statusBar().clearMessage()
|
||||
|
||||
def _on_boost_measured(self, plans: dict):
|
||||
gains = self._ask_boost(plans)
|
||||
if not gains:
|
||||
steps = self._ask_boost(plans)
|
||||
if not steps:
|
||||
self._boost_end()
|
||||
return
|
||||
self._boost.start_amplifying(gains)
|
||||
self._boost.start_boosting(steps)
|
||||
|
||||
def _ask_boost(self, plans: dict) -> dict:
|
||||
"""The warning before anything changes: how many dB, and whether it
|
||||
clips. ``{track id: gain dB}`` to apply, empty for none."""
|
||||
from lintunes import boost
|
||||
"""The one question before anything changes: how many dB. Never
|
||||
clips, so there is nothing else to choose. ``{track id: steps}``,
|
||||
empty for no."""
|
||||
parent = QApplication.activeWindow() or self
|
||||
tracks = self._manager.library.tracks
|
||||
name = lambda tid: f"“{tracks[tid].name}”" if tid in tracks else "This song"
|
||||
typical = self._boost_typical
|
||||
unmeasurable = [t for t, p in plans.items() if not p.measurable]
|
||||
loud = [t for t, p in plans.items() if p.measurable and not p.worth_it]
|
||||
todo = {t: p for t, p in plans.items() if p.worth_it}
|
||||
todo = {t: p for t, p in plans.items() if p.steps > 0}
|
||||
if not todo:
|
||||
if unmeasurable and not loud:
|
||||
text = (f"{name(unmeasurable[0])} couldn't be measured — it "
|
||||
"may be silent or unreadable." if len(plans) == 1 else
|
||||
"None of those songs could be measured.")
|
||||
elif len(plans) == 1:
|
||||
p = plans[loud[0]]
|
||||
text = (f"{name(loud[0])} is already as loud as a typical song "
|
||||
f"({p.lufs:.1f} LUFS; typical is {typical:.1f}) — "
|
||||
"nothing to boost.")
|
||||
if len(plans) == 1:
|
||||
tid, p = next(iter(plans.items()))
|
||||
text = (f"{name(tid)} couldn't be measured — it may be silent "
|
||||
"or unreadable." if not p.measurable else
|
||||
f"{name(tid)} can't get any louder without clipping, "
|
||||
"or is already as loud as a typical song.")
|
||||
else:
|
||||
text = "Those songs are already as loud as a typical song."
|
||||
text = ("None of those songs can get louder without clipping, "
|
||||
"or they're already as loud as a typical song.")
|
||||
QMessageBox.information(parent, "Boost Volume", text)
|
||||
return {}
|
||||
undo_note = ("The original goes to the trash; Edit ▸ Undo puts it back."
|
||||
if len(todo) == 1 else
|
||||
"The originals go to the trash; Edit ▸ Undo puts them all back.")
|
||||
if len(todo) == 1:
|
||||
tid, p = next(iter(todo.items()))
|
||||
text = (f"{name(tid)} will be boosted {p.gain_db:+.1f} dB"
|
||||
+ (", to a typical song's loudness," if p.reaches_typical
|
||||
else ", as far as it goes without clipping,")
|
||||
+ " and will not clip.")
|
||||
else:
|
||||
lines = [f"{name(t)}: {p.gain_db:+.1f} dB" for t, p in todo.items()]
|
||||
left = len(plans) - len(todo)
|
||||
text = (f"{len(todo)} songs will be boosted toward a typical "
|
||||
"song's loudness, and none will clip:\n\n"
|
||||
+ "\n".join(lines[:10]) + ("\n…" if len(lines) > 10 else "")
|
||||
+ (f"\n\n{left} can't get louder and are left as they are."
|
||||
if left else ""))
|
||||
box = QMessageBox(parent)
|
||||
box.setWindowTitle("Boost Volume")
|
||||
box.setIcon(QMessageBox.Icon.Question)
|
||||
clipping = {t: p for t, p in todo.items() if p.clips}
|
||||
if len(todo) == 1:
|
||||
tid, p = next(iter(todo.items()))
|
||||
if not p.clips:
|
||||
box.setText(f"{name(tid)} will be amplified {p.target_db:+.1f} dB, "
|
||||
"to a typical song's loudness, and will not clip.")
|
||||
else:
|
||||
box.setText(
|
||||
f"{name(tid)} needs {p.target_db:+.1f} dB to be as loud as "
|
||||
f"a typical song, which would clip it. Without clipping it "
|
||||
f"can be amplified {p.clean_gain:+.1f} dB.")
|
||||
else:
|
||||
lines = [f"{name(t)}: {p.target_db:+.1f} dB"
|
||||
+ (f" (clips; {p.clean_gain:+.1f} dB without)" if p.clips else "")
|
||||
for t, p in todo.items()]
|
||||
skipped = len(loud) + len(unmeasurable)
|
||||
box.setText(f"{len(todo)} songs will be amplified to a typical "
|
||||
"song's loudness" + (" — some would clip:" if clipping
|
||||
else ", and none will clip:"))
|
||||
box.setDetailedText("\n".join(lines))
|
||||
box.setInformativeText(
|
||||
"\n".join(lines[:8]) + ("\n…" if len(lines) > 8 else "")
|
||||
+ (f"\n\n{skipped} already loud enough or unmeasurable, left as they are."
|
||||
if skipped else "") + "\n\n" + undo_note)
|
||||
if len(todo) == 1:
|
||||
box.setInformativeText(undo_note)
|
||||
full = clean = None
|
||||
if not clipping:
|
||||
full = box.addButton("Amplify", QMessageBox.ButtonRole.AcceptRole)
|
||||
box.setDefaultButton(full)
|
||||
else:
|
||||
if len(todo) == 1:
|
||||
p = next(iter(todo.values()))
|
||||
if p.clean_gain >= boost.MIN_BOOST_DB:
|
||||
clean = box.addButton(f"Amplify {p.clean_gain:+.1f} dB",
|
||||
QMessageBox.ButtonRole.AcceptRole)
|
||||
full = box.addButton(f"Amplify {p.target_db:+.1f} dB (clips)",
|
||||
QMessageBox.ButtonRole.AcceptRole)
|
||||
else:
|
||||
clean = box.addButton("Amplify Without Clipping",
|
||||
QMessageBox.ButtonRole.AcceptRole)
|
||||
full = box.addButton("Amplify All the Way (clips)",
|
||||
QMessageBox.ButtonRole.AcceptRole)
|
||||
box.setDefaultButton(clean or full)
|
||||
box.setText(text)
|
||||
box.setInformativeText(
|
||||
"Nothing is re-encoded: only the MP3's own volume setting "
|
||||
"changes. Edit ▸ Undo puts the original back.")
|
||||
ok = box.addButton("Boost", QMessageBox.ButtonRole.AcceptRole)
|
||||
box.addButton(QMessageBox.StandardButton.Cancel)
|
||||
box.setDefaultButton(ok)
|
||||
box.exec()
|
||||
chosen = box.clickedButton()
|
||||
if chosen is full:
|
||||
return {t: p.target_db for t, p in todo.items()}
|
||||
if chosen is clean:
|
||||
return {t: p.clean_gain for t, p in todo.items()
|
||||
if p.clean_gain >= boost.MIN_BOOST_DB}
|
||||
return {}
|
||||
if box.clickedButton() is not ok:
|
||||
return {}
|
||||
return {t: p.steps for t, p in todo.items()}
|
||||
|
||||
def _on_boost_amplified(self, done: list, failed: list):
|
||||
def _on_boosted(self, done: list, failed: list):
|
||||
try:
|
||||
failures = self._manager.replace_track_files(
|
||||
done, label="Boost Volume", in_place=True)
|
||||
|
||||
@@ -800,7 +800,6 @@ class TrackTableView(QTableView):
|
||||
identify_requested = pyqtSignal(list) # selected track ids
|
||||
bpm_requested = pyqtSignal(list) # selected track ids
|
||||
convert_requested = pyqtSignal(list) # selected track ids (to MP3)
|
||||
boost_requested = pyqtSignal(list) # selected track ids (Boost Volume)
|
||||
dj_prepare_requested = pyqtSignal(list) # selected track ids
|
||||
remove_from_library_requested = pyqtSignal(list) # track ids, file kept
|
||||
delete_from_library_requested = pyqtSignal(list) # track ids, file trashed
|
||||
@@ -1134,7 +1133,6 @@ class TrackTableView(QTableView):
|
||||
locations = self.selected_locations()
|
||||
reveal_action = copy_path_action = download_art_action = None
|
||||
identify_action = bpm_action = dj_action = convert_action = None
|
||||
boost_action = None
|
||||
if locations:
|
||||
menu.addSeparator()
|
||||
reveal_action = menu.addAction(
|
||||
@@ -1144,9 +1142,6 @@ class TrackTableView(QTableView):
|
||||
# Fingerprinting reads the audio, so this needs a file on disk.
|
||||
identify_action = menu.addAction("Identify Track…")
|
||||
bpm_action = menu.addAction("Calculate BPM")
|
||||
boost_action = menu.addAction("Boost Volume…")
|
||||
boost_action.setToolTip("Amplify a quiet song's file up to a "
|
||||
"typical song's loudness")
|
||||
dj_action = menu.addAction("Prepare for DJ")
|
||||
dj_action.setToolTip("Work out BPM and separate vocals now, so "
|
||||
"these load instantly onto a deck")
|
||||
@@ -1210,8 +1205,6 @@ class TrackTableView(QTableView):
|
||||
self.identify_requested.emit(self.selected_track_ids())
|
||||
elif bpm_action is not None and chosen is bpm_action:
|
||||
self.bpm_requested.emit(self.selected_track_ids())
|
||||
elif boost_action is not None and chosen is boost_action:
|
||||
self.boost_requested.emit(self.selected_track_ids())
|
||||
elif convert_action is not None and chosen is convert_action:
|
||||
self.convert_requested.emit(self.selected_track_ids())
|
||||
elif dj_action is not None and chosen is dj_action:
|
||||
|
||||
+117
-61
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user