Fixed Stem track importing. Added remove from collection for Rekordbox

This commit is contained in:
patben8 committed 2026-10-01 11:42:55 +02:00
1 parent badf12b991
commit 5c193e0ab7
12 files changed
+385 -20

No files matched your search

@@ -421,10 +421,12 @@ class RekordboxAdapter:
self._refuse("Adding tracks")
def remove_tracks(self, track_ids: list[str]) -> int:
# Same shape as adding: a track is a djmdContent row plus its cues,
# playlist rows, contentCue/contentFile mirrors and ANLZ files, and
# which of those Rekordbox expects to be deleted together is unmeasured.
self._refuse("Removing tracks")
# What goes with a track was measured in Rekordbox 7 — see the store.
self._require_writable("Removing tracks")
n = self._store.remove_tracks(track_ids)
if n:
self._rebuild()
return n
def apply_stem_swaps(self, swaps, *, add_to_playlist=None):
# Rekordbox does not play native-instruments stem files as stems.
@@ -87,6 +87,7 @@ def capabilities_for(
# rather than mapped onto something approximate.
editable_fields=sorted(editable_fields or []),
media_kinds=["audio"],
removable=True,
artwork=False,
artwork_note=None,
),
+149 -1
View File
@@ -37,7 +37,13 @@ from sqlalchemy import func, select, text
from sqlalchemy.exc import OperationalError
from sqlalchemy.orm import joinedload
from ...core.adapter import InvalidCommand, LibraryNotSupported, NotFound, SaveOutcome
from ...core.adapter import (
InvalidCommand,
LibraryNotSupported,
NotFound,
SaveOutcome,
Unsupported,
)
from ...core.edit_journal import EditJournal
from ...core.pathmap import PathMapping
from . import timebase
@@ -45,6 +51,9 @@ from .cue_types import beat_loop_size, kind_for, role_and_slot
log = logging.getLogger(__name__)
# Where a track's analysis files live, as `contentFile.Path` spells it.
_ANLZ_ROOT = "/PIONEER/USBANLZ/"
@contextmanager
def rekordbox_probe_suppressed():
@@ -85,6 +94,9 @@ class RekordboxStore:
# 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]] = {}
# 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()
self._load()
# ---- open ------------------------------------------------------------
@@ -117,6 +129,7 @@ class RekordboxStore:
self.close()
self._journal = EditJournal()
self._pending_grids.clear()
self._pending_file_removals.clear()
self._load()
def close(self) -> None:
@@ -526,6 +539,140 @@ class RekordboxStore:
self._journal.record("playlist", "entries", playlist.Name, after=len(track_ids))
return len(track_ids)
# ---- 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:
@@ -551,6 +698,7 @@ class RekordboxStore:
# been committed to the database either.
self._flush_grids()
self._commit()
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.
+9 -1
View File
@@ -51,7 +51,7 @@ from ...core.edit_journal import EditJournal
from ...core.pathmap import common_dir_prefix
from ...core.pathmap import PathMapping
from ...core.relocate import PathGroup
from ...core.stem_file import NML_STEMS_JSON
from ...core.stem_file import NML_STEMS_JSON, nml_stems_for
from ...schemas import PlaylistNode
from . import beatgrid, timebase
from .locations import os_path_to_location, resolve_path
@@ -429,7 +429,14 @@ class TraktorStore:
and ``loudness``. Both are outputs of Traktor's own analysis and cannot
be computed here; Traktor re-analyses a track that has none. Writing a
plausible-looking fingerprint would be inventing data.
A stem FILE gets ``<STEMS>``, rendered from its own ``stem`` box as
Traktor renders it: that element is what makes the entry a stem track
(its playlist keys ``TYPE="STEM"``, the Type column), and without it a
stem file added here read as plain audio.
"""
# Read before the lock: it opens the file.
stems = nml_stems_for(audio_path)
with self._lock:
volume, dir_, file = os_path_to_location(Path(audio_path))
key = f"{volume}{dir_}{file}"
@@ -473,6 +480,7 @@ class TraktorStore:
# `replace_grid` overwrites it from the markers when they land.
tempo=Tempotype(bpm=float(bpm)) if bpm else None,
cue_v2=[],
stems=Stemstype(stems=stems) if stems else None,
)
self._nml.collection.entry.append(entry)
self._entry_by_key[key] = entry
+4 -2
View File
@@ -31,6 +31,7 @@ from pathlib import Path
from .capabilities import Capabilities, SaveCapabilities, TrackCapabilities
from .model import PlaylistNode, Track, TrackCues
from .places import is_hidden
from .stem_file import is_stem_file
log = logging.getLogger(__name__)
@@ -59,7 +60,8 @@ def _bpm(tags) -> float | None:
def read_track(path: Path) -> Track:
"""Project one audio file. Never raises: an unreadable tag is an untitled track."""
track = Track(id=str(path), title=path.stem, filepath=str(path))
track = Track(id=str(path), title=path.stem, filepath=str(path),
media_kind="stem" if is_stem_file(path) else "audio")
try:
import mutagen
@@ -112,7 +114,7 @@ def capabilities_for(folder: Path) -> Capabilities:
platform="folder",
writable=False,
readonly_cause="not_in_library",
tracks=TrackCapabilities(editable_fields=[], artwork=False),
tracks=TrackCapabilities(editable_fields=[], artwork=False, media_kinds=["audio", "stem"]),
save=SaveCapabilities(
app_name="Files",
library_label=folder.name or str(folder),
+40 -1
View File
@@ -36,6 +36,7 @@ Things that were measured and are easy to get wrong:
from __future__ import annotations
import fractions
import json
import struct
import sys
from dataclasses import dataclass
@@ -373,6 +374,43 @@ def stem_layout(path: Path | str) -> list[dict] | None:
for i, s in enumerate(stems)]
def _traktor_json(v) -> str:
if isinstance(v, bool):
return "true" if v else "false"
if isinstance(v, float):
return str(int(v)) if v.is_integer() else "%.16g" % v
if isinstance(v, (int, str)) or v is None:
return json.dumps(v, ensure_ascii=False)
if isinstance(v, list):
return "[" + ",".join(_traktor_json(x) for x in v) + "]"
if isinstance(v, dict):
return "{" + ",".join(f"{json.dumps(k, ensure_ascii=False)}:{_traktor_json(v[k])}"
for k in sorted(v)) + "}"
raise TypeError(f"not JSON: {v!r}")
def traktor_stems_json(box: bytes) -> str:
"""A `stem` box payload as Traktor writes it into `<STEMS STEMS="…">`: keys
sorted, no spaces, a whole float as an integer, any other to 16 significant
digits. Measured: it reproduces Traktor's value for every stem file on this
machine, and re-renders each of the 3,678 `<STEMS>` in the user's big
collection unchanged — but all of those carry ONE layout (NI's defaults),
so a box with other values is the same rule extrapolated. Raises ValueError
on a box that is not JSON."""
return _traktor_json(json.loads(box))
def nml_stems_for(path: Path | str) -> str | None:
"""The `<STEMS>` value a library entry for this file should carry, or None
when it is not a playable stem file (the test `stem_layout` applies)."""
if stem_layout(path) is None:
return None
try:
return traktor_stems_json(read_stem_box(path))
except (OSError, ValueError, TypeError):
return None
def extract_stream(path: Path | str, stream: int, fp) -> None:
"""Copy audio stream `stream` (0 = the mix, 1-4 the stems) into its own MP4,
written to the file object `fp` — packets COPIED, never re-encoded.
@@ -404,5 +442,6 @@ def extract_stream(path: Path | str, stream: int, fp) -> None:
__all__ = [
"DEMUCS_ORDER", "NML_STEMS_JSON", "SR", "STEM_BOX_JSON", "STEM_NAMES", "Source",
"StemFileError", "Written", "add_stem_box", "build", "choose_bitrate", "decode",
"default_encoder", "extract_stream", "is_stem_file", "read_stem_box", "stem_layout", "stem_target_name", "verify",
"default_encoder", "extract_stream", "is_stem_file", "nml_stems_for", "read_stem_box", "stem_layout",
"stem_target_name", "traktor_stems_json", "verify",
]