v0.76.0: Convert to MP3 for songs already in the library, and for Cassette arrivals

- right-click › Convert to MP3…: lossless songs become MP3s at a chosen
  bitrate; same tracks (plays, ratings, playlists kept), originals to the
  trash, one undo step brings them back; Cancel changes nothing
- Preferences › Importing › Convert songs from Cassette friends too
- the bitrate list is just the numbers
- conversions stage in ~/.cache, not /tmp
This commit is contained in:
2026-10-23 01:21:52 -07:00
parent 3a3d518092
commit e368b8eb6e
14 changed files with 639 additions and 138 deletions
+12
View File
@@ -615,6 +615,18 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal
batch's playlist inserts use `add_tracks_to_playlist(undoable=False)` —
an undo step left behind would put back ids Cancel removed. A lossless
file already in the library isn't converted again.
**Round 107**: "Convert songs from Cassette friends too"
(`import_compress_cassette`, needs the main box; `lossless.cassette_kbps`
read by `DeliveryCoordinator` each pass) converts a lossless *library*
arrival inside `delivery.run_plans` before staging (followed-playlist
cache files are left as sent). Right-click › **Convert to MP3…**
(`ConvertLibrary`) does songs already in the library: everything is
converted first, *then* each MP3 is moved beside its original and
`LibraryManager.replace_track_files` swaps them as ONE undo step (same
track id, so plays/ratings/playlists stay; library tags written into the
MP3; originals to the trash, undo brings them back) — so its Cancel
changes nothing. Conversions stage in `$XDG_CACHE_HOME/lintunes/
converting/` (`lossless.staging_root`), never /tmp, which is often RAM.
- **`lintunes/fingerprint.py`** — "Identify Track…": Chromaprint's `fpcalc`
CLI (detected with `shutil.which`, the `ffmpeg_available()` pattern — a
+1 -1
View File
@@ -53,7 +53,7 @@ mkdir -p ~/Music/lintunes
python3 -m lintunes.main --data-dir ~/Music/lintunes --save-config
```
Now you can open LinTunes from your app menu like any other app. Now you're running LinTunes! You can drag music in and it'll copy it into the ~/Music/lintunes folder and keep it organize (make sure you have enough ssd space to store your music).
**Now you can open LinTunes from your app menu like any other app**. You can drag music in and it'll copy it into the ~/Music/lintunes folder and keep it organize (make sure you have enough ssd space to store your music).
If you see a little asterix in the bottom-left next to the version number it means there's a software update. Click that number and it'll do the update.
+34 -5
View File
@@ -234,9 +234,30 @@ class DeliveryResult:
errors: list = field(default_factory=list) # (what, error text)
def _stage_compressed(source: Path, music_dir: Path, original: str,
kbps: int, cancel) -> tuple[Path, dict] | None:
"""A lossless arrival converted to MP3 (``importers.lossless``) and
staged under the name it was sent with; None when cancelled. The outbox
copy is only read — it's the friend's to delete."""
import tempfile
from lintunes.importers import lossless
from lintunes.importers.file_importer import stage_file
root = lossless.staging_root()
root.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix="cassette-", dir=root) as tmp:
mp3 = Path(tmp) / (Path(original).stem + ".mp3")
if not lossless.convert(source, mp3, kbps, cancel=cancel):
return None
return stage_file(mp3, music_dir, mp3.name)
def run_plans(send_plans, receive_plans, music_dir: Path | None,
cancel: threading.Event | None = None) -> DeliveryResult:
"""All the file work. Safe off the GUI thread: touches no library."""
cancel: threading.Event | None = None,
compress_kbps: int | None = None) -> DeliveryResult:
"""All the file work. Safe off the GUI thread: touches no library.
With ``compress_kbps``, a lossless song coming into the library is
converted to an MP3 at that bitrate first (Round 107)."""
from lintunes.importers import lossless
from lintunes.importers.file_importer import stage_file
result = DeliveryResult()
for plan in send_plans:
@@ -279,7 +300,14 @@ def run_plans(send_plans, receive_plans, music_dir: Path | None,
tmp.replace(dest)
result.cached.append((plan.token, arrival.track_id))
if arrival.to_library and music_dir is not None:
dest, fields = stage_file(arrival.path, music_dir, original)
staged = None
if compress_kbps and lossless.is_lossless(arrival.path):
staged = _stage_compressed(arrival.path, music_dir,
original, compress_kbps, cancel)
if staged is None:
return result
dest, fields = staged or stage_file(arrival.path, music_dir,
original)
result.staged.append(Staged(plan.token, arrival.track_id,
dest, fields,
Path(original).stem))
@@ -304,7 +332,8 @@ class DeliveryWorker(QObject):
def cancel(self):
self._cancel.set()
def start(self, send_plans, receive_plans, music_dir):
def start(self, send_plans, receive_plans, music_dir,
compress_kbps: int | None = None):
if self._busy:
return False
self._busy = True
@@ -313,7 +342,7 @@ class DeliveryWorker(QObject):
def run():
try:
result = run_plans(send_plans, receive_plans, music_dir,
self._cancel)
self._cancel, compress_kbps)
except Exception as exc: # never die silently
log.exception("cassette delivery")
result = DeliveryResult(errors=[("Delivering songs", str(exc))])
+6 -2
View File
@@ -26,10 +26,13 @@ class DeliveryCoordinator(QObject):
library_grew = pyqtSignal(list) # new track ids
passed = pyqtSignal() # a pass finished (the cache may have moved)
def __init__(self, service, manager, parent=None):
def __init__(self, service, manager, parent=None, compress_kbps=None):
super().__init__(parent)
self._service = service
self._manager = manager
# () -> kbps to convert lossless arrivals to, or None (the
# "from Cassette friends too" preference, read at each pass).
self._compress_kbps = compress_kbps or (lambda: None)
self._worker = delivery.DeliveryWorker(self)
self._worker.finished.connect(self._on_finished)
self._again = False
@@ -102,7 +105,8 @@ class DeliveryCoordinator(QObject):
self._finish_receives(receives, set())
self.passed.emit()
return
self._worker.start(sends, receives, self._manager.organize_root())
self._worker.start(sends, receives, self._manager.organize_root(),
self._compress_kbps())
def _on_finished(self, result, receives):
added = []
+4 -1
View File
@@ -84,7 +84,10 @@ class CassetteUi(QObject):
self._republish_timer.start()
if self._manager is not None:
from lintunes.gui.cassette_delivery import DeliveryCoordinator
self.delivery = DeliveryCoordinator(self.service, self._manager, self)
from lintunes.importers import lossless
self.delivery = DeliveryCoordinator(
self.service, self._manager, self,
compress_kbps=lambda: lossless.cassette_kbps(self._prefs))
self.delivery.notice.connect(self._on_notice)
self.delivery.step_failed.connect(self._on_step_failed)
self.delivery.library_grew.connect(self._on_library_grew)
+158 -6
View File
@@ -32,6 +32,8 @@ IMPORTED = "Imported"
CONVERTED = "Converted and imported"
ALREADY = "Already in your library"
CANCELLED = "Cancelled"
READY = "Converted"
CONVERT_TITLE = "Converting to MP3"
NOT_IMPORTED = "Not imported"
@@ -59,9 +61,10 @@ class CompressProgress(QDialog):
cancel_requested = pyqtSignal()
done_requested = pyqtSignal()
def __init__(self, items, kbps: int, parent=None):
def __init__(self, items, kbps: int, parent=None, title: str = "Importing",
note: str = ""):
super().__init__(parent)
self.setWindowTitle("Importing")
self.setWindowTitle(title)
self.setModal(False)
self.resize(640, 440)
self._finished = False
@@ -98,8 +101,8 @@ class CompressProgress(QDialog):
layout.addWidget(self._tree, 1)
buttons = QHBoxLayout()
self._note = QLabel(f"Lossless files become {kbps} kbps MP3s; "
"the originals aren't touched.")
self._note = QLabel(note or f"Lossless files become {kbps} kbps "
"MP3s; the originals aren't touched.")
self._note.setWordWrap(True)
buttons.addWidget(self._note, 1)
self.cancel_button = QPushButton("Cancel")
@@ -143,9 +146,11 @@ class CompressProgress(QDialog):
def _refresh_summary(self):
statuses = [item.text(2) for item in self._rows]
landed = sum(1 for s in statuses if s in (IMPORTED, CONVERTED, ALREADY))
landed = sum(1 for s in statuses
if s in (IMPORTED, CONVERTED, ALREADY, READY))
failed = sum(1 for s in statuses if s.startswith("Couldn't"))
text = f"{landed} of {len(statuses)} songs imported"
verb = "converted" if self.windowTitle() == CONVERT_TITLE else "imported"
text = f"{landed} of {len(statuses)} songs {verb}"
if failed:
text += f" · {failed} couldn't be"
self._summary.setText(("Done: " if self._finished else "") + text)
@@ -352,3 +357,150 @@ class CompressImport(QObject):
if self.window is not None:
self.window.hide()
shutil.rmtree(self.worker.tmp_dir, ignore_errors=True)
def convertible(tracks) -> list:
"""The tracks Convert to MP3 can do: a lossless file that's on disk."""
return [t for t in tracks if t.location and Path(t.location).is_file()
and lossless.is_lossless(Path(t.location))]
class ConvertLibrary(QObject):
"""Convert to MP3 on songs already in the library (Round 107).
Every song is converted into the staging folder first and nothing in
the library changes until the last one is done; then each MP3 is moved
beside its original and ``LibraryManager.replace_track_files`` swaps
them in one undo step (originals to the trash). So Cancel needs no
undoing: it stops and throws the MP3s away."""
status = pyqtSignal(str, int, int)
worker_finished = pyqtSignal()
over = pyqtSignal(str)
def __init__(self, manager, tracks, kbps: int, parent_widget=None,
worker_factory=None):
super().__init__(parent_widget)
self._manager = manager
self._tracks = list(tracks)
self._kbps = kbps
self._items = [(Path(t.location), True, int(t.total_time or 0))
for t in self._tracks]
self._ready: dict[int, Path] = {}
self._failures: list[str] = []
self._closed = False
factory = worker_factory or lossless.CompressWorker
self.worker = factory(self._items, kbps, self)
self.worker.started.connect(self._on_started)
self.worker.progress.connect(self._on_progress)
self.worker.ready.connect(self._on_ready)
self.worker.failed.connect(self._on_failed)
self.worker.finished.connect(self._on_finished)
self.window = None
if len(self._tracks) > 1:
self.window = CompressProgress(
self._items, kbps, parent_widget, title=CONVERT_TITLE,
note=f"Each song becomes a {kbps} kbps MP3 when all are done; "
"the originals go to the trash. Edit ▸ Undo puts them back.")
for item, track in zip(self.window._rows, self._tracks):
item.setText(0, f"{track.artist} — {track.name}"
if track.artist else track.name)
self.window.cancel_requested.connect(self.request_cancel)
self.window.done_requested.connect(self._close_window)
def start(self):
self.worker.start()
if self.window is not None:
self.window.show()
def show_window(self):
if self.window is not None:
self.window.show()
self.window.raise_()
self.window.activateWindow()
def _label(self, index: int) -> str:
track = self._tracks[index]
return track.name or Path(track.location).name
def _emit_status(self, index: int, percent: int):
total = len(self._items)
name = self._label(index)
name = name if len(name) <= 40 else name[:39] + "…"
if total == 1:
self.status.emit(f"Converting {name}", percent, 100)
else:
self.status.emit(f"Converting {index + 1} of {total} · {name}",
index * 100 + percent, total * 100)
def _on_started(self, index: int):
if self.window is not None:
self.window.started(index, True)
self._emit_status(index, 0)
def _on_progress(self, index: int, percent: int):
if self.window is not None:
self.window.progress(index, percent)
self._emit_status(index, percent)
def _on_ready(self, index: int, path: str, _converted: bool):
self._ready[index] = Path(path)
if self.window is not None:
self.window.set_status(index, READY, 100)
def _on_failed(self, index: int, reason: str):
self._failures.append(f"{self._label(index)}: {reason}")
if self.window is not None:
self.window.set_status(index, f"Couldn't convert: {reason}")
def _on_finished(self, summary: dict):
try:
if self._closed or summary.get("cancelled"):
return
changes, move_failures = [], []
for index, mp3 in sorted(self._ready.items()):
track = self._tracks[index]
original = Path(track.location)
try:
dest = file_importer.unique_path(original.with_suffix(".mp3"))
shutil.move(str(mp3), str(dest))
except OSError as e:
move_failures.append(f"{self._label(index)}: {e}")
continue
changes.append((track.track_id, dest))
failures = self._manager.replace_track_files(changes)
done = len(changes) - len(failures)
text = f"Converted {done} song{'s' if done != 1 else ''} to {self._kbps} kbps MP3"
problems = len(self._failures) + len(move_failures) + len(failures)
if problems:
text += f" · {problems} couldn't be"
for line in self._failures + move_failures:
log.warning("Convert to MP3: %s", line)
if self.window is not None:
self.window.finish(False)
self.window.cancel_button.setEnabled(False)
self._closed = True
self.over.emit(text)
finally:
shutil.rmtree(self.worker.tmp_dir, ignore_errors=True)
self.worker_finished.emit()
def _close_window(self):
if self.window is not None:
self.window.hide()
def request_cancel(self, confirm: bool = True):
"""Nothing has changed yet, so there is nothing to ask about."""
if self._closed:
self._close_window()
return
self._closed = True
self.worker.cancel()
self._close_window()
self.over.emit("Convert to MP3 cancelled — nothing was changed")
def shutdown(self):
self.worker.cancel()
self._closed = True
self._close_window()
shutil.rmtree(self.worker.tmp_dir, ignore_errors=True)
+71 -2
View File
@@ -5,7 +5,8 @@ from pathlib import Path
from PyQt6.QtWidgets import (
QMainWindow, QSplitter, QStackedWidget, QWidget, QVBoxLayout, QLineEdit,
QPlainTextEdit, QTextEdit, QAbstractSpinBox, QComboBox, QApplication,
QLabel, QMessageBox, QFileDialog, QProgressBar, QPushButton,
QLabel, QMessageBox, QFileDialog, QProgressBar, QPushButton, QDialog,
QDialogButtonBox, QHBoxLayout,
)
from PyQt6.QtCore import QRect, Qt, QEvent, QObject, QTimer, pyqtSignal
from PyQt6.QtGui import QAction, QKeySequence
@@ -333,6 +334,7 @@ class MainWindow(QMainWindow):
view.table.download_art_requested.connect(self._download_album_art)
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.dj_prepare_requested.connect(self._prepare_for_dj)
view.table.remove_from_library_requested.connect(
lambda ids: self._delete_tracks(ids, delete_files=False))
@@ -1696,9 +1698,76 @@ class MainWindow(QMainWindow):
self._compress_reload.stop()
self._library_view_reload()
self.statusBar().showMessage(message, 8000)
if not message.startswith("Import cancelled"):
if "cancelled" not in message:
sounds.play_done(self._prefs)
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)."""
from lintunes.gui import compress_import
if not lossless.ffmpeg_available():
QMessageBox.warning(
self, "Convert to MP3",
"Converting needs ffmpeg, which is not installed.\n\n"
"Install your distro's “ffmpeg” package and try again.")
return
if self._busy_worker() is not None or self._compress is not None:
self.statusBar().showMessage(
"Wait for the current import or transfer to finish first", 6000)
return
tracks = [self._manager.library.tracks[t] for t in track_ids
if t in self._manager.library.tracks]
tracks = compress_import.convertible(tracks)
if not tracks:
self.statusBar().showMessage(
"None of those songs are lossless — nothing to convert", 6000)
return
kbps = self._ask_convert_kbps(tracks)
if kbps is None:
return
batch = compress_import.ConvertLibrary(self._manager, tracks, kbps, self)
batch.status.connect(self._on_compress_status)
batch.worker_finished.connect(self._free_sync_widgets)
batch.over.connect(self._on_compress_over)
self._compress = batch
self._sync_label.setText("Converting…")
self._sync_progress.setRange(0, 100)
self._sync_progress.setValue(0)
for widget in (self._sync_label, self._sync_progress, self._sync_cancel):
widget.show()
batch.start()
def _ask_convert_kbps(self, tracks) -> int | None:
"""Confirm, and at what bitrate (starting at Preferences' one)."""
n = len(tracks)
dialog = QDialog(self)
dialog.setWindowTitle("Convert to MP3")
layout = QVBoxLayout(dialog)
what = (f"“{tracks[0].name}”" if n == 1 else f"{n} lossless songs")
text = QLabel(f"Convert {what} to MP3? Play counts, ratings and "
"playlists stay as they are. The original files go to "
"the trash, and Edit ▸ Undo brings them back.")
text.setWordWrap(True)
layout.addWidget(text)
row = QHBoxLayout()
row.addWidget(QLabel("Bitrate:"))
combo = QComboBox()
for rate in lossless.BITRATES:
combo.addItem(f"{rate} kbps", rate)
combo.setCurrentIndex(lossless.BITRATES.index(lossless.settings(self._prefs)[1]))
row.addWidget(combo)
row.addStretch(1)
layout.addLayout(row)
buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Cancel)
buttons.addButton("Convert", QDialogButtonBox.ButtonRole.AcceptRole)
buttons.accepted.connect(dialog.accept)
buttons.rejected.connect(dialog.reject)
layout.addWidget(buttons)
dialog.resize(420, dialog.sizeHint().height())
if dialog.exec() != QDialog.DialogCode.Accepted:
return None
return combo.currentData()
def _free_sync_widgets(self):
"""Hide the status-bar progress unless another transfer took it."""
if self._busy_worker() is None:
+15 -3
View File
@@ -256,10 +256,18 @@ class PreferencesDialog(QDialog):
self._compress_check.setChecked(on)
self._compress_kbps = QComboBox()
for rate in lossless.BITRATES:
note = {320: " (best)", 256: " (recommended)", 128: " (smallest)"}
self._compress_kbps.addItem(f"{rate} kbps{note.get(rate, '')}", rate)
self._compress_kbps.addItem(f"{rate} kbps", rate)
self._compress_kbps.setCurrentIndex(lossless.BITRATES.index(kbps))
self._compress_kbps.setEnabled(on)
self._compress_cassette = QCheckBox("Convert songs from Cassette friends too")
self._compress_cassette.setToolTip(
"Lossless songs a friend sends you are converted before they go "
"in your library. Songs from playlists you follow aren't.")
self._compress_cassette.setChecked(
bool(self._prefs.get("import_compress_cassette", False)))
self._compress_cassette.setEnabled(on)
self._compress_cassette.toggled.connect(
lambda checked: self._prefs.set("import_compress_cassette", checked))
self._compress_check.toggled.connect(self._on_compress_toggled)
self._compress_kbps.currentIndexChanged.connect(
lambda _i: self._prefs.set("import_compress_kbps",
@@ -268,19 +276,23 @@ class PreferencesDialog(QDialog):
row.addWidget(self._compress_kbps)
row.addStretch(1)
column.addLayout(row)
column.addWidget(self._compress_cassette)
if lossless.ffmpeg_available():
note = ("FLAC, WAV, AIFF and Apple Lossless files you add are "
"converted, and the MP3 goes in your library — a fraction "
"of the size. The file you added from isn't changed or "
"moved. Songs already in your library are left as they are.")
"moved. To shrink songs already in your library, "
"right-click them and choose Convert to MP3.")
else:
note = "Needs ffmpeg, which isn't installed."
self._compress_check.setEnabled(False)
self._compress_cassette.setEnabled(False)
column.addWidget(self._note(note))
return group
def _on_compress_toggled(self, on: bool):
self._compress_kbps.setEnabled(on)
self._compress_cassette.setEnabled(on)
self._prefs.set("import_compress", on)
def _build_sound_group(self) -> QGroupBox:
+15 -1
View File
@@ -18,8 +18,14 @@ from PyQt6.QtDBus import (
QDBusConnection, QDBusInterface, QDBusMessage, QDBusArgument,
)
from pathlib import Path
from lintunes.models import Track
from lintunes.gui import drag_ghost
from lintunes.importers.lossless import LOSSLESS_SUFFIXES
# Suffixes that offer Convert to MP3 (an .m4a may be Apple Lossless).
LOSSLESS_MENU_SUFFIXES = LOSSLESS_SUFFIXES | {".m4a"}
TRACKS_MIME = "application/x-lintunes-tracks"
@@ -714,6 +720,7 @@ class TrackTableView(QTableView):
download_art_requested = pyqtSignal(list) # selected track ids
identify_requested = pyqtSignal(list) # selected track ids
bpm_requested = pyqtSignal(list) # selected track ids
convert_requested = pyqtSignal(list) # selected track ids (to MP3)
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
@@ -1046,7 +1053,7 @@ class TrackTableView(QTableView):
locations = self.selected_locations()
reveal_action = copy_path_action = download_art_action = None
identify_action = bpm_action = dj_action = None
identify_action = bpm_action = dj_action = convert_action = None
if locations:
menu.addSeparator()
reveal_action = menu.addAction("Reveal in File Browser")
@@ -1058,6 +1065,11 @@ class TrackTableView(QTableView):
dj_action = menu.addAction("Prepare for DJ")
dj_action.setToolTip("Work out BPM and separate vocals now, so "
"these load instantly onto a deck")
# By suffix only (opening every file would slow the menu); an
# .m4a may turn out to be plain AAC, which the action reports.
if any(Path(loc).suffix.lower() in LOSSLESS_MENU_SUFFIXES
for loc in locations):
convert_action = menu.addAction("Convert to MP3…")
# Single track only: one click shouldn't open a browser tab per song.
# Needs no file, so it's offered for a dangling location too.
@@ -1113,6 +1125,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 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:
self.dj_prepare_requested.emit(self.selected_track_ids())
elif youtube_action is not None and chosen is youtube_action:
+18 -1
View File
@@ -20,6 +20,7 @@ unevenly, and the art must arrive as an ID3 front cover.
from __future__ import annotations
import logging
import os
import shutil
import subprocess
import tempfile
@@ -37,6 +38,13 @@ DEFAULT_BITRATE = 256
LOSSLESS_SUFFIXES = {".flac", ".wav", ".aiff", ".aif"}
def staging_root() -> Path:
"""Where conversions are written before they're filed: the cache, on
disk — /tmp is often RAM, and a batch of songs can be gigabytes."""
base = os.environ.get("XDG_CACHE_HOME") or str(Path.home() / ".cache")
return Path(base) / "lintunes" / "converting"
def ffmpeg_available() -> bool:
return shutil.which("ffmpeg") is not None
@@ -49,6 +57,13 @@ def settings(prefs) -> tuple[bool, int]:
return on, kbps if kbps in BITRATES else DEFAULT_BITRATE
def cassette_kbps(prefs) -> int | None:
"""The bitrate songs arriving from Cassette friends are converted to, or
None to keep them as sent. Needs the main setting on as well."""
on, kbps = settings(prefs)
return kbps if on and prefs.get("import_compress_cassette", False) else None
def is_lossless(path: Path) -> bool:
"""FLAC/WAV/AIFF by suffix; an .m4a only when it holds Apple Lossless
(the same container holds plain AAC, which must be left alone)."""
@@ -177,7 +192,9 @@ class CompressWorker(QObject):
self._convert = convert_fn or convert
self._busy = False
self._cancel = threading.Event()
self.tmp_dir = Path(tempfile.mkdtemp(prefix="lintunes-compress-"))
root = staging_root()
root.mkdir(parents=True, exist_ok=True)
self.tmp_dir = Path(tempfile.mkdtemp(prefix="batch-", dir=root))
def busy(self) -> bool:
return self._busy
+84
View File
@@ -688,6 +688,90 @@ class LibraryManager(QObject):
redo=lambda: [self._revert_track_fields(tid, new)
for tid, new, _old in changes]))
_FILE_FIELDS = ("location", "kind", "bit_rate", "sample_rate", "size",
"total_time")
def replace_track_files(self, changes: list[tuple[int, Path]]) -> 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.
The library's own tags are written into the new file, since it is
the source of truth. ONE undoable command for the batch: undo brings
the originals back from the trash and trashes the copies.
Returns ``(name, error)`` per track left as it was (its new file is
trashed again, so nothing is left lying around)."""
records = [] # [track, {"old": fields, "new": fields, "trashed": path}]
failures = []
for track_id, new_path in changes:
track = self.library.tracks.get(track_id)
if track is None or not track.location:
continue
new_path = Path(new_path)
writable = {k: getattr(track, k) for k in tagging.EDITABLE_FIELDS
if hasattr(track, k)}
try:
tagging.write_tags(new_path, writable)
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),
**{k: fields[k] for k in self._FILE_FIELDS[1:] if k in fields}}
old = {k: getattr(track, k) for k in new}
try:
trashed = trash.send_to_trash(Path(track.location))
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
continue
records.append([track, {"old": old, "new": new, "trashed": trashed,
"trashed_new": None}])
self._apply_track_fields(track_id, new)
if not records:
return failures
def swap(track, r, put_away: str, bring_back: str) -> bool:
"""Trash the file the track plays now (``put_away`` side) and
restore the other one; on failure, leave both as they were."""
here = Path(r[put_away]["location"])
stash = "trashed" if bring_back == "old" else "trashed_new"
other = "trashed_new" if stash == "trashed" else "trashed"
if r[stash] is None:
return False
try:
r[other] = trash.send_to_trash(here)
except trash.TrashError as e:
self.file_move_failed.emit(track.name or "", str(e))
return False
try:
trash.restore_from_trash(r[stash], Path(r[bring_back]["location"]))
except trash.TrashError as e:
self.file_move_failed.emit(track.name or "", str(e))
try:
trash.restore_from_trash(r[other], here)
except trash.TrashError:
log.warning("%s is left in the trash", here)
r[other] = None
return False
r[stash] = None
self._apply_track_fields(track.track_id, r[bring_back])
return True
def undo():
for track, r in records:
swap(track, r, "new", "old")
def redo():
for track, r in records:
swap(track, r, "old", "new")
self.undo_stack.push(Command("Convert to MP3", undo=undo, redo=redo))
return failures
def _write_track_tags(self, track, field_map: dict) -> bool:
# Library-only fields (rating, size, start/stop times) have no tag
# representation; don't rewrite the audio file for them.
+1
View File
@@ -88,6 +88,7 @@ DEFAULTS = {
# (importers/lossless.py). The original file is never touched.
"import_compress": False,
"import_compress_kbps": 256,
"import_compress_cassette": False, # ...songs from Cassette friends too
# The quiet "tink" when a sync, export or URL import finishes.
"sound_effects": True,
# The yearly Wrapped (storage/listen_history.py). Synced on purpose: one
+6
View File
@@ -16,6 +16,12 @@ from lintunes.preferences import Preferences
from tests.conftest import _generate_audio
@pytest.fixture(autouse=True)
def _staging_in_tmp(tmp_path, monkeypatch):
"""Conversions stage under $XDG_CACHE_HOME — never the real one."""
monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path / "cache"))
@pytest.fixture
def isolated_config(tmp_path, monkeypatch):
monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "config"))
+214 -116
View File
@@ -1,123 +1,221 @@
"""Round 107: opening DJ mode with both decks empty doesn't stop the song —
Deck A loads it and takes over without a gap, and closing DJ mode goes back
to where the main player left off."""
"""Round 107: no quality labels on the bitrates, "Convert songs from Cassette
friends too", and right-click › Convert to MP3… on songs already in the
library."""
import shutil
from pathlib import Path
import pytest
from lintunes.dj import analysis, stems
from lintunes.dj.audio import RATE, Source
from lintunes.player import Player
from tests.test_round93 import _tone
from lintunes import tagging
from lintunes.importers import lossless
from lintunes.library_manager import LibraryManager
from lintunes.models import Library, Playlist, Track
from lintunes.preferences import Preferences
from tests.test_round106 import _digest, _tagged_flac, _wait
@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 window(qapp, tmp_path, monkeypatch):
from lintunes.gui import dj_shelf
def fake_trash(tmp_path, monkeypatch):
"""send/restore that never reach the real desktop trash."""
bin_ = tmp_path / "trash-bin"
bin_.mkdir()
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"{len(list(bin_.iterdir()))}-{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 _library_with_flacs(tmp_path, names):
music = tmp_path / "media" / "Music" / "Nissa" / "Big Files"
music.mkdir(parents=True)
library = Library(music_folder=str(tmp_path / "media"))
for tid, name in enumerate(names, start=1):
path = _tagged_flac(music / f"{tid:02d} {name}.flac", name, seconds=2)
fields = tagging.read_tags(path)
library.tracks[tid] = Track(
track_id=tid, name=name, artist="Nissa", album="Big Files",
location=str(path), kind=fields["kind"], play_count=7 * tid,
rating=80, total_time=fields["total_time"], size=fields["size"])
library.playlists["P"] = Playlist(name="Mix", persistent_id="P",
track_ids=list(library.tracks))
return LibraryManager(library, tmp_path / "data")
# ---- the setting ----
def test_bitrates_are_just_numbers(qapp, tmp_path):
from unittest.mock import MagicMock
from lintunes.gui.preferences_dialog import PreferencesDialog
dialog = PreferencesDialog(Preferences(tmp_path / "data"), MagicMock())
labels = [dialog._compress_kbps.itemText(i)
for i in range(dialog._compress_kbps.count())]
assert labels == ["320 kbps", "256 kbps", "192 kbps", "160 kbps", "128 kbps"]
def test_cassette_setting_needs_the_main_one(qapp, tmp_path):
from unittest.mock import MagicMock
from lintunes.gui.preferences_dialog import PreferencesDialog
prefs = Preferences(tmp_path / "data")
assert lossless.cassette_kbps(prefs) is None
dialog = PreferencesDialog(prefs, MagicMock())
assert not dialog._compress_cassette.isEnabled()
dialog._compress_check.setChecked(True)
assert dialog._compress_cassette.isEnabled()
assert lossless.cassette_kbps(prefs) is None # off by default
dialog._compress_cassette.setChecked(True)
assert lossless.cassette_kbps(prefs) == 256
dialog._compress_check.setChecked(False)
assert lossless.cassette_kbps(prefs) is None
assert not dialog._compress_cassette.isEnabled()
def test_a_lossless_cassette_arrival_is_converted(tmp_path, mp3_file):
from lintunes.cassette import delivery
outbox = tmp_path / "outbox"
outbox.mkdir()
flac = _tagged_flac(outbox / "7 ~ Huge.flac", "Huge")
sent = _digest(flac)
mp3 = shutil.copy(mp3_file, outbox / "8 ~ Small.mp3")
plan = delivery.ReceivePlan(token="t", arrivals=[
delivery.Arrival(7, flac, True, False),
delivery.Arrival(8, Path(mp3), True, False)])
music = tmp_path / "Music"
result = delivery.run_plans([], [plan], music, compress_kbps=160)
assert result.errors == []
huge, small = result.staged
assert huge.dest.name == "Huge.mp3" and huge.dest.parent.parent.name == "Nissa"
assert huge.fields["kind"] == "MPEG audio file"
assert 150 <= huge.fields["bit_rate"] <= 170
assert small.dest.name == "Small.mp3"
assert _digest(flac) == sent # the friend's copy is only read
assert not any(lossless.staging_root().iterdir())
# Off: as sent.
result = delivery.run_plans([], [plan], tmp_path / "Music2")
assert result.staged[0].dest.suffix == ".flac"
def test_the_coordinator_reads_the_setting_each_pass(qapp, tmp_path):
from unittest.mock import MagicMock
from lintunes.gui.cassette_delivery import DeliveryCoordinator
kbps = [None]
service = MagicMock()
coordinator = DeliveryCoordinator(service, MagicMock(),
compress_kbps=lambda: kbps[0])
coordinator._worker = MagicMock()
coordinator._worker.busy.return_value = False
from lintunes.cassette import delivery
plan = delivery.ReceivePlan(token="t", arrivals=[MagicMock()])
with pytest.MonkeyPatch.context() as mp:
mp.setattr(delivery, "plan_send", lambda *a: delivery.SendPlan(
token="t", outbox=tmp_path))
mp.setattr(delivery, "plan_receive", lambda *a, **k: plan)
service.state.return_value.friends = {"t": MagicMock()}
service.root = tmp_path
kbps[0] = 192
coordinator.run()
assert coordinator._worker.start.call_args.args[3] == 192
# ---- Convert to MP3 on library songs ----
def test_only_lossless_songs_are_convertible(tmp_path, mp3_file, m4a_file):
from lintunes.gui.compress_import import convertible
flac = _tagged_flac(tmp_path / "a.flac", "A")
tracks = [Track(track_id=i, location=str(p)) for i, p in
enumerate([flac, mp3_file, m4a_file, tmp_path / "gone.flac"])]
assert [t.track_id for t in convertible(tracks)] == [0]
def test_convert_swaps_files_keeps_the_track_and_undoes(qapp, tmp_path, fake_trash):
from lintunes.gui.compress_import import ConvertLibrary
manager = _library_with_flacs(tmp_path, ["Alpha", "Bravo"])
originals = {tid: (Path(t.location), _digest(Path(t.location)))
for tid, t in manager.library.tracks.items()}
batch = ConvertLibrary(manager, list(manager.library.tracks.values()), 128)
assert batch.window is not None
over = []
batch.over.connect(over.append)
batch.start()
_wait(qapp, batch)
assert over == ["Converted 2 songs to 128 kbps MP3"]
for tid, (flac, digest) in originals.items():
track = manager.library.tracks[tid]
assert track.location == str(flac.with_suffix(".mp3"))
assert Path(track.location).is_file() and not flac.exists()
assert track.kind == "MPEG audio file" and track.bit_rate <= 136
assert track.play_count == 7 * tid and track.rating == 80
assert tagging.read_tags(track.location)["name"] == track.name
assert manager.library.playlists["P"].track_ids == [1, 2]
assert len(list(fake_trash.iterdir())) == 2
assert not any(lossless.staging_root().iterdir())
manager.undo_stack.undo() # one step for the batch
for tid, (flac, digest) in originals.items():
track = manager.library.tracks[tid]
assert track.location == str(flac) and _digest(flac) == digest
assert track.kind == "FLAC audio file"
assert not flac.with_suffix(".mp3").exists()
manager.undo_stack.redo()
assert all(t.location.endswith(".mp3") and Path(t.location).is_file()
for t in manager.library.tracks.values())
def test_cancel_changes_nothing(qapp, tmp_path, fake_trash):
from lintunes.gui.compress_import import ConvertLibrary
manager = _library_with_flacs(tmp_path, ["Alpha", "Bravo"])
before = {t: tr.location for t, tr in manager.library.tracks.items()}
batch = ConvertLibrary(manager, list(manager.library.tracks.values()), 128)
over = []
batch.over.connect(over.append)
batch.start()
batch.request_cancel()
_wait(qapp, batch)
assert {t: tr.location for t, tr in manager.library.tracks.items()} == before
assert all(Path(p).exists() for p in before.values())
assert list(fake_trash.iterdir()) == []
assert not manager.undo_stack.can_undo()
assert over == ["Convert to MP3 cancelled — nothing was changed"]
assert not any(lossless.staging_root().iterdir())
def test_window_right_click_flow(qapp, tmp_path, fake_trash, monkeypatch):
from lintunes.gui.main_window import MainWindow
from lintunes.library_manager import LibraryManager
from lintunes.models import Track
from lintunes.models.library import Library
from lintunes.preferences import Preferences
monkeypatch.setattr("lintunes.gui.main_window.load_config", lambda: {})
monkeypatch.setattr("lintunes.gui.main_window.save_config", lambda c: None)
monkeypatch.setattr(dj_shelf.DeckLoader, "request", lambda *a, **k: None)
monkeypatch.setattr(stems, "available", lambda: False)
monkeypatch.setattr(dj_shelf.tagging, "read_embedded_artwork", lambda p: None)
library = Library()
for tid in (1, 2):
library.tracks[tid] = Track(track_id=tid, name=f"Song {tid}", artist="Test",
location=f"/x{tid}.mp3", bpm=120)
made = MainWindow(LibraryManager(library, tmp_path), Preferences(tmp_path))
# A main player "playing" song 1, 42 s in.
state = {"track": library.tracks[1], "playing": True, "ms": 42_000, "seeks": []}
monkeypatch.setattr(Player, "current_track", property(lambda self: state["track"]))
player = made.player
player.is_playing = lambda: state["playing"]
player.position_ms = lambda: state["ms"]
player.pause = lambda: state.update(playing=False)
player.play = lambda: state.update(playing=True)
player.seek = lambda ms: state["seeks"].append(ms)
made.state = state
made.library = library
yield made
made.close()
def _finish_loading(window, track):
from lintunes.dj.loader import Loaded
samples = _tone(seconds=60.0)
window._dj._on_loader_result("A", Loaded(
track_id=track.track_id, source=Source(samples),
peaks=analysis.peaks(samples, RATE), bpm=120.0, offset=0.0, detected=False))
def _close(window, qapp):
window.set_dj_mode(False)
window._dj_anim.stop()
window._dj_closed()
def test_empty_decks_take_the_playing_song_over(window, qapp):
state = window.state
window.set_dj_mode(True)
shelf = window._dj
a = shelf.views[0]
assert state["playing"], "the song keeps playing while Deck A loads"
assert window.player.suspended
assert a.track is state["track"]
assert shelf.crossfader.value() == 0 # Deck A alone
_finish_loading(window, state["track"])
assert a.deck.playing
assert a.deck.position / RATE == pytest.approx(42.0 + shelf.latency_ms() / 1000, abs=0.01)
qapp.processEvents() # the latency passes
assert not state["playing"]
assert window._dj_pin == (1, 42_000, True)
_close(window, qapp)
assert state["seeks"] == [42_000] and state["playing"]
assert window._dj_pin is None
def test_a_paused_song_is_cued_and_stays_paused(window, qapp):
state = window.state
state["playing"] = False
window.set_dj_mode(True)
a = window._dj.views[0]
_finish_loading(window, state["track"])
assert not a.deck.playing
assert a.deck.position / RATE == pytest.approx(42.0, abs=0.01)
_close(window, qapp)
assert not state["playing"]
def test_closing_before_the_deck_loads_leaves_the_song_playing(window, qapp):
state = window.state
window.set_dj_mode(True)
_close(window, qapp)
assert state["playing"] and not window.player.suspended
assert window._dj.views[0].handoff is None
assert window._dj_pin is None
def test_a_loaded_deck_means_the_song_just_stops(window, qapp):
state = window.state
window.set_dj_mode(True)
_finish_loading(window, state["track"])
qapp.processEvents()
_close(window, qapp)
window._dj.load(window._dj.views[1], window.library.tracks[2])
window._dj.views[0].track = None # only Deck B holds something now
state["playing"] = True
window.set_dj_mode(True)
assert not state["playing"]
assert window._dj.views[0].track is None # nothing loaded for it
_close(window, qapp)
assert not state["playing"]
def test_a_failed_load_stops_the_song(window, qapp):
state = window.state
window.set_dj_mode(True)
window._dj._on_loader_failed("A", 1, "no decoder")
assert not state["playing"]
_close(window, qapp)
assert not state["playing"]
manager = _library_with_flacs(tmp_path, ["Alpha"])
window = MainWindow(manager, Preferences(tmp_path / "data"))
asked = []
monkeypatch.setattr(window, "_ask_convert_kbps",
lambda tracks: asked.append(len(tracks)) or 192)
try:
window._convert_to_mp3([1])
assert asked == [1]
batch = window._compress
assert batch is not None and batch.window is None # one song
assert window._sync_label.isVisibleTo(window)
_wait(qapp, batch)
assert window._compress is None
assert manager.library.tracks[1].location.endswith(".mp3")
# Nothing lossless left: says so, starts nothing.
window._convert_to_mp3([1])
assert window._compress is None and asked == [1]
finally:
window.close()