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