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`,
|
without recursing. Widgets react to its signals (`playlists_changed`,
|
||||||
`playlist_content_changed(pid)`, `track_updated(id)`, `track_fields_edited`).
|
`playlist_content_changed(pid)`, `track_updated(id)`, `track_fields_edited`).
|
||||||
|
|
||||||
- **Boost Volume** (Round 131, `boost.py`; Get Info's button and the
|
- **Boost Volume** (Round 131, `boost.py`; Get Info's button, shown only
|
||||||
right-click menu) replaced Round 79's per-track Volume Adjustment, which
|
for an MP3 it can treat) replaced Round 79's per-track Volume Adjustment,
|
||||||
scaled the slider and so could never play past full — with the slider up
|
which scaled the slider and so could never play past full — with the
|
||||||
it did nothing (normalization has the same ceiling for quiet songs). The
|
slider up it did nothing (normalization has the same ceiling for quiet
|
||||||
file itself is amplified once: ebur128 measures integrated loudness and
|
songs). **Never transcode** (trav's rule, after v0.99.0 re-encoded and
|
||||||
true peak, the target is a *typical* song (`LoudnessAnalyzer.typical_lufs`,
|
was pulled): it adds the same number of units to every granule's 8-bit
|
||||||
the median measured), the clean limit is the true peak to −1 dBTP; when
|
`global_gain` in the MP3 side info, mp3gain's method — 1.5 dB a unit,
|
||||||
typical needs more, the warning offers both (clean, or all the way and
|
decoded audio exactly × 2^(units/4), same length, nothing else changes.
|
||||||
clipping — trav wants iTunes' clipping boost available). ffmpeg rewrites
|
Granules with `part2_3_length` 0 are silence (LAME parks them at 210/255)
|
||||||
the same format (MP3 at V0, AAC 320k, lossless as itself), tags and art
|
and are skipped; CRC-protected frames make a file unsupported; the
|
||||||
copied, staged in `lossless.staging_root()`, then
|
Xing/Info frame is left alone (LAME's tag CRCs it). How much: whole units
|
||||||
`replace_track_files(…, in_place=True)` trashes the original and puts the
|
toward a *typical* song (`LoudnessAnalyzer.typical_lufs`), never past −1
|
||||||
boosted file at the same path — one undo step. A boost of the playing song
|
dBTP true peak — **no clipping, no options**, one Boost/Cancel. A boosted
|
||||||
`Player.reopen_current()`s it where it was (no new listen).
|
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.
|
`Track.volume_adjustment` is still imported and stored but nothing reads it.
|
||||||
|
|
||||||
- **Volume normalization** (Round 83, `loudness.py`, Controls → Normalize
|
- **Volume normalization** (Round 83, `loudness.py`, Controls → Normalize
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
"""LinTunes — iTunes-style music library manager and player for Linux."""
|
"""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
|
"""Boost Volume (Round 131): make a too-quiet MP3 as loud as the rest
|
||||||
the file itself.
|
**without re-encoding it** — the way ``mp3gain`` does.
|
||||||
|
|
||||||
Why in the file: the player can't play louder than the file (Qt's output
|
Why the file and not the player: the player can't play louder than the file
|
||||||
volume stops at 1.0), so neither iTunes' old per-song Volume Adjustment nor
|
(Qt's output volume stops at 1.0), so neither iTunes' old per-song Volume
|
||||||
volume normalization could lift a quiet song while the main volume was up —
|
Adjustment nor volume normalization could lift a quiet song while the main
|
||||||
and turning the laptop up for it blasted the next one. So the song's audio is
|
volume was up.
|
||||||
amplified once, by the ``ffmpeg`` CLI, and saved.
|
|
||||||
|
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
|
How much: up to a *typical* song's loudness (the median of every song the
|
||||||
normalizer has measured, ``LoudnessAnalyzer.typical_lufs``), measured as EBU
|
normalizer has measured, ``LoudnessAnalyzer.typical_lufs``, EBU R128 via
|
||||||
R128 integrated loudness. How much it can take *cleanly* is its true peak's
|
ffmpeg, which only *reads*), but never past ``CEILING_DBTP`` true peak — a
|
||||||
distance from ``CEILING_DBTP``. When the typical level needs more than that,
|
boost never clips. One choice, no options.
|
||||||
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.
|
|
||||||
|
|
||||||
The file keeps its name, format and tags (mutagen copies them and the art,
|
Frames whose side info is CRC-protected would need their CRC redone, so such
|
||||||
as Convert to MP3 does); a lossy one is re-encoded at a high setting (MP3 at
|
a file counts as unsupported. The Xing/Info frame is left alone: its side
|
||||||
V0) so the second generation costs as little as it can. The library swaps
|
info is all zeros anyway, and LAME's tag in it carries a CRC over those bytes.
|
||||||
files through ``LibraryManager.replace_track_files``: the original goes to
|
|
||||||
the trash, Edit ▸ Undo puts it back.
|
|
||||||
|
|
||||||
Shaped like ``loudness.py``: pure parsing and planning first, then the
|
The library swaps files through ``LibraryManager.replace_track_files``
|
||||||
subprocesses, then ``BoostWorker`` on a daemon thread.
|
(in place): the original goes to the trash, Edit ▸ Undo puts it back.
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
import math
|
||||||
import re
|
import re
|
||||||
import subprocess
|
import shutil
|
||||||
import tempfile
|
import tempfile
|
||||||
import threading
|
import threading
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
@@ -40,14 +45,15 @@ from lintunes.importers import lossless
|
|||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
CEILING_DBTP = -1.0 # true-peak headroom a clean boost keeps (lossy decoders overshoot)
|
CEILING_DBTP = -1.0 # true-peak headroom a boost keeps: it never clips
|
||||||
MIN_BOOST_DB = 0.5 # less is inaudible: not worth a re-encode
|
STEP_DB = 1.5 # one global_gain unit
|
||||||
MAX_BOOST_DB = 30.0 # sanity: past this it's a near-silent file, all hiss
|
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")
|
_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]:
|
def parse_measurement(output: str) -> tuple[float | None, float | None]:
|
||||||
"""``(integrated LUFS, true peak dBTP)`` from ffmpeg's ebur128 summary
|
"""``(integrated LUFS, true peak dBTP)`` from ffmpeg's ebur128 summary
|
||||||
(run with ``peak=true``); either is None when absent or silent."""
|
(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."""
|
"""What a boost of one song would do."""
|
||||||
lufs: float | None # how loud it is now
|
lufs: float | None # how loud it is now
|
||||||
peak: float | None # its true peak now, dBTP
|
peak: float | None # its true peak now, dBTP
|
||||||
target_db: float # gain to a typical song's loudness
|
steps: int # global_gain units to add (1.5 dB each)
|
||||||
clean_db: float # the most it can take without clipping
|
reaches_typical: bool # False when the peak stopped it short
|
||||||
|
|
||||||
|
@property
|
||||||
|
def gain_db(self) -> float:
|
||||||
|
return self.steps * STEP_DB
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def measurable(self) -> bool:
|
def measurable(self) -> bool:
|
||||||
return self.lufs is not None and self.peak is not None
|
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:
|
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:
|
if lufs is None or peak is None:
|
||||||
return Plan(lufs, peak, 0.0, 0.0)
|
return Plan(lufs, peak, 0, False)
|
||||||
target = max(0.0, min(MAX_BOOST_DB, typical_lufs - lufs))
|
wanted = typical_lufs - lufs
|
||||||
clean = max(0.0, min(MAX_BOOST_DB, CEILING_DBTP - peak))
|
room = CEILING_DBTP - peak
|
||||||
return Plan(lufs, peak, round(target, 1), round(clean, 1))
|
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]:
|
def measure(path: str) -> tuple[float | None, float | None]:
|
||||||
"""Decode the whole file once through ebur128 with true peak."""
|
"""Decode the whole file once through ebur128 with true peak."""
|
||||||
|
import subprocess
|
||||||
try:
|
try:
|
||||||
result = subprocess.run(
|
result = subprocess.run(
|
||||||
["ffmpeg", "-nostdin", "-nostats", "-hide_banner", "-i", path,
|
["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)
|
return parse_measurement(result.stderr)
|
||||||
|
|
||||||
|
|
||||||
def probe_codec(path: str) -> str | None:
|
# ---- MP3 frames ----
|
||||||
try:
|
|
||||||
result = subprocess.run(
|
class Mp3Error(Exception):
|
||||||
["ffprobe", "-v", "error", "-select_streams", "a:0",
|
"""Not an MP3 whose gain this can change."""
|
||||||
"-show_entries", "stream=codec_name", "-of", "csv=p=0", path],
|
|
||||||
capture_output=True, text=True, timeout=30)
|
|
||||||
except (OSError, subprocess.SubprocessError):
|
_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 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):
|
def _audio_start(data) -> int:
|
||||||
"""Write ``src`` amplified by ``gain_db`` to ``dest`` (same format),
|
"""Past an ID3v2 tag (and its footer), if there is one."""
|
||||||
tags and art copied. Raises OSError on failure; ``src`` is only read."""
|
if data[:3] == b"ID3" and len(data) >= 10:
|
||||||
codec_args = encoder_args(src, probe_codec(str(src)))
|
size = 0
|
||||||
if codec_args is None:
|
for b in data[6:10]:
|
||||||
raise OSError(f"can't rewrite a {src.suffix or 'suffixless'} file")
|
size = (size << 7) | (b & 0x7F)
|
||||||
result = subprocess.run(ffmpeg_command(src, dest, gain_db, codec_args),
|
return 10 + size + (10 if data[5] & 0x10 else 0)
|
||||||
capture_output=True, text=True, errors="replace",
|
return 0
|
||||||
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 _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):
|
class BoostWorker(QObject):
|
||||||
"""Measures songs, then (once told how much) amplifies them, on a daemon
|
"""Measures songs, then (once told how much) writes boosted copies, on
|
||||||
thread. Works from ``(track id, path)`` snapshots, never the library.
|
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.
|
``[(track id, staged file)]`` plus ``[(track id, reason)]`` failures.
|
||||||
The caller removes ``tmp_dir`` when it's done with the staged files."""
|
The caller removes ``tmp_dir`` when it's done with the staged files."""
|
||||||
|
|
||||||
measured = pyqtSignal(dict)
|
measured = pyqtSignal(dict)
|
||||||
progress = pyqtSignal(str)
|
progress = pyqtSignal(str)
|
||||||
amplified = pyqtSignal(list, list)
|
boosted = pyqtSignal(list, list)
|
||||||
|
|
||||||
def __init__(self, items: list[tuple[int, str, str]], typical_lufs: float,
|
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)
|
super().__init__(parent)
|
||||||
self._items = list(items) # (track id, path, display name)
|
self._items = list(items)
|
||||||
self._typical = typical_lufs
|
self._typical = typical_lufs
|
||||||
self._measure = measure_fn or measure
|
self._measure = measure_fn or measure
|
||||||
self._amplify = amplify_fn or amplify
|
|
||||||
self.tmp_dir: Path | None = None
|
self.tmp_dir: Path | None = None
|
||||||
self._busy = False
|
self._busy = False
|
||||||
|
|
||||||
@@ -199,8 +334,8 @@ class BoostWorker(QObject):
|
|||||||
def start_measuring(self):
|
def start_measuring(self):
|
||||||
self._start(self._run_measure)
|
self._start(self._run_measure)
|
||||||
|
|
||||||
def start_amplifying(self, gains: dict[int, float]):
|
def start_boosting(self, steps: dict[int, int]):
|
||||||
self._start(lambda: self._run_amplify(gains))
|
self._start(lambda: self._run_boost(steps))
|
||||||
|
|
||||||
def _start(self, target):
|
def _start(self, target):
|
||||||
self._busy = True
|
self._busy = True
|
||||||
@@ -219,25 +354,25 @@ class BoostWorker(QObject):
|
|||||||
plans[tid] = plan(*self._measure(path), self._typical)
|
plans[tid] = plan(*self._measure(path), self._typical)
|
||||||
self.measured.emit(plans)
|
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 = lossless.staging_root()
|
||||||
root.mkdir(parents=True, exist_ok=True)
|
root.mkdir(parents=True, exist_ok=True)
|
||||||
self.tmp_dir = Path(tempfile.mkdtemp(prefix="boost-", dir=root))
|
self.tmp_dir = Path(tempfile.mkdtemp(prefix="boost-", dir=root))
|
||||||
done, failed = [], []
|
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):
|
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)
|
src = Path(path)
|
||||||
dest = self.tmp_dir / f"{tid}" / src.name
|
dest = self.tmp_dir / f"{tid}" / src.name
|
||||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||||
try:
|
try:
|
||||||
self._amplify(src, dest, gains[tid])
|
boost_file(src, dest, steps[tid])
|
||||||
except Exception as e:
|
except (OSError, Mp3Error) as e:
|
||||||
log.warning("boost: %s: %s", path, e)
|
log.warning("boost: %s: %s", path, e)
|
||||||
failed.append((tid, str(e)))
|
failed.append((tid, str(e)))
|
||||||
continue
|
continue
|
||||||
done.append((tid, dest))
|
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:
|
def _which(self, n: int, name: str, total: int | None = None) -> str:
|
||||||
total = total if total is not None else len(self._items)
|
total = total if total is not None else len(self._items)
|
||||||
|
|||||||
@@ -379,18 +379,23 @@ class InfoDialog(QDialog):
|
|||||||
form.addRow("", self._stop_row)
|
form.addRow("", self._stop_row)
|
||||||
|
|
||||||
# Boost Volume (Round 131) replaced iTunes' Volume Adjustment slider,
|
# Boost Volume (Round 131) replaced iTunes' Volume Adjustment slider,
|
||||||
# which could never play past full volume. It amplifies the file
|
# which could never play past full volume. It raises an MP3's own
|
||||||
# itself, at once, as its own undo step; MainWindow does the work.
|
# gain (no re-encode), at once, as its own undo step; MainWindow
|
||||||
volume_row = QHBoxLayout()
|
# 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 = QPushButton("Boost Volume…")
|
||||||
self._boost_button.setToolTip(
|
self._boost_button.setToolTip(
|
||||||
"Make a quiet song as loud as a typical one by amplifying the "
|
"Make a quiet MP3 about as loud as a typical song, without "
|
||||||
"file itself. Edit ▸ Undo puts the original back.")
|
"re-encoding it or clipping. Edit ▸ Undo puts the original back.")
|
||||||
self._boost_button.setAutoDefault(False)
|
self._boost_button.setAutoDefault(False)
|
||||||
self._boost_button.clicked.connect(self._on_boost)
|
self._boost_button.clicked.connect(self._on_boost)
|
||||||
volume_row.addWidget(self._boost_button)
|
volume_row.addWidget(self._boost_button)
|
||||||
volume_row.addStretch(1)
|
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 = QLabel()
|
||||||
self._file_label.setStyleSheet("color: gray; font-size: 10px;")
|
self._file_label.setStyleSheet("color: gray; font-size: 10px;")
|
||||||
@@ -412,6 +417,7 @@ class InfoDialog(QDialog):
|
|||||||
self._load_multi()
|
self._load_multi()
|
||||||
else:
|
else:
|
||||||
self._load_current()
|
self._load_current()
|
||||||
|
self._show_boost()
|
||||||
|
|
||||||
def _make_time_row(self, title: str):
|
def _make_time_row(self, title: str):
|
||||||
row = QWidget()
|
row = QWidget()
|
||||||
@@ -603,9 +609,20 @@ class InfoDialog(QDialog):
|
|||||||
|
|
||||||
# ---- volume ----
|
# ---- volume ----
|
||||||
|
|
||||||
def _on_boost(self):
|
def _boostable_ids(self) -> list[int]:
|
||||||
|
from lintunes import boost
|
||||||
ids = (list(self._track_ids) if self._multi
|
ids = (list(self._track_ids) if self._multi
|
||||||
else [self._current_track().track_id])
|
else [self._current_track().track_id])
|
||||||
|
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)
|
self.boost_requested.emit(ids)
|
||||||
|
|
||||||
def _on_ok(self):
|
def _on_ok(self):
|
||||||
|
|||||||
+43
-82
@@ -318,7 +318,6 @@ class MainWindow(QMainWindow):
|
|||||||
# Done or Cancel — which can be after its worker has finished.
|
# Done or Cancel — which can be after its worker has finished.
|
||||||
self._compress = None
|
self._compress = None
|
||||||
self._boost = None # boost.BoostWorker while one runs
|
self._boost = None # boost.BoostWorker while one runs
|
||||||
self._boost_typical = 0.0
|
|
||||||
self._compress_reload = QTimer(self)
|
self._compress_reload = QTimer(self)
|
||||||
self._compress_reload.setSingleShot(True)
|
self._compress_reload.setSingleShot(True)
|
||||||
self._compress_reload.setInterval(400)
|
self._compress_reload.setInterval(400)
|
||||||
@@ -391,7 +390,6 @@ class MainWindow(QMainWindow):
|
|||||||
view.table.identify_requested.connect(self._identify_tracks)
|
view.table.identify_requested.connect(self._identify_tracks)
|
||||||
view.table.bpm_requested.connect(self._calculate_bpm)
|
view.table.bpm_requested.connect(self._calculate_bpm)
|
||||||
view.table.convert_requested.connect(self._convert_to_mp3)
|
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.dj_prepare_requested.connect(self._prepare_for_dj)
|
||||||
view.table.remove_from_library_requested.connect(
|
view.table.remove_from_library_requested.connect(
|
||||||
lambda ids: self._delete_tracks(ids, delete_files=False))
|
lambda ids: self._delete_tracks(ids, delete_files=False))
|
||||||
@@ -1911,13 +1909,13 @@ class MainWindow(QMainWindow):
|
|||||||
# ---- Boost Volume (Round 131, lintunes/boost.py) ----
|
# ---- Boost Volume (Round 131, lintunes/boost.py) ----
|
||||||
|
|
||||||
def _boost_volume(self, track_ids: list[int]):
|
def _boost_volume(self, track_ids: list[int]):
|
||||||
"""Right-click or Get Info › Boost Volume…: measure, say what it
|
"""Get Info › Boost Volume…: measure, say what it would do, raise
|
||||||
would do, amplify the files, swap them in as one undo step."""
|
the MP3s' own gain (no re-encode), swap them in as one undo step."""
|
||||||
from lintunes import boost
|
from lintunes import boost
|
||||||
if not lossless.ffmpeg_available():
|
if not lossless.ffmpeg_available():
|
||||||
QMessageBox.warning(
|
QMessageBox.warning(
|
||||||
QApplication.activeWindow() or self, "Boost Volume",
|
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.")
|
"Install your distro's “ffmpeg” package and try again.")
|
||||||
return
|
return
|
||||||
if self._boost is not None:
|
if self._boost is not None:
|
||||||
@@ -1926,9 +1924,9 @@ class MainWindow(QMainWindow):
|
|||||||
return
|
return
|
||||||
tracks = [self._manager.library.tracks[t] for t in track_ids
|
tracks = [self._manager.library.tracks[t] for t in track_ids
|
||||||
if t in self._manager.library.tracks]
|
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:
|
if not tracks:
|
||||||
self.statusBar().showMessage("No song file to boost", 6000)
|
self.statusBar().showMessage("Only MP3s can be boosted", 6000)
|
||||||
return
|
return
|
||||||
analyzer = getattr(self.player, "loudness", None)
|
analyzer = getattr(self.player, "loudness", None)
|
||||||
typical = (analyzer.typical_lufs() if analyzer is not 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)
|
[(t.track_id, t.location, t.name or Path(t.location).stem)
|
||||||
for t in tracks], typical, self)
|
for t in tracks], typical, self)
|
||||||
self._boost = worker
|
self._boost = worker
|
||||||
self._boost_typical = typical
|
|
||||||
worker.progress.connect(lambda text: self.statusBar().showMessage(text))
|
worker.progress.connect(lambda text: self.statusBar().showMessage(text))
|
||||||
worker.measured.connect(self._on_boost_measured)
|
worker.measured.connect(self._on_boost_measured)
|
||||||
worker.amplified.connect(self._on_boost_amplified)
|
worker.boosted.connect(self._on_boosted)
|
||||||
worker.start_measuring()
|
worker.start_measuring()
|
||||||
|
|
||||||
def _boost_end(self, message: str = ""):
|
def _boost_end(self, message: str = ""):
|
||||||
@@ -1953,98 +1950,62 @@ class MainWindow(QMainWindow):
|
|||||||
self.statusBar().clearMessage()
|
self.statusBar().clearMessage()
|
||||||
|
|
||||||
def _on_boost_measured(self, plans: dict):
|
def _on_boost_measured(self, plans: dict):
|
||||||
gains = self._ask_boost(plans)
|
steps = self._ask_boost(plans)
|
||||||
if not gains:
|
if not steps:
|
||||||
self._boost_end()
|
self._boost_end()
|
||||||
return
|
return
|
||||||
self._boost.start_amplifying(gains)
|
self._boost.start_boosting(steps)
|
||||||
|
|
||||||
def _ask_boost(self, plans: dict) -> dict:
|
def _ask_boost(self, plans: dict) -> dict:
|
||||||
"""The warning before anything changes: how many dB, and whether it
|
"""The one question before anything changes: how many dB. Never
|
||||||
clips. ``{track id: gain dB}`` to apply, empty for none."""
|
clips, so there is nothing else to choose. ``{track id: steps}``,
|
||||||
from lintunes import boost
|
empty for no."""
|
||||||
parent = QApplication.activeWindow() or self
|
parent = QApplication.activeWindow() or self
|
||||||
tracks = self._manager.library.tracks
|
tracks = self._manager.library.tracks
|
||||||
name = lambda tid: f"“{tracks[tid].name}”" if tid in tracks else "This song"
|
name = lambda tid: f"“{tracks[tid].name}”" if tid in tracks else "This song"
|
||||||
typical = self._boost_typical
|
todo = {t: p for t, p in plans.items() if p.steps > 0}
|
||||||
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}
|
|
||||||
if not todo:
|
if not todo:
|
||||||
if unmeasurable and not loud:
|
if len(plans) == 1:
|
||||||
text = (f"{name(unmeasurable[0])} couldn't be measured — it "
|
tid, p = next(iter(plans.items()))
|
||||||
"may be silent or unreadable." if len(plans) == 1 else
|
text = (f"{name(tid)} couldn't be measured — it may be silent "
|
||||||
"None of those songs could be measured.")
|
"or unreadable." if not p.measurable else
|
||||||
elif len(plans) == 1:
|
f"{name(tid)} can't get any louder without clipping, "
|
||||||
p = plans[loud[0]]
|
"or is already as loud as a typical song.")
|
||||||
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.")
|
|
||||||
else:
|
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)
|
QMessageBox.information(parent, "Boost Volume", text)
|
||||||
return {}
|
return {}
|
||||||
undo_note = ("The original goes to the trash; Edit ▸ Undo puts it back."
|
if len(todo) == 1:
|
||||||
if len(todo) == 1 else
|
tid, p = next(iter(todo.items()))
|
||||||
"The originals go to the trash; Edit ▸ Undo puts them all back.")
|
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 = QMessageBox(parent)
|
||||||
box.setWindowTitle("Boost Volume")
|
box.setWindowTitle("Boost Volume")
|
||||||
box.setIcon(QMessageBox.Icon.Question)
|
box.setIcon(QMessageBox.Icon.Question)
|
||||||
clipping = {t: p for t, p in todo.items() if p.clips}
|
box.setText(text)
|
||||||
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(
|
box.setInformativeText(
|
||||||
"\n".join(lines[:8]) + ("\n…" if len(lines) > 8 else "")
|
"Nothing is re-encoded: only the MP3's own volume setting "
|
||||||
+ (f"\n\n{skipped} already loud enough or unmeasurable, left as they are."
|
"changes. Edit ▸ Undo puts the original back.")
|
||||||
if skipped else "") + "\n\n" + undo_note)
|
ok = box.addButton("Boost", QMessageBox.ButtonRole.AcceptRole)
|
||||||
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.addButton(QMessageBox.StandardButton.Cancel)
|
box.addButton(QMessageBox.StandardButton.Cancel)
|
||||||
|
box.setDefaultButton(ok)
|
||||||
box.exec()
|
box.exec()
|
||||||
chosen = box.clickedButton()
|
if box.clickedButton() is not ok:
|
||||||
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 {}
|
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:
|
try:
|
||||||
failures = self._manager.replace_track_files(
|
failures = self._manager.replace_track_files(
|
||||||
done, label="Boost Volume", in_place=True)
|
done, label="Boost Volume", in_place=True)
|
||||||
|
|||||||
@@ -800,7 +800,6 @@ class TrackTableView(QTableView):
|
|||||||
identify_requested = pyqtSignal(list) # selected track ids
|
identify_requested = pyqtSignal(list) # selected track ids
|
||||||
bpm_requested = pyqtSignal(list) # selected track ids
|
bpm_requested = pyqtSignal(list) # selected track ids
|
||||||
convert_requested = pyqtSignal(list) # selected track ids (to MP3)
|
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
|
dj_prepare_requested = pyqtSignal(list) # selected track ids
|
||||||
remove_from_library_requested = pyqtSignal(list) # track ids, file kept
|
remove_from_library_requested = pyqtSignal(list) # track ids, file kept
|
||||||
delete_from_library_requested = pyqtSignal(list) # track ids, file trashed
|
delete_from_library_requested = pyqtSignal(list) # track ids, file trashed
|
||||||
@@ -1134,7 +1133,6 @@ class TrackTableView(QTableView):
|
|||||||
locations = self.selected_locations()
|
locations = self.selected_locations()
|
||||||
reveal_action = copy_path_action = download_art_action = None
|
reveal_action = copy_path_action = download_art_action = None
|
||||||
identify_action = bpm_action = dj_action = convert_action = None
|
identify_action = bpm_action = dj_action = convert_action = None
|
||||||
boost_action = None
|
|
||||||
if locations:
|
if locations:
|
||||||
menu.addSeparator()
|
menu.addSeparator()
|
||||||
reveal_action = menu.addAction(
|
reveal_action = menu.addAction(
|
||||||
@@ -1144,9 +1142,6 @@ class TrackTableView(QTableView):
|
|||||||
# Fingerprinting reads the audio, so this needs a file on disk.
|
# Fingerprinting reads the audio, so this needs a file on disk.
|
||||||
identify_action = menu.addAction("Identify Track…")
|
identify_action = menu.addAction("Identify Track…")
|
||||||
bpm_action = menu.addAction("Calculate BPM")
|
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 = menu.addAction("Prepare for DJ")
|
||||||
dj_action.setToolTip("Work out BPM and separate vocals now, so "
|
dj_action.setToolTip("Work out BPM and separate vocals now, so "
|
||||||
"these load instantly onto a deck")
|
"these load instantly onto a deck")
|
||||||
@@ -1210,8 +1205,6 @@ class TrackTableView(QTableView):
|
|||||||
self.identify_requested.emit(self.selected_track_ids())
|
self.identify_requested.emit(self.selected_track_ids())
|
||||||
elif bpm_action is not None and chosen is bpm_action:
|
elif bpm_action is not None and chosen is bpm_action:
|
||||||
self.bpm_requested.emit(self.selected_track_ids())
|
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:
|
elif convert_action is not None and chosen is convert_action:
|
||||||
self.convert_requested.emit(self.selected_track_ids())
|
self.convert_requested.emit(self.selected_track_ids())
|
||||||
elif dj_action is not None and chosen is dj_action:
|
elif dj_action is not None and chosen is dj_action:
|
||||||
|
|||||||
+114
-58
@@ -1,14 +1,9 @@
|
|||||||
"""Round 131: Boost Volume (lintunes/boost.py) replaces the per-track Volume
|
"""Round 131: Boost Volume (lintunes/boost.py) replaces the per-track Volume
|
||||||
Adjustment, which could never play past full volume.
|
Adjustment, which could never play past full volume.
|
||||||
|
|
||||||
1. Measuring: integrated loudness + true peak from ffmpeg's ebur128.
|
It raises an MP3's own global_gain (mp3gain's method): nothing is re-encoded,
|
||||||
2. The plan: up to a typical song's loudness, and how far it can go clean.
|
the decoded audio is the original times exactly 2^(steps/4), and it never
|
||||||
3. Amplifying writes the same format, tags and art kept, the source only read.
|
clips. Only MP3s get the button, in Get Info.
|
||||||
4. The library swaps the file in place as one undo step (original to the
|
|
||||||
trash; undo puts it back at the same path).
|
|
||||||
5. The player reopens the playing song where it was, without a new listen.
|
|
||||||
6. Get Info has a Boost Volume… button and no slider; the right-click menu
|
|
||||||
and the window run the whole thing.
|
|
||||||
"""
|
"""
|
||||||
import shutil
|
import shutil
|
||||||
import subprocess
|
import subprocess
|
||||||
@@ -93,7 +88,7 @@ SUMMARY = """[Parsed_ebur128_0 @ 0x1] Summary:
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
# ---- 1 & 2 ----
|
# ---- measuring and the plan ----
|
||||||
|
|
||||||
class TestMeasureAndPlan:
|
class TestMeasureAndPlan:
|
||||||
def test_parses_loudness_and_true_peak(self):
|
def test_parses_loudness_and_true_peak(self):
|
||||||
@@ -102,54 +97,108 @@ class TestMeasureAndPlan:
|
|||||||
def test_nothing_to_parse(self):
|
def test_nothing_to_parse(self):
|
||||||
assert boost.parse_measurement("garbage") == (None, None)
|
assert boost.parse_measurement("garbage") == (None, None)
|
||||||
|
|
||||||
def test_a_quiet_song_with_room_goes_all_the_way_clean(self):
|
def test_whole_steps_toward_typical(self):
|
||||||
p = boost.plan(-28.7, -18.9, -14.0)
|
p = boost.plan(-28.7, -18.9, -14.0) # wants 14.7, room 17.9
|
||||||
assert p.target_db == 14.7 and not p.clips and p.clean_gain == 14.7
|
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):
|
def test_never_past_the_ceiling(self):
|
||||||
p = boost.plan(-28.7, -18.9, -10.0)
|
p = boost.plan(-28.7, -18.9, -10.0) # wants 18.7, room 17.9
|
||||||
assert p.target_db == 18.7 and p.clips
|
assert p.steps == 11 and p.gain_db <= 17.9 and not p.reaches_typical
|
||||||
assert p.clean_gain == pytest.approx(17.9) # true peak to -1 dBTP
|
|
||||||
|
|
||||||
def test_already_loud_is_not_worth_it(self):
|
def test_nothing_to_do(self):
|
||||||
assert not boost.plan(-9.0, -0.2, -10.0).worth_it
|
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
|
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):
|
# ---- the MP3 gain ----
|
||||||
assert boost.encoder_args(Path("a.mp3"), "mp3")[:2] == ["-c:a", "libmp3lame"]
|
|
||||||
assert boost.encoder_args(Path("a.m4a"), "alac") == ["-c:a", "alac"]
|
def _decode(path):
|
||||||
assert boost.encoder_args(Path("a.m4a"), "aac")[1] == "aac"
|
import numpy as np
|
||||||
assert boost.encoder_args(Path("a.m4p"), "aac") is None
|
out = subprocess.run(["ffmpeg", "-v", "error", "-i", str(path), "-f",
|
||||||
assert boost.encoder_args(Path("a.m4a"), None) is None # protected?
|
"f32le", "-ac", "1", "-"], capture_output=True).stdout
|
||||||
|
return np.frombuffer(out, np.float32)
|
||||||
|
|
||||||
|
|
||||||
# ---- 3 ----
|
@pytest.mark.parametrize("args", [
|
||||||
|
["-ac", "2", "-b:a", "192k"], # MPEG-1 stereo
|
||||||
def test_amplify_reaches_the_target_and_keeps_tags_and_art(tmp_path):
|
["-ac", "1", "-b:a", "96k"], # MPEG-1 mono
|
||||||
src = _quiet_mp3(tmp_path / "in" / "q.mp3")
|
["-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()
|
before = src.read_bytes()
|
||||||
lufs, peak = boost.measure(str(src))
|
dest = tmp_path / "out.mp3"
|
||||||
p = boost.plan(lufs, peak, -14.0)
|
boost.boost_file(src, dest, 4) # +6 dB = exactly x2
|
||||||
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
|
assert src.read_bytes() == before # only read
|
||||||
tags = tagging.read_tags(dest)
|
after = dest.read_bytes()
|
||||||
assert tags["name"] == "Salivate-ish" and tags["artist"] == "Quiet Band"
|
assert len(after) == len(before)
|
||||||
assert tagging.read_embedded_artwork(dest)
|
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):
|
def test_silent_granules_are_left_alone():
|
||||||
odd = tmp_path / "x.wma"
|
"""LAME parks silence at 210/255; those must not count against the
|
||||||
odd.write_bytes(b"x")
|
ceiling, or a quiet song with a silent intro could never be boosted."""
|
||||||
with pytest.raises(OSError):
|
data = bytearray(_frame_stream(gain=150, frames=20))
|
||||||
boost.amplify(odd, tmp_path / "y.wma", 3.0)
|
# 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 ----
|
# ---- 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()
|
original = Path(location).read_bytes()
|
||||||
staged = tmp_path / "cache" / "boosted" / "04 Salivate-ish.mp3"
|
staged = tmp_path / "cache" / "boosted" / "04 Salivate-ish.mp3"
|
||||||
staged.parent.mkdir(parents=True)
|
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",
|
assert manager.replace_track_files([(1, staged)], label="Boost Volume",
|
||||||
in_place=True) == []
|
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()
|
boosted = Path(location).read_bytes()
|
||||||
assert track.location == location and boosted != original
|
assert track.location == location and boosted != original
|
||||||
assert boost.measure(location)[0] > boost.measure(
|
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 track.play_count == 9 and manager.library.playlists["P"].track_ids == [1]
|
||||||
assert not staged.exists()
|
assert not staged.exists()
|
||||||
assert "Boost Volume" in manager.undo_stack.undo_label()
|
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 ----
|
# ---- 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 PyQt6.QtWidgets import QPushButton, QSlider
|
||||||
from lintunes.gui.info_dialog import InfoDialog
|
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 = Library()
|
||||||
library.tracks[1] = Track(track_id=1, name="A")
|
library.tracks[1] = Track(track_id=1, name="A", location=str(mp3))
|
||||||
library.tracks[2] = Track(track_id=2, name="B")
|
library.tracks[2] = Track(track_id=2, name="B", location=str(flac))
|
||||||
manager = LibraryManager(library, tmp_path / "data")
|
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)
|
dialog = InfoDialog(manager, ids)
|
||||||
assert not dialog.findChildren(QSlider)
|
assert not dialog.findChildren(QSlider)
|
||||||
button = next(b for b in dialog.findChildren(QPushButton)
|
assert dialog._form.isRowVisible(dialog._boost_row) == shown
|
||||||
if b.text() == "Boost Volume…")
|
if shown:
|
||||||
asked = []
|
asked = []
|
||||||
dialog.boost_requested.connect(asked.append)
|
dialog.boost_requested.connect(asked.append)
|
||||||
button.click()
|
button(dialog).click()
|
||||||
assert asked == [ids]
|
assert asked == [[1]] # only the MP3
|
||||||
|
|
||||||
|
|
||||||
def test_window_flow_boosts_and_undoes(qapp, tmp_path, fake_trash, monkeypatch):
|
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 = []
|
seen = []
|
||||||
monkeypatch.setattr(window, "_ask_boost",
|
monkeypatch.setattr(window, "_ask_boost",
|
||||||
lambda plans: seen.append(plans) or
|
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:
|
try:
|
||||||
window._boost_volume([1])
|
window._boost_volume([1])
|
||||||
deadline = time.time() + 30
|
deadline = time.time() + 30
|
||||||
@@ -273,7 +329,7 @@ def test_window_flow_boosts_and_undoes(qapp, tmp_path, fake_trash, monkeypatch):
|
|||||||
qapp.processEvents()
|
qapp.processEvents()
|
||||||
time.sleep(0.02)
|
time.sleep(0.02)
|
||||||
assert window._boost is None
|
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
|
assert Path(location).read_bytes() != original
|
||||||
lufs, _ = boost.measure(location)
|
lufs, _ = boost.measure(location)
|
||||||
assert lufs > boost.measure(str(next(fake_trash.iterdir())))[0] + 5
|
assert lufs > boost.measure(str(next(fake_trash.iterdir())))[0] + 5
|
||||||
|
|||||||
Reference in New Issue
Block a user