forked from trav/lintunes
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:
@@ -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:
|
||||
|
||||
Reference in New Issue
Block a user