Implemented importing into Rekordbox

This commit is contained in:
patben8 committed 2026-10-01 13:12:10 +02:00
1 parent 5c193e0ab7
commit d7f8768d4c
19 files changed
+793 -113

No files matched your search

@@ -251,7 +251,7 @@ class OneLibraryAdapter:
def _refuse(self, what: str):
raise Unsupported(self._readonly_reason(what))
def add_tracks(self, items: list) -> list[str]:
def add_tracks(self, items: list, *, checkpoint=None) -> list[str]:
self._refuse("Adding tracks")
def remove_tracks(self, track_ids: list[str]) -> int:
@@ -27,7 +27,7 @@ from ...core.model import GridMarker, PlaylistNode, Track, TrackCues
from ...core.pathmap import PathMapping, common_dir_prefix
from ...core.query import TrackIndex
from . import capabilities as caps
from . import palette, projection
from . import palette, projection, timebase
from .store import RekordboxStore
@@ -412,13 +412,84 @@ class RekordboxAdapter:
if self._cloud_synced:
raise Unsupported(self._readonly_reason(what))
def add_tracks(self, items: list) -> list[str]:
# Not a refusal in principle — Rekordbox could receive imported
# tracks — but adding one means a djmdContent row, its lookup-table
# foreign keys, a USN, and an ANLZ file built from scratch, which
# is unexplored (see the export handoff). Traktor is the only
# import target for now.
self._refuse("Adding tracks")
def add_tracks(self, items: list, *, checkpoint=None) -> list[str]:
"""Add tracks that came from somewhere else, with their prep.
Rekordbox keeps the beatgrid AND the waveforms in per-track analysis
files, and shows neither grid nor cues for a track without them — so
unlike Traktor, which re-analyses on load, every file is decoded here.
A file that brings no grid gets one from Konduktor's own detector
(decided 2026-10-01: a track should arrive ready to prep).
Two phases, and the split is the point. FIRST every file is decoded and
analysed, which is slow and may be cancelled through `checkpoint` —
before the library is touched, so a cancel leaves it as it was. THEN
each row is added and its grid and cues replayed through the ordinary
store commands (`replace_grid`, `set_cue`), so an added track inherits
their conventions and tests rather than growing a second copy.
Nothing is lost on the way in: Rekordbox has memory cues and coloured
cues, so both cross as themselves. A hot cue whose pad is out of the
bank or already taken becomes a memory cue at the same position rather
than being dropped.
"""
from ...core import audio_tags, grid_detect, waveform
self._require_writable("Adding tracks")
held = set(self._store.all_audio_paths())
prepared = []
total = len(items)
for n, item in enumerate(items, start=1):
audio = Path(item.audio_path)
if checkpoint is not None:
checkpoint(f"Analysing {item.track.title or audio.name} ({n}/{total})",
step=n, of=total)
if not audio.is_file():
raise InvalidCommand(f"No audio file at {audio}")
if str(audio) in held:
raise InvalidCommand(f"The library already holds {audio}")
held.add(str(audio))
samples = waveform.decode(audio)
measured = waveform.analyse_samples(samples, lead=timebase.offset(audio))
markers = list(item.cues.grid_markers) if item.cues else []
if not markers and samples is not None:
try:
found = grid_detect.detect_grid(str(audio), y=samples, sr=waveform.SR)
markers = [GridMarker(start=found.anchor, bpm=found.bpm)]
except ValueError:
pass # no pulse to fit (a one-shot, silence): no grid
art = item.art or audio_tags.read_cover(audio)
prepared.append((item, audio, measured, markers, art[0] if art else None))
added: list[str] = []
for item, audio, measured, markers, art in prepared:
track_id = self._store.add_track(
audio, item.track, measured=measured, with_grid=bool(markers), art=art)
self._index.add(projection.to_track(self._store.content(track_id), ()))
if markers:
self._store.replace_grid(track_id, markers)
if item.cues is not None:
self._place_imported_cues(track_id, item.cues)
self._refresh(track_id)
added.append(track_id)
return added
def _place_imported_cues(self, track_id: str, cues) -> None:
"""Hot cues on their own pads; memory cues — and a hot cue with no
free pad — as memory cues. Colour as the nearest palette swatch."""
taken: set[int] = set()
for cue in sorted(cues.cues or [], key=lambda c: c.start):
cue_type = "loop" if getattr(cue, "length", 0) else "cue"
code, _rgb = palette.code_for(cue.color)
common = dict(start_sec=cue.start, cue_type=cue_type,
length_sec=getattr(cue, "length", 0.0) or 0.0,
name=getattr(cue, "name", None), color_code=code or None)
slot = cue.slot if cue.role == "hotcue" else None
if slot is not None and 0 <= slot < caps.HOTCUE_SLOTS and slot not in taken:
self._store.set_cue(track_id, slot=slot, **common)
taken.add(slot)
else:
self._store.add_memory_cue(track_id, **common)
def remove_tracks(self, track_ids: list[str]) -> int:
# What goes with a track was measured in Rekordbox 7 — see the store.
@@ -404,13 +404,18 @@ def cue_tags(cues: list[dict], *, extended: bool) -> list[bytes]:
_FILE_HEADER_LEN = 28
def write_anlz(path: Path, tags: list[bytes]) -> Path:
"""Assemble and write an ANLZ file from built tag bytes."""
path.parent.mkdir(parents=True, exist_ok=True)
def anlz_bytes(tags: list[bytes]) -> bytes:
"""Assemble an ANLZ file from built tag bytes."""
body = b"".join(tags)
header = struct.pack(
">4sIIIIII", b"PMAI", _FILE_HEADER_LEN, _FILE_HEADER_LEN + len(body),
FILE_HEADER_U1, FILE_HEADER_U2, FILE_HEADER_U3, 0,
)
path.write_bytes(header + body)
return header + body
def write_anlz(path: Path, tags: list[bytes]) -> Path:
"""Assemble and write an ANLZ file from built tag bytes."""
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(anlz_bytes(tags))
return path
@@ -88,6 +88,7 @@ def capabilities_for(
editable_fields=sorted(editable_fields or []),
media_kinds=["audio"],
removable=True,
addable=True,
artwork=False,
artwork_note=None,
),
+18 -83
View File
@@ -58,8 +58,7 @@ from sqlalchemy import text
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
from ...core.cue_colors import effective_color
from . import anlz_writer as W
from . import artwork, palette
from . import new_content, palette
from . import timebase
from .beatgrid import beats_from_markers
from .capabilities import capabilities_for
@@ -82,15 +81,8 @@ SEED = _FIXTURES / "seed.sql"
#: Rekordbox counts cue positions in frames at 150 fps, not milliseconds.
FRAMES_PER_SECOND = 150
#: `djmdContent.ContentLink` — NOT optional, and a bit field. Measured by giving
#: five tracks of a Konduktor-written library different values and loading it
#: in Rekordbox 7: with it NULL the song-list preview is plain blue with a "?"
#: beside CUE; any value colours the preview; the 0x200000 bit (0x2C060E here,
#: 0x0C060E without it) clears the "?"; and 0x3D060E — what the real library's
#: MP3/M4A tracks carry — adds two more bits that draw an extra badge, most
#: likely claiming phrase/vocal analysis this exporter does not write. So the
#: value that claims only what is written: 0x2C060E.
CONTENT_LINK = 2885134
#: `djmdContent.ContentLink` — see `new_content`, where its bits are measured.
CONTENT_LINK = new_content.CONTENT_LINK
#: Rekordbox's playlist side file, beside master.db. It lists every playlist
#: node with a `Timestamp` matching the row's `updated_at` (ms); a playlist the
@@ -319,27 +311,7 @@ class RekordboxExporter:
@staticmethod
def _lookup(db, kind: str, name: str | None):
"""Find-or-create a lookup row, returning its id.
`djmdKey` is the odd one out twice over: its name column is `ScaleName`,
not `Name`, and pyrekordbox has no `add_key`. So keys are inserted
directly, with a `Seq` that keeps them in wheel order in Rekordbox's UI.
"""
if not name:
return None
if kind == "key":
found = db.get_key(ScaleName=name).first()
if found is not None:
return found.ID
return _insert_key(db, name)
found = {"artist": db.get_artist, "album": db.get_album,
"genre": db.get_genre, "label": db.get_label}[kind](Name=name).first()
if found is not None:
return found.ID
created = {"artist": db.add_artist, "album": db.add_album,
"genre": db.add_genre, "label": db.add_label}[kind](name)
db.flush()
return created.ID
return new_content.lookup(db, kind, name)
# ---- analysis ---------------------------------------------------------------
@@ -350,24 +322,15 @@ class RekordboxExporter:
and the file on disk have to agree — so the same derivation is used here
rather than a path of our own choosing.
"""
track_uuid = str(content.UUID)
# Rekordbox derives these two levels from the track's UUID, and the
# column and the file have to agree — so the same derivation is used.
rel = f"/PIONEER/USBANLZ/{track_uuid[:3]}/{track_uuid[3:]}/ANLZ0000.DAT"
rel = new_content.anlz_rel(str(content.UUID))
content.AnalysisDataPath = rel
content.Analysed = 105 # what a rekordbox-analysed track carries
content.AnalysisUpdated = 1
db.flush()
# The same three files as a rekordbox-analysed track. The `.DAT` needs
# PVBR and the preview waveforms before rekordbox shows a grid at all
# (measured on a OneLibrary stick; the same Pioneer file here); the
# `.EXT`/`.2EX` carry the drawn waveforms. Cue lists are present but
# EMPTY — master.db keeps cues in djmdCue.
off = timebase.offset(item.destination)
measured = item.waveform(lead=off)
path = str(item.destination)
tags = [W.path_tag(path), W.vbr_tag(W.mp3_samples(item.destination))]
beats = None
markers = item.cues.grid_markers if item.cues else []
if markers:
duration = ((measured.duration if measured else 0.0)
@@ -377,26 +340,18 @@ class RekordboxExporter:
# Onto rekordbox's clock (~25 ms behind on MP3/AAC — `timebase`).
# The cues need no such line: they are replayed through
# `set_cue`, which applies the same offset itself.
tags.append(W.beatgrid_tag(
[(n, bpm, timebase.to_pioneer(t, off)) for n, bpm, t in zip(nums, bpms, times)]))
if measured:
tags += W.preview_tags(measured.columns.rms, measured.columns.brightness)
ext_waves, two_ex = W.waveform_tags(measured.frames.bands)
else:
tags += W.flat_preview_tags()
ext_waves, two_ex = [], []
tags += W.cue_tags([], extended=False)
beats = [(n, bpm, timebase.to_pioneer(t, off))
for n, bpm, t in zip(nums, bpms, times)]
# AnalysisDataPath is rooted at a `share` directory BESIDE master.db,
# not at the library root — the read path joins it that way, and writing
# it anywhere else produces a track whose grid silently reads as empty.
dat = root / "share" / rel.lstrip("/")
written = [
W.write_anlz(dat, tags),
W.write_anlz(dat.with_suffix(".EXT"), [W.path_tag(path), *ext_waves[:1],
*W.cue_tags([], extended=True), *ext_waves[1:]]),
]
if two_ex:
written.append(W.write_anlz(dat.with_suffix(".2EX"), [W.path_tag(path), *two_ex]))
written = []
for suffix, data in new_content.anlz_files(item.destination, measured, beats).items():
target = dat.with_suffix(suffix)
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(data)
written.append(target)
return written
# ---- artwork ------------------------------------------------------------------
@@ -412,17 +367,14 @@ class RekordboxExporter:
rooted at `share/` like `AnalysisDataPath`. All measured on a real
Rekordbox 7 library.
"""
if not item.art:
files = new_content.artwork_files(item.art[0] if item.art else None)
if files is None:
return []
jpegs = artwork.library_jpegs(item.art[0])
if jpegs is None:
return []
track_uuid = str(content.UUID)
rel = f"/PIONEER/Artwork/{track_uuid[:3]}/{track_uuid[3:]}"
rel = new_content.artwork_rel(str(content.UUID))
folder = root / "share" / rel.lstrip("/")
folder.mkdir(parents=True, exist_ok=True)
written = []
for name, data in zip(("artwork.jpg", "artwork_m.jpg", "artwork_s.jpg"), jpegs):
for name, data in files.items():
(folder / name).write_bytes(data)
written.append(folder / name)
content.ImagePath = f"{rel}/artwork.jpg"
@@ -462,20 +414,3 @@ class RekordboxExporter:
db.add_to_playlist(playlist, content)
db.flush()
def _insert_key(db, name: str) -> str:
"""A `djmdKey` row. Raw SQL for the same reason the registry row is: the
ORM's DateTime binder raises on the NULLs a real row carries."""
from pyrekordbox.masterdb import models
now = datetime.now().isoformat(sep=" ", timespec="milliseconds")
seq = (db.query(models.DjmdKey).count() or 0) + 1
key_id = str(uuidlib.uuid4().int % 2_147_483_647)
db.session.execute(
text('INSERT INTO "djmdKey" (ID, ScaleName, Seq, UUID, created_at, '
"updated_at) VALUES (:id, :name, :seq, :uuid, :now, :now)"),
{"id": key_id, "name": name, "seq": seq,
"uuid": str(uuidlib.uuid4()), "now": now},
)
db.flush()
return key_id
@@ -0,0 +1,138 @@
"""A NEW track's rows and files in a `master.db` library.
Shared by the two places a track is created rather than edited: the Rekordbox
Library exporter (a `master.db` from nothing) and `RekordboxStore.add_tracks`
(a track added to the user's own library). One definition, because a track
row, its lookups and its analysis files are the same thing in both, and two
copies would drift.
What a track Rekordbox itself adds looks like was MEASURED (two files dragged
into Rekordbox 7.2's collection, 2026-10-01, every row and file diffed): a
`djmdContent` row, three ANLZ files plus a `.3EX`, the embedded cover as three
JPEGs, one `contentFile` row per file (its `Hash` the file's MD5), and its own
analysis results — key, mixer gain, phrases — which nothing here can produce.
"""
from __future__ import annotations
import uuid as uuidlib
from datetime import datetime
from pathlib import Path
from sqlalchemy import text
from . import anlz_writer as W
from . import artwork
#: `djmdContent.ContentLink` — NOT optional, and a bit field. Measured by giving
#: five tracks of a Konduktor-written library different values and loading it
#: in Rekordbox 7: with it NULL the song-list preview is plain blue with a "?"
#: beside CUE; any value colours the preview; the 0x200000 bit (0x2C060E here,
#: 0x0C060E without it) clears the "?"; and 0x3D060E — what the real library's
#: MP3/M4A tracks carry, and what Rekordbox writes for a track it analyses
#: itself — adds two more bits that draw an extra badge, most likely claiming
#: phrase/vocal analysis Konduktor does not write. So the value that claims
#: only what is written: 0x2C060E.
CONTENT_LINK = 2885134
def anlz_rel(track_uuid: str) -> str:
"""`djmdContent.AnalysisDataPath` for a track. Rekordbox derives it from
the track's UUID, and the column and the file have to agree."""
return f"/PIONEER/USBANLZ/{track_uuid[:3]}/{track_uuid[3:]}/ANLZ0000.DAT"
def artwork_rel(track_uuid: str) -> str:
"""The track's artwork FOLDER — the same UUID split as its analysis."""
return f"/PIONEER/Artwork/{track_uuid[:3]}/{track_uuid[3:]}"
def anlz_files(audio: Path, measured, beats: list | None) -> dict[str, bytes]:
"""The analysis files for a track, by suffix: `.DAT`, `.EXT`, `.2EX`.
The same files as a rekordbox-analysed track. The `.DAT` needs PVBR and the
preview waveforms before rekordbox shows a grid at all (measured on a
OneLibrary stick; the same Pioneer file here); the `.EXT`/`.2EX` carry the
drawn waveforms. Cue lists are present but EMPTY — master.db keeps cues in
djmdCue. `measured` is `waveform.analyse`'s result (None: flat previews).
`beats` is `(beat-in-bar, bpm, seconds)` ON REKORDBOX'S CLOCK; None writes
no `PQTZ`, and `[]` an empty one for `write_pqtz` to fill later.
"""
path = str(audio)
tags = [W.path_tag(path), W.vbr_tag(W.mp3_samples(audio))]
if beats is not None:
tags.append(W.beatgrid_tag(beats))
if measured:
tags += W.preview_tags(measured.columns.rms, measured.columns.brightness)
ext_waves, two_ex = W.waveform_tags(measured.frames.bands)
else:
tags += W.flat_preview_tags()
ext_waves, two_ex = [], []
tags += W.cue_tags([], extended=False)
out = {
".DAT": W.anlz_bytes(tags),
".EXT": W.anlz_bytes([W.path_tag(path), *ext_waves[:1],
*W.cue_tags([], extended=True), *ext_waves[1:]]),
}
if two_ex:
out[".2EX"] = W.anlz_bytes([W.path_tag(path), *two_ex])
return out
def artwork_files(art: bytes | None) -> dict[str, bytes] | None:
"""The cover as a rekordbox-managed track carries it, by file name.
`artwork.jpg` (the cover, fit to 800 px), `artwork_m.jpg` (240) and
`artwork_s.jpg` (80), the last two letterboxed square; `djmdContent.
ImagePath` names `artwork.jpg`. All measured on a real Rekordbox 7 library.
None when there is no art or it cannot be read.
"""
if not art:
return None
jpegs = artwork.library_jpegs(art)
if jpegs is None:
return None
return dict(zip(("artwork.jpg", "artwork_m.jpg", "artwork_s.jpg"), jpegs))
def lookup(db, kind: str, name: str | None):
"""Find-or-create a lookup row, returning its id.
Lookups are foreign keys; pyrekordbox's `add_*` RAISES on an existing name,
so every one is find-or-create — the same rule the in-place adapter follows.
`djmdKey` is the odd one out twice over: its name column is `ScaleName`,
not `Name`, and pyrekordbox has no `add_key`. So keys are inserted
directly, with a `Seq` that keeps them in wheel order in Rekordbox's UI.
"""
if not name:
return None
if kind == "key":
found = db.get_key(ScaleName=name).first()
if found is not None:
return found.ID
return insert_key(db, name)
found = {"artist": db.get_artist, "album": db.get_album,
"genre": db.get_genre, "label": db.get_label}[kind](Name=name).first()
if found is not None:
return found.ID
created = {"artist": db.add_artist, "album": db.add_album,
"genre": db.add_genre, "label": db.add_label}[kind](name)
db.flush()
return created.ID
def insert_key(db, name: str) -> str:
"""A `djmdKey` row. Raw SQL: the ORM's DateTime binder raises on the NULLs
a real row carries."""
from pyrekordbox.masterdb import models
now = datetime.now().isoformat(sep=" ", timespec="milliseconds")
seq = (db.query(models.DjmdKey).count() or 0) + 1
key_id = str(uuidlib.uuid4().int % 2_147_483_647)
db.session.execute(
text('INSERT INTO "djmdKey" (ID, ScaleName, Seq, UUID, created_at, '
"updated_at) VALUES (:id, :name, :seq, :uuid, :now, :now)"),
{"id": key_id, "name": name, "seq": seq,
"uuid": str(uuidlib.uuid4()), "now": now},
)
db.flush()
return key_id
+172 -4
View File
@@ -51,6 +51,33 @@ from .cue_types import 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/"
@@ -97,6 +124,9 @@ class RekordboxStore:
# 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 ------------------------------------------------------------
@@ -130,6 +160,7 @@ class RekordboxStore:
self._journal = EditJournal()
self._pending_grids.clear()
self._pending_file_removals.clear()
self._pending_new_files.clear()
self._load()
def close(self) -> None:
@@ -532,13 +563,140 @@ class RekordboxStore:
.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.remove_from_playlist(playlist, song)
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
from .projection import render_key
audio = Path(audio)
if not audio.is_file():
raise InvalidCommand(f"No audio file at {audio}")
t = self._tables
if self._db.session.query(t.DjmdContent).filter_by(FolderPath=str(audio)).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)
# Rendered from the wheel, never copied: the source's notation is not
# Rekordbox's ("10m" is "Cm" here).
content.KeyID = new_content.lookup(
self._db, "key", render_key(track.key_wheel, track.key_mode))
content.ContentLink = new_content.CONTENT_LINK
track_uuid = str(content.UUID)
rel = new_content.anlz_rel(track_uuid)
content.AnalysisDataPath = rel
content.Analysed = 105 # what a rekordbox-analysed track carries
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
@@ -695,9 +853,19 @@ class RekordboxStore:
"""
summary = self._journal.summary()
# Files first: if an analysis file cannot be written, nothing should have
# been committed to the database either.
self._flush_grids()
self._commit()
# 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_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
@@ -173,7 +173,7 @@ class TraktorAdapter:
return result
# ---- adding tracks ----------------------------------------------------
def add_tracks(self, items: list) -> list[str]:
def add_tracks(self, items: list, *, checkpoint=None) -> list[str]:
"""Add tracks that came from somewhere else, with their prep.
Two steps, and the split is the point. The store creates a bare ENTRY —
@@ -195,6 +195,7 @@ class TraktorAdapter:
type, so a free RGB value has nowhere to go.
Returns the new track ids, in the order the items were given.
`checkpoint` is unused: nothing here is slow (Traktor analyses on load).
"""
added: list[str] = []
for item in items:
@@ -62,6 +62,7 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
editable_fields=sorted(editable_fields),
media_kinds=["audio", "stem"],
removable=True,
addable=True,
stem_convertible=True,
# `.mp4` covers stem files (`.stem.mp4`). Traktor also reads WMA,
# but only on Windows, and a file added on one OS must play on both.
+12 -1
View File
@@ -73,6 +73,11 @@ class NewTrack:
track: Track
audio_path: Path
cues: TrackCues | None = None
# The cover as the SOURCE library shows it — `(bytes, mime)` from its
# `cover_art` — since a library's art is not always embedded in the file.
# For a platform that keeps its own copy of the art (Rekordbox); one that
# reads the file's tags (Traktor) ignores it.
art: tuple[bytes, str] | None = None
@dataclass(frozen=True)
@@ -173,7 +178,13 @@ class LibraryAdapter(Protocol):
# fidelity guarantee hold. A new entry has no parsed original, so the rule
# becomes "an added entry must not perturb any existing one" — which is
# what `test_save_fidelity.py` checks rather than taking on trust.
def add_tracks(self, items: list["NewTrack"]) -> list[str]: ...
#
# `checkpoint(message, step, of)` is called before each slow step (a
# platform that must ANALYSE what it adds, like Rekordbox, decodes every
# file) and may raise to cancel; it is only ever called before the library
# is touched, so a cancel leaves it as it was. Gated on
# `capabilities().tracks.addable`.
def add_tracks(self, items: list["NewTrack"], *, checkpoint=None) -> list[str]: ...
# Remove tracks from the library — and so from every playlist, since an
# entry naming a track the library no longer has is a dangling reference.
+3
View File
@@ -63,6 +63,9 @@ class TrackCapabilities(BaseModel):
# Tracks can be removed from the library (and so from its playlists). The
# audio file is never touched either way.
removable: bool = False
# Tracks can be added to the library (`add_tracks`): an import from a
# device, or browsed files added to the collection.
addable: bool = False
# Tracks can be converted to native-instruments STEM files, which this
# platform plays as stems (`apply_stem_swaps`).
stem_convertible: bool = False
+12 -1
View File
@@ -173,7 +173,18 @@ def _frames(y: np.ndarray, lead: float) -> Frames:
def analyse(path: Path, *, n_columns: int = 400, lead: float = 0.0) -> Analysis | None:
"""Decode `path` once and measure both resolutions; None if undecodable."""
y = _decode(path)
return analyse_samples(decode(path), n_columns=n_columns, lead=lead)
def decode(path: Path) -> np.ndarray | None:
"""Mono float32 at `SR` — the same samples `analyse` measures, for a caller
that needs them for something else too (grid detection runs at `SR`)."""
return _decode(path)
def analyse_samples(y: np.ndarray | None, *, n_columns: int = 400,
lead: float = 0.0) -> Analysis | None:
"""`analyse` on samples already decoded by `decode`."""
if y is None or len(y) < max(n_columns, N_FFT):
return None
return Analysis(columns=_columns(y, n_columns), frames=_frames(y, lead))
+16 -2
View File
@@ -340,9 +340,23 @@ def run(
cues = source.track_cues(planned.track_id)
except Exception: # noqa: BLE001 — prep is a bonus, not a blocker
log.debug("could not read cues for %s", planned.track_id, exc_info=True)
items.append(NewTrack(track=track, audio_path=target, cues=cues))
art = None
cover_art = getattr(source, "cover_art", None)
if cover_art is not None:
try:
art = cover_art(planned.track_id)
except Exception: # noqa: BLE001 — art is a bonus too
log.debug("could not read art for %s", planned.track_id, exc_info=True)
items.append(NewTrack(track=track, audio_path=target, cues=cues, art=art))
new_ids = dest.add_tracks(items)
def checkpoint(message: str, *, step: int, of: int) -> None:
# A platform that analyses what it adds (Rekordbox) is slow here,
# and calls this before touching the library — so a cancel still
# leaves it untouched and the copies are cleaned up below.
handle.raise_if_cancelled()
handle.progress(done=step - 1, total=of, message=message)
new_ids = dest.add_tracks(items, checkpoint=checkpoint)
by_source = {
planned.track_id: new_id
for (planned, _), new_id in zip(copied, new_ids)
+8
View File
@@ -1875,8 +1875,15 @@ def folder_track_stems(track_id: str) -> dict:
return _stem_layout_of(_folder_track(track_id).audio_path(track_id))
def _require_addable(dest) -> None:
caps = dest.capabilities()
if not (caps.writable and caps.tracks.addable):
raise HTTPException(422, "Tracks cannot be added to this library")
def _folder_add_plan(body: FolderAddRequest):
dest = require_adapter()
_require_addable(dest)
tracks = []
for track_id in body.track_ids:
track = _folder_track(track_id).track(track_id)
@@ -1957,6 +1964,7 @@ def folder_add(body: FolderAddRequest) -> JobStatus:
def _import_plan(body: ImportRequest):
source, dest = require_source(), require_adapter()
_require_addable(dest)
destination = Path(body.destination).expanduser()
return source, dest, destination, importer.plan(
source,