v0.34.0: Calculate BPM from the audio, on the right-click menu

Spectral-flux onsets + autocorrelation in numpy, decoded by the ffmpeg CLI;
no new dependency. Runs on a worker with the status-bar progress bar, for
one track or many, and the batch is one Ctrl+Z.
This commit is contained in:
2026-10-02 14:55:35 -07:00
parent 481edd65ce
commit 10ced778af
7 changed files with 504 additions and 4 deletions
+75 -2
View File
@@ -10,7 +10,7 @@ from PyQt6.QtWidgets import (
from PyQt6.QtCore import Qt, QEvent, QObject, QTimer, pyqtSignal
from PyQt6.QtGui import QAction, QKeySequence
from lintunes import device_sync, music_folder, theme, url_import
from lintunes import bpm_detect, device_sync, music_folder, theme, url_import
from lintunes.andtunes import layout as andtunes_layout
from lintunes.andtunes import install as andtunes_install
from lintunes.andtunes import sync as andtunes_sync
@@ -223,6 +223,9 @@ class MainWindow(QMainWindow):
self._identify_running = False
# Import from URL: also shares the status-bar progress widgets.
self._url_worker = None
# Calculate BPM: also shares the status-bar progress widgets.
self._bpm_worker = None
self._bpm_results: dict[int, int] = {}
self._url_target = None # url_import.ImportTarget, or None
self._url_inserted = 0 # songs added to the target so far
self._url_imported = 0
@@ -256,6 +259,7 @@ class MainWindow(QMainWindow):
view.table.tracks_changed.connect(self._update_totals)
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.remove_from_library_requested.connect(
lambda ids: self._delete_tracks(ids, delete_files=False))
view.table.delete_from_library_requested.connect(
@@ -550,12 +554,17 @@ class MainWindow(QMainWindow):
def _busy_worker(self):
"""The transfer currently owning the status-bar progress widgets."""
for worker in (self._andtunes_planner, self._andtunes_worker,
self._export_worker, self._url_worker):
self._export_worker, self._url_worker,
self._bpm_worker):
if worker is not None and worker.busy():
return worker
return None
def _confirm_cancel_sync(self):
if self._bpm_worker is not None and self._bpm_worker.busy():
# Nothing to lose: what's been measured is kept.
self._bpm_worker.cancel()
return
if self._url_worker is not None and self._url_worker.busy():
self._confirm_cancel_url_import()
return
@@ -1586,6 +1595,70 @@ class MainWindow(QMainWindow):
return
self._enqueue_identify(tracks)
# ---- Calculate BPM ----
def _calculate_bpm(self, track_ids: list[int]):
"""Measure the tempo of the selection on a worker thread, with the
status-bar progress bar; results land as one undoable edit."""
if not exporter.web_support.ffmpeg_available():
QMessageBox.warning(
self, "Calculate BPM",
"Calculating BPM 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:
self.statusBar().showMessage(
"Wait for the current transfer to finish first", 6000)
return
items = []
for tid in track_ids:
track = self._manager.library.tracks.get(tid)
if track is not None and track.location:
label = (f"{track.artist} — {track.name}" if track.artist
else track.name) or Path(track.location).name
items.append((tid, track.location, label))
if not items:
return
self._bpm_results = {}
worker = bpm_detect.BpmWorker(items, self)
worker.progress.connect(self._on_bpm_progress)
worker.detected.connect(self._bpm_results.__setitem__)
worker.finished.connect(self._on_bpm_finished)
self._bpm_worker = worker
self._sync_label.setText("Calculating BPM…")
self._sync_progress.setRange(0, len(items))
self._sync_progress.setValue(0)
self._sync_cancel.show()
self._sync_label.show()
self._sync_progress.show()
worker.start()
def _on_bpm_progress(self, done: int, total: int, label: str):
self._sync_progress.setRange(0, total)
self._sync_progress.setValue(done)
if label:
short = label if len(label) <= 40 else label[:39] + "…"
where = f"{done + 1} of {total} · " if total > 1 else ""
self._sync_label.setText(f"BPM {where}{short}")
def _on_bpm_finished(self, summary: dict):
self._hide_sync_widgets()
results, self._bpm_results = self._bpm_results, {}
self._manager.set_tracks_bpm(results)
if len(results) == 1 and not summary["cancelled"]:
msg = f"BPM: {next(iter(results.values()))}"
else:
msg = f"BPM set for {len(results)} track(s)"
if summary["cancelled"]:
msg = "Calculate BPM stopped — " + msg[0].lower() + msg[1:]
if summary["no_beat"]:
msg += f" · no steady beat in {summary['no_beat']}"
if summary["failed"]:
msg += f" · {summary['failed']} couldn't be read"
if not summary["cancelled"]:
sounds.play_done(self._prefs)
self.statusBar().showMessage(msg, 10000)
def _identify_setup_problem(self) -> str:
"""Why an AcoustID lookup can't run on this machine, or ''."""
if not fpcalc_available():