Added support for legacy Rekordbox exports

This commit is contained in:
patben8 committed 2026-09-27 23:19:53 +02:00
1 parent 0b909a84f4
commit 4b9716d47a
17 files changed
+1058 -10

No files matched your search

+24 -1
View File
@@ -1084,7 +1084,30 @@ that number and nothing else — everything derives from it:
(`share/PIONEER/Artwork/<uuid[:3]>/<uuid[3:]>/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<n>.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
@@ -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.
Binary file not shown.
Binary file not shown.
@@ -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": "000000000c0000000500000034000000140000000000000002400024b80f1800010001000000000001000000010000000941626d020000000200000007456d0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000Line truncated
}
+3
View File
@@ -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(
@@ -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.
@@ -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)
@@ -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<n>.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<n>.jpg` / `a<n>_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
@@ -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
+432
View File
@@ -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("<BHB", 0x90, len(wide) + 4, 0) + wide
if len(raw) <= 126:
return bytes([((len(raw) + 1) << 1) | 1]) + raw
return struct.pack("<BHB", 0x40, len(raw) + 4, 0) + raw
def read_dsql(buf: bytes, off: int) -> 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("<H", buf, off + 1)[0]
body = buf[off + 4:off + n]
return body.decode("utf-16-le" if head == 0x90 else "ascii", "replace")
def _pad4(row: bytes) -> 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("<I", row_id) + dsql(text))
def key_row(row_id: int, name: str) -> bytes:
"""Keys store their id twice."""
return _pad4(struct.pack("<II", row_id, row_id) + dsql(name))
def artist_row(row_id: int, name: str) -> bytes:
"""Subtype 0x60: the name starts at a fixed offset of 10."""
return _pad4(struct.pack("<HHIBB", 0x60, 0, row_id, 0x03, 10) + dsql(name))
def album_row(row_id: int, name: str, artist_id: int = 0) -> 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("<HHIIIIBB", 0x80, 0, 0, artist_id, row_id, 0, 0x03, 22) + dsql(name))
def playlist_tree_row(row_id: int, parent_id: int, sort_order: int, name: str, *, folder: bool) -> bytes:
return _pad4(struct.pack("<IIIII", parent_id, 0, sort_order, row_id, 1 if folder else 0) + dsql(name))
def playlist_entry_row(entry_index: int, track_id: int, playlist_id: int) -> bytes:
return struct.pack("<III", entry_index, track_id, playlist_id)
# ---- pages ---------------------------------------------------------------------
def _index_space(n: int) -> 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("<H", row, shift_at, slot << 5)
offsets.append(len(heap))
heap += row
n = len(rows)
groups = (n + 15) // 16
page[_HEADER:_HEADER + len(heap)] = heap
for g in range(groups):
base = PAGE - g * _GROUP
k = min(16, n - 16 * g)
struct.pack_into("<H", page, base - 4, (1 << k) - 1) # present
struct.pack_into("<H", page, base - 2, 1 << (k - 1)) # last written
for r in range(k):
struct.pack_into("<H", page, base - 6 - 2 * r, offsets[16 * g + r])
used = len(heap)
free = PAGE - _HEADER - used - (2 * n + 4 * groups)
struct.pack_into("<6I", page, 0, 0, index, table, next_page, sequence, 0)
page[0x18] = n & 0xFF
page[0x19] = ((n >> 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("<I", self.buf, 8)[0]
self.next_unused = struct.unpack_from("<I", self.buf, 12)[0]
self.sequence = struct.unpack_from("<I", self.buf, 20)[0]
self.tables = {}
self.pages_with_room = 0
for i in range(n_tables):
t, empty, first, last = struct.unpack_from("<4I", self.buf, 28 + 16 * i)
self.tables[t] = [i, empty, first, last]
def _alloc(self) -> 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("<I", self.buf, o + _HEADER + 4, data_pages[0])
if not indexed:
return
flags = [3 if i + 1 == len(data_pages) else 0 for i in range(len(data_pages))]
struct.pack_into("<HH", self.buf, o + _HEADER + 16, len(data_pages), 0x1FFF)
for k, (page, flag) in enumerate(zip(data_pages, flags)):
struct.pack_into("<I", self.buf, o + _HEADER + 20 + 4 * k, (page << 3) | flag)
room = [k for k, flag in enumerate(flags) if flag == 3]
struct.pack_into("<HH", self.buf, o + 0x20, len(room) or _NONE, room[0] if room else _NONE)
struct.pack_into("<H", self.buf, o + 0x26, len(data_pages))
self.pages_with_room += len(room)
def stamp_track_count(self, n: int) -> 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("<I", self.buf, row + 4, n)
break
if n:
# A library with tracks also INDEXES its history page — entry
# `page << 3 | 0`, count 1, u7 1 — which the empty template does not.
o = first * PAGE
struct.pack_into("<HH", self.buf, o + _HEADER + 16, 1, 0x1FFF)
struct.pack_into("<I", self.buf, o + _HEADER + 20, last << 3)
struct.pack_into("<H", self.buf, o + 0x26, 1)
def stamp_history_date(self, when: date) -> 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("<I", self.buf, 12, self.next_unused)
# 1 in the empty template, 4 on a real export whose index lists three
# pages with room: 1 + that count fits both. The least certain field here.
struct.pack_into("<I", self.buf, 16, 1 + self.pages_with_room)
struct.pack_into("<I", self.buf, 20, self.sequence + 1)
top = max([len(self.buf) // PAGE - 1, *self.pages])
out = bytearray(self.buf) + bytes((top + 1) * PAGE - len(self.buf))
for index, page in self.pages.items():
out[index * PAGE:(index + 1) * PAGE] = page
return bytes(out)
def template(name: str = "export.pdb") -> 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("<I", buf, o + 12)[0],
"free": struct.unpack_from("<H", buf, o + 0x1C)[0],
"used": struct.unpack_from("<H", buf, o + 0x1E)[0]}
yield header, None
if not flags & _HEADER_PAGE:
for g in range((n + 15) // 16):
base = o + PAGE - g * _GROUP
present = struct.unpack_from("<H", buf, base - 4)[0]
for r in range(16):
if present & (1 << r):
yield header, o + _HEADER + struct.unpack_from("<H", buf, base - 6 - 2 * r)[0]
if p == last or seen > 10000:
return
p, seen = header["next"], seen + 1
def read(buf: bytes) -> Library:
lib = Library()
n_tables = struct.unpack_from("<I", buf, 8)[0]
for i in range(n_tables):
t, _empty, first, last = struct.unpack_from("<4I", buf, 28 + 16 * i)
for header, row in _rows(buf, first, last):
if row is None:
lib.pages.setdefault(t, []).append(header)
continue
if t == TRACKS:
values = dict(zip([n for n, _ in _TRACK_FIELDS], struct.unpack_from(_TRACK_FMT, buf, row)))
offs = struct.unpack_from(f"<{len(TRACK_STRINGS)}H", buf, row + _TRACK_FIXED)
values.update({name: read_dsql(buf, row + o) for name, o in zip(TRACK_STRINGS, offs)})
lib.tracks.append(values)
elif t in (GENRES, LABELS, ARTWORK):
target = {GENRES: lib.genres, LABELS: lib.labels, ARTWORK: lib.artwork}[t]
target[struct.unpack_from("<I", buf, row)[0]] = read_dsql(buf, row + 4)
elif t == KEYS:
lib.keys[struct.unpack_from("<I", buf, row)[0]] = read_dsql(buf, row + 8)
elif t == ARTISTS:
sub, _shift, rid, _b, ofs = struct.unpack_from("<HHIBB", buf, row)
if sub == 0x64:
ofs = struct.unpack_from("<H", buf, row + 10)[0]
lib.artists[rid] = read_dsql(buf, row + ofs)
elif t == ALBUMS:
sub, _shift, _u, artist, rid, _u3, _b, ofs = struct.unpack_from("<HHIIIIBB", buf, row)
lib.albums[rid] = read_dsql(buf, row + ofs)
elif t == PLAYLIST_TREE:
parent, _u, sort, rid, folder = struct.unpack_from("<5I", buf, row)
lib.playlists.append({"id": rid, "parent": parent, "sort": sort,
"folder": bool(folder), "name": read_dsql(buf, row + 20)})
elif t == PLAYLIST_ENTRIES:
lib.entries.append(struct.unpack_from("<3I", buf, row))
return lib
__all__ = [
"ALBUMS", "ARTISTS", "ARTWORK", "GENRES", "KEYS", "LABELS", "Library", "PAGE",
"PLAYLIST_ENTRIES", "PLAYLIST_TREE", "PdbWriter", "TRACKS", "TRACK_STRINGS",
"album_row", "artist_row", "dsql", "id_string_row", "key_row", "playlist_entry_row",
"playlist_tree_row", "read", "read_dsql", "template", "track_row",
]
@@ -63,6 +63,7 @@ OTHER_PLAYLIST = "Other"
class TraktorExporter:
platform = "traktor"
menu_order = 20
library_filename = "collection.nml"
drive_root = False
+5
View File
@@ -115,6 +115,11 @@ class LibraryExporter(Protocol):
platform: str
#: What the written library file is called, e.g. "collection.nml".
library_filename: str
#: Where the target sits in the export dialog's list, lowest first. Optional
#: (unset sorts last): a stick's formats lead, a computer library trails.
#: The name the export dialog shows. Optional: a target named after its
#: platform omits it and the driver's `display_name` is used. Needed where
#: one platform has two targets ("Rekordbox Library" / "Rekordbox Export").
#: The library is only found when the destination is a DRIVE'S ROOT — a
#: player looks for it there and nowhere else. Several targets can share one
#: destination, so this is a warning the UI raises, not a refusal: the other
+27 -7
View File
@@ -621,19 +621,39 @@ def export_targets() -> 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 ---------------------------------------------------
+1 -1
View File
@@ -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 "──────────────────────────────────────────"
+228
View File
@@ -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("<H", page, 0x1E)[0]
offs = [struct.unpack_from("<H", page, P.PAGE - 6 - 2 * r)[0] for r in range(n)] + [used]
rows = [page[0x28 + offs[r]:0x28 + offs[r + 1]] for r in range(n)]
rebuilt = P._data_page(REF["keys_page_index"], P.KEYS, struct.unpack_from("<I", page, 12)[0], rows,
struct.unpack_from("<I", page, 16)[0], shift_at=None)
check("a data page rebuilt from its rows is byte-identical (header, heap, row index)", rebuilt == page)
print("== strings ==")
for text in ("", "Am", "x" * 126, "x" * 127, "Café del Mar", "日本語"):
enc = P.dsql(text)
check(f"{text[:12]!r} ({len(text)} chars) round-trips", P.read_dsql(enc, 0) == text)
check("up to 126 ASCII chars is a short string", P.dsql("x" * 126)[0] & 1 == 1)
check("127+ ASCII chars is a long ASCII string (0x40)", P.dsql("x" * 127)[0] == 0x40)
check("non-ASCII is UTF-16LE (0x90)", P.dsql("Café")[0] == 0x90)
print("== the writer follows rekordbox's allocation ==")
tmpl = P.template()
w = P.PdbWriter(tmpl)
_slot, candidate, first, _last = w.tables[P.TRACKS]
start_unused = w.next_unused
many = [P.track_row({"subtype": 0x24, "id": i}, {"title": f"Track {i} " + "x" * 200,
"file_path": f"/Contents/{i}.mp3"}) for i in range(1, 41)]
w.fill(P.TRACKS, many)
w.fill(P.ARTISTS, [P.artist_row(1, "A")])
out = w.render()
lib = P.read(out)
check("all 40 tracks read back, in order", [t["id"] for t in lib.tracks] == list(range(1, 41)))
tpages = [p for p in lib.pages[P.TRACKS] if not p["flags"] & 0x40]
check("they span several pages", len(tpages) > 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("<I", buf, 28 + 16 * i)[0] == table)
o = first * P.PAGE
n = struct.unpack_from("<H", buf, o + 0x38)[0]
return (struct.unpack_from("<I", buf, o + 0x2C)[0],
[(e >> 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("<H", buf, o + 0x26)[0])
first_data, entries, (u5, nrl), u7 = index(out, P.TRACKS)
check("the tracks header points at its first data page", first_data == tpages[0]["index"])
check("and lists every data page: full ones flag 0, the last (with room) flag 3",
entries == [(p["index"], 3 if k == len(tpages) - 1 else 0) for k, p in enumerate(tpages)], entries)
check("its u7 counts them; u5 / nrl = pages with room / the first of them",
u7 == len(tpages) and (u5, nrl) == (1, len(tpages) - 1), (u5, nrl, u7))
check("a non-indexed table's header still points at its data",
index(out, P.ARTISTS)[0] == next(p["index"] for p in P.read(out).pages[P.ARTISTS] if not p["flags"] & 0x40)
and index(out, P.ARTISTS)[1] == [])
h_first, h_entries, _, h_u7 = index(out, P.HISTORY)
check("with tracks, the history page is indexed too (flag 0, count 1)",
h_entries == [(h_first, 0)] and h_u7 == 1, (h_entries, h_u7))
hist_row = next(r for h, r in P._rows(out, *struct.unpack_from("<2I", out, 28 + 16 * 19 + 8)) if r is not None)
check("the history row counts the tracks and flags that there are some",
out[hist_row + 3] == 1 and struct.unpack_from("<I", out, hist_row + 4)[0] == 40)
full = [p for p in tpages[:-1]]
check("full tracks pages carry 0x1FFF/0x1FFF, the last rows+1 / 0",
all(struct.unpack_from("<2H", out, p["index"] * P.PAGE + 0x20) == (0x1FFF, 0x1FFF) for p in full)
and struct.unpack_from("<2H", out, tpages[-1]["index"] * P.PAGE + 0x20) == (tpages[-1]["rows"] + 1, 0))
check("the file header's second counter is 1 + pages with room", struct.unpack_from("<I", out, 16)[0] == 2)
try:
w.fill(P.TRACKS, many[:1])
check("filling a table twice is refused", False, "it accepted")
except ValueError:
check("filling a table twice is refused", True)
print("== an export end to end ==")
root = Path(tempfile.mkdtemp())
sr = 22050
tone = np.random.default_rng(1).uniform(-0.4, 0.4, sr * 6).astype(np.float32)
tracks = []
for i, (title, artist, key) in enumerate((("One", "Artist A", (8, "minor")), ("Two", "Artist B", (None, None)),
("Três", "Artist A", (8, "minor")))):
audio = root / "Contents" / ("House" if i < 2 else "Techno") / f"{title}.wav"
audio.parent.mkdir(parents=True, exist_ok=True)
sf.write(audio, tone, sr)
png = __import__("io").BytesIO()
Image.new("RGB", (300, 300), (40 * i, 90, 160)).save(png, format="PNG")
t = Track(id=f"src{i}", title=title, artist=artist, album="LP", genre="House", bpm=125.0,
key_wheel=key[0], key_mode=key[1], length=6, rating=i + 1, filepath=str(audio))
tracks.append(ExportTrack(track=t, destination=audio, art=(png.getvalue(), "image/png"),
cues=TrackCues(track_id=t.id, grid_markers=[GridMarker(start=0.0, bpm=125.0)],
cues=[CuePoint(type="cue", role="hotcue", start=1.0, length=0.0, slot=0)])))
payload = ExportPayload(name="GIG", tracks=tracks, playlists=[
ExportPlaylist(name="Peak", track_ids=["src0", "src1"], folders=["House"])])
dev = core_export.for_platform("rekordbox_export")
check("the target is registered, named 'Rekordbox Export'", dev is not None and dev.display_name == "Rekordbox Export")
check("and the master.db target is 'Rekordbox Library'",
core_export.for_platform("rekordbox").display_name == "Rekordbox Library")
written = dev.write(payload, root)
lib = P.read(written.library.read_bytes())
check("export.pdb lands in PIONEER/rekordbox/", written.library == root / "PIONEER" / "rekordbox" / "export.pdb")
check("with exportExt.pdb beside it", (root / "PIONEER" / "rekordbox" / "exportExt.pdb") in written.extra)
check("three tracks, titles intact (UTF-16 included)", [t["title"] for t in lib.tracks] == ["One", "Two", "Três"])
check("artists are shared, not duplicated", lib.artists == {1: "Artist A", 2: "Artist B"})
check("the key is rendered in rekordbox's notation", lib.keys == {1: "Am"}, lib.keys)
check("a track with no key has key 0", lib.tracks[1]["key_id"] == 0)
check("bpm x100, rating, file type, bitmask as rekordbox writes them",
all(t["tempo"] == 12500 and t["u6"] == 11 and t["bitmask"] == 0xC0700 and t["u5"] == 0x29 for t in lib.tracks)
and [t["rating"] for t in lib.tracks] == [1, 2, 3])
check("the file path is drive-relative", lib.tracks[0]["file_path"] == "/Contents/House/One.wav", lib.tracks[0]["file_path"])
check("no computer's masterDbId is claimed", all(t["u3"] == 0 and t["u4"] == 0 for t in lib.tracks))
tree = {p["name"]: p for p in lib.playlists}
check("the tree: a folder named after the export > 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<n>.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<n>.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)
+7 -1
View File
@@ -52,6 +52,12 @@ const MARKS: Record<string, Mark> = {
onelibrary: () => <path d="M44.29 9.4A41 41 0 1 0 58.52 90.1L55.41 75.43A26 26 0 1 1 46.38 24.25ZM61.58 89.33A41 41 0 0 0 66.41 87.57L61.23 75.71A28.05 28.05 0 0 1 57.92 76.91ZM70.13 85.72A41 41 0 0 0 74.45 82.92L67.45 73.5A29.27 29.27 0 0 1 64.37 75.5ZM77.65 80.28A41 41 0 0 0 81.22 76.57L73.09 69.65A30.32 30.32 0 0 1 70.44 72.39ZM83.75 73.28A41 41 0 0 0 86.4 68.87L77.65 64.33A31.14 31.14 0 0 1 75.63 67.68ZM88.12 65.09A41 41 0 0 0 89.71 60.2L80.71 57.89A31.71 31.71 0 0 1 79.48 61.67ZM90.54 56.13A41 41 0 0 0 90.99 51L81.97 50.78A31.98 31.98 0 0 1 81.62 54.78ZM90.88 46.85A41 41 0 0 0 90.16 41.76L81.29 43.58A31.94 31.94 0 0 1 81.85 47.55ZM89.12 37.74A41 41 0 0 0 87.28 32.93L78.73 36.84A31.6 31.6 0 0 1 80.16 40.55ZM85.36 29.25A41 41 0 0 0 82.48 24.98L74.54 31.1A30.97 30.97 0 0 1 76.72 34.33ZM79.79 21.83A41 41 0 0 0 76.02 18.32L69.1 26.75A30.09 30.09 0 0 1 71.86 29.32ZM72.69 15.85A41 41 0 0 0 68.23 13.28L62.89 24.02A29 29 0 0 1 66.05 25.85ZM64.43 11.62A41 41 0 0 0 59.5 10.12L56.43 23A27.75 27.75 0 0 1 59.77 24.02ZM55.42 9.36A41 41 0 0 0 50.29 9L50.18 23.58A26.42 26.42 0 0 1 53.49 23.81Z" />,
}
/** 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<string, string> = {
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 <Icon name="music" size={size} className={className} />
return (
<svg