Implemented Device Library and OneLibrary sync

This commit is contained in:
patben8 committed 2026-10-01 16:00:33 +02:00
1 parent e73fa05e1f
commit c5280a95f2
3 files changed
+384 -4

No files matched your search

@@ -0,0 +1,192 @@
"""Keeping a stick's legacy Device Library (`export.pdb`) in step with its OneLibrary.
Most rekordbox sticks carry BOTH: `exportLibrary.db` (OneLibrary, newer players)
and `export.pdb` (the Device Library, older players and rekordbox's own "Device
Library" view). Cues and the grid live in the analysis files both share, so they
follow an edit by themselves; titles and playlists live in each database
separately. **rekordbox itself lets them drift**: measured on Goober
(2026-10-01), its edits updated the pdb's track metadata but not a new playlist
or a reorder. Konduktor rebuilds the pdb at Save instead (decision 2 of the
editing discussion), so a stick never shows different playlists depending on
which player reads it.
**Ids are mirrored, not assigned.** rekordbox exports both libraries from the
same ids — pdb track id = `content_id`, the artist/album/genre/label/key ids, the
playlist ids, playlist `sort` = `sequenceNo`, entries `(sequenceNo, content_id,
playlist_id)`, artwork id = `image_id` — all checked on Goober. So the OneLibrary
database IS the answer for every row the pdb shares with it.
**An edit, not a regeneration.** The stick's own `export.pdb` is edited in place
(`pdb.PdbEditor`): only the tracks, the four lookup tables and the playlist tree
and entries are candidates, a table is rewritten only if one of its rows changed,
and an unchanged row keeps rekordbox's bytes. A changed TRACK row is the old row
with the edited fields overwritten, so everything the pdb holds that OneLibrary
does not — the phrase-analysis strings, the `masterDbId` halves, play counts,
dates — survives. History, colours, menus, artwork, keys and `exportExt.pdb` are
never touched.
"""
from __future__ import annotations
import struct
from pathlib import Path
from ..rekordbox import pdb
#: Tables this rebuild owns. Everything else in the file is left as it is.
_OWNED = (pdb.TRACKS, pdb.ARTISTS, pdb.ALBUMS, pdb.GENRES, pdb.LABELS,
pdb.PLAYLIST_TREE, pdb.PLAYLIST_ENTRIES)
def _lookup_name(table: int, row: bytes) -> str:
if table == pdb.ARTISTS:
sub, _shift, _rid, _b, ofs = struct.unpack_from("<HHIBB", row, 0)
if sub == 0x64:
ofs = struct.unpack_from("<H", row, 10)[0]
return pdb.read_dsql(row, ofs)
if table == pdb.ALBUMS:
sub, _shift, _u, _artist, _rid, _u3, _b, ofs = struct.unpack_from("<HHIIIIBB", row, 0)
return pdb.read_dsql(row, ofs)
return pdb.read_dsql(row, 4)
def _tree_value(row: bytes) -> tuple:
parent, _u, sort, rid, folder = struct.unpack_from("<5I", row, 0)
return parent, sort, rid, bool(folder), pdb.read_dsql(row, 20)
def _merge(old: list[bytes], new: dict, table: int, same) -> list[bytes] | None:
"""The table's rows: old ORDER kept, an unchanged row's old BYTES kept, new
rows appended by id. None when nothing changed (the table is not rewritten).
`new` maps row id -> (value, encode()); `same(old_row, value)` says whether
an old row already says `value`.
"""
out, changed, seen = [], False, set()
for row in old:
rid = pdb.row_id(table, row)
if rid not in new:
changed = True # removed
continue
seen.add(rid)
value, encode = new[rid]
if same(row, value):
out.append(row)
else:
out.append(encode())
changed = True
for rid in sorted((r for r in new if r not in seen), key=str):
out.append(new[rid][1]())
changed = True
return out if changed else None
def rebuild(existing: bytes, session) -> bytes | None:
"""`export.pdb` edited to match the OneLibrary database open in `session`
(the working copy, edits committed); None if it already matches."""
from sqlalchemy import text
tables: dict[int, list[bytes]] = {}
# ---- lookups ----------------------------------------------------------------
for table, sql, build in (
(pdb.ARTISTS, "SELECT artist_id, name FROM artist", pdb.artist_row),
# rekordbox's export leaves an album's artist 0 (see `pdb.album_row`).
(pdb.ALBUMS, "SELECT album_id, name FROM album", pdb.album_row),
(pdb.GENRES, "SELECT genre_id, name FROM genre", pdb.id_string_row),
(pdb.LABELS, "SELECT label_id, name FROM label", pdb.id_string_row),
):
want = {int(i): (name or "", (lambda i=i, n=name, b=build: b(int(i), n or "")))
for i, name in session.execute(text(sql))}
merged = _merge(pdb.table_rows(existing, table), want, table,
lambda row, value, t=table: _lookup_name(t, row) == value)
if merged is not None:
tables[table] = merged
# ---- tracks -----------------------------------------------------------------
old_tracks = {pdb.row_id(pdb.TRACKS, r): r for r in pdb.table_rows(existing, pdb.TRACKS)}
want = {}
for (cid, title, artist, remixer, album, genre, label, rating, bpm, year, released,
comment, *fresh) in session.execute(text(
"SELECT content_id, title, artist_id_artist, artist_id_remixer, album_id, genre_id, "
"label_id, rating, bpmx100, releaseYear, releaseDate, djComment, "
"path, fileName, fileSize, fileType, bitrate, bitDepth, samplingRate, length, "
"analysisDataFilePath, dateAdded, key_id, image_id FROM content")):
cid = int(cid)
if cid in old_tracks:
fields, strings = pdb.track_fields(old_tracks[cid])
else:
fields, strings = _fresh_track(cid, *fresh)
fields = {**fields, "artist_id": artist or 0, "remixer_id": remixer or 0,
"album_id": album or 0, "genre_id": genre or 0, "label_id": label or 0,
"rating": max(0, min(5, int(rating or 0))), "tempo": int(bpm or 0),
"year": int(year or 0)}
strings = {**strings, "title": title or "", "comment": comment or "",
"release_date": released or ""}
want[cid] = ((fields, strings),
(lambda f=fields, s=strings: pdb.track_row(f, s)))
merged = _merge(list(old_tracks.values()), want, pdb.TRACKS,
lambda row, value: _same_track(pdb.track_fields(row), value))
if merged is not None:
tables[pdb.TRACKS] = merged
# ---- playlists ----------------------------------------------------------------
want = {int(pid): ((int(parent or 0), int(seq or 0), int(pid), int(attr or 0) == 1, name or ""),
(lambda p=pid, par=parent, s=seq, n=name, a=attr:
pdb.playlist_tree_row(int(p), int(par or 0), int(s or 0), n or "",
folder=int(a or 0) == 1)))
for pid, parent, seq, name, attr in session.execute(text(
"SELECT playlist_id, playlist_id_parent, sequenceNo, name, attribute FROM playlist"))}
merged = _merge(pdb.table_rows(existing, pdb.PLAYLIST_TREE), want, pdb.PLAYLIST_TREE,
lambda row, value: _tree_value(row) == value)
if merged is not None:
tables[pdb.PLAYLIST_TREE] = merged
want = {}
for pid, cid, seq in session.execute(text(
"SELECT playlist_id, content_id, sequenceNo FROM playlist_content "
"ORDER BY playlist_id, sequenceNo")):
key = (int(seq), int(cid), int(pid))
want[key] = (key, (lambda k=key: pdb.playlist_entry_row(*k)))
merged = _merge(pdb.table_rows(existing, pdb.PLAYLIST_ENTRIES), want, pdb.PLAYLIST_ENTRIES,
lambda row, value: True)
if merged is not None:
tables[pdb.PLAYLIST_ENTRIES] = merged
if not tables:
return None
editor = pdb.PdbEditor(existing)
for table in _OWNED:
if table in tables:
editor.refill(table, tables[table])
return editor.render()
def _same_track(old: tuple[dict, dict], new: tuple[dict, dict]) -> bool:
"""Equal in every field that means something: `index_shift` is the row's slot
in its page, re-stamped whenever a page is written."""
(of, os_), (nf, ns) = old, new
return ({k: v for k, v in of.items() if k != "index_shift"}
== {k: v for k, v in nf.items() if k != "index_shift"} and os_ == ns)
def _fresh_track(cid: int, path, file_name, file_size, file_type, bitrate, bit_depth,
sample_rate, length, analysis, date_added, key_id, image_id) -> tuple[dict, dict]:
"""A track the pdb has never listed (one added to the stick by Konduktor), in
the shape `device_export` writes one — the values a rekordbox device export
was measured to carry (see that module)."""
from ..rekordbox.device_export import ANALYSED, BITMASK
added = str(date_added or "")[:10]
fields = {
"subtype": 0x24, "bitmask": BITMASK, "sample_rate": int(sample_rate or 0),
"file_size": int(file_size or 0), "u2": cid + 0x600, "artwork_id": int(image_id or 0),
"key_id": int(key_id or 0), "bitrate": int(bitrate or 0), "id": cid,
"sample_depth": int(bit_depth or 0), "duration": min(int(length or 0), 0xFFFF),
"u5": ANALYSED, "u6": int(file_type or 0), "u7": 3,
}
strings = {
"kuvo_public": "ON", "autoload_hotcues": "ON", "date_added": added,
"analyze_path": analysis or "", "analyze_date": added,
"filename": file_name or Path(str(path or "")).name, "file_path": path or "",
}
return fields, strings
+29 -4
View File
@@ -145,6 +145,7 @@ class OneLibraryStore(ReplaceGridCommands):
self._db = None self._db = None
self._work: Path | None = None self._work: Path | None = None
self._opened_as: tuple | None = None self._opened_as: tuple | None = None
self._pdb_seen: tuple | None = None
self._journal = EditJournal() self._journal = EditJournal()
# Parsed ANLZ, keyed by track id. Two caches because the two files cost # Parsed ANLZ, keyed by track id. Two caches because the two files cost
# an order of magnitude apart: a grid read must not drag in the .EXT. # an order of magnitude apart: a grid read must not drag in the .EXT.
@@ -171,6 +172,7 @@ class OneLibraryStore(ReplaceGridCommands):
work = Path(tempfile.mkdtemp(prefix="drive-", dir=_work_root())) work = Path(tempfile.mkdtemp(prefix="drive-", dir=_work_root()))
try: try:
self._opened_as = _fingerprint(self.path) self._opened_as = _fingerprint(self.path)
self._pdb_seen = _fingerprint_file(self.device_library) if self.device_library.is_file() else None
working = work / self.path.name working = work / self.path.name
shutil.copyfile(self.path, working) shutil.copyfile(self.path, working)
for suffix in _SIDECARS[:1]: # the WAL carries data; -shm is rebuilt for suffix in _SIDECARS[:1]: # the WAL carries data; -shm is rebuilt
@@ -213,6 +215,12 @@ class OneLibraryStore(ReplaceGridCommands):
self.close() self.close()
self._load() self._load()
@property
def device_library(self) -> Path:
"""The legacy `export.pdb` beside the OneLibrary database — on most
rekordbox sticks; rebuilt at Save when present (`device_library.py`)."""
return self.path.with_name("export.pdb")
def _require_db(self): def _require_db(self):
if self._db is None: if self._db is None:
raise LibraryNotSupported("The OneLibrary database is closed") raise LibraryNotSupported("The OneLibrary database is closed")
@@ -890,13 +898,15 @@ class OneLibraryStore(ReplaceGridCommands):
In this order, each step a precondition for the next: In this order, each step a precondition for the next:
1. the drive is still there, and NOTHING else has written its database 1. the drive is still there, and NOTHING else has written its database
(or an analysis file this save rewrites) since Konduktor read it — (or an analysis file, or `export.pdb`) since Konduktor read it —
otherwise this would silently undo that; otherwise this would silently undo that;
2. the drive's current database and those analysis files are backed 2. the drive's current database and those analysis files are backed
up to app-data; up to app-data;
3. each edited analysis file is written beside itself and renamed over 3. each edited analysis file is written beside itself and renamed over
it — BEFORE the database, as the Rekordbox store writes files before it — BEFORE the database, as the Rekordbox store writes files before
committing, so a failure here leaves the database untouched; committing, so a failure here leaves the database untouched — and
then, where the stick has one, the legacy `export.pdb`, edited to
match (`device_library.rebuild`; untouched if it already does);
4. the working copy is committed and closed, which folds its WAL in, so 4. the working copy is committed and closed, which folds its WAL in, so
the copy is one self-contained file; the copy is one self-contained file;
5. the copy is written beside the drive's database under a temporary 5. the copy is written beside the drive's database under a temporary
@@ -920,7 +930,8 @@ class OneLibraryStore(ReplaceGridCommands):
for path, (edited, seen) in self._pending_anlz.items(): for path, (edited, seen) in self._pending_anlz.items():
if not path.is_file() or _fingerprint_file(path) != seen: if not path.is_file() or _fingerprint_file(path) != seen:
changed_anlz.append(path) changed_anlz.append(path)
if _fingerprint(self.path) != self._opened_as or changed_anlz: pdb_now = _fingerprint_file(self.device_library) if self.device_library.is_file() else None
if _fingerprint(self.path) != self._opened_as or changed_anlz or pdb_now != self._pdb_seen:
raise InvalidCommand( raise InvalidCommand(
f"Another app has changed {self.layout.root.name} since Konduktor " f"Another app has changed {self.layout.root.name} since Konduktor "
"opened it, and saving would undo that. Discard your changes and " "opened it, and saving would undo that. Discard your changes and "
@@ -933,8 +944,17 @@ class OneLibraryStore(ReplaceGridCommands):
# command that failed after reading, leaves nothing to write. # command that failed after reading, leaves nothing to write.
anlz_writes = [(path, data) for path, (edited, _seen) in self._pending_anlz.items() anlz_writes = [(path, data) for path, (edited, _seen) in self._pending_anlz.items()
if (data := edited.to_bytes()) != path.read_bytes()] if (data := edited.to_bytes()) != path.read_bytes()]
# The legacy Device Library, edited to match (None: already does). Read
# inside the transaction, which sees every edit.
pdb_bytes = None
if self.device_library.is_file():
from . import device_library
self._backup([path for path, _ in anlz_writes]) db.flush()
pdb_bytes = device_library.rebuild(self.device_library.read_bytes(), db.session)
self._backup([path for path, _ in anlz_writes]
+ ([self.device_library] if pdb_bytes is not None else []))
for path, data in anlz_writes: for path, data in anlz_writes:
partial = path.with_name(f".{path.name}.konduktor-partial") partial = path.with_name(f".{path.name}.konduktor-partial")
partial.write_bytes(data) partial.write_bytes(data)
@@ -942,6 +962,11 @@ class OneLibraryStore(ReplaceGridCommands):
# Ours now: a retry after a later failure must not mistake this # Ours now: a retry after a later failure must not mistake this
# write for another app's. # write for another app's.
self._pending_anlz[path] = (self._pending_anlz[path][0], _fingerprint_file(path)) self._pending_anlz[path] = (self._pending_anlz[path][0], _fingerprint_file(path))
if pdb_bytes is not None:
partial = self.device_library.with_name(".export.pdb.konduktor-partial")
partial.write_bytes(pdb_bytes)
os.replace(partial, self.device_library)
self._pdb_seen = _fingerprint_file(self.device_library)
db.session.commit() db.session.commit()
work, working = self._work, self._work / self.path.name work, working = self._work, self._work / self.path.name
+163
View File
@@ -430,3 +430,166 @@ __all__ = [
"album_row", "artist_row", "dsql", "id_string_row", "key_row", "playlist_entry_row", "album_row", "artist_row", "dsql", "id_string_row", "key_row", "playlist_entry_row",
"playlist_tree_row", "read", "read_dsql", "template", "track_row", "playlist_tree_row", "read", "read_dsql", "template", "track_row",
] ]
# ---- editing an existing library -----------------------------------------------
#
# Editing a stick rekordbox wrote, rather than writing one from the template:
# only the tables whose rows change are rewritten, and inside them a row that
# does not change keeps rekordbox's own bytes. Every other table — history,
# colours, menus, artwork — stays byte-identical, and so does exportExt.pdb.
def _chain(buf: bytes, first: int, last: int) -> list[int]:
"""A table's page chain, header page first."""
pages, p = [first], first
while p != last and len(pages) < 100000:
p = struct.unpack_from("<I", buf, p * PAGE + 12)[0]
pages.append(p)
return pages
def table_rows(buf: bytes, table: int) -> list[bytes]:
"""Every present row of `table`, in page order, as its own bytes (padding
included) — a row's extent is up to the next row's heap offset, or the end
of the page's used heap."""
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)
if t != table:
continue
out = []
for p in _chain(buf, first, last)[1:]:
o = p * PAGE
if buf[o + 0x1B] & _HEADER_PAGE:
continue
n = (buf[o + 0x19] >> 5) | (buf[o + 0x1A] << 3)
used = struct.unpack_from("<H", buf, o + 0x1E)[0]
offs, present = [], []
# As `_rows` reads them: every bit of every group, since a page
# rekordbox has edited holds more row slots than its small count.
for g in range((n + 15) // 16):
base = o + PAGE - g * _GROUP
mask = struct.unpack_from("<H", buf, base - 4)[0]
for r in range(16):
if mask & (1 << r):
offs.append(struct.unpack_from("<H", buf, base - 6 - 2 * r)[0])
present.append(True)
ends = sorted(set(offs)) + [used]
for off, ok in zip(offs, present):
if ok:
end = next(e for e in ends if e > off)
row = bytes(buf[o + _HEADER + off:o + _HEADER + end])
if table == TRACKS:
row = row[:track_extent(row)]
out.append(row)
return out
return []
def _dsql_len(buf: bytes, off: int) -> int:
head = buf[off]
return (head >> 1) if head & 1 else struct.unpack_from("<H", buf, off + 1)[0]
def track_extent(row: bytes) -> int:
"""Where a track row really ends: past its last string, 4-aligned.
NOT the next row's offset: rekordbox reuses its heap, and the bytes between
a row and the next can be a stale tail of an older, longer string (seen on
Goober: `...mp3` followed by `ing.stem.m4a`)."""
offs = struct.unpack_from(f"<{len(TRACK_STRINGS)}H", row, _TRACK_FIXED)
end = max(o + _dsql_len(row, o) for o in offs)
return end + (-end % 4)
def track_fields(row: bytes) -> tuple[dict, dict]:
"""A raw track row as (`fields`, `strings`) — what `track_row` takes back."""
fields = dict(zip([n for n, _ in _TRACK_FIELDS], struct.unpack_from(_TRACK_FMT, row, 0)))
offs = struct.unpack_from(f"<{len(TRACK_STRINGS)}H", row, _TRACK_FIXED)
return fields, {name: read_dsql(row, o) for name, o in zip(TRACK_STRINGS, offs)}
def row_id(table: int, row: bytes) -> int | tuple:
"""A row's identity within its table (the triple, for playlist entries)."""
if table == TRACKS:
return track_fields(row)[0]["id"]
if table == ARTISTS:
return struct.unpack_from("<I", row, 4)[0]
if table == ALBUMS:
return struct.unpack_from("<I", row, 12)[0]
if table == PLAYLIST_TREE:
return struct.unpack_from("<I", row, 12)[0]
if table == PLAYLIST_ENTRIES:
return struct.unpack_from("<3I", row, 0)
return struct.unpack_from("<I", row, 0)[0]
class PdbEditor(PdbWriter):
"""`PdbWriter` over an EXISTING library: `refill` replaces one table's rows.
The table keeps its pages — overwritten in place, more taken from the
next-unused counter if needed, any left over unlinked and blanked (a blank
reserved page inside the file is a state rekordbox's own template has) —
and keeps its empty candidate. `render` leaves the header's
pages-with-room field as it was: rekordbox did not touch it when it edited
Goober, and it is the least understood field in the file.
"""
def __init__(self, existing: bytes):
super().__init__(existing)
self._room_field = struct.unpack_from("<I", self.buf, 16)[0]
self._blank: set[int] = set()
def refill(self, table: int, rows: list[bytes]) -> None:
slot, candidate, first, last = self.tables[table]
old = _chain(bytes(self.buf), first, last)[1:]
if candidate in old:
old.remove(candidate)
chunks = _chunk(rows) if rows else []
indices = old[:len(chunks)] + [self._alloc() for _ in chunks[len(old):]]
for p in old[len(chunks):]:
self._blank.add(p)
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
fill = None
if indexed:
fill = (len(chunk) + 1, 0) if i + 1 == len(chunks) 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._reindex(first, indices, indexed=indexed)
self.tables[table] = [slot, candidate, first, indices[-1] if indices else first]
if not indices:
# No rows: the header page points straight at the candidate again.
struct.pack_into("<I", self.buf, first * PAGE + 12, candidate)
def _reindex(self, header_page: int, data_pages: list[int], *, indexed: bool) -> None:
o = header_page * PAGE
struct.pack_into("<I", self.buf, o + 12, data_pages[0] if data_pages else
struct.unpack_from("<I", self.buf, o + 12)[0])
if indexed:
# Clear the old entries first: a table that shrank must not keep
# listing pages it no longer has.
count = struct.unpack_from("<H", self.buf, o + _HEADER + 16)[0]
for k in range(max(count, len(data_pages))):
struct.pack_into("<I", self.buf, o + _HEADER + 20 + 4 * k, 0x1FFFFFF8)
if data_pages:
pages_with_room = self.pages_with_room
self._index(header_page, data_pages, indexed=indexed)
self.pages_with_room = pages_with_room
else:
struct.pack_into("<I", self.buf, o + _HEADER + 4, 0x03FFFFFF)
if indexed:
struct.pack_into("<HH", self.buf, o + _HEADER + 16, 0, 0x1FFF)
struct.pack_into("<HH", self.buf, o + 0x20, _NONE, _NONE)
struct.pack_into("<H", self.buf, o + 0x26, 0)
def render(self) -> bytes:
out = bytearray(super().render())
struct.pack_into("<I", out, 16, self._room_field)
for p in self._blank - set(self.pages):
out[p * PAGE:(p + 1) * PAGE] = bytes(PAGE)
return bytes(out)