diff --git a/CLAUDE.md b/CLAUDE.md index 055d220..57bc4e9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1084,7 +1084,30 @@ that number and nothing else — everything derives from it: (`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 + every adapter edit, so the `contentCue` mirror stays in step. + **Two Rekordbox targets, named for what they are:** "Rekordbox Library" + (`export.py`, a COMPUTER `master.db` — Rekordbox never reads one from a stick) + and **"Rekordbox Export"** (`device_export.py`, platform `rekordbox_export`: a + stick's legacy **Device Library**, `PIONEER/rekordbox/export.pdb` + + `exportExt.pdb`, what Rekordbox lists as "Device Library" and pre-OneLibrary + players read). `pdb.py` reads and writes the DeviceSQL format — no public spec; + the layout is crate-digger's, CONFIRMED byte for byte against a real rekordbox 7 + device export (every row re-encodes identically; a data page rebuilt from its + rows is identical). It writes from rekordbox's OWN empty device library + (`fixtures/rekordbox/device/`, the fixed colour/column/menu tables) and follows + rekordbox's page allocation (a table's first data page is its reserved + candidate; further pages and the new candidate come from next-unused). The + track row's `bitmask` is 0xC0700 = OneLibrary's `contentLink`; `u3`/`u4` are + the halves of rekordbox's `masterDbId` and stay 0. **A table's HEADER page is + not empty: it indexes its data** (first data page; for tracks, playlist tree + and history an entry per data page, `page << 3 | 3` if it has room) and the + history row counts the tracks — left as in the empty template, Rekordbox 7 + said "Device library is corrupted". It shares the stick's + analysis files and `a.jpg` artwork with the OneLibrary target — the same + paths, and whichever target runs second REUSES what the first just wrote, so a + two-format stick costs one decode per track. A target with no reader is listed + by `/api/export-targets` from the exporter registry; `LibraryExporter. + display_name` names a target where one platform has two. `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/fixtures/rekordbox/device/README.md b/backend/fixtures/rekordbox/device/README.md new file mode 100644 index 0000000..9e108df --- /dev/null +++ b/backend/fixtures/rekordbox/device/README.md @@ -0,0 +1,20 @@ +# Empty rekordbox device library (`export.pdb`, `exportExt.pdb`) + +The legacy "Device Library" a Pioneer USB stick carries — the one Rekordbox +lists as **Device Library** and older players (CDJ-2000NXS2, many XDJs) read — +exactly as **Rekordbox 7.2.18 wrote it for an empty stick**: it creates both +files the first time it mounts a drive that has none. + +They are the starting point of the "Rekordbox Export" target +(`adapters/rekordbox/device_export.py`), for the same reason `seed.sql` exists: +the format has fixed tables that are the same on every stick and cannot be +derived — the colour list (table 6), the browse columns (16), two menu tables +(17, 18) and a history header (19) in `export.pdb`; rekordbox's default MyTag +names in `exportExt.pdb`. Every data table (tracks, artists, albums, genres, +labels, keys, playlists, artwork) holds only its header page, with a blank page +reserved after it for its first rows — the allocation rule the writer follows. + +**No user data**: the only strings are colour names, column names, the default +MyTag names, the creation date (`2026-09-27`, rewritten on every export) and the +database version `1000`. Pages 13-14 and 33-38 are byte-identical to the same +pages of a real rekordbox device export of eight tracks. diff --git a/backend/fixtures/rekordbox/device/export.pdb b/backend/fixtures/rekordbox/device/export.pdb new file mode 100755 index 0000000..2be4573 Binary files /dev/null and b/backend/fixtures/rekordbox/device/export.pdb differ diff --git a/backend/fixtures/rekordbox/device/exportExt.pdb b/backend/fixtures/rekordbox/device/exportExt.pdb new file mode 100755 index 0000000..b7af3a4 Binary files /dev/null and b/backend/fixtures/rekordbox/device/exportExt.pdb differ diff --git a/backend/fixtures/rekordbox/device/reference_rows.json b/backend/fixtures/rekordbox/device/reference_rows.json new file mode 100644 index 0000000..773e496 --- /dev/null +++ b/backend/fixtures/rekordbox/device/reference_rows.json @@ -0,0 +1,62 @@ +{ + "note": "Rows from a real rekordbox 7.2.18 device export (export.pdb), for byte-level tests. Only the Loopmasters demo tracks and generic key names; see README.md. The track row's u3/u4 (the exporting computer's rekordbox masterDbId) are zeroed.", + "track_row_demo_track_2": "2400200000070c0044ac000000000000f6304e0011a8a6040000000000000000000000000000000001000000000000004001000000000000e02e000000000000000000000100000002000000000000000000100080002900000001000300880089008a008c008e00910092009500980099009a00a500a600a700a800d400df00fd000a010b011c0103030531053107313103074f4e074f4e030317323031382d30352d3235030303592f50494f4e4545522f555342414e4c5a2f503035332f30303031443231462f414e4c5a303030302e44415417323032362d30392d31373d547261636b73206279207777772e6c6f6f706d6173746572732e636f6d1b44656d6f20547261636b2032032344656d6f20547261636b20322e6d7033692f436f6e74656e74732f4c6f6f706d6173746572732f556e6b6e6f776e416c62756d2f44656d6f20547261636b20322e6d7033", + "track_row_demo_track_2_fields": { + "subtype": 36, + "index_shift": 32, + "bitmask": 788224, + "sample_rate": 44100, + "composer_id": 0, + "file_size": 5124342, + "u2": 78030865, + "u3": 0, + "u4": 0, + "artwork_id": 0, + "key_id": 0, + "original_artist_id": 0, + "label_id": 1, + "remixer_id": 0, + "bitrate": 320, + "track_number": 0, + "tempo": 12000, + "genre_id": 0, + "album_id": 0, + "artist_id": 1, + "id": 2, + "disc_number": 0, + "play_count": 0, + "year": 0, + "sample_depth": 16, + "duration": 128, + "u5": 41, + "color_id": 0, + "rating": 0, + "u6": 1, + "u7": 3, + "isrc": "", + "texter": "", + "unknown_string_2": "1", + "unknown_string_3": "1", + "unknown_string_4": "11", + "message": "", + "kuvo_public": "ON", + "autoload_hotcues": "ON", + "unknown_string_5": "", + "unknown_string_6": "", + "date_added": "2018-05-25", + "release_date": "", + "mix_name": "", + "unknown_string_7": "", + "analyze_path": "/PIONEER/USBANLZ/P053/0001D21F/ANLZ0000.DAT", + "analyze_date": "2026-09-17", + "comment": "Tracks by www.loopmasters.com", + "title": "Demo Track 2", + "unknown_string_8": "", + "filename": "Demo Track 2.mp3", + "file_path": "/Contents/Loopmasters/UnknownAlbum/Demo Track 2.mp3" + }, + "artist_row_loopmasters": "6000000001000000030a194c6f6f706d617374657273000000000000", + "playlist_row_demos": "00000000000000000100000001000000000000000d64656d6f730000", + "keys_page_index": 12, + "keys_page": "000000000c0000000500000034000000140000000000000002400024b80f1800010001000000000001000000010000000941626d020000000200000007456d00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c00000003000200" +} \ No newline at end of file diff --git a/backend/konduktor-sidecar.spec b/backend/konduktor-sidecar.spec index d322fe3..1bbf02a 100644 --- a/backend/konduktor-sidecar.spec +++ b/backend/konduktor-sidecar.spec @@ -44,6 +44,9 @@ datas += [ ("fixtures/rekordbox/seed.sql", "fixtures/rekordbox"), ("fixtures/onelibrary/schema.sql", "fixtures/onelibrary"), ("fixtures/onelibrary/seed.sql", "fixtures/onelibrary"), + # The "Rekordbox Export" target starts from rekordbox's own empty device library. + ("fixtures/rekordbox/device/export.pdb", "fixtures/rekordbox/device"), + ("fixtures/rekordbox/device/exportExt.pdb", "fixtures/rekordbox/device"), ] a = Analysis( diff --git a/backend/konduktor/adapters/onelibrary/export.py b/backend/konduktor/adapters/onelibrary/export.py index 701a34e..748a39d 100644 --- a/backend/konduktor/adapters/onelibrary/export.py +++ b/backend/konduktor/adapters/onelibrary/export.py @@ -97,6 +97,7 @@ def _anlz_dir(drive_relative: str) -> str: class OneLibraryExporter: platform = "onelibrary" + menu_order = 10 #: Relative to the drive root, which is what the destination folder is. library_filename = str(Path("PIONEER") / DB_SUBPATH) #: A CDJ looks for `PIONEER/` at the root of the stick and nowhere else. diff --git a/backend/konduktor/adapters/rekordbox/__init__.py b/backend/konduktor/adapters/rekordbox/__init__.py index 6076a5b..5192c8e 100644 --- a/backend/konduktor/adapters/rekordbox/__init__.py +++ b/backend/konduktor/adapters/rekordbox/__init__.py @@ -8,6 +8,7 @@ capabilities. from ...core import export as core_export from ...core import registry from .driver import RekordboxDriver +from .device_export import RekordboxDeviceExporter from .export import RekordboxExporter REKORDBOX = RekordboxDriver() @@ -15,3 +16,8 @@ registry.register(REKORDBOX) REKORDBOX_EXPORTER = RekordboxExporter() core_export.register(REKORDBOX_EXPORTER) + +# The stick's legacy Device Library (`export.pdb`): a separate TARGET with no +# reader of its own — Konduktor reads a stick through its OneLibrary database. +REKORDBOX_DEVICE_EXPORTER = RekordboxDeviceExporter() +core_export.register(REKORDBOX_DEVICE_EXPORTER) diff --git a/backend/konduktor/adapters/rekordbox/device_export.py b/backend/konduktor/adapters/rekordbox/device_export.py new file mode 100644 index 0000000..e84c826 --- /dev/null +++ b/backend/konduktor/adapters/rekordbox/device_export.py @@ -0,0 +1,237 @@ +"""The "Rekordbox Export" target: a USB stick's legacy Device Library (`export.pdb`). + +What Rekordbox lists as a stick's **Device Library**, and what pre-OneLibrary +players (CDJ-2000NXS2, many XDJs) read. Not to be confused with the "Rekordbox +Library" target (`export.py`), which writes a COMPUTER library (`master.db`) +that Rekordbox never reads from a stick. + +## Shared with the OneLibrary target — deliberately + +Rekordbox's own device export writes `export.pdb` AND `exportLibrary.db`, both +pointing at ONE set of audio, analysis files and artwork. This target does the +same: the analysis files are written by the OneLibrary exporter's own +`_write_anlz`, at the same paths (`PIONEER/USBANLZ/P0xx/xxxxxxxx/`), and the +artwork is the `a.jpg` pair the OneLibrary target also writes (rekordbox's +`a` files are the ones `export.pdb` names; OneLibrary's `image` table names the +byte-identical `b` files). When both targets are ticked, whichever runs second +finds the analysis already on the stick — written moments ago by the first, as +the runner clears the previous export before copying — and reuses it rather +than decoding every track again. + +## The database + +`pdb.PdbWriter` fills rekordbox's own empty device library (a template) with +rows; see `pdb.py` for the format and why a template. Values follow a real +rekordbox 7 device export: + + * `bitmask` 0xC0700 — the same value as OneLibrary's `content.contentLink`, + which is what makes rekordbox draw a track's song-list preview there; + * `u2` = the track id + 0x600 (rekordbox: masterContentId + 0x600); + * `u3`/`u4` = 0: they are the halves of rekordbox's `masterDbId`, the link to a + computer's collection, which a Konduktor export does not claim; + * `u5` 0x29 (= `analysedBits` 41), `u6` the file type, `u7` 3; + * strings "ON" for kuvo_public / autoload_hotcues; the three unnamed strings + rekordbox fills from its phrase analysis are left EMPTY — this exporter + writes no phrases, and whether players care is what the device test checks. +""" +from __future__ import annotations + +import logging +from datetime import date +from pathlib import Path + +from ...core.export import ExportPayload, ExportTrack, WrittenLibrary +from . import artwork, pdb +from .projection import render_key + +log = logging.getLogger(__name__) + +PDB_DIR = Path("PIONEER") / "rekordbox" +OTHER_PLAYLIST = "Other" +BITMASK = 0xC0700 +ANALYSED = 0x29 + + +class RekordboxDeviceExporter: + platform = "rekordbox_export" + menu_order = 30 + display_name = "Rekordbox Export" + library_filename = str(PDB_DIR / "export.pdb") + #: A player looks for `PIONEER/` at the root of the stick. + drive_root = True + + def capabilities(self): + """What a stick's device library can hold — the OneLibrary target's + answer, since both describe the same drive and its analysis files.""" + from ..onelibrary.export import OneLibraryExporter + + return OneLibraryExporter().capabilities() + + def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary: + # Imported here, not at module level: the OneLibrary package imports this + # package's modules, and a module-level import would be circular. + from ..onelibrary.export import ( + OneLibraryExporter, _anlz_dir, _audio_format, _drive_relative, _file_type, _kbps, + ) + + root = Path(destination) + (root / PDB_DIR).mkdir(parents=True, exist_ok=True) + today = date.today().isoformat() + drive = OneLibraryExporter() + extra: list[Path] = [] + + ids = {name: {} for name in ("artist", "album", "genre", "label", "key")} + rows = {t: [] for t in (pdb.TRACKS, pdb.ARTISTS, pdb.ALBUMS, pdb.GENRES, + pdb.LABELS, pdb.KEYS, pdb.ARTWORK)} + builders = {"artist": (pdb.ARTISTS, pdb.artist_row), "album": (pdb.ALBUMS, pdb.album_row), + "genre": (pdb.GENRES, pdb.id_string_row), "label": (pdb.LABELS, pdb.id_string_row), + "key": (pdb.KEYS, pdb.key_row)} + + def lookup(kind: str, name: str | None) -> int: + if not name: + return 0 + table = ids[kind] + if name not in table: + table[name] = len(table) + 1 + t, build = builders[kind] + rows[t].append(build(table[name], name)) + return table[name] + + by_source: dict[str, int] = {} + art_n = 0 + total = len(payload.tracks) + for n, item in enumerate(payload.tracks, start=1): + payload.checkpoint(f"Writing the device library: {item.track.title or item.destination.name} ({n}/{total})") + track = item.track + by_source[item.source_id] = n + rel = _drive_relative(item.destination, root) + anlz_rel = f"{_anlz_dir(rel)}/ANLZ0000.DAT" + dat = root / anlz_rel.lstrip("/") + extra += self._analysis(drive, item, rel, dat) + + artwork_id = 0 + art = self._art(item, root, art_n + 1) + if art: + art_n += 1 + artwork_id = art_n + extra += art + rows[pdb.ARTWORK].append(pdb.id_string_row(art_n, f"/PIONEER/Artwork/00001/a{art_n}.jpg")) + + sample_rate, bit_depth = _audio_format(item.destination) + try: + size = item.destination.stat().st_size + except OSError: + size = 0 + year = int(track.release_date[:4]) if (track.release_date or "")[:4].isdigit() else 0 + rows[pdb.TRACKS].append(pdb.track_row( + { + "subtype": 0x24, "bitmask": BITMASK, "sample_rate": sample_rate or 0, + "file_size": size, "u2": n + 0x600, + "artwork_id": artwork_id, + "key_id": lookup("key", render_key(track.key_wheel, track.key_mode)), + "label_id": lookup("label", track.label), + "bitrate": _kbps(track.bitrate) or 0, + "tempo": int(round((track.bpm or 0) * 100)), + "genre_id": lookup("genre", track.genre), + "album_id": lookup("album", track.album), + "artist_id": lookup("artist", track.artist), + "id": n, "year": year, "sample_depth": bit_depth or 0, + "duration": min(int(track.length or 0), 0xFFFF), + "u5": ANALYSED, "rating": max(0, min(5, int(track.rating or 0))), + "u6": _file_type(item.destination), "u7": 3, + }, + { + "kuvo_public": "ON", "autoload_hotcues": "ON", + "date_added": today, "release_date": track.release_date or "", + "mix_name": track.mix or "", "analyze_path": anlz_rel, + "analyze_date": today, "comment": track.comment or "", + "title": track.title or item.destination.stem, + "filename": item.destination.name, "file_path": rel, + }, + )) + + tree, entries = self._playlists(payload, by_source) + writer = pdb.PdbWriter(pdb.template("export.pdb")) + for table in (pdb.TRACKS, pdb.GENRES, pdb.ARTISTS, pdb.ALBUMS, pdb.LABELS, pdb.KEYS, pdb.ARTWORK): + writer.fill(table, rows[table]) + writer.fill(pdb.PLAYLIST_TREE, tree) + writer.fill(pdb.PLAYLIST_ENTRIES, entries) + writer.stamp_history_date(date.today()) + writer.stamp_track_count(len(rows[pdb.TRACKS])) + + library = root / self.library_filename + library.write_bytes(writer.render()) + ext = root / PDB_DIR / "exportExt.pdb" + ext.write_bytes(pdb.template("exportExt.pdb")) + return WrittenLibrary(library=library, extra=[ext, *extra]) + + # ---- shared drive files --------------------------------------------------- + + @staticmethod + def _analysis(drive, item: ExportTrack, rel: str, dat: Path) -> list[Path]: + """This track's analysis files — reused when the OneLibrary target has + just written them in this same export, else written the same way.""" + existing = [dat.with_suffix(s) for s in (".DAT", ".EXT", ".2EX") if dat.with_suffix(s).exists()] + if dat.exists() and dat.with_suffix(".EXT").exists(): + return existing + return drive._write_anlz(item, rel, dat) + + @staticmethod + def _art(item: ExportTrack, root: Path, n: int) -> list[Path]: + """`a.jpg` / `a_m.jpg` — the pair export.pdb's artwork table names, + numbered in track order exactly as the OneLibrary target numbers them.""" + if not item.art: + return [] + folder = root / "PIONEER" / "Artwork" / "00001" + small, medium = folder / f"a{n}.jpg", folder / f"a{n}_m.jpg" + if small.exists() and medium.exists(): + return [small, medium] + jpegs = artwork.pioneer_jpegs(item.art[0]) + if jpegs is None: + return [] + folder.mkdir(parents=True, exist_ok=True) + small.write_bytes(jpegs[0]) + medium.write_bytes(jpegs[1]) + return [small, medium] + + # ---- playlists ------------------------------------------------------------ + + @staticmethod + def _playlists(payload: ExportPayload, by_source: dict) -> tuple[list[bytes], list[bytes]]: + """The tree under one folder named after the export, as the other + targets build it. `sort_order` is a node's position among its siblings.""" + tree: list[bytes] = [] + entries: list[bytes] = [] + next_id = [0] + siblings: dict[int, int] = {} + + def add(name: str, parent: int, *, folder: bool) -> int: + next_id[0] += 1 + order = siblings.get(parent, 0) + siblings[parent] = order + 1 + tree.append(pdb.playlist_tree_row(next_id[0], parent, order, name, folder=folder)) + return next_id[0] + + def fill(playlist_id: int, source_ids: list[str]) -> None: + index = 0 + for source_id in source_ids: + track_id = by_source.get(source_id) + if track_id is not None: + index += 1 + entries.append(pdb.playlist_entry_row(index, track_id, playlist_id)) + + root = add(payload.name, 0, folder=True) + folders: dict[tuple[str, ...], int] = {(): root} + for playlist in payload.playlists: + parent = root + for depth in range(1, len(playlist.folders) + 1): + branch = tuple(playlist.folders[:depth]) + if branch not in folders: + folders[branch] = add(branch[-1], folders[branch[:-1]], folder=True) + parent = folders[branch] + fill(add(playlist.name, parent, folder=False), playlist.track_ids) + claimed = {t for p in payload.playlists for t in p.track_ids} + loose = [t.source_id for t in payload.tracks if t.source_id not in claimed] + if loose: + fill(add(OTHER_PLAYLIST, root, folder=False), loose) + return tree, entries diff --git a/backend/konduktor/adapters/rekordbox/export.py b/backend/konduktor/adapters/rekordbox/export.py index 9caee7e..f14aa3e 100644 --- a/backend/konduktor/adapters/rekordbox/export.py +++ b/backend/konduktor/adapters/rekordbox/export.py @@ -110,6 +110,10 @@ OTHER_PLAYLIST = "Other" class RekordboxExporter: platform = "rekordbox" + menu_order = 40 + #: A COMPUTER library (master.db), which Rekordbox never reads from a stick — + #: named so, beside "Rekordbox Export" (the stick's Device Library). + display_name = "Rekordbox Library" library_filename = "master.db" drive_root = False diff --git a/backend/konduktor/adapters/rekordbox/pdb.py b/backend/konduktor/adapters/rekordbox/pdb.py new file mode 100644 index 0000000..41a6936 --- /dev/null +++ b/backend/konduktor/adapters/rekordbox/pdb.py @@ -0,0 +1,432 @@ +"""The legacy rekordbox device library: `export.pdb` (DeviceSQL), read and written. + +What Rekordbox lists as a stick's **Device Library** and what pre-OneLibrary +players (CDJ-2000NXS2, many XDJs) read. Rekordbox writes it beside the +OneLibrary `exportLibrary.db`; both point at the same audio, analysis files and +artwork. + +## The format + +There is no public specification. The layout used here is the one Deep +Symmetry's crate-digger documents, CONFIRMED byte for byte against a real +rekordbox 7 device export of eight tracks (every row of every table decodes, and +the page arithmetic below reproduces rekordbox's header fields exactly): + + * the file is 4096-byte pages; page 0 is a header listing 20 tables, each a + chain of pages `first -> ... -> last -> empty_candidate` (the candidate is a + reserved page, possibly beyond the end of the file); + * every table starts with a HEADER page that holds no rows (flags 0x64) but + DOES hold an index: the table's first data page, and for tracks, the + playlist tree and history an entry per data page (`page << 3 | flag`, 3 = + has room). A first Konduktor export left these pointing nowhere and + rekordbox 7 called the device library corrupted; rows live in DATA pages + (flags 0x34 for tracks and the playlist tree, else 0x24); + * a data page is a 0x28-byte header, a heap of rows (each 4-byte aligned) from + the top, and a row index growing from the bottom in groups of 16: per group + 16 u16 heap offsets, a u16 "present" bitmask and a u16 bitmask of the last + row written; + * strings are DeviceSQL strings: short ASCII `((len+1)<<1)|1` + bytes, long + ASCII `0x40` + u16 length + pad, or UTF-16LE `0x90` + u16 length + pad. + +## Writing + +**From a template, not from nothing** (`fixtures/rekordbox/device/`): the empty +library rekordbox itself writes for a new stick. It carries the tables that are +the same on every stick and cannot be derived (colours, browse columns, menus, +the history header), and reserves a blank page after each data table's header +page. Filling a table follows rekordbox's own allocation, read off a real +export: the first data page is the table's reserved candidate, further pages and +the new candidate come from the file header's next-unused counter, and any +reserved page left inside the file stays blank. + +Data pages are written the way a rekordbox EXPORT writes them (rows appended +one by one): `u5` = 1, `num_rows_large` = rows - 1, and each index group's +"last written" mask names its final row. +""" +from __future__ import annotations + +import re +import struct +from dataclasses import dataclass, field +from datetime import date +from pathlib import Path + +PAGE = 4096 +_HEADER = 0x28 +_GROUP = 0x24 # one row-index group: 16 offsets + present + last-written + +TRACKS, GENRES, ARTISTS, ALBUMS, LABELS, KEYS, COLORS = 0, 1, 2, 3, 4, 5, 6 +PLAYLIST_TREE, PLAYLIST_ENTRIES, ARTWORK, HISTORY = 7, 8, 13, 19 + +#: Data-page flags per table, as rekordbox writes them. +_PAGE_FLAGS = {TRACKS: 0x34, PLAYLIST_TREE: 0x34} +_DEFAULT_FLAGS = 0x24 +_HEADER_PAGE = 0x40 # bit set on header / non-data pages + +TEMPLATE_DIR = Path(__file__).resolve().parents[3] / "fixtures" / "rekordbox" / "device" + + +# ---- strings ------------------------------------------------------------------- + + +def dsql(text: str | None) -> bytes: + """A DeviceSQL string.""" + text = text or "" + try: + raw = text.encode("ascii") + except UnicodeEncodeError: + wide = text.encode("utf-16-le") + return struct.pack(" str: + head = buf[off] + if head & 1: + n = (head >> 1) - 1 + return buf[off + 1:off + 1 + n].decode("ascii", "replace") + n = struct.unpack_from(" bytes: + return row + bytes(-len(row) % 4) + + +# ---- rows ---------------------------------------------------------------------- + +#: The track row's fixed part, in order: 94 bytes. +_TRACK_FIELDS = ( + ("subtype", "H"), ("index_shift", "H"), ("bitmask", "I"), ("sample_rate", "I"), + ("composer_id", "I"), ("file_size", "I"), ("u2", "I"), ("u3", "H"), ("u4", "H"), + ("artwork_id", "I"), ("key_id", "I"), ("original_artist_id", "I"), ("label_id", "I"), + ("remixer_id", "I"), ("bitrate", "I"), ("track_number", "I"), ("tempo", "I"), + ("genre_id", "I"), ("album_id", "I"), ("artist_id", "I"), ("id", "I"), + ("disc_number", "H"), ("play_count", "H"), ("year", "H"), ("sample_depth", "H"), + ("duration", "H"), ("u5", "H"), ("color_id", "B"), ("rating", "B"), ("u6", "H"), ("u7", "H"), +) +_TRACK_FMT = "<" + "".join(f for _, f in _TRACK_FIELDS) +_TRACK_FIXED = struct.calcsize(_TRACK_FMT) # 94 +#: The 21 string slots, in the order their offsets follow the fixed part. +TRACK_STRINGS = ( + "isrc", "texter", "unknown_string_2", "unknown_string_3", "unknown_string_4", + "message", "kuvo_public", "autoload_hotcues", "unknown_string_5", "unknown_string_6", + "date_added", "release_date", "mix_name", "unknown_string_7", "analyze_path", + "analyze_date", "comment", "title", "unknown_string_8", "filename", "file_path", +) +_INDEX_SHIFT_AT = 2 # tracks, artists and albums carry their slot << 5 here +#: Tables whose header page indexes every data page (the rest only point at the +#: first). History (19) is already indexed in the template. +_INDEXED = (TRACKS, PLAYLIST_TREE) +_NONE = 0x1FFF + + +def track_row(fields: dict, strings: dict) -> bytes: + """A tracks-table row. `fields` fills the fixed part (missing = 0); + `strings` the string slots (missing = empty).""" + values = [fields.get(name, 0) for name, _ in _TRACK_FIELDS] + fixed = struct.pack(_TRACK_FMT, *values) + offsets, heap = [], b"" + base = _TRACK_FIXED + 2 * len(TRACK_STRINGS) + for name in TRACK_STRINGS: + offsets.append(base + len(heap)) + heap += dsql(strings.get(name)) + return _pad4(fixed + struct.pack(f"<{len(offsets)}H", *offsets) + heap) + + +def id_string_row(row_id: int, text: str) -> bytes: + """Genres, labels and artwork: u32 id + string.""" + return _pad4(struct.pack(" bytes: + """Keys store their id twice.""" + return _pad4(struct.pack(" bytes: + """Subtype 0x60: the name starts at a fixed offset of 10.""" + return _pad4(struct.pack(" bytes: + """Subtype 0x80: the name starts at 22. rekordbox's own export leaves the + album's artist 0 even when the track has one, so the default follows it.""" + return _pad4(struct.pack(" bytes: + return _pad4(struct.pack(" bytes: + return struct.pack(" int: + """Bytes the row index occupies at the bottom of a page holding `n` rows.""" + return ((n + 15) // 16) * _GROUP + + +def _chunk(rows: list[bytes]) -> list[list[bytes]]: + """Greedy: as many rows per page as fit beside their index.""" + pages, cur, used = [], [], 0 + for row in rows: + if cur and _HEADER + used + len(row) + _index_space(len(cur) + 1) > PAGE: + pages.append(cur) + cur, used = [], 0 + if _HEADER + len(row) + _index_space(1) > PAGE: + raise ValueError(f"a {len(row)}-byte row cannot fit in a page") + cur.append(row) + used += len(row) + if cur: + pages.append(cur) + return pages + + +def _data_page(index: int, table: int, next_page: int, rows: list[bytes], sequence: int, + *, shift_at: int | None, fill: tuple[int, int] | None = None) -> bytes: + page = bytearray(PAGE) + heap = bytearray() + offsets = [] + for slot, row in enumerate(rows): + row = bytearray(row) + if shift_at is not None: + struct.pack_into("> 8) & 0x1F) | ((n & 0x07) << 5) + page[0x1A] = (n >> 3) & 0xFF + page[0x1B] = _PAGE_FLAGS.get(table, _DEFAULT_FLAGS) + u5, nrl = fill if fill is not None else (1, n - 1) + struct.pack_into("<6H", page, 0x1C, free, used, u5, nrl, 0, 0) + return bytes(page) + + +# ---- the writer ---------------------------------------------------------------- + + +class PdbWriter: + """Fills an empty rekordbox device library (the template) with rows.""" + + def __init__(self, template: bytes): + self.buf = bytearray(template) + self.pages: dict[int, bytes] = {} + n_tables = struct.unpack_from(" int: + page = self.next_unused + self.next_unused += 1 + return page + + def fill(self, table: int, rows: list[bytes]) -> None: + """Write `rows` into `table`, which must still be empty (header page only).""" + if not rows: + return + slot, empty, first, last = self.tables[table] + if first != last: + raise ValueError(f"table {table} already has data pages") + chunks = _chunk(rows) + indices = [empty] + [self._alloc() for _ in chunks[1:]] + candidate = self._alloc() + shift_at = _INDEX_SHIFT_AT if table in (TRACKS, ARTISTS, ALBUMS) else None + indexed = table in _INDEXED + for i, chunk in enumerate(chunks): + nxt = indices[i + 1] if i + 1 < len(indices) else candidate + last_page = i + 1 == len(chunks) + # Indexed tables mark a full page 0x1FFF/0x1FFF and a page with room + # rows+1 / 0 — as a real export's tracks and playlist pages do. + fill = None + if indexed: + fill = (len(chunk) + 1, 0) if last_page else (_NONE, _NONE) + self.sequence += 1 + self.pages[indices[i]] = _data_page(indices[i], table, nxt, chunk, self.sequence, + shift_at=shift_at, fill=fill) + self._index(first, indices, indexed=indexed) + self.tables[table] = [slot, candidate, first, indices[-1]] + + def _index(self, header_page: int, data_pages: list[int], *, indexed: bool) -> None: + """Point the table's HEADER page at its data. + + A header page is not empty: past its 0x28-byte header it holds an index — + its own number, the FIRST DATA PAGE, 0x03FFFFFF, 0, a u16 entry count, + 0x1FFF, then entries `page << 3 | flag` padded with 0x1FFFFFF8. Every + table with data points at its first data page (left at 0x03FFFFFF, + rekordbox calls the library corrupted); the indexed tables (tracks, the + playlist tree, history) also list every data page — flag 3 for a page + with room, 0 for a full one — and the header's u7 is that count, u5 the + number of pages with room and num_rows_large the first of them. + """ + o = header_page * PAGE + struct.pack_into(" None: + """The history header row counts the library's tracks (and flags that + it has any): 8 on a real 8-track export, 0 in the empty template.""" + _, _, first, last = self.tables[HISTORY] + for _header, row in _rows(bytes(self.buf), first, last): + if row is not None: + self.buf[row + 3] = 1 if n else 0 + struct.pack_into(" None: + """The history header row records the library's creation date.""" + _, _, first, last = self.tables[HISTORY] + o = last * PAGE + page = self.buf[o:o + PAGE] + m = re.search(rb"\d{4}-\d{2}-\d{2}", page[_HEADER:]) + if m: + at = o + _HEADER + m.start() + self.buf[at:at + 10] = when.isoformat().encode("ascii") + + def render(self) -> bytes: + for t, (slot, empty, first, last) in self.tables.items(): + struct.pack_into("<4I", self.buf, 28 + 16 * slot, t, empty, first, last) + struct.pack_into(" bytes: + return (TEMPLATE_DIR / name).read_bytes() + + +# ---- the reader ---------------------------------------------------------------- + + +@dataclass +class Library: + """What a device library holds, decoded — for tests and diagnostics.""" + + tracks: list[dict] = field(default_factory=list) + genres: dict[int, str] = field(default_factory=dict) + artists: dict[int, str] = field(default_factory=dict) + albums: dict[int, str] = field(default_factory=dict) + labels: dict[int, str] = field(default_factory=dict) + keys: dict[int, str] = field(default_factory=dict) + artwork: dict[int, str] = field(default_factory=dict) + playlists: list[dict] = field(default_factory=list) + entries: list[tuple[int, int, int]] = field(default_factory=list) + pages: dict[int, list[dict]] = field(default_factory=dict) # table -> page headers + + +def _rows(buf: bytes, first: int, last: int): + """(page header dict, row offset) for every present row of a table.""" + p, seen = first, 0 + while True: + o = p * PAGE + if o + PAGE > len(buf): + return + flags = buf[o + 0x1B] + n = (buf[o + 0x19] >> 5) | (buf[o + 0x1A] << 3) + header = {"index": p, "flags": flags, "rows": n, + "next": struct.unpack_from(" 10000: + return + p, seen = header["next"], seen + 1 + + +def read(buf: bytes) -> Library: + lib = Library() + n_tables = struct.unpack_from(" list[PlatformOption]: absent option reads as a missing feature; a disabled one reads as a roadmap. """ supported = _export_targets() - return [ - PlatformOption( + options = [] + for d in registry.drivers(): + exporter = core_export.for_platform(d.platform) + options.append(PlatformOption( platform=d.platform, - name=d.display_name, + name=getattr(exporter, "display_name", None) or d.display_name, library_label=getattr(d, "library_label", ""), selects="directory", # an export destination is always a folder installed=d.platform in supported, found=0, removable=bool(getattr(d, "removable", False)), - drive_root=bool(getattr(core_export.for_platform(d.platform), "drive_root", False)), - ) - for d in registry.drivers() - ] + drive_root=bool(getattr(exporter, "drive_root", False)), + )) + # Targets with no reader of their own (the stick's legacy Device Library): + # listed too, or registering one would not make it selectable. + readers = {d.platform for d in registry.drivers()} + order = {e.platform: getattr(e, "menu_order", 1000) for e in core_export.exporters()} + for exporter in core_export.exporters(): + if exporter.platform in readers: + continue + options.append(PlatformOption( + platform=exporter.platform, + name=getattr(exporter, "display_name", exporter.platform), + library_label="", + selects="directory", + installed=True, + found=0, + removable=bool(getattr(exporter, "drive_root", False)), + drive_root=bool(getattr(exporter, "drive_root", False)), + )) + # Each exporter states its own place; a platform with no exporter (not yet a + # target, shown disabled) goes last. Stable, so equal places keep their order. + return sorted(options, key=lambda o: order.get(o.platform, 1000)) # ---- health / state --------------------------------------------------- diff --git a/backend/run_tests.sh b/backend/run_tests.sh index 5ceeeaa..ec97e7c 100755 --- a/backend/run_tests.sh +++ b/backend/run_tests.sh @@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")" source .venv/bin/activate fail=0 -for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_phase3.py test_history.py; do +for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py; do echo "──────────────────────────────────────────" echo "▶ $t" echo "──────────────────────────────────────────" diff --git a/backend/test_device_export.py b/backend/test_device_export.py new file mode 100644 index 0000000..92d83b8 --- /dev/null +++ b/backend/test_device_export.py @@ -0,0 +1,228 @@ +"""The "Rekordbox Export" target: a stick's legacy Device Library (`export.pdb`). + +What Rekordbox lists as a stick's Device Library and pre-OneLibrary players +read. There is no public spec, so this pins the writer to bytes REKORDBOX wrote: +rows and a whole page taken from a real rekordbox 7 device export +(`fixtures/rekordbox/device/reference_rows.json`) must be reproduced exactly. +Then the structure a player walks (page chains, allocation, row indexes), and +an export end to end — including that alongside the OneLibrary target the stick +carries ONE set of analysis files and artwork, as a rekordbox-made stick does. +""" +import json +import os +import struct +import sys +import tempfile +from pathlib import Path + +os.environ.setdefault("KONDUKTOR_DATA_DIR", tempfile.mkdtemp(prefix="konduktor-test-")) +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import numpy as np # noqa: E402 +import soundfile as sf # noqa: E402 +from PIL import Image # noqa: E402 + +import konduktor.adapters # noqa: E402,F401 — registers every target +from konduktor.adapters.rekordbox import pdb as P # noqa: E402 +from konduktor.core import export as core_export # noqa: E402 +from konduktor.core.export import ExportPayload, ExportPlaylist, ExportTrack # noqa: E402 +from konduktor.core.model import CuePoint, GridMarker, Track, TrackCues # noqa: E402 + +failed = False + + +def check(label, cond, detail=""): + global failed + print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else "")) + if not cond: + failed = True + + +REF = json.loads((P.TEMPLATE_DIR / "reference_rows.json").read_text()) + +print("== rows are rekordbox's bytes ==") +fields = REF["track_row_demo_track_2_fields"] +ours = P.track_row({k: v for k, v in fields.items() if k not in P.TRACK_STRINGS}, + {k: fields[k] for k in P.TRACK_STRINGS}) +check("a track row is byte-identical to rekordbox's", ours.hex() == REF["track_row_demo_track_2"]) +# rekordbox leaves variable slack after a row on its page (6-9 bytes, sometimes +# stale data); readers find rows through the page's index, never by size. So a +# row is compared over its own bytes. +artist = P.artist_row(1, "Loopmasters").rstrip(b"\0") +check("an artist row is byte-identical", REF["artist_row_loopmasters"].startswith(artist.hex())) +plist = P.playlist_tree_row(1, 0, 1, "demos", folder=False).rstrip(b"\0") +check("a playlist row is byte-identical", REF["playlist_row_demos"].startswith(plist.hex())) + +print("== a page is rekordbox's bytes ==") +page = bytes.fromhex(REF["keys_page"]) +n = (page[0x19] >> 5) | (page[0x1A] << 3) +used = struct.unpack_from(" 1, len(tpages)) +check("the first data page is the table's reserved candidate", tpages[0]["index"] == candidate) +check("further pages come from the next-unused counter", + all(p["index"] >= start_unused for p in tpages[1:])) +check("the chain ends in a fresh reserved candidate beyond every data page", + tpages[-1]["next"] >= max(p["index"] for p in tpages)) +check("the header page still starts the chain", lib.pages[P.TRACKS][0]["index"] == first) +check("every page's free space follows rekordbox's arithmetic", + all(p["free"] == P.PAGE - 0x28 - p["used"] - (2 * p["rows"] + 4 * ((p["rows"] + 15) // 16)) for p in tpages)) +check("tracks pages carry flags 0x34, others 0x24", + all(p["flags"] == 0x34 for p in tpages) + and all(p["flags"] == 0x24 for p in lib.pages[P.ARTISTS] if not p["flags"] & 0x40)) +fixed_pages = (13, 14, 33, 34, 35, 36, 37, 38) +check("the fixed tables (colours, columns, menus) are untouched", + all(out[p * P.PAGE:(p + 1) * P.PAGE] == tmpl[p * P.PAGE:(p + 1) * P.PAGE] for p in fixed_pages)) +print("== header pages index their data (else rekordbox: 'Device library is corrupted') ==") +# A header page holds an index: its own number, the FIRST DATA PAGE, ... a +# count and entries `page << 3 | flag`. Left pointing nowhere, rekordbox 7 called +# a Konduktor-written library corrupted. Rules read off a real export. +w.stamp_track_count(40) +out = w.render() +def index(buf, table): + _t, _e, first, _l = next(struct.unpack_from("<4I", buf, 28 + 16 * i) for i in range(20) + if struct.unpack_from("> 3, e & 7) for e in struct.unpack_from(f"<{n}I", buf, o + 0x3C)], + struct.unpack_from("<2H", buf, o + 0x20), struct.unpack_from(" House > Peak, plus Other for loose tracks", + tree["GIG"]["folder"] and tree["House"]["parent"] == tree["GIG"]["id"] + and tree["Peak"]["parent"] == tree["House"]["id"] and tree["Other"]["parent"] == tree["GIG"]["id"]) +peak = [e for e in lib.entries if e[2] == tree["Peak"]["id"]] +check("playlist entries in order, 1-based", peak == [(1, 1, tree["Peak"]["id"]), (2, 2, tree["Peak"]["id"])], peak) +check("every track has an analysis path, and the files exist", + all((root / t["analyze_path"].lstrip("/")).is_file() for t in lib.tracks)) +check("artwork rows name the a.jpg files, which exist", + all((root / p.lstrip("/")).is_file() for p in lib.artwork.values()) and len(lib.artwork) == 3) +check("every file written is reported, so a re-export can clear it", + all(p.exists() for p in written.all_paths)) + +print("== alongside OneLibrary: one set of analysis files and artwork ==") +both = Path(tempfile.mkdtemp()) +for t in tracks: + dst = both / t.destination.relative_to(root) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_bytes(t.destination.read_bytes()) +import dataclasses # noqa: E402 +moved = [dataclasses.replace(t, destination=both / t.destination.relative_to(root)) for t in tracks] +both_payload = ExportPayload(name="GIG", tracks=moved, playlists=payload.playlists) +ol_written = core_export.for_platform("onelibrary").write(both_payload, both) +stamp = {p: p.stat().st_mtime_ns for p in ol_written.extra if p.suffix in (".DAT", ".EXT", ".2EX")} +calls = [] +both_payload.checkpoint = calls.append +dev_written = dev.write(both_payload, both) +dat_files = sorted(both.rglob("*.DAT")) +check("still one .DAT per track", len(dat_files) == 3, len(dat_files)) +check("the device library reuses the analysis OneLibrary wrote (not rewritten)", + all(p.stat().st_mtime_ns == m for p, m in stamp.items())) +lib2 = P.read(dev_written.library.read_bytes()) +from konduktor.adapters.onelibrary.driver import OneLibraryDriver # noqa: E402 +ol = OneLibraryDriver().open(both) +check("both libraries point at the same analysis files", + sorted(str(r.analysisDataFilePath) for r in ol._store.iter_content()) == sorted(t["analyze_path"] for t in lib2.tracks)) +check("the a.jpg files both write are the same files", + {p.name for p in (both / "PIONEER/Artwork/00001").iterdir()} >= {Path(v).name for v in lib2.artwork.values()}) +check("progress is reported per track", len(calls) == 3, calls) + +print("== the export dialog lists the targets in a fixed order ==") +from fastapi.testclient import TestClient # noqa: E402 +from konduktor.main import app # noqa: E402 + +names = [o["name"] for o in TestClient(app).get("/api/export-targets").json()] +check("OneLibrary, Traktor, Rekordbox Export, Rekordbox Library", + names[:4] == ["OneLibrary", "Traktor", "Rekordbox Export", "Rekordbox Library"], names) + +print("\n" + ("❌ FAILED" if failed else "✅ PASSED")) +raise SystemExit(1 if failed else 0) diff --git a/frontend/src/lib/platformIcons.tsx b/frontend/src/lib/platformIcons.tsx index bc846ca..d3ea9b9 100644 --- a/frontend/src/lib/platformIcons.tsx +++ b/frontend/src/lib/platformIcons.tsx @@ -52,6 +52,12 @@ const MARKS: Record = { onelibrary: () => , } +/** Export targets that are another FORMAT of a platform, drawn with its mark: + * "Rekordbox Export" (a stick's Device Library) is still Rekordbox. */ +const ALIASES: Record = { + rekordbox_export: 'rekordbox', +} + export function PlatformIcon({ platform, size = 20, @@ -63,7 +69,7 @@ export function PlatformIcon({ }) { // Masks are addressed by id, and one page can show the same mark twice. const mask = `pm-${useId().replace(/:/g, '')}` - const Mark = MARKS[platform] + const Mark = MARKS[platform] ?? MARKS[ALIASES[platform]] if (!Mark) return return (