diff --git a/CLAUDE.md b/CLAUDE.md index a04647d..f51be84 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -139,13 +139,21 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal without recursing. Widgets react to its signals (`playlists_changed`, `playlist_content_changed(pid)`, `track_updated(id)`, `track_fields_edited`). -- **Per-track volume** (Round 79): `Track.volume_adjustment` is iTunes' - "Volume Adjustment", imported as-is (±255 = ±100%) and edited in Get Info. - `player.volume_with_adjustment` scales the slider's *perceptual* level by - it: −100% is silence, and a boost can't pass full. `Player` applies it - through `_output_volume()` everywhere it pushes volume to a sink, before - each load, and on `refresh_volume()` (MainWindow calls that when the - playing track is edited). `Player.volume()` stays the bare slider value. +- **Boost Volume** (Round 131, `boost.py`; Get Info's button and the + right-click menu) replaced Round 79's per-track Volume Adjustment, which + scaled the slider and so could never play past full — with the slider up + it did nothing (normalization has the same ceiling for quiet songs). The + file itself is amplified once: ebur128 measures integrated loudness and + true peak, the target is a *typical* song (`LoudnessAnalyzer.typical_lufs`, + the median measured), the clean limit is the true peak to −1 dBTP; when + typical needs more, the warning offers both (clean, or all the way and + clipping — trav wants iTunes' clipping boost available). ffmpeg rewrites + the same format (MP3 at V0, AAC 320k, lossless as itself), tags and art + copied, staged in `lossless.staging_root()`, then + `replace_track_files(…, in_place=True)` trashes the original and puts the + boosted file at the same path — one undo step. A boost of the playing song + `Player.reopen_current()`s it where it was (no new listen). + `Track.volume_adjustment` is still imported and stored but nothing reads it. - **Volume normalization** (Round 83, `loudness.py`, Controls → Normalize Volume / Preferences → General): each file's EBU R128 integrated loudness diff --git a/lintunes/__init__.py b/lintunes/__init__.py index 3a3ea67..10c7d57 100644 --- a/lintunes/__init__.py +++ b/lintunes/__init__.py @@ -1,3 +1,3 @@ """LinTunes — iTunes-style music library manager and player for Linux.""" -__version__ = "0.98.1" +__version__ = "0.99.0" diff --git a/lintunes/boost.py b/lintunes/boost.py new file mode 100644 index 0000000..d2dc060 --- /dev/null +++ b/lintunes/boost.py @@ -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}" diff --git a/lintunes/gui/info_dialog.py b/lintunes/gui/info_dialog.py index 2dd7c82..dc5216a 100644 --- a/lintunes/gui/info_dialog.py +++ b/lintunes/gui/info_dialog.py @@ -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() diff --git a/lintunes/gui/main_window.py b/lintunes/gui/main_window.py index 3d5cbb0..d6c0e37 100644 --- a/lintunes/gui/main_window.py +++ b/lintunes/gui/main_window.py @@ -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 diff --git a/lintunes/gui/track_table.py b/lintunes/gui/track_table.py index aedbdf1..53715a0 100644 --- a/lintunes/gui/track_table.py +++ b/lintunes/gui/track_table.py @@ -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: diff --git a/lintunes/library_manager.py b/lintunes/library_manager.py index deec820..938d9e6 100644 --- a/lintunes/library_manager.py +++ b/lintunes/library_manager.py @@ -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: diff --git a/lintunes/player.py b/lintunes/player.py index 5fe8d1e..68d80a6 100644 --- a/lintunes/player.py +++ b/lintunes/player.py @@ -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 ---- diff --git a/tests/test_round131.py b/tests/test_round131.py new file mode 100644 index 0000000..ac443ea --- /dev/null +++ b/tests/test_round131.py @@ -0,0 +1,284 @@ +"""Round 131: Boost Volume (lintunes/boost.py) replaces the per-track Volume +Adjustment, which could never play past full volume. + +1. Measuring: integrated loudness + true peak from ffmpeg's ebur128. +2. The plan: up to a typical song's loudness, and how far it can go clean. +3. Amplifying writes the same format, tags and art kept, the source only read. +4. The library swaps the file in place as one undo step (original to the + trash; undo puts it back at the same path). +5. The player reopens the playing song where it was, without a new listen. +6. Get Info has a Boost Volume… button and no slider; the right-click menu + and the window run the whole thing. +""" +import shutil +import subprocess +import time +from pathlib import Path + +import pytest + +from lintunes import boost, tagging +from lintunes.library_manager import LibraryManager +from lintunes.models import Library, Playlist, Track +from lintunes.preferences import Preferences +from tests.test_round29 import _player, _local_track, _FakeSink + + +@pytest.fixture(autouse=True) +def _staging_in_tmp(tmp_path, monkeypatch): + monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path / "cache")) + monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "config")) + + +@pytest.fixture +def fake_trash(tmp_path, monkeypatch): + bin_ = tmp_path / "trash-bin" + bin_.mkdir() + count = iter(range(10**6)) # a name per send, never reused + + def send(path): + path = Path(path) + if not path.exists(): + from lintunes.trash import TrashError + raise TrashError(f"{path} doesn't exist") + dest = bin_ / f"{next(count)}-{path.name}" + shutil.move(str(path), dest) + return dest + + def restore(trashed, original): + Path(original).parent.mkdir(parents=True, exist_ok=True) + shutil.move(str(trashed), str(original)) + monkeypatch.setattr("lintunes.library_manager.trash.send_to_trash", send) + monkeypatch.setattr("lintunes.library_manager.trash.restore_from_trash", + restore) + return bin_ + + +def _quiet_mp3(path: Path, db: float = -20.0, seconds: int = 3) -> Path: + if shutil.which("ffmpeg") is None: + pytest.skip("ffmpeg not available") + path.parent.mkdir(parents=True, exist_ok=True) + subprocess.run(["ffmpeg", "-y", "-f", "lavfi", "-i", + f"sine=f=440:d={seconds},volume={db}dB", "-ac", "2", + "-c:a", "libmp3lame", "-b:a", "128k", str(path)], + capture_output=True, check=True) + tagging.write_tags(path, {"name": "Salivate-ish", "artist": "Quiet Band", + "album": "Hush", "track_number": 4}) + tagging.write_artwork(path, _jpeg(), "image/jpeg") + return path + + +def _jpeg() -> bytes: + from PyQt6.QtCore import QBuffer, QIODevice + from PyQt6.QtGui import QColor, QImage + image = QImage(8, 8, QImage.Format.Format_RGB32) + image.fill(QColor("red")) + buffer = QBuffer() + buffer.open(QIODevice.OpenModeFlag.WriteOnly) + image.save(buffer, "JPG") + return bytes(buffer.data()) + + +SUMMARY = """[Parsed_ebur128_0 @ 0x1] Summary: + + Integrated loudness: + I: -28.7 LUFS + Threshold: -39.0 LUFS + + Loudness range: + LRA: 5.0 LU + + True peak: + Peak: -18.9 dBFS +""" + + +# ---- 1 & 2 ---- + +class TestMeasureAndPlan: + def test_parses_loudness_and_true_peak(self): + assert boost.parse_measurement(SUMMARY) == (-28.7, -18.9) + + def test_nothing_to_parse(self): + assert boost.parse_measurement("garbage") == (None, None) + + def test_a_quiet_song_with_room_goes_all_the_way_clean(self): + p = boost.plan(-28.7, -18.9, -14.0) + assert p.target_db == 14.7 and not p.clips and p.clean_gain == 14.7 + + def test_when_typical_needs_more_than_the_headroom_it_clips(self): + p = boost.plan(-28.7, -18.9, -10.0) + assert p.target_db == 18.7 and p.clips + assert p.clean_gain == pytest.approx(17.9) # true peak to -1 dBTP + + def test_already_loud_is_not_worth_it(self): + assert not boost.plan(-9.0, -0.2, -10.0).worth_it + assert not boost.plan(None, None, -10.0).measurable + + def test_a_near_silent_file_is_capped(self): + assert boost.plan(-70.0 + 15, -50.0, -10.0).target_db == boost.MAX_BOOST_DB + + def test_formats(self): + assert boost.encoder_args(Path("a.mp3"), "mp3")[:2] == ["-c:a", "libmp3lame"] + assert boost.encoder_args(Path("a.m4a"), "alac") == ["-c:a", "alac"] + assert boost.encoder_args(Path("a.m4a"), "aac")[1] == "aac" + assert boost.encoder_args(Path("a.m4p"), "aac") is None + assert boost.encoder_args(Path("a.m4a"), None) is None # protected? + + +# ---- 3 ---- + +def test_amplify_reaches_the_target_and_keeps_tags_and_art(tmp_path): + src = _quiet_mp3(tmp_path / "in" / "q.mp3") + before = src.read_bytes() + lufs, peak = boost.measure(str(src)) + p = boost.plan(lufs, peak, -14.0) + assert not p.clips + dest = tmp_path / "out" / "q.mp3" + dest.parent.mkdir() + boost.amplify(src, dest, p.clean_gain) + after, _ = boost.measure(str(dest)) + assert after == pytest.approx(-14.0, abs=0.5) + assert src.read_bytes() == before # only read + tags = tagging.read_tags(dest) + assert tags["name"] == "Salivate-ish" and tags["artist"] == "Quiet Band" + assert tagging.read_embedded_artwork(dest) + + +def test_amplify_refuses_what_it_cant_rewrite(tmp_path): + odd = tmp_path / "x.wma" + odd.write_bytes(b"x") + with pytest.raises(OSError): + boost.amplify(odd, tmp_path / "y.wma", 3.0) + + +# ---- 4 ---- + +def _library(tmp_path): + path = _quiet_mp3(tmp_path / "media" / "Music" / "Quiet Band" / "Hush" + / "04 Salivate-ish.mp3") + fields = tagging.read_tags(path) + library = Library(music_folder=str(tmp_path / "media")) + library.tracks[1] = Track(track_id=1, name="Salivate-ish", + artist="Quiet Band", album="Hush", + location=str(path), play_count=9, rating=80, + size=fields["size"], kind=fields["kind"], + total_time=fields["total_time"]) + library.playlists["P"] = Playlist(name="Mix", persistent_id="P", + track_ids=[1]) + return LibraryManager(library, tmp_path / "data") + + +def test_in_place_swap_keeps_the_path_and_undoes(qapp, tmp_path, fake_trash): + manager = _library(tmp_path) + location = manager.library.tracks[1].location + original = Path(location).read_bytes() + staged = tmp_path / "cache" / "boosted" / "04 Salivate-ish.mp3" + staged.parent.mkdir(parents=True) + boost.amplify(Path(location), staged, 10.0) + + assert manager.replace_track_files([(1, staged)], label="Boost Volume", + in_place=True) == [] + track = manager.library.tracks[1] + boosted = Path(location).read_bytes() + assert track.location == location and boosted != original + assert boost.measure(location)[0] > boost.measure( + str(next(fake_trash.iterdir())))[0] + 9 + assert track.play_count == 9 and manager.library.playlists["P"].track_ids == [1] + assert not staged.exists() + assert "Boost Volume" in manager.undo_stack.undo_label() + + manager.undo_stack.undo() + assert Path(location).read_bytes() == original + assert manager.library.tracks[1].location == location + manager.undo_stack.redo() + assert Path(location).read_bytes() == boosted + + +def test_a_failed_trash_leaves_the_song_alone(qapp, tmp_path, monkeypatch): + from lintunes.trash import TrashError + manager = _library(tmp_path) + location = manager.library.tracks[1].location + original = Path(location).read_bytes() + staged = tmp_path / "staged.mp3" + staged.write_bytes(original) + + def refuse(_path): + raise TrashError("no trash here") + monkeypatch.setattr("lintunes.library_manager.trash.send_to_trash", refuse) + failures = manager.replace_track_files([(1, staged)], in_place=True) + assert len(failures) == 1 and Path(location).read_bytes() == original + + +# ---- 5 ---- + +def test_reopen_current_keeps_place_and_listen(qapp, tmp_path): + track = _local_track(tmp_path, 1) + player = _player(qapp, [track]) + sink = _FakeSink() + player.set_sink(sink) + player.play_queue([1], 0) + sink._position = 61_000 + changed = [] + player.track_changed.connect(changed.append) + player.reopen_current() + assert sink.loads[-1] == (1, True, 61_000) + assert changed == [] + + +def test_the_player_ignores_the_old_adjustment(qapp, tmp_path): + track = _local_track(tmp_path, 1, volume_adjustment=-255) + player = _player(qapp, [track]) + sink = _FakeSink() + player.set_sink(sink) + player.set_volume(0.6) + player.play_queue([1], 0) + assert sink.volume == pytest.approx(0.6) + + +# ---- 6 ---- + +def test_get_info_has_the_button_not_the_slider(qapp, tmp_path): + from PyQt6.QtWidgets import QPushButton, QSlider + from lintunes.gui.info_dialog import InfoDialog + library = Library() + library.tracks[1] = Track(track_id=1, name="A") + library.tracks[2] = Track(track_id=2, name="B") + manager = LibraryManager(library, tmp_path / "data") + for ids in ([1], [1, 2]): + dialog = InfoDialog(manager, ids) + assert not dialog.findChildren(QSlider) + button = next(b for b in dialog.findChildren(QPushButton) + if b.text() == "Boost Volume…") + asked = [] + dialog.boost_requested.connect(asked.append) + button.click() + assert asked == [ids] + + +def test_window_flow_boosts_and_undoes(qapp, tmp_path, fake_trash, monkeypatch): + from lintunes.gui.main_window import MainWindow + manager = _library(tmp_path) + location = manager.library.tracks[1].location + original = Path(location).read_bytes() + window = MainWindow(manager, Preferences(tmp_path / "data")) + seen = [] + monkeypatch.setattr(window, "_ask_boost", + lambda plans: seen.append(plans) or + {t: p.clean_gain for t, p in plans.items()}) + try: + window._boost_volume([1]) + deadline = time.time() + 30 + while window._boost is not None and time.time() < deadline: + qapp.processEvents() + time.sleep(0.02) + assert window._boost is None + assert seen and seen[0][1].worth_it + assert Path(location).read_bytes() != original + lufs, _ = boost.measure(location) + assert lufs > boost.measure(str(next(fake_trash.iterdir())))[0] + 5 + assert not list((tmp_path / "cache").rglob("boost-*")) # staging gone + manager.undo_stack.undo() + assert Path(location).read_bytes() == original + finally: + window.close() diff --git a/tests/test_round79.py b/tests/test_round79.py index 359d84a..40e4efe 100644 --- a/tests/test_round79.py +++ b/tests/test_round79.py @@ -1,10 +1,9 @@ """Round 79: per-track volume, Get Info tidy-up, Preferences headings, and the laser rig diagram. -1. A track's volume adjustment (iTunes' "Volume Adjustment", already - imported) scales the output while that track plays. -2. Get Info edits it — one track or several — and has no dead - Previous/Next buttons. +1. (Retired in Round 131: the per-track volume adjustment, which could never + play past full volume; Boost Volume amplifies the file instead.) +2. Get Info has no dead Previous/Next buttons. 3. Preferences section headings are bold and 2 px larger than the text. 4. The laser page draws the rig, labelling distance, angles and dot size in place of those sliders' own numbers. @@ -15,62 +14,7 @@ from PyQt6.QtCore import QObject, pyqtSignal from PyQt6.QtGui import QFontInfo from PyQt6.QtWidgets import QApplication, QLabel, QPushButton -from lintunes.player import volume_with_adjustment, VOLUME_ADJUSTMENT_MAX from lintunes.preferences import Preferences -from tests.test_round29 import _player, _local_track, _FakeSink - - -# -------------------------------------------------------------------------- -# 1. The player -# -------------------------------------------------------------------------- - -class TestVolumeAdjustment: - def test_none_changes_nothing(self): - assert volume_with_adjustment(0.6, 0) == 0.6 - - def test_minus_100_is_silence_and_plus_100_doubles(self): - assert volume_with_adjustment(0.6, -VOLUME_ADJUSTMENT_MAX) == 0.0 - assert volume_with_adjustment(0.3, VOLUME_ADJUSTMENT_MAX) == 0.6 - - def test_never_past_full(self): - assert volume_with_adjustment(0.8, VOLUME_ADJUSTMENT_MAX) == 1.0 - - def test_out_of_range_values_are_clamped(self): - assert volume_with_adjustment(0.5, -10_000) == 0.0 - assert volume_with_adjustment(0.5, 10_000) == 1.0 - - def test_applied_when_the_track_loads(self, qapp, tmp_path): - quiet = _local_track(tmp_path, 1, volume_adjustment=-128) - plain = _local_track(tmp_path, 2) - player = _player(qapp, [quiet, plain]) - sink = _FakeSink() - player.set_sink(sink) - player.set_volume(0.8) - player.play_queue([1, 2], 0) - assert sink.volume == pytest.approx(0.8 * (1 - 128 / 255)) - assert player.volume() == 0.8 # the slider is untouched - player.next() - assert sink.volume == pytest.approx(0.8) - - def test_moving_the_slider_keeps_the_adjustment(self, qapp, tmp_path): - track = _local_track(tmp_path, 1, volume_adjustment=255) - player = _player(qapp, [track]) - sink = _FakeSink() - player.set_sink(sink) - player.play_queue([1], 0) - player.set_volume(0.25) - assert sink.volume == pytest.approx(0.5) - - def test_an_edit_while_playing_applies_on_refresh(self, qapp, tmp_path): - track = _local_track(tmp_path, 1) - player = _player(qapp, [track]) - sink = _FakeSink() - player.set_sink(sink) - player.set_volume(0.6) - player.play_queue([1], 0) - track.volume_adjustment = -255 - player.refresh_volume() - assert sink.volume == 0.0 # -------------------------------------------------------------------------- @@ -99,48 +43,6 @@ class TestInfoDialog: texts = {b.text() for b in _info(manager, ids).findChildren(QPushButton)} assert not texts & {"Previous", "Next"} - def test_shows_the_tracks_adjustment(self, qapp, manager): - dialog = _info(manager, [2]) - assert dialog._volume.value() == 20 # 51/255 - assert dialog._volume_label.text() == "+20%" - assert _info(manager, [1])._volume_label.text() == "None" - - def test_saving_one_track(self, qapp, manager): - dialog = _info(manager, [1]) - dialog._volume.setValue(-50) - dialog._on_ok() - assert manager.library.tracks[1].volume_adjustment == -128 - - def test_an_untouched_value_keeps_its_exact_number(self, qapp, manager): - manager.library.tracks[1].volume_adjustment = 37 # an iTunes value - dialog = _info(manager, [1]) - dialog._on_ok() - assert manager.library.tracks[1].volume_adjustment == 37 - - def test_the_edit_is_undoable(self, qapp, manager): - dialog = _info(manager, [1]) - dialog._volume.setValue(100) - dialog._on_ok() - manager.undo_stack.undo() - assert manager.library.tracks[1].volume_adjustment == 0 - - def test_several_tracks_mixed_untouched(self, qapp, manager): - dialog = _info(manager, [1, 2]) - assert dialog._volume_label.text() == "Mixed" - dialog._on_ok() - assert manager.library.tracks[1].volume_adjustment == 0 - assert manager.library.tracks[2].volume_adjustment == 51 - - def test_several_tracks_shared_value(self, qapp, manager): - assert _info(manager, [2, 3])._volume_label.text() == "+20%" - - def test_several_tracks_touched(self, qapp, manager): - dialog = _info(manager, [1, 2]) - dialog._volume.setValue(-100) - dialog._on_ok() - assert manager.library.tracks[1].volume_adjustment == -255 - assert manager.library.tracks[2].volume_adjustment == -255 - # -------------------------------------------------------------------------- # 3 & 4. Preferences