mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 18:22:53 +01:00
1622 lines
72 KiB
Python
1622 lines
72 KiB
Python
"""The retained native model for Rekordbox: the open ``master.db`` session.
|
|
|
|
This is the only module that knows ``pyrekordbox`` exists. It owns the decrypted
|
|
SQLCipher session, the ANLZ analysis files, and the caches the projection reads.
|
|
|
|
**Writes cover track metadata and playlists.** Cues and the beatgrid are
|
|
deliberately absent rather than stubbed — they are separate stores (two DB tables
|
|
kept consistent, and the ANLZ analysis files) and a store that cannot write them
|
|
cannot half-write them.
|
|
|
|
Edits accumulate in the SQLAlchemy session and are only made permanent by
|
|
`save()`, which maps exactly onto Konduktor's "edit in memory, Save writes to
|
|
disk" model. `pyrekordbox`'s `commit()` is what assigns Rekordbox's update
|
|
sequence numbers, and a real Rekordbox was verified to accept and continue from
|
|
the result — see the handoff's Findings.
|
|
|
|
Two things here are not obvious and are load-bearing:
|
|
|
|
* **ANLZ is read LAZILY.** The beatgrid lives in a per-track analysis file, not
|
|
in the database, and parsing them all costs ~1.4 ms each — about 12 seconds
|
|
for a library the size of the project's Traktor collection. So grids are
|
|
parsed on demand and cached, and `Track.grid_marker_count` carries a
|
|
documented approximation until a track's grid is actually read.
|
|
* **Cue counts come from ONE aggregate query**, not from walking each track's
|
|
relationship, which would be a per-track round trip at open.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import logging
|
|
import os
|
|
import uuid
|
|
from contextlib import contextmanager
|
|
from datetime import datetime
|
|
from pathlib import Path
|
|
|
|
from sqlalchemy import func, select, text
|
|
from sqlalchemy.exc import OperationalError
|
|
from sqlalchemy.orm import joinedload
|
|
|
|
from ...core.adapter import (
|
|
InvalidCommand,
|
|
LibraryNotSupported,
|
|
NotFound,
|
|
SaveOutcome,
|
|
Unsupported,
|
|
)
|
|
from ...core.edit_journal import EditJournal
|
|
from ...core.grid_edit import ReplaceGridCommands
|
|
from ...core.pathmap import PathMapping, stored_form
|
|
from . import gain, memory_palette, timebase, track_palette
|
|
from .cue_types import MAX_MEMORY_CUES, beat_loop_size, kind_for, role_and_slot
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
|
def _file_facts(audio: Path) -> dict:
|
|
"""What Rekordbox reads off the file itself for a new track's row."""
|
|
from datetime import date
|
|
|
|
out: dict = {}
|
|
try:
|
|
st = audio.stat()
|
|
born = getattr(st, "st_birthtime", None) or st.st_mtime
|
|
out["created"] = date.fromtimestamp(born)
|
|
except OSError:
|
|
pass
|
|
try:
|
|
import mutagen
|
|
|
|
info = mutagen.File(str(audio)).info
|
|
out["length"] = int(round(info.length)) if info.length else None
|
|
if getattr(info, "bitrate", None):
|
|
out["bitrate"] = int(round(info.bitrate / 1000)) # kbps, as Rekordbox stores it
|
|
if getattr(info, "sample_rate", None):
|
|
out["sample_rate"] = int(info.sample_rate)
|
|
if getattr(info, "bits_per_sample", None):
|
|
out["bit_depth"] = int(info.bits_per_sample)
|
|
except Exception: # noqa: BLE001 — facts are a nicety; the row stands without them
|
|
log.debug("could not read %s", audio, exc_info=True)
|
|
return out
|
|
|
|
# Where a track's analysis files live, as `contentFile.Path` spells it.
|
|
_ANLZ_ROOT = "/PIONEER/USBANLZ/"
|
|
|
|
|
|
@contextmanager
|
|
def rekordbox_probe_suppressed():
|
|
"""Stop `pyrekordbox.commit()` refusing because a Rekordbox process exists.
|
|
|
|
Its check is process-wide, not per-file: it refuses to write ANY database
|
|
while Rekordbox is open — including a temp copy, or a brand-new export
|
|
Rekordbox cannot possibly have open. Neutralising the probe for the call
|
|
keeps everything else `commit()` does. SQLite's own lock still applies.
|
|
"""
|
|
from pyrekordbox.masterdb import database as rb_database
|
|
|
|
original = rb_database.get_rekordbox_pid
|
|
rb_database.get_rekordbox_pid = lambda *a, **kw: 0
|
|
try:
|
|
yield
|
|
finally:
|
|
rb_database.get_rekordbox_pid = original
|
|
|
|
|
|
def _iso_stamp(value) -> str:
|
|
"""Rekordbox writes timestamps in the JSON mirror as ISO-8601 with a
|
|
+00:00 offset and millisecond precision (e.g. 2026-09-17T20:55:13.862+00:00).
|
|
"""
|
|
if isinstance(value, datetime):
|
|
return value.strftime("%Y-%m-%dT%H:%M:%S.") + f"{value.microsecond // 1000:03d}+00:00"
|
|
return str(value)
|
|
|
|
|
|
class RekordboxStore(ReplaceGridCommands):
|
|
"""One open Rekordbox library."""
|
|
|
|
def __init__(self, path: Path):
|
|
self.path = Path(path)
|
|
self._mapping = PathMapping()
|
|
# Write an added file in the library's STORED form (`pathmap.stored_form`).
|
|
self._write_stored_paths = False
|
|
self._grid_cache: dict[str, tuple[list[float], list[float], list[int]] | None] = {}
|
|
self._journal = EditJournal()
|
|
# Grid edits buffered until save(): ANLZ files are written to disk, so
|
|
# applying them at command time would break the save contract.
|
|
self._pending_grids: dict[str, tuple[list, list, list]] = {}
|
|
# Normalize: drawn waveforms regenerated from the new audio, written
|
|
# into the track's ANLZ files at save (cues, grid, phrases untouched).
|
|
self._pending_waveforms: dict[str, object] = {}
|
|
# Analysis/artwork files of removed tracks, `share`-relative, deleted
|
|
# by save() AFTER the commit — a failed commit must leave them in place.
|
|
self._pending_file_removals: set[str] = set()
|
|
# Files of ADDED tracks, `share`-relative path -> bytes, written by
|
|
# save() BEFORE the commit (and removed again if it fails).
|
|
self._pending_new_files: dict[str, bytes] = {}
|
|
self._load()
|
|
|
|
# ---- open ------------------------------------------------------------
|
|
def _load(self) -> None:
|
|
from pyrekordbox.masterdb import MasterDatabase
|
|
from pyrekordbox.masterdb import models as tables
|
|
|
|
self._tables = tables
|
|
try:
|
|
self._db = MasterDatabase(path=str(self.path), unlock=True)
|
|
except Exception as ex: # noqa: BLE001 — surfaced as a clean 4xx
|
|
raise LibraryNotSupported(f"Could not open Rekordbox library: {ex}") from ex
|
|
self._grid_cache.clear()
|
|
self._stem_cache: dict[str, bool] = {}
|
|
self._content_cache: list | None = None
|
|
self._by_id: dict[str, object] | None = None
|
|
|
|
def discard(self) -> None:
|
|
"""Drop every unsaved edit and re-open the library as it is on disk.
|
|
|
|
Three things hold edits here, and all three must go: the SQLAlchemy
|
|
session (rolled back, then closed with its engine — `_load()` alone
|
|
would open a SECOND connection and leak the first), the buffered grid
|
|
writes (which the next save would otherwise still write to ANLZ files),
|
|
and the journal (else the library keeps reporting unsaved changes).
|
|
"""
|
|
try:
|
|
self._db.session.rollback()
|
|
except Exception: # noqa: BLE001 — discarding must not fail halfway
|
|
pass
|
|
self.close()
|
|
self._journal = EditJournal()
|
|
self._pending_grids.clear()
|
|
self._pending_waveforms.clear()
|
|
self._pending_file_removals.clear()
|
|
self._pending_new_files.clear()
|
|
self._load()
|
|
|
|
def close(self) -> None:
|
|
"""Release the session AND the pooled connection.
|
|
|
|
`pyrekordbox`'s own `close()` only closes the SQLAlchemy session, which
|
|
returns the connection to the engine's pool — the OS file handle stays
|
|
open. Disposing the engine is what actually releases `master.db`, and
|
|
without it the file cannot be replaced (a restore, or a test copying a
|
|
fresh library over it) on any platform that locks open files.
|
|
"""
|
|
try:
|
|
self._db.close()
|
|
except Exception: # noqa: BLE001 — closing must never raise
|
|
pass
|
|
try:
|
|
self._db.engine.dispose()
|
|
except Exception: # noqa: BLE001
|
|
pass
|
|
|
|
# ---- identity --------------------------------------------------------
|
|
@property
|
|
def cloud_synced(self) -> bool:
|
|
"""True when this library participates in Rekordbox's Cloud Library Sync.
|
|
|
|
Konduktor REFUSES to write a cloud-synced library: a local edit that the
|
|
server did not issue could propagate a corrupt sync state to the user's
|
|
other machines, which version history cannot undo. Detection is the
|
|
presence of a server-issued sequence number (`usn`) on any row, or a
|
|
populated cloud registry.
|
|
"""
|
|
t = self._tables
|
|
with self._db.session.no_autoflush:
|
|
for table in (t.DjmdContent, t.DjmdPlaylist, t.DjmdCue):
|
|
n = self._db.session.execute(
|
|
select(func.count()).select_from(table).where(table.usn.isnot(None))
|
|
).scalar()
|
|
if n:
|
|
return True
|
|
# pyrekordbox does not model every cloud table, so the rest is a
|
|
# raw probe: any row carrying a server-issued usn means synced.
|
|
for table_name in ("cloudAgentRegistry", "djmdCloudProperty"):
|
|
try:
|
|
n = self._db.session.execute(
|
|
text(f'SELECT COUNT(*) FROM "{table_name}" WHERE usn IS NOT NULL')
|
|
).scalar()
|
|
except Exception: # noqa: BLE001 — table may be absent
|
|
continue
|
|
if n:
|
|
return True
|
|
return False
|
|
|
|
@property
|
|
def local_usn(self) -> int | None:
|
|
"""Rekordbox's global local update counter (for diagnostics/tests)."""
|
|
try:
|
|
return self._db.get_local_usn()
|
|
except Exception: # noqa: BLE001
|
|
return None
|
|
|
|
# ---- content ---------------------------------------------------------
|
|
def iter_content(self) -> list:
|
|
"""Every track, with the lookup tables eagerly joined.
|
|
|
|
Without `joinedload` each track's artist/album/genre/key would be a
|
|
separate query — thousands of round trips on a real library.
|
|
"""
|
|
if self._content_cache is None:
|
|
t = self._tables
|
|
q = (
|
|
self._db.session.query(t.DjmdContent)
|
|
.options(
|
|
joinedload(t.DjmdContent.Artist),
|
|
joinedload(t.DjmdContent.Album),
|
|
joinedload(t.DjmdContent.Genre),
|
|
joinedload(t.DjmdContent.Key),
|
|
joinedload(t.DjmdContent.Label),
|
|
joinedload(t.DjmdContent.Remixer),
|
|
)
|
|
.filter(t.DjmdContent.rb_local_deleted == 0)
|
|
)
|
|
self._content_cache = list(q)
|
|
self._by_id = {str(c.ID): c for c in self._content_cache}
|
|
return self._content_cache
|
|
|
|
def content(self, track_id: str):
|
|
self.iter_content()
|
|
assert self._by_id is not None
|
|
row = self._by_id.get(str(track_id))
|
|
if row is None:
|
|
raise NotFound(f"No track {track_id!r}")
|
|
return row
|
|
|
|
def cue_kinds(self) -> dict[str, list[tuple[int | None, int | None, int | None]]]:
|
|
"""``{track_id: [(Kind, OutMsec, ColorTableIndex), ...]}`` for every live
|
|
cue, in one query.
|
|
|
|
Just enough per cue for the library table's count and hotcue dots,
|
|
without a per-track round trip. What a ``Kind`` means is decided in the
|
|
projection, by the same `role_and_slot` the deck's cues use, so the
|
|
table and the pads cannot disagree.
|
|
"""
|
|
t = self._tables
|
|
rows = self._db.session.execute(
|
|
select(t.DjmdCue.ContentID, t.DjmdCue.Kind, t.DjmdCue.OutMsec,
|
|
t.DjmdCue.ColorTableIndex)
|
|
.where(t.DjmdCue.rb_local_deleted == 0)
|
|
).all()
|
|
out: dict[str, list[tuple[int | None, int | None, int | None]]] = {}
|
|
for content_id, kind, out_msec, color_code in rows:
|
|
out.setdefault(str(content_id), []).append((kind, out_msec, color_code))
|
|
return out
|
|
|
|
def cues(self, track_id: str) -> list:
|
|
"""A track's cue rows, ordered by position."""
|
|
t = self._tables
|
|
return list(
|
|
self._db.session.query(t.DjmdCue)
|
|
.filter(t.DjmdCue.ContentID == str(track_id))
|
|
.filter(t.DjmdCue.rb_local_deleted == 0)
|
|
.order_by(t.DjmdCue.InMsec)
|
|
)
|
|
|
|
# ---- playlists -------------------------------------------------------
|
|
def playlists(self) -> list:
|
|
"""User playlists, excluding Rekordbox's own internal ones.
|
|
|
|
Rekordbox keeps working lists ("CUE Analysis Playlist", "Cloud Library
|
|
Sync") in the same table at reserved ids. They are not the user's and
|
|
showing them in the sidebar would be noise.
|
|
"""
|
|
from pyrekordbox.masterdb.database import SPECIAL_PLAYLIST_IDS
|
|
|
|
t = self._tables
|
|
return [
|
|
p
|
|
for p in self._db.session.query(t.DjmdPlaylist)
|
|
.filter(t.DjmdPlaylist.rb_local_deleted == 0)
|
|
.order_by(t.DjmdPlaylist.Seq)
|
|
if str(p.ID) not in SPECIAL_PLAYLIST_IDS
|
|
]
|
|
|
|
def playlist_song_ids(self, playlist_id: str) -> list[str]:
|
|
t = self._tables
|
|
rows = (
|
|
self._db.session.query(t.DjmdSongPlaylist.ContentID)
|
|
.filter(t.DjmdSongPlaylist.PlaylistID == str(playlist_id))
|
|
.filter(t.DjmdSongPlaylist.rb_local_deleted == 0)
|
|
.order_by(t.DjmdSongPlaylist.TrackNo)
|
|
)
|
|
return [str(r[0]) for r in rows]
|
|
|
|
def count_playlists(self) -> int:
|
|
"""Playlists the user has, for the status bar — folders excluded."""
|
|
folder = int(self._tables.PlaylistType.FOLDER)
|
|
return sum(1 for p in self.playlists() if int(p.Attribute or 0) != folder)
|
|
|
|
# ---- analysis files (the beatgrid) -----------------------------------
|
|
def anlz_grid(self, track_id: str) -> tuple[list[float], list[float], list[int]] | None:
|
|
"""``(times_sec, bpms, beat_in_bar)`` per beat for a track, or None if
|
|
unanalysed. The beat numbers matter: they say where the first DOWNBEAT
|
|
is, which a grid starting mid-bar does not put first.
|
|
|
|
Parsed on demand and cached — see the module docstring for why this is
|
|
not done eagerly.
|
|
"""
|
|
key = str(track_id)
|
|
if key in self._grid_cache:
|
|
return self._grid_cache[key]
|
|
result = self._read_anlz_grid(key)
|
|
if result is not None:
|
|
off = self.time_offset(key)
|
|
times, bpms, beats = result
|
|
result = ([timebase.from_pioneer(t, off) for t in times], bpms, beats)
|
|
self._grid_cache[key] = result
|
|
return result
|
|
|
|
def _read_anlz_grid(self, track_id: str):
|
|
row = self.content(track_id)
|
|
rel = getattr(row, "AnalysisDataPath", None)
|
|
if not rel:
|
|
return None
|
|
# AnalysisDataPath is rooted at the library's `share` directory and is
|
|
# stored with a leading slash.
|
|
path = self.path.parent / "share" / str(rel).lstrip("/\\")
|
|
if not path.is_file():
|
|
return None
|
|
try:
|
|
from pyrekordbox.anlz import AnlzFile
|
|
|
|
anlz = AnlzFile.parse_file(str(path))
|
|
except Exception as ex: # noqa: BLE001 — a bad ANLZ must not break a read
|
|
log.debug("ANLZ parse failed for %s: %s", track_id, ex)
|
|
return None
|
|
for tag in anlz.tags:
|
|
# Never treat AnlzFile as a Mapping: keys()/len() recurse forever in
|
|
# pyrekordbox 0.4.4.
|
|
if tag.type == "PQTZ":
|
|
try:
|
|
return ([float(t) for t in tag.times], [float(b) for b in tag.bpms],
|
|
[int(b) for b in tag.beats])
|
|
except Exception: # noqa: BLE001
|
|
return None
|
|
return None
|
|
|
|
def has_analysis(self, track_id: str) -> bool:
|
|
return bool(getattr(self.content(track_id), "AnalysisDataPath", None))
|
|
|
|
# ---- paths -----------------------------------------------------------
|
|
def set_path_mapping(self, mapping: PathMapping) -> None:
|
|
self._mapping = mapping or PathMapping()
|
|
|
|
def set_write_stored_paths(self, enabled: bool) -> None:
|
|
self._write_stored_paths = bool(enabled)
|
|
|
|
def _stored(self, audio: Path) -> Path:
|
|
if not self._write_stored_paths:
|
|
return Path(audio)
|
|
return stored_form(Path(audio), [self._mapping])
|
|
|
|
def is_stem(self, track_id: str) -> bool:
|
|
"""Whether the track's FILE is a native-instruments stem file — read
|
|
from its contents (only `.m4a`/`.mp4` are opened, ~0.7 ms each), and
|
|
cached per path, since the projection asks for every track at open."""
|
|
from ...core.stem_file import is_stem_file
|
|
|
|
path = self.audio_path(track_id)
|
|
if path is None:
|
|
return False
|
|
key = str(path)
|
|
if key not in self._stem_cache:
|
|
self._stem_cache[key] = is_stem_file(path)
|
|
return self._stem_cache[key]
|
|
|
|
@property
|
|
def path_mapping(self) -> PathMapping:
|
|
return self._mapping
|
|
|
|
def audio_path(self, track_id: str) -> Path | None:
|
|
"""The track's audio file on THIS machine, after any path remap."""
|
|
folder = getattr(self.content(track_id), "FolderPath", None)
|
|
if not folder:
|
|
return None
|
|
return self._mapping.apply(Path(str(folder)))
|
|
|
|
def time_offset(self, track_id: str) -> float:
|
|
"""Seconds rekordbox's clock runs behind the decoded audio for this
|
|
track — per FILE (an MP3's header, an M4A's edit list; 0 lossless).
|
|
Added on every position written, subtracted on every position read —
|
|
see `timebase`. Read from the file as it resolves here (path mapping
|
|
applied); a file that is offline falls back to its format's default."""
|
|
return timebase.offset(self.audio_path(track_id))
|
|
|
|
def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
|
|
"""The art embedded in the audio file, else Rekordbox's own copy.
|
|
|
|
The file comes first because it is what Traktor reads too, so one track
|
|
shows the same art on both platforms. Rekordbox's copy (`ImagePath`,
|
|
rooted at `share/` like `AnalysisDataPath`) covers files it cannot be
|
|
read from — a WAV, or a drive that is not mounted.
|
|
"""
|
|
from ...core import audio_tags
|
|
|
|
path = self.audio_path(track_id)
|
|
if path is not None and path.is_file():
|
|
art = audio_tags.read_cover(path)
|
|
if art:
|
|
return art
|
|
rel = getattr(self.content(track_id), "ImagePath", None)
|
|
if not rel:
|
|
return None
|
|
image = self.path.parent / "share" / str(rel).lstrip("/\\")
|
|
try:
|
|
data = image.read_bytes()
|
|
except OSError:
|
|
return None
|
|
return data, "image/png" if image.suffix.lower() == ".png" else "image/jpeg"
|
|
|
|
def all_audio_paths(self) -> list[str]:
|
|
return [
|
|
str(c.FolderPath) for c in self.iter_content() if getattr(c, "FolderPath", None)
|
|
]
|
|
|
|
# ---- writes: track metadata -----------------------------------------
|
|
#
|
|
# Deliberately NOT editable: the file path (it is the track's identity),
|
|
# BPM and key (audio/grid territory), and Rekordbox's own read-only
|
|
# bookkeeping. `producer` and `mix` are Traktor concepts with no Rekordbox
|
|
# column — Rekordbox has a Composer, which is not the same field — so they
|
|
# are simply absent from the set rather than mapped to something close.
|
|
_DIRECT_FIELDS = {
|
|
"title": "Title",
|
|
"comment": "Commnt",
|
|
"release_date": "ReleaseDate",
|
|
}
|
|
# Fields stored as a foreign key into a lookup table, which must be
|
|
# found-or-created: `add_*` in pyrekordbox RAISES on an existing name.
|
|
_LOOKUP_FIELDS = {
|
|
"artist": ("DjmdArtist", "ArtistID", "add_artist"),
|
|
"album": ("DjmdAlbum", "AlbumID", "add_album"),
|
|
"genre": ("DjmdGenre", "GenreID", "add_genre"),
|
|
"label": ("DjmdLabel", "LabelID", "add_label"),
|
|
# A remixer IS an artist in Rekordbox — same table, different column.
|
|
"remixer": ("DjmdArtist", "RemixerID", "add_artist"),
|
|
}
|
|
EDITABLE_FIELDS = set(_DIRECT_FIELDS) | set(_LOOKUP_FIELDS) | {"rating"}
|
|
|
|
def _lookup_id(self, table_name: str, adder: str, name: str) -> str | None:
|
|
"""The id of the lookup row called `name`, creating it if needed."""
|
|
if not name:
|
|
return None
|
|
table = getattr(self._tables, table_name)
|
|
existing = self._db.session.query(table).filter_by(Name=name).first()
|
|
if existing is not None:
|
|
return str(existing.ID)
|
|
row = getattr(self._db, adder)(name)
|
|
return str(row.ID)
|
|
|
|
def set_track_metadata(self, track_id: str, fields: dict) -> None:
|
|
row = self.content(track_id)
|
|
for key, value in fields.items():
|
|
if key not in self.EDITABLE_FIELDS:
|
|
continue # unknown/!safe fields are ignored, never guessed at
|
|
if key == "rating":
|
|
try:
|
|
stars = int(value or 0)
|
|
except (TypeError, ValueError):
|
|
raise InvalidCommand(f"Rating must be a number, got {value!r}") from None
|
|
if not 0 <= stars <= 5:
|
|
raise InvalidCommand(f"Rating must be 0-5, got {stars}")
|
|
before, new = row.Rating, stars
|
|
row.Rating = stars
|
|
elif key in self._DIRECT_FIELDS:
|
|
column = self._DIRECT_FIELDS[key]
|
|
before = getattr(row, column)
|
|
new = (value or None) if isinstance(value, str) else value
|
|
setattr(row, column, new)
|
|
else:
|
|
table_name, column, adder = self._LOOKUP_FIELDS[key]
|
|
before = getattr(row, column)
|
|
new = self._lookup_id(table_name, adder, (value or "").strip())
|
|
setattr(row, column, new)
|
|
self._journal.record("track", "set", track_id, key, before, new)
|
|
# Artist/album/genre/label are FOREIGN KEYS. Setting the id does not move
|
|
# the ORM's cached relationship, so re-projecting the row immediately
|
|
# would read the OLD name back and report a successful edit as a no-op.
|
|
# Flush pushes the ids into the transaction; expiring the row makes the
|
|
# next attribute access reload the joined rows with them.
|
|
self._db.flush()
|
|
self._db.session.expire(row)
|
|
|
|
# ---- writes: musical key ---------------------------------------------
|
|
def _key_id(self, wheel: int | None, mode: str | None) -> str | None:
|
|
"""The `djmdKey` row for a key, found by what it MEANS, not its text.
|
|
|
|
A library's key table holds rekordbox's own names ("Abm") and whatever
|
|
key tags imported ("12A"), so matching on a rendered name would add a
|
|
second row for a key the library already has. Only a key it has never
|
|
seen gets a row — created as rekordbox creates its own (measured on the
|
|
local library, which rekordbox fills lazily as it analyses): named in
|
|
its spelling, `Seq` NULL, and through the ORM so `commit()` stamps the
|
|
row's `rb_local_usn` like any other change. (The exporters' raw insert
|
|
would leave it unstamped.)"""
|
|
from .projection import parse_key, render_key
|
|
|
|
if wheel is None or mode is None:
|
|
return None
|
|
for k in self._db.query(self._tables.DjmdKey).all():
|
|
if parse_key(k.ScaleName) == (wheel, mode):
|
|
return str(k.ID)
|
|
row = self._tables.DjmdKey(
|
|
ID=str(uuid.uuid4().int % 2_147_483_647),
|
|
ScaleName=render_key(wheel, mode),
|
|
UUID=str(uuid.uuid4()),
|
|
)
|
|
self._db.add(row)
|
|
self._db.flush()
|
|
return str(row.ID)
|
|
|
|
def set_key(self, track_id: str, wheel: int, mode: str) -> None:
|
|
if not (isinstance(wheel, int) and 1 <= wheel <= 12) or mode not in ("major", "minor"):
|
|
raise InvalidCommand(f"Not a key: wheel {wheel!r}, mode {mode!r}")
|
|
row = self.content(track_id)
|
|
before = row.KeyID
|
|
row.KeyID = self._key_id(wheel, mode)
|
|
self._journal.record("track", "set", track_id, "key", before, row.KeyID)
|
|
# A foreign key, like artist: flush + expire, or the re-projection
|
|
# reads the old key back through the cached relationship.
|
|
self._db.flush()
|
|
self._db.session.expire(row)
|
|
|
|
# ---- writes: track colour ---------------------------------------------
|
|
def set_track_color(self, track_id: str, color: str | None) -> None:
|
|
"""`djmdContent.ColorID`, a 1-based id into `djmdColor` (see
|
|
`track_palette`). Cleared = "0", as on the uncoloured rows of the local
|
|
library (a few hold NULL; both read as none)."""
|
|
new = track_palette.id_for(color)
|
|
if color is not None and not new:
|
|
raise InvalidCommand(f"Not a track colour: {color!r}")
|
|
row = self.content(track_id)
|
|
before = row.ColorID
|
|
if track_palette.id_for(track_palette.color_for(before)) == new:
|
|
return
|
|
row.ColorID = str(new)
|
|
self._journal.record("track", "set", track_id, "color", before, row.ColorID)
|
|
# A foreign key into djmdColor: flush + expire, as for the others.
|
|
self._db.flush()
|
|
self._db.session.expire(row)
|
|
|
|
# ---- auto gain ------------------------------------------------------------
|
|
def _mixer_row(self, track_id: str):
|
|
return (self._db.query(self._tables.DjmdMixerParam)
|
|
.filter(self._tables.DjmdMixerParam.ContentID == str(track_id)).first())
|
|
|
|
def mixer_gains(self) -> dict[str, float]:
|
|
"""``{track_id: auto gain dB}`` for every track with a row — ONE query, so
|
|
the projection never lazy-loads a relationship per track."""
|
|
t = self._tables.DjmdMixerParam
|
|
out = {}
|
|
for content_id, low, high in self._db.query(t.ContentID, t.GainLow, t.GainHigh).all():
|
|
if content_id is not None and low is not None and high is not None:
|
|
out[str(content_id)] = t._get_db(low, high)
|
|
return out
|
|
|
|
def mixer_gain(self, track_id: str) -> float | None:
|
|
row = self._mixer_row(track_id)
|
|
if row is None or row.GainLow is None or row.GainHigh is None:
|
|
return None
|
|
return row.Gain
|
|
|
|
def set_auto_gain(self, track_id: str, loudness) -> None:
|
|
"""The track's `djmdMixerParam` row (see `gain`), created as rekordbox
|
|
creates its own — `ID` and `UUID` both UUID strings — and through the
|
|
ORM, so `commit()` stamps `rb_local_usn`. Writing the halves already
|
|
there leaves the library clean."""
|
|
self.content(track_id) # NotFound for an unknown track
|
|
gain_db, peak_db = gain.values(loudness)
|
|
t = self._tables.DjmdMixerParam
|
|
g_low, g_high = t._set_db(gain_db)
|
|
p_low, p_high = t._set_db(peak_db)
|
|
row = self._mixer_row(track_id)
|
|
before = None if row is None else (row.GainHigh, row.GainLow, row.PeakHigh, row.PeakLow)
|
|
after = (g_high, g_low, p_high, p_low)
|
|
if before == after:
|
|
return
|
|
if row is None:
|
|
row = t(ID=str(uuid.uuid4()), ContentID=str(track_id), UUID=str(uuid.uuid4()))
|
|
self._db.add(row)
|
|
row.GainHigh, row.GainLow, row.PeakHigh, row.PeakLow = after
|
|
self._journal.record("track", "set", track_id, "auto_gain", before, after)
|
|
self._db.flush()
|
|
|
|
# ---- writes: playlists ------------------------------------------------
|
|
def _playlist(self, node_id: str):
|
|
t = self._tables
|
|
row = (
|
|
self._db.session.query(t.DjmdPlaylist)
|
|
.filter(t.DjmdPlaylist.ID == str(node_id))
|
|
.first()
|
|
)
|
|
if row is None:
|
|
raise NotFound(f"No playlist {node_id!r}")
|
|
return row
|
|
|
|
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
|
|
name = (name or "").strip()
|
|
if not name:
|
|
raise InvalidCommand("A playlist needs a name")
|
|
parent = self._playlist(parent_id) if parent_id else None
|
|
if parent is not None and int(parent.Attribute or 0) != int(
|
|
self._tables.PlaylistType.FOLDER
|
|
):
|
|
raise InvalidCommand("A playlist can only be created inside a folder")
|
|
row = self._db.create_playlist(name, parent=parent)
|
|
self._journal.record("playlist", "create", name)
|
|
return str(row.ID)
|
|
|
|
def create_folder(self, name: str, parent_id: str | None = None) -> str:
|
|
name = (name or "").strip()
|
|
if not name:
|
|
raise InvalidCommand("A folder needs a name")
|
|
parent = self._playlist(parent_id) if parent_id else None
|
|
if parent is not None and int(parent.Attribute or 0) != int(
|
|
self._tables.PlaylistType.FOLDER
|
|
):
|
|
raise InvalidCommand("A folder can only be created inside a folder")
|
|
row = self._db.create_playlist_folder(name, parent=parent)
|
|
self._journal.record("playlist", "create-folder", name)
|
|
return str(row.ID)
|
|
|
|
def rename_playlist(self, node_id: str, name: str) -> None:
|
|
name = (name or "").strip()
|
|
if not name:
|
|
raise InvalidCommand("A playlist needs a name")
|
|
row = self._playlist(node_id)
|
|
self._db.rename_playlist(row, name)
|
|
self._journal.record("playlist", "rename", name)
|
|
|
|
def delete_playlist(self, node_id: str) -> None:
|
|
row = self._playlist(node_id)
|
|
name = row.Name
|
|
self._db.delete_playlist(row)
|
|
self._journal.record("playlist", "delete", name)
|
|
|
|
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
|
|
"""Move a node to `index` among `parent_id`'s visible children.
|
|
|
|
Not pyrekordbox's `move_playlist`: its `parent=None` means "keep the
|
|
parent", so nothing can be moved to the top level with it. The same
|
|
writes are made here — `ParentID`, the moved row's `updated_at`, and
|
|
`Seq` renumbered from 1 in both parents (only rows whose `Seq` changes
|
|
are touched) — plus `masterPlaylists6.xml`'s `ParentId`, which
|
|
pyrekordbox's version leaves stale. Rekordbox's hidden working lists
|
|
share the table and the numbering, so `index` is placed relative to
|
|
the VISIBLE siblings and the hidden ones keep their order around it."""
|
|
import datetime
|
|
|
|
from pyrekordbox.masterdb.database import SPECIAL_PLAYLIST_IDS
|
|
|
|
t = self._tables
|
|
row = self._playlist(node_id)
|
|
dest = self._playlist(parent_id) if parent_id else None
|
|
if dest is not None and int(dest.Attribute or 0) != int(t.PlaylistType.FOLDER):
|
|
raise InvalidCommand("A playlist can only be moved into a folder")
|
|
ancestor = dest
|
|
while ancestor is not None:
|
|
if str(ancestor.ID) == str(row.ID):
|
|
raise InvalidCommand("A folder cannot be moved into itself")
|
|
up = str(ancestor.ParentID or "root")
|
|
ancestor = None if up in ("root", "0", "") else self._playlist(up)
|
|
|
|
def children(key: str) -> list:
|
|
return (
|
|
self._db.session.query(t.DjmdPlaylist)
|
|
.filter(t.DjmdPlaylist.ParentID == key)
|
|
.filter(t.DjmdPlaylist.rb_local_deleted == 0)
|
|
.order_by(t.DjmdPlaylist.Seq)
|
|
.all()
|
|
)
|
|
|
|
old_key = str(row.ParentID or "root")
|
|
new_key = str(dest.ID) if dest is not None else "root"
|
|
siblings = [c for c in children(new_key) if str(c.ID) != str(row.ID)]
|
|
visible = [c for c in siblings if str(c.ID) not in SPECIAL_PLAYLIST_IDS]
|
|
index = max(0, min(int(index), len(visible)))
|
|
if index < len(visible):
|
|
at = siblings.index(visible[index])
|
|
else:
|
|
at = siblings.index(visible[-1]) + 1 if visible else len(siblings)
|
|
order = siblings[:at] + [row] + siblings[at:]
|
|
if old_key == new_key and [str(c.ID) for c in order] == [
|
|
str(c.ID) for c in children(new_key)
|
|
]:
|
|
return str(row.ID)
|
|
|
|
row.ParentID = new_key
|
|
with self._db.registry.disabled():
|
|
row.updated_at = datetime.datetime.now()
|
|
for n, c in enumerate(order, start=1):
|
|
if c.Seq != n:
|
|
c.Seq = n
|
|
if old_key != new_key:
|
|
for n, c in enumerate(
|
|
(c for c in children(old_key) if str(c.ID) != str(row.ID)), start=1
|
|
):
|
|
if c.Seq != n:
|
|
c.Seq = n
|
|
xml = getattr(self._db, "playlist_xml", None)
|
|
if xml is not None:
|
|
try:
|
|
xml.update(row.ID, parent_id=new_key)
|
|
except ValueError:
|
|
pass # a playlist the XML never listed: nothing to keep in step
|
|
self._db.flush()
|
|
self._journal.record("playlist", "move", row.Name)
|
|
return str(row.ID)
|
|
|
|
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
|
|
"""Replace a playlist's contents, in the given order.
|
|
|
|
Rekordbox keys order by `DjmdSongPlaylist.TrackNo`, and there is no
|
|
bulk reorder — so this clears the list and re-adds it. `add_to_playlist`
|
|
is used one row at a time because it is what maintains Rekordbox's own
|
|
USN ordering for these rows.
|
|
"""
|
|
t = self._tables
|
|
playlist = self._playlist(node_id)
|
|
if int(playlist.Attribute or 0) != int(t.PlaylistType.PLAYLIST):
|
|
raise InvalidCommand("Only a plain playlist has an editable track list")
|
|
known = {tid for tid in track_ids if self._by_id and str(tid) in self._by_id}
|
|
unknown = [tid for tid in track_ids if tid not in known]
|
|
if unknown:
|
|
raise NotFound(f"Unknown track(s): {', '.join(map(str, unknown[:3]))}")
|
|
existing = (
|
|
self._db.session.query(t.DjmdSongPlaylist)
|
|
.filter(t.DjmdSongPlaylist.PlaylistID == str(node_id))
|
|
.all()
|
|
)
|
|
# NOT `remove_from_playlist`: it commits, which wrote an unsaved edit
|
|
# to disk (beyond Discard's reach) and raised while Rekordbox ran.
|
|
# The list is rebuilt from 1 below, so no renumbering is needed.
|
|
for song in existing:
|
|
self._db.delete(song)
|
|
self._db.flush()
|
|
for n, track_id in enumerate(track_ids, start=1):
|
|
self._db.add_to_playlist(playlist, str(track_id), track_no=n)
|
|
self._journal.record("playlist", "entries", playlist.Name, after=len(track_ids))
|
|
return len(track_ids)
|
|
|
|
# ---- writes: adding tracks ---------------------------------------------
|
|
#
|
|
# MEASURED, by dragging two files into Rekordbox 7.2's collection and
|
|
# diffing (2026-10-01): see `new_content`. Rekordbox fills the row from the
|
|
# FILE (size, sample rate, bit rate, and `DateCreated` from the file's
|
|
# creation date), stamps it with this library's device, and lists every
|
|
# file it writes for the track in `contentFile` with the file's MD5.
|
|
def add_track(self, audio: Path, track, *, measured, with_grid: bool,
|
|
art: bytes | None) -> str:
|
|
"""Add one track's row, return its id. Its analysis files and artwork
|
|
are held until save(); its grid and cues are the caller's to replay
|
|
through the ordinary commands. `with_grid` reserves an empty `PQTZ`
|
|
in the `.DAT` for `replace_grid` to fill."""
|
|
from . import new_content
|
|
|
|
audio = Path(audio)
|
|
if not audio.is_file():
|
|
raise InvalidCommand(f"No audio file at {audio}")
|
|
t = self._tables
|
|
stored = self._stored(audio)
|
|
for form in {str(audio), str(stored)}:
|
|
if self._db.session.query(t.DjmdContent).filter_by(FolderPath=form).count():
|
|
raise InvalidCommand(f"The library already holds {audio}")
|
|
facts = _file_facts(audio)
|
|
content = self._db.add_content(
|
|
str(audio),
|
|
Title=track.title or audio.stem,
|
|
Length=facts.get("length") or track.length,
|
|
BitRate=facts.get("bitrate") or (int(track.bitrate / 1000) if track.bitrate else None),
|
|
SampleRate=facts.get("sample_rate"),
|
|
BitDepth=facts.get("bit_depth", 16),
|
|
Rating=track.rating or 0,
|
|
Commnt=track.comment or "",
|
|
ReleaseDate=track.release_date or "",
|
|
)
|
|
year = str(track.release_date or "")[:4]
|
|
if year.isdigit():
|
|
content.ReleaseYear = int(year)
|
|
if facts.get("created"):
|
|
content.DateCreated = facts["created"]
|
|
content.ArtistID = new_content.lookup(self._db, "artist", track.artist)
|
|
content.AlbumID = new_content.lookup(self._db, "album", track.album)
|
|
content.GenreID = new_content.lookup(self._db, "genre", track.genre)
|
|
content.LabelID = new_content.lookup(self._db, "label", track.label)
|
|
# From the wheel, never the source's text: its notation is not
|
|
# Rekordbox's ("10m" is "Cm" here), and a row it already has is reused.
|
|
content.KeyID = self._key_id(track.key_wheel, track.key_mode)
|
|
content.ContentLink = new_content.CONTENT_LINK
|
|
content.ColorID = str(track_palette.id_for(track.color))
|
|
if stored != audio:
|
|
# pyrekordbox reads the file where it IS; the row names it as the
|
|
# library stores every other path (the server's mapping, inverted).
|
|
content.FolderPath = str(stored)
|
|
|
|
track_uuid = str(content.UUID)
|
|
rel = new_content.anlz_rel(track_uuid)
|
|
content.AnalysisDataPath = rel
|
|
content.Analysed = new_content.ANALYSED
|
|
content.AnalysisUpdated = 1
|
|
files = new_content.anlz_files(audio, measured, [] if with_grid else None)
|
|
for suffix, data in files.items():
|
|
self._pending_new_files[str(Path(rel).with_suffix(suffix))] = data
|
|
art_files = new_content.artwork_files(art)
|
|
if art_files:
|
|
folder = new_content.artwork_rel(track_uuid)
|
|
for name, data in art_files.items():
|
|
self._pending_new_files[f"{folder}/{name}"] = data
|
|
content.ImagePath = f"{folder}/artwork.jpg"
|
|
self._db.flush()
|
|
|
|
track_id = str(content.ID)
|
|
if self._content_cache is not None and self._by_id is not None:
|
|
self._content_cache.append(content)
|
|
self._by_id[track_id] = content
|
|
self._grid_cache.pop(track_id, None)
|
|
self._journal.record("track", "add", track_id)
|
|
return track_id
|
|
|
|
def _write_new_files(self) -> list[Path]:
|
|
"""Write added tracks' files; return what was written."""
|
|
share = self.path.parent / "share"
|
|
written: list[Path] = []
|
|
try:
|
|
for rel, data in self._pending_new_files.items():
|
|
path = share / rel.lstrip("/")
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
written.append(path) # before the write: a partial file is cleaned too
|
|
path.write_bytes(data)
|
|
except BaseException:
|
|
for path in written:
|
|
path.unlink(missing_ok=True)
|
|
raise
|
|
return written
|
|
|
|
def _add_content_files(self, written: list[Path]) -> None:
|
|
"""One `contentFile` row per file an added track carries, as Rekordbox
|
|
writes them: `Hash` is the file's MD5, and its `_m`/`_s` artwork sizes
|
|
are not listed."""
|
|
import hashlib
|
|
from urllib.parse import quote
|
|
|
|
t = self._tables
|
|
share = self.path.parent / "share"
|
|
by_folder = {}
|
|
for row in self.iter_content():
|
|
for rel in (row.AnalysisDataPath, row.ImagePath):
|
|
if rel:
|
|
by_folder[str(Path(rel).parent)] = row
|
|
for path in written:
|
|
if path.name in ("artwork_m.jpg", "artwork_s.jpg"):
|
|
continue
|
|
rel = "/" + path.relative_to(share).as_posix()
|
|
row = by_folder.get(str(Path(rel).parent))
|
|
if row is None:
|
|
continue
|
|
self._db.add(t.ContentFile(
|
|
ID=f"{row.UUID}_{quote(rel, safe='')}",
|
|
ContentID=str(row.ID),
|
|
Path=rel,
|
|
Hash=hashlib.md5(path.read_bytes()).hexdigest(),
|
|
Size=path.stat().st_size,
|
|
rb_local_path=str(path),
|
|
UUID=str(uuid.uuid4()),
|
|
created_at=datetime.now(),
|
|
updated_at=datetime.now(),
|
|
))
|
|
self._db.flush()
|
|
|
|
# ---- writes: removing tracks -------------------------------------------
|
|
#
|
|
# MEASURED, by removing a track in Rekordbox 7.2 and diffing every row and
|
|
# every file under `share/` (Demo Track 2, 2026-10-01): Rekordbox DELETES
|
|
# the rows — it does not set `rb_local_deleted` — from these tables, leaves
|
|
# the playlist row itself alone, and deletes the files `contentFile` lists
|
|
# (there, the four ANLZ files) together with their emptied folders. That
|
|
# track had no artwork, and an Artwork folder holds `_m`/`_s` sizes that
|
|
# `contentFile` does not list, so artwork is left in place: an orphaned
|
|
# image is harmless, a guessed deletion is not.
|
|
_REMOVED_WITH_TRACK = ("DjmdCue", "ContentCue", "ContentFile", "DjmdMixerParam",
|
|
"DjmdSongPlaylist")
|
|
# Also keyed by ContentID, but empty in the measured library, so what
|
|
# Rekordbox does with them is unknown. A track that appears in one is
|
|
# refused rather than guessed at.
|
|
_UNMEASURED_LINKS = {
|
|
"djmdSongHistory": "a History list",
|
|
"djmdSongSampler": "the Sampler",
|
|
"djmdSongTagList": "the Tag List",
|
|
"djmdSongMyTag": "My Tag",
|
|
"djmdSongHotCueBanklist": "a Hot Cue Bank List",
|
|
"djmdSongRelatedTracks": "Related Tracks",
|
|
"djmdSongRequestList": "a request list",
|
|
"djmdActiveCensor": "an Active Censor",
|
|
"contentActiveCensor": "an Active Censor",
|
|
"djmdCloudExportSongPlaylist": "a cloud export",
|
|
}
|
|
|
|
def _unmeasured_links(self, ids: list[str]) -> list[tuple[str, str]]:
|
|
"""``(track_id, where)`` for each track named by an unmeasured table."""
|
|
params = {f"i{n}": tid for n, tid in enumerate(ids)}
|
|
marks = ", ".join(f":{k}" for k in params)
|
|
found: list[tuple[str, str]] = []
|
|
for table, where in self._UNMEASURED_LINKS.items():
|
|
try:
|
|
rows = self._db.session.execute(
|
|
text(f'SELECT DISTINCT ContentID FROM "{table}" '
|
|
f"WHERE ContentID IN ({marks})"), params
|
|
).all()
|
|
except Exception: # noqa: BLE001 — table absent in this schema version
|
|
continue
|
|
found += [(str(r[0]), where) for r in rows]
|
|
return found
|
|
|
|
def remove_tracks(self, track_ids: list[str]) -> int:
|
|
"""Remove tracks from the library and every playlist; return how many.
|
|
|
|
Validated as a whole first, so a refused batch changes nothing. The
|
|
audio files are never touched; the analysis files go at save().
|
|
"""
|
|
t = self._tables
|
|
self.iter_content()
|
|
assert self._by_id is not None
|
|
ids = [str(tid) for tid in dict.fromkeys(track_ids) if str(tid) in self._by_id]
|
|
if not ids:
|
|
return 0
|
|
blocked = self._unmeasured_links(ids)
|
|
if blocked:
|
|
tid, where = blocked[0]
|
|
title = self._by_id[tid].Title or tid
|
|
more = f" (and {len(blocked) - 1} more)" if len(blocked) > 1 else ""
|
|
raise Unsupported(
|
|
f"“{title}” is in {where} in Rekordbox{more}, and Konduktor does not "
|
|
"yet know how Rekordbox removes a track from there. Remove it in "
|
|
"Rekordbox instead — nothing was changed."
|
|
)
|
|
|
|
playlists: set[str] = set()
|
|
for tid in ids:
|
|
for name in self._REMOVED_WITH_TRACK:
|
|
table = getattr(t, name)
|
|
for row in self._db.session.query(table).filter(table.ContentID == tid):
|
|
if name == "ContentFile" and str(row.Path or "").startswith(_ANLZ_ROOT):
|
|
self._pending_file_removals.add(str(row.Path))
|
|
elif name == "DjmdSongPlaylist":
|
|
playlists.add(str(row.PlaylistID))
|
|
self._db.delete(row)
|
|
self._db.delete(self._by_id[tid])
|
|
self._pending_grids.pop(tid, None)
|
|
self._grid_cache.pop(tid, None)
|
|
self._journal.record("track", "remove", tid)
|
|
self._db.flush()
|
|
for playlist_id in playlists:
|
|
self._renumber(playlist_id)
|
|
self._content_cache = None
|
|
self._by_id = None
|
|
return len(ids)
|
|
|
|
def _renumber(self, playlist_id: str) -> None:
|
|
"""Close the gaps removed entries left in a playlist's `TrackNo`s, as
|
|
`pyrekordbox.remove_from_playlist` does — one 'move' for the registry,
|
|
not an update per row."""
|
|
t = self._tables
|
|
moved = []
|
|
now = datetime.now()
|
|
rows = (
|
|
self._db.session.query(t.DjmdSongPlaylist)
|
|
.filter(t.DjmdSongPlaylist.PlaylistID == playlist_id)
|
|
.order_by(t.DjmdSongPlaylist.TrackNo)
|
|
)
|
|
with self._db.registry.disabled():
|
|
for n, row in enumerate(rows, start=1):
|
|
if row.TrackNo != n:
|
|
row.TrackNo = n
|
|
row.updated_at = now
|
|
moved.append(row)
|
|
if moved:
|
|
self._db.registry.on_move(moved)
|
|
|
|
def _delete_removed_files(self) -> None:
|
|
"""Delete removed tracks' analysis/artwork files, then their emptied
|
|
folders. Called after the commit; a file another track still lists is
|
|
kept, and a failure only leaves an orphan behind, so it is logged."""
|
|
t = self._tables
|
|
share = (self.path.parent / "share").resolve()
|
|
still_listed = {str(p) for (p,) in self._db.session.query(t.ContentFile.Path)}
|
|
for rel in sorted(self._pending_file_removals - still_listed):
|
|
parts = Path(rel.lstrip("/\\")).parts
|
|
path = (share / Path(*parts)).resolve()
|
|
# Folders below e.g. `PIONEER/USBANLZ` are the track's own; that
|
|
# level and above are Rekordbox's and stay even when emptied.
|
|
keep = (share / Path(*parts[:2])).resolve()
|
|
if len(parts) < 3 or keep not in path.parents:
|
|
continue
|
|
try:
|
|
path.unlink(missing_ok=True)
|
|
folder = path.parent
|
|
while folder != keep and not any(folder.iterdir()):
|
|
folder.rmdir()
|
|
folder = folder.parent
|
|
except OSError as ex:
|
|
log.warning("Could not delete %s: %s", path, ex)
|
|
self._pending_file_removals.clear()
|
|
|
|
# ---- save --------------------------------------------------------------
|
|
@property
|
|
def dirty(self) -> bool:
|
|
return self._journal.dirty
|
|
|
|
def edited_fields(self, track_id: str) -> set[str]:
|
|
return self._journal.fields_for(track_id)
|
|
|
|
def save(self) -> SaveOutcome:
|
|
"""Make the session's edits permanent.
|
|
|
|
`commit(autoinc=True)` is what assigns Rekordbox's update sequence
|
|
numbers — one increment per change, stamped onto each changed row. A real
|
|
Rekordbox was verified to accept a library written this way and to carry
|
|
on from the counter it was left at.
|
|
|
|
`snapshot` is None: a Rekordbox library is `master.db` plus its analysis
|
|
files plus a playlist XML, so there is no single blob to version, and
|
|
`capabilities.save.history` says so.
|
|
"""
|
|
summary = self._journal.summary()
|
|
# Files first: if an analysis file cannot be written, nothing should have
|
|
# been committed to the database either. An added track's files go
|
|
# before the grids, which write into them, and their `contentFile`
|
|
# rows after, which hash what was finally written.
|
|
written = self._write_new_files()
|
|
try:
|
|
self._flush_waveforms()
|
|
self._flush_grids()
|
|
self._add_content_files(written)
|
|
self._commit()
|
|
except BaseException:
|
|
for path in written:
|
|
path.unlink(missing_ok=True)
|
|
raise
|
|
self._pending_new_files.clear()
|
|
self._delete_removed_files()
|
|
self._journal.clear()
|
|
# Reads go through the same session, so nothing needs re-projecting from
|
|
# scratch — but the grid cache is keyed by track and survives a save.
|
|
return SaveOutcome(summary=summary, snapshot=None, tag_results=[])
|
|
|
|
def _commit(self) -> None:
|
|
"""Commit, warning rather than refusing if Rekordbox is running.
|
|
|
|
`pyrekordbox.commit()` raises outright when it sees a Rekordbox process.
|
|
That is not Konduktor's behaviour: the settled decision is to **warn but
|
|
proceed**, matching how Traktor is handled — the user is told, not
|
|
blocked on a detection heuristic. The check is also process-wide rather
|
|
than per-file, so it would refuse to write a temp copy of a library while
|
|
Rekordbox had an entirely different one open, which makes tests depend on
|
|
whether the app happens to be running.
|
|
|
|
The veto is suppressed by neutralising the process probe for the duration
|
|
of the call, so every other thing `commit()` does — the USN
|
|
auto-increment, the session commit, and keeping `masterPlaylists6.xml`'s
|
|
timestamps in step — still runs as the library intends. Duplicating that
|
|
body here would silently drift from it on upgrade.
|
|
"""
|
|
from pyrekordbox.masterdb import database as rb_database
|
|
|
|
if rb_database.get_rekordbox_pid():
|
|
log.warning(
|
|
"Rekordbox appears to be running; saving anyway. It may overwrite "
|
|
"or re-sync the library while it is open."
|
|
)
|
|
try:
|
|
with rekordbox_probe_suppressed():
|
|
self._db.commit(autoinc=True)
|
|
except OperationalError as ex:
|
|
# Suppressing pyrekordbox's veto does not remove SQLite's own lock:
|
|
# a running Rekordbox really does hold the database, and the raw
|
|
# error is an unhelpful 500. Say what happened and what to do.
|
|
if "locked" not in str(ex).lower():
|
|
raise
|
|
raise InvalidCommand(
|
|
"Rekordbox has the library open, so it cannot be written right "
|
|
"now. Close Rekordbox and save again — your changes are still here."
|
|
) from ex
|
|
|
|
@property
|
|
def app_running(self) -> bool:
|
|
"""Whether a Rekordbox process is up — for warning the user, not blocking."""
|
|
try:
|
|
from pyrekordbox.masterdb import database as rb_database
|
|
|
|
return bool(rb_database.get_rekordbox_pid())
|
|
except Exception: # noqa: BLE001 — detection must never break a save
|
|
return False
|
|
|
|
# ---- writes: cues -----------------------------------------------------
|
|
#
|
|
# Rekordbox keeps cues in TWO places that must agree: normalized `djmdCue`
|
|
# rows, and a denormalized JSON mirror in `contentCue.Cues` alongside a
|
|
# `rb_cue_count`. Every mutation here ends in `_sync_content_cue()`.
|
|
#
|
|
# Field conventions below are read off a real library (see the handoff's
|
|
# Findings), not guessed:
|
|
# * `Kind` is the bank slot; 0 means a memory cue.
|
|
# * a loop is an ordinary cue row with `OutMsec` > 0 plus `BeatLoopSize`.
|
|
# * `InFrame`/`OutFrame` are the position in frames at 150 fps.
|
|
# * an uncoloured cue is `Color=-1, ColorTableIndex=NULL`; Rekordbox writes
|
|
# `Color=255, ColorTableIndex=0` on the loops and auto-cues it creates.
|
|
|
|
_FPS = 150 # Rekordbox stores cue positions in frames as well as ms
|
|
|
|
@staticmethod
|
|
def _frames(msec: int) -> int:
|
|
return int(msec * RekordboxStore._FPS / 1000)
|
|
|
|
def _cue_row(self, track_id: str, slot: int):
|
|
"""The hot cue occupying the 0-based generic `slot`, or None."""
|
|
t = self._tables
|
|
return (
|
|
self._db.session.query(t.DjmdCue)
|
|
.filter(t.DjmdCue.ContentID == str(track_id))
|
|
.filter(t.DjmdCue.Kind == kind_for("hotcue", slot))
|
|
.filter(t.DjmdCue.rb_local_deleted == 0)
|
|
.first()
|
|
)
|
|
|
|
def _loop_beats(self, track_id: str, start_sec: float, length_sec: float) -> int | None:
|
|
"""Musical length of a loop, from the track's own tempo at that point."""
|
|
if length_sec <= 0:
|
|
return None
|
|
bpm = None
|
|
grid = self.anlz_grid(track_id)
|
|
if grid:
|
|
times, bpms = grid[0], grid[1]
|
|
for t, b in zip(times, bpms):
|
|
if t <= start_sec:
|
|
bpm = b
|
|
else:
|
|
break
|
|
if bpm is None and bpms:
|
|
bpm = bpms[0]
|
|
if not bpm:
|
|
raw = getattr(self.content(track_id), "BPM", 0) or 0
|
|
bpm = raw / 100.0 if raw else None
|
|
if not bpm:
|
|
return None
|
|
beats = round(length_sec / (60.0 / bpm))
|
|
return max(1, int(beats))
|
|
|
|
def set_cue(
|
|
self,
|
|
track_id: str,
|
|
*,
|
|
slot: int,
|
|
start_sec: float,
|
|
cue_type: str,
|
|
length_sec: float = 0.0,
|
|
name: str | None = None,
|
|
color_code: int | None = None,
|
|
) -> None:
|
|
"""Create or replace the cue in `slot`. A loop is a cue with a length.
|
|
|
|
`color_code` is a rekordbox palette code (`palette.PALETTE`). None KEEPS
|
|
the colour of the cue already in the slot — the colour belongs to the
|
|
pad, so a rename, a type change or an Auto Hotcues Replace leaves it as
|
|
the user set it — and a new cue is uncoloured. Only `set_cue_color`
|
|
clears one.
|
|
"""
|
|
if int(slot) < 0:
|
|
raise InvalidCommand(f"Hot cue slot cannot be negative, got {slot}")
|
|
existing = self._cue_row(track_id, slot)
|
|
if color_code is None and existing is not None:
|
|
color_code = existing.ColorTableIndex or None
|
|
self._write_cue(
|
|
track_id, existing, kind=kind_for("hotcue", slot), start_sec=start_sec,
|
|
cue_type=cue_type, length_sec=length_sec, name=name, color_code=color_code,
|
|
)
|
|
self._journal.record("cue", "add" if existing is None else "modify", track_id, f"slot:{slot}")
|
|
|
|
MAX_MEMORY_CUES = MAX_MEMORY_CUES # see `cue_types`
|
|
|
|
def memory_cue_rows(self, track_id: str) -> list:
|
|
"""A track's memory cues (`Kind` 0), in row order."""
|
|
t = self._tables
|
|
return list(
|
|
self._db.session.query(t.DjmdCue)
|
|
.filter(t.DjmdCue.ContentID == str(track_id))
|
|
.filter(t.DjmdCue.Kind == kind_for("memory", None))
|
|
.filter(t.DjmdCue.rb_local_deleted == 0)
|
|
)
|
|
|
|
def _memory_cue_row(self, track_id: str, cue_id: str):
|
|
"""The memory cue whose `djmdCue.ID` is `cue_id` (`CuePoint.id`)."""
|
|
row = next((c for c in self.memory_cue_rows(track_id) if str(c.ID) == str(cue_id)), None)
|
|
if row is None:
|
|
raise NotFound(f"No memory cue {cue_id!r} on this track")
|
|
return row
|
|
|
|
def add_memory_cue(
|
|
self,
|
|
track_id: str,
|
|
*,
|
|
start_sec: float,
|
|
cue_type: str = "cue",
|
|
length_sec: float = 0.0,
|
|
name: str | None = None,
|
|
color_code: int | None = None,
|
|
enforce_cap: bool = True,
|
|
) -> None:
|
|
"""Add a MEMORY cue (`Kind` 0); a memory loop when `length_sec` > 0.
|
|
|
|
`color_code` is a 0-based `memory_palette` code — NOT a hot-cue palette
|
|
code: a memory cue keeps its colour in `Color`, not `ColorTableIndex`.
|
|
`enforce_cap` refuses the 11th (an edit); the exporter, building a
|
|
library from a source that may hold more, trims before calling.
|
|
"""
|
|
if enforce_cap and len(self.memory_cue_rows(track_id)) >= self.MAX_MEMORY_CUES:
|
|
raise InvalidCommand(
|
|
f"rekordbox keeps at most {self.MAX_MEMORY_CUES} memory cues per track"
|
|
)
|
|
self._write_cue(
|
|
track_id, None, kind=kind_for("memory", None), start_sec=start_sec,
|
|
cue_type=cue_type, length_sec=length_sec, name=name, color_code=color_code,
|
|
)
|
|
self._journal.record("cue", "add", track_id, "memory")
|
|
|
|
def rename_memory_cue(self, track_id: str, cue_id: str, name: str | None) -> None:
|
|
"""A memory cue's name is rekordbox's `Comment`; only that column changes."""
|
|
cue = self._memory_cue_row(track_id, cue_id)
|
|
is_loop = (cue.OutMsec or 0) > 0
|
|
# An unnamed memory LOOP is '' (measured); an unnamed point cue NULL.
|
|
cue.Comment = name or ("" if is_loop else None)
|
|
self._db.flush()
|
|
self._sync_content_cue(track_id)
|
|
self._journal.record("cue", "modify", track_id, "memory")
|
|
|
|
def set_memory_cue_color(self, track_id: str, cue_id: str, color_code: int | None) -> None:
|
|
"""Recolour a memory cue; None = rekordbox's "No Color" (255, measured)."""
|
|
cue = self._memory_cue_row(track_id, cue_id)
|
|
self._apply_memory_color(cue, color_code, (cue.OutMsec or 0) > 0, cleared=True)
|
|
self._db.flush()
|
|
self._sync_content_cue(track_id)
|
|
self._journal.record("cue", "modify", track_id, "memory")
|
|
|
|
def delete_memory_cue(self, track_id: str, cue_id: str) -> None:
|
|
"""Delete the row outright, as rekordbox does (never `rb_local_deleted`)."""
|
|
cue = self._memory_cue_row(track_id, cue_id)
|
|
self._db.delete(cue)
|
|
self._db.flush()
|
|
self._sync_content_cue(track_id)
|
|
self._journal.record("cue", "delete", track_id, "memory")
|
|
|
|
def _write_cue(self, track_id: str, cue, *, kind: int, start_sec: float, cue_type: str,
|
|
length_sec: float, name: str | None, color_code: int | None) -> None:
|
|
"""Fill one `djmdCue` row (a new one when `cue` is None) and resync the
|
|
`contentCue` mirror — the single definition of a cue row's fields.
|
|
|
|
`color_code` is a hot-cue palette code on a hot cue and a 0-based
|
|
`memory_palette` code on a memory cue (`Kind` 0): the two keep their
|
|
colour in different columns."""
|
|
if start_sec < 0:
|
|
raise InvalidCommand("A cue cannot be before the start of the track")
|
|
row = self.content(track_id)
|
|
off = self.time_offset(track_id)
|
|
in_ms = int(round(timebase.to_pioneer(start_sec, off) * 1000))
|
|
is_loop = cue_type == "loop" and length_sec > 0
|
|
out_ms = (int(round(timebase.to_pioneer(start_sec + length_sec, off) * 1000))
|
|
if is_loop else -1)
|
|
|
|
if cue is None:
|
|
t = self._tables
|
|
cue = t.DjmdCue.create(
|
|
ID=str(self._db.generate_unused_id(t.DjmdCue)),
|
|
ContentID=str(track_id),
|
|
# Verified: a cue's ContentUUID is the TRACK's UUID, which is also
|
|
# the id of its contentCue mirror row.
|
|
ContentUUID=str(row.UUID),
|
|
UUID=str(uuid.uuid4()),
|
|
Kind=kind,
|
|
rb_data_status=0,
|
|
rb_local_data_status=0,
|
|
rb_local_deleted=0,
|
|
rb_local_synced=0,
|
|
)
|
|
self._db.add(cue)
|
|
|
|
cue.InMsec = in_ms
|
|
cue.InFrame = self._frames(in_ms)
|
|
cue.InMpegFrame = 0
|
|
cue.InMpegAbs = 0
|
|
cue.OutMsec = out_ms
|
|
cue.OutFrame = self._frames(out_ms) if is_loop else 0
|
|
cue.OutMpegFrame = 0
|
|
cue.OutMpegAbs = 0
|
|
cue.Kind = kind
|
|
if is_loop:
|
|
beats = self._loop_beats(track_id, start_sec, length_sec)
|
|
cue.BeatLoopSize = beat_loop_size(beats) if beats else None
|
|
cue.ActiveLoop = 0
|
|
cue.CueMicrosec = 0
|
|
else:
|
|
cue.BeatLoopSize = None
|
|
cue.ActiveLoop = None
|
|
cue.CueMicrosec = None
|
|
if kind == kind_for("memory", None):
|
|
self._apply_memory_color(cue, color_code, is_loop)
|
|
# Measured: an unnamed memory LOOP has Comment '', a point cue NULL.
|
|
cue.Comment = name or ("" if is_loop else None)
|
|
else:
|
|
self._apply_color(cue, color_code, is_loop)
|
|
cue.Comment = name or None
|
|
|
|
self._db.flush()
|
|
self._sync_content_cue(track_id)
|
|
|
|
@staticmethod
|
|
def _apply_color(cue, color_code: int | None, is_loop: bool) -> None:
|
|
"""A row's two colour columns — the one definition of both conventions."""
|
|
if color_code:
|
|
# A palette-coloured cue, as the real library stores one: the code in
|
|
# ColorTableIndex (22 = green), Color -1. Coloured loops store the
|
|
# same; verified in Rekordbox 7 through the master.db export.
|
|
cue.ColorTableIndex = int(color_code)
|
|
cue.Color = -1
|
|
elif is_loop:
|
|
# What Rekordbox writes on the loops and auto-cues it creates.
|
|
cue.Color = 255
|
|
cue.ColorTableIndex = 0
|
|
else:
|
|
cue.Color = -1
|
|
cue.ColorTableIndex = None
|
|
|
|
@staticmethod
|
|
def _apply_memory_color(cue, code: int | None, is_loop: bool, *, cleared: bool = False) -> None:
|
|
"""A MEMORY cue's colour columns (measured 2026-10-16, kit M1): the
|
|
0-based `memory_palette` code in `Color`, `ColorTableIndex` untouched by
|
|
colour — NULL on a point cue, 0 on a loop (rekordbox's loop marker).
|
|
Uncoloured is -1 on a new point cue, 255 on a loop and on any cue set
|
|
back to "No Color" (`cleared`)."""
|
|
cue.ColorTableIndex = 0 if is_loop else None
|
|
if code is not None:
|
|
cue.Color = int(code)
|
|
elif cleared or is_loop:
|
|
cue.Color = memory_palette.CLEARED
|
|
else:
|
|
cue.Color = -1
|
|
|
|
def set_cue_color(self, track_id: str, slot: int, color_code: int | None) -> None:
|
|
"""Recolour the cue in `slot`; None makes it uncoloured. Touches only the
|
|
colour columns, so the position does not take a time-base round trip."""
|
|
cue = self._cue_row(track_id, slot)
|
|
if cue is None:
|
|
raise NotFound(f"No cue in slot {slot}")
|
|
self._apply_color(cue, color_code, (cue.OutMsec or 0) > 0)
|
|
self._db.flush()
|
|
self._sync_content_cue(track_id)
|
|
self._journal.record("cue", "modify", track_id, f"slot:{slot}")
|
|
|
|
def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> None:
|
|
cue = self._cue_row(track_id, slot)
|
|
if cue is None:
|
|
raise NotFound(f"No cue in slot {slot}")
|
|
# Back to the decoded time base: set_cue re-applies the offset.
|
|
start = timebase.from_pioneer((cue.InMsec or 0) / 1000.0, self.time_offset(track_id))
|
|
length = 0.0
|
|
if cue_type == "loop":
|
|
if cue.OutMsec and cue.OutMsec > 0:
|
|
length = (cue.OutMsec - (cue.InMsec or 0)) / 1000.0
|
|
else:
|
|
raise InvalidCommand(
|
|
"Turning a cue into a loop needs a length — set the loop first"
|
|
)
|
|
self.set_cue(
|
|
track_id, slot=slot, start_sec=start, cue_type=cue_type,
|
|
length_sec=length, name=cue.Comment,
|
|
)
|
|
|
|
def delete_cue(self, track_id: str, slot: int) -> None:
|
|
cue = self._cue_row(track_id, slot)
|
|
if cue is None:
|
|
raise NotFound(f"No cue in slot {slot}")
|
|
self._db.delete(cue)
|
|
self._db.flush()
|
|
self._sync_content_cue(track_id)
|
|
self._journal.record("cue", "delete", track_id, f"slot:{slot}")
|
|
|
|
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> None:
|
|
"""Batch placement (Auto Hotcues). Fills empty slots unless overwriting."""
|
|
for cue in cues:
|
|
slot = int(getattr(cue, "slot"))
|
|
if not overwrite and self._cue_row(track_id, slot) is not None:
|
|
continue
|
|
self.set_cue(
|
|
track_id,
|
|
slot=slot,
|
|
start_sec=float(getattr(cue, "start", 0.0)),
|
|
cue_type=getattr(cue, "type", "cue"),
|
|
length_sec=float(getattr(cue, "length", 0.0) or 0.0),
|
|
name=getattr(cue, "name", None),
|
|
)
|
|
|
|
def _sync_content_cue(self, track_id: str) -> None:
|
|
"""Rebuild the denormalized `contentCue` mirror for a track.
|
|
|
|
Rekordbox keeps a JSON copy of every cue alongside a count, and stamps
|
|
its USN on THAT row rather than on the individual cue rows — it is the
|
|
sync unit. Leaving it stale after editing `djmdCue` would make the two
|
|
disagree, which is this platform's version of Traktor's companion-cue
|
|
trap.
|
|
|
|
Keys whose value is NULL are omitted, which is what Rekordbox's own
|
|
serializer does in every row observed.
|
|
"""
|
|
t = self._tables
|
|
row = self.content(track_id)
|
|
# In ROW order, as rekordbox writes it (measured: a memory cue added at
|
|
# 1:55 is listed after older ones at 2:04 and 3:26), not by position.
|
|
cues = (
|
|
self._db.session.query(t.DjmdCue)
|
|
.filter(t.DjmdCue.ContentID == str(track_id))
|
|
.filter(t.DjmdCue.rb_local_deleted == 0)
|
|
.order_by(text("djmdCue.rowid"))
|
|
.all()
|
|
)
|
|
fields = (
|
|
"ID", "ContentID", "ContentUUID", "InMsec", "InFrame", "InMpegFrame",
|
|
"InMpegAbs", "OutMsec", "OutFrame", "OutMpegFrame", "OutMpegAbs",
|
|
"Kind", "Color", "ColorTableIndex", "ActiveLoop", "Comment",
|
|
"BeatLoopSize", "CueMicrosec", "UUID",
|
|
)
|
|
records = []
|
|
for cue in cues:
|
|
rec = {}
|
|
for field in fields:
|
|
value = getattr(cue, field, None)
|
|
if value is None:
|
|
continue
|
|
rec[field] = value
|
|
for stamp in ("created_at", "updated_at"):
|
|
value = getattr(cue, stamp, None)
|
|
if value is not None:
|
|
rec[stamp] = _iso_stamp(value)
|
|
records.append(rec)
|
|
|
|
mirror = (
|
|
self._db.session.query(t.ContentCue)
|
|
.filter(t.ContentCue.ContentID == str(track_id))
|
|
.first()
|
|
)
|
|
if mirror is None:
|
|
if not records:
|
|
return
|
|
mirror = t.ContentCue.create(
|
|
# Verified: the mirror's id IS the track's UUID.
|
|
ID=str(row.UUID),
|
|
ContentID=str(track_id),
|
|
UUID=str(uuid.uuid4()),
|
|
rb_data_status=0,
|
|
rb_local_data_status=0,
|
|
rb_local_deleted=0,
|
|
rb_local_synced=0,
|
|
)
|
|
self._db.add(mirror)
|
|
mirror.Cues = json.dumps(records, ensure_ascii=False)
|
|
mirror.rb_cue_count = len(records)
|
|
self._db.flush()
|
|
|
|
# ---- writes: the beatgrid ---------------------------------------------
|
|
#
|
|
# The grid lives in the track's ANLZ `.DAT` (`PQTZ`), not in the database.
|
|
# Verified in Rekordbox 7: it reads the grid and the deck's BPM readout from
|
|
# `PQTZ`, leaves a rewritten `.DAT` exactly as Konduktor wrote it, ignores
|
|
# the stale extended grid in `.EXT` — and does NOT reconcile
|
|
# `djmdContent.BPM`, which stayed at the old tempo while the deck showed the
|
|
# new one. So that column is Konduktor's to maintain.
|
|
#
|
|
# Edits are BUFFERED and the files are written on save(), so the grid obeys
|
|
# the same "edit in memory, Save writes to disk" contract as everything else
|
|
# — an unsaved grid change must not already be on disk.
|
|
|
|
def current_markers(self, track_id: str) -> list:
|
|
"""The track's grid as a generic marker list (pending edits included)."""
|
|
from . import beatgrid as grid_math
|
|
|
|
grid = self.anlz_grid(track_id)
|
|
if grid is None:
|
|
return []
|
|
return grid_math.markers_from_beats(*grid)
|
|
|
|
def track_duration(self, track_id: str) -> float:
|
|
"""Seconds, for expanding markers back into beats."""
|
|
length = getattr(self.content(track_id), "Length", None)
|
|
if length:
|
|
return float(length)
|
|
grid = self.anlz_grid(track_id)
|
|
if grid and grid[0]:
|
|
return float(grid[0][-1]) + 1.0
|
|
return 0.0
|
|
|
|
def replace_grid(self, track_id: str, markers: list) -> None:
|
|
"""Set the grid to exactly these markers. The one primitive; every
|
|
marker-level command is expressed as a read-modify-replace on top."""
|
|
from . import beatgrid as grid_math
|
|
|
|
for m in markers:
|
|
if m.bpm <= 0:
|
|
raise InvalidCommand(f"A beatgrid marker needs a positive tempo, got {m.bpm}")
|
|
if m.start < 0:
|
|
raise InvalidCommand("A beatgrid marker cannot be before the track starts")
|
|
ordered = sorted(markers, key=lambda m: m.start)
|
|
duration = self.track_duration(track_id)
|
|
beat_nums, bpms, times = grid_math.beats_from_markers(ordered, duration)
|
|
# Buffer as the same (times, bpms) shape the reader returns, so the
|
|
# projection needs no special case for an unsaved grid.
|
|
self._pending_grids[str(track_id)] = (beat_nums, bpms, times)
|
|
self._grid_cache[str(track_id)] = (times, bpms, beat_nums) if times else None
|
|
# TEMPO mirrors the first marker, exactly as Traktor's <TEMPO> does —
|
|
# Rekordbox will not do it for us.
|
|
row = self.content(track_id)
|
|
row.BPM = int(round(ordered[0].bpm * 100)) if ordered else 0
|
|
self._journal.record("grid", "replace" if ordered else "delete", track_id)
|
|
|
|
def audio_changed(self, track_id: str, change) -> None:
|
|
"""The file changed level in place (Normalize): `FileSize` follows, and
|
|
the drawn waveforms are regenerated from the new audio at save (they
|
|
are drawn from the audio's level; cues, grid and phrases stay)."""
|
|
row = self.content(track_id)
|
|
before = row.FileSize
|
|
row.FileSize = int(change.size)
|
|
if change.measured is not None:
|
|
self._pending_waveforms[str(track_id)] = change.measured
|
|
self._journal.record("track", "audio", track_id, "level", before, change.gain_db)
|
|
self._db.flush()
|
|
|
|
def _flush_waveforms(self) -> None:
|
|
"""Write regenerated waveform tags into existing ANLZ files: `.DAT`
|
|
PWAV/PWV2, `.EXT` PWV3/PWV5/PWV4, `.2EX` PWV7/PWV6/PWVC — each replaced
|
|
in place (`AnlzFile.put`), every other tag kept byte for byte."""
|
|
from . import anlz_file, anlz_writer
|
|
|
|
for track_id, measured in list(self._pending_waveforms.items()):
|
|
rel = getattr(self.content(track_id), "AnalysisDataPath", None)
|
|
if not rel:
|
|
continue # no analysis files: rekordbox draws from its own analysis
|
|
dat = self.path.parent / "share" / str(rel).lstrip("/\\")
|
|
ext_tags, two_tags = anlz_writer.waveform_tags(measured.frames.bands)
|
|
plan = [(dat, anlz_writer.preview_tags(measured.columns.rms, measured.columns.brightness),
|
|
("PPTH", "PVBR", "PQTZ")),
|
|
(dat.with_suffix(".EXT"), ext_tags, ("PPTH",)),
|
|
(dat.with_suffix(".2EX"), two_tags, ("PPTH",))]
|
|
for path, tags, after in plan:
|
|
if not path.is_file():
|
|
continue
|
|
parsed = anlz_file.parse_file(path)
|
|
for data in tags:
|
|
parsed.put(data[:4].decode("latin-1"), data, after=after)
|
|
partial = path.with_name(f".{path.name}.konduktor-partial")
|
|
partial.write_bytes(parsed.to_bytes())
|
|
os.replace(partial, path)
|
|
self._pending_waveforms.clear()
|
|
|
|
def _flush_grids(self) -> None:
|
|
"""Write buffered grids into their ANLZ files. Called by save().
|
|
|
|
Only `.DAT`'s `PQTZ` is written — `.EXT`'s extended grid carries
|
|
undecoded bytes, and Rekordbox was verified to read the grid from
|
|
`PQTZ` and to be untroubled by the other being stale.
|
|
"""
|
|
from . import beatgrid as grid_math
|
|
|
|
for track_id, (beat_nums, bpms, times) in list(self._pending_grids.items()):
|
|
rel = getattr(self.content(track_id), "AnalysisDataPath", None)
|
|
if not rel:
|
|
raise InvalidCommand(
|
|
"This track has no analysis file, so it has nowhere to store a beatgrid"
|
|
)
|
|
path = self.path.parent / "share" / str(rel).lstrip("/\\")
|
|
if not path.is_file():
|
|
raise InvalidCommand(f"Analysis file is missing: {path}")
|
|
off = self.time_offset(track_id)
|
|
grid_math.write_pqtz(path, beat_nums, bpms,
|
|
[timebase.to_pioneer(t, off) for t in times])
|
|
self._pending_grids.clear()
|