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",
]
-3
View File
@@ -337,9 +337,6 @@ with tempfile.TemporaryDirectory() as d:
print("== what Rekordbox genuinely cannot do still refuses, with a reason ==")
commands = {
"set_cover_art": lambda: adapter.set_cover_art(sample.id, b"", "image/jpeg"),
# A track spans rows in several tables plus ANLZ files; which of them
# Rekordbox expects deleted together is unmeasured.
"remove_tracks": lambda: adapter.remove_tracks([sample.id]),
# Rekordbox genuinely has no per-track grid lock, unlike Traktor's LOCK.
"set_grid_lock": lambda: adapter.set_grid_lock(sample.id, True),
"remap_locations": lambda: adapter.remap_locations(None),
+90
View File
@@ -418,5 +418,95 @@ with tempfile.TemporaryDirectory() as d:
str(fields.get("BPM")))
adapter.close()
# ---- I: removing a track does what Rekordbox 7 itself does -----------
# Measured 2026-10-01 by removing a track in Rekordbox and diffing: its
# rows are DELETED (not flagged) from djmdContent, djmdCue, contentCue,
# contentFile, djmdMixerParam and djmdSongPlaylist, the playlist row is
# left alone, and the files contentFile lists go with their folders.
print("== I: removing a track deletes exactly what Rekordbox deletes ==")
from konduktor.core.adapter import Unsupported # noqa: E402
clean_copy(REAL, work)
before = dump(work)
measured = ("djmdCue", "contentCue", "contentFile", "djmdMixerParam", "djmdSongPlaylist")
sampler = {str(r["ContentID"]) for r in before.get("djmdSongSampler", {}).values()}
songs = before["djmdSongPlaylist"].values()
# The FIRST entry of the longest playlist, so the entries after it must
# be renumbered.
by_list: dict[str, list] = {}
for r in songs:
by_list.setdefault(str(r["PlaylistID"]), []).append(r)
longest = max(by_list.values(), key=len, default=[])
first = min(longest, key=lambda r: r["TrackNo"]) if len(longest) > 1 else None
if first is None or str(first["ContentID"]) in sampler:
print(" (skipped: no playlist with two entries to remove from)")
else:
victim = str(first["ContentID"])
playlist_id = str(first["PlaylistID"])
listed = [r["Path"] for r in before["contentFile"].values()
if str(r["ContentID"]) == victim]
files = [p for p in listed if p.startswith("/PIONEER/USBANLZ/")]
art = [p for p in listed if p.startswith("/PIONEER/Artwork/")]
adapter = RekordboxAdapter(work)
n_tracks = len(adapter.tracks)
check("remove_tracks reports one track removed", adapter.remove_tracks([victim]) == 1)
check("it leaves the projection at once",
adapter.track(victim) is None and len(adapter.tracks) == n_tracks - 1)
check("and its playlist", victim not in adapter.playlist_entries(playlist_id))
check("the adapter is dirty", adapter.dirty is True)
check("nothing is on disk before save", not diff(before, dump(work)))
check("its analysis files are still there before save",
all((Path(d) / "share" / p.lstrip("/")).is_file() for p in files))
adapter.save()
changes = diff(before, dump(work))
expected_deletes = {("djmdContent", victim)} | {
(t, pk) for t in measured for pk, r in before[t].items()
if str(r.get("ContentID")) == victim
}
deletes = {(t, pk) for t, pk, kind, _ in changes if kind == "DELETE"}
check("exactly the measured rows are deleted", deletes == expected_deletes,
f"extra {sorted(deletes - expected_deletes)} missing "
f"{sorted(expected_deletes - deletes)}")
check("nothing is inserted", not [c for c in changes if c[2] == "INSERT"])
updates = {(t, pk): f for t, pk, kind, f in changes if kind == "UPDATE"}
later = {pk for pk, r in before["djmdSongPlaylist"].items()
if str(r["PlaylistID"]) == playlist_id and r["TrackNo"] > first["TrackNo"]}
check("only the counter and the later entries' TrackNo move",
set(updates) == {("agentRegistry", "localUpdateCount")}
| {("djmdSongPlaylist", pk) for pk in later}, describe(changes))
check("each later entry moves up by one",
all(updates[("djmdSongPlaylist", pk)]["TrackNo"][1]
== before["djmdSongPlaylist"][pk]["TrackNo"] - 1 for pk in later))
check("the playlist row itself is left alone",
("djmdPlaylist", playlist_id) not in updates)
check("the track's analysis files are deleted",
not any((Path(d) / "share" / p.lstrip("/")).exists() for p in files), str(files))
check("and their emptied folder",
not any((Path(d) / "share" / p.lstrip("/")).parent.exists() for p in files))
# Unmeasured (the measured track had none), so left in place.
check("its artwork is left alone",
all((Path(d) / "share" / p.lstrip("/")).is_file() for p in art))
check("the analysis root is kept",
(Path(d) / "share" / "PIONEER" / "USBANLZ").is_dir())
adapter.close()
reopened = RekordboxAdapter(work)
check("the track is gone after a reopen", reopened.track(victim) is None)
reopened.close()
# A table that was EMPTY in the measured library is not guessed at.
if sampler:
clean_copy(REAL, work)
adapter = RekordboxAdapter(work)
target = next(iter(sampler))
try:
adapter.remove_tracks([adapter.tracks[0].id, target])
check("a track in the Sampler is refused", False)
except Unsupported as ex:
check("a track in the Sampler is refused", "Sampler" in str(ex), str(ex))
check("and the whole batch changed nothing",
adapter.dirty is False and adapter.track(target) is not None)
adapter.close()
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+20
View File
@@ -108,6 +108,26 @@ if real_nml.is_file():
check("the NML value is the one Traktor wrote on every stem entry", values == {sf.NML_STEMS_JSON}, str(len(values)))
else:
print(" (skipped: the real collection is not on this machine)")
# How a stem file that Konduktor did NOT write gets its `<STEMS>` when added:
# rendered from its own box by Traktor's rule.
check("Traktor's rendering rule turns the box literal into the NML literal",
sf.traktor_stems_json(sf.STEM_BOX_JSON) == sf.NML_STEMS_JSON)
check("…and keeps other names, colours and values (keys sorted, whole floats as integers)",
sf.traktor_stems_json(b'{"version": 1, "stems": [{"name": "Kick \\u00e9", "color": "#010203"}], '
b'"x": {"b": 2.5, "a": 3.0, "c": true}}')
== '{"stems":[{"color":"#010203","name":"Kick é"}],"version":1,"x":{"a":3,"b":2.5,"c":true}}')
nml_stem_entries = {}
for n in (real_nml, Path.home() / "Downloads/collection.nml"):
if n.is_file():
for file, value in re.findall(r'FILE="([^"]+)"(?:(?!</ENTRY>).)*?<STEMS STEMS="([^"]*)"',
n.read_text(encoding="utf-8"), re.S):
nml_stem_entries[html.unescape(file)] = html.unescape(value)
pairs = [(p, nml_stem_entries[p.name]) for p in commercial if p.name in nml_stem_entries]
if pairs:
check(f"…and gives exactly what Traktor wrote for {len(pairs)} stem files in its collections",
all(sf.nml_stems_for(p) == v for p, v in pairs))
else:
print(" (skipped: no stem file with a Traktor entry on this machine)")
print("== 2. decode: mono level, resampling does not move time ==")
m = np.zeros((1, 44100), np.float32)
+38
View File
@@ -16,10 +16,13 @@ stems are distinct scalings of the mix, so each served stem can be told apart.
"""
from __future__ import annotations
import html
import os
import re
import shutil
import sys
import tempfile
import time
import warnings
from pathlib import Path
@@ -148,6 +151,41 @@ with TestClient(main.app) as c:
got = ROOT / "folder-1.m4a"
got.write_bytes(r.content)
check("…and serves them", r.status_code == 200 and np.array_equal(decode(got), decode(stem, 2)))
kinds = {t["id"]: t["media_kind"] for t in listing.json()["tracks"]}
check("the listing marks the stem file as a stem track and the MP3 as audio",
kinds.get(str(stem)) == "stem" and kinds.get(str(plain)) == "audio", str(kinds))
print("== adding a stem file to the collection ==")
extra_dir = ROOT / "More"
extra_dir.mkdir()
extra = extra_dir / "Other.stem.m4a"
shutil.copy2(stem, extra)
extra_plain = make_mp3(extra_dir / "Other.mp3", seed=9)
assert c.get("/api/folder/tracks", params={"path": str(extra_dir)}).status_code == 200
pl_id = c.post("/api/playlists", json={"name": "Stem Adds"}).json()["id"]
job = c.post("/api/folder/add", json={"track_ids": [str(extra), str(extra_plain)],
"mode": "reference", "playlist_id": pl_id}).json()
while job["state"] == "running":
time.sleep(0.05)
job = c.get(f"/api/jobs/{job['id']}").json()
check("(setup) the add finishes", job["state"] == "done", str(job))
new_stem, new_plain = job["result"]["track_ids"]
kinds = {t["id"]: t["media_kind"] for t in c.get("/api/tracks", params={"limit": 20000}).json()["items"]}
check("the added stem file is a stem track, the MP3 beside it audio",
kinds.get(new_stem) == "stem" and kinds.get(new_plain) == "audio", f"{kinds.get(new_stem)} {kinds.get(new_plain)}")
saved = work.read_text(encoding="utf-8")
def entry_of(name: str) -> str:
at = saved.find(f'FILE="{name}"')
return saved[at:saved.find("</ENTRY>", at)] if at >= 0 else ""
m = re.search(r'<STEMS STEMS="([^"]*)"', entry_of(extra.name))
check("…its saved ENTRY carries <STEMS>, rendered as Traktor renders that file's box",
m is not None and html.unescape(m.group(1)) == sf.NML_STEMS_JSON, entry_of(extra.name)[:300])
check("…the MP3's carries none", entry_of(extra_plain.name) != "" and "<STEMS" not in entry_of(extra_plain.name))
check('…and the playlist keys the stem file TYPE="STEM", the MP3 TYPE="TRACK"',
re.search(r'<PRIMARYKEY TYPE="STEM" KEY="[^"]*Other\.stem\.m4a"', saved) is not None
and re.search(r'<PRIMARYKEY TYPE="TRACK" KEY="[^"]*Other\.mp3"', saved) is not None)
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)