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

This commit is contained in:
2026-11-19 22:51:16 -08:00
parent f52dd7f567
commit a7d061b200
10 changed files with 783 additions and 196 deletions
+1 -1
View File
@@ -1,3 +1,3 @@
"""LinTunes — iTunes-style music library manager and player for Linux."""
__version__ = "0.98.1"
__version__ = "0.99.0"
+245
View File
@@ -0,0 +1,245 @@
"""Boost Volume (Round 131): make a too-quiet song as loud as the rest, in
the file itself.
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.
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.
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.
Shaped like ``loudness.py``: pure parsing and planning first, then the
subprocesses, then ``BoostWorker`` on a daemon thread.
"""
from __future__ import annotations
import logging
import re
import subprocess
import tempfile
import threading
from dataclasses import dataclass
from pathlib import Path
from PyQt6.QtCore import QObject, pyqtSignal
from lintunes import loudness
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
_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")
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."""
lufs = loudness.parse_ebur128(output)
match = _TRUE_PEAK.search(output)
peak = None
if match and match.group(1) != "-inf":
peak = float(match.group(1))
return lufs, peak
@dataclass
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
@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:
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))
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."""
try:
result = subprocess.run(
["ffmpeg", "-nostdin", "-nostats", "-hide_banner", "-i", path,
"-map", "0:a:0", "-af", "ebur128=peak=true:framelog=quiet",
"-f", "null", "-"],
capture_output=True, text=True, errors="replace", timeout=300)
except (OSError, subprocess.SubprocessError) as exc:
log.info("boost: couldn't measure %s: %s", path, exc)
return None, 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):
return None
return result.stdout.strip() or None
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)
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.
``measured`` carries ``{track id: Plan}``; ``amplified`` 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)
def __init__(self, items: list[tuple[int, str, str]], typical_lufs: float,
parent=None, measure_fn=None, amplify_fn=None):
super().__init__(parent)
self._items = list(items) # (track id, path, display name)
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
def busy(self) -> bool:
return self._busy
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(self, target):
self._busy = True
def run():
try:
target()
finally:
self._busy = False
threading.Thread(target=run, daemon=True).start()
def _run_measure(self):
plans = {}
for n, (tid, path, name) in enumerate(self._items, 1):
self.progress.emit(f"Measuring {self._which(n, name)}")
plans[tid] = plan(*self._measure(path), self._typical)
self.measured.emit(plans)
def _run_amplify(self, gains: dict[int, float]):
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]
for n, (tid, path, name) in enumerate(todo, 1):
self.progress.emit(f"Amplifying {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:
log.warning("boost: %s: %s", path, e)
failed.append((tid, str(e)))
continue
done.append((tid, dest))
self.amplified.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)
name = name if len(name) <= 40 else name[:39] + "…"
return name if total == 1 else f"{n} of {total} · {name}"
+19 -51
View File
@@ -12,7 +12,6 @@ from PyQt6.QtGui import QPixmap, QImage, QKeySequence, QShortcut
from lintunes import tagging
from lintunes.gui.art_ops import embed_artwork
from lintunes.player import VOLUME_ADJUSTMENT_MAX
from lintunes.gui.file_filters import IMAGE_FILTER
from lintunes.gui.track_table import key_hint
@@ -293,12 +292,14 @@ class InfoDialog(QDialog):
"""iTunes-style Get Info: edits library fields and the file's real tags.
Single track: custom start/stop times and the file's path, besides the
fields every mode has (incl. Volume, iTunes' per-song volume adjustment).
Multiple tracks: a combined
fields every mode has. Multiple tracks: a combined
editor where fields shared by every selection are editable and applied to
all, while fields that differ show "Mixed" and are only written if touched.
Boost Volume… acts at once rather than on OK: ``boost_requested``.
"""
boost_requested = pyqtSignal(list) # track ids
def __init__(self, manager, track_ids: list[int], parent=None):
super().__init__(parent)
self._manager = manager
@@ -377,25 +378,18 @@ class InfoDialog(QDialog):
form.addRow("", self._start_row)
form.addRow("", self._stop_row)
# Volume adjustment: iTunes' own (imported as-is), ±255 = ±100%.
# 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()
self._volume = QSlider(Qt.Orientation.Horizontal)
self._volume.setRange(-100, 100)
self._volume.setPageStep(10)
self._volume.setTickPosition(QSlider.TickPosition.TicksBelow)
self._volume.setTickInterval(50)
self._volume.setToolTip(
"Make this song quieter or louder than the rest. A boost can't "
"go past full volume, so it only helps while the main volume "
"isn't all the way up.")
self._volume_label = QLabel()
self._volume_label.setMinimumWidth(QLabel("Mixed").sizeHint().width() + 8)
self._volume.valueChanged.connect(self._on_volume_moved)
volume_row.addWidget(QLabel("−100%"))
volume_row.addWidget(self._volume, stretch=1)
volume_row.addWidget(QLabel("+100%"))
volume_row.addSpacing(6)
volume_row.addWidget(self._volume_label)
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.")
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)
self._file_label = QLabel()
@@ -489,7 +483,6 @@ class InfoDialog(QDialog):
self._stop_time.setEnabled(track.stop_time > 0)
self._stop_time.set_ms(track.stop_time)
self._file_label.setText(track.location or "")
self._set_volume_slider(track.volume_adjustment or 0)
self._loading = False
def _load_multi(self):
@@ -522,9 +515,6 @@ class InfoDialog(QDialog):
self._comments.setPlainText("")
else:
self._comments.setPlainText(comments or "")
volume = self._common_value("volume_adjustment")
self._set_volume_slider(0 if volume is _MIXED else (volume or 0),
mixed=volume is _MIXED)
self._loading = False
def _collect_fields(self) -> dict:
@@ -539,7 +529,6 @@ class InfoDialog(QDialog):
if self._start_check.isChecked() else 0)
fields["stop_time"] = (self._stop_time.ms()
if self._stop_check.isChecked() else 0)
fields["volume_adjustment"] = self._volume_adjustment()
return fields
def _validate_times(self, track) -> str | None:
@@ -591,8 +580,6 @@ class InfoDialog(QDialog):
fields["compilation"] = self._compilation.isChecked()
if "comments" in self._touched:
fields["comments"] = self._comments.toPlainText().strip()
if "volume_adjustment" in self._touched:
fields["volume_adjustment"] = self._volume_adjustment()
if self._staged_art is not None:
tracks = [self._manager.library.tracks[tid]
for tid in self._track_ids]
@@ -616,29 +603,10 @@ class InfoDialog(QDialog):
# ---- volume ----
def _set_volume_slider(self, adjustment: int, mixed: bool = False):
self._volume.setValue(round(100 * adjustment / VOLUME_ADJUSTMENT_MAX))
self._show_volume(mixed)
def _volume_adjustment(self) -> int:
"""The slider in iTunes' unit. A value the slider shows unchanged
keeps its exact stored number (±1 % is 2–3 units)."""
position = self._volume.value()
if not self._multi:
stored = self._current_track().volume_adjustment or 0
if round(100 * stored / VOLUME_ADJUSTMENT_MAX) == position:
return stored
return round(position * VOLUME_ADJUSTMENT_MAX / 100)
def _on_volume_moved(self, _value):
if not self._loading:
self._mark_touched("volume_adjustment")
self._show_volume(mixed=False)
def _show_volume(self, mixed: bool):
value = self._volume.value()
self._volume_label.setText(
"Mixed" if mixed else "None" if value == 0 else f"{value:+d}%")
def _on_boost(self):
ids = (list(self._track_ids) if self._multi
else [self._current_track().track_id])
self.boost_requested.emit(ids)
def _on_ok(self):
saved = self._save_multi() if self._multi else self._save_current()
+163 -2
View File
@@ -1,3 +1,4 @@
import logging
import shutil
import threading
from pathlib import Path
@@ -316,6 +317,8 @@ class MainWindow(QMainWindow):
# A compressing import (gui/compress_import.py), from start until
# 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)
@@ -388,6 +391,7 @@ 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))
@@ -1714,7 +1718,9 @@ class MainWindow(QMainWindow):
def _show_info(self, track_ids: list[int]):
if track_ids:
InfoDialog(self._manager, track_ids, self).exec()
dialog = InfoDialog(self._manager, track_ids, self)
dialog.boost_requested.connect(self._boost_volume)
dialog.exec()
def _info_for_current_view(self):
view = self._content.currentWidget()
@@ -1902,6 +1908,162 @@ class MainWindow(QMainWindow):
if "cancelled" not in message:
sounds.play_done(self._prefs)
# ---- 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."""
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"
"Install your distro's “ffmpeg” package and try again.")
return
if self._boost is not None:
self.statusBar().showMessage(
"Wait for the current boost to finish first", 6000)
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()]
if not tracks:
self.statusBar().showMessage("No song file to boost", 6000)
return
analyzer = getattr(self.player, "loudness", None)
typical = (analyzer.typical_lufs() if analyzer is not None
else loudness.TYPICAL_LUFS)
worker = boost.BoostWorker(
[(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.start_measuring()
def _boost_end(self, message: str = ""):
worker, self._boost = self._boost, None
if worker is not None and worker.tmp_dir is not None:
shutil.rmtree(worker.tmp_dir, ignore_errors=True)
if message:
self.statusBar().showMessage(message, 8000)
else:
self.statusBar().clearMessage()
def _on_boost_measured(self, plans: dict):
gains = self._ask_boost(plans)
if not gains:
self._boost_end()
return
self._boost.start_amplifying(gains)
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
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}
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.")
else:
text = "Those songs are 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.")
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.addButton(QMessageBox.StandardButton.Cancel)
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 {}
def _on_boost_amplified(self, done: list, failed: list):
try:
failures = self._manager.replace_track_files(
done, label="Boost Volume", in_place=True)
except Exception as e: # never leave the boost stuck "running"
logging.getLogger(__name__).exception("Boost Volume failed")
self._boost_end(f"Boost Volume failed: {e}")
return
current = self.player.current_track
if current is not None and any(tid == current.track_id for tid, _ in done):
self.player.reopen_current()
n = len(done) - len(failures)
text = (f"Boosted {n} song{'s' if n != 1 else ''} · Edit ▸ Undo puts "
f"{'it' if n == 1 else 'them'} back" if n else "Nothing was boosted")
problems = len(failed) + len(failures)
if problems:
first = failed[0][1] if failed else failures[0][1]
text += f" · {problems} couldn't be ({first})"
self._boost_end(text)
def _convert_to_mp3(self, track_ids: list[int]):
"""Right-click › Convert to MP3…: shrink lossless songs already in
the library (gui/compress_import.ConvertLibrary)."""
@@ -3386,7 +3548,6 @@ class MainWindow(QMainWindow):
current = self.player.current_track
if current is not None and current.track_id == track_id:
self._sidebar.art.refresh()
self.player.refresh_volume() # its volume adjustment may have moved
def _update_now_playing_icon(self, _playing=None):
track = self.player.current_track
+7
View File
@@ -800,6 +800,7 @@ 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
@@ -1133,6 +1134,7 @@ 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(
@@ -1142,6 +1144,9 @@ 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")
@@ -1205,6 +1210,8 @@ 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:
+28 -8
View File
@@ -1,6 +1,7 @@
import logging
import os
import secrets
import shutil
import unicodedata
from datetime import datetime, timezone
from pathlib import Path
@@ -751,7 +752,9 @@ class LibraryManager(QObject):
_FILE_FIELDS = ("location", "kind", "bit_rate", "sample_rate", "size",
"total_time")
def replace_track_files(self, changes: list[tuple[int, Path]]) -> list:
def replace_track_files(self, changes: list[tuple[int, Path]],
label: str = "Convert to MP3",
in_place: bool = False) -> list:
"""Convert to MP3 (Round 107): each track now plays ``new_path``, a
converted copy of its file, and the old file goes to the desktop
trash. Same track — play counts, playlists and ratings don't move.
@@ -759,8 +762,12 @@ class LibraryManager(QObject):
the source of truth. ONE undoable command for the batch: undo brings
the originals back from the trash and trashes the copies.
``in_place`` (Boost Volume, Round 131): ``new_path`` is a staged
file that takes the original's own path once the original is in the
trash — same name, same format.
Returns ``(name, error)`` per track left as it was (its new file is
trashed again, so nothing is left lying around)."""
trashed again, or left in staging, so nothing is left lying around)."""
records = [] # [track, {"old": fields, "new": fields, "trashed": path}]
failures = []
for track_id, new_path in changes:
@@ -775,7 +782,8 @@ class LibraryManager(QObject):
except Exception as e:
log.warning("Couldn't write tags to %s: %s", new_path, e)
fields = tagging.read_tags(new_path)
new = {"location": str(new_path),
final = Path(track.location) if in_place else new_path
new = {"location": str(final),
**{k: fields[k] for k in self._FILE_FIELDS[1:] if k in fields}}
old = {k: getattr(track, k) for k in new}
try:
@@ -783,11 +791,23 @@ class LibraryManager(QObject):
except trash.TrashError as e:
log.warning("Could not trash %s: %s", track.location, e)
failures.append((track.name or track.location, str(e)))
try:
trash.send_to_trash(new_path)
except trash.TrashError:
pass
if not in_place:
try:
trash.send_to_trash(new_path)
except trash.TrashError:
pass
continue
if in_place:
try:
shutil.move(str(new_path), str(final))
except OSError as e:
log.warning("Could not put %s in place: %s", final, e)
failures.append((track.name or track.location, str(e)))
try:
trash.restore_from_trash(trashed, final)
except trash.TrashError:
log.warning("%s is left in the trash", final)
continue
records.append([track, {"old": old, "new": new, "trashed": trashed,
"trashed_new": None}])
self._apply_track_fields(track_id, new)
@@ -829,7 +849,7 @@ class LibraryManager(QObject):
for track, r in records:
swap(track, r, "old", "new")
self.undo_stack.push(Command("Convert to MP3", undo=undo, redo=redo))
self.undo_stack.push(Command(label, undo=undo, redo=redo))
return failures
def _write_track_tags(self, track, field_map: dict) -> bool:
+18 -26
View File
@@ -70,21 +70,6 @@ def make_shuffle_order(count: int, start_index: int) -> list[int]:
return order
VOLUME_ADJUSTMENT_MAX = 255 # iTunes' unit: ±255 is its slider's ±100%
def volume_with_adjustment(level: float, adjustment: int) -> float:
"""A track's volume adjustment (Get Info → Volume, iTunes' "Volume
Adjustment", imported as-is) applied to the logical 0..1 volume.
It scales the slider's own perceptual level: −100% is silence, +50% is
the slider half again as far up. It can't go past full — no output can —
so a boost only helps while the main volume is below the top, exactly
like iTunes'."""
share = max(-1.0, min(1.0, adjustment / VOLUME_ADJUSTMENT_MAX))
return max(0.0, min(1.0, level * (1.0 + share)))
_LOG100 = math.log(100.0)
@@ -719,18 +704,25 @@ class Player(QObject):
self._volume = max(0.0, min(1.0, float(level)))
self._sink.set_volume(self._output_volume())
def refresh_volume(self):
"""Re-apply the volume — after the playing track's own volume
adjustment was edited."""
self._sink.set_volume(self._output_volume())
def _output_volume(self) -> float:
"""The slider's volume with the playing track's adjustment and the
normalization gain on it."""
return volume_with_gain(volume_with_adjustment(
self._volume,
getattr(self._current_track, "volume_adjustment", 0) or 0),
self._gain_db)
"""The slider's volume with the normalization gain on it. (Round 131
retired iTunes' per-song Volume Adjustment here: a boost could never
pass full volume, so it did nothing with the slider up. Boost Volume
amplifies the file instead, ``boost.py``.)"""
return volume_with_gain(self._volume, self._gain_db)
def reopen_current(self):
"""Load the playing song's file again where it's up to, playing if it
was — after the file under it was replaced (Boost Volume). Not a new
song: no track_changed, the listen carries on."""
track = self._current_track
if track is None or not track.location:
return
position = self._sink.position_ms()
playing = self._sink.is_playing()
self._aim_gain(track, glide=False)
self._sink.set_volume(self._output_volume())
self._sink.load(track, playing, position)
# ---- normalization ----