diff --git a/CLAUDE.md b/CLAUDE.md index 2d6e996..055d220 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1058,7 +1058,6 @@ that number and nothing else — everything derives from it: unmeasured). Type colours map by intent (cue -> light blue 0x05, loop -> green 0x16), anything else to the nearest hue; the palette has NO white, so a grid companion is code 0 + RGB white (what rekordbox draws for it: unverified). The - `master.db` exporter still writes no cue colour (generic `set_cue` has none). **Artwork** (`adapters/rekordbox/artwork.py`, Pillow), measured on a rekordbox 7 export: `PIONEER/Artwork/00001/{a,b}.jpg` at 80 px and `_m` at 240 px, `a` byte-identical to `b`, baseline JPEG q85 4:2:0, non-square art LETTERBOXED onto @@ -1069,7 +1068,23 @@ that number and nothing else — everything derives from it: The OneLibrary READER now serves `cover_art` too (the `_m` file). How rekordbox itself splits a large library across `Artwork/000NN` folders is unknown; one folder of 207 was verified to load in full. - The `master.db` target still writes no artwork. `adapters/rekordbox/export.py` writes a `master.db` and + **The `master.db` target was opened in a real Rekordbox 7** (2026-09-27, by + swapping an export into `~/Library/Pioneer/rekordbox` with a full backup): + it accepts the library, keeps our tracks/cues/analysis untouched, and shows + grids, cues and the playlist tree. Two things it needed: a + `masterPlaylists6.xml` beside `master.db` (written as a skeleton BEFORE the DB + is opened, so pyrekordbox registers each playlist in it), and + `djmdContent.ContentLink` — a bit field: NULL = blue song-list preview + "?", + any value = coloured, 0x200000 clears the "?", and the real library's + 0x3D060E adds a badge claiming analysis we do not write, so the exporter uses + 0x2C060E. **Parity with the OneLibrary target is done and verified in + Rekordbox 7**: cue colours (palette code in `djmdCue.ColorTableIndex`, + `Color` -1 — coloured loops included), memory cues (`store.add_memory_cue`, + export-only: the adapter still refuses memory-cue edits), and artwork + (`share/PIONEER/Artwork///artwork.jpg` fit to 800 px plus + `_m` 240 / `_s` 80 letterboxed, `ImagePath` -> artwork.jpg). The exporter writes + cues through `store.set_cue`/`add_memory_cue`, which share `_write_cue` with + every adapter edit, so the `contentCue` mirror stays in step. `adapters/rekordbox/export.py` writes a `master.db` and **replays cues through the ordinary `RekordboxAdapter.set_cue`**, so it inherits `_sync_content_cue`, the sparse `Kind` bank and their tests rather than redefining them; its ANLZ files go under a **`share/` directory beside diff --git a/backend/konduktor/adapters/rekordbox/artwork.py b/backend/konduktor/adapters/rekordbox/artwork.py index ba4a8a1..41d5889 100644 --- a/backend/konduktor/adapters/rekordbox/artwork.py +++ b/backend/konduktor/adapters/rekordbox/artwork.py @@ -20,6 +20,10 @@ import logging log = logging.getLogger(__name__) SMALL, MEDIUM = 80, 240 +#: A master.db library also keeps a LARGE copy: the cover itself, aspect kept, +#: scaled down to fit 800 px (never up) — Motorola's 4112 x 1112 art is stored +#: 800 x 216, a 640 or 300 px cover unchanged. +LARGE = 800 _QUALITY = 85 @@ -41,6 +45,31 @@ def _jpeg(image) -> bytes: return out.getvalue() +def _open(data: bytes): + from PIL import Image + + try: + with Image.open(io.BytesIO(data)) as src: + src.load() + return src.convert("RGB") # PNG alpha / palette / CMYK -> RGB + except Exception as ex: # noqa: BLE001 — any unreadable image + log.warning("could not read cover art (%s); exporting without it", ex) + return None + + +def library_jpegs(data: bytes) -> tuple[bytes, bytes, bytes] | None: + """(large, 240 px, 80 px) for a `master.db` library — `artwork.jpg`, + `artwork_m.jpg`, `artwork_s.jpg` — or None when the image cannot be read.""" + from PIL import Image + + rgb = _open(data) + if rgb is None: + return None + large = rgb.copy() + large.thumbnail((LARGE, LARGE), Image.BICUBIC) + return _jpeg(large), _jpeg(_square(rgb, MEDIUM)), _jpeg(_square(rgb, SMALL)) + + def pioneer_jpegs(data: bytes) -> tuple[bytes, bytes] | None: """(80 px JPEG, 240 px JPEG) from any image the source library holds, or None when it cannot be read — a bad cover costs the artwork, not the export.""" diff --git a/backend/konduktor/adapters/rekordbox/export.py b/backend/konduktor/adapters/rekordbox/export.py index df5c3b2..9caee7e 100644 --- a/backend/konduktor/adapters/rekordbox/export.py +++ b/backend/konduktor/adapters/rekordbox/export.py @@ -58,7 +58,9 @@ from sqlalchemy import text from ...core.export import ExportPayload, ExportTrack, WrittenLibrary from ...core import waveform +from ...core.cue_colors import effective_color from . import anlz_writer as W +from . import artwork, palette from . import timebase from .beatgrid import beats_from_markers from .capabilities import capabilities_for @@ -80,6 +82,29 @@ 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 + +#: 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 +#: file does not vouch for is not shown. The skeleton is a real Rekordbox 7 +#: file's, minus its nodes — pyrekordbox adds ours as it creates them. +PLAYLISTS_XML = "masterPlaylists6.xml" +PLAYLISTS_XML_SKELETON = ( + '\n\n' + '\n' + ' \n' + ' \n \n' + '\n' +) OTHER_PLAYLIST = "Other" @@ -128,8 +153,16 @@ class RekordboxExporter: finally: con.close() + # BEFORE the database is opened: pyrekordbox keeps masterPlaylists6.xml + # in step with every playlist it creates — but only if the file exists + # at open time. Without it Rekordbox opened the library, generated its + # own file listing our playlists with Timestamp 0, and showed NONE of + # them (measured by swapping an export into a real Rekordbox 7). + playlists_xml = root / PLAYLISTS_XML + playlists_xml.write_text(PLAYLISTS_XML_SKELETON, encoding="utf-8") + db = MasterDatabase(path=str(library), key=key) - extra: list[Path] = [] + extra: list[Path] = [playlists_xml] ids: dict[str, str] = {} try: self._seed_registry(db, models) @@ -143,6 +176,7 @@ class RekordboxExporter: rows[item.source_id] = content ids[item.source_id] = str(content.ID) extra += self._write_anlz(item, content, root, db) + extra += self._write_art(item, content, root) self._write_playlists(db, payload, rows) # A brand-new file: a running Rekordbox cannot have it open, so its # process-wide veto protects nothing here. @@ -156,7 +190,7 @@ class RekordboxExporter: @staticmethod def _replay_cues(library: Path, payload: ExportPayload, ids: dict) -> None: - """Write the cues through the ORDINARY adapter, not by hand. + """Write the cues through the ORDINARY cue-row code, not by hand. Same reason the Traktor exporter replays commands: `set_cue` already owns every convention a cue row needs — the sparse `Kind` bank, frames @@ -168,24 +202,33 @@ class RekordboxExporter: from .adapter import RekordboxAdapter adapter = RekordboxAdapter(library) + # The store, not the adapter's commands: the adapter refuses memory cues + # (editing them in a user's library is off-limits) and takes no colour. + # Building a NEW library is neither an edit nor lossy by choice, so the + # exporter writes both — through the same `_write_cue` every edit uses. + store = adapter._store try: for item in payload.tracks: track_id = ids.get(item.source_id) if track_id is None or not item.cues: continue for cue in item.cues.cues: - # Memory cues are a Rekordbox-only concept the generic model - # preserves but never writes; a cue with no slot has no pad - # to land on. - if cue.role != "hotcue" or cue.slot is None: + if cue.role == "memory" or cue.slot is None: + # rekordbox's own "unset" for a memory cue with no colour. + code, _rgb = palette.code_for(cue.color) + store.add_memory_cue( + track_id, start_sec=cue.start, cue_type=cue.type, + length_sec=cue.length, name=cue.name, color_code=code or None, + ) continue - adapter.set_cue( - track_id, - slot=cue.slot, - start_sec=cue.start, - cue_type=cue.type, - length_sec=cue.length, - name=cue.name, + # What Konduktor SHOWS — stored colour, else the type's (blue + # cue, green loop) — as a palette code, which is what + # rekordbox draws from. White (a grid companion) has no swatch: + # code 0, i.e. uncoloured. + code, _rgb = palette.code_for(effective_color(cue)) + store.set_cue( + track_id, slot=cue.slot, start_sec=cue.start, cue_type=cue.type, + length_sec=cue.length, name=cue.name, color_code=code or None, ) adapter.save() finally: @@ -265,6 +308,7 @@ class RekordboxExporter: # NOT `track.key`: that is the SOURCE platform's notation, so a Traktor # export would put "10m" where Rekordbox shows "Cm". content.KeyID = self._lookup(db, "key", render_key(track.key_wheel, track.key_mode)) + content.ContentLink = CONTENT_LINK db.flush() return content @@ -350,6 +394,35 @@ class RekordboxExporter: written.append(W.write_anlz(dat.with_suffix(".2EX"), [W.path_tag(path), *two_ex])) return written + # ---- artwork ------------------------------------------------------------------ + + @staticmethod + def _write_art(item: ExportTrack, content, root: Path) -> list[Path]: + """The cover, as a rekordbox-managed track carries it. + + Three JPEGs under `share/PIONEER/Artwork///` — the + same UUID split as the analysis folder — named `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`, + rooted at `share/` like `AnalysisDataPath`. All measured on a real + Rekordbox 7 library. + """ + if not item.art: + 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:]}" + 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): + (folder / name).write_bytes(data) + written.append(folder / name) + content.ImagePath = f"{rel}/artwork.jpg" + return written + # ---- playlists --------------------------------------------------------------- def _write_playlists(self, db, payload: ExportPayload, rows: dict) -> None: diff --git a/backend/konduktor/adapters/rekordbox/store.py b/backend/konduktor/adapters/rekordbox/store.py index a8df250..966e471 100644 --- a/backend/konduktor/adapters/rekordbox/store.py +++ b/backend/konduktor/adapters/rekordbox/store.py @@ -647,12 +647,51 @@ class RekordboxStore: 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.""" - if start_sec < 0: - raise InvalidCommand("A cue cannot be before the start of the track") + """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 or 0 + writes the uncoloured convention, which is what every edit through the + adapter does — only the exporter passes a colour. + """ if int(slot) < 0: raise InvalidCommand(f"Hot cue slot cannot be negative, got {slot}") + existing = self._cue_row(track_id, slot) + 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}") + + 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, + ) -> None: + """Add a MEMORY cue (`Kind` 0) — for the exporter building a new library. + + The adapter never calls this: editing memory cues in a user's library + stays refused under the two-platform promotion rule. A new export is not + an edit, and dropping the source's memory cues would lose prep. + """ + 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 _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.""" + 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)) @@ -660,10 +699,6 @@ class RekordboxStore: out_ms = (int(round(timebase.to_pioneer(start_sec + length_sec, off) * 1000)) if is_loop else -1) - kind = kind_for("hotcue", slot) - existing = self._cue_row(track_id, slot) - op = "add" if existing is None else "modify" - cue = existing if cue is None: t = self._tables cue = t.DjmdCue.create( @@ -703,11 +738,17 @@ class RekordboxStore: cue.CueMicrosec = None cue.Color = -1 cue.ColorTableIndex = None + if color_code: + # A palette-coloured cue, as the real library stores one: the code in + # ColorTableIndex (22 = green), Color -1. How rekordbox stores a + # COLOURED LOOP is not in the reference library; the same column is + # assumed and is what the smoke test checks. + cue.ColorTableIndex = int(color_code) + cue.Color = -1 cue.Comment = name or None self._db.flush() self._sync_content_cue(track_id) - self._journal.record("cue", op, 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) diff --git a/backend/test_export_pioneer.py b/backend/test_export_pioneer.py index 783e6e8..cc99f2c 100644 --- a/backend/test_export_pioneer.py +++ b/backend/test_export_pioneer.py @@ -503,5 +503,92 @@ check("every track carries contentLink 788224, beside analysedBits 41", check("an unreadable cover costs the artwork, not the export", artwork_mod.pioneer_jpegs(b"not an image") is None) +print("\n== a Rekordbox library carries masterPlaylists6.xml, vouching for every playlist ==") +# Measured by swapping an export into a real Rekordbox 7: without this file +# Rekordbox opened the library, generated one listing our playlists with +# Timestamp 0, and showed NONE of them in its sidebar. +import xml.etree.ElementTree as ET # noqa: E402 + +rb_root = Path(tempfile.mkdtemp()) +rb_written = core_export.for_platform("rekordbox").write(build(rb_root), rb_root) +pl_xml = rb_root / "masterPlaylists6.xml" +check("the file is written beside master.db", pl_xml.is_file()) +check("and reported, so a re-export can clear it", pl_xml in rb_written.all_paths) +nodes = ET.parse(pl_xml).getroot().find("PLAYLISTS").findall("NODE") +rb_db = RekordboxDriver().open(rb_root / "master.db") +flat = [] + + +def _walk(ns): + for n in ns: + flat.append(n) + _walk(n.children) + + +_walk(rb_db.playlist_tree()) +check("one node per playlist and folder in the database", len(nodes) == len(flat), (len(nodes), len(flat))) +_rbc = _sq.connect(str(rb_root / "master.db")) +from pyrekordbox.masterdb.database import BLOB as _MBLOB # noqa: E402 +_rbc.execute(f"PRAGMA key='{_deob(_MBLOB)}'") +_links = {r[0] for r in _rbc.execute("SELECT ContentLink FROM djmdContent")} +_rbc.close() +check("every track carries ContentLink 0x2C060E (coloured preview, no '?')", + _links == {2885134}, _links) +check("every node carries a real timestamp, not 0", + nodes and all(int(n.get("Timestamp", "0")) > 0 for n in nodes), [n.get("Timestamp") for n in nodes]) +rb_db.close() + +print("\n== the Rekordbox target: cue colours, memory cues and artwork ==") +rbp_root = Path(tempfile.mkdtemp()) +rbp_audio = rbp_root / "Contents" / "parity.wav" +rbp_audio.parent.mkdir(parents=True) +sf.write(rbp_audio, tone, sr) +parity_cues = [ + CuePoint(type="cue", role="hotcue", start=1.0, length=0.0, slot=0), # -> light blue + CuePoint(type="loop", role="hotcue", start=2.0, length=0.96, slot=1), # -> green + CuePoint(type="cue", role="hotcue", start=0.0, length=0.0, slot=2, color="#FFFFFF"), # grid cue + CuePoint(type="cue", role="memory", start=4.0, length=0.0, slot=None), +] +parity = ExportTrack(track=live_t.model_copy(update={"id": "parity", "title": "parity"}), + destination=rbp_audio, art=(png.getvalue(), "image/png"), + cues=TrackCues(track_id="parity", cues=parity_cues, + grid_markers=[GridMarker(start=0.0, bpm=125.0)])) +rbp_written = core_export.for_platform("rekordbox").write(ExportPayload(name="PARITY", tracks=[parity]), rbp_root) + +_c = _sq.connect(str(rbp_root / "master.db")) +_c.execute(f"PRAGMA key='{_deob(_MBLOB)}'") +cue_rows = _c.execute("SELECT Kind, ColorTableIndex, Color, InMsec FROM djmdCue ORDER BY InMsec").fetchall() +mirror = _c.execute("SELECT Cues FROM contentCue").fetchone() +image_path = _c.execute("SELECT ImagePath FROM djmdContent").fetchone()[0] +_c.close() +by_kind = {k: (cti, col) for k, cti, col, _ms in cue_rows} +check("four cue rows: three hot cues and a memory cue (Kind 0)", + sorted(k for k, *_ in cue_rows) == [0, 1, 2, 3], cue_rows) +check("a plain cue is rekordbox's light blue (code 5)", by_kind.get(1) == (0x05, -1), by_kind.get(1)) +check("a loop is rekordbox's green (code 22)", by_kind.get(2) == (0x16, -1), by_kind.get(2)) +check("the white grid cue has no swatch, so stays uncoloured", by_kind.get(3) == (None, -1), by_kind.get(3)) +check("the memory cue is written, uncoloured", by_kind.get(0) == (None, -1), by_kind.get(0)) +check("the contentCue mirror holds all four, colours included", + mirror is not None and mirror[0].count('"Kind"') == 4 and '"ColorTableIndex": 22' in mirror[0].replace(":22", ": 22"), + mirror and mirror[0][:200]) + +art_dir = rbp_root / "share" / image_path.lstrip("/").rsplit("/", 1)[0] if image_path else None +check("ImagePath names artwork.jpg under the track's UUID folder", + bool(image_path) and image_path.startswith("/PIONEER/Artwork/") and image_path.endswith("/artwork.jpg"), image_path) +sizes = {p.name: Image.open(p).size for p in art_dir.iterdir()} if art_dir and art_dir.exists() else {} +check("three JPEGs: the cover fit to 800 px (aspect kept), 240 and 80 px squares", + sizes == {"artwork.jpg": (400, 100), "artwork_m.jpg": (240, 240), "artwork_s.jpg": (80, 80)}, sizes) +check("every art file is reported, so a re-export can clear it", + art_dir is not None and all(p in rbp_written.extra for p in art_dir.iterdir())) +rb_back = RekordboxDriver().open(rbp_root / "master.db") +t_back = rb_back.tracks[0] +served = rb_back.cover_art(t_back.id) +check("Konduktor's Rekordbox reader serves the cover back", + served is not None and served[0] == (art_dir / "artwork.jpg").read_bytes()) +memory_back = [c for c in rb_back.track_cues(t_back.id).cues if c.role == "memory"] +check("and reads the memory cue back, at its place", + len(memory_back) == 1 and abs(memory_back[0].start - 4.0) < 0.002, memory_back) +rb_back.close() + print("\n" + ("❌ FAILED" if failed else "✅ PASSED")) raise SystemExit(1 if failed else 0)