Compare commits

..
78 changed files with 4019 additions and 338 deletions

No files matched your search

+133 -18
View File
@@ -47,6 +47,10 @@ Two independent apps that talk over HTTP:
- `registry.py` — adapter selection by **`can_open()` probe**, not extension
(Rekordbox is a `.db`, Serato is a directory).
- `audio_tags.py`, `pathmap.py` — format-agnostic helpers.
- `grid_edit.py` (`ReplaceGridCommands`) — the marker-level grid commands
(add / move-with-clamp / retempo / delete) for a store whose one primitive
is `replace_grid`: Rekordbox's and OneLibrary's, whose grids are per-beat
lists. Traktor keeps its own, companion-aware versions.
- `relocate.py` — **auto path remapping's search** (see `relocation.py`).
Fixes ONE thing: a stored prefix changed and the layout under it did not
(a collection built on Windows with the SSD as `X:`, opened on a Mac where
@@ -255,8 +259,9 @@ Two independent apps that talk over HTTP:
**Memory cues stay preserved-but-uneditable** (Rekordbox is the only
platform with them — the two-platform promotion rule).
**Hot cue colour is writable** (`set_cue_color`, `PATCH
/api/tracks/cue/color`) from `palette.SWATCHES` — the 15 MEASURED swatches
of rekordbox's 16 (the teal-green is left out, not guessed); a pick must
/api/tracks/cue/color`) from `palette.SWATCHES` — all 16 of rekordbox's
swatches, MEASURED (the teal-green, 0x13 #00FF30, came last: rekordbox
wrote it as its default for a hot cue added on a stick); a pick must
be an exact swatch (`swatch_code`), unlike the exporter's nearest-hue
`code_for`. Not a breach of the promotion rule: Rekordbox, OneLibrary and
Serato all colour cues — Traktor is the odd one out, by type only, so it
@@ -295,9 +300,73 @@ Two independent apps that talk over HTTP:
`close()` disposes the SQLAlchemy engine, not just the session — otherwise
the OS file handle stays open and `master.db` cannot be replaced. `AppState`
closes the previous adapter when opening a new library.
- `adapters/onelibrary/` — **read-only.** The cross-vendor USB export format
(AlphaTheta + Algoriddim + Native Instruments), read by CDJ-class hardware.
Built as the source half of a future "import a stick into Traktor" feature.
- `adapters/onelibrary/` — **editable when opened as THE library; read-only
when browsed from the sidebar's Devices** (`read_only=True`, cause `browsing`).
The cross-vendor USB export format (AlphaTheta + Algoriddim + Native
Instruments), read by CDJ-class hardware. Editing is landing in steps toward
parity with the Rekordbox adapter — track metadata, playlists, hot cues and
the beatgrid, and the `export.pdb` rebuild done and VERIFIED in rekordbox 7
(both library views matched); adding/removing tracks done (checked
in rekordbox too) and the UI ("Open for editing…" on a Devices row) — all
VERIFIED in rekordbox 7 on a real stick (2026-10-01) — decided in
[the editing discussion](.claude/discussions/discuss-onelibrary-editing-2026-10-01.md),
which also holds what rekordbox 7 was MEASURED writing when it edits a stick
(no update counter moves, the `cue` table stays empty, a new playlist goes on
top). **The store never opens the database ON the drive**: it works on a copy
in app-data and Save writes it back whole — fingerprint check (refuses if
another app wrote the stick since open), backup to app-data, temp file beside
the database, stale `-wal`/`-shm` deleted, rename — then writes edited text
fields into the audio files' tags as rekordbox does (not the rating). Cue tags
are read by Konduktor's own `rekordbox/anlz_file.py`, NOT pyrekordbox: rekordbox
writes COMPACT cue entries when it edits (48 / 44 bytes, export: 88), and
pyrekordbox's parser raised on the 44-byte one and lost the whole `.EXT`.
**Cue and grid edits rewrite only the cue LISTS they touch, and inside them
only the entries they touch** (`anlz_file.raw_entries` keeps the rest as
rekordbox wrote them), held as edited in-memory copies of the `.DAT`/`.EXT`
that every read serves, written at Save BEFORE the database (temp + rename,
fingerprinted, backed up). Each rule reproduces rekordbox's own measured edit
byte for byte: a recolour changes only the `PCP2` colour bytes (palette code
+ RGB — rekordbox draws the CODE, so `cues.color` is `palette`, like
master.db); a new pad is APPENDED to its lists; a grid edit rewrites `PQTZ`,
BLANKS `.EXT`'s `PQT2` (`anlz_writer.blank_pqt2`), clears every loop's beat
length to 0/0, leaves `.2EX` alone, and sets `bpmx100` from the first marker.
A pad keeps its colour and (unless given one) its name through a move or
retype. An `.EXT` without `PCO2` gets both lists seeded from its `PCOB`s on
the first edit — readers prefer `PCO2`, so a one-pad list would hide the rest.
A track with no analysis files refuses cue/grid edits. Memory cues stay
preserved-but-uneditable.
**`device_library.py` keeps the stick's legacy `export.pdb` in step** at
every Save (rekordbox's own edits let its playlists drift — measured). The
stick's own pdb is EDITED (`pdb.PdbEditor`), not regenerated: ids are
mirrored from OneLibrary (rekordbox exports both from the same ids), only the
tracks / lookup / playlist tables are candidates, a table is rewritten only if
a row changed, an unchanged row keeps rekordbox's bytes, and a changed track
row is the old row with the edited fields overwritten — so phrase strings,
`masterDbId` halves and play counts survive. A track row ends at its last
string (`pdb.track_extent`), NOT at the next row: rekordbox's heap holds stale
tails between rows. Keys and artwork are mirrored too (pdb artwork row =
`a<n>.jpg` beside OneLibrary's `b<n>`); history and `exportExt.pdb` are
untouched.
**Adding and removing tracks** (`tracks.places_audio`: the LIBRARY places
added audio, so the importer asks `place_audio` instead of the user, and the
routes check space at `audio_home()`): a file already on the stick is used in
place, anything else is copied to `Contents/<Artist>/<Album>/` (rekordbox's
layout: `UnknownArtist`/`UnknownAlbum`, file names cut to 48 characters) via
`<stick>/.konduktor-incoming/`, playable from there until Save moves it into
place; Discard deletes it, and a crashed session's incoming folder is cleared
on the next EDITABLE open (never a browsing one). Each added track is decoded
once and gets the OneLibrary exporter's own `.DAT`/`.EXT`/`.2EX`
(`OneLibraryExporter.anlz_files` builds bytes rather than writing) and art
(`art_files`), held in memory and written at Save; hot cues replay through
`set_cue`, memory cues (and a hot cue with no free pad) cross as memory cues.
The row copies a rekordbox stick row column for column (search columns NULL,
no counters) and `property.numberOfContents` follows. Removing deletes every
row naming the track (playlist entries renumbered from 1) and, AFTER the
database is saved, its audio, analysis files and unshared artwork, pruning
emptied folders. The adapter re-projects after every save, since Save moves
files. `save.managed_by_export` is set when the drive's root carries an
export set's `.konduktor-export.json`, and SaveBar warns that the next export
run replaces edits made in place.
Full research, incl. the schema, is in
[.claude/handoffs/onelibrary-adapter.md](.claude/handoffs/onelibrary-adapter.md);
the four things that make it unlike the Rekordbox adapter:
@@ -567,12 +636,20 @@ Two independent apps that talk over HTTP:
clicking a folder is the `folder` source kind — its audio in the ordinary
table, read-only via `readonly_cause: 'not_in_library'`, with files the
collection already holds checked off in the # column (`TrackTable`'s
`marked`). Capped at 40% of the sidebar and self-scrolling so a deep tree
`marked`). A browsed device is read-only (cause `browsing`); **"Open for
editing…"** — the drive row's right-click menu, and a button while browsing
a device whose caps say `browsing` — opens it as THE library via App's
`openForEditing` (unsaved-edits confirm, source closed, library opened).
Capped at 40% of the sidebar and self-scrolling so a deep tree
gives way before the playlists do) + `AddFilesDialog` (copy vs. leave in
place is **asked every time with nothing preselected** — the answer depends
on the drive — and warns that a referenced file on an external drive goes
missing on unplug. A playlist/export target adds to the collection first
and says so; it runs through `importer.run(reference=…, into_playlist=…)`),
and says so; it runs through `importer.run(reference=…, into_playlist=…)`.
A library with `tracks.places_audio` (a stick) is the exception: no
question and no destination — the dialog STATES how many files are copied
and how many stay in place (`platformCopy.placedAudioSummary`), and
`ImportDialog` drops its destination folder the same way),
`CollectionPicker` (**two steps: which PLATFORM, then which
library** — Automatic / Open last / Find manually, the last revealing a file
browser. The platform comes first because every later answer depends on it:
@@ -901,6 +978,42 @@ serialization path.** It enforces:
Konduktor wrote. Pins the drive-relative path resolution, the `PCOB`/`PCO2`
merge, and — cross-checked against the same cues in `master.db` — the dense
ANLZ slot numbering, which is the thing most likely to be silently wrong.
Also reads `fixtures/onelibrary/rekordbox-edited/` (a stick after rekordbox
itself edited it: compact cue entries) and pins browsing vs editable mode. It
opens a temp COPY of the fixture — a stray save once rewrote the checked-in one.
- `test_onelibrary_fidelity.py` — the row-level diff for OneLibrary writes, on a
temp copy of the fixture: nothing reaches the drive before Save, a no-op save
changes zero rows, a title edit exactly `content.title` (no counter, as
rekordbox), dates as `YYYY-MM-DD` text, lookups found-or-created with
`nameForSearch` NULL, a new playlist on top with siblings shifted, entries
from 1; and the stick hazards — another app's write refused, an unplugged
drive keeps the edits, stale `-shm` deleted, the backup holds the old rows,
the drive never held open, file tags written (title yes, rating no).
- `test_onelibrary_anlz.py` — cue and grid edits in the ANLZ files. First
against **rekordbox's own edit** of the same thing
(`fixtures/onelibrary-goober/after/`): a recolour's `PCO2` and a grid edit's
blanked `PQT2` and cleared loop beats are rekordbox's bytes exactly, and the
new `PQTZ` keeps the marker where it was (rekordbox's own halving moved its
anchor 6 ms; within 10 ms). Then fidelity on the demo drive: nothing on the
drive before Save, only the touched tags change (in place, order kept), a
moved pad keeps colour and name, memory cues refused, swatches only, a
same-tempo marker collapses (a per-beat grid has no markers), another app's
ANLZ write refused, an `.EXT` with no `PCO2` keeps every pad, a track with no
analysis files refuses.
- `test_onelibrary_pdb.py` — the Device Library rebuild on Goober's own
`export.pdb`: every track row reads (rows end at their last string; stale
heap tails ignored), a no-op rebuild returns None and a no-op save leaves the
file byte-identical (ids are mirrored), an edit changes only the edited
fields, a new playlist and a reorder reach it, every untouched table and
`exportExt.pdb` stay byte-identical, another app's pdb write is refused, and a
stick without one never gets one.
- `test_onelibrary_tracks.py` — adding and removing through `importer.run` on
Goober: placement (in place on the stick, else `Contents/<Artist>/<Album>/`,
Unknown*, FAT-safe names, 48 chars, suffixed on collision), the prep crossing
(pad + colour + name, memory cues, a taken pad -> memory, a detected grid),
the row's shape, art as a/b pairs, the Device Library rows; a cancel
mid-copy, a Discard and a crash leave nothing; removal deletes rows at once
and files only at Save, renumbers playlists and prunes empty folders.
- `test_import.py` — the import feature end to end: a drive's tracks into a temp
copy of the real collection. Asserts the prep survives (hot cues keep their
PAD, memory cues fill spare ones, the flexible grid crosses intact, no
@@ -1268,15 +1381,17 @@ that number and nothing else — everything derives from it:
library. Lossiness follows the settled rule: memory cues become hot cues in
spare pads (earliest first), cue colour is dropped (Traktor derives it from
type).
- 🟡 OneLibrary adapter — **read-only, done**. A OneLibrary USB drive opens,
projects, browses and searches: tracks, playlists, hot cues, memory cues, loops
and flexible beatgrids. Built as the readable SOURCE half of a future
**"import a OneLibrary stick into a Traktor library"** feature, which is the
motivating use case. Everything unknown about the format is on the write side
(the `cue` table's MPEG seek columns, the waveform tags a CDJ draws from, the
update counters), so read-only is a deliberate boundary rather than an
unfinished one. All research — including the schema, which has no public spec —
is in [.claude/handoffs/onelibrary-adapter.md](.claude/handoffs/onelibrary-adapter.md).
- ✅ OneLibrary adapter — **reading and editing done**, at parity with the
Rekordbox adapter (2026-10-01, [decisions](.claude/discussions/discuss-onelibrary-editing-2026-10-01.md)).
A OneLibrary USB drive opens, projects, browses and searches: tracks,
playlists, hot cues, memory cues, loops and flexible beatgrids. Done: track
metadata (+ file tags), playlists, hot cues and the beatgrid (in the ANLZ
files, each rule matching rekordbox's measured edit), the `export.pdb` rebuild
on save, adding/removing tracks (the library places the audio), Save via a
working copy, and "Open for editing…" on a Devices row — all verified in
rekordbox 7. Same gaps as Rekordbox: cover-art writing, memory-cue editing,
stem conversion. All format research — including the schema, which has no
public spec — is in [.claude/handoffs/onelibrary-adapter.md](.claude/handoffs/onelibrary-adapter.md).
- 🟡 **Export/conversion** — **in progress.** Both the design AND the user flow
are settled; see
[the export discussion doc](.claude/discussions/discuss-export-implementation-2026-09-22.md),
@@ -1408,8 +1523,8 @@ that number and nothing else — everything derives from it:
rekordbox draw its own defaults (green/orange). **rekordbox draws a hot cue
from its palette CODE** (`PCP2` byte 44, before the RGB; `djmdCue.ColorTableIndex`
in master.db), not the RGB — `adapters/rekordbox/palette.py` holds the 16-swatch
table MEASURED from a rekordbox 7 export (one swatch, ~0x12 teal-green, still
unmeasured). Type colours map by intent (cue -> light blue 0x05, loop -> green
table MEASURED from a rekordbox 7 export (the teal-green, 0x13 #00FF30, measured
later from a rekordbox-edited stick). Type colours map by intent (cue -> light blue 0x05, loop -> green
0x16), anything else to the nearest hue; the palette has NO white, so a grid
companion is code 0 + RGB white (what rekordbox draws for it: unverified). The
**Artwork** (`adapters/rekordbox/artwork.py`, Pillow), measured on a rekordbox 7
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,32 @@
# Goober: a rekordbox-written stick, before and after rekordbox edited it
The stick Ben keeps for measuring the Pioneer formats, as rekordbox 7 left it:
11 tracks, 2 playlists, **both** libraries (`exportLibrary.db` and the legacy
`export.pdb` + `exportExt.pdb`). `test_onelibrary_anlz.py`,
`test_onelibrary_pdb.py` and `test_onelibrary_tracks.py` run against copies of it.
## What is here
- `PIONEER/rekordbox/` holds the three databases, **untouched**: bytes rekordbox
wrote (snapshot `s0`, 2026-10-01).
- `PIONEER/USBANLZ/` holds every track's `.DAT` and `.EXT`, trimmed by dropping
whole tags: only `PPTH`, `PQTZ`, `PCOB`, `PCO2` and `PQT2` are kept, byte for
byte. The waveforms are gone, and so are the `.2EX` files.
- `after/` holds the same tags after **rekordbox 7 itself** edited the stick
(snapshot `s1`, one edit per track):
- `black-bloc-recoloured.EXT`: pad C recoloured to `0x2D` `#FF0045`.
- `wtf-87bpm.DAT` / `.EXT`: "Result – WTF" changed from 174 to 87 BPM.
- `demo2-pad-e-added.EXT`: a hot cue added on pad E of "Demo Track 2".
There is no audio. The adapter resolves paths and never needs the files, so the
time base falls back to rekordbox's MP3 default, the same offset for reading and
writing.
## Why
Konduktor's edits are pinned against what rekordbox wrote for the SAME edit, not
against Konduktor's own reader. A recolour and a grid edit must reproduce
rekordbox's bytes exactly (colour bytes, the blanked `PQT2`, loop beats cleared).
The pdb tests prove that an in-place edit of a rekordbox-written `export.pdb`
leaves everything else as rekordbox wrote it. The full diff of the measurement is
in `.claude/discussions/discuss-onelibrary-editing-2026-10-01.md`.
+13
View File
@@ -56,3 +56,16 @@ implementation — open and write to it.
Not loaded by the tests; kept as documentation, and as the starting point if
Konduktor ever needs to create a drive from nothing.
## rekordbox-edited/
Analysis files from a SECOND stick (Goober), after rekordbox 7 itself edited it
(2026-10-01): a hot cue added on pad E of `demo-track-2`, and a memory cue added on
the start of `nemean`'s memory loop. Trimmed the same way as above, by dropping
whole tags: only `PPTH`, `PCOB` and `PCO2` are kept, byte for byte.
They exist for one property: rekordbox writes **compact** cue entries when it
edits (48 bytes for that hot cue, 44 with no colour for the memory cue; an export
writes 88). pyrekordbox's parser raises on the 44-byte form, which once made the
reader drop the whole `.EXT`, losing pads D-H and every colour. See
`adapters/rekordbox/anlz_file.py`.
+245 -47
View File
@@ -5,28 +5,30 @@ Mirrors `adapters.rekordbox.adapter`. It holds:
* a ``OneLibraryStore`` — the retained NATIVE model (the open drive),
* a ``TrackIndex`` — the generic READ projection built from it.
**Read-only.** Every command is refused and `capabilities.writable` is False with
cause `platform_incomplete`, so the UI never offers an edit in the first place;
the raises here are the backstop, not the mechanism.
**Editable when opened as THE library**, with parity with the Rekordbox adapter
as the goal (decisions: `.claude/discussions/discuss-onelibrary-editing-2026-10-01.md`).
Opened `read_only` — as the sidebar's Devices do, beside the loaded library — it
reports `writable=False` with cause `browsing`, and every command is refused.
That scope is deliberate rather than provisional. The purpose of this adapter is
to make a OneLibrary drive a readable SOURCE — the half an import into another
library needs — and every genuinely unknown part of the format sits on the write
side: the `cue` table's eight MPEG frame/offset columns, whose values a player
needs to seek accurately in a VBR file; the waveform tags a CDJ draws from; and
the update counters a drive uses to reconcile edits made on hardware. None of
those has to be guessed at to read a drive, and none of them should be guessed at
at all.
What a write must look like was MEASURED by diffing a stick before and after
rekordbox 7 edited it, rather than guessed: the update counters a drive carries
do NOT move, and the `cue` table stays empty. Landing in steps — track metadata,
playlists, hot cues and the beatgrid so far; adding and removing tracks next —
and every command not written yet is refused, with its capability flag False so
the UI never offers it.
"""
from __future__ import annotations
from pathlib import Path
from ...core.adapter import Unsupported
from ...core.adapter import InvalidCommand, Unsupported
from ...core.capabilities import Capabilities
from ...core.model import HotcueChip, PlaylistNode, Track, TrackCues
from ...core.model import GridMarker, HotcueChip, PlaylistNode, Track, TrackCues
from ...core.pathmap import PathMapping, common_dir_prefix
from ...core.query import TrackIndex
from ..rekordbox import palette
from ..rekordbox.cue_types import WRITABLE_CUE_TYPES
from ...exporter import MANIFEST_NAME
from . import capabilities as caps
from . import projection
from .store import OneLibraryStore
@@ -42,9 +44,10 @@ ATTRIBUTE_SMART = 4
class OneLibraryAdapter:
platform = "onelibrary"
def __init__(self, path: Path):
def __init__(self, path: Path, *, read_only: bool = False):
self.path = Path(path)
self._store = OneLibraryStore(self.path)
self.read_only = read_only
self._store = OneLibraryStore(self.path, read_only=read_only)
self._index = TrackIndex()
self._rebuild()
@@ -60,7 +63,9 @@ class OneLibraryAdapter:
self._index.rebuild(tracks)
def _drive_path(self, row) -> str | None:
resolved = self._store.layout.resolve(getattr(row, "path", None))
# Through the store: an added track plays from its incoming copy until
# Save puts it in place.
resolved = self._store.resolve_audio(getattr(row, "path", None))
return str(resolved) if resolved is not None else None
def close(self) -> None:
@@ -72,14 +77,27 @@ class OneLibraryAdapter:
self._store.close()
def reload(self) -> None:
self._store._load()
"""Re-read the drive, DISCARDING unsaved edits."""
self._store.discard()
self._rebuild()
def _refresh(self, track_id: str) -> None:
"""Re-project one track after a command, so the UI cannot go stale."""
from ...core.stem_file import is_stem_file
row = self._store.content(track_id)
path = self._drive_path(row)
self._index.replace(projection.to_track(row, path, stem=bool(path) and is_stem_file(path)))
# ---- identity --------------------------------------------------------
def capabilities(self) -> Capabilities:
return caps.capabilities_for(
device_name=self._store.device_name,
version=self._store.db_version,
read_only=self.read_only,
editable_fields=sorted(OneLibraryStore.EDITABLE_FIELDS),
# A drive an export set wrote carries the export's manifest at its root.
managed_by_export=(self._store.layout.root / MANIFEST_NAME).is_file(),
)
# ---- read ------------------------------------------------------------
@@ -146,7 +164,9 @@ class OneLibraryAdapter:
rather than an absence, and treating 0 as a real id would orphan every
top-level playlist.
"""
rows = self._store.playlists()
rows = sorted(self._store.playlists(),
key=lambda r: (int(getattr(r, "sequenceNo", 0) or 0), int(r.playlist_id)))
writable = not self.read_only
nodes: dict[str, PlaylistNode] = {}
parents: dict[str, str] = {}
@@ -166,12 +186,12 @@ class OneLibraryAdapter:
count=(0 if kind == "folder" else len(self._store.playlist_song_ids(node_id))),
children=[],
selectable=kind == "playlist",
# Read-only: every per-node flag is False, and
# Opened read-only, every flag is False and
# `capabilities.writable` tells the UI why, once.
can_add_tracks=False,
can_reorder=False,
can_rename=False,
can_delete=False,
can_add_tracks=writable and kind == "playlist",
can_reorder=writable and kind == "playlist",
can_rename=writable,
can_delete=writable,
can_contain_children=kind == "folder",
)
parent = str(getattr(r, "playlist_id_parent", 0) or 0)
@@ -238,32 +258,139 @@ class OneLibraryAdapter:
# ---- save -------------------------------------------------------------
@property
def dirty(self) -> bool:
return False
return self._store.dirty
def save(self):
raise Unsupported(self._readonly_reason("Saving"))
self._require_writable("Saving")
outcome = self._store.save()
# Save MOVES files (an added track's audio leaves its incoming copy), so
# the projection is rebuilt from what is now on the drive.
self._rebuild()
return outcome
def snapshot(self) -> bytes:
raise Unsupported("OneLibrary drives are not versioned by Konduktor")
# ---- commands: all refused -------------------------------------------
# ---- commands -----------------------------------------------------------
def _readonly_reason(self, what: str) -> str:
if self.read_only:
return (f"{what} is not possible while the drive is open for browsing. "
"Open it for editing to change it.")
return f"{what} is not supported yet for OneLibrary drives."
def _refuse(self, what: str):
raise Unsupported(self._readonly_reason(what))
def _require_writable(self, what: str) -> None:
"""Every write passes through here, so a command added later cannot
forget that a browsing drive is read-only."""
if self.read_only:
self._refuse(what)
# ---- audio placement (`tracks.places_audio`) ----------------------------
def audio_home(self) -> Path:
return self._store.audio_home()
def place_audio(self, source: Path, track) -> Path | None:
self._require_writable("Adding tracks")
return self._store.place_audio(source, track)
def add_tracks(self, items: list, *, checkpoint=None) -> list[str]:
self._refuse("Adding tracks")
"""Add tracks, each arriving ready to prep — as the Rekordbox adapter does.
A drive keeps the beatgrid, cues and waveforms in per-track analysis
files, and rekordbox shows neither grid nor cues without them, so every
file is decoded ONCE here and its `.DAT`/`.EXT`/`.2EX` built by the
OneLibrary exporter's own writer — the files rekordbox 7 was verified
to read. A file with no grid of its own gets Konduktor's.
Two phases, as in Rekordbox: FIRST the slow, cancellable part (decoding,
grid detection, building the analysis and artwork bytes) before the
library is touched; THEN the rows, with hot cues replayed through the
ordinary `set_cue` so they keep its conventions. Memory cues — and a hot
cue with no free pad — cross as memory cues, written with the files.
`audio_path` is where `place_audio` said to copy it (or the file itself,
already on the stick); Save moves copies into place.
"""
from ...core import audio_tags, grid_detect, waveform
from ...core.export import ExportTrack
from ..rekordbox import artwork, timebase
from .export import OneLibraryExporter
self._require_writable("Adding tracks")
exporter = OneLibraryExporter()
prepared = []
total = len(items)
for n, item in enumerate(items, start=1):
audio = Path(item.audio_path)
if checkpoint is not None:
checkpoint(f"Analysing {item.track.title or audio.name} ({n}/{total})", step=n, of=total)
if not audio.is_file():
raise InvalidCommand(f"No audio file at {audio}")
try:
rel = self._store.drive_relative(self._store.final_of(audio))
except ValueError:
raise InvalidCommand(f"{audio} is not on this drive") from None
samples = waveform.decode(audio)
measured = waveform.analyse_samples(samples, lead=timebase.offset(audio))
markers = list(item.cues.grid_markers) if item.cues else []
if not markers and samples is not None:
try:
found = grid_detect.detect_grid(str(audio), y=samples, sr=waveform.SR)
markers = [GridMarker(start=found.anchor, bpm=found.bpm)]
except ValueError:
pass # no pulse to fit (a one-shot, silence): no grid
hot, memory, taken = [], [], set()
for cue in sorted((item.cues.cues if item.cues else []), key=lambda c: c.start):
if (cue.role == "hotcue" and cue.slot is not None
and 0 <= cue.slot < caps.HOTCUE_SLOTS and cue.slot not in taken):
hot.append(cue)
taken.add(cue.slot)
else:
memory.append(cue.model_copy(update={"role": "memory", "slot": None}))
export_track = ExportTrack(track=item.track, destination=audio,
cues=TrackCues(grid_markers=markers, cues=memory))
# Decoded once above; the writer must not decode it again.
export_track.waveform = lambda *, lead=0.0, m=measured: m
art = item.art or audio_tags.read_cover(audio)
jpegs = artwork.pioneer_jpegs(art[0]) if art else None
length = item.track.length or (int(measured.duration) if measured else None)
prepared.append((item, audio, rel, exporter.anlz_files(export_track, rel), jpegs,
markers, hot, length))
added: list[str] = []
for item, audio, rel, anlz, jpegs, markers, hot, length in prepared:
track_id = self._store.add_track(
audio, item.track, rel=rel, anlz_rel=self._store._anlz_rel(rel), anlz=anlz,
jpegs=jpegs, bpm=markers[0].bpm if markers else item.track.bpm, length=length)
for cue in hot:
self._store.set_cue(track_id, slot=cue.slot, start_sec=cue.start,
cue_type="loop" if cue.length else "cue",
length_sec=cue.length or 0.0, name=cue.name)
code, _rgb = palette.code_for(cue.color)
if cue.color and code:
self._store.set_cue_color(track_id, cue.slot, code)
added.append(track_id)
self._rebuild()
return added
def remove_tracks(self, track_ids: list[str]) -> int:
self._refuse("Removing tracks")
"""Remove tracks — and, on a stick, their audio and analysis files at Save
(decision 3: a stick's audio belongs to its library)."""
self._require_writable("Removing tracks")
n = self._store.remove_tracks(track_ids)
if n:
self._rebuild()
return n
def apply_stem_swaps(self, swaps, *, add_to_playlist=None):
self._refuse("Converting tracks to stems")
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None:
self._refuse("Editing track metadata")
self._require_writable("Editing track metadata")
self._store.set_track_metadata(track_id, fields)
self._refresh(track_id)
return self._index.get(track_id)
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
self._refuse("Editing cover art")
@@ -272,55 +399,126 @@ class OneLibraryAdapter:
return self._store.cover_art(track_id)
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
self._refuse("Creating playlists")
self._require_writable("Creating playlists")
return self._store.create_playlist(name, parent_id)
def create_folder(self, name: str, parent_id: str | None = None) -> str:
self._refuse("Creating playlist folders")
self._require_writable("Creating playlist folders")
return self._store.create_folder(name, parent_id)
def rename_playlist(self, node_id: str, name: str) -> None:
self._refuse("Renaming playlists")
self._require_writable("Renaming playlists")
self._store.rename_playlist(node_id, name)
def delete_playlist(self, node_id: str) -> None:
self._refuse("Deleting playlists")
self._require_writable("Deleting playlists")
self._store.delete_playlist(node_id)
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
self._refuse("Editing playlists")
self._require_writable("Editing playlists")
return self._store.set_playlist_entries(node_id, track_ids)
def set_cue(self, track_id: str, **kw) -> TrackCues:
self._refuse("Editing cues")
def _refresh_cues(self, track_id: str) -> TrackCues:
"""Re-project a track AND return its fresh cues — every cue/grid command
ends here, so a route can never serve a stale projection."""
self._refresh(track_id)
return self.track_cues(track_id) or TrackCues()
def _check_cue_type(self, cue_type: str) -> None:
if cue_type not in WRITABLE_CUE_TYPES:
raise Unsupported(f"OneLibrary has no cue type {cue_type!r}")
def set_cue(
self,
track_id: str,
*,
slot: int,
start_sec: float,
cue_type: str,
length_sec: float = 0.0,
role: str = "hotcue",
name: str | None = None,
) -> TrackCues:
self._require_writable("Editing cues")
if role != "hotcue":
# Preserved-but-uneditable, exactly as in the Rekordbox adapter.
raise Unsupported(
"Memory cues are shown but cannot be edited — only hot cues are writable"
)
self._check_cue_type(cue_type)
self._store.set_cue(track_id, slot=slot, start_sec=start_sec, cue_type=cue_type,
length_sec=length_sec, name=name)
return self._refresh_cues(track_id)
def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> TrackCues:
self._refuse("Editing cues")
self._require_writable("Editing cues")
self._check_cue_type(cue_type)
self._store.set_cue_type(track_id, slot, cue_type)
return self._refresh_cues(track_id)
def set_cue_color(self, track_id: str, slot: int, color: str | None) -> TrackCues:
self._refuse("Editing cues")
self._require_writable("Editing cues")
code = None
if color is not None:
code = palette.swatch_code(color)
if code is None:
raise InvalidCommand(f"{color!r} is not one of rekordbox's hot cue colours")
self._store.set_cue_color(track_id, slot, code)
return self._refresh_cues(track_id)
def delete_cue(self, track_id: str, slot: int) -> TrackCues:
self._refuse("Deleting cues")
self._require_writable("Deleting cues")
self._store.delete_cue(track_id, slot)
return self._refresh_cues(track_id)
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues:
self._refuse("Placing cues")
self._require_writable("Placing cues")
for cue in cues:
self._check_cue_type(getattr(cue, "type", "cue"))
self._store.place_cues(track_id, cues, overwrite=overwrite)
return self._refresh_cues(track_id)
# ---- commands: beatgrid -----------------------------------------------
@staticmethod
def _markers_from(markers: list) -> list:
"""Accept either GridMarkers or the (start, bpm) tuples routes send."""
return [m if isinstance(m, GridMarker) else GridMarker(start=float(m[0]), bpm=float(m[1]))
for m in markers]
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> TrackCues:
self._refuse("Editing the beatgrid")
self._require_writable("Editing the beatgrid")
self._store.add_grid_marker(track_id, start_sec, bpm)
return self._refresh_cues(track_id)
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> TrackCues:
self._refuse("Editing the beatgrid")
self._require_writable("Editing the beatgrid")
self._store.move_grid_marker(track_id, index, start_sec)
return self._refresh_cues(track_id)
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> TrackCues:
self._refuse("Editing the beatgrid")
self._require_writable("Editing the beatgrid")
self._store.set_grid_marker_bpm(track_id, index, bpm)
return self._refresh_cues(track_id)
def delete_grid_marker(self, track_id: str, index: int) -> TrackCues:
self._refuse("Editing the beatgrid")
self._require_writable("Editing the beatgrid")
self._store.delete_grid_marker(track_id, index)
return self._refresh_cues(track_id)
def replace_grid(self, track_id: str, markers: list) -> TrackCues:
self._refuse("Editing the beatgrid")
self._require_writable("Editing the beatgrid")
self._store.replace_grid(track_id, self._markers_from(markers))
return self._refresh_cues(track_id)
def set_analysed_grid(self, track_id: str, markers: list) -> TrackCues:
self._refuse("Editing the beatgrid")
"""An analysis result, as rekordbox's analyser would write it: nothing is
paired with a marker (the companion cue is Traktor's), so a replace."""
return self.replace_grid(track_id, markers)
def delete_grid(self, track_id: str) -> TrackCues:
self._refuse("Deleting the beatgrid")
self._require_writable("Deleting the beatgrid")
self._store.delete_grid(track_id)
return self._refresh_cues(track_id)
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues:
raise Unsupported("OneLibrary has no beatgrid lock")
@@ -28,7 +28,8 @@ __all__ = ["BPM_EPSILON", "markers_from_beats", "beats_from_pqtz", "markers_from
def beats_from_pqtz(anlz) -> tuple[list[float], list[float], list[int]] | None:
"""Per-beat ``(times_sec, bpms, beat_in_bar)`` from a parsed ANLZ file's `PQTZ` tag.
"""Per-beat ``(times_sec, bpms, beat_in_bar)`` from a parsed ANLZ file's `PQTZ` tag
(an `anlz_file.AnlzFile`).
Returns None when the file has no `PQTZ` — which is a real state, not an
error: rekordbox analyses one-shot samples too, and gives them an analysis
@@ -39,7 +40,7 @@ def beats_from_pqtz(anlz) -> tuple[list[float], list[float], list[int]] | None:
for tag in getattr(anlz, "tags", []):
if tag.type != "PQTZ":
continue
entries = getattr(getattr(tag.struct, "content", None), "entries", None)
entries = tag.entries
if not entries:
return None
times: list[float] = []
@@ -1,25 +1,27 @@
"""What a OneLibrary drive can persist: nothing, for now.
"""What a OneLibrary drive can persist.
`writable` is False with cause `platform_incomplete`. That is the distinction the
capability system exists to draw — this is a ROADMAP GAP, not a refusal. A
cloud-synced Rekordbox library is refused permanently to protect the user's other
machines; a OneLibrary drive simply has no write path yet, and the UI must word
those two very differently.
Opened as THE library, a drive is writable, and the per-feature flags say which
edits have landed: track metadata, playlists, hot cues, the grid, and adding
and removing tracks, so the UI never offers an edit the adapter
would refuse. Opened `read_only` — the sidebar's Devices, browsing beside the
loaded library — `writable` is False with cause `browsing`, which the UI words
as "open it for editing", not as a missing feature.
The per-feature flags below still report what the FORMAT supports rather than
being blanked to false, because that is what `writable=False` is for: the UI can
show a drive's cues and grid honestly, and say once, in one place, that the whole
library is read-only. Blanking them would claim OneLibrary has no hot cues.
With `writable=False` the per-feature flags still report what the FORMAT
supports rather than being blanked, because that is what the library-level flag
is for: the UI can show a drive's cues and grid honestly and say once, in one
place, that the library is read-only. Blanking them would claim OneLibrary has no
hot cues.
Two answers are worth recording now, while the evidence is in front of us, since
getting them wrong later would be a silent data bug rather than a missing
feature:
* cue colour is **free RGB**, not a palette index. The `PCO2` tag stores three
bytes per cue, and the reference drive held #4D00FF, #33FF00, #00C4FF and
#FF8C00. This differs from the desktop Rekordbox adapter, which reports
"palette" because `djmdCue` stores an index into a built-in table — the same
vendor, two genuinely different representations.
* cue colour is a **palette**, like master.db's. `PCO2` stores a palette CODE
and an RGB per cue, and rekordbox DRAWS from the code (an export writing only
RGB had every cue in rekordbox's defaults) — so a pick is one of rekordbox's
16 swatches and both are written. (This was first read as "free RGB" off the
RGB bytes alone; the code byte beside them is what decides.)
* a loop is a cue with an out-point, so ``loops="cue_type"`` — the same answer
as Traktor and Rekordbox, and NOT the `separate_bank` the original
multi-platform plan assumed.
@@ -34,44 +36,58 @@ from ...core.capabilities import (
SaveCapabilities,
TrackCapabilities,
)
from ..rekordbox import palette
from ..rekordbox.cue_types import WRITABLE_CUE_TYPES
# Pads A-H. Unlike `djmdCue.Kind`, the ANLZ slot number is a dense 1-based index,
# so the bank really is 1..8 (see `cues.py`).
HOTCUE_SLOTS = 8
def capabilities_for(device_name: str | None = None, version: str | None = None) -> Capabilities:
def capabilities_for(
device_name: str | None = None,
version: str | None = None,
*,
read_only: bool = False,
editable_fields: list[str] | None = None,
managed_by_export: bool = False,
) -> Capabilities:
return Capabilities(
platform="onelibrary",
version=version,
# A roadmap gap, not a protective refusal — the UI words the two
# differently, which is the whole reason `readonly_cause` exists.
writable=False,
readonly_cause="platform_incomplete",
writable=not read_only,
readonly_cause="browsing" if read_only else None,
cues=CueCapabilities(
editable=False,
editable=True,
hotcue_slots=HOTCUE_SLOTS,
slot_labels="letter",
# OneLibrary carries memory cues, as Rekordbox does. They are
# projected and preserved; nothing here is editable anyway.
# OneLibrary carries memory cues, as Rekordbox does: projected and
# preserved, NOT editable (the two-platform rule, as in Rekordbox).
memory_cues=True,
max_memory_cues=None,
types=["cue", "loop"],
color="free", # PCO2 stores RGB per cue, not a palette index
palette=[],
types=WRITABLE_CUE_TYPES,
color="palette",
palette=[palette.hex_for(code) for code in palette.SWATCHES],
named=True, # PCO2 carries a per-cue comment
loops="cue_type",
),
# The grid is the ANLZ `PQTZ` tag, per beat, and multi-tempo grids do
# survive an export — so the format is flexible even though Konduktor
# does not write it here.
grid=GridCapabilities(editable=False, flexible=True, lockable=False),
# The grid is the ANLZ `PQTZ` tag, per beat; multi-tempo grids survive.
# No per-track grid lock exists in the format.
grid=GridCapabilities(editable=True, flexible=True, lockable=False),
tracks=TrackCapabilities(
rating_max=5, # stored 0-5 directly, as in master.db
editable_fields=[],
# The Rekordbox adapter's set: `producer`/`mix` have no column.
editable_fields=sorted(editable_fields or []),
media_kinds=["audio", "stem"],
# `artwork` gates EDITING, and a drive is read-only here. Reading
# works: `store.cover_art` follows `content.image_id` -> `image.path`.
# A stick's audio belongs to its library: added files are copied onto
# it (laid out as rekordbox does) and a removed track's file goes
# with it, at Save — so the library, not the user, places the audio.
addable=not read_only,
removable=not read_only,
places_audio=True,
# `artwork` gates EDITING, which Rekordbox does not do yet either
# (parity). Reading works: `store.cover_art` follows
# `content.image_id` -> `image.path`.
artwork=False,
artwork_note=None,
),
@@ -80,13 +96,18 @@ def capabilities_for(device_name: str | None = None, version: str | None = None)
# A drive carries no smart playlists: rekordbox resolves them to
# static lists on export, because a CDJ cannot evaluate rules.
smart="none",
reorder=False,
reorder=True,
),
save=SaveCapabilities(
app_name="OneLibrary",
library_label=device_name or "exportLibrary.db",
# Nothing is written, so nothing can be overwritten by another app.
# Named for the DRIVE ("Save to Goober"): a person has several
# sticks, and "Save to OneLibrary" would not say which.
app_name=device_name or "OneLibrary",
library_label="exportLibrary.db",
# Another app writing the drive between open and save is CAUGHT,
# not risked: the store fingerprints the database at open and
# refuses to save over a change it did not make.
overwrite_risk="none",
managed_by_export=managed_by_export,
# A drive is a database plus N analysis files plus the audio itself,
# so there is no single blob that IS the library — the same reason
# Rekordbox libraries are not versioned.
+36 -23
View File
@@ -37,6 +37,7 @@ from __future__ import annotations
import logging
from ...core.model import CuePoint
from ..rekordbox import palette
log = logging.getLogger(__name__)
@@ -47,14 +48,13 @@ NO_LOOP = 0xFFFFFFFF
# `hot_cue` for a cue that sits in no pad bank, i.e. a memory cue.
MEMORY_SLOT = 0
# PCO2/PCOB entry kinds. The value is the same in both tags; PCOB exposes it as
# a construct enum and PCO2 as a plain int, so both are normalised to an int.
# PCO2/PCOB entry kinds. The value is the same in both tags.
ENTRY_CUE = 1
ENTRY_LOOP = 2
def _entry_kind(value) -> int:
"""PCOB gives an enum, PCO2 an int — one number out of either."""
"""An entry's kind as an int, defaulting to a point cue if unreadable."""
try:
return int(value)
except (TypeError, ValueError):
@@ -68,8 +68,17 @@ def _color(entry) -> str | None:
real black in principle, but rekordbox uses it as "unset" and shows such a
cue in the default colour, so it is reported as no colour rather than as
black. Memory cues in the reference export are exactly this case.
rekordbox DRAWS a cue from its palette CODE (`rekordbox.palette`), so a known
code is reported as that swatch; a cue with code 0 and an RGB (older
exports, the reference fixture) is reported by its RGB.
"""
swatch = palette.hex_for(getattr(entry, "color_code", None))
if swatch is not None:
return swatch
try:
# None on an entry too short to carry a colour: every PCPT, and the
# compact 44-byte PCP2 rekordbox writes for a memory cue it added.
r, g, b = int(entry.color_red), int(entry.color_green), int(entry.color_blue)
except (AttributeError, TypeError, ValueError):
return None
@@ -78,7 +87,7 @@ def _color(entry) -> str | None:
return f"#{r:02X}{g:02X}{b:02X}"
def _to_cue(entry, *, with_color: bool) -> CuePoint | None:
def _to_cue(entry, *, with_color: bool, editable: bool = False) -> CuePoint | None:
"""One ANLZ cue entry as a generic `CuePoint`, or None if unreadable."""
try:
hot_cue = int(entry.hot_cue)
@@ -111,11 +120,11 @@ def _to_cue(entry, *, with_color: bool) -> CuePoint | None:
length=length,
slot=slot,
color=_color(entry) if with_color else None,
# A OneLibrary drive is read-only in Konduktor, so no cue accepts a
# command. `capabilities.writable` is what the UI actually gates on;
# this keeps the per-cue answer consistent with it.
editable=False,
readonly_reason="platform_managed",
# Hot cues are editable on a drive opened for editing (the caller says
# so). MEMORY cues never are — preserved-but-uneditable, as in the
# Rekordbox adapter (the two-platform rule).
editable=editable and role == "hotcue",
readonly_reason=None if editable and role == "hotcue" else "platform_managed",
grid_marker=None,
)
@@ -130,15 +139,14 @@ def _entries(anlz, tag_type: str) -> list:
"""
out: list = []
for tag in getattr(anlz, "tags", []):
if tag.type != tag_type:
continue
content = getattr(tag.struct, "content", None)
out.extend(getattr(content, "entries", None) or [])
if tag.type == tag_type:
out.extend(tag.entries)
return out
def cues_from_anlz(dat, ext) -> list[CuePoint]:
"""The track's complete cue list, from its parsed `.DAT` and `.EXT`.
def cues_from_anlz(dat, ext, *, editable: bool = False) -> list[CuePoint]:
"""The track's complete cue list, from its parsed `.DAT` and `.EXT`
(`rekordbox.anlz_file.AnlzFile`s).
Either may be None — a drive can carry a `.DAT` with no `.EXT` — and a track
with no cues at all yields an empty list rather than an error.
@@ -153,14 +161,14 @@ def cues_from_anlz(dat, ext) -> list[CuePoint]:
for f in files:
pco2.extend(_entries(f, "PCO2"))
if pco2:
cues = [c for e in pco2 if (c := _to_cue(e, with_color=True)) is not None]
cues = [c for e in pco2 if (c := _to_cue(e, with_color=True, editable=editable)) is not None]
else:
# Fallback: merge PCOB across BOTH files. The .DAT holds pads 1-3 and the
# .EXT the rest, so either alone is an incomplete bank.
pcob: list = []
for f in files:
pcob.extend(_entries(f, "PCOB"))
cues = [c for e in pcob if (c := _to_cue(e, with_color=False)) is not None]
cues = [c for e in pcob if (c := _to_cue(e, with_color=False, editable=editable)) is not None]
return _dedupe(cues)
@@ -168,18 +176,23 @@ def cues_from_anlz(dat, ext) -> list[CuePoint]:
def _dedupe(cues: list[CuePoint]) -> list[CuePoint]:
"""Collapse the same cue appearing in more than one tag or file.
Identity is (role, slot, start) rather than the whole cue: the same pad can
be described by both `PCOB` and `PCO2`, and by both files, and those copies
agree on position while differing in how much detail they carry. The first
one wins, which — given PCO2 is read first — is the richest.
Identity is (role, slot, start, type, length) rather than the whole cue:
the same pad can be described by both `PCOB` and `PCO2`, and by both files,
and those copies agree on all five while differing in how much detail they
carry (colour, comment). The first one wins, which — given PCO2 is read
first — is the richest.
Type and length are part of it because two MEMORY cues may share a position:
rekordbox happily stores a memory cue on the start of a memory loop (seen on
Goober), and keying on position alone silently dropped the loop.
Ordered by position, then by slot, so the projection is stable across reads
regardless of the order the tags happened to store.
"""
seen: set[tuple[str, int | None, int]] = set()
seen: set[tuple] = set()
out: list[CuePoint] = []
for c in cues:
key = (c.role, c.slot, round(c.start * 1000))
key = (c.role, c.slot, round(c.start * 1000), c.type, round(c.length * 1000))
if key in seen:
continue
seen.add(key)
@@ -0,0 +1,208 @@
"""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 lookup tables (artist, album, genre,
label, key), artwork 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 and `exportExt.pdb` are never touched.
"""
from __future__ import annotations
import re
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.KEYS,
pdb.ARTWORK, 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)
if table == pdb.KEYS:
return pdb.read_dsql(row, 8)
return pdb.read_dsql(row, 4)
def _pdb_art_path(path: str | None) -> str:
"""OneLibrary's `image.path` names the `b<n>` file; export.pdb's artwork row
the byte-identical `a<n>` beside it (as on Goober, and as rekordbox writes)."""
return re.sub(r"/b(\d+)(\.jpg)$", r"/a\1\2", path or "")
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),
(pdb.KEYS, "SELECT key_id, name FROM key", pdb.key_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
want = {int(i): (_pdb_art_path(path), (lambda i=i, p=path: pdb.id_string_row(int(i), _pdb_art_path(p))))
for i, path in session.execute(text("SELECT image_id, path FROM image"))}
merged = _merge(pdb.table_rows(existing, pdb.ARTWORK), want, pdb.ARTWORK,
lambda row, value: pdb.read_dsql(row, 4) == value)
if merged is not None:
tables[pdb.ARTWORK] = 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
@@ -73,8 +73,8 @@ class OneLibraryDriver:
except Exception: # noqa: BLE001
pass
def open(self, path: Path) -> OneLibraryAdapter:
return OneLibraryAdapter(path)
def open(self, path: Path, *, read_only: bool = False) -> OneLibraryAdapter:
return OneLibraryAdapter(path, read_only=read_only)
def detect(self) -> list[dict]:
return discovery.detect_libraries()
@@ -265,11 +265,9 @@ class OneLibraryExporter:
n = counter["next"]
folder = root / "PIONEER" / "Artwork" / "00001"
folder.mkdir(parents=True, exist_ok=True)
small, medium = jpegs
files = []
for letter in ("a", "b"):
for suffix, data in (("", small), ("_m", medium)):
path = folder / f"{letter}{n}{suffix}.jpg"
for rel, data in art_files(n, jpegs):
path = root / rel.lstrip("/")
path.write_bytes(data)
files.append(path)
con.execute("INSERT INTO image (image_id, path) VALUES (?, ?)",
@@ -278,8 +276,10 @@ class OneLibraryExporter:
# ---- the analysis files --------------------------------------------------
def _write_anlz(self, item: ExportTrack, rel: str, dat: Path) -> list[Path]:
"""The `.DAT`, `.EXT` and `.2EX`, as rekordbox 7 writes them.
def anlz_files(self, item: ExportTrack, rel: str) -> list[tuple[str, bytes]]:
"""The `.DAT`, `.EXT` and `.2EX` as `(suffix, bytes)`, as rekordbox 7 writes
them — built, not written, so a library adding a track to a stick can hold
them until Save (`OneLibraryStore.add_track`).
All three, and every cue list, even for a track with no cues: rekordbox
never produces a track without them, and `PCO2` — the complete list,
@@ -318,9 +318,18 @@ class OneLibraryExporter:
tags += previews
tags += W.cue_tags(cues, extended=False)
ext = [W.path_tag(rel), *ext_waves[:1], *W.cue_tags(cues, extended=True), *ext_waves[1:]]
written = [W.write_anlz(dat, tags), W.write_anlz(dat.with_suffix(".EXT"), ext)]
files = [(".DAT", W.anlz_bytes(tags)), (".EXT", W.anlz_bytes(ext))]
if two_ex:
written.append(W.write_anlz(dat.with_suffix(".2EX"), [W.path_tag(rel), *two_ex]))
files.append((".2EX", W.anlz_bytes([W.path_tag(rel), *two_ex])))
return files
def _write_anlz(self, item: ExportTrack, rel: str, dat: Path) -> list[Path]:
written = []
for suffix, data in self.anlz_files(item, rel):
path = dat.with_suffix(suffix)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
written.append(path)
return written
@staticmethod
@@ -424,6 +433,15 @@ _FILE_TYPES = {".mp3": 1, ".m4a": 4, ".mp4": 4, ".aac": 4, ".flac": 5, ".wav": 1
".aif": 12, ".aiff": 12}
def art_files(n: int, jpegs: tuple[bytes, bytes]) -> list[tuple[str, bytes]]:
"""Image `n`'s four files as `(drive-relative path, bytes)`: `a<n>`/`b<n>`
and their `_m`, byte-identical pairs, in `Artwork/00001/` (see `_write_art`).
`image.path` names the `b` file; `export.pdb`'s artwork table the `a` one."""
small, medium = jpegs
return [(f"/PIONEER/Artwork/00001/{letter}{n}{suffix}.jpg", data)
for letter in ("a", "b") for suffix, data in (("", small), ("_m", medium))]
def _file_type(path: Path) -> int:
return _FILE_TYPES.get(path.suffix.lower(), 1)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,291 @@
"""Reading an ANLZ analysis file at the TAG level, by hand.
The writer half is `anlz_writer`; this is its reader. Like the writer it lives
here because the format is Pioneer's, not one product's.
**Why not `pyrekordbox`'s parser.** It decodes a cue entry with a FIXED layout,
and rekordbox does not write one. An exported entry is 88 bytes, but when
rekordbox 7 EDITS a stick it writes compact ones (measured on Goober,
2026-10-01): a hot cue added in rekordbox was a 48-byte `PCP2` (colour, no
padding), and a memory cue a 44-byte one (no colour bytes at all). pyrekordbox
raises `PaddingError` on the 44-byte form, the whole `.EXT` fails to parse, and
a reader that falls back to the `.DAT` silently loses pads D-H and every colour.
So every entry here is read at its own `len_entry`, and a field the entry is too
short to hold is simply absent.
A file is also split into its RAW tags, kept byte for byte. Editing a stick
replaces one or two tags of a file rekordbox wrote; everything else (the
waveforms, `PVBR`, tags nobody has decoded) must go back exactly as it was, and
re-serialising through a parser is how bytes get lost.
"""
from __future__ import annotations
import struct
from dataclasses import dataclass, field
#: `PMAI` · len_header · len_file · …
FILE_MAGIC = b"PMAI"
NO_LOOP = 0xFFFFFFFF
#: The cue-list kinds in `PCOB`/`PCO2`'s own header.
LIST_MEMORY = 0
LIST_HOT = 1
@dataclass
class Tag:
"""One tag, raw. `data` is the WHOLE tag: magic, both lengths, and body."""
type: str
data: bytes
_entries: list | None = field(default=None, repr=False, compare=False)
@property
def len_header(self) -> int:
return struct.unpack_from(">I", self.data, 4)[0]
@property
def list_kind(self) -> int | None:
"""`PCOB`/`PCO2`: whether this is the hot cue or the memory list."""
if self.type in ("PCOB", "PCO2") and len(self.data) >= 16:
return struct.unpack_from(">I", self.data, 12)[0]
return None
@property
def entries(self) -> list:
"""The tag's decoded entries (cues, or beats for `PQTZ`); [] otherwise."""
if self._entries is None:
decode = _DECODERS.get(self.type)
self._entries = decode(self.data) if decode else []
return self._entries
@dataclass
class AnlzFile:
"""An analysis file split into its header and raw tags."""
header: bytes
tags: list[Tag]
def to_bytes(self) -> bytes:
"""Reassemble, fixing only the header's file length."""
body = b"".join(t.data for t in self.tags)
head = bytearray(self.header)
struct.pack_into(">I", head, 8, len(head) + len(body))
return bytes(head) + body
def copy(self) -> "AnlzFile":
return AnlzFile(self.header, [Tag(t.type, t.data) for t in self.tags])
def find(self, kind: str, list_kind: int | None = None) -> int | None:
"""Index of the first `kind` tag (of that cue-list kind, if given)."""
for i, t in enumerate(self.tags):
if t.type == kind and (list_kind is None or t.list_kind == list_kind):
return i
return None
def put(self, kind: str, data: bytes, *, list_kind: int | None = None,
after: tuple[str, ...] = ()) -> None:
"""Replace the `kind` tag IN PLACE, keeping every other tag where it is.
A file without one gets it inserted after the last tag named in
`after` (rekordbox's order), else at the end.
"""
tag = Tag(kind, data)
i = self.find(kind, list_kind)
if i is not None:
self.tags[i] = tag
return
at = max((j for j, t in enumerate(self.tags) if t.type in after), default=len(self.tags) - 1)
self.tags.insert(at + 1, tag)
class AnlzError(ValueError):
pass
def parse(data: bytes) -> AnlzFile:
"""Split a file into its tags. Raises `AnlzError` on a malformed file.
Lengths are trusted only as far as the file reaches: a tag claiming more
bytes than remain ends the walk with an error rather than a short read.
"""
if len(data) < 12 or data[:4] != FILE_MAGIC:
raise AnlzError("not an ANLZ file")
len_header = struct.unpack_from(">I", data, 4)[0]
if not 12 <= len_header <= len(data):
raise AnlzError(f"bad file header length {len_header}")
tags: list[Tag] = []
off = len_header
while off < len(data):
if off + 12 > len(data):
raise AnlzError(f"truncated tag at {off}")
kind = data[off:off + 4].decode("latin-1")
len_tag = struct.unpack_from(">I", data, off + 8)[0]
if len_tag < 12 or off + len_tag > len(data):
raise AnlzError(f"bad length {len_tag} for {kind} at {off}")
tags.append(Tag(kind, data[off:off + len_tag]))
off += len_tag
return AnlzFile(header=data[:len_header], tags=tags)
def parse_file(path) -> AnlzFile:
with open(path, "rb") as f:
return parse(f.read())
# ---- cue entries ------------------------------------------------------------
@dataclass
class CueEntry:
"""One `PCPT` or `PCP2` entry. Attribute names follow pyrekordbox's, which
is what `onelibrary.cues` was written against.
`color_code` / RGB are None when the entry is too short to carry them (every
`PCPT`, and rekordbox's compact 44-byte `PCP2`).
"""
hot_cue: int
type: int
time: int
loop_time: int
comment: str = ""
loop_numerator: int = 0
loop_denominator: int = 0
color_code: int | None = None
color_red: int | None = None
color_green: int | None = None
color_blue: int | None = None
len_entry: int = 0
def raw_entries(tag: Tag) -> list[bytes]:
"""A `PCOB`/`PCO2` tag's entries as their own bytes, each at its own length —
so an entry Konduktor does not change goes back exactly as rekordbox wrote it."""
if tag.type == "PCOB":
count, first, magic = struct.unpack_from(">H", tag.data, 18)[0], 24, b"PCPT"
elif tag.type == "PCO2":
count, first, magic = struct.unpack_from(">H", tag.data, 16)[0], 20, b"PCP2"
else:
return []
return [tag.data[off:off + n] for off, n in _walk(tag.data, first, magic, count)]
def decode_entry(entry: bytes) -> CueEntry:
"""One raw `PCPT` or `PCP2` entry, decoded."""
if entry[:4] == b"PCPT":
return _pcob(struct.pack(">4sIIIHHi", b"PCOB", 24, 24 + len(entry), 0, 0, 1, -1) + entry)[0]
return _pco2(struct.pack(">4sIIIHH", b"PCO2", 20, 20 + len(entry), 0, 1, 0) + entry)[0]
def entry_hot_cue(entry: bytes) -> int:
"""A PCPT/PCP2 entry's `hot_cue`: its pad, 1-based; 0 for a memory cue."""
return struct.unpack_from(">I", entry, 12)[0]
def entry_with_colour(entry: bytes, code: int, rgb: tuple[int, int, int]) -> bytes | None:
"""A `PCP2` entry with ONLY its colour bytes changed — what rekordbox itself
does to recolour a cue (measured: those 4 bytes and nothing else). None if
the entry is too short to carry a colour (rekordbox's 44-byte form)."""
if len(entry) < 44:
return None
len_comment = struct.unpack_from(">I", entry, 40)[0]
at = 44 + len_comment
if at + 4 > len(entry):
return None
return entry[:at] + bytes([code & 0xFF, *rgb]) + entry[at + 4:]
def entry_without_loop_beats(entry: bytes) -> bytes:
"""A `PCP2` entry with its loop length in beats cleared to 0/0 — what
rekordbox does to every loop when the grid changes (measured: 32/1 -> 0/0),
rather than recomputing it."""
if len(entry) < 40 or entry[36:40] == b"\0\0\0\0":
return entry
return entry[:36] + bytes(4) + entry[40:]
def _walk(data: bytes, first: int, magic: bytes, count: int):
"""(offset, len_entry) for each entry, trusting each entry's own length."""
off = first
for _ in range(count):
if off + 12 > len(data) or data[off:off + 4] != magic:
return
len_entry = struct.unpack_from(">I", data, off + 8)[0]
if len_entry < 12 or off + len_entry > len(data):
return
yield off, len_entry
off += len_entry
def _pcob(data: bytes) -> list[CueEntry]:
# tag prefix(12) · I list kind · H 0 · H count · i last
count = struct.unpack_from(">H", data, 18)[0]
out = []
for off, n in _walk(data, 24, b"PCPT", count):
if n < 44:
continue
# 4s · I len_header · I len_entry · I hot_cue · I status · I 0x10000 ·
# H order_first · H order_last · B kind · x · H 1000 · I time · I loop
hot_cue, = struct.unpack_from(">I", data, off + 12)
kind = data[off + 28]
time, loop = struct.unpack_from(">II", data, off + 32)
out.append(CueEntry(hot_cue=hot_cue, type=kind, time=time, loop_time=loop, len_entry=n))
return out
def _pco2(data: bytes) -> list[CueEntry]:
# tag prefix(12) · I list kind · H count · H 0
count = struct.unpack_from(">H", data, 16)[0]
out = []
for off, n in _walk(data, 20, b"PCP2", count):
if n < 28:
continue
hot_cue, = struct.unpack_from(">I", data, off + 12)
kind = data[off + 16]
time, loop = struct.unpack_from(">II", data, off + 20)
e = CueEntry(hot_cue=hot_cue, type=kind, time=time, loop_time=loop, len_entry=n)
if n >= 44:
e.loop_numerator, e.loop_denominator, len_comment = struct.unpack_from(">HHI", data, off + 36)
colour_at = off + 44 + len_comment
if len_comment and colour_at <= off + n:
e.comment = data[off + 44:colour_at].decode("utf-16-be", "replace").rstrip("\x00")
if colour_at + 4 <= off + n:
e.color_code, e.color_red, e.color_green, e.color_blue = data[colour_at:colour_at + 4]
out.append(e)
return out
# ---- the beatgrid -----------------------------------------------------------
@dataclass
class Beat:
beat: int # 1-4, position in the bar
tempo: int # BPM x 100
time: int # ms
def _pqtz(data: bytes) -> list[Beat]:
# tag prefix(12) · I 0 · I 0x80000 · I count, then 8-byte entries
count = struct.unpack_from(">I", data, 20)[0]
first = struct.unpack_from(">I", data, 4)[0]
out = []
for i in range(count):
off = first + 8 * i
if off + 8 > len(data):
break
beat, tempo, time = struct.unpack_from(">HHI", data, off)
out.append(Beat(beat=beat, tempo=tempo, time=time))
return out
_DECODERS = {"PCOB": _pcob, "PCO2": _pco2, "PQTZ": _pqtz}
__all__ = [
"AnlzError", "AnlzFile", "Beat", "CueEntry", "LIST_HOT", "LIST_MEMORY",
"NO_LOOP", "Tag", "decode_entry", "entry_hot_cue", "entry_with_colour", "entry_without_loop_beats",
"parse", "parse_file", "raw_entries",
]
@@ -313,30 +313,38 @@ def flat_preview_tags() -> list[bytes]:
return preview_tags([0.0] * 400, [0.0] * 400)
def _pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
rgb: tuple[int, int, int] | None, beats: int | None, code: int = 0) -> bytes:
def pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
rgb: tuple[int, int, int] | None, beats: int | None, code: int = 0,
comment: str | None = None) -> bytes:
"""One `PCP2` entry, byte-for-byte as rekordbox 7 writes it.
Two constants in here are rekordbox's, not the documented struct's: the
`1000` after the kind (the struct calls it padding) and the `1` after the
colour id. Both appear in every entry of a real export; zeros there were a
guess, and pyrekordbox's parser would never notice one.
A `comment` (the cue's name) is UTF-16BE with a terminating NUL, and
`len_comment` counts the terminator — crate-digger's layout, which both
Konduktor's reader and pyrekordbox's agree with. No reference cue carries
one, so that detail is documented rather than measured. The entry stays the
exported 88 bytes unless the name needs more.
"""
comment = b""
comment_bytes = (comment.encode("utf-16-be") + b"\0\0") if comment else b""
red, green, blue = rgb or (0, 0, 0)
length = max(PCP2_ENTRY_LEN, 48 + len(comment_bytes))
return struct.pack(
">4sIIIBxHIIBB6xHHI",
b"PCP2", 16, PCP2_ENTRY_LEN, hot_cue, kind, 1000,
b"PCP2", 16, length, hot_cue, kind, 1000,
int(time_ms), NO_LOOP if loop_ms is None else int(loop_ms),
0, 1, beats or 0, 1 if beats else 0, len(comment),
0, 1, beats or 0, 1 if beats else 0, len(comment_bytes),
# The colour is the palette CODE, then RGB: rekordbox draws from the code
# (`palette`); a code of 0 draws its default colour whatever the RGB says.
) + comment + struct.pack(">4B", code & 0xFF, red, green, blue) + bytes(
PCP2_ENTRY_LEN - 48 - len(comment)
) + comment_bytes + struct.pack(">4B", code & 0xFF, red, green, blue) + bytes(
length - 48 - len(comment_bytes)
)
def _pcpt_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None) -> bytes:
def pcpt_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None) -> bytes:
"""One `PCPT` entry, byte-for-byte as rekordbox 7 writes it.
`len_header` is **28**, not 12: a reader that trusts it finds the body 16
@@ -353,28 +361,54 @@ def _pcpt_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None) -
) + bytes(16)
def _pcob(cue_type: int, chosen: list[dict]) -> bytes:
blob = b"".join(
_pcpt_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
loop_ms=c["loop_ms"])
for c in chosen
)
def pcob_tag(cue_type: int, entries: list[bytes]) -> bytes:
"""A `PCOB` around already-built `PCPT` entries (rekordbox's own, untouched,
or new ones from `pcpt_entry`)."""
# cue_type is Int32ub (an Enum over it), NOT Int16 — getting this wrong
# shifts every following field and the reader sees garbage. The last field
# is -1 on a hot-cue list and (count - 1) on a memory list, as rekordbox
# writes it.
last = -1 if cue_type == 1 else len(chosen) - 1
return _wrap("PCOB", struct.pack(">IHHi", cue_type, 0, len(chosen), last) + blob)
# writes it (an export, and rekordbox's own edits, alike).
last = -1 if cue_type == 1 else len(entries) - 1
return _wrap("PCOB", struct.pack(">IHHi", cue_type, 0, len(entries), last) + b"".join(entries))
def pco2_tag(cue_type: int, entries: list[bytes]) -> bytes:
"""A `PCO2` around already-built `PCP2` entries."""
return _wrap("PCO2", struct.pack(">IHH", cue_type, len(entries), 0) + b"".join(entries))
def _pcob(cue_type: int, chosen: list[dict]) -> bytes:
return pcob_tag(cue_type, [
pcpt_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
loop_ms=c["loop_ms"])
for c in chosen
])
def _pco2(cue_type: int, chosen: list[dict]) -> bytes:
blob = b"".join(
_pcp2_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
return pco2_tag(cue_type, [
pcp2_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
loop_ms=c["loop_ms"], rgb=c.get("rgb"), beats=c.get("beats"),
code=c.get("code", 0))
code=c.get("code", 0), comment=c.get("comment"))
for c in chosen
)
return _wrap("PCO2", struct.pack(">IHH", cue_type, len(chosen), 0) + blob)
])
#: `PQT2` as rekordbox 7 leaves it after a grid edit: header kept, every count
#: and the beat list gone (56 bytes, the `len_header`). MEASURED on Goober
#: (2026-10-01): rekordbox does not recompute this "extended" grid when the grid
#: changes, it blanks it, and a CDJ then works from `PQTZ`.
_PQT2_HEADER = 56
def blank_pqt2(tag: bytes) -> bytes:
"""The blanked form of an existing `PQT2` tag, exactly as rekordbox writes it.
Bytes 12-24 (rekordbox's constants, `00000000 01000002 00000000` on every
file seen) are KEPT; the counts and first/last-beat fields after them are
zeroed, and the beat entries dropped.
"""
return tag[:8] + struct.pack(">I", _PQT2_HEADER) + tag[12:24] + bytes(_PQT2_HEADER - 24)
def cue_tags(cues: list[dict], *, extended: bool) -> list[bytes]:
@@ -69,8 +69,8 @@ def capabilities_for(
max_memory_cues=None, # unlimited
# Both cue types write; Rekordbox has no fade/load types.
types=WRITABLE_CUE_TYPES,
# A hot cue's colour is one of rekordbox's swatches (the 15 that
# were measured, see `palette`), offered in rekordbox's own order.
# A hot cue's colour is one of rekordbox's 16 swatches (all
# measured, see `palette`), offered in rekordbox's own order.
color="palette",
palette=[palette.hex_for(code) for code in palette.SWATCHES],
named=True, # djmdCue.Comment
@@ -63,7 +63,7 @@ class RekordboxDriver:
except Exception: # noqa: BLE001
pass
def open(self, path: Path) -> RekordboxAdapter:
def open(self, path: Path, *, read_only: bool = False) -> RekordboxAdapter:
return RekordboxAdapter(path)
def detect(self) -> list[dict]:
@@ -9,8 +9,9 @@ The table was MEASURED, not recalled: 16 hot cues coloured through rekordbox 7's
own palette, one colour per pad, exported to a stick, and read back. Rekordbox
writes the palette's exact RGB beside each code.
* One palette colour went unmeasured — the teal-green between 0x0E and 0x16
(probably code 0x12); a cue that should be it maps to its nearest neighbour.
* The teal-green between 0x0E and 0x16 was missed by that measurement, and
found later: it is **0x13 = #00FF30**, which rekordbox 7 wrote itself as the
DEFAULT colour of a hot cue added on a stick (Goober, 2026-10-01).
* 0x2B (#FF0017) was observed on a real export though it is not one of the 16
swatches; it is kept so such a colour survives a round trip exactly.
* **The palette has no white or grey.** A colourless (white/grey) cue — above
@@ -32,6 +33,7 @@ PALETTE: dict[int, tuple[int, int, int]] = {
0x05: (0x00, 0x70, 0xFF), # light blue
0x09: (0x00, 0xE0, 0xFF), # cyan
0x0E: (0x00, 0xFF, 0xA3), # teal
0x13: (0x00, 0xFF, 0x30), # teal-green (rekordbox's default for a new hot cue)
0x16: (0x1A, 0xFF, 0x00), # green
0x1A: (0x80, 0xFF, 0x00), # lime
0x1E: (0xE6, 0xFF, 0x00), # yellow-lime
@@ -94,18 +96,17 @@ def code_for(color: str | None) -> tuple[int, tuple[int, int, int]]:
#: The swatches a user can pick, in rekordbox's own order — what
#: `capabilities.cues.palette` offers. 15 of rekordbox's 16: the unmeasured
#: teal-green is left out rather than offered with a guessed RGB, and 0x2B is
#: not a swatch at all (see the module note).
#: `capabilities.cues.palette` offers: all 16. 0x2B is not a swatch at all (see
#: the module note).
SWATCHES: list[int] = [code for code in PALETTE if code != 0x2B]
def hex_for(code: int | None) -> str | None:
"""`#RRGGBB` for a stored palette code; None for uncoloured or unknown.
An unknown code (the unmeasured teal-green) projects as no colour rather
than a guessed one; it is still kept on the row, since editing a cue's
position, type or name never rewrites its colour.
An unknown code projects as no colour rather than a guessed one; it is
still kept on the row, since editing a cue's position, type or name never
rewrites its colour.
"""
rgb = PALETTE.get(code) if code else None
return None if rgb is None else f"#{rgb[0]:02X}{rgb[1]:02X}{rgb[2]:02X}"
+163
View File
@@ -430,3 +430,166 @@ __all__ = [
"album_row", "artist_row", "dsql", "id_string_row", "key_row", "playlist_entry_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)
+2 -48
View File
@@ -45,6 +45,7 @@ from ...core.adapter import (
Unsupported,
)
from ...core.edit_journal import EditJournal
from ...core.grid_edit import ReplaceGridCommands
from ...core.pathmap import PathMapping
from . import timebase
from .cue_types import beat_loop_size, kind_for, role_and_slot
@@ -110,7 +111,7 @@ def _iso_stamp(value) -> str:
return str(value)
class RekordboxStore:
class RekordboxStore(ReplaceGridCommands):
"""One open Rekordbox library."""
def __init__(self, path: Path):
@@ -1285,53 +1286,6 @@ class RekordboxStore:
row.BPM = int(round(ordered[0].bpm * 100)) if ordered else 0
self._journal.record("grid", "replace" if ordered else "delete", track_id)
def delete_grid(self, track_id: str) -> None:
self.replace_grid(track_id, [])
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> None:
from ...core.model import GridMarker
markers = self.current_markers(track_id)
if bpm is None:
# Inherit the tempo governing this point, like Traktor's add does.
governing = [m for m in markers if m.start <= start_sec]
bpm = governing[-1].bpm if governing else (markers[0].bpm if markers else None)
if not bpm:
raise InvalidCommand("The first marker on an ungridded track needs a tempo")
if any(abs(m.start - start_sec) < 0.001 for m in markers):
raise InvalidCommand("There is already a marker here")
markers.append(GridMarker(start=float(start_sec), bpm=float(bpm)))
self.replace_grid(track_id, markers)
def _marker_at(self, track_id: str, index: int) -> tuple[list, int]:
markers = self.current_markers(track_id)
if not 0 <= index < len(markers):
raise NotFound(f"No grid marker {index}")
return markers, index
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> None:
markers, i = self._marker_at(track_id, index)
# Clamp between neighbours so the list cannot reorder under the caller.
low = markers[i - 1].start + 0.001 if i > 0 else 0.0
high = markers[i + 1].start - 0.001 if i + 1 < len(markers) else None
target = max(low, float(start_sec))
if high is not None:
target = min(target, high)
markers[i] = markers[i].model_copy(update={"start": target})
self.replace_grid(track_id, markers)
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> None:
markers, i = self._marker_at(track_id, index)
if bpm <= 0:
raise InvalidCommand(f"A tempo must be positive, got {bpm}")
markers[i] = markers[i].model_copy(update={"bpm": float(bpm)})
self.replace_grid(track_id, markers)
def delete_grid_marker(self, track_id: str, index: int) -> None:
markers, i = self._marker_at(track_id, index)
del markers[i]
self.replace_grid(track_id, markers)
def _flush_grids(self) -> None:
"""Write buffered grids into their ANLZ files. Called by save().
+1 -1
View File
@@ -25,7 +25,7 @@ class TraktorDriver:
return False
return b"<NML" in head and b"VERSION=" in head
def open(self, path: Path) -> TraktorAdapter:
def open(self, path: Path, *, read_only: bool = False) -> TraktorAdapter:
return TraktorAdapter(path)
def detect(self) -> list[dict]:
+1 -11
View File
@@ -22,7 +22,6 @@ import copy
import math
import threading
import uuid as uuidlib
from dataclasses import dataclass
from pathlib import Path
from traktor_nml_utils import (
@@ -46,7 +45,7 @@ from traktor_nml_utils.models.collection import (
)
from xsdata.formats.dataclass.serializers import XmlSerializer
from ...core.adapter import InvalidCommand, SaveOutcome, StemSwapResult
from ...core.adapter import FileTagResult, InvalidCommand, SaveOutcome, StemSwapResult
from ...core.edit_journal import EditJournal
from ...core.pathmap import common_dir_prefix
from ...core.pathmap import PathMapping
@@ -71,15 +70,6 @@ class PlaylistError(InvalidCommand):
"""
@dataclass
class FileTagResult:
track_id: str
file: str
ok: bool
status: str # "written" | "file-not-found" | "unsupported-format" | "error"
detail: str = ""
class TraktorStore:
def __init__(self, nml_path: Path):
self.nml_path = Path(nml_path)
+2 -2
View File
@@ -79,7 +79,7 @@ class AppState:
rests on, and an adapter is the thing that knows whether it is true —
so it is asserted here rather than assumed everywhere else.
"""
adapter = registry.open_library(path)
adapter = registry.open_library(path, read_only=True)
if adapter.capabilities().writable:
if hasattr(adapter, "close"):
try:
@@ -87,7 +87,7 @@ class AppState:
except Exception: # noqa: BLE001
pass
raise ValueError(
f"{path} is a writable library; only read-only sources "
f"{path} cannot be opened read-only; only a library that can "
"(such as a OneLibrary drive) can be opened as a source"
)
self.close_source()
+29 -3
View File
@@ -28,6 +28,21 @@ from .pathmap import PathMapping
from .relocate import PathGroup
@dataclass
class FileTagResult:
"""One audio-file tag write a save made — the `SaveOutcome.tag_results` item.
Promoted from the Traktor store when OneLibrary became the second platform
that writes edited fields into the audio files themselves.
"""
track_id: str
file: str
ok: bool
status: str # "written" | "file-not-found" | "unsupported-format" | "error"
detail: str = ""
@dataclass
class SaveOutcome:
"""What a save produced, in terms every platform can answer.
@@ -185,11 +200,18 @@ class LibraryAdapter(Protocol):
# is touched, so a cancel leaves it as it was. Gated on
# `capabilities().tracks.addable`.
def add_tracks(self, items: list["NewTrack"], *, checkpoint=None) -> list[str]: ...
# OPTIONAL, where `capabilities().tracks.places_audio`: the library decides
# where added audio goes. `place_audio(source, track)` returns the path the
# importer must COPY `source` to (which becomes `NewTrack.audio_path`), or
# None when the file is already where the library can use it in place;
# `audio_home()` is where that audio lands, for the free-space check.
# (A protocol member would make every adapter implement them.)
# Remove tracks from the library — and so from every playlist, since an
# entry naming a track the library no longer has is a dangling reference.
# Never touches audio files. Returns how many were removed; gated on
# `capabilities().tracks.removable`.
# Never touches audio files, except where `tracks.places_audio` (a stick's
# audio belongs to its library): there the file goes too, at Save. Returns
# how many were removed; gated on `capabilities().tracks.removable`.
def remove_tracks(self, track_ids: list[str]) -> int: ...
# Swap converted stem files into the library (see `StemSwap`), all at once:
@@ -274,7 +296,11 @@ class LibraryDriver(Protocol):
selects: str
def can_open(self, path: Path) -> bool: ...
def open(self, path: Path) -> LibraryAdapter: ...
# `read_only` opens a library only to READ it, alongside the loaded one (the
# sidebar's Devices). An adapter that honours it reports `writable=False`
# with cause `browsing`; one that ignores it still reports writable, and the
# caller — `AppState.open_source` — refuses it, so ignoring is safe.
def open(self, path: Path, *, read_only: bool = False) -> LibraryAdapter: ...
# OPTIONAL. What to call an opened library on screen. Only the adapter can
# answer for a platform where one library has more than one valid path —
# the filename is otherwise assumed, and that assumption is wrong for a
+14 -2
View File
@@ -22,7 +22,10 @@ from pydantic import BaseModel
# permanent refusal protecting their other machines.
# `not_in_library` is a folder of loose files being browsed: nothing there is a
# library to write to, and the way to edit one is to add it to the collection.
ReadonlyCause = Literal["platform_incomplete", "cloud_synced", "not_in_library"]
# `browsing` is an editable library opened only to READ alongside the loaded one
# (a OneLibrary stick in the sidebar's Devices): the way to edit it is to open it
# as THE library, which one SaveBar and one dirty state can then follow.
ReadonlyCause = Literal["platform_incomplete", "cloud_synced", "not_in_library", "browsing"]
CueType = Literal["cue", "fade_in", "fade_out", "load", "loop"]
CueRole = Literal["hotcue", "memory"]
@@ -61,11 +64,17 @@ class TrackCapabilities(BaseModel):
editable_fields: list[str] = []
media_kinds: list[MediaKind] = ["audio"]
# Tracks can be removed from the library (and so from its playlists). The
# audio file is never touched either way.
# audio file is never touched — except where `places_audio`: a library that
# owns where its audio lives (a stick) deletes it with the track, at Save.
removable: bool = False
# Tracks can be added to the library (`add_tracks`): an import from a
# device, or browsed files added to the collection.
addable: bool = False
# The LIBRARY decides where added audio goes (`place_audio`), so the user is
# neither asked "copy or leave in place?" nor for a destination: a OneLibrary
# stick can only point at files on itself, and lays them out as rekordbox
# does. False: the user chooses, as for a desktop collection.
places_audio: bool = False
# Tracks can be converted to native-instruments STEM files, which this
# platform plays as stems (`apply_stem_swaps`).
stem_convertible: bool = False
@@ -95,6 +104,9 @@ class SaveCapabilities(BaseModel):
library_label: str
overwrite_risk: Literal["none", "on_exit", "while_running"] = "none"
history: bool = True
# The library was written by one of Konduktor's EXPORT sets, whose next run
# replaces it — so an edit made here directly is undone by the next export.
managed_by_export: bool = False
class Capabilities(BaseModel):
+69
View File
@@ -0,0 +1,69 @@
"""Marker-level beatgrid commands, for a store whose one primitive is "replace".
A platform that stores the grid as a flat list of beats (Rekordbox's `PQTZ`, and
so OneLibrary's) has no native "move this marker": every marker-level command is
a read-modify-replace of the generic marker list. Promoted here when OneLibrary
became the second store needing exactly that, so "where does a moved marker
clamp" cannot mean two things. (Traktor's store has markers natively and keeps
its own, companion-cue-aware versions.)
A store using it provides `current_markers(track_id)` and
`replace_grid(track_id, markers)`.
"""
from __future__ import annotations
from .adapter import InvalidCommand, NotFound
from .model import GridMarker
class ReplaceGridCommands:
def current_markers(self, track_id: str) -> list[GridMarker]: # pragma: no cover
raise NotImplementedError
def replace_grid(self, track_id: str, markers: list[GridMarker]) -> None: # pragma: no cover
raise NotImplementedError
def delete_grid(self, track_id: str) -> None:
self.replace_grid(track_id, [])
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> None:
markers = self.current_markers(track_id)
if bpm is None:
# Inherit the tempo governing this point, like Traktor's add does.
governing = [m for m in markers if m.start <= start_sec]
bpm = governing[-1].bpm if governing else (markers[0].bpm if markers else None)
if not bpm:
raise InvalidCommand("The first marker on an ungridded track needs a tempo")
if any(abs(m.start - start_sec) < 0.001 for m in markers):
raise InvalidCommand("There is already a marker here")
markers.append(GridMarker(start=float(start_sec), bpm=float(bpm)))
self.replace_grid(track_id, markers)
def _marker_at(self, track_id: str, index: int) -> tuple[list, int]:
markers = self.current_markers(track_id)
if not 0 <= index < len(markers):
raise NotFound(f"No grid marker {index}")
return markers, index
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> None:
markers, i = self._marker_at(track_id, index)
# Clamp between neighbours so the list cannot reorder under the caller.
low = markers[i - 1].start + 0.001 if i > 0 else 0.0
high = markers[i + 1].start - 0.001 if i + 1 < len(markers) else None
target = max(low, float(start_sec))
if high is not None:
target = min(target, high)
markers[i] = markers[i].model_copy(update={"start": target})
self.replace_grid(track_id, markers)
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> None:
markers, i = self._marker_at(track_id, index)
if bpm <= 0:
raise InvalidCommand(f"A tempo must be positive, got {bpm}")
markers[i] = markers[i].model_copy(update={"bpm": float(bpm)})
self.replace_grid(track_id, markers)
def delete_grid_marker(self, track_id: str, index: int) -> None:
markers, i = self._marker_at(track_id, index)
del markers[i]
self.replace_grid(track_id, markers)
+2 -2
View File
@@ -44,8 +44,8 @@ def driver_for(path: Path) -> LibraryDriver:
raise LibraryNotSupported(f"No DJ library Konduktor recognises at {path}")
def open_library(path: Path):
return driver_for(path).open(path)
def open_library(path: Path, *, read_only: bool = False):
return driver_for(path).open(path, read_only=read_only)
def describe(path: Path) -> dict:
+36 -3
View File
@@ -290,9 +290,15 @@ def run(
destination and nothing to roll back. `into_playlist` appends every planned
track — the new ones and those the destination already held — to one of the
destination's playlists before the save, so both land in one commit.
A destination that PLACES ITS OWN AUDIO (`tracks.places_audio`: a OneLibrary
stick) overrides both: `dest.place_audio` names each copy's target, or says
the file can be used where it is, and `reference`/`plan.destination` are
ignored.
"""
destination = plan.destination
if not reference:
places = places_audio(dest)
if not reference and not places:
assert destination is not None
destination.mkdir(parents=True, exist_ok=True)
@@ -318,11 +324,18 @@ def run(
for planned in importable:
handle.raise_if_cancelled()
assert planned.source_path is not None
if reference:
if places:
target = dest.place_audio(planned.source_path, source.track(planned.track_id))
if target is None:
copied.append((planned, planned.source_path))
continue
handle.progress(message=f"Copying {planned.title}")
target.parent.mkdir(parents=True, exist_ok=True)
elif reference:
copied.append((planned, planned.source_path))
continue
else:
target = _unique_target(destination, planned.source_path.name, taken)
handle.progress(message=f"Copying {planned.title}")
created.append(target) # registered BEFORE the write, so a cancel
copy_file(planned.source_path, target, handle, bump) # mid-file is cleaned
copied.append((planned, target))
@@ -399,6 +412,26 @@ def run(
raise
def places_audio(dest) -> bool:
"""Whether the destination decides where added audio goes (a stick)."""
try:
return bool(dest.capabilities().tracks.places_audio) and hasattr(dest, "place_audio")
except Exception: # noqa: BLE001
return False
def placed_bytes(dest, plan: ImportPlan) -> int:
"""What an import into a self-placing library will COPY: a file already under
its `audio_home()` is used in place and costs nothing."""
home = dest.audio_home()
total = 0
for planned in plan.importable:
path = planned.source_path
if path is not None and not path.resolve().is_relative_to(home.resolve()):
total += planned.size
return total
def _save(dest):
"""Save through AppState so the version-history commit is not skipped."""
from .app_state import STATE
+34 -11
View File
@@ -1894,7 +1894,10 @@ def _folder_add_plan(body: FolderAddRequest):
# One source across however many folders the ids came from.
source = FolderSource(Path(tracks[0].id).parent, tracks)
destination = None
if body.mode == "copy":
if importer.places_audio(dest):
# The library decides (a stick): no mode, no destination to ask for.
destination = dest.audio_home()
elif body.mode == "copy":
if not body.destination:
raise HTTPException(400, "Copying needs a destination folder")
destination = Path(body.destination).expanduser()
@@ -1910,9 +1913,11 @@ def _folder_add_plan(body: FolderAddRequest):
@app.post("/api/folder/add/preview")
def folder_add_preview(body: FolderAddRequest) -> dict:
_source, _dest, destination, plan = _folder_add_plan(body)
_source, dest, destination, plan = _folder_add_plan(body)
out = plan.as_dict(free_bytes=importer.free_bytes(destination) if destination else None)
if body.mode == "reference":
if importer.places_audio(dest):
_placed_space(out, dest, plan, destination)
elif body.mode == "reference":
# Nothing is copied, so there is no size to fit anywhere.
out.update(total_bytes=0, free_bytes=None, enough_space=None)
drive = _drive_of(Path(body.track_ids[0]), places.drives()) if body.track_ids else None
@@ -1927,12 +1932,13 @@ def folder_add(body: FolderAddRequest) -> JobStatus:
source, dest, destination, plan = _folder_add_plan(body)
if not plan.importable and not plan.existing:
raise HTTPException(400, "Nothing to add (none of those files exist)")
if body.mode == "copy":
if body.mode == "copy" or importer.places_audio(dest):
free = importer.free_bytes(destination)
if free is not None and free < plan.total_bytes + importer.SPACE_HEADROOM:
needed = importer.placed_bytes(dest, plan) if importer.places_audio(dest) else plan.total_bytes
if free is not None and free < needed + importer.SPACE_HEADROOM:
raise HTTPException(
400,
f"Not enough space: {plan.total_bytes / 1e9:.1f} GB needed, "
f"Not enough space: {needed / 1e9:.1f} GB needed, "
f"{free / 1e9:.1f} GB free at {destination}",
)
if JOBS.active("import"):
@@ -1962,10 +1968,23 @@ def folder_add(body: FolderAddRequest) -> JobStatus:
# threads rather than something fancier.
def _placed_space(out: dict, dest, plan, destination: Path) -> None:
"""A self-placing library's preview: only what is really COPIED needs room,
and the preview says how many files will be copied vs used in place."""
needed = importer.placed_bytes(dest, plan)
free = importer.free_bytes(destination)
in_place = sum(1 for t in plan.importable if t.source_path is not None
and t.source_path.resolve().is_relative_to(destination.resolve()))
out.update(total_bytes=needed, free_bytes=free,
enough_space=None if free is None else free >= needed + importer.SPACE_HEADROOM,
places_audio=True, in_place=in_place, copied=len(plan.importable) - in_place)
def _import_plan(body: ImportRequest):
source, dest = require_source(), require_adapter()
_require_addable(dest)
destination = Path(body.destination).expanduser()
destination = (dest.audio_home() if importer.places_audio(dest)
else Path(body.destination).expanduser())
return source, dest, destination, importer.plan(
source,
dest,
@@ -1982,8 +2001,11 @@ def import_preview(body: ImportRequest) -> dict:
Computed fresh on every call and never stored — a stick can be re-exported
between the preview and the import, and a stale preview is worse than none.
"""
_source, _dest, destination, plan = _import_plan(body)
return plan.as_dict(free_bytes=importer.free_bytes(destination))
_source, dest, destination, plan = _import_plan(body)
out = plan.as_dict(free_bytes=importer.free_bytes(destination))
if importer.places_audio(dest):
_placed_space(out, dest, plan, destination)
return out
@app.post("/api/import", response_model=JobStatus)
@@ -1994,10 +2016,11 @@ def start_import(body: ImportRequest) -> JobStatus:
if not plan.importable:
raise HTTPException(400, "Nothing to import (no tracks, or none of their files exist)")
free = importer.free_bytes(destination)
if free is not None and free < plan.total_bytes + importer.SPACE_HEADROOM:
needed = importer.placed_bytes(dest, plan) if importer.places_audio(dest) else plan.total_bytes
if free is not None and free < needed + importer.SPACE_HEADROOM:
raise HTTPException(
400,
f"Not enough space: {plan.total_bytes / 1e9:.1f} GB needed, "
f"Not enough space: {needed / 1e9:.1f} GB needed, "
f"{free / 1e9:.1f} GB free at {destination}",
)
# One at a time: two concurrent imports would race on filename collisions and
+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_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.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 test_discard.py; do
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.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 test_discard.py; do
echo "──────────────────────────────────────────"
echo "▶ $t"
echo "──────────────────────────────────────────"
+15 -5
View File
@@ -118,14 +118,24 @@ else:
RekordboxAdapter(work).track(track.id).title == title)
del before
print("== read-only ==")
print("== a OneLibrary drive (editable as THE library) ==")
# A COPY: an editable drive must never be the checked-in fixture.
os.environ["KONDUKTOR_NML"] = ""
drive = Path(tempfile.mkdtemp()) / "Dingus"
shutil.copytree(FIXTURE, drive, ignore=shutil.ignore_patterns("rekordbox-edited"))
db_file = drive / "PIONEER" / "rekordbox" / "exportLibrary.db"
on_disk = db_file.read_bytes()
track_id = "/Contents/Loopmasters/UnknownAlbum/Demo Track 1.mp3"
with TestClient(main.app) as c:
r = c.post("/api/library/open", json={"path": str(FIXTURE)})
r = c.post("/api/library/open", json={"path": str(drive)})
check("the drive opens as the library", r.status_code == 200, f"{r.status_code} {r.text[:200]}")
if r.status_code == 200:
check("a read-only library has nothing to discard (409)", c.post("/api/discard").status_code == 409)
else:
print(f" (skipped: fixture did not open: {r.status_code})")
c.patch("/api/tracks", json={"track_id": track_id, "fields": {"title": "Thrown away"}})
check("the edit is held", main.STATE.adapter.dirty)
check("discard succeeds", c.post("/api/discard").status_code == 200)
check("and drops the edit",
main.STATE.adapter.track(track_id).title.startswith("Demo Track 1"))
check("the drive was never written", db_file.read_bytes() == on_disk)
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+19 -3
View File
@@ -227,13 +227,29 @@ with TestClient(main.app, raise_server_exceptions=False) as c:
check("and saved, not left pending", not rb.dirty)
rb.close()
print("== a library that cannot take tracks refuses the route ==")
fixture = Path(__file__).resolve().parent / "fixtures" / "onelibrary"
print("== a stick places its own audio; a library that cannot add refuses ==")
# A COPY: opened as THE library, a OneLibrary drive is editable.
fixture = Path(tempfile.mkdtemp()) / "onelibrary"
shutil.copytree(Path(__file__).resolve().parent / "fixtures" / "onelibrary", fixture)
r = c.post("/api/library/open", json={"path": str(fixture)})
if r.status_code == 200:
check("the add preview is refused (422)",
# No mode and no destination: the library decides (decision 7).
r = c.post("/api/folder/add/preview", json={"track_ids": [str(two)], "mode": "copy"})
body = r.json() if r.status_code == 200 else {}
check("a stick's preview needs no destination, and counts the copy",
r.status_code == 200 and body.get("places_audio") and body.get("copied") == 1
and body.get("in_place") == 0, f"{r.status_code} {r.text[:200]}")
adapter = main.STATE.adapter
real = adapter.capabilities
caps = real()
adapter.capabilities = lambda: caps.model_copy(
update={"tracks": caps.tracks.model_copy(update={"addable": False})})
try:
check("a library whose capabilities say it cannot add refuses the route (422)",
c.post("/api/folder/add/preview",
json={"track_ids": [str(two)], "mode": "reference"}).status_code == 422)
finally:
adapter.capabilities = real
else:
print(f" (skipped: fixture did not open — {r.status_code})")
+2 -1
View File
@@ -89,7 +89,8 @@ def stage(src: OneLibraryAdapter, music: Path) -> list[NewTrack]:
print("== a drive's tracks land in the collection ==")
nml, music, original = fresh_collection()
source = OneLibraryAdapter(FIXTURE)
# As the app opens a device: read-only (a drive opened as THE library is editable).
source = OneLibraryAdapter(FIXTURE, read_only=True)
dest = TraktorAdapter(nml)
before = len(dest.tracks)
items = stage(source, music)
+115 -18
View File
@@ -112,9 +112,11 @@ class _Entry(dict):
class _Tag:
"""A stand-in for `anlz_file.Tag`: a type and its decoded entries."""
def __init__(self, tag_type, entries):
self.type = tag_type
self.struct = type("S", (), {"content": type("C", (), {"entries": entries})()})()
self.entries = entries
class _Anlz:
@@ -174,6 +176,49 @@ check("nothing read from a drive claims to be editable",
all(not c.editable for c in merged))
print("== a stick rekordbox has EDITED ==")
# rekordbox 7 writes COMPACT cue entries when it edits a stick, where an export
# writes 88-byte ones: a hot cue it added is a 48-byte PCP2, a memory cue a
# 44-byte one with no colour at all. pyrekordbox raised PaddingError on the
# latter, the whole .EXT failed to parse, and the reader fell back to the .DAT —
# losing pads D-E and every colour. These files are Goober's after Ben edited it
# in rekordbox 7 (2026-10-01), trimmed to PPTH + the cue tags, byte for byte.
from konduktor.adapters.rekordbox import anlz_file # noqa: E402
EDITED = FIXTURE / "rekordbox-edited"
for f in sorted(FIXTURE.glob("PIONEER/USBANLZ/*/*/ANLZ*")) + sorted(EDITED.glob("*.*")):
raw = f.read_bytes()
if anlz_file.parse(raw).to_bytes() != raw:
check(f"{f.name} round-trips through the tag reader byte for byte", False)
break
else:
check("every analysis file round-trips through the tag reader byte for byte", True)
nemean = cues_from_anlz(anlz_file.parse_file(EDITED / "nemean.DAT"),
anlz_file.parse_file(EDITED / "nemean.EXT"))
hot = [c for c in nemean if c.role == "hotcue"]
check("the .EXT holding a 44-byte memory entry still parses: all five pads",
[c.slot for c in sorted(hot, key=lambda c: c.slot)] == [0, 1, 2, 3, 4],
str([c.slot for c in hot]))
check("and their colours survive",
{c.slot: c.color for c in hot} == {0: "#1AFF00", 1: "#00E0FF", 2: "#FF5E00",
3: "#B300FF", 4: "#FF0000"},
str({c.slot: c.color for c in hot}))
memory = sorted((c for c in nemean if c.role == "memory"), key=lambda c: (c.start, c.type))
check("a memory cue ON a memory loop's start is not merged into it",
[(round(c.start * 1000), c.type) for c in memory] == [(23, "cue"), (121402, "cue"), (121402, "loop")],
str([(c.start, c.type) for c in memory]))
check("the compact memory entry has no colour, rather than black",
all(c.color is None for c in memory))
demo2 = cues_from_anlz(anlz_file.parse_file(EDITED / "demo-track-2.DAT"),
anlz_file.parse_file(EDITED / "demo-track-2.EXT"))
pad_e = [c for c in demo2 if c.slot == 4]
check("a 48-byte hot cue (added in rekordbox) reads with its colour",
len(pad_e) == 1 and pad_e[0].color == "#00FF30" and round(pad_e[0].start * 1000) == 47525,
str(pad_e))
# ---- the real drive ------------------------------------------------------
if not (FIXTURE / "PIONEER" / "rekordbox" / "exportLibrary.db").is_file():
print(f"\nSKIP: no fixture drive at {FIXTURE}")
@@ -194,7 +239,13 @@ fake.parent.mkdir(parents=True)
shutil.copy(Path(__file__), fake) # a plain text file wearing the right name
check("can_open rejects a non-database in the right place", not driver.can_open(fake.parent.parent.parent))
adapter = OneLibraryAdapter(FIXTURE)
# A drive is now WRITABLE, so the adapter under test opens a COPY — a stray save
# here once rewrote the checked-in fixture. The copy keeps the fixture's folder
# name, which is what the drive's label is checked against.
DRIVE = Path(tempfile.mkdtemp(prefix="konduktor-ol-drive-")) / FIXTURE.name
shutil.copytree(FIXTURE, DRIVE)
FIXTURE_DB_BYTES = (FIXTURE / "PIONEER" / "rekordbox" / "exportLibrary.db").read_bytes()
adapter = OneLibraryAdapter(DRIVE)
check("implements the LibraryAdapter protocol", isinstance(adapter, LibraryAdapter))
print("== the projection ==")
@@ -216,7 +267,7 @@ check("comment comes through", (one.comment or "").startswith("Tracks by"))
check("the track id is its drive-relative path",
one.id == "/Contents/Loopmasters/UnknownAlbum/Demo Track 1.mp3", one.id)
check("filepath resolves under the mount point",
one.filepath == str(FIXTURE / "Contents/Loopmasters/UnknownAlbum/Demo Track 1.mp3"))
one.filepath == str(DRIVE / "Contents/Loopmasters/UnknownAlbum/Demo Track 1.mp3"))
check("and the resolved file is really there", Path(one.filepath).is_file())
check("audio_path agrees with the projection", str(adapter.audio_path(one.id)) == one.filepath)
@@ -266,7 +317,12 @@ memory = [c for c in cues.cues if c.role == "memory"]
check("the memory cue is preserved", len(memory) == 1)
check("it has no slot", memory[0].slot is None)
check("it is the same loop, at the same place", abs(memory[0].start - (40.0 - OFF)) < 0.001)
check("no cue on a read-only drive is editable", all(not c.editable for c in cues.cues))
check("on an editable drive every hot cue is editable, no memory cue is",
all(c.editable == (c.role == "hotcue") for c in cues.cues))
_browse = OneLibraryAdapter(DRIVE, read_only=True)
check("on a browsing drive no cue is editable",
all(not c.editable for c in _browse.track_cues(one.id).cues))
_browse.close()
print("== playlists ==")
tree = adapter.playlist_tree()
@@ -280,8 +336,8 @@ check("its entries are track ids, in order",
entries == [t.id for t in (adapter.playlist_tracks(node.id) or [])])
check("and they resolve to the two tracks", len(adapter.playlist_tracks(node.id)) == 2)
check("a root playlist's parent 0 is not treated as a real node id", len(tree) == 1)
check("nothing on the drive claims to be editable",
not any(n.can_rename or n.can_delete or n.can_add_tracks or n.can_reorder for n in tree))
check("on an editable drive a playlist offers every edit",
all(n.can_rename and n.can_delete and n.can_add_tracks and n.can_reorder for n in tree))
check("entries for an unknown node are None", adapter.playlist_entries("999999") is None)
print("== capabilities gate the UI ==")
@@ -289,27 +345,44 @@ caps = adapter.capabilities()
check("platform is onelibrary", caps.platform == "onelibrary")
# The distinction the whole capability system exists for: this is a roadmap gap,
# not a protective refusal, and the UI must word the two differently.
check("the library is read-only", caps.writable is False)
check("because the platform is incomplete, not because of a sync state",
caps.readonly_cause == "platform_incomplete")
check("opened as THE library, a drive is writable", caps.writable is True and caps.readonly_cause is None)
check("the version is the drive's dbVersion", caps.version == "1000", str(caps.version))
# The per-feature flags still describe the FORMAT. Blanking them to false would
# claim OneLibrary has no hot cues, which is not what read-only means.
check("the format is still reported as having hot cues", caps.cues.hotcue_slots == 8)
check("cue colour is free RGB here, unlike master.db's palette", caps.cues.color == "free")
check("cue colour is rekordbox's palette (rekordbox draws the PCP2 code)",
caps.cues.color == "palette" and len(caps.cues.palette) == 16)
check("loops are a cue type, not a separate bank", caps.cues.loops == "cue_type")
check("memory cues are acknowledged", caps.cues.memory_cues is True)
check("the grid is flexible even though we do not write it", caps.grid.flexible is True)
check("nothing is editable", not caps.cues.editable and not caps.grid.editable)
check("no metadata field is editable", caps.tracks.editable_fields == [])
check("hot cues and the grid are editable", caps.cues.editable and caps.grid.editable)
check("the editable fields are the Rekordbox adapter's set",
caps.tracks.editable_fields == sorted(["title", "artist", "album", "genre", "label",
"remixer", "comment", "rating", "release_date"]),
str(caps.tracks.editable_fields))
check("tracks can be added and removed, the library placing the audio",
caps.tracks.addable and caps.tracks.removable and caps.tracks.places_audio)
check("playlists can be reordered", caps.playlists.reorder is True)
check("ratings are 0-5", caps.tracks.rating_max == 5)
check("folders are supported by the format", caps.playlists.folders is True)
check("a drive carries no smart playlists", caps.playlists.smart == "none")
check("drives are not versioned", caps.save.history is False)
check("nothing else can overwrite it, because we never write", caps.save.overwrite_risk == "none")
check("the label is the drive's name", caps.save.library_label == FIXTURE.name)
check("another app's write is caught at save, not risked", caps.save.overwrite_risk == "none")
check("Save is named for the drive", caps.save.app_name == FIXTURE.name, caps.save.app_name)
print("== every command is refused ==")
print("== opened for BROWSING (the sidebar's Devices) ==")
browse = OneLibraryAdapter(DRIVE, read_only=True)
bcaps = browse.capabilities()
check("a browsing drive is read-only", bcaps.writable is False)
check("because it is being browsed, not because the platform is incomplete",
bcaps.readonly_cause == "browsing", str(bcaps.readonly_cause))
check("and the registry opens it that way when asked",
registry.open_library(DRIVE, read_only=True).capabilities().readonly_cause == "browsing")
bnode = browse.playlist_tree()[0]
check("its playlists offer nothing",
not (bnode.can_add_tracks or bnode.can_reorder or bnode.can_rename or bnode.can_delete))
print("== what is refused ==")
COMMANDS = [
("set_track_metadata", lambda: adapter.set_track_metadata(one.id, {"title": "x"})),
("set_cover_art", lambda: adapter.set_cover_art(one.id, b"", "image/png")),
@@ -335,9 +408,31 @@ COMMANDS = [
("save", lambda: adapter.save()),
("snapshot", lambda: adapter.snapshot()),
]
refused = [name for name, fn in COMMANDS if not _raises(fn, Unsupported)]
check(f"all {len(COMMANDS)} commands raise Unsupported", not refused, "; ".join(refused))
check("nothing is ever dirty", adapter.dirty is False)
# Browsing: EVERY command refuses — the ones that work on an editable drive too.
BROWSE = [(n, (lambda f=f: f(browse))) for n, f in [
("set_track_metadata", lambda a: a.set_track_metadata(one.id, {"title": "x"})),
("create_playlist", lambda a: a.create_playlist("x")),
("create_folder", lambda a: a.create_folder("x")),
("rename_playlist", lambda a: a.rename_playlist(node.id, "x")),
("delete_playlist", lambda a: a.delete_playlist(node.id)),
("set_playlist_entries", lambda a: a.set_playlist_entries(node.id, [])),
("save", lambda a: a.save()),
]]
refused = [name for name, fn in BROWSE if not _raises(fn, Unsupported)]
check("a browsing drive refuses every edit, Save included", not refused, "; ".join(refused))
check("and is never dirty", browse.dirty is False)
browse.close()
# Editable: what has not landed yet still refuses (each with its flag False).
LANDED = {"set_track_metadata", "create_playlist", "rename_playlist", "delete_playlist",
"set_playlist_entries", "save",
"set_cue", "set_cue_type", "set_cue_color", "delete_cue", "place_cues",
"add_grid_marker", "move_grid_marker", "set_grid_marker_bpm", "delete_grid_marker",
"replace_grid", "set_analysed_grid", "delete_grid", "remove_tracks"}
pending = [(n, fn) for n, fn in COMMANDS if n not in LANDED]
refused = [name for name, fn in pending if not _raises(fn, Unsupported)]
check(f"the {len(pending)} commands not written yet raise Unsupported", not refused, "; ".join(refused))
check("refusing leaves nothing dirty", adapter.dirty is False)
check("an unknown track is a NotFound, not an Unsupported",
_raises(lambda: adapter.audio_path("no-such-track"), NotFound))
@@ -360,6 +455,8 @@ check("detection of unplugged drives is empty, not an error",
adapter.close()
check("closing twice is safe", adapter.close() is None)
check("the checked-in fixture was never written",
(FIXTURE / "PIONEER" / "rekordbox" / "exportLibrary.db").read_bytes() == FIXTURE_DB_BYTES)
print()
print("RESULT:", "FAILED" if failed else "ALL PASSED")
+261
View File
@@ -0,0 +1,261 @@
"""Cue and beatgrid edits on a OneLibrary stick: the ANLZ files.
Two kinds of check, on temp copies of two real rekordbox-written drives:
* **against rekordbox's own edit** (`fixtures/onelibrary-goober/after/`): the
same edit made in rekordbox 7 and in Konduktor must produce the same bytes —
a recolour changes only the colour bytes, a grid edit blanks `PQT2` and
clears the loop beat lengths exactly as rekordbox did;
* **fidelity**: nothing reaches the drive before Save, only the tags an edit
touches change (in place, order kept), a pad keeps its colour and name
through a move, memory cues stay uneditable, and an `.EXT` with no `PCO2`
keeps every pad when the first edit creates one.
"""
import os
import shutil
import sys
import tempfile
import time
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
APPDATA = Path(tempfile.mkdtemp(prefix="konduktor-olanlz-appdata-"))
os.environ["KONDUKTOR_DATA_DIR"] = str(APPDATA)
from konduktor.adapters.onelibrary.adapter import OneLibraryAdapter # noqa: E402
from konduktor.adapters.rekordbox import anlz_file as A # noqa: E402
from konduktor.adapters.rekordbox import anlz_writer as W # noqa: E402
from konduktor.core.adapter import InvalidCommand, NotFound, Unsupported # noqa: E402
from konduktor.core.model import CuePoint, GridMarker # noqa: E402
HERE = Path(__file__).resolve().parent
GOOBER = HERE / "fixtures" / "onelibrary-goober"
DEMO = HERE / "fixtures" / "onelibrary"
TRACK_1 = "/Contents/Loopmasters/UnknownAlbum/Demo Track 1.mp3"
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
def _raises(fn, exc) -> bool:
try:
fn()
except exc:
return True
except Exception: # noqa: BLE001
return False
return False
def copy_of(fixture: Path, name: str) -> Path:
root = Path(tempfile.mkdtemp(prefix="konduktor-olanlz-")) / name
shutil.copytree(fixture, root, ignore=shutil.ignore_patterns("after", "rekordbox-edited", "README.md"))
return root
def tag(path: Path, kind: str, list_kind: int | None = None) -> bytes | None:
f = A.parse_file(path)
return next((t.data for t in f.tags
if t.type == kind and (list_kind is None or t.list_kind == list_kind)), None)
def tags_by_key(source) -> dict:
"""Tags keyed by (type, list kind), from a path or from bytes."""
out = {}
parsed = A.parse(source) if isinstance(source, bytes) else A.parse_file(source)
for t in parsed.tags:
key = (t.type, t.list_kind)
out[key if key not in out else (*key, len(out))] = t.data
return out
def dat_of(adapter, track_id: str) -> Path:
return adapter._store.layout.resolve(adapter._store.content(track_id).analysisDataFilePath)
# ---- against rekordbox's own edits -----------------------------------------------
print("== the same edit as rekordbox 7 made, the same bytes ==")
drive = copy_of(GOOBER, "Goober")
a = OneLibraryAdapter(drive)
by = lambda prefix: next(t for t in a.tracks if t.title.startswith(prefix)) # noqa: E731
black_bloc, wtf, demo2 = by("Justin Hawkes"), by("Result"), by("Demo Track 2")
before_dat = dat_of(a, black_bloc.id).read_bytes()
a.set_cue_color(black_bloc.id, 2, "#FF0045")
a.set_grid_marker_bpm(wtf.id, 0, 87.0)
a.set_cue(demo2.id, slot=4, start_sec=47.5, cue_type="cue")
a.save()
ext = dat_of(a, black_bloc.id).with_suffix(".EXT")
check("a recolour: the PCO2 hot list is rekordbox's, byte for byte",
tag(ext, "PCO2", A.LIST_HOT) == tag(GOOBER / "after" / "black-bloc-recoloured.EXT", "PCO2", A.LIST_HOT))
check("and the .DAT, which holds no colour, is untouched", dat_of(a, black_bloc.id).read_bytes() == before_dat)
ext = dat_of(a, wtf.id).with_suffix(".EXT")
check("a grid edit blanks PQT2 exactly as rekordbox does",
tag(ext, "PQT2") == tag(GOOBER / "after" / "wtf-87bpm.EXT", "PQT2"))
check("and clears the memory loop's beat length exactly as rekordbox does",
tag(ext, "PCO2", A.LIST_MEMORY) == tag(GOOBER / "after" / "wtf-87bpm.EXT", "PCO2", A.LIST_MEMORY))
ours = [e.time for t in A.parse_file(dat_of(a, wtf.id)).tags if t.type == "PQTZ" for e in t.entries]
theirs = [e.time for t in A.parse_file(GOOBER / "after" / "wtf-87bpm.DAT").tags if t.type == "PQTZ"
for e in t.entries]
check("PQTZ: the same number of beats as rekordbox's", len(ours) == len(theirs), f"{len(ours)} vs {len(theirs)}")
# rekordbox re-derives its anchor and works at its own tempo precision (its first
# beat moved 83 -> 89 ms, steps alternate 689/690); Konduktor keeps the marker.
check("each within 10 ms of rekordbox's (its anchor moves; ours stays put)",
max(abs(x - y) for x, y in zip(ours, theirs)) <= 10)
check("from the marker where it was, 60/87 s apart",
ours[0] == 83 and all(abs(ours[k] - 83 - k * 60000 / 87) <= 0.5 for k in range(len(ours))))
check("bpmx100 follows the first marker, as rekordbox's did", a._store.content(wtf.id).bpmx100 == 8700)
pads = {c.slot: c for c in a.track_cues(demo2.id).cues if c.role == "hotcue"}
theirs = {e.hot_cue - 1: e for t in A.parse_file(GOOBER / "after" / "demo2-pad-e-added.EXT").tags
if t.type == "PCO2" and t.list_kind == A.LIST_HOT for e in t.entries}
check("a new pad lands where rekordbox's did, the other pads as they were",
sorted(pads) == sorted(theirs) and all(abs(pads[s].start * 1000 - theirs[s].time) < 30
or s == 4 for s in pads), str(sorted(pads)))
a.close()
# ---- fidelity on the demo drive --------------------------------------------------
print("== nothing reaches the drive before Save; only touched tags change ==")
drive = copy_of(DEMO, "Dingus")
a = OneLibraryAdapter(drive)
dat = dat_of(a, TRACK_1)
ext = dat.with_suffix(".EXT")
original = {p: p.read_bytes() for p in (dat, ext)}
cues = {c.slot: c for c in a.track_cues(TRACK_1).cues if c.role == "hotcue"}
check("hot cues are editable, memory cues are not",
all(c.editable == (c.role == "hotcue") for c in a.track_cues(TRACK_1).cues))
a.set_cue(TRACK_1, slot=5, start_sec=10.0, cue_type="cue", name="Drop")
a.set_cue_color(TRACK_1, 5, "#FF0045")
a.set_cue(TRACK_1, slot=5, start_sec=11.0, cue_type="cue")
pad = next(c for c in a.track_cues(TRACK_1).cues if c.slot == 5)
check("a moved pad keeps its colour and its name",
(round(pad.start, 3), pad.color, pad.name) == (11.0, "#FF0045", "Drop"), str(pad))
check("the edit shows at once", a.dirty and round(pad.start, 3) == 11.0)
check("but the drive's files are untouched", all(p.read_bytes() == b for p, b in original.items()))
a.set_cue_type(TRACK_1, 0, "cue") # pad A was a loop
check("a loop retyped to a cue loses its length",
next(c for c in a.track_cues(TRACK_1).cues if c.slot == 0).length == 0.0)
check("a cue cannot become a loop without a length",
_raises(lambda: a.set_cue_type(TRACK_1, 5, "loop"), InvalidCommand))
a.delete_cue(TRACK_1, 3)
check("a pad can be deleted (pad D, which lives in the .EXT's PCOB)",
3 not in {c.slot for c in a.track_cues(TRACK_1).cues if c.role == "hotcue"})
check("deleting an empty pad is NotFound", _raises(lambda: a.delete_cue(TRACK_1, 7), NotFound))
check("a pad beyond the bank is refused",
_raises(lambda: a.set_cue(TRACK_1, slot=8, start_sec=1.0, cue_type="cue"), InvalidCommand))
check("memory cues are not editable",
_raises(lambda: a.set_cue(TRACK_1, slot=0, start_sec=1.0, cue_type="cue", role="memory"), Unsupported))
check("a colour must be one of rekordbox's swatches",
_raises(lambda: a.set_cue_color(TRACK_1, 5, "#123456"), InvalidCommand))
a.place_cues(TRACK_1, [CuePoint(slot=1, start=30.0, length=0.0, type="cue"),
CuePoint(slot=6, start=31.0, length=0.0, type="cue")])
starts = {c.slot: round(c.start, 2) for c in a.track_cues(TRACK_1).cues if c.role == "hotcue"}
check("place_cues fills empty pads and leaves occupied ones", starts.get(6) == 31.0 and starts.get(1) != 30.0)
markers = a.track_cues(TRACK_1).grid_markers
# A per-beat grid has no markers: one at the governing tempo, on its beats, is
# indistinguishable from none and collapses on read (as on the Rekordbox side).
a.add_grid_marker(TRACK_1, markers[-1].start + 10 * 60 / markers[-1].bpm)
check("a marker at the governing tempo collapses into it",
len(a.track_cues(TRACK_1).grid_markers) == len(markers))
a.add_grid_marker(TRACK_1, 100.0, 100.0)
check("a marker with a new tempo is a new segment",
[m.bpm for m in a.track_cues(TRACK_1).grid_markers] == [128.0, 90.0, 100.0])
a.move_grid_marker(TRACK_1, 1, 200.0)
moved = a.track_cues(TRACK_1).grid_markers
check("a moved marker is clamped before its neighbour", moved[1].start < moved[2].start)
a.delete_grid_marker(TRACK_1, 2)
check("and deleted", len(a.track_cues(TRACK_1).grid_markers) == len(markers))
a.save()
after = {p: tags_by_key(p) for p in (dat, ext)}
before = {p: tags_by_key(b) for p, b in original.items()}
changed = {p.suffix: sorted(f"{k[0]}/{k[1]}" for k in before[p] if before[p][k] != after[p].get(k))
for p in original}
check("the .DAT: only the pad 1-3 list and the grid changed",
changed[".DAT"] == ["PCOB/1", "PQTZ/None"], str(changed[".DAT"]))
check("the .EXT: only its cue lists changed (memory: the loop beats a grid edit clears)",
set(changed[".EXT"]) <= {"PCOB/1", "PCO2/1", "PCO2/0"}, str(changed[".EXT"]))
check("tag order is kept in both files",
all([t.type for t in A.parse(original[p]).tags] == [t.type for t in A.parse_file(p).tags]
for p in original))
check("the .DAT's memory list (no beat field there) is byte-identical",
tag(dat, "PCOB", A.LIST_MEMORY) == before[dat][("PCOB", A.LIST_MEMORY)])
backups = sorted((APPDATA / "onelibrary" / "backups" / "Dingus").iterdir())
check("both analysis files were backed up first",
all((backups[-1] / p.relative_to(drive)).read_bytes() == b for p, b in original.items()))
a.close()
b = OneLibraryAdapter(drive)
check("everything reads back after a reopen",
{c.slot: round(c.start, 2) for c in b.track_cues(TRACK_1).cues if c.role == "hotcue"} == starts
and next(c for c in b.track_cues(TRACK_1).cues if c.slot == 5).name == "Drop")
b.close()
print("== another app wrote an analysis file since Konduktor read it ==")
drive = copy_of(DEMO, "Dingus")
a = OneLibraryAdapter(drive)
a.set_cue(TRACK_1, slot=6, start_sec=5.0, cue_type="cue")
time.sleep(0.01)
os.utime(dat_of(a, TRACK_1).with_suffix(".EXT"))
check("Save refuses rather than undo it", _raises(a.save, InvalidCommand) and a.dirty)
a.close()
print("== an .EXT with no PCO2 keeps every pad on the first edit ==")
drive = copy_of(DEMO, "Dingus")
probe = OneLibraryAdapter(drive)
ext = dat_of(probe, TRACK_1).with_suffix(".EXT")
want = sorted(c.slot for c in probe.track_cues(TRACK_1).cues if c.role == "hotcue")
memory = sum(c.role == "memory" for c in probe.track_cues(TRACK_1).cues)
probe.close()
f = A.parse_file(ext)
f.tags = [t for t in f.tags if t.type != "PCO2"]
ext.write_bytes(f.to_bytes())
a = OneLibraryAdapter(drive)
check("read from PCOB alone, the pads are all there", sorted(
c.slot for c in a.track_cues(TRACK_1).cues if c.role == "hotcue") == want)
a.set_cue(TRACK_1, slot=6, start_sec=5.0, cue_type="cue")
got = a.track_cues(TRACK_1).cues
check("after the edit creates PCO2, every old pad AND the new one read",
sorted(c.slot for c in got if c.role == "hotcue") == sorted(want + [6]), str([c.slot for c in got]))
check("and the memory cue survives", sum(c.role == "memory" for c in got) == memory)
a.close()
print("== a track without analysis files ==")
drive = copy_of(DEMO, "Dingus")
probe = OneLibraryAdapter(drive)
dat = dat_of(probe, TRACK_1)
probe.close()
for p in (dat, dat.with_suffix(".EXT")):
p.unlink()
a = OneLibraryAdapter(drive)
check("refuses a cue edit (it has nowhere to store one)",
_raises(lambda: a.set_cue(TRACK_1, slot=0, start_sec=1.0, cue_type="cue"), InvalidCommand))
check("and a grid edit", _raises(lambda: a.replace_grid(TRACK_1, [GridMarker(start=0, bpm=120)]),
InvalidCommand))
a.close()
print("== the entry helpers ==")
e = W.pcp2_entry(hot_cue=2, kind=1, time_ms=5, loop_ms=None, rgb=(1, 2, 3), beats=None, code=9,
comment="A name longer than forty bytes in UTF-16")
d = A.decode_entry(e)
check("a long name grows the entry past 88 bytes and round-trips",
len(e) > 88 and d.comment == "A name longer than forty bytes in UTF-16" and d.color_code == 9)
check("a 44-byte compact entry has no colour bytes to patch",
A.entry_with_colour(A.raw_entries(A.Tag("PCO2", tag(HERE / "fixtures" / "onelibrary" / "rekordbox-edited"
/ "nemean.EXT", "PCO2", A.LIST_MEMORY)))[-1],
9, (1, 2, 3)) is None)
print()
print("RESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+354
View File
@@ -0,0 +1,354 @@
"""OneLibrary's analogue of `test_rekordbox_fidelity.py`: an edit changes only
what it was supposed to change, checked as a FULL TABLE DUMP before and after
(a byte diff means nothing against SQLite), on a temp copy of the fixture drive.
The expected diffs are rekordbox's own, MEASURED on Goober (2026-10-01; see the
editing discussion log): a title edit changes `content.title` and nothing else —
no update counter moves — a new playlist goes on top with its siblings shifted
down one, and a reorder renumbers that playlist's entries from 1.
And the properties a STICK needs that a desktop library does not: nothing
reaches the drive before Save, the drive is replaced in one rename, another
app's write since open is refused rather than undone, an unplugged drive keeps
the edits for a retry, stale `-wal`/`-shm` files are deleted, and a backup of
the drive's database lands in app-data first.
"""
import os
import shutil
import sys
import tempfile
import time
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
APPDATA = Path(tempfile.mkdtemp(prefix="konduktor-olfid-appdata-"))
os.environ["KONDUKTOR_DATA_DIR"] = str(APPDATA)
from konduktor.adapters.onelibrary.adapter import OneLibraryAdapter # noqa: E402
from konduktor.core.adapter import InvalidCommand # noqa: E402
FIXTURE = Path(__file__).resolve().parent / "fixtures" / "onelibrary"
TRACK_1 = "/Contents/Loopmasters/UnknownAlbum/Demo Track 1.mp3"
TRACK_2 = "/Contents/Loopmasters/UnknownAlbum/Demo Track 2.mp3"
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
def _raises(fn, exc) -> bool:
try:
fn()
except exc:
return True
except Exception: # noqa: BLE001
return False
return False
# ---- the row-level dump/diff harness -------------------------------------
LINK_TABLES = {"playlist_content", "history_content", "myTag_content", "hotCueBankList_cue"}
def dump(db: Path) -> dict:
"""Every row of every table; keyed by primary key, or by the whole row for
the link tables, which have none."""
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.devicelib_plus.database import BLOB
from pyrekordbox.utils import deobfuscate
con = sqlcipher.connect(str(db))
con.execute(f"PRAGMA key='{deobfuscate(BLOB)}'")
cur = con.cursor()
names = [r[0] for r in cur.execute(
"SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").fetchall()]
out: dict[str, dict] = {}
for table in names:
cols = [r[1] for r in cur.execute(f'PRAGMA table_info("{table}")').fetchall()]
rows = {}
for r in cur.execute(f'SELECT * FROM "{table}"').fetchall():
d = dict(zip(cols, r))
key = "|".join(map(str, r)) if table in LINK_TABLES else str(r[0])
rows[key] = d
out[table] = rows
con.close()
return out
def diff(before: dict, after: dict) -> list:
changes = []
for table in sorted(set(before) | set(after)):
a, b = before.get(table, {}), after.get(table, {})
for pk in sorted(set(a) | set(b)):
if pk not in a:
changes.append((table, pk, "INSERT", b[pk]))
elif pk not in b:
changes.append((table, pk, "DELETE", a[pk]))
else:
fields = {k: (a[pk][k], b[pk].get(k)) for k in a[pk] if a[pk][k] != b[pk].get(k)}
if fields:
changes.append((table, pk, "UPDATE", fields))
return changes
def describe(changes) -> str:
return "; ".join(f"{t}/{pk} {kind}" for t, pk, kind, _ in changes) or "(none)"
def fresh_drive() -> Path:
root = Path(tempfile.mkdtemp(prefix="konduktor-olfid-")) / "Dingus"
shutil.copytree(FIXTURE, root, ignore=shutil.ignore_patterns("rekordbox-edited"))
return root
def db_of(root: Path) -> Path:
return root / "PIONEER" / "rekordbox" / "exportLibrary.db"
# ---- A: nothing reaches the drive until Save --------------------------------
print("== edits stay off the drive until Save ==")
drive = fresh_drive()
before_bytes = db_of(drive).read_bytes()
before = dump(db_of(drive))
a = OneLibraryAdapter(drive)
check("opening writes nothing", db_of(drive).read_bytes() == before_bytes)
check("and leaves no -wal/-shm on the drive",
not any(db_of(drive).with_name(db_of(drive).name + s).exists() for s in ("-wal", "-shm")))
a.set_track_metadata(TRACK_1, {"title": "Edited"})
check("an edit makes the library dirty", a.dirty is True)
check("and the projection shows it at once", a.track(TRACK_1).title == "Edited")
check("but the drive's database is byte-identical", db_of(drive).read_bytes() == before_bytes)
print("== Discard ==")
a.reload()
check("discarding drops the edit", a.track(TRACK_1).title.startswith("Demo Track 1"), a.track(TRACK_1).title)
check("and leaves nothing dirty", a.dirty is False)
check("and the drive untouched", db_of(drive).read_bytes() == before_bytes)
# ---- B: a no-op save ----------------------------------------------------------
print("== a no-op save ==")
a.save()
check("changes zero rows", diff(before, dump(db_of(drive))) == [], describe(diff(before, dump(db_of(drive)))))
a.close()
# ---- C: one field, one column ---------------------------------------------------
print("== a one-field edit changes exactly that column ==")
drive = fresh_drive()
before = dump(db_of(drive))
a = OneLibraryAdapter(drive)
a.set_track_metadata(TRACK_1, {"title": "Edited"})
outcome = a.save()
changes = diff(before, dump(db_of(drive)))
check("exactly one row changed", len(changes) == 1, describe(changes))
check("content.title, and no update counter (measured: rekordbox moves none)",
changes and changes[0][0] == "content" and set(changes[0][3]) == {"title"}
and changes[0][3]["title"][1] == "Edited", str(changes))
check("the save is not dirty afterwards", a.dirty is False)
check("and the adapter reads the saved drive", a.track(TRACK_1).title == "Edited")
check("the save reports a summary of the edit", bool(outcome.summary), outcome.summary)
check("no version-history snapshot (a drive is many files)", outcome.snapshot is None)
backups = sorted((APPDATA / "onelibrary" / "backups" / "Dingus").iterdir())
check("a backup was written to app-data, not the drive", len(backups) >= 1)
check("holding the database as it was BEFORE the save",
dump(backups[-1] / "exportLibrary.db") == before)
check("no partial file is left beside the database",
not list(db_of(drive).parent.glob("*.konduktor-partial")))
a.close()
print("== rating, comment, release date ==")
drive = fresh_drive()
before = dump(db_of(drive))
a = OneLibraryAdapter(drive)
a.set_track_metadata(TRACK_1, {"rating": 3})
a.set_track_metadata(TRACK_2, {"comment": "", "release_date": "2021-03-04"})
check("an out-of-range rating is refused", _raises(lambda: a.set_track_metadata(TRACK_1, {"rating": 6}),
InvalidCommand))
check("a malformed date is refused", _raises(lambda: a.set_track_metadata(TRACK_1, {"release_date": "soon"}),
InvalidCommand))
a.save()
changes = {(t, pk): f for t, pk, kind, f in diff(before, dump(db_of(drive)))}
row1 = next(f for (t, pk), f in changes.items() if t == "content" and pk == "1")
row2 = next(f for (t, pk), f in changes.items() if t == "content" and pk == "2")
check("rating is stored 0-5 directly", row1 == {"rating": (0, 3)}, str(row1))
check("a cleared comment is '' as rekordbox stores it, not NULL",
row2.get("djComment", (None, None))[1] == "", str(row2))
check("a full date sets releaseYear AND releaseDate as YYYY-MM-DD text",
row2.get("releaseYear", (0, 0))[1] == 2021 and row2.get("releaseDate", ("", ""))[1] == "2021-03-04",
str(row2))
check("and reads back", a.track(TRACK_2).release_date == "2021-03-04", str(a.track(TRACK_2).release_date))
check("nothing else changed", len(changes) == 2, str(list(changes)))
a.set_track_metadata(TRACK_2, {"release_date": "2019"})
check("a bare year is releaseYear with an empty releaseDate",
a._store.content(TRACK_2).releaseYear == 2019 and a.track(TRACK_2).release_date == "2019",
str(a.track(TRACK_2).release_date))
a.close()
print("== lookups are found or created ==")
drive = fresh_drive()
before = dump(db_of(drive))
a = OneLibraryAdapter(drive)
a.set_track_metadata(TRACK_1, {"artist": "Loopmasters"}) # already there
check("an existing name is reused, not duplicated", a.dirty and a._store.content(TRACK_1).artist_id_artist == 1)
a.set_track_metadata(TRACK_1, {"artist": "New Artist", "genre": "Techno"})
check("the projection reads the NEW names (not the stale relationship)",
a.track(TRACK_1).artist == "New Artist" and a.track(TRACK_1).genre == "Techno",
f"{a.track(TRACK_1).artist} / {a.track(TRACK_1).genre}")
a.set_track_metadata(TRACK_2, {"label": ""})
check("clearing a lookup unsets it", a.track(TRACK_2).label is None)
a.save()
changes = diff(before, dump(db_of(drive)))
inserts = [(t, f) for t, pk, kind, f in changes if kind == "INSERT"]
check("one new artist and one new genre row",
sorted(t for t, _ in inserts) == ["artist", "genre"], describe(changes))
check("with nameForSearch NULL, as rekordbox leaves it",
all(f.get("nameForSearch") is None for t, f in inserts if t == "artist"))
a.close()
# ---- D: playlists, as rekordbox writes them ---------------------------------------
print("== playlists ==")
drive = fresh_drive()
before = dump(db_of(drive))
a = OneLibraryAdapter(drive)
demos = a.playlist_tree()[0]
new_id = a.create_playlist("Probe")
tree = a.playlist_tree()
check("a new playlist is listed FIRST (rekordbox puts it on top)",
[n.name for n in tree] == ["Probe", "demos"], str([n.name for n in tree]))
a.set_playlist_entries(new_id, [TRACK_2])
a.set_playlist_entries(demos.id, [TRACK_2, TRACK_1])
check("a reorder reads back in the new order", a.playlist_entries(demos.id) == [TRACK_2, TRACK_1])
a.save()
changes = diff(before, dump(db_of(drive)))
pl = {pk: (kind, f) for t, pk, kind, f in changes if t == "playlist"}
check("the new playlist row has sequenceNo 0, attribute 0, parent 0",
pl.get(new_id, ("", {}))[0] == "INSERT"
and {k: pl[new_id][1][k] for k in ("sequenceNo", "attribute", "playlist_id_parent")}
== {"sequenceNo": 0, "attribute": 0, "playlist_id_parent": 0}, str(pl.get(new_id)))
check("and its sibling moved down one", pl.get(demos.id) == ("UPDATE", {"sequenceNo": (0, 1)})
or pl.get(demos.id, ("", {}))[1].get("sequenceNo", (None, None))[1]
== before["playlist"][demos.id]["sequenceNo"] + 1, str(pl.get(demos.id)))
entries = sorted((f["playlist_id"], f["content_id"], f["sequenceNo"])
for t, pk, kind, f in changes if t == "playlist_content" and kind == "INSERT")
check("entries are numbered from 1 (measured)",
entries == sorted([(int(new_id), 2, 1), (int(demos.id), 2, 1), (int(demos.id), 1, 2)]), str(entries))
check("no other table changed", {t for t, *_ in changes} == {"playlist", "playlist_content"},
describe(changes))
folder = a.create_folder("Gigs")
inner = a.create_playlist("Friday", folder)
a.set_playlist_entries(inner, [TRACK_1])
check("a playlist can only be created inside a FOLDER",
_raises(lambda: a.create_playlist("x", demos.id), InvalidCommand))
check("a nameless playlist is refused", _raises(lambda: a.create_playlist(" "), InvalidCommand))
a.rename_playlist(inner, "Saturday")
gigs = next(n for n in a.playlist_tree() if n.id == folder)
check("a folder nests its playlist", [c.name for c in gigs.children] == ["Saturday"])
a.save()
mid = dump(db_of(drive))
a.delete_playlist(folder)
a.save()
after = dump(db_of(drive))
changes = diff(mid, after)
check("deleting a folder deletes what is in it, entries included",
sorted((t, kind) for t, pk, kind, _ in changes if kind == "DELETE")
== [("playlist", "DELETE"), ("playlist", "DELETE"), ("playlist_content", "DELETE")],
describe(changes))
seqs = sorted(r["sequenceNo"] for r in after["playlist"].values() if r["playlist_id_parent"] == 0)
check("and closes the gap among its siblings", seqs == list(range(len(seqs))), str(seqs))
a.close()
# ---- E: a stick's hazards ------------------------------------------------------------
print("== another app wrote the drive since it was opened ==")
drive = fresh_drive()
a = OneLibraryAdapter(drive)
a.set_track_metadata(TRACK_1, {"title": "Mine"})
theirs = db_of(drive).read_bytes()
time.sleep(0.01)
os.utime(db_of(drive)) # e.g. rekordbox saving the stick meanwhile
check("Save refuses rather than undo it", _raises(a.save, InvalidCommand))
check("the drive is exactly as the other app left it", db_of(drive).read_bytes() == theirs)
check("and the edit is still pending", a.dirty and a.track(TRACK_1).title == "Mine")
a.close()
print("== an unplugged drive ==")
drive = fresh_drive()
a = OneLibraryAdapter(drive)
a.set_track_metadata(TRACK_1, {"title": "Kept"})
parked = drive.parent / "unplugged"
(drive / "PIONEER").rename(parked)
check("Save refuses cleanly", _raises(a.save, InvalidCommand))
check("keeping the edit", a.dirty and a.track(TRACK_1).title == "Kept")
parked.rename(drive / "PIONEER")
a.save()
check("and saves it once the drive is back",
dump(db_of(drive))["content"]["1"]["title"] == "Kept" and not a.dirty)
a.close()
print("== stale SQLite sidecars ==")
drive = fresh_drive()
shm = db_of(drive).with_name("exportLibrary.db-shm")
shm.write_bytes(b"\0" * 32768) # rekordbox leaves one on a stick it mounted
a = OneLibraryAdapter(drive)
a.set_track_metadata(TRACK_1, {"title": "x"})
a.save()
check("a stale -shm is deleted on save (SQLite would trust it)", not shm.exists())
check("and the saved database opens", dump(db_of(drive))["content"]["1"]["title"] == "x")
a.close()
print("== the drive is never held open ==")
drive = fresh_drive()
a = OneLibraryAdapter(drive)
try:
import subprocess
mine = subprocess.run(["lsof", "-Fn", "-p", str(os.getpid())], capture_output=True,
text=True).stdout
check("no file on the drive is open in this process",
str(db_of(drive)) not in mine, "exportLibrary.db is open")
except FileNotFoundError:
print(" (lsof unavailable — skipped)")
a.close()
print("== a read-only (browsing) drive ==")
drive = fresh_drive()
b = OneLibraryAdapter(drive, read_only=True)
check("is not writable", b.capabilities().writable is False)
b.close()
check("closing removes its working copy",
not any((APPDATA / "onelibrary" / "work").iterdir()))
print("== file tags (decision 5: as rekordbox does) ==")
drive = fresh_drive()
from stem_test_support import make_mp3 # noqa: E402
audio = drive / TRACK_1.lstrip("/")
make_mp3(audio) # the fixture's MP3s are 12-byte placeholders
a = OneLibraryAdapter(drive)
a.set_track_metadata(TRACK_1, {"title": "Tagged", "artist": "Somebody", "rating": 4})
outcome = a.save()
import mutagen # noqa: E402
tags = mutagen.File(str(audio)).tags
check("the edited title reaches the file's TIT2", str(tags.get("TIT2")) == "Tagged", str(tags.get("TIT2")))
check("and the artist its TPE1", str(tags.get("TPE1")) == "Somebody")
check("the rating does NOT (rekordbox keeps it library-only)", not tags.getall("POPM"))
check("the write is reported", any(r.ok and r.track_id == TRACK_1 for r in outcome.tag_results),
str(outcome.tag_results))
(drive / TRACK_2.lstrip("/")).unlink() # its audio gone from the stick
a.set_track_metadata(TRACK_2, {"title": "Missing"})
outcome = a.save()
check("a missing audio file is reported, not fatal",
[r.status for r in outcome.tag_results] == ["file-not-found"] and not a.dirty
and dump(db_of(drive))["content"]["2"]["title"] == "Missing", str(outcome.tag_results))
a.close()
print()
print("RESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+152
View File
@@ -0,0 +1,152 @@
"""The legacy Device Library (`export.pdb`) kept in step with a stick's OneLibrary.
On a temp copy of Goober (`fixtures/onelibrary-goober/`), whose three databases
are rekordbox's own bytes. Pins:
* reading: every rekordbox track row decodes, and re-encodes to the same
meaningful bytes (rekordbox leaves stale bytes in alignment padding and
between rows — `track_extent`);
* ids are mirrored: rekordbox exported both libraries from the same ids, so a
no-op rebuild changes NOTHING, and a no-op save leaves the file byte-identical;
* an edit reaches the pdb (title, rating, artist, a new playlist, a reorder —
the last two are what rekordbox's own edits failed to carry over), every table
the edit does not touch stays byte-identical, and `exportExt.pdb` is never
written;
* another app's write to `export.pdb` since open is refused, not undone.
Verified in rekordbox 7 on the real Goober (2026-10-01): both library views
matched after exactly these edits.
"""
import os
import shutil
import sys
import tempfile
import time
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-olpdb-appdata-")
from konduktor.adapters.onelibrary import device_library # noqa: E402
from konduktor.adapters.onelibrary.adapter import OneLibraryAdapter # noqa: E402
from konduktor.adapters.rekordbox import pdb # noqa: E402
from konduktor.core.adapter import InvalidCommand # noqa: E402
HERE = Path(__file__).resolve().parent
GOOBER = HERE / "fixtures" / "onelibrary-goober"
DEMO = HERE / "fixtures" / "onelibrary"
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
def copy_of(fixture: Path, name: str) -> Path:
root = Path(tempfile.mkdtemp(prefix="konduktor-olpdb-")) / name
shutil.copytree(fixture, root, ignore=shutil.ignore_patterns("after", "rekordbox-edited", "README.md"))
return root
PDB = GOOBER / "PIONEER" / "rekordbox" / "export.pdb"
raw = PDB.read_bytes()
print("== reading rekordbox's rows ==")
tracks = pdb.table_rows(raw, pdb.TRACKS)
check("every track row is found (as many as the reader sees)", len(tracks) == len(pdb.read(raw).tracks) == 11)
same = [pdb.track_row(*pdb.track_fields(r)) for r in tracks]
check("each re-encodes to the same bytes up to its 4-byte alignment padding",
all(a[:len(a) - 3] == b[:len(a) - 3] and len(a) == len(b) for a, b in zip(tracks, same)))
check("a row ends at its last string, not at the next row (stale heap tails)",
all(pdb.track_extent(r) == len(r) for r in tracks))
check("artists, keys, artwork and the playlist tree all read",
[len(pdb.table_rows(raw, t)) for t in (pdb.ARTISTS, pdb.KEYS, pdb.ARTWORK, pdb.PLAYLIST_TREE)]
== [5, 4, 3, 2])
print("== ids are mirrored: nothing to do on an unedited stick ==")
drive = copy_of(GOOBER, "Goober")
a = OneLibraryAdapter(drive)
rebuilt = device_library.rebuild(raw, a._store._require_db().session)
check("a rebuild of an unedited stick changes nothing", rebuilt is None)
a.set_track_metadata(a.tracks[0].id, {"title": a.tracks[0].title}) # dirty, but a no-op
a.save()
check("a save that changes nothing in it leaves export.pdb byte-identical",
(drive / "PIONEER" / "rekordbox" / "export.pdb").read_bytes() == raw)
a.close()
print("== an edit reaches the Device Library, and only the edit ==")
drive = copy_of(GOOBER, "Goober")
P = drive / "PIONEER" / "rekordbox"
ext_before = (P / "exportExt.pdb").read_bytes()
a = OneLibraryAdapter(drive)
by = lambda prefix: next(t for t in a.tracks if t.title.startswith(prefix)) # noqa: E731
tian, bensley, alkyn = by("Tian"), by("Bensley"), by("Alkyn")
a.set_track_metadata(tian.id, {"title": tian.title + " X"})
a.set_track_metadata(bensley.id, {"rating": 3})
a.set_track_metadata(alkyn.id, {"artist": "Alkyn"})
demos = next(n for n in a.playlist_tree() if n.name == "demos")
order = a.playlist_entries(demos.id)
a.set_playlist_entries(demos.id, order[::-1])
probe = a.create_playlist("Probe")
a.set_playlist_entries(probe, [alkyn.id])
a.save()
after = (P / "export.pdb").read_bytes()
A, B = pdb.read(raw), pdb.read(after)
old = {t["id"]: t for t in A.tracks}
new = {t["id"]: t for t in B.tracks}
diffs = {i: {k for k in old[i] if old[i][k] != new[i][k] and k != "index_shift"} for i in old}
check("only the edited fields of the edited tracks changed",
{i: d for i, d in diffs.items() if d} == {6: {"title"}, 7: {"rating"}, 8: {"artist_id"}},
str({i: d for i, d in diffs.items() if d}))
check("the new artist is mirrored under OneLibrary's own id",
B.artists.get(new[8]["artist_id"]) == "Alkyn" and new[8]["artist_id"] == 6)
tree = sorted((p["name"], p["sort"]) for p in B.playlists)
check("the new playlist reached it, on top (rekordbox's own edit did not carry it over)",
tree == [("Para Ben", 1), ("Probe", 0), ("demos", 2)], str(tree))
demos_entries = [t for _i, t, p in sorted(B.entries) if p == int(demos.id)]
check("and so did the reorder", [new[t]["file_path"] for t in demos_entries] == order[::-1])
for table, name in ((pdb.COLORS, "colours"), (pdb.KEYS, "keys"), (pdb.ARTWORK, "artwork"),
(pdb.GENRES, "genres"), (pdb.LABELS, "labels"), (pdb.ALBUMS, "albums"),
(pdb.HISTORY, "history"), (16, "browse columns"), (17, "menus")):
check(f"untouched table ({name}) is byte-identical",
pdb.table_rows(raw, table) == pdb.table_rows(after, table))
check("an unchanged track row keeps rekordbox's own bytes (stale padding and all)",
[r for r in pdb.table_rows(after, pdb.TRACKS) if pdb.row_id(pdb.TRACKS, r) == 1]
== [r for r in tracks if pdb.row_id(pdb.TRACKS, r) == 1])
check("the file did not grow", len(after) == len(raw))
check("exportExt.pdb is never written", (P / "exportExt.pdb").read_bytes() == ext_before)
check("the previous export.pdb was backed up",
any(p.read_bytes() == raw for p in
(Path(os.environ["KONDUKTOR_DATA_DIR"]) / "onelibrary" / "backups").rglob("export.pdb")))
a.close()
print("== another app wrote export.pdb since open ==")
drive = copy_of(GOOBER, "Goober")
a = OneLibraryAdapter(drive)
a.set_track_metadata(a.tracks[0].id, {"rating": 5})
time.sleep(0.01)
os.utime(drive / "PIONEER" / "rekordbox" / "export.pdb")
try:
a.save()
refused = False
except InvalidCommand:
refused = True
check("Save refuses", refused and a.dirty)
a.close()
print("== a stick with no Device Library ==")
drive = copy_of(DEMO, "Dingus")
a = OneLibraryAdapter(drive)
a.set_track_metadata(a.tracks[0].id, {"rating": 2})
a.save()
check("saving does not create one", not (drive / "PIONEER" / "rekordbox" / "export.pdb").exists())
a.close()
print()
print("RESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+312
View File
@@ -0,0 +1,312 @@
"""Adding tracks to a OneLibrary stick and removing them (decisions 3, 6 and 7).
On temp copies of Goober (`fixtures/onelibrary-goober/`, with its Device Library)
and generated MP3s, through `importer.run` — the path every add route takes:
* placement: the LIBRARY decides — a file already on the stick is used in
place; anything else goes to `Contents/<Artist>/<Album>/` as rekordbox lays a
stick out (`UnknownArtist`/`UnknownAlbum`, names cut to 48 characters),
through `.konduktor-incoming/`;
* an added track arrives ready to prep: analysis files (grid, cues, memory
cues), artwork, a row shaped like rekordbox's, the track count, and its row
in the Device Library;
* nothing is left behind: a cancel mid-copy, a Discard, a crash (cleared on the
next EDITABLE open only);
* removal: every row naming the track goes (playlists renumbered), and its
audio, analysis files and unshared artwork are deleted AFTER the save that
stopped naming them — never before.
"""
import hashlib
import io
import os
import shutil
import sys
import tempfile
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-oltracks-appdata-")
from stem_test_support import make_mp3 # noqa: E402
from konduktor import importer # noqa: E402
from konduktor.adapters.onelibrary.adapter import OneLibraryAdapter # noqa: E402
from konduktor.adapters.rekordbox import pdb # noqa: E402
from konduktor.core.adapter import NewTrack # noqa: E402
from konduktor.core.model import CuePoint, GridMarker, Track, TrackCues # noqa: E402
from konduktor.jobs import Job, JobCancelled, JobHandle # noqa: E402
HERE = Path(__file__).resolve().parent
GOOBER = HERE / "fixtures" / "onelibrary-goober"
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
def copy_of(name: str = "Goober") -> Path:
root = Path(tempfile.mkdtemp(prefix="konduktor-oltracks-")) / name
shutil.copytree(GOOBER, root, ignore=shutil.ignore_patterns("after", "README.md"))
return root
def fingerprint(root: Path) -> str:
h = hashlib.sha1()
for p in sorted(root.rglob("*")):
if p.is_file():
h.update(str(p.relative_to(root)).encode() + p.read_bytes())
return h.hexdigest()
def rows(root: Path, sql: str):
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.devicelib_plus.database import BLOB
from pyrekordbox.utils import deobfuscate
con = sqlcipher.connect(str(root / "PIONEER" / "rekordbox" / "exportLibrary.db"))
con.execute(f"PRAGMA key='{deobfuscate(BLOB)}'")
con.row_factory = lambda cur, row: dict(zip([d[0] for d in cur.description], row))
try:
return con.execute(sql).fetchall()
finally:
con.close()
def jpeg() -> bytes:
from PIL import Image
buf = io.BytesIO()
Image.new("RGB", (300, 200), (200, 40, 90)).save(buf, "JPEG")
return buf.getvalue()
SRC = Path(tempfile.mkdtemp(prefix="konduktor-oltracks-src-"))
ONE = make_mp3(SRC / "Kick One.mp3", seconds=20)
TWO = make_mp3(SRC / "Kick Two.mp3", seconds=20, seed=5)
COVER = jpeg()
class Source:
"""Two tracks: one fully prepped (grid, hot cue, memory loop, cover), one bare."""
def __init__(self):
self.t = {
str(ONE): Track(id=str(ONE), title="Kick One", artist="Konduktor: Test", album="Probe EP",
bpm=120.0, length=20, rating=4, filepath=str(ONE)),
str(TWO): Track(id=str(TWO), title="Kick Two", length=20, filepath=str(TWO)),
}
@property
def tracks(self):
return list(self.t.values())
def track(self, i):
return self.t.get(i)
def track_cues(self, i):
if i != str(ONE):
return None
return TrackCues(grid_markers=[GridMarker(start=0.5, bpm=120.0)], cues=[
CuePoint(role="hotcue", slot=1, start=2.5, length=0.0, type="cue", color="#FF0045", name="In"),
CuePoint(role="hotcue", slot=1, start=4.5, length=0.0, type="cue"), # pad taken -> memory
CuePoint(role="memory", start=8.5, length=2.0, type="loop"),
])
def cover_art(self, i):
return (COVER, "image/jpeg") if i == str(ONE) else None
class CancelOnFirstBytes(JobHandle):
def progress(self, done=None, **kw):
super().progress(done=done, **kw)
if done:
self._job._cancel.set()
def run(adapter, handle_cls=JobHandle, track_ids=(str(ONE), str(TWO))):
plan = importer.plan(Source(), adapter, None, track_ids=list(track_ids))
return importer.run(Source(), adapter, plan, handle_cls(Job(id="t", kind="import")))
# ---- placement -----------------------------------------------------------------
print("== the library places the audio ==")
drive = copy_of()
a = OneLibraryAdapter(drive)
caps = a.capabilities()
check("an editable stick adds, removes, and places its own audio",
caps.tracks.addable and caps.tracks.removable and caps.tracks.places_audio)
check("a browsing one does neither", not OneLibraryAdapter(drive, read_only=True).capabilities().tracks.addable)
on_stick = drive / "Contents" / "Here.mp3"
on_stick.parent.mkdir(parents=True, exist_ok=True)
on_stick.write_bytes(b"x")
check("a file already on the stick is used where it is", a.place_audio(on_stick, Track(id="x")) is None)
target = a.place_audio(ONE, Track(id="x", artist="A/B: C", album="Album."))
final = a._store.final_of(target)
check("anything else is copied in through .konduktor-incoming/",
target.parent == drive / ".konduktor-incoming" and target.suffix == ".mp3")
check("to Contents/<Artist>/<Album>/, with characters FAT refuses replaced",
final == drive / "Contents" / "A_B_ C" / "Album" / "Kick One.mp3", str(final))
check("no artist or album: UnknownArtist / UnknownAlbum (rekordbox's names)",
a._store.final_of(a.place_audio(TWO, Track(id="y"))).parent
== drive / "Contents" / "UnknownArtist" / "UnknownAlbum")
long = SRC / ("L" * 60 + ".mp3")
long.write_bytes(b"x")
check("a long file name is cut to 48 characters, as rekordbox does",
len(a._store.final_of(a.place_audio(long, Track(id="z"))).name) == 48)
taken = drive / "Contents" / "UnknownArtist" / "UnknownAlbum" / "Kick Two.mp3"
taken.parent.mkdir(parents=True, exist_ok=True)
taken.write_bytes(b"x")
check("a name already taken on the stick gets a suffix",
a._store.final_of(a.place_audio(TWO, Track(id="y"))).name == "Kick Two-2.mp3")
a.close()
# ---- adding ----------------------------------------------------------------------
print("== an import into the stick ==")
drive = copy_of()
a = OneLibraryAdapter(drive)
before_n = rows(drive, "SELECT numberOfContents AS n FROM property")[0]["n"]
result = run(a)
one_id, two_id = result["track_ids"]
check("both tracks are added", result["tracks"] == 2)
check("the import saved, so the copies are in place and the incoming folder is gone",
(drive / one_id.lstrip("/")).is_file() and (drive / two_id.lstrip("/")).is_file()
and not (drive / ".konduktor-incoming").exists())
check("laid out as rekordbox does",
one_id == "/Contents/Konduktor_ Test/Probe EP/Kick One.mp3"
and two_id == "/Contents/UnknownArtist/UnknownAlbum/Kick Two.mp3", f"{one_id} {two_id}")
check("the projection plays them from there", a.track(one_id).filepath == str(drive / one_id.lstrip("/")))
cues = a.track_cues(one_id)
hot = [c for c in cues.cues if c.role == "hotcue"]
memory = sorted((c for c in cues.cues if c.role == "memory"), key=lambda c: c.start)
check("a hot cue keeps its pad, colour and name",
[(c.slot, round(c.start, 2), c.color, c.name) for c in hot] == [(1, 2.5, "#FF0045", "In")], str(hot))
check("a memory loop, and a hot cue whose pad was taken, cross as memory cues",
[(round(c.start, 2), c.type) for c in memory] == [(4.5, "cue"), (8.5, "loop")], str(memory))
check("its grid crosses", [(round(m.start, 3), m.bpm) for m in cues.grid_markers] == [(0.5, 120.0)],
str(cues.grid_markers))
check("a file with no grid gets Konduktor's", len(a.track_cues(two_id).grid_markers) == 1)
dat = drive / rows(drive, f"SELECT analysisDataFilePath AS p FROM content WHERE path = '{one_id}'")[0]["p"].lstrip("/")
check("its .DAT, .EXT and .2EX are on the stick",
all(dat.with_suffix(s).is_file() for s in (".DAT", ".EXT", ".2EX")))
row = rows(drive, f"SELECT * FROM content WHERE path = '{one_id}'")[0]
check("the row is shaped like rekordbox's own (search NULL, no counters, '' texts)",
row["titleForSearch"] is None and row["cueUpdateCount"] is None and row["hasModified"] == 0
and row["subtitle"] == "" and row["isrc"] == "" and row["contentLink"] == 788224
and row["analysedBits"] == 41, str(row))
check("with the file's facts", row["fileName"] == "Kick One.mp3" and row["fileType"] == 1
and row["samplingRate"] == 44100 and row["bpmx100"] == 12000 and row["rating"] == 4)
check("dates as YYYY-MM-DD text", len(row["dateAdded"]) == 10 and len(row["dateCreated"] or "") == 10)
check("the track count follows",
rows(drive, "SELECT numberOfContents AS n FROM property")[0]["n"] == before_n + 2)
image = rows(drive, f"SELECT path FROM image WHERE image_id = {row['image_id']}")[0]["path"]
art = drive / "PIONEER" / "Artwork" / "00001"
n = row["image_id"]
check("the cover is written as rekordbox writes it: a/b pairs, 80 and 240 px",
image == f"/PIONEER/Artwork/00001/b{n}.jpg"
and all((art / f"{x}{n}{s}.jpg").is_file() for x in "ab" for s in ("", "_m")))
check("and served as the track's art", a.cover_art(one_id)[1] == "image/jpeg")
lib = pdb.read((drive / "PIONEER" / "rekordbox" / "export.pdb").read_bytes())
new = {t["file_path"]: t for t in lib.tracks}
check("the Device Library lists both, with OneLibrary's ids",
new.get(one_id, {}).get("id") == row["content_id"] and two_id in new)
check("their analysis paths and artwork (the a<n> file) reach it too",
new[one_id]["analyze_path"] == row["analysisDataFilePath"]
and lib.artwork.get(new[one_id]["artwork_id"]) == f"/PIONEER/Artwork/00001/a{n}.jpg")
a.close()
print("== nothing is left behind ==")
drive = copy_of()
before = fingerprint(drive)
a = OneLibraryAdapter(drive)
try:
run(a, CancelOnFirstBytes)
cancelled = False
except JobCancelled:
cancelled = True
check("a cancel mid-copy leaves the stick exactly as it was",
cancelled and fingerprint(drive) == before and not a.dirty)
target = a.place_audio(ONE, Track(id="x", title="Kick"))
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(ONE, target)
[pending] = a.add_tracks([NewTrack(track=Track(id="x", title="Kick"), audio_path=target)])
check("an unsaved add plays from its incoming copy", a.track(pending).filepath == str(target))
a.reload()
check("Discard deletes the copy and leaves the stick as it was",
not target.exists() and fingerprint(drive) == before and a.track(pending) is None)
a.close()
(drive / ".konduktor-incoming").mkdir()
(drive / ".konduktor-incoming" / "crashed.mp3").write_bytes(b"x")
OneLibraryAdapter(drive, read_only=True).close()
check("a crash's leftovers survive a BROWSING open", (drive / ".konduktor-incoming").exists())
OneLibraryAdapter(drive).close()
check("and are cleared by the next editable one", not (drive / ".konduktor-incoming").exists())
# ---- removing ----------------------------------------------------------------------
print("== removing tracks ==")
drive = copy_of()
a = OneLibraryAdapter(drive)
by = lambda prefix: next(t for t in a.tracks if t.title.startswith(prefix)) # noqa: E731
victim = by("Demo Track 1")
audio = drive / victim.id.lstrip("/")
audio.parent.mkdir(parents=True, exist_ok=True)
audio.write_bytes(b"audio") # the fixture carries no audio
dat = a._store.layout.resolve(a._store.content(victim.id).analysisDataFilePath)
tian = by("Tian") # holds image 3, shared with nobody
n = a._store.content(tian.id).image_id
art = drive / "PIONEER" / "Artwork" / "00001"
art.mkdir(parents=True, exist_ok=True)
for x in "ab":
for s in ("", "_m"):
(art / f"{x}{n}{s}.jpg").write_bytes(b"jpg")
demos = next(p for p in a.playlist_tree() if p.name == "demos")
count = rows(drive, "SELECT numberOfContents AS n FROM property")[0]["n"]
check("removing two tracks reports two", a.remove_tracks([victim.id, tian.id]) == 2)
check("they leave the library and its playlists at once",
a.track(victim.id) is None and victim.id not in (a.playlist_entries(demos.id) or []))
check("but nothing is deleted before Save", audio.exists() and dat.exists() and (art / f"b{n}.jpg").exists())
a.save()
check("Save deletes the audio, the analysis files and the unshared artwork",
not audio.exists() and not dat.exists() and not dat.with_suffix(".EXT").exists()
and not any((art / f"{x}{n}{s}.jpg").exists() for x in "ab" for s in ("", "_m")))
check("and prunes the folders that left empty", not dat.parent.exists())
check("the drive's top-level folders stay", (drive / "Contents").is_dir() and (drive / "PIONEER" / "USBANLZ").is_dir())
seqs = [r["sequenceNo"] for r in rows(drive, f"SELECT sequenceNo FROM playlist_content "
f"WHERE playlist_id = {demos.id} ORDER BY sequenceNo")]
check("the playlist is renumbered from 1", seqs == list(range(1, len(seqs) + 1)), str(seqs))
check("no row anywhere names them",
not rows(drive, f"SELECT 1 FROM content WHERE path IN ('{victim.id}', '{tian.id}')")
and not rows(drive, f"SELECT 1 FROM image WHERE image_id = {n}"))
check("the track count follows", rows(drive, "SELECT numberOfContents AS n FROM property")[0]["n"] == count - 2)
lib = pdb.read((drive / "PIONEER" / "rekordbox" / "export.pdb").read_bytes())
check("and the Device Library drops them, their entries and the artwork row",
not {victim.id, tian.id} & {t["file_path"] for t in lib.tracks}
and all(t != 1 for _i, t, _p in lib.entries) and n not in lib.artwork)
a.close()
print("== removing a track added this session, before Save ==")
drive = copy_of()
before = fingerprint(drive)
a = OneLibraryAdapter(drive)
target = a.place_audio(ONE, Track(id="x", title="Kick"))
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(ONE, target)
[pending] = a.add_tracks([NewTrack(track=Track(id="x", title="Kick"), audio_path=target)])
a.remove_tracks([pending])
check("its copy is deleted at once", not target.exists())
a.save()
check("and the save leaves no trace of it",
not rows(drive, f"SELECT 1 FROM content WHERE path = '{pending}'")
and not (drive / pending.lstrip("/")).exists())
a.close()
print()
print("RESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+2 -2
View File
@@ -93,8 +93,8 @@ check("and decodes back", beats_in_loop(262145) == 4 and beats_in_loop(None) is
print("== hot cue colour palette ==")
# rekordbox has 16; the teal-green between 0x0E and 0x16 was never measured, and
# is left out rather than offered with a guessed RGB.
check("15 pickable swatches, without the observed-only red",
len(palette.SWATCHES) == 15 and 0x2B not in palette.SWATCHES)
check("16 pickable swatches, without the observed-only red",
len(palette.SWATCHES) == 16 and 0x2B not in palette.SWATCHES)
check("a code projects as its measured RGB", palette.hex_for(0x16) == "#1AFF00")
check("uncoloured (None, or a loop's 0) projects as no colour",
palette.hex_for(None) is None and palette.hex_for(0) is None)
+18 -7
View File
@@ -2,7 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import type { ColumnSizingState, SortingState, VisibilityState } from '@tanstack/react-table'
import { CapabilitiesContext, slotLabeller } from './lib/capabilities'
import { writeHint } from './lib/platformCopy'
import { removalNote, writeHint } from './lib/platformCopy'
import { invalidateTrackLists } from './lib/trackQueries'
import { api, type CueBatchResult, type GridBatchResult, type AutoCueSlot, type PlaylistNode, type StemBatchResult, type Track, type TrackOrigin } from './api'
import { confirmDiscardUnsaved } from './lib/unsaved'
@@ -578,6 +578,21 @@ export default function App() {
qc.invalidateQueries() // refetch everything for the newly-opened collection
}
// "Open for editing…" on a device: the drive becomes THE library — one library,
// one dirty state, one SaveBar (decided 2026-10-01). Unsaved edits to the
// current library are confirmed first, as switching library always is, and the
// browsing copy is closed so the drive is not open twice.
const openForEditing = async (path: string) => {
if (!(await confirmDiscardUnsaved())) return
try {
await api.closeSource()
await api.openCollection(path)
handleOpened()
} catch (e) {
onError((e as Error).message)
}
}
// ---- Convert to Stems ------------------------------------------------------
const canStems = canEdit && !viewForeign && !!capabilities.data?.tracks.stem_convertible
const finishStemBatch = (state: string, r: StemBatchResult | null, error: string | null) => {
@@ -841,12 +856,7 @@ export default function App() {
<p>
Remove {trackNoun(ids)} from the collection and from every playlist?
</p>
<p className="text-faint">
The audio {ids.length === 1 ? 'file stays' : 'files stay'} on disk. Nothing is written until you
save{capabilities.data?.save.history
? ', and a save can be rolled back from version history.'
: ', and that save cannot be undone.'}
</p>
{capabilities.data && <p className="text-faint">{removalNote(capabilities.data, ids.length)}</p>}
</>
),
confirmLabel: `Remove ${nTracks(ids.length)}`,
@@ -1161,6 +1171,7 @@ export default function App() {
onOpenHistory={() => setShowHistory(true)}
onImport={() => setImporting(true)}
onSwitchLibrary={() => setForcePicker(true)}
onOpenLibrary={(path) => void openForEditing(path)}
onDone={(msg) => notify('success', msg)}
onOpenPathMapping={() => setShowPaths(true)}
onDiscarded={() => afterBulk(prepTrack ? [prepTrack.id] : [], true)}
+10 -1
View File
@@ -222,10 +222,12 @@ export interface SaveCapabilities {
library_label: string
overwrite_risk: 'none' | 'on_exit' | 'while_running'
history: boolean
/** Written by a Konduktor export set, whose next run replaces it. */
managed_by_export: boolean
}
/** Why a library cannot be edited. A fact — lib/platformCopy.ts words it. */
export type ReadonlyCause = 'platform_incomplete' | 'cloud_synced' | 'not_in_library'
export type ReadonlyCause = 'platform_incomplete' | 'cloud_synced' | 'not_in_library' | 'browsing'
export interface Capabilities {
platform: Platform
@@ -249,6 +251,8 @@ export interface Capabilities {
removable: boolean
/** Tracks can be added to the library (import, add browsed files). */
addable: boolean
/** The library decides where added audio goes — no copy/in-place question. */
places_audio: boolean
/** Tracks can be converted to native-instruments STEM files. */
stem_convertible: boolean
/** Lower-case suffixes this library can hold — what a browsed folder lists. */
@@ -361,6 +365,11 @@ export interface ImportPreview {
destination: string | null
free_bytes: number | null
enough_space: boolean | null
/** Set when the library places its own audio (`tracks.places_audio`): how
* many files will be copied onto it, and how many are already there. */
places_audio?: boolean
copied?: number
in_place?: number
}
// ---- drives and folders ----
+34 -13
View File
@@ -2,12 +2,18 @@ import { createPortal } from 'react-dom'
import { useEffect, useRef, useState, type ReactNode } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { api, type FolderAddPreview, type FolderAddRequest, type JobStatus } from '../api'
import { useCaps } from '../lib/capabilities'
import { placedAudioSummary } from '../lib/platformCopy'
import { FolderPicker } from './FolderPicker'
/**
* Add browsed files to the collection — and, optionally, to a playlist or export.
*
* Copy vs. leave-in-place is ASKED every time, with nothing preselected: the
* A library that places its own audio (`tracks.places_audio`, a OneLibrary
* stick) is the exception: only files already on it can stay in place, so the
* dialog STATES what will happen instead of asking (decided 2026-10-01).
*
* Otherwise copy vs. leave-in-place is ASKED every time, with nothing preselected: the
* right answer depends on the drive (a stick is about to be unplugged) and on
* how the DJ keeps their music, and a remembered default would quietly apply
* last week's answer to a different drive.
@@ -42,6 +48,11 @@ interface Props {
export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: Props) {
const qc = useQueryClient()
// The LIBRARY's capabilities (this dialog is mounted outside the browsed
// view's swapped context). A library that places its own audio — a stick —
// decides copy vs in place itself, so there is nothing to ask.
const caps = useCaps()
const places = caps.tracks.places_audio
const [mode, setMode] = useState<'copy' | 'reference' | null>(null)
const [folder, setFolder] = useState('')
const [browsing, setBrowsing] = useState(false)
@@ -62,16 +73,16 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
track_ids: trackIds,
// The preview needs A mode to size anything; "reference" costs nothing to
// ask about and is replaced as soon as the user picks.
mode: mode ?? 'reference',
destination: mode === 'copy' ? folder : null,
mode: places ? 'copy' : (mode ?? 'reference'),
destination: !places && mode === 'copy' ? folder : null,
playlist_id: target?.kind === 'playlist' ? target.id : null,
export_id: target?.kind === 'export' ? target.id : null,
}
const preview = useQuery<FolderAddPreview>({
queryKey: ['folder-add-preview', trackIds, mode, folder, target?.id],
queryKey: ['folder-add-preview', trackIds, places ? 'placed' : mode, folder, target?.id],
queryFn: () => api.folderAddPreview(body),
enabled: !job && (mode !== 'copy' || !!folder),
enabled: !job && (places || mode !== 'copy' || !!folder),
staleTime: 0,
gcTime: 0,
})
@@ -146,13 +157,15 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
const pct = job && job.total > 0 ? Math.min(100, (job.done / job.total) * 100) : null
const n = trackIds.length
const newCount = p?.importable ?? 0
const shown = places ? 'placed' : mode
const libraryName = places ? caps.save.app_name : 'your collection'
const canAdd =
!starting && mode !== null && !!p && (newCount > 0 || (!!target && p.existing.length > 0)) &&
!starting && shown !== null && !!p && (newCount > 0 || (!!target && p.existing.length > 0)) &&
p.enough_space !== false
const title = target
? `Add ${n} track${n === 1 ? '' : 's'} to ${target.name}`
: `Add ${n} track${n === 1 ? '' : 's'} to your collection`
: `Add ${n} track${n === 1 ? '' : 's'} to ${libraryName}`
const option = (value: 'copy' | 'reference', label: string, detail: ReactNode) => (
<label
@@ -205,6 +218,13 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
</div>
)}
{places && p && (
<div className="rounded well px-3 py-2 text-xs text-muted">
{placedAudioSummary(caps.save, p.copied ?? 0, p.in_place ?? 0)}
</div>
)}
{!places && (
<div className="space-y-1">
{option(
'copy',
@@ -232,6 +252,7 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
'Your collection points at these files. Nothing is copied.',
)}
</div>
)}
{mode === 'reference' && p?.removable && (
<div className="rounded well px-3 py-2 text-xs text-gold">
@@ -244,15 +265,15 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
<div className="text-pink">{(preview.error as Error).message}</div>
)}
{mode && p && (
{shown && p && (
<div className="space-y-2">
<div className="text-text">
{newCount} new to your collection
{mode === 'copy' && (
{newCount} new to {libraryName}
{shown !== 'reference' && p.total_bytes > 0 && (
<span className="text-muted"> · {gb(p.total_bytes)} to copy</span>
)}
</div>
{mode === 'copy' && p.free_bytes != null && (
{shown !== 'reference' && p.free_bytes != null && (
<div className={p.enough_space === false ? 'text-pink' : 'text-faint'}>
{gb(p.free_bytes)} free
{p.enough_space === false && ' — not enough space'}
@@ -261,7 +282,7 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
{p.existing.length > 0 && (
<div className="rounded well px-3 py-2 text-xs text-muted">
{p.existing.length} {p.existing.length === 1 ? 'is' : 'are'} already in
your collection and will not be added again
{' '}{libraryName} and will not be added again
{target ? ` — but will still go into ${target.name}` : ''}.
</div>
)}
@@ -271,7 +292,7 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
there and will be skipped.
</div>
)}
{mode === 'copy' && p.duplicates.length > 0 && (
{shown !== 'reference' && p.duplicates.length > 0 && (
<div className="rounded well px-3 py-2 text-xs text-gold">
{p.duplicates.length} of these look like tracks your collection already
has. The copies will be added as new entries.
+42 -1
View File
@@ -3,6 +3,7 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api, type Drive, type PlaylistNode } from '../api'
import type { Source } from './Sidebar'
import { Icon } from '../lib/icons'
import { ContextMenu, type MenuItem } from './ContextMenu'
/**
* Every drive, in the sidebar: plugged-in ones under Devices, and the computer's
@@ -17,6 +18,11 @@ import { Icon } from '../lib/icons'
*
* The list genuinely changes while the app is open, so unlike everything else in
* the sidebar this POLLS. Folder levels are fetched only when expanded.
*
* A device here is BROWSED, read-only, beside the loaded library. Editing one
* means opening it as THE library ("Open for editing…": the drive row's
* right-click menu, and a button while a device that can be edited is being
* browsed) — one library, one dirty state, one SaveBar (decided 2026-10-01).
*/
const POLL_MS = 4000
@@ -26,9 +32,11 @@ interface Props {
onSelect: (s: Source) => void
onError: (msg: string) => void
onImport: () => void
/** Open a drive's library as THE library, to edit it. */
onOpenLibrary: (path: string) => void
}
export function DevicesSection({ source, onSelect, onError, onImport }: Props) {
export function DevicesSection({ source, onSelect, onError, onImport, onOpenLibrary }: Props) {
const qc = useQueryClient()
// Which rows are expanded, by a key per row kind. Not persisted: a tree
// reopening deep inside a drive that is no longer plugged in helps nobody.
@@ -101,6 +109,16 @@ export function DevicesSection({ source, onSelect, onError, onImport }: Props) {
}, [folderGone])
const viewingDevice = source.kind === 'device' || source.kind === 'device-playlist'
const [menu, setMenu] = useState<{ x: number; y: number; items: MenuItem[] } | null>(null)
// Whether the browsed device could be edited if opened as the library: a
// FACT from its capabilities (`browsing`), never the platform's name.
const deviceCaps = useQuery({
queryKey: ['source-capabilities'],
queryFn: api.sourceCapabilities,
enabled: !!openPath,
staleTime: Infinity,
})
const editable = deviceCaps.data?.readonly_cause === 'browsing'
const driveRow = (d: Drive, depth: number) => {
const key = `drive:${d.path}`
@@ -125,6 +143,16 @@ export function DevicesSection({ source, onSelect, onError, onImport }: Props) {
expanded={expandedHere}
onToggle={() => setRow(key, !expandedHere)}
onClick={onClick}
onContextMenu={
d.library
? (e) => {
e.preventDefault()
const path = d.library!.path
setMenu({ x: e.clientX, y: e.clientY,
items: [{ label: 'Open for editing…', onClick: () => onOpenLibrary(path) }] })
}
: undefined
}
selected={isOpen && source.kind === 'device'}
trailing={
isOpen && open.data?.tracks != null ? (
@@ -211,6 +239,16 @@ export function DevicesSection({ source, onSelect, onError, onImport }: Props) {
Import to collection…
</button>
)}
{viewingDevice && openPath && editable && (
<button
onClick={() => onOpenLibrary(openPath)}
title="Open this drive as the library, so its tracks, playlists and cues can be edited"
className="mb-1 w-full rounded-full btn-glass px-2 py-1.5 text-sm text-muted hover:text-text"
>
Open for editing…
</button>
)}
{menu && <ContextMenu {...menu} onClose={() => setMenu(null)} />}
</div>
</div>
)
@@ -235,6 +273,7 @@ function TreeRow({
expanded,
onToggle,
onClick,
onContextMenu,
selected = false,
trailing,
}: {
@@ -245,11 +284,13 @@ function TreeRow({
expanded: boolean
onToggle: () => void
onClick: () => void
onContextMenu?: (e: React.MouseEvent) => void
selected?: boolean
trailing?: ReactNode
}) {
return (
<div
onContextMenu={onContextMenu}
style={{ paddingLeft: indent(depth) }}
className={`flex w-full items-center gap-1 rounded-md py-1 pr-2 text-sm transition-colors ${
selected ? 'is-selected text-text' : 'text-muted hover:bg-ink-800 hover:text-text'
+15 -2
View File
@@ -2,6 +2,8 @@ import { createPortal } from 'react-dom'
import { useEffect, useRef, useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { api, type ImportPreview, type JobStatus } from '../api'
import { useCaps } from '../lib/capabilities'
import { placedAudioSummary } from '../lib/platformCopy'
import { FolderPicker } from './FolderPicker'
/**
@@ -39,6 +41,10 @@ export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError
// different decisions: where your music lives, and how one import is filed
// inside it. Joining them for display would make the toggle look like it was
// editing the folder you picked.
// The LIBRARY's capabilities (mounted outside the browsed device's context).
// One that places its own audio — a stick — needs no destination.
const caps = useCaps()
const places = caps.tracks.places_audio
const [baseFolder, setBaseFolder] = useState('')
const [useSubfolder, setUseSubfolder] = useState(true)
const [browsing, setBrowsing] = useState(false)
@@ -166,6 +172,12 @@ export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError
<div className="space-y-4 px-5 py-4 text-sm">
{!job && (
<>
{places && p && (
<div className="rounded well px-3 py-2 text-xs text-muted">
{placedAudioSummary(caps.save, p.copied ?? 0, p.in_place ?? 0)}
</div>
)}
{!places && (
<div>
<span className="mb-1 block text-xs text-muted">Copy audio into</span>
<div className="flex items-center gap-2">
@@ -204,6 +216,7 @@ export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError
{destination}
</div>
</div>
)}
{preview.isLoading && <div className="text-faint">Checking…</div>}
{preview.isError && (
@@ -216,7 +229,7 @@ export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError
{p.importable} track{p.importable === 1 ? '' : 's'}
{p.playlists.length > 0 &&
` · ${p.playlists.length} playlist${p.playlists.length === 1 ? '' : 's'}`}
<span className="text-muted"> · {gb(p.total_bytes)} to copy</span>
{p.total_bytes > 0 && <span className="text-muted"> · {gb(p.total_bytes)} to copy</span>}
</div>
{p.free_bytes != null && (
@@ -240,7 +253,7 @@ export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError
entry, so a re-import legitimately duplicates. */}
{p.duplicates.length > 0 && (
<div className="rounded well px-3 py-2 text-xs text-gold">
{p.duplicates.length} of these look like tracks your collection already has.
{p.duplicates.length} of these look like tracks {places ? caps.save.app_name : 'your collection'} already has.
They will be added again as new entries.
</div>
)}
+8 -1
View File
@@ -2,7 +2,7 @@ import { useState, type ReactNode } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api } from '../api'
import { useCaps } from '../lib/capabilities'
import { overwriteWarning, readOnlyNotice, saveLabel } from '../lib/platformCopy'
import { exportManagedWarning, overwriteWarning, readOnlyNotice, saveLabel } from '../lib/platformCopy'
import { Icon } from '../lib/icons'
import { askConfirm } from '../lib/confirm'
@@ -55,6 +55,7 @@ export function SaveBar({ onError, trailing, onDiscarded }: Props) {
const caps = useCaps()
const warning = overwriteWarning(caps.save)
const exportWarning = exportManagedWarning(caps.save)
const dirty = state?.dirty ?? false
const pending = state?.pending_stems
const readOnly = readOnlyNotice(caps)
@@ -81,6 +82,12 @@ export function SaveBar({ onError, trailing, onDiscarded }: Props) {
<span>{warning}</span>
</div>
)}
{dirty && exportWarning && (
<div className="mb-2 flex gap-1.5 rounded-xl bg-gold/10 px-2.5 py-1.5 text-[11px] leading-snug text-gold">
<Icon name="warning" size={13} className="mt-px shrink-0" />
<span>{exportWarning}</span>
</div>
)}
{/* Decided: the consequence is shown where Save is pressed, not only in
the Stems panel — Save deletes what a Replace conversion parked. */}
{pending && pending.parked > 0 && (
+4
View File
@@ -47,6 +47,8 @@ interface Props {
onOpenHistory: () => void
onImport: () => void
onSwitchLibrary: () => void
/** Open a drive's library as THE library (Devices' "Open for editing…"). */
onOpenLibrary: (path: string) => void
onDone: (msg: string) => void
onOpenPathMapping: () => void
/** After unsaved edits were discarded (SaveBar). */
@@ -319,6 +321,7 @@ export function Sidebar({
onOpenHistory,
onImport,
onSwitchLibrary,
onOpenLibrary,
onDone,
onOpenPathMapping,
onDiscarded,
@@ -591,6 +594,7 @@ export function Sidebar({
onSelect={onSelect}
onError={onError}
onImport={onImport}
onOpenLibrary={onOpenLibrary}
/>
</div>
+35
View File
@@ -55,6 +55,8 @@ export function readOnlyNotice(caps: Capabilities): string | null {
return `This ${caps.save.app_name} library is synced with ${caps.save.app_name} Cloud, so Konduktor will not write to it — an edit it did not make could break syncing on your other devices.`
case 'not_in_library':
return 'This file is not in your collection yet — add it to edit its tags, cues or beatgrid.'
case 'browsing':
return `This ${caps.save.app_name} drive is open for browsing. Open it for editing to change it.`
case 'platform_incomplete':
default:
return `Konduktor can read ${caps.save.app_name} libraries but cannot save changes to them yet.`
@@ -92,3 +94,36 @@ export function platformAvailability(p: PlatformOption): string {
export function browsePrompt(p: PlatformOption): string {
return p.selects === 'directory' ? 'Find the drive to open.' : `Choose a ${p.library_label} to open.`
}
// ---- a library that places its own audio (a stick) ---------------------------
//
// `tracks.places_audio`: the library, not the user, decides where added audio
// goes (a OneLibrary stick can only point at files on itself), and a removed
// track's audio goes with it. These word the consequences from that fact.
/** Shown while there are unsaved changes, on a library an export set wrote. */
export function exportManagedWarning(save: SaveCapabilities): string | null {
return save.managed_by_export
? `${save.app_name} was written by a Konduktor export — its next run replaces edits made here.`
: null
}
/** What adding will do on a library that places its own audio. */
export function placedAudioSummary(save: SaveCapabilities, copied: number, inPlace: number): string {
const parts: string[] = []
if (copied) parts.push(`${copied} ${copied === 1 ? 'file is' : 'files are'} copied to ${save.app_name}, into Contents/<Artist>/<Album>/`)
if (inPlace) parts.push(`${inPlace} ${inPlace === 1 ? 'is' : 'are'} already on ${save.app_name} and ${inPlace === 1 ? 'stays' : 'stay'} where ${inPlace === 1 ? 'it is' : 'they are'}`)
return parts.length ? parts.join('; ') + '.' : `Nothing needs copying to ${save.app_name}.`
}
/** The removal confirm's note on what happens to the audio files. */
export function removalNote(caps: Capabilities, count: number): string {
const files = count === 1 ? 'Its audio and analysis files are' : 'Their audio and analysis files are'
if (caps.tracks.places_audio) {
return `${files} deleted from ${caps.save.app_name} when you save, and that save cannot be undone.`
}
const stay = count === 1 ? 'The audio file stays' : 'The audio files stay'
return `${stay} on disk. Nothing is written until you save${caps.save.history
? ', and a save can be rolled back from version history.'
: ', and that save cannot be undone.'}`
}