Compare commits

..
116 Commits
Author SHA1 Message Date
patben8 0fac84cb73 Fixed issue with release pipeline 2026-10-04 21:57:40 +02:00
patben8 71ee877784 Merge pull request #5 from MrPatben8/dev
Implemented Key Analysis & Remote Library Management
2026-10-04 18:35:08 +02:00
patben8 920146f2c0 Bumped version number 2026-10-04 18:33:33 +02:00
patben8 ba7b662b93 Fixed port assumption 2026-10-04 17:13:24 +02:00
patben8 e5fb0f0dbb Initial implementation of remote library system 2026-10-04 17:13:24 +02:00
patben8 e8a53eee07 Added analyze dialog 2026-10-04 17:00:33 +02:00
patben8 36a6df4d3b Build analyze backend 2026-10-04 16:33:37 +02:00
patben8 72a52d3291 Reworked analysis menu 2026-10-04 16:18:43 +02:00
patben8 c3571fd054 Implemented key setting into adapters 2026-10-04 16:06:36 +02:00
patben8 b5b3dd04c3 Implemented key analysis system 2026-10-04 15:26:34 +02:00
patben8 4e9472c14a Unified prefs writing 2026-10-03 10:31:32 +02:00
patben8 957525393b Merge pull request #4 from MrPatben8/dev
Implemented STEM generation & OneLibrary editing support
2026-10-01 17:18:05 +02:00
patben8 bdc62f2c1b Added OneLibrary testing fixtures 2026-10-01 17:00:13 +02:00
patben8 7960a5a68f Implemented OneLibrary track addition and removal 2026-10-01 16:43:37 +02:00
patben8 c5280a95f2 Implemented Device Library and OneLibrary sync 2026-10-01 16:00:33 +02:00
patben8 e73fa05e1f Implemented OneLibrary cue and grid edits 2026-10-01 15:48:44 +02:00
patben8 775e94168c Begun implementing OneLibrary editing 2026-10-01 15:07:43 +02:00
patben8 2784879872 Added a clear button for the search bar 2026-10-01 13:32:54 +02:00
patben8 702e5d86a6 Stem tracks are now correctly labeled in the song list 2026-10-01 13:25:13 +02:00
patben8 d7f8768d4c Implemented importing into Rekordbox 2026-10-01 13:12:10 +02:00
patben8 5c193e0ab7 Fixed Stem track importing. Added remove from collection for Rekordbox 2026-10-01 11:42:55 +02:00
patben8 badf12b991 Improved progress status section layout 2026-10-01 10:55:09 +02:00
patben8 ecc0e4c8df Implemented STEM playback 2026-10-01 10:55:09 +02:00
patben8 ae03a93f98 Implemented front end for stem conversion 2026-10-01 10:55:09 +02:00
patben8 c560876c02 Implemented stem conversion API 2026-10-01 10:55:09 +02:00
patben8 e805635383 More stem engine implementation
# Conflicts:
#	backend/konduktor/schemas.py
2026-10-01 10:55:09 +02:00
patben8 27471a82cd Implemented demucs engine 2026-10-01 10:54:27 +02:00
patben8 28b705173e Implemented Discard changes button 2026-10-01 10:54:27 +02:00
patben8 681add852a Implemented foundation of STEM support 2026-10-01 10:54:27 +02:00
patben8 376569ec75 Fixed track collision bug 2026-10-01 10:54:27 +02:00
patben8 b5b0fa91fe Refined Rekordbox timing fix 2026-10-01 10:54:27 +02:00
patben8 34b18893ef Refined traktor timing fix 2026-10-01 10:54:27 +02:00
patben8 2c02019bb2 Implemented traktor utility fixes 2026-10-01 10:54:27 +02:00
patben8 08c53e1150 Added support for coloring Rekordbox hotcues 2026-10-01 10:54:14 +02:00
patben8 9be2c029b2 Loop controls now adjust to active hotcue loop 2026-09-28 23:36:43 +02:00
patben8 a6f96d5943 Improved play buttons in list 2026-09-28 22:15:36 +02:00
patben8 bd35418a89 Track tags are now refreshed correctly when editing from within an export folder 2026-09-28 21:25:37 +02:00
patben8 86b26e3229 Fixed Rekordbox export preview waveform not matching playhead position 2026-09-28 21:15:11 +02:00
patben8 bb9f6e2bd3 Implemented efficient re-exporting 2026-09-28 20:44:14 +02:00
patben8 3a9dc90344 Added warning for Rekordbox Library exports 2026-09-28 18:21:31 +02:00
patben8 4b9716d47a Added support for legacy Rekordbox exports 2026-09-27 23:19:53 +02:00
patben8 0b909a84f4 Implemented feature parity between Rekordbox and OneLibrary exporters 2026-09-27 22:37:14 +02:00
patben8 157c2c0a04 Fixed issues with OneLibrary export 2026-09-27 20:06:09 +02:00
patben8 4878d82671 Fixed OneLibrary export missing data 2026-09-27 16:27:55 +02:00
patben8 c2f5191962 Exports can now be multiplatform 2026-09-27 14:35:27 +02:00
patben8 99d590a051 Implemented automatic path remapping 2026-09-27 13:39:17 +02:00
patben8 eccd352ae5 Added support for comment 2 2026-09-26 22:25:59 +02:00
patben8 90beeef226 Fixed hot cue scaling 2026-09-26 18:13:03 +02:00
patben8 84947bb0bb Fixed sidebar scaling 2026-09-26 17:55:23 +02:00
patben8 08884ca6bd Updated icon 2026-09-26 17:49:16 +02:00
patben8 9851c3c056 Updated version number 2026-09-26 17:11:45 +02:00
patben8 17b68c40bb Merge pull request #3 from MrPatben8/multiplatform
Multiplatform Support and Reskinning
2026-09-26 16:37:48 +02:00
patben8 cb76277016 Fixed arrow scrolling selection going out of frame 2026-09-26 15:57:18 +02:00
patben8 24b9dfe49f Jumping to a hot cue outside a loop now cancels the loop 2026-09-26 13:30:50 +02:00
patben8 513808a6d2 Grid can now be nudged by one beat 2026-09-26 12:46:27 +02:00
patben8 85f01f6723 Grid and BPM can now be fully manual 2026-09-26 12:46:11 +02:00
patben8 2e04bcb9f6 Fixed album art not loading for Rekordbox collections 2026-09-26 11:58:13 +02:00
patben8 bd425f8cd6 Added device file exploration and file importing 2026-09-25 23:30:24 +02:00
patben8 b9d43dd7ea Fixed crash caused by permanent path remapping 2026-09-25 22:41:08 +02:00
patben8 a3747e887b Fixed bug related to exporting with path remapping 2026-09-25 22:25:07 +02:00
patben8 8c875cb6cd Prevented browser navigation 2026-09-25 21:45:15 +02:00
patben8 ce06731dc8 Moved native confirmation dialogs to custom component 2026-09-25 17:19:44 +02:00
patben8 c6aaded26d Improved hotcue icons 2026-09-25 17:16:16 +02:00
patben8 c1f121ae1d Improved hotcue button contrast 2026-09-25 17:11:04 +02:00
patben8 f1087b60fa Improved TAP usability 2026-09-25 17:07:07 +02:00
patben8 394520c2cf Improved beat jump visuals 2026-09-25 17:00:01 +02:00
patben8 642977e9bc Improved manual loop visuals 2026-09-25 16:56:15 +02:00
patben8 9f299051fa Cue button is now reactive 2026-09-25 16:52:33 +02:00
patben8 738d04eada Fixed track column header style 2026-09-25 16:46:21 +02:00
patben8 22f59c5c1e Removed paragraph from edit tag dialog 2026-09-25 16:44:13 +02:00
patben8 805d360907 Added waveform range indicator 2026-09-25 16:22:12 +02:00
patben8 46d3978580 Reworked deck UI 2026-09-25 16:17:06 +02:00
patben8 0a9764ee89 Added platform icon to sidebar 2026-09-25 15:55:53 +02:00
patben8 f9497b391b Added platform icons and fixed context menu scrolling 2026-09-25 15:23:39 +02:00
patben8 be80e572e5 Fixed overlay windows rendering below other UI 2026-09-25 15:23:16 +02:00
patben8 2810f24563 Changed theme to liquid glass 2026-09-25 14:57:27 +02:00
patben8 950352f7ec Added shortcuts menu 2026-09-25 13:57:12 +02:00
patben8 b4dc8949de Added beat jump size adjust shortcut 2026-09-25 13:53:23 +02:00
patben8 0fd5d56a4e Enter key now loads track 2026-09-25 13:43:40 +02:00
patben8 88737f2b08 Added playlist folder management 2026-09-25 13:26:37 +02:00
patben8 efdd0f6203 Disabled text highlighting unless in an input field 2026-09-25 13:02:21 +02:00
patben8 d18db9566c Added batch auto hot cue and reworked remove context menu 2026-09-25 11:54:09 +02:00
patben8 76bf142fb4 Cleaned up column settings 2026-09-25 11:05:14 +02:00
patben8 73694fe532 Unified track list component and improved playlist reordering 2026-09-25 10:55:31 +02:00
patben8 532dc5d6ac Added context option to multi analyze 2026-09-25 10:46:31 +02:00
patben8 b71436fad6 Autohotcues are now ignored on beats with existing hot cues 2026-09-25 10:38:24 +02:00
patben8 5909c704f4 Added extensive add to in context menu 2026-09-25 10:32:01 +02:00
patben8 07e85cfdc9 Implemented better track multiselect 2026-09-25 10:27:00 +02:00
patben8 6c123e2597 Fixed auto hotcue overlap and analysis locked hotcue 2026-09-24 14:05:35 +02:00
patben8 46ce3db916 Improved auto hot cue system 2026-09-24 13:53:42 +02:00
patben8 6cc73267a6 Improved beat and grid detection 2026-09-23 17:25:37 +02:00
patben8 68e0b032b3 Implemented untested support for Rekordbox and OneLibrary exports 2026-09-23 16:19:50 +02:00
patben8 a5f995562f Finished Traktor exporting 2026-09-23 15:28:37 +02:00
patben8 4aeb5d65d3 Built core and traktor exporter 2026-09-23 15:14:04 +02:00
patben8 7160fa3978 Implemented export creation UI 2026-09-23 15:04:53 +02:00
patben8 805b95fe5e Begun adding export support 2026-09-23 14:46:58 +02:00
patben8 93ec2ef425 Improved file browser 2026-09-23 11:19:58 +02:00
patben8 8d11acd783 Improved library selection flow 2026-09-23 10:44:25 +02:00
patben8 a081a7a44d Import now allows user to select copy location 2026-09-23 09:43:31 +02:00
patben8 06137f5c99 Updated projection 2026-09-22 22:11:18 +02:00
patben8 36cfb96c05 Added OneLibrary USB loading 2026-09-22 21:27:33 +02:00
patben8 ed9dfc9d6b Implemented export status 2026-09-22 21:12:07 +02:00
patben8 ba3e7c251e Extended OneLibrary support 2026-09-22 17:38:23 +02:00
patben8 0b38d4826f Implemented OneLibrary adapter base 2026-09-22 16:43:12 +02:00
patben8 7b0d7e3a07 Finished Rekordbox adapter 2026-09-19 13:48:45 +02:00
patben8 00dd3fe766 Fixed Rekordbox hotcue issues 2026-09-19 12:40:05 +02:00
patben8 5aeb9956cd Added grid support to Rekordbox Adapter 2026-09-19 11:01:51 +02:00
patben8 30065a94fe Improved Rekordbox adapter 2026-09-19 09:57:26 +02:00
patben8 43e712afbd Extended Rekordbox support 2026-09-18 12:59:44 +02:00
patben8 010f67cd2d Added Rekordbox capabilities handling 2026-09-18 09:36:05 +02:00
patben8 4592e13228 Implemented Rekordbox core base 2026-09-18 09:12:59 +02:00
patben8 6e24f5ef1d Switched to more generic wording 2026-09-17 22:24:56 +02:00
patben8 c9e85bbdb5 Updated backend 2026-09-17 17:30:36 +02:00
patben8 08c9b8121d Refactored library system to support different libraries (adapters) 2026-09-17 17:15:41 +02:00
patben8 dd97f27ac7 Added support for flexible beatgrids 2026-09-17 15:14:07 +02:00
patben8 3f51444e2a Documented multiplatform changes 2026-09-17 15:13:53 +02:00
356 changed files with 57460 additions and 4112 deletions

No files matched your search

@@ -0,0 +1,635 @@
# Discussion: Multi-platform library support (Traktor / Rekordbox / Serato)
Date: 2026-09-17
Status: Concluded
## Context
Konduktor currently targets Traktor only (NML v20 via `traktor-nml-utils`), with a
save path whose central guarantee is byte-exact fidelity: a no-op save is
byte-identical, and only edited objects diff (`test_save_fidelity.py`).
Ben wants to extend to Rekordbox and Serato. Proposed shape:
1. A generic library data structure that supports **all** features of **all**
platforms ("full support is critical").
2. Load any platform's library into that structure.
3. Edit/prepare with Konduktor's existing features.
4. Save back to the **original** library format.
5. Ultimate goal: **convert** a library from one platform to another.
## Open Questions
- [ ] **Command vocabulary for grids** (now evidenced): `set_grid(bpm, anchor_sec)`
cannot express per-marker edits. Needs marker-level commands — add / move /
set-BPM / delete marker — plus marker selection in `GridControls`. Design these.
- [ ] Verification tests: write the per-platform "localized change" analogues —
Rekordbox row-level table-dump diff, Serato byte diff excluding the patched GEOB
frame + whole-file diff of crates.
- [ ] Rekordbox `rb_local_usn` / update-sequence + cloud-sync columns: writing rows
without maintaining these may corrupt RB's own sync state. Needs investigation.
## Decisions Made
### Write scope: full read/write for all three platforms
- **Decision**: Konduktor must edit and save back into each platform's own live
library — Traktor NML, Rekordbox (`master.db`), and Serato (binary crates +
in-file GEOB tags). Not read-only, not export-only.
- **Rationale**: The user's existing library on their chosen platform is the
canonical source; Konduktor is a management tool for it, so it must be able to
write back wherever the user actually works.
- **Alternatives considered**: Traktor-write-only with read+export for the others
(smaller, safer v1); Traktor+Serato write with Rekordbox read-only (avoids the
encrypted/unsupported RB DB); read-all/export-only (no in-place editing at all).
All rejected as too limited.
- **Consequence**: Rekordbox and Serato writes carry materially higher risk than
NML — both formats are reverse-engineered and neither has a fidelity guarantee
equivalent to the current byte-exact NML save. Per-platform backup + verification
strategy becomes a first-class requirement.
### End goal: canonical-library management + converted exports
- **Decision**: The user's main platform library remains the canonical source of
truth. Konduktor manages and edits it in place, and *additionally* can produce
converted exports for other platforms.
- **Rationale**: Keeps the user's existing workflow intact — they keep using their
DJ software normally — while making conversion a deliberate, separate output.
- **Alternatives considered**: one-shot migration only (too narrow); two-way sync
between libraries (rejected — requires cross-platform track identity, change
detection and conflict resolution; much larger project); Konduktor owning its own
canonical library format with platforms as import/export only (rejected — changes
the product's identity and displaces the user's real library).
- **Consequence**: Two distinct write paths must coexist: a high-fidelity in-place
*edit* path per platform, and a lossy-by-design *export* path. They have opposite
requirements and should not share an implementation.
### Track identity: not needed — export always generates a fresh target library
- **Decision**: An Export is a one-time conversion that generates a **fresh** target
library. It never merges into an existing library on the target platform. The
originally-loaded library remains canonical and is the only thing edited in place.
- **Rationale**: Keeps the canonical-source model clean — edits go back to the source
library, exports are disposable output. Removes the need for any cross-platform
track-matching mechanism.
- **Alternatives considered**: path-only matching (fails on relocation); path with
artist/title/duration tag fallback (false positives); audio content hashing (robust,
survives moves, but requires a full library scan); acoustic fingerprinting
(Chromaprint/AcoustID — heavy, solves a problem this product doesn't have). All
rejected as unnecessary given fresh-export-only.
- **Consequence**: The existing `volume + dir + file` primary key remains sufficient.
Cross-library identity is deferred indefinitely; it would only return if merge-style
export were ever wanted.
### Serato backup: GEOB-frame sidecar, not full file copies
- **Decision**: Before patching a Serato GEOB frame, snapshot the original frame bytes
to a sidecar restore file. Do not copy whole audio files. Crate files are copied
wholesale (tiny).
- **Rationale**: Kilobytes instead of gigabytes per save, and a complete restore for
everything Konduktor actually touches, since Konduktor only ever rewrites those frames.
- **Alternatives considered**: full audio-file backups — rejected on cost (~1 GB for a
100-track save).
- **Risk accepted**: does not protect against the tag library corrupting an unrelated
region of the audio file. This exposure already exists via `file_tags.py` cover-art
writes; Serato support widens it from occasional to routine.
### Export = a new self-contained library, always including copied audio
- **Decision**: An export/conversion always produces a whole new library at a
user-chosen destination, complete with copies of the music files — for every target
platform, not just Serato. Reference-in-place is not offered.
- **Audio folder layout**: a **global, persistent export setting** with two options —
**flat single folder (default)** or **mirror source directory structure**.
*Rationale*: flat is predictable and simple for the common case; mirroring is there
for users who want their original structure preserved. *Alternatives considered*:
organised Artist/Album from metadata (clean but depends on metadata quality and needs
sanitising); mirror playlist structure (legible on USB, but duplicates tracks that
appear in multiple playlists).
- **Rationale**: The export is self-contained and portable (USB drive, another machine,
handing it to someone else). Consistent behaviour across targets.
- **Alternatives considered**: copy only where the format forces it (Serato), letting
Traktor/Rekordbox exports reference originals in place for a near-instant export;
offering it as a per-export user choice. Both rejected in favour of one predictable
behaviour.
### Export Sets: user-curated export scope
- **Decision**: Introduce an **Export Set** (not "Crate" — see naming decision) — a named, persisted list of track and playlist
*references* defining what a given export includes. Enables partial exports. Each
crate belongs to a specific library, and crate data is persisted in Konduktor's own
storage (not in the platform library).
- **Flow**: open library → prep tracks → save back to the canonical library → create a
crate → drag tracks/playlists into it → export crate (choose target platform +
destination) → Konduktor writes the target library files and copies the audio.
- **Rationale**: Users rarely want to convert an entire library; export scope needs to
be curated and re-usable across repeat exports.
- **Naming**: called **Export Set**, not "Crate". *Rationale*: "Crate" is Serato's own
term for a playlist and Konduktor imports Serato crates — the collision would be
confusing in a multi-platform tool. *Alternatives considered*: keeping "Crate"
(familiar DJ vocabulary, but ambiguous); "Bundle"; "Package".
- **Reference semantics: live**. An Export Set stores pointers to playlists; export
resolves them at export time, so later additions to a playlist are picked up.
*Alternatives considered*: snapshot-at-add (frozen and auditable, but stale);
live-with-optional-freeze (more flexible, more UI + model complexity).
*Consequence*: the export preview must be computed at export time, never stored.
- **Storage: own store, keyed by stable library ID**. A dedicated Export Sets store,
separate from `userprefs.json`, with each library assigned a stable generated ID so
that moving or renaming the collection file does not orphan its export sets.
*Alternatives considered*: keying by collection file path (simple, orphans on move);
storing inside `userprefs.json` (best-effort I/O, no backup — inadequate for curated
user work); a sidecar file next to the user's library (travels automatically, but
writes Konduktor files into the user's Traktor/Serato folders).
### Export mechanics
- **Flat-layout filename collisions: counter suffix.** Second and later collisions
become `Xtal-2.mp3`, `Xtal-3.mp3`. *Rationale*: human-readable and predictable.
*Alternatives considered*: metadata-based disambiguation (`Xtal (Aphex Twin).mp3` —
most legible and stable, but depends on metadata quality and needs sanitising); short
hash suffix (stable across re-exports regardless of order, but ugly).
*Known consequence*: numbering depends on processing order, so repeat exports may
assign different suffixes to the same tracks.
- **Playlist folder structure: preserve where supported, flatten with path names
otherwise.** Keep the tree on Traktor and Rekordbox; on flat targets, flatten to names
encoding the path (e.g. `House / Peak Time`). *Rationale*: retains the structural
information in readable form on every target and avoids name collisions between
same-named playlists in different folders. *Alternatives considered*: flatten to bare
names (cleaner, but collides); always flatten (uniform, but discards structure the
target could represent).
- **Re-export to an occupied destination: warn, then overwrite on confirm.** *Rationale*:
the destination stays the single current copy, which is what re-export usually means,
with a guard against accidental loss. *Alternatives considered*: always write a new
timestamped folder (safe, but fills the drive with copies of a large collection);
refuse and require an empty destination (tedious for a routine operation); incremental
update in place (fast, but reintroduces target-library matching/diffing, which the
fresh-export decision deliberately avoided).
- **Whole-library export: an explicit "export entire library" action.** A separate
action that skips export-set creation. *Rationale*: wholesale migration is a common
real use case and shouldn't require busywork. *Alternatives considered*: export sets
only (uniform, but forces a select-everything set); a select-all shortcut inside the
export set editor (single code path, but less discoverable).
### Export set resolution and export UX
- **Playlist resolution: auto-include, deduplicate, copy once.** Every track referenced
by a playlist in the export set is included automatically; a track appearing in
multiple playlists, or also added individually, is copied to disk exactly once.
*Alternatives considered*: auto-include but surface the implied tracks in the UI (more
transparent, more UI); require explicit inclusion (precise, but surprising).
- **Missing audio files: pre-scan, report, let the user decide.** Verify every file
exists before copying anything; present what's missing and let the user cancel or
proceed without them. *Rationale*: fails fast rather than halfway through a multi-hour
copy. *Alternatives considered*: skip silently (incomplete export the user never
learns about — worse given the loss report was deferred); abort entirely (one
unmounted drive blocks an otherwise fine export).
- **Export UX: pre-check space, progress with cancel.** Estimate total size and verify
the destination has room before starting; show per-file progress with a working
cancel. *Alternatives considered*: cancel with rollback (destination never left
half-finished, but deleting files from a user-chosen location needs care);
progress-only with no pre-check (discovers a full drive after an hour of copying).
*Known consequence*: cancelling leaves a partial export that must be cleaned up or
clearly marked incomplete.
### Serato export copies the audio files
- **Decision**: Exporting to Serato copies the original audio files to the export
destination and writes the GEOB frames into the **copies**, leaving the canonical
library's files untouched.
- **Rationale**: Serato's prep data lives inside the audio files, so a Serato export
cannot reference the originals without mutating them — and the originals belong to
the canonical library.
- **Open consequence**: creates an asymmetry with Traktor/Rekordbox exports, whose data
lives in a library file and could reference originals in place. See Open Questions.
### Rekordbox open-app handling: warn and proceed
- **Decision**: If Rekordbox appears to be running when the user saves, Konduktor
**warns but allows the save to proceed** — it does not hard-refuse.
- **Rationale**: Consistent with the existing Traktor behaviour (the user is warned to
close Traktor before saving, not blocked).
- **Alternatives considered**: detect-and-refuse (safer, but blocks the user on a
detection heuristic that may be wrong).
- **Risk accepted**: Rekordbox may hold `master.db` open and runs cloud sync, so a
concurrent write is riskier than Traktor's overwrite-on-exit behaviour. The backup
taken before the write is the mitigation.
### Backup/verification: same invariant, per-platform mechanism
- **Decision**: Keep the existing invariant — *an edit changes only what it was
supposed to change* — and implement a per-platform comparison mechanism for it:
Traktor byte diff (existing), Rekordbox full table dump with row-level diff, Serato
byte diff of the audio file excluding the patched GEOB frame plus whole-file diff of
crate files. Backups: copy `collection.nml` / copy `master.db` (+ WAL/SHM) /
Serato strategy TBD (see Open Questions).
- **Rationale**: Generalizes `test_save_fidelity.py`'s guarantee to formats where a
byte-identical whole-file comparison is meaningless.
- **Alternatives considered**: dropping the fidelity guarantee for the non-Traktor
platforms — rejected, it is the project's core safety property.
### Cue model: rich core cue, adapters collapse on write
- **Decision**: Model a cue richly enough to cover all three platforms:
`{ position_sec, length_sec?, role: hotcue|memory, slot?, type: cue|fade_in|fade_out|
load|loop, color?, name? }`. Adapters collapse it per platform — Traktor rejects
`role: memory`; Rekordbox and Serato have no `fade_in`/`fade_out`/`load` types;
Serato keeps loops in a separate saved-loop bank rather than consuming a cue slot.
- **Platform differences captured**: Traktor = 8 typed hotcue slots (loop is a cue
*type*); Rekordbox = 8 hotcues A–H plus unlimited memory cues, colour per cue;
Serato = 8 cues plus a separate saved-loop bank, colour per cue.
- **Correction noted during discussion**: Traktor's `CueV2Type` *does* carry a `color`
field, so NML supports cue colours — an earlier assumption to the contrary was wrong.
**Lesson: establish capabilities empirically per format rather than assuming them.**
### Lossiness policy: degrade where sensible, drop otherwise
- **Decision**: On export, data the target cannot represent is **degraded to the
nearest equivalent where one exists, and dropped only where none does** — e.g. a
Traktor fade-in cue becomes a plain cue in Serato; Rekordbox memory cues fill spare
hotcue slots in Traktor until they run out.
- **Rationale**: The project aims for as much feature parity across platforms as
possible; silently discarding representable data works against that.
- **Alternatives considered**: drop silently (clean output, but the user only discovers
the loss on the gear); refuse to export when data would be lost (too rigid).
- **No loss report for now**: an export summary of what was degraded or dropped was
explicitly deferred ("not for now"). The adapters will know what they collapsed, so
it remains cheap to add later.
### Proposed sequencing (not yet confirmed)
1. Fix the flexible-grid bug standalone (small, independent, fixes a present-day data
risk). Requires verifying the NML representation first.
2. Refactor to generic model + adapter interface with **Traktor as the only adapter** —
no new formats, all existing tests must still pass, so `test_save_fidelity.py` proves
the projection+command split broke nothing. Takes the architectural risk where it is
verifiable.
3. Add the second platform — where a one-adapter abstraction gets tested for real.
4. Export — only meaningful once two platforms exist.
### Sequencing: grid fix → Traktor-only refactor → Rekordbox → export
- **Decision**:
1. Fix the flexible-beatgrid handling as a **standalone change first** (small,
independent, and currently writing inconsistent grids to real collections).
2. Refactor to the generic model + adapter interface with **Traktor as the only
adapter** — no new formats, every existing test must still pass, so
`test_save_fidelity.py` proves the projection+command split changed nothing.
3. Add **Rekordbox** as the second platform.
4. Build the **export** path last (it only becomes meaningful once two platforms
exist).
- **Rationale**: takes the architectural risk where it is verifiable against existing
invariants, before any unverifiable format is introduced. A one-adapter abstraction is
always wrong in ways that only surface with the second adapter.
- **Second platform — Rekordbox over Serato**: chosen despite the riskier write target
(SQLCipher-encrypted DB, cloud sync, version-fragile schema) because `pyrekordbox` is
the more mature library. *Alternative considered*: Serato second — no library-file
risk, but writes go into users' audio files and the format is entirely
reverse-engineered.
- **Tauri packaging: dropped from scope for now.**
- **CDJ/USB export (`export.pdb` + ANLZ files): explicitly OUT OF SCOPE.** Raised in a
forked conversation and rejected as impractical to implement. Recorded here only so
it is not rediscovered and re-proposed.
- **Bulk metadata editing: dropped from scope for now.** Not built before the refactor;
revisit after the adapter architecture exists so it only has to be written once.
### One library open at a time
- **Decision**: `AppState` continues to hold exactly one loaded library. Export always
reads the currently-open library.
- **Rationale**: Simplest plumbing, no ambiguity about which library an edit or export
targets, and the existing collection-picker flow is unchanged.
- **Alternatives considered**: multiple loaded with one active (faster switching, but
dirty-flag/save-bar/unsaved-changes state all become per-library); fully concurrent
multi-library (powerful, but multiplies UI and state complexity and invites the
merge/sync expectations already ruled out).
### Capability detection: version first, probe as fallback
- **Decision**: Derive capabilities from the library's declared version where one
exists (NML version, Rekordbox schema version); where no version is stamped — Serato
— infer capabilities from the data actually present.
- **Rationale**: Accurate per-library capability reporting without assuming a floor that
denies users features their software actually has.
- **Alternatives considered**: probe-only (uniform and empirical, but an empty or simple
library under-reports); assume-newest-and-degrade-on-failure (least work, risks
writing data older software can't read); static per-platform floor (trivial, but
penalises users on current versions).
- **Consequence**: each adapter needs its own version-detection story.
- **Serato exception**: Serato has no version-stamped library file, so rather than
probing the data, Konduktor simply **assumes the latest Serato version** and reports
the full capability set. *Rationale*: keeps it simple, and probing under-reports on
small or fresh libraries. *Risk accepted*: a user on an older Serato build could be
written prep data their install cannot read; mitigated by Serato's aggressive
auto-update and the relative stability of the GEOB tag format.
### Field mapping: normalise, but keep the native value alongside
- **Implementation requirement**: this demands **per-field dirty tracking**. The rule
"reuse the native value unless the user edited this field" needs to know *which
fields* changed, not just which tracks — `PlaylistStore` currently tracks dirtiness at
track level. It must exist from the start: retrofitted, it cannot distinguish
edited-to-the-same-value from untouched. It pairs well with projection+command, since
a command already names the field it changes, so the flag falls out of the command
rather than requiring a diff.
- **Decision**: Ratings, keys, colours and comments are stored in canonical form in the
generic model (rating 0–5, key as canonical pitch-class + mode, colour as RGB), and
**each field also retains its untouched native value**. On write-back the native value
is reused unless the user actually edited that field, so untouched tracks round-trip
exactly and only genuine edits go through conversion.
- **Rationale**: Gets a clean, convertible canonical model without introducing
round-trip drift on data the user never touched — consistent with the project's
fidelity-first posture.
- **Alternatives considered**: normalise-in/denormalise-out only (clean model, but
round-tripping through a lossy scale shifts values); preserve native and convert only
on export (zero round-trip risk, but every UI consumer must interpret
platform-specific values).
### Prep UI: generic model with capability-gated controls
- **Decision**: The prep UI (waveform, cues, grid) works purely off the generic model,
with capability flags disabling or hiding the individual controls the loaded platform
cannot persist (e.g. no memory-cue control on Traktor). No platform branching inside
components.
- **Rationale**: One UI to maintain, and users are never offered an edit that will
silently vanish on save.
- **Alternatives considered**: no gating, letting adapters silently collapse on write
(simplest, but is precisely the failure mode the capability system exists to prevent);
gate-plus-warn with controls left enabled (more discoverable, but risks nagging during
normal prep work).
## Findings
### VERIFIED: Traktor flexible-grid representation in NML
Checked against `All I Need` (Shiba San, Tim Baresko) in
`/Users/ben/Documents/Native Instruments/Traktor 4.5.0/collection.nml`. A flexible grid
is stored as **multiple `CUE_V2 TYPE="4"` markers, each with its own `<GRID BPM>`
child**:
```
TEMPO BPM="124.999908"
CUE_V2 TYPE="4" NAME="AutoGrid" START="71.815535" GRID BPM="124.999908"
CUE_V2 TYPE="4" NAME="Beat Marker" START="46151.849285" GRID BPM="62.499954"
CUE_V2 TYPE="4" NAME="Beat Marker" START="76871.871785" GRID BPM="249.999817"
```
- The first marker is named `AutoGrid`; subsequent ones are `Beat Marker`.
- `TEMPO BPM` mirrors the **first** marker's BPM.
- The half/double BPMs (62.5 / 250 against a base of 125) are genuine half-time and
double-time sections.
- A non-flexible track (`Cash Money`) has exactly one `TYPE="4"` marker — so the same
structure covers both cases; a constant grid is just a marker list of length one.
- Separately, tracks carry a `TYPE="0"` cue named `AutoGrid` in **hotcue slot 0** with
`COLOR="#FFFFFF"`, positioned at almost (not exactly) the type-4 anchor's START.
- `COLOR` is populated in practice, confirming Traktor does carry per-cue colour.
### Current `set_grid` is incorrect for flexible beatgrids (present-day bug risk)
`PlaylistStore._grid_marker()` ([backend/konduktor/playlist_store.py:395](../../backend/konduktor/playlist_store.py#L395))
returns only the **first** `CUE_V2` with a `grid` child. Consequences on a track with
a flexible (multi-marker) grid:
- `set_grid(bpm=X)` updates `TEMPO` and only the *first* marker's BPM, leaving
subsequent markers at their old BPM → internally inconsistent grid written to disk.
- `set_grid(anchor_sec=X)` moves only the first marker.
- `delete_grid()` removes all grid markers, but **leaves the companion `TYPE="0"`
`AutoGrid` hotcue-slot-0 cue behind** as debris, since it only strips cues with a
`grid` child.
- Concretely on `All I Need`: `set_grid(bpm=130)` would set `TEMPO` and the `AutoGrid`
marker to 130 and leave the Beat Markers at 62.5 and 250 — a destroyed grid.
- The frontend beatgrid drawing (`cues.ts`) is built around a single BPM + anchor, so
a flexible grid would also render incorrectly.
CLAUDE.md describes the grid as "the grid marker (`CUE_V2` type 4 with a `<GRID BPM>`
child)" — singular — so this assumption is baked into the docs as well as the code.
**Implication for step 1**: this is not a small bug fix. `set_grid(bpm, anchor_sec)`
structurally cannot express per-marker edits, so the fix requires a new marker-level
command vocabulary and marker selection in the `GridControls` UI.
## Next Steps
1. **Design the grid marker command vocabulary** (plan mode, with
`backend/konduktor/playlist_store.py` and `frontend/src/components/GridControls.tsx`
open). `set_grid(bpm, anchor_sec)` must be replaced by marker-level commands, and
`GridControls` needs marker selection.
2. **Fix flexible-beatgrid handling** as a standalone change, including the
`delete_grid` debris bug (the companion `TYPE="0"` `AutoGrid` hotcue-0 cue is left
behind). Add a test fixture based on `All I Need` (three grid markers at 125 / 62.5 /
250 BPM). Update CLAUDE.md, which documents the grid as singular.
3. **Refactor to generic model + adapter interface, Traktor-only.** All existing tests
must still pass unchanged — `test_save_fidelity.py` is the proof that the
projection+command split changed nothing.
4. **Add the Rekordbox adapter.** Research `rb_local_usn` / cloud-sync columns first.
Write the Rekordbox verification test (row-level table-dump diff).
5. **Add the Serato adapter.** GEOB-frame sidecar backups; write the Serato verification
test (byte diff excluding the patched frame, plus whole-file crate diff).
6. **Build the export path.** Only meaningful once two platforms exist.
### Command vocabulary: strictly generic, no adapter escape hatches
- **Decision**: Every command is defined in generic-model terms and each adapter
translates it. Adapters may not expose platform-specific commands.
- **Rationale**: Keeps the UI fully platform-agnostic and forces genuine abstraction
rather than letting platform specifics leak upward.
- **Alternatives considered**: a generic core plus adapter escape hatches (pragmatic,
but the hatch gets used and generic coverage quietly erodes); starting generic and
adding hatches only on demonstrated need.
- **Two-platform promotion rule** (resolves the single-platform-feature problem):
- A feature that exists on only **one** platform is **preserved but not editable** —
no command, no generic concept, no editing UI. Under projection+command it survives
round-trip intact for free, because unmodelled native data never leaves the native
model. The strictly-generic vocabulary therefore constrains what Konduktor can
**edit**, not what it **preserves**.
- A concept is **promoted into the core vocabulary once at least two platforms have
it**, at which point there is real evidence of what the shared abstraction should
be, rather than a concept invented to accommodate a single format.
- *Rationale*: avoids both failure modes — inventing a fake abstraction to house a
one-platform feature (e.g. a "performance sequence" concept only Serato ever uses),
and opening an escape hatch that quietly erodes generic coverage.
- *UI affordance*: show preserved-but-uneditable data as read-only, so users can see
that e.g. their Serato Flip data is intact rather than assuming Konduktor discarded
it. Makes the limitation honest instead of invisible.
- *Consequence accepted*: conversion coverage is capped at what two or more platforms
share — which matches the stated parity goal rather than compromising it.
### Save model: projection + command replay
- **Decision**: The generic model is a **read projection**. Edits are expressed as
commands and replayed by a per-platform adapter onto the **retained native model**,
which remains the write target. Export is a separate, lossy path reading from the
projection.
- **Rationale**: It is the only model that matches how all three storage formats
actually behave — Rekordbox `master.db` requires row `UPDATE`s (cannot be
regenerated: internal IDs, FKs, ANLZ pointers, `rb_local_usn` sync columns), Serato
requires patching individual GEOB frames inside audio files, and Traktor already
deliberately avoids regeneration. It also preserves the byte-exact NML guarantee and
`test_save_fidelity.py`, makes unknown native fields survive **for free** (they are
never lifted out of the native model), and keeps edit *intent* explicit. Critically,
Konduktor already implements this shape for Traktor: `CollectionService` is the read
projection, `PlaylistStore` holds the native model with command methods, the HTTP API
is already a command bus, and `replace_track()` is the projection refresh. This is a
generalization, not a rewrite.
- **Alternatives considered**: *Generic model as source of truth* — rejected: would
lose unmodelled fields on real irreplaceable data, discards the byte-exact guarantee,
cannot work for `master.db`, and its headline benefit (free conversion) is illusory
since per-target serializers are needed either way; its only real prize is simpler UI
mutation code. *Source of truth + diff-based writeback* — rejected: diffing destroys
edit intent exactly where platforms disagree (grid phase-shift vs. retempo is
indistinguishable in a marker-position diff), ordered-list diffs are fiddly, and it
needs a full deep snapshot at load.
- **Cost accepted**: an N×M adapter matrix (~15 commands × 3 platforms), plus careful
choice of command altitude.
### Model shape: rich core + capability system
- **Decision**: Model the union of *concepts* at full fidelity in the generic model —
beatgrid is always a marker list, a cue always carries position/type/colour/role/slot
— and build a per-platform **capability system** so the UI never offers an edit the
loaded platform cannot persist.
- **Rationale**: The conversion goal requires one shared vocabulary; anything parked in
a platform-specific extension namespace cannot be converted. Ben confirmed
willingness to build the capability UI.
- **Alternatives considered**: *Union superset* — rejected, forces every UI consumer to
branch on the loaded platform. *Core + per-platform extensions* — rejected, because
the data that would land in extensions (Rekordbox memory cues, Serato saved loops) is
central rather than exotic, and extensions do not convert.
- **Note from Ben**: Traktor 3.4+ supports **flexible beatgrids**, so the marker-list
model is right for all three platforms rather than being a Traktor-side compromise.
This also means the current single-marker assumption in the codebase is already wrong
(see Findings).
### Undo/redo: deferred but not precluded
- **Decision**: Do not implement undo/redo now, but design the command layer so
inverse commands can be added later.
- **Rationale**: Keeps the adapter surface smaller for the initial build while
retaining the option; the command model makes it cheap to add.
- **Alternatives considered**: designing for inverses from day one (more discipline in
every adapter method); ruling it out entirely (loses a strong safety feature).
### Format layers: reuse mature libraries
- **Decision**: Use existing libraries for the Rekordbox and Serato format layers
(e.g. `pyrekordbox` for `master.db`/SQLCipher/XML/ANLZ, an existing Serato
crate+GEOB library), wrapped behind Konduktor's adapter interface.
- **Rationale**: Fastest path to coverage; the project already accepts this class of
dependency risk with `traktor-nml-utils`.
- **Alternatives considered**: reuse for reading but own all write paths (more control
over surgical patching and fidelity, more work); build everything in-house (maximum
control, very large reverse-engineering effort); spike first and decide per platform.
## Agent Onboarding
### Summary
Konduktor is today a Traktor-only tool whose defining property is **save fidelity**: it
never regenerates `collection.nml`, it surgically patches a parsed dataclass model and
renders through the library's own pipeline, so a no-op save is byte-identical and only
edited objects diff (`test_save_fidelity.py`, CLAUDE.md gotcha 3).
Ben wants to extend it to Rekordbox and Serato, with library conversion as the ultimate
payoff. His opening proposal was a generic data structure that all platforms load into,
are edited through, and are saved back out of.
The central tension explored was that **"load into a generic model and serialize back
out" would destroy the fidelity guarantee**. The discussion resolved it by establishing
that for two of the three platforms, whole-model serialization is not even a coherent
operation: Rekordbox's `master.db` is SQLite with internal IDs, FKs, ANLZ pointers and
sync columns (you `UPDATE` rows, you cannot regenerate), and Serato's prep data lives as
binary GEOB frames inside the audio files themselves (you patch a frame). Both are
inherently mutation-oriented. This made **projection + command replay** the only model
that generalizes — and, critically, Konduktor already implements exactly that shape for
Traktor (`CollectionService` = read projection, `PlaylistStore` = native model + command
methods, the HTTP API = command bus, `replace_track()` = projection refresh). The work is
a generalization, not a rewrite.
A second thread established that the generic model should be **rich** (model the union
of concepts at full fidelity, adapters collapse on write) rather than
lowest-common-denominator or core-plus-extensions, because anything parked in a
platform-specific namespace cannot be converted. This makes a **capability system**
mandatory so the UI never offers an edit that silently won't persist.
A third thread covered **exports**: always a fresh, self-contained target library with
copied audio, scoped by a user-curated **Export Set**. Because exports never merge into
an existing target, cross-platform track identity is not needed at all — the existing
path-based primary key suffices.
Along the way the discussion surfaced a **present-day bug**: Ben noted Traktor 3.4+
supports flexible beatgrids, and verification against his real collection confirmed
Traktor stores them as multiple `CUE_V2 TYPE="4"` markers each with its own `<GRID BPM>`.
`PlaylistStore._grid_marker()` only ever reads the first, so `set_grid(bpm=X)` writes
internally inconsistent grids to real collections today. This became step 1 of the plan,
and it is bigger than a bug fix because the `set_grid(bpm, anchor_sec)` signature
structurally cannot express per-marker edits.
Note: a "CDJ/USB export" requirement appeared in this log mid-discussion from a forked
conversation. Ben confirmed it was rejected as impractical and had it removed. **Do not
re-propose it.**
### If Continuing This Discussion
All design questions are resolved. Three items remain, none of them decisions:
- Grid marker command vocabulary — a design task for plan mode, not an open question.
- Per-platform verification tests — implementation work landing with each adapter.
- Rekordbox `rb_local_usn` / cloud-sync columns — research for the Rekordbox phase.
Deliberately deferred, do not reopen without Ben raising them: the export loss report
("not for now"), bulk metadata editing, Tauri packaging, and CDJ/USB export (rejected).
### If Moving to Planning/Implementation
**Requirements**
1. **Save model — projection + command replay.** The generic model is a *read
projection*. Edits are commands replayed by a per-platform adapter onto the
**retained native model**, which stays the write target. Never serialize the generic
model back over a native library. This preserves byte-exact NML saves and means
unmodelled native fields survive for free.
2. **Command vocabulary — strictly generic.** All commands are defined in generic-model
terms; adapters translate. **No platform-specific escape hatches.** Single-platform
features are *preserved but not editable*; a concept is promoted into the core
vocabulary only once **two or more platforms have it**. Surface preserved-but-
uneditable data as read-only in the UI.
3. **Generic model — rich core.** Model the union of concepts at full fidelity.
Beatgrid is **always a marker list** (a constant grid is a list of length one — this
is correct for all three platforms, not a compromise). Cue shape:
`{ position_sec, length_sec?, role: hotcue|memory, slot?, type: cue|fade_in|fade_out|
load|loop, color?, name? }`.
4. **Capability system — mandatory.** Capabilities are `f(platform, version)`, derived
from the declared version where one exists; **Serato assumes the latest version** for
simplicity. The prep UI works purely off the generic model with capability-gated
controls — no platform branching inside components.
5. **Field mapping — normalise, keep native alongside.** Canonical forms in the model
(rating 0–5, canonical key, RGB colour) *plus* the untouched native value. On
write-back, reuse the native value unless the user actually edited that field.
**This requires per-field dirty tracking** — `PlaylistStore` is track-level today, and
it must exist from the start because it cannot be retrofitted (edited-to-same-value
becomes indistinguishable from untouched). It falls out of the command, which already
names the field it changes.
6. **Write scope — full read/write for all three platforms**, in place, to the user's
canonical library. One library open at a time (`AppState` keeps holding exactly one).
7. **Safety — same invariant, per-platform mechanism.** "An edit changes only what it
was supposed to change." Traktor: byte diff (exists). Rekordbox: full table dump,
row-level diff; back up `master.db` + WAL/SHM; **warn but proceed** if Rekordbox is
running. Serato: byte diff of the audio file excluding the patched GEOB frame, plus
whole-file crate diff; **back up GEOB frames to a sidecar, not whole audio files**
(KB not GB; accepted risk: no protection if the tag library mangles an unrelated
region — an exposure `file_tags.py` already carries).
8. **Export — always a fresh, self-contained library** at a user-chosen destination,
**including copied audio, for every target** (not just Serato). Never merges into an
existing target library, so no cross-platform track identity is required.
- Scoped by an **Export Set**: a named, persisted list of track and playlist
references. **Live references** — resolved at export time, so the preview must be
computed then, never stored. Playlist tracks auto-included, deduplicated, copied
once.
- Stored in Konduktor's own store (not `userprefs.json`), keyed by a stable library
ID held in a **sidecar file next to the user's collection**.
- Audio layout: a **global persistent setting** — flat single folder (**default**) or
mirror source structure. Flat collisions get a **counter suffix** (`Xtal-2.mp3`).
- Playlist folders preserved where the target supports them, otherwise flattened to
**path-encoding names** (`House / Peak Time`).
- **Pre-scan for missing audio files**, report, let the user decide. **Pre-check disk
space**; progress with a working cancel (cancel leaves a partial export — clean up
or mark clearly).
- Re-export to an occupied destination: **warn, overwrite on confirm**.
- Provide an explicit **"export entire library"** action that skips export-set creation.
9. **Lossiness — degrade where sensible, drop otherwise.** Goal is maximum feature
parity. No loss report for now (deferred, cheap to add later since adapters know what
they collapsed).
10. **Format layers — reuse mature libraries** (`pyrekordbox` for master.db/SQLCipher/
XML/ANLZ; an existing Serato crate+GEOB library) behind Konduktor's adapter
interface, consistent with the existing `traktor-nml-utils` dependency posture.
11. **Undo/redo — not now, but do not preclude it.** Design commands so inverses can be
added later.
**Sequencing** (see Next Steps for the actionable breakdown)
Grid fix → Traktor-only refactor → Rekordbox → Serato → export. Rekordbox was chosen as
the second platform over Serato because `pyrekordbox` is the more mature library, despite
the riskier write target.
**Out of scope**: Tauri packaging, bulk metadata editing, CDJ/USB export
(`export.pdb` + ANLZ — rejected as impractical), two-way sync, Konduktor owning its own
canonical library format.
**Rejected alternatives worth not relitigating**
- Generic model as source of truth, and source-of-truth + diff-based writeback — both
rejected; see the save model decision. The claimed "free conversion" benefit is
illusory (per-target serializers are needed either way), and diffing destroys edit
intent exactly where platforms disagree.
- Union superset and core-plus-extensions model shapes.
- Cross-platform track matching by path/tags/content-hash/fingerprint — unnecessary
given fresh-export-only.
- Full audio-file backups for Serato writes.
- Reference-in-place exports for non-Serato targets.
**Standing lesson from this discussion**: establish format capabilities **empirically**
against real files rather than assuming them. An assumption that Traktor could not store
cue colours was wrong (`CueV2Type` has a `color` field, populated in practice), and the
flexible-grid assumption was only settled by reading Ben's actual collection.
+221
View File
@@ -0,0 +1,221 @@
# Handoff: the export feature
**For**: an agent picking up Konduktor with no prior context.
**Task**: build library export — converting a curated slice of the loaded library
into a **fresh, self-contained library for another platform**, with the audio
files copied alongside.
**Status of the plan**: the multi-platform work is done through the Rekordbox
adapter. Export was originally sequenced *after* a Serato adapter; Ben has
chosen to bring it forward, so **the only export targets that can exist today are
Traktor and Rekordbox**.
Every *design* decision was settled in
[`.claude/discussions/discuss-multi-platform-library-2026-09-17.md`](../discussions/discuss-multi-platform-library-2026-09-17.md)
— read its **Export** sections and **"If Moving to Planning/Implementation"**
before designing anything. This handoff is the current-state companion: what
exists, what to build, and what will bite you. Where they disagree, the
discussion doc wins on intent and this one on facts about the code.
The Rekordbox handoff ([`rekordbox-adapter.md`](rekordbox-adapter.md)) is worth
skimming too — its §8 Findings are the format knowledge any Rekordbox *writer*
will need, and its history is a good model of how this project verifies things.
---
## 1. Where the project is
Konduktor is a library-management and track-prep tool for DJ software, built on a
**generic model + per-platform adapter** architecture. Two adapters exist:
- **Traktor** (`collection.nml`) — full read/write, byte-exact saves, version
history.
- **Rekordbox** (`master.db` + ANLZ analysis files) — read/write for metadata,
playlists, hot cues and beatgrids. No version history (a deliberate, accepted
scope decision). Gaps: cover art, `remap_locations`.
```
backend/konduktor/
core/ generic. MUST NOT import a native library type (test_layering.py)
model.py Track, CuePoint, GridMarker, TrackCues, PlaylistNode…
adapter.py LibraryAdapter / LibraryDriver protocols, SaveOutcome, errors
capabilities.py what a loaded library can persist
query.py TrackIndex: query/filter/sort/facets/stats
registry.py adapter selection by can_open() probe
adapters/traktor/ store.py (native model) adapter.py projection.py driver.py …
adapters/rekordbox/ same shape; store.py owns the SQLCipher session + ANLZ
app_state.py the one loaded library + version-history commits
prefs.py userprefs.json in the per-OS app-data dir (paths.app_data_dir())
main.py thin FastAPI routes, all under /api
```
**Tests**: `cd backend && ./run_tests.sh` → 331 assertions across
`test_layering.py`, `test_save_fidelity.py`, `test_traktor_adapter.py`,
`test_rekordbox_adapter.py`, `test_rekordbox_fidelity.py`, `test_phase3.py`,
`test_history.py`. Frontend: `npm run build && npm run test`.
**The suite must be green at the end of every step** — that discipline is why a
1,500-line refactor of the save path landed without a fidelity regression.
---
## 2. The one architectural gap, and it is not small
**No adapter can create a library from nothing.**
`LibraryDriver` is `can_open` / `open` / `detect` / `describe` / `restore`.
`LibraryAdapter` is built entirely around *one already-open library* that commands
are replayed onto. Export needs the opposite: **write a brand-new library at a
path where nothing exists yet.**
This is the central design question of the whole feature, and the discussion doc
does not settle it. Decide it deliberately and write down why. The obvious
shapes:
1. **A separate `LibraryWriter` protocol** — `create(path)` returning something
that accepts tracks, playlists and prep data, implemented per target. Keeps
the edit path untouched, which matters because the edit path is the one with
the fidelity guarantees. Some duplication with the adapters' write code.
2. **Extend `LibraryDriver` with `create(path) -> LibraryAdapter`** — an empty
library is then just a library, and the existing commands populate it. Elegant
on paper; the risk is that "empty new file" and "the user's real library"
start sharing code paths, and the *reason* the current architecture is safe is
that the write target is always a retained native model that was parsed from a
real file.
3. **Target-specific exporters with no shared protocol** — fastest to a working
Traktor export, and it will rot.
The discussion doc's strongest constraint bears on this: *"Two distinct write
paths must coexist: a high-fidelity in-place edit path per platform, and a
lossy-by-design export path. They have opposite requirements and should not
share an implementation."* Read that as pointing at (1), but make the call
yourself with the code in front of you.
---
## 3. What the design already settles
Do not relitigate these. They are decided, with rationale and rejected
alternatives recorded in the discussion doc.
**Shape of an export**
- Always a **fresh, self-contained library** at a user-chosen destination.
**Never merges** into an existing target library. This is what removes any need
for cross-platform track identity — there is nothing to match against.
- **Always copies the audio files**, for every target, not just Serato.
- Audio layout is a **global, persisted setting**: **flat single folder
(default)** or **mirror the source directory structure**.
- Flat-layout filename collisions get a **counter suffix** (`Xtal-2.mp3`).
Known consequence: numbering depends on processing order, so repeat exports may
assign different suffixes to the same tracks.
- Playlist folders: **preserve where the target supports them**, otherwise
flatten to path-encoding names (`House / Peak Time`).
- Re-export to an occupied destination: **warn, overwrite on confirm.**
- Provide an explicit **"export entire library"** action that skips export-set
creation entirely.
**Export Sets** (the unit of curation)
- A named, persisted list of **track and playlist references** scoping an export.
Called an **Export Set**, never a "Crate" — Serato uses "crate" for a playlist
and Konduktor will import those.
- **References are LIVE**: an export set stores pointers, and export resolves
them at export time, so later additions to a playlist are picked up.
**Consequence: the export preview must be computed at export time, never
stored.**
- Playlist resolution **auto-includes** referenced tracks, **deduplicates**, and
copies each file **exactly once**.
- Stored in **Konduktor's own store**, not in the platform library and not in
`userprefs.json`, keyed by a **stable library ID**.
**Running an export**
- **Pre-scan for missing audio files**, report them, let the user cancel or
proceed without them — fail fast rather than halfway through a multi-hour copy.
- **Pre-check disk space** before starting.
- **Progress with a working cancel.** Known consequence: cancelling leaves a
partial export, which must be cleaned up or clearly marked incomplete.
**Lossiness**
- **Degrade to the nearest equivalent where one exists, drop only where none
does.** A Traktor fade-in cue becomes a plain cue on a target without them;
Rekordbox memory cues fill spare hot cue slots until they run out.
- **No loss report for now** — explicitly deferred. Adapters know what they
collapsed, so it stays cheap to add.
---
## 4. Landmines, earned
**There is no stable library ID.** Export sets are specified as keyed by one,
held in a sidecar next to the user's collection — and nothing like it exists.
Today everything keys off the library's **OS path**: `prefs.get_path_mapping`,
`prefs.get_last_collection`, and `history`'s repo directory (a hash of the
resolved path). Moving a collection silently orphans all of it. Building export
sets on the path would inherit that; building the sidecar is the decided design
but is genuinely new work. Do it first — retrofitting an ID once sets exist means
migrating them.
**The lossiness rule needs capabilities the target does not have loaded.**
`Capabilities` describes *the currently open library*, via an adapter instance
built from a real file. Export needs to know what a target platform can hold
*before* any such library exists. Either capabilities must become derivable from
a platform alone (not an instance), or exporters must carry their own static
declaration. This is exactly where a "what can the target represent?" question
will first bite, and `capabilities_for()` in each adapter currently takes a
`path`.
**The two-platform promotion rule still applies.** A concept enters the generic
vocabulary only once **two or more** platforms have it. Export will tempt you to
add target-specific knobs to generic types; don't. Single-platform concepts stay
*preserved but not editable* — for instance Rekordbox **memory cues** are
projected and displayed and never written.
**Rekordbox as an export TARGET is much harder than Traktor.** A Traktor export
is one XML file Konduktor already renders byte-exactly. A Rekordbox export needs
a `master.db` — SQLCipher, foreign keys into lookup tables, USN bookkeeping — plus
per-track ANLZ analysis files containing the beatgrid, plus `masterPlaylists6.xml`.
Worse, `.DAT`/`.EXT` analysis files can currently only be *modified*, never
created: `beatgrid.write_pqtz()` rebuilds the `PQTZ` tag **inside an existing
file**. Generating ANLZ from scratch is unexplored, and `PQT2` (the extended
grid) is undecoded — `pyrekordbox` names its per-beat field `unkown`.
**Strongly consider shipping Traktor as the only export target first.**
**CDJ/USB export (`export.pdb` + ANLZ) is rejected as impractical.** It has been
re-proposed twice. Do not raise it again.
---
## 5. Working agreements
- **`./run_tests.sh` green at the end of every step.**
- **`schemas.py` and `api.ts` land in the same commit** — one contract in two
languages.
- **Verify against reality, do not infer.** The project's standing lesson, and it
has been proved right four times: Traktor cue colours, flexible grid marker
naming, whether Rekordbox reads `PQTZ` or `PQT2`, and the hot cue slot
encoding. That last one cost two rounds of wrong theory built on three
incidental data points; one deliberate probe across the full range settled it.
For export the equivalent is: **write an export, then open it in the real DJ
software** before believing it works.
- **Ben's Rekordbox library is a disposable test library** — write to it directly,
no backups needed. **His Traktor collection is real, irreplaceable data**
(8,485 entries): always work against copies. `./dev-sandbox.sh` already
encodes exactly this split and refuses to start if another server holds the
ports.
- **Capability-gate every control.** The UI must never offer an edit — or an
export target — that cannot actually be produced. This has failed twice and
both times it was a stale flag, not missing machinery.
## 6. Suggested first steps
1. **Decide the writer architecture** (§2) and record the decision and its
rejected alternatives, in the style of the discussion doc.
2. **Build the stable library ID sidecar** (§4) — everything else keys off it.
3. **Export Sets: model, store, API, UI.** Live references; preview computed at
export time.
4. **A Traktor exporter end to end**, with the audio copy, the pre-scan, the
space check and cancellable progress.
5. **Open the result in Traktor.** Not "the tests pass" — actually open it.
6. Only then consider a Rekordbox exporter, knowing §4's warning.
Bulk metadata editing also remains unbuilt and unblocked; it is far smaller than
this and was deferred specifically until the adapter architecture existed. If a
shippable win is wanted sooner, that is the alternative — confirm with Ben rather
than assuming.
File diff suppressed because it is too large. Load diff
+49
View File
@@ -114,6 +114,52 @@ jobs:
if-no-files-found: error
path: installer/*
# The Konduktor SERVER image (server/Dockerfile): a remote library's half,
# pushed to GHCR with the same version as the desktop app, so a TrueNAS app
# can name the tag that matches the app it is opened from.
server-image:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write # push to ghcr.io
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Resolve version and image name
id: meta
run: |
echo "version=$(jq -r .version frontend/package.json)" >> "$GITHUB_OUTPUT"
# GHCR names must be lower-case; the owner may not be.
echo "image=ghcr.io/${GITHUB_REPOSITORY_OWNER,,}/konduktor-server" >> "$GITHUB_OUTPUT"
- name: Log in to GHCR
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Set up Buildx
uses: docker/setup-buildx-action@v3
- name: Build and push
uses: docker/build-push-action@v6
env:
DOCKER_BUILD_RECORD_UPLOAD: false # no .dockerbuild artifact in the run
with:
context: .
file: server/Dockerfile
platforms: linux/amd64
push: true
tags: |
${{ steps.meta.outputs.image }}:${{ steps.meta.outputs.version }}-b${{ github.run_number }}
${{ steps.meta.outputs.image }}:${{ steps.meta.outputs.version }}
${{ steps.meta.outputs.image }}:latest
labels: |
org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}
org.opencontainers.image.version=${{ steps.meta.outputs.version }}
# Gather both platforms' installers and publish them as a single new Release.
# Runs once, after both builds succeed, so the two matrix jobs never race to
# create the same tag/release.
@@ -136,6 +182,9 @@ jobs:
- name: Download installers from both builds
uses: actions/download-artifact@v4
with:
# Only the installers: the run also holds server-image's Docker build
# record, which is not a release asset (and once failed to download).
pattern: konduktor-*
path: artifacts # → artifacts/konduktor-macOS/…, artifacts/konduktor-Windows/…
- name: Publish release
+142
View File
@@ -0,0 +1,142 @@
# The stem engine: a frozen torch + Demucs program, built per target and
# published on its OWN release channel (`engine-v<version>`), separate from the
# app's `v<version>-b<N>` releases. The app downloads the one it needs on first
# use (see backend/konduktor/stems/engine_manager.py).
#
# * A tag `engine-v1.2.3` builds, tests and publishes — the tag must match
# `konduktor_engine.VERSION`.
# * A manual run builds and tests only (artifacts, no release).
#
# Releases are `prerelease: true` and `make_latest: false`: GitHub's "latest"
# is what an app would take for itself, and the app's update check reads the
# release list (UpdateDialog.tsx) — an engine release must never look like one.
#
# The weights are NOT in the engine (their licence is ambiguous): CI fetches the
# pinned files from Hugging Face only to run the golden test.
name: Engine
on:
push:
tags: ["engine-v*"]
workflow_dispatch:
concurrency:
group: engine-${{ github.ref }}
cancel-in-progress: true
jobs:
build:
strategy:
fail-fast: false
matrix:
include:
- target: macos-arm64
os: macos-latest
torch_index: ""
- target: windows-x64-cpu
os: windows-latest
torch_index: "" # PyPI's Windows torch is the CPU build
- target: windows-x64-cuda
os: windows-latest
# CUDA 13: Turing (RTX 20) through Blackwell (RTX 50); needs an
# NVIDIA driver from r580. Older cards get the CPU engine — the
# manager checks `engine info`'s arch list before offering this.
torch_index: "https://download.pytorch.org/whl/cu130"
runs-on: ${{ matrix.os }}
name: ${{ matrix.target }}
defaults:
run:
shell: bash
working-directory: engine
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Check the tag matches the engine version
if: startsWith(github.ref, 'refs/tags/engine-v')
run: |
want="$(python -c 'import konduktor_engine as e; print(e.VERSION)')"
[ "${GITHUB_REF_NAME#engine-v}" = "$want" ] || { echo "tag ${GITHUB_REF_NAME} != engine $want"; exit 1; }
- name: Install
run: |
python -m pip install --upgrade pip uv
uv venv .venv --python 3.12
PY=.venv/bin/python; [ -f .venv/Scripts/python.exe ] && PY=.venv/Scripts/python.exe
echo "PY=$PY" >> "$GITHUB_ENV"
if [ -n "${{ matrix.torch_index }}" ]; then
uv pip install --python "$PY" "torch==2.14.0" --index-url "${{ matrix.torch_index }}"
fi
uv pip install --python "$PY" -r requirements.txt "pyinstaller==6.21.0"
- name: Weights (for the golden test only)
uses: actions/cache@v4
with:
path: engine/weights
key: htdemucs-ft-d74ac89c3a1e874fc78f152555cf4d8533f06cd4
- run: $PY fetch_weights.py weights
- name: Freeze
run: $PY -m PyInstaller --noconfirm --clean konduktor-engine.spec
- name: Golden test (frozen vs unfrozen, CPU)
run: |
EXE=dist/konduktor-engine/konduktor-engine; [ -f "$EXE.exe" ] && EXE="$EXE.exe"
$PY test_engine.py --weights weights --frozen "$EXE"
- name: Package
run: $PY package.py ${{ matrix.target }} dist out
- name: Paths fit Windows' limit once installed
run: |
# Installed under e.g. %LOCALAPPDATA%\Konduktor\engine\<ver>\<target>\
# (~70 characters on a typical user name): the tree must stay short.
$PY -c "import json,sys; n=json.load(open('out/${{ matrix.target }}.json'))['longest_path']; print('longest', n); sys.exit(n > 180)"
- uses: actions/upload-artifact@v4
with:
name: engine-${{ matrix.target }}
path: engine/out/*
if-no-files-found: error
release:
needs: build
if: startsWith(github.ref, 'refs/tags/engine-v')
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
path: artifacts
merge-multiple: true
- name: Manifest
run: |
python - <<'PY'
import json, glob, os
targets = {}
for f in glob.glob("artifacts/*.json"):
info = json.load(open(f))
targets[info["target"]] = info
version = os.environ["GITHUB_REF_NAME"].removeprefix("engine-v")
weights = json.load(open("engine/weights.json"))
json.dump({"version": version, "targets": targets, "weights": weights},
open("artifacts/engine-manifest.json", "w"), indent=1)
PY
- uses: softprops/action-gh-release@v2
with:
tag_name: ${{ github.ref_name }}
name: Konduktor stem engine ${{ github.ref_name }}
prerelease: true
make_latest: false
fail_on_unmatched_files: true
files: |
artifacts/*.tar.gz*
artifacts/engine-manifest.json
body: |
The stem engine Konduktor downloads for **Convert to Stems** — not an app release.
Konduktor fetches the right file for your computer itself; there is nothing to install by hand.
+4
View File
@@ -47,3 +47,7 @@ backend/userprefs.json
# build_sidecar.sh are source and ARE tracked.
backend/build/
backend/dist/
# ---- Stem engine (PyInstaller onedir build) ----
engine/build/
engine/dist/
+1796 -73
View File
File diff suppressed because it is too large. Load diff
+43
View File
@@ -200,6 +200,49 @@ play around.
---
## A remote library (Konduktor server on a NAS)
Keep your whole library — the collection file and the music — on a server, and
open it from any computer with Konduktor. Prep tracks, edit playlists, and
export sticks for your gigs without the music ever living on your performance
laptop.
The server is a small container (`server/`). It holds the library and saves it.
Playback, analysis and stem separation run on the computer you open it from,
on copies it downloads, so the server needs no GPU and does very little work.
**On the server (e.g. TrueNAS SCALE):**
1. Copy `server/compose.yaml` and `server/.env.example` (renamed to `.env`)
onto the NAS. Point the volumes at your datasets, and fill in `.env`: the
platform (`traktor` or `rekordbox`), the library file, the music folder, a
username and password, and — for a collection made on a Mac — the path
mapping (`/Users/you/Music => /music`).
2. Install it: on TrueNAS, **Apps → Discover Apps → ⋮ → Install via YAML** and
paste the compose file; anywhere else, `docker compose up -d`. A bad setting
stops the container with one clear line in its log.
**In the app:** choose **Remote** on the platform screen → **Add a remote
library** → enter the server's address (and a fallback, such as its Tailscale
address, for when you're away from home), the username and the password.
Konduktor checks the server before it saves the remote, and keeps the
password in your keychain.
Good to know:
- **One computer at a time.** If another computer has the library open,
Konduktor says who has it and offers to take over. Edits that computer
hadn't saved stay with the library, and you're asked to save or discard
them.
- **Plain HTTP.** Reach the server over your home network or a VPN
(Tailscale / WireGuard). Don't expose its port to the internet.
- **Unsaved edits live on the server** until you save. Restarting the
container drops them.
- Downloaded tracks are cached on your computer (Settings → **Remote audio**
sets the size), so a track you've prepped and then export is fetched once.
---
## Good to know
- Konduktor is built on [`traktor-nml-utils`](https://github.com/MrPatben8/traktor-nml-utils)
+189
View File
@@ -0,0 +1,189 @@
"""Benchmark beatgrid detection against grids a DJ platform already analysed.
NOT part of `run_tests.sh`: it needs real audio, and the answer is a score to
compare rather than a pass/fail. Every open is read-only — nothing is saved.
python bench_grid_detect.py # the local Rekordbox library
python bench_grid_detect.py path/to/collection.nml path/to/master.db
python bench_grid_detect.py --legacy # score the old librosa beat_track
python bench_grid_detect.py --hold bpm # Grid alone: phase, given the right BPM
python bench_grid_detect.py --hold anchor # BPM alone: tempo, given the right anchor
The reference is each track's own grid, and only single-marker grids are used:
a multi-marker grid is either a real tempo change (which a constant-tempo
detector cannot match by design) or a hand edit, and neither is ground truth
for "what is this track's tempo".
Per track it reports:
- BPM error, and whether it is an octave error (half/double tempo);
- PHASE error at 30 s in and 30 s before the end — the distance between the
detected grid's nearest beat and the reference's, in ms. Measuring at two
ends is what separates "anchor wrong" (both off by the same amount) from
"BPM wrong" (error grows along the track), which one number would conflate.
"""
from __future__ import annotations
import argparse
import os
import sys
import tempfile
import time
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
os.environ.setdefault("KONDUKTOR_DATA_DIR", tempfile.mkdtemp(prefix="konduktor-bench-"))
import konduktor.adapters # noqa: E402,F401 — registers the drivers
from konduktor.core import registry # noqa: E402
BPM_OK = 0.02 # a grid this close drifts < 1/50 beat per minute...
PHASE_OK_MS = 10.0 # roughly where a DJ starts to hear flamming
def _phase_error_ms(t: float, ref: tuple[float, float], det: tuple[float, float]) -> float:
"""Signed distance (ms) from the reference's nearest beat at ``t`` to the
detected grid's nearest beat, wrapped to half the reference beat."""
r0, rb = ref
d0, db = det
rp, dp = 60.0 / rb, 60.0 / db
ref_beat = r0 + round((t - r0) / rp) * rp
det_beat = d0 + round((ref_beat - d0) / dp) * dp
e = det_beat - ref_beat
e = (e + rp / 2) % rp - rp / 2
return e * 1000.0
def _octave(det: float, ref: float) -> str:
for k, name in ((2.0, "x2"), (0.5, "/2"), (1.5, "x1.5"), (2 / 3, "/1.5")):
if abs(det - ref * k) < 0.5:
return name
return ""
def legacy_detect(audio_path: str):
"""The detector `core/grid_detect.py` replaced (librosa ``beat_track``), kept
here so the two can still be compared on the same references."""
import librosa
import numpy as np
from konduktor.core.grid_detect import GridResult
y, sr = librosa.load(audio_path, sr=22050, mono=True)
tempo, beats = librosa.beat.beat_track(y=y, sr=sr, trim=False)
return GridResult(float(np.ravel(tempo)[0]), float(librosa.frames_to_time(beats, sr=sr)[0]), len(y) / sr)
def references(paths: list[Path]) -> list[tuple[str, Path, float, float]]:
out = []
for p in paths:
a = registry.open_library(p)
try:
for t in a.tracks:
cues = a.track_cues(t.id)
if cues is None or len(cues.grid_markers) != 1:
continue
audio = a.audio_path(t.id)
if audio is None or not audio.exists():
continue
m = cues.grid_markers[0]
out.append((f"{t.artist or ''} - {t.title or audio.stem}".strip(" -"), audio, m.start, m.bpm))
finally:
close = getattr(a, "close", None)
if close:
close()
# One row per audio file: the same file in two libraries would count twice.
seen, uniq = set(), []
for r in out:
if r[1] not in seen:
seen.add(r[1])
uniq.append(r)
return uniq
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("libraries", nargs="*", type=Path)
ap.add_argument("--legacy", action="store_true", help="score the old librosa beat_track detector")
ap.add_argument("--hold", choices=("bpm", "anchor"),
help="score one half alone: hold the REFERENCE's BPM (the Analyze dialog's "
"'Grid' tick — phase is all that is scored) or its anchor ('BPM')")
args = ap.parse_args()
libs = args.libraries or [Path.home() / "Library/Pioneer/rekordbox/master.db"]
refs = references(libs)
if not refs:
print("No single-marker reference grids with reachable audio.")
return 1
if args.legacy:
detect = legacy_detect
else:
from konduktor.core.grid_detect import detect_grid as detect
rows = []
for name, audio, r0, rb in refs:
t0 = time.perf_counter()
try:
hold = {"bpm": {"bpm": rb}, "anchor": {"anchor": r0}}.get(args.hold, {})
res = detect(str(audio), **hold)
except Exception as ex: # a failure is a data point, not a crash
print(f" FAIL {name[:48]:48} {ex}")
rows.append(None)
continue
dt = time.perf_counter() - t0
bpm, first = res.bpm, res.anchor
import soundfile as sf
try:
dur = sf.info(str(audio)).duration
except Exception:
dur = res.duration
early = _phase_error_ms(min(30.0, dur / 3), (r0, rb), (first, bpm))
late = _phase_error_ms(max(dur - 30.0, 2 * dur / 3), (r0, rb), (first, bpm))
oct_ = _octave(bpm, rb) if abs(bpm - rb) >= 0.5 else ""
ok = abs(bpm - rb) <= BPM_OK and abs(early) <= PHASE_OK_MS and abs(late) <= PHASE_OK_MS
lossy = audio.suffix.lower() not in (".wav", ".aif", ".aiff", ".flac")
rows.append((abs(bpm - rb), early, late, oct_, ok, dt, lossy))
conf = f"{res.drift_ms:5.1f}" if res.drift_ms is not None else " -"
print(
f" {'ok ' if ok else 'BAD '} {name[:48]:48} ref {rb:7.3f} got {bpm:8.3f} {oct_:5}"
f" phase {early:+7.1f} / {late:+7.1f} ms drift {conf} ms {dt:4.1f}s"
)
good = [r for r in rows if r]
n = len(rows)
same_octave = [r for r in good if not r[3]]
print()
print(f"tracks {n}")
print(f"all correct {sum(r[4] for r in good)}/{n}")
print(f"BPM within {BPM_OK} {sum(r[0] <= BPM_OK for r in good)}/{n}")
print(f"octave errors {sum(bool(r[3]) for r in good)}/{n}")
if same_octave:
import statistics as st
print(f"median |phase| early {st.median(abs(r[1]) for r in same_octave):.1f} ms")
print(f"median |phase| late {st.median(abs(r[2]) for r in same_octave):.1f} ms")
print(f"phase within {PHASE_OK_MS:.0f} ms "
f"{sum(abs(r[1]) <= PHASE_OK_MS and abs(r[2]) <= PHASE_OK_MS for r in same_octave)}/{n}")
print(f"mean time per track {sum(r[5] for r in good) / max(1, len(good)):.2f} s")
# A platform's MP3/AAC time base can differ from the decoded audio's by a
# constant (Rekordbox: ~+26 ms, the decoder delay it does not trim). That
# is not detection error, and it would swamp it — so report the constant
# per format, and how tightly the tracks sit around it.
import statistics as st
print()
for label, want in (("lossless", False), ("lossy", True)):
grp = [r for r in same_octave if r[6] == want and r[0] <= BPM_OK]
if len(grp) < 2:
continue
offs = [(r[1] + r[2]) / 2 for r in grp]
med = st.median(offs)
spread = [abs(o - med) for o in offs]
within = sum(abs(r[1] - med) <= PHASE_OK_MS and abs(r[2] - med) <= PHASE_OK_MS for r in grp)
print(f"{label:9} n={len(grp):2} constant offset {med:+6.1f} ms "
f"|deviation| median {st.median(spread):4.1f} max {max(spread):5.1f} ms "
f"within {PHASE_OK_MS:.0f} ms of it: {within}/{len(grp)}")
return 0
if __name__ == "__main__":
sys.exit(main())
+172
View File
@@ -0,0 +1,172 @@
"""Benchmark key detection (`core/key_detect.py`).
NOT part of `run_tests.sh`: it needs real audio, and the answer is a score to
compare rather than a pass/fail.
python bench_key_detect.py --giantsteps DATA/gs # hand-annotated EDM
python bench_key_detect.py ~/Music # files with a key TAG
GiantSteps (604 Beatport previews, keys corrected by hand) is ground truth
and the number to quote; the model never trained on it (see
`train_key_model.py`). A folder's key tags were written by some other
analyser — usually Traktor, sometimes Mixed In Key or a store — so that score
is AGREEMENT with it, not accuracy. Copies of one song (a stem file beside its
source) count once, by title.
Errors are classed the MIREX way, because they are not equally wrong for a
DJ: a FIFTH (one step round the Camelot wheel) or the RELATIVE key (same
number, other letter) still mixes harmonically; PARALLEL (same tonic, other
mode) and OTHER do not. MIREX's weighted score is 1 / 0.5 / 0.3 / 0.2 / 0.
"""
from __future__ import annotations
import argparse
import os
import re
import sys
import warnings
from collections import Counter
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
warnings.filterwarnings("ignore")
from konduktor.core import key_detect, musical_key # noqa: E402
WEIGHT = {"exact": 1.0, "fifth": 0.5, "relative": 0.3, "parallel": 0.2, "other": 0.0}
AUDIO = {".mp3", ".m4a", ".mp4", ".flac", ".aif", ".aiff", ".wav", ".ogg"}
def relation(det: tuple[int, str], ref: tuple[int, str]) -> str:
"""How a detected (wheel, mode) relates to the reference."""
(dw, dm), (rw, rm) = det, ref
if (dw, dm) == (rw, rm):
return "exact"
if dw == rw:
return "relative"
if dm == rm and (dw - rw) % 12 in (1, 11):
return "fifth"
if dm != rm:
major, minor = (dw, rw) if dm == "major" else (rw, dw)
if (major - minor) % 12 == 3: # C major 8B vs C minor 5A
return "parallel"
return "other"
def parse_any(text: str) -> tuple[int, str] | None:
"""Open Key, Camelot or a named key ("Abm", "F# minor", "Gmin")."""
w, m = musical_key.parse(text)
return (w, m) if w else None
def _tag_key(path: Path) -> tuple[str, str] | None:
import mutagen
try:
f = mutagen.File(path)
except Exception:
return None
if not f or not f.tags:
return None
t = f.tags
def has(name: str) -> bool:
try:
return name in t
except ValueError: # a Vorbis comment refuses an MP4-style atom name
return False
key = title = None
for name in ("TKEY", "----:com.apple.iTunes:initialkey", "initialkey", "INITIALKEY"):
if has(name):
v = t[name]
v = v.text[0] if hasattr(v, "text") else v[0]
key = v.decode() if isinstance(v, bytes) else str(v)
break
for name in ("TIT2", "\xa9nam", "title", "TITLE"):
if has(name):
v = t[name]
title = str(v.text[0] if hasattr(v, "text") else v[0])
break
return (key, title or path.stem) if key else None
def folder_refs(roots: list[Path]) -> list[tuple[Path, tuple[int, str], str]]:
seen, out = set(), []
for root in roots:
for dp, dirs, files in os.walk(root):
dirs[:] = sorted(d for d in dirs if not d.startswith("."))
for name in sorted(files):
p = Path(dp) / name
if p.suffix.lower() not in AUDIO or name.startswith("."):
continue
tagged = _tag_key(p)
if not tagged or not (ref := parse_any(tagged[0])):
continue
title = re.sub(r"\.stem$", "", tagged[1].strip().lower())
if title not in seen:
seen.add(title)
out.append((p, ref, tagged[1]))
return out
def giantsteps_refs(gs: Path) -> list[tuple[Path, tuple[int, str], str]]:
out = []
for f in sorted((gs / "annotations/key").glob("*.key")):
audio = gs / "audio" / f"{f.stem}.mp3"
ref = parse_any(f.read_text()) # "C minor"
if audio.exists() and ref:
out.append((audio, ref, f.stem))
return out
def _detect(path: Path):
warnings.filterwarnings("ignore")
try:
r = key_detect.detect_key(str(path))
except Exception as ex: # an undecodable file is reported, not fatal
return None, str(ex)
return (r.wheel, r.mode, r.name, r.confidence) if r else None, None
def run(refs, label: str, verbose: bool) -> None:
with ProcessPoolExecutor() as ex:
results = list(ex.map(_detect, [p for p, _, _ in refs], chunksize=2))
rels, misses = [], []
for (path, ref, title), (det, err) in zip(refs, results):
if det is None:
print(f" could not analyse {title}: {err or 'silent / too short'}")
continue
rel = relation(det[:2], ref)
rels.append(rel)
if rel != "exact":
misses.append((title, ref, det, rel))
n = len(rels)
if not n:
print(f"{label}: nothing to score")
return
c = Counter(rels)
print(f"\n{label}: {n} tracks")
for k in WEIGHT:
print(f" {k:9s} {c[k]:4d} {100 * c[k] / n:5.1f}%")
print(f" MIREX weighted score {sum(WEIGHT[r] for r in rels) / n:.3f}")
print(f" harmonically mixable (exact + fifth + relative) {100 * (c['exact'] + c['fifth'] + c['relative']) / n:.1f}%")
if verbose:
for title, ref, det, rel in misses:
print(f" {rel:9s} ref {ref[0]}{'A' if ref[1] == 'minor' else 'B'} "
f"got {det[0]}{'A' if det[1] == 'minor' else 'B'} ({det[2]}, p={det[3]:.2f}) {title[:60]}")
if __name__ == "__main__":
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("folders", nargs="*", type=Path, help="folders of audio files carrying a key tag")
ap.add_argument("--giantsteps", type=Path, help="a downloaded giantsteps-key-dataset clone")
ap.add_argument("-v", "--verbose", action="store_true", help="list every miss")
a = ap.parse_args()
if not a.folders and not a.giantsteps:
ap.error("give --giantsteps and/or folders")
if a.giantsteps:
run(giantsteps_refs(a.giantsteps), "GiantSteps key (hand-annotated)", a.verbose)
if a.folders:
run(folder_refs(a.folders), "Key tags (agreement with another analyser)", a.verbose)
sys.exit(0)
+133
View File
@@ -0,0 +1,133 @@
"""Benchmark Auto Hotcues' structure events against Rekordbox's phrase analysis.
NOT part of `run_tests.sh`: it needs real audio and a Rekordbox library whose
tracks were analysed with phrase analysis on (the `PSSI` tag in each `.EXT`).
Read-only — nothing is saved.
python bench_structure.py # the local Rekordbox library
python bench_structure.py -v # per-track events, detected vs reference
The reference is Rekordbox's own analysis, not ground truth, and it is only
comparable on "High"-mood tracks, whose labels map onto what a DJ cues:
Intro / Up (build) / Down (breakdown) / Chorus (drop) / Outro. "Mid" tracks are
labelled Verse / Chorus / Bridge and are reported separately for that reason.
Tracks whose detected BPM is a different octave from Rekordbox's are skipped:
their bars are not the same bars.
Events are compared in bars from each side's own first downbeat:
- drop_n = start of the n-th Chorus run;
- breakdown_n = end of the n-th drop, when another drop follows;
- build_n = the Up run right before drop_n (Rekordbox's Up usually spans the
whole pre-drop groove, so this one is indicative at best);
- outro = start of the Outro.
"""
from __future__ import annotations
import os
import sys
import tempfile
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
os.environ.setdefault("KONDUKTOR_DATA_DIR", tempfile.mkdtemp(prefix="konduktor-bench-"))
import konduktor.adapters # noqa: E402,F401 — registers the drivers
from konduktor.core import grid_detect, registry, structure # noqa: E402
DROP = {1: 5, 2: 9} # PSSI kind of a Chorus, by mood (1 = High, 2 = Mid)
OUTRO = {1: 6, 2: 10}
UP = {1: 2}
def references(db: Path) -> list[dict]:
from pyrekordbox.anlz import AnlzFile
a = registry.open_library(db)
out = []
try:
st = a._store
for t in a.tracks:
path = a.audio_path(t.id)
rel = getattr(st.content(t.id), "AnalysisDataPath", None)
if not path or not path.exists() or not rel:
continue
base = st.path.parent / "share" / str(rel).lstrip("/\\")
ext = base.with_suffix(".EXT")
if not (base.is_file() and ext.is_file()):
continue
rec = {"path": str(path), "title": t.title or path.stem}
for tag in AnlzFile.parse_file(str(base)).tags:
if tag.type == "PQTZ" and len(tag.content.entries): # one-shots have none
e = tag.content.entries
rec["bpm"] = e[0].tempo / 100
rec["first_down"] = next(i for i, x in enumerate(e) if x.beat == 1)
for tag in AnlzFile.parse_file(str(ext)).tags:
if tag.type == "PSSI":
rec["mood"] = tag.content.mood
rec["phrases"] = [(x.beat, x.kind) for x in tag.content.entries]
if "phrases" in rec and "bpm" in rec:
out.append(rec)
finally:
a.close()
return out
def truth(rec: dict) -> dict[str, int]:
runs: list[tuple[int, int]] = []
for beat, kind in rec["phrases"]:
bar = round((beat - 1 - rec["first_down"]) / 4)
if not runs or runs[-1][1] != kind:
runs.append((bar, kind))
m, ev = rec["mood"], {}
drops = [i for i, (_, k) in enumerate(runs) if k == DROP.get(m)]
for n, i in enumerate(drops, start=1):
ev[f"drop_{n}"] = runs[i][0]
if n < len(drops) and i + 1 < len(runs):
ev[f"breakdown_{n}"] = runs[i + 1][0]
if m in UP and i > 0 and runs[i - 1][1] == UP[m]:
ev[f"build_{n}"] = runs[i - 1][0]
outro = [b for b, k in runs if k == OUTRO.get(m)]
if outro:
ev["outro"] = outro[0]
return ev
def main() -> int:
verbose = "-v" in sys.argv
args = [a for a in sys.argv[1:] if not a.startswith("-")]
db = Path(args[0]) if args else Path.home() / "Library/Pioneer/rekordbox/master.db"
refs = references(db)
if not refs:
print("No tracks with Rekordbox phrase analysis and reachable audio.")
return 1
for mood, label in ((1, "High"), (2, "Mid")):
stats: dict[str, list[int]] = {}
for rec in (r for r in refs if r["mood"] == mood):
g = grid_detect.detect_grid(rec["path"])
if abs(g.bpm - rec["bpm"]) >= 1:
continue # a different octave: not the same bars
st = structure.analyse(rec["path"], [(g.anchor, g.bpm)])
det = {k: (v - st.bar0) // 4 for k, v in st.events.items()}
tru = truth(rec)
if verbose:
print(f" {rec['title'][:28]:28} ref {tru}\n {'':28} got { {k: det[k] for k in tru if k in det} }")
for e, bar in tru.items():
key = e if e in ("drop_1", "drop_2", "breakdown_1", "build_1", "build_2", "outro") else e.split("_")[0] + "_n"
s = stats.setdefault(key, [0, 0, 0])
s[0] += 1
if e in det:
s[1] += det[e] == bar
s[2] += abs(det[e] - bar) <= 4
if not stats:
continue
print(f"== {label}-mood tracks")
for k in sorted(stats):
n, exact, near = stats[k]
print(f" {k:12} n={n:2} exact bar {exact:2} ({exact / n:4.0%}) within 4 bars {near:2} ({near / n:4.0%})")
return 0
if __name__ == "__main__":
sys.exit(main())
+129
View File
@@ -0,0 +1,129 @@
"""DEV ONLY — convert audio files to stem files with an UNFROZEN engine.
Not shipped, not in run_tests.sh. It exists so real stem files can be made (and
checked in Traktor) before the frozen engine and its download exist: the stem
writer (`core/stem_file.py`) runs here in the backend venv, and the separation
runs in any Python that has torch + demucs, through the engine's own one-shot
CLI — the same raw-f32 exchange the batch will use.
python dev_stems.py --engine-python ~/demucs-venv/bin/python \\
--weights ~/.cache/huggingface/hub/models--adefossez--HTDemucs-ft/snapshots/<rev> \\
[--out-dir DIR] [--device auto] FILE...
Each FILE becomes `<name>.stem.m4a` beside it (or in --out-dir); an existing
target is skipped, never overwritten.
With `--collection NML` it also does what the batch will do at its end: park
each original (`.<name>.konduktor-parked`, beside it), repoint the collection
entry that names it at the stem file (`apply_stem_swaps`), and SAVE — after
copying the collection into its `backups/` folder. Traktor must be closed.
`--keep-audio-id` keeps Traktor's analysis fingerprint on the swapped entries
(the milestone-2 check compares kept vs cleared).
"""
from __future__ import annotations
import argparse
import json
import os
import subprocess
import sys
import tempfile
import time
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
import numpy as np # noqa: E402
from konduktor.core import stem_file as sf # noqa: E402
ENGINE_DIR = Path(__file__).resolve().parents[1] / "engine"
def engine_separator(python: str, weights: str, device: str):
def separate(pcm: np.ndarray) -> list[np.ndarray]:
with tempfile.TemporaryDirectory(prefix="konduktor-dev-stems-") as d:
mix = Path(d) / "mix.f32"
np.ascontiguousarray(pcm, dtype=np.float32).tofile(mix)
cmd = [python, "-m", "konduktor_engine", "separate", "--input", str(mix),
"--samples", str(pcm.shape[1]), "--output-dir", str(Path(d) / "out"),
"--weights", weights, "--device", device]
proc = subprocess.Popen(cmd, cwd=ENGINE_DIR, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, text=True)
last = None
for line in proc.stdout:
msg = json.loads(line)
if msg["event"] == "progress":
print(f"\r separating {msg['fraction'] * 100:5.1f} %", end="", flush=True)
last = msg
proc.wait()
print()
if not last or last["event"] != "done":
raise sf.StemFileError(f"engine failed: {last}")
return [np.fromfile(Path(d) / "out" / f"{name}.f32", dtype=np.float32).reshape(2, -1)
for name in sf.DEMUCS_ORDER]
return separate
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--engine-python", required=True)
ap.add_argument("--weights", required=True)
ap.add_argument("--out-dir")
ap.add_argument("--device", default="auto")
ap.add_argument("--collection")
ap.add_argument("--keep-audio-id", action="store_true")
ap.add_argument("files", nargs="+")
args = ap.parse_args()
separate = engine_separator(args.engine_python, args.weights, args.device)
adapter = None
swaps = []
if args.collection:
if subprocess.run(["pgrep", "-x", "Traktor"], capture_output=True).returncode == 0:
print("Traktor is running — close it first (it rewrites the collection on exit).")
return 1
from konduktor.adapters.traktor.adapter import TraktorAdapter
adapter = TraktorAdapter(Path(args.collection))
adapter.store._KEEP_AUDIO_ID_ON_STEM = args.keep_audio_id
by_path = {str(adapter.audio_path(t.id)): t.id for t in adapter.tracks}
for f in (Path(x).expanduser().absolute() for x in args.files):
target = (Path(args.out_dir) if args.out_dir else f.parent) / sf.stem_target_name(f.name)
if target.exists():
print(f"skip (exists): {target}")
continue
partial = target.with_name(target.name + ".konduktor-partial")
t0 = time.time()
print(f"{f.name}")
try:
written = sf.build(f, partial, separate)
except Exception:
partial.unlink(missing_ok=True)
raise
os.replace(partial, target)
print(f" -> {target.name} {written.duration:.0f} s, {written.bit_rate // 1000} kbps x5, "
f"{written.size / 1e6:.1f} MB, {time.time() - t0:.0f} s")
if adapter is not None:
from konduktor.core.adapter import StemSwap
tid = by_path.get(str(f))
if tid is None:
print(f" (not in the collection: {f})")
continue
parked = f.with_name(f".{f.name}.konduktor-parked")
os.replace(f, parked)
swaps.append(StemSwap(tid, target, "repoint", parked, written.bit_rate,
written.duration, written.size))
if adapter is not None and swaps:
import shutil
nml = Path(args.collection)
backups = nml.parent / "backups"
backups.mkdir(exist_ok=True)
shutil.copy2(nml, backups / f"{nml.name}.{time.strftime('%Y%m%d-%H%M%S')}.dev-stems.bak")
res = adapter.apply_stem_swaps(swaps)
adapter.save()
print(f"swapped {len(res.renamed)} entries; clamped: {res.clamped or 'none'}; saved {nml}")
return 0
if __name__ == "__main__":
sys.exit(main())
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`.
@@ -0,0 +1 @@
placeholder
@@ -0,0 +1 @@
placeholder
Binary file not shown.
+71
View File
@@ -0,0 +1,71 @@
# OneLibrary fixture drive
A real OneLibrary USB export, trimmed to the size of a test fixture. This is the
drive `test_onelibrary_adapter.py` runs against, so the suite needs no USB stick
plugged in and gives the same answer on every machine.
Produced by rekordbox 7.2.18 exporting a two-track playlist to an exFAT stick.
**Nothing in the database was written or edited by Konduktor** — it is the bytes
rekordbox itself wrote, which is the whole point of a fixture whose job is to
prove we read the real format correctly.
## What was changed
Only the analysis files, and only by deleting whole tags:
| File | Original | Here |
|---|---|---|
| `ANLZ0000.DAT` | 4,972 B | 2,812 B |
| `ANLZ0000.EXT` | 85,602 B | 732 B |
`PPTH`, `PQTZ`, `PCOB` and `PCO2` — the path, the beatgrid and the two cue lists,
i.e. everything the adapter reads — are kept **byte for byte**. The waveform tags
(`PWAV`, `PWV2`–`PWV5`) are dropped, which is where ~99% of the `.EXT` went, and
the `.2EX` files are omitted entirely.
The trim is byte-level tag surgery, rewriting only the `PMAI` header's file
length: `pyrekordbox` cannot rebuild a file containing cue tags, so re-serialising
was not an option.
The two `.mp3` files are **placeholders**, not audio. The adapter resolves paths
and never opens them; carrying 12 MB of demo tracks in the repo to prove that
would be silly.
## What is in it
- 2 tracks, one of which (`Demo Track 1`) carries a **flexible multi-tempo grid**
(128.00 BPM to 60 s, then 90.00 BPM) — the awkward case, deliberately.
- 4 hot cues plus a looped memory cue on that track, including one on pad **D**,
which is the cue that lives only in the `.EXT` and that a reader looking at the
`.DAT` alone would lose.
- 1 playlist, `demos`, holding both tracks in order.
`Demo Track 1`'s title still reads `[KONDUKTOR WROTE THIS]` because the grid and
title were written into `master.db` by Konduktor before the export. That is
incidental to the fixture, but it does record that the whole chain — Konduktor →
`master.db` → rekordbox's OneLibrary export → this file — preserved them.
## schema.sql
The complete `CREATE TABLE` set for a OneLibrary database, all 22 tables,
extracted from Traktor Pro 4.5's binary, which embeds the DDL it uses to create
one. AlphaTheta publishes no specification, so this is the closest thing to one:
a second vendor's independent implementation of the same schema. It was verified
by building an empty database from it and having `pyrekordbox`'s ORM — a third
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`.
+208
View File
@@ -0,0 +1,208 @@
CREATE TABLE IF NOT EXISTS "content" (
"content_id" integer primary key not null,
"title" varchar,
"titleForSearch" varchar,
"subtitle" varchar,
"bpmx100" int,
"length" int,
"trackNo" int,
"discNo" int,
"artist_id_artist" int,
"artist_id_remixer" int,
"artist_id_originalArtist" int,
"artist_id_composer" int,
"artist_id_lyricist" int,
"album_id" int,
"genre_id" int,
"label_id" int,
"key_id" int,
"color_id" int,
"image_id" int,
"djComment" varchar,
"rating" int,
"releaseYear" int,
"releaseDate" varchar,
"dateAdded" varchar,
"dateCreated" varchar,
"path" varchar,
"fileName" varchar,
"fileSize" int,
"fileType" int,
"bitrate" int,
"bitDepth" int,
"samplingRate" int,
"isrc" varchar,
"djPlayCount" int,
"isHotCueAutoLoadOn" int,
"isKuvoDeliverStatusOn" int,
"kuvoDeliveryComment" varchar,
"masterDbId" int not null,
"masterContentId" int not null,
"analysisDataFilePath" varchar,
"analysedBits" int,
"contentLink" int,
"hasModified" int,
"cueUpdateCount" int,
"analysisDataUpdateCount" int,
"informationUpdateCount" int
);
CREATE TABLE IF NOT EXISTS "genre" (
"genre_id" integer primary key not null,
"name" varchar
);
CREATE TABLE IF NOT EXISTS "artist" (
"artist_id" integer primary key not null,
"name" varchar,
"nameForSearch" varchar
);
CREATE TABLE IF NOT EXISTS "album" (
"album_id" integer primary key not null,
"name" varchar not null,
"artist_id" int,
"image_id" int,
"isComplation" int,
"nameForSearch" varchar
);
CREATE TABLE IF NOT EXISTS "label" (
"label_id" integer primary key not null,
"name" varchar
);
CREATE TABLE IF NOT EXISTS "key" (
"key_id" integer primary key not null,
"name" varchar
);
CREATE TABLE IF NOT EXISTS "color" (
"color_id" integer primary key not null,
"name" varchar
);
CREATE TABLE IF NOT EXISTS "playlist" (
"playlist_id" integer primary key not null,
"sequenceNo" int,
"name" varchar,
"image_id" int,
"attribute" int,
"playlist_id_parent" int
);
CREATE TABLE IF NOT EXISTS "playlist_content" (
"playlist_id" int not null,
"content_id" int not null,
"sequenceNo" int not null
);
CREATE TABLE IF NOT EXISTS "history" (
"history_id" integer primary key not null,
"sequenceNo" int,
"name" varchar,
"attribute" int,
"history_id_parent" int
);
CREATE TABLE IF NOT EXISTS "history_content" (
"history_id" int,
"content_id" int,
"sequenceNo" int
);
CREATE TABLE IF NOT EXISTS "image" (
"image_id" integer primary key not null,
"path" varchar
);
CREATE TABLE IF NOT EXISTS "menuItem" (
"menuItem_id" integer primary key not null,
"kind" int,
"name" varchar
);
CREATE TABLE IF NOT EXISTS "category" (
"category_id" integer primary key not null,
"menuItem_id" int,
"sequenceNo" int,
"isVisible" int
);
CREATE TABLE IF NOT EXISTS "sort" (
"sort_id" integer primary key not null,
"menuItem_id" int,
"sequenceNo" int,
"isVisible" int,
"isSelectedAsSubColumn" int
);
CREATE TABLE IF NOT EXISTS "property" (
"deviceName" varchar,
"dbVersion" varchar,
"numberOfContents" int,
"createdDate" varchar,
"backGroundColorType" int,
"myTagMasterDBID" int
);
CREATE TABLE IF NOT EXISTS "hotCueBankList" (
"hotCueBankList_id" integer primary key not null,
"sequenceNo" int,
"name" varchar,
"image_id" int,
"attribute" int,
"hotCueBankList_id_parent" int
);
CREATE TABLE IF NOT EXISTS "hotCueBankList_cue" (
"hotCueBankList_id" int not null,
"cue_id" int not null,
"sequenceNo" int not null
);
CREATE TABLE IF NOT EXISTS "cue" (
"cue_id" integer primary key not null,
"content_id" int not null,
"kind" int not null,
"colorTableIndex" int,
"cueComment" varchar,
"isActiveLoop" int not null,
"beatLoopNumerator" int,
"beatLoopDenominator" int,
"inUsec" int not null,
"outUsec" int,
"in150FramePerSec" int not null,
"out150FramePerSec" int,
"inMpegFrameNumber" int,
"outMpegFrameNumber" int,
"inMpegAbs" int,
"outMpegAbs" int,
"inDecodingStartFramePosition" int,
"outDecodingStartFramePosition" int,
"inFileOffsetInBlock" int,
"outFileOffsetInBlock" int,
"inNumberOfSampleInBlock" int,
"outNumberOfSampleInBlock" int
);
CREATE TABLE IF NOT EXISTS "recommendedLike" (
"content_id_1" int not null,
"content_id_2" int not null,
"rating" int,
"createdDate" datetime
);
CREATE TABLE IF NOT EXISTS "myTag" (
"myTag_id" integer primary key not null,
"sequenceNo" int,
"name" varchar,
"attribute" int,
"myTag_id_parent" int
);
CREATE TABLE IF NOT EXISTS "myTag_content" (
"myTag_id" int not null,
"content_id" int not null
);
+81
View File
@@ -0,0 +1,81 @@
-- rekordbox's own scaffolding rows for a OneLibrary drive: the browse menu
-- items, the categories and sort columns a player offers, and the colour
-- palette. Extracted verbatim from fixtures/onelibrary/PIONEER/rekordbox/
-- exportLibrary.db (a real rekordbox 7.2.18 export). No user data, no
-- machine identity. rekordbox writes these on every export, so a drive without
-- them is not a shape any player has been tested against.
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (1, 128, 'GENRE');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (2, 129, 'ARTIST');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (3, 130, 'ALBUM');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (4, 131, 'TRACK');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (5, 133, 'BPM');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (6, 134, 'RATING');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (7, 135, 'YEAR');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (8, 136, 'REMIXER');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (9, 137, 'LABEL');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (10, 138, 'ORIGINAL ARTIST');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (11, 139, 'KEY');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (12, 141, 'CUE');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (13, 142, 'COLOR');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (14, 146, 'TIME');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (15, 147, 'BITRATE');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (16, 148, 'FILE NAME');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (17, 132, 'PLAYLIST');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (18, 152, 'HOT CUE BANK');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (19, 149, 'HISTORY');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (20, 145, 'SEARCH');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (21, 150, 'COMMENTS');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (22, 140, 'DATE ADDED');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (23, 151, 'DJ PLAY COUNT');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (24, 144, 'FOLDER');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (25, 161, 'DEFAULT');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (26, 162, 'ALPHABET');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (27, 170, 'MATCHING');
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (1, 1, 0, 0);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (2, 2, 1, 1);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (3, 3, 2, 1);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (4, 4, 3, 1);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (5, 17, 5, 1);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (6, 5, 0, 0);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (7, 6, 0, 0);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (8, 7, 0, 0);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (9, 8, 0, 0);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (10, 9, 0, 0);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (11, 10, 0, 0);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (12, 11, 4, 1);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (15, 13, 0, 0);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (17, 24, 9, 1);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (18, 20, 7, 1);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (19, 14, 0, 0);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (20, 15, 0, 0);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (21, 16, 0, 0);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (22, 19, 6, 1);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (23, 18, 0, 0);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (26, 27, 8, 1);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (27, 22, 10, 1);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (0, 25, 1, 1, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (1, 26, 2, 1, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (2, 2, 3, 1, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (3, 3, 4, 1, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (4, 5, 5, 1, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (5, 6, 6, 1, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (6, 1, 0, 0, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (7, 21, 0, 0, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (8, 14, 0, 0, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (9, 8, 0, 0, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (10, 9, 0, 0, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (11, 10, 0, 0, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (12, 11, 7, 1, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (13, 15, 0, 0, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (15, 13, 0, 0, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (16, 23, 0, 0, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (17, 22, 0, 0, 0);
INSERT INTO "color" ("color_id", "name") VALUES (1, 'Pink');
INSERT INTO "color" ("color_id", "name") VALUES (2, 'Red');
INSERT INTO "color" ("color_id", "name") VALUES (3, 'Orange');
INSERT INTO "color" ("color_id", "name") VALUES (4, 'Yellow');
INSERT INTO "color" ("color_id", "name") VALUES (5, 'Green');
INSERT INTO "color" ("color_id", "name") VALUES (6, 'Aqua');
INSERT INTO "color" ("color_id", "name") VALUES (7, 'Blue');
INSERT INTO "color" ("color_id", "name") VALUES (8, 'Purple');
+20
View File
@@ -0,0 +1,20 @@
# `master.db` schema
`schema.sql` is the DDL of a real Rekordbox 7 library — 47 tables and 288
indexes — used by the Rekordbox **exporter** to create a database from nothing.
**It contains no user data.** Table and index definitions only, extracted with
`SELECT sql FROM sqlite_master`.
## Why this, and not pyrekordbox's models
`Base.metadata.create_all()` looked like the obvious way to build the schema, and
it is wrong in two ways that matter:
- it models **37 tables**, not 47;
- it marks columns **NOT NULL that Rekordbox leaves nullable**. `agentRegistry
.id_1` is the one that caught it: a real library has NULL there, and a database
built from the ORM refuses the row Rekordbox itself writes.
So the DDL is the authority and the models are not. Regenerate with the snippet
in the export handoff if a future Rekordbox version changes the schema.
@@ -0,0 +1,20 @@
# Empty rekordbox device library (`export.pdb`, `exportExt.pdb`)
The legacy "Device Library" a Pioneer USB stick carries — the one Rekordbox
lists as **Device Library** and older players (CDJ-2000NXS2, many XDJs) read —
exactly as **Rekordbox 7.2.18 wrote it for an empty stick**: it creates both
files the first time it mounts a drive that has none.
They are the starting point of the "Rekordbox Export" target
(`adapters/rekordbox/device_export.py`), for the same reason `seed.sql` exists:
the format has fixed tables that are the same on every stick and cannot be
derived — the colour list (table 6), the browse columns (16), two menu tables
(17, 18) and a history header (19) in `export.pdb`; rekordbox's default MyTag
names in `exportExt.pdb`. Every data table (tracks, artists, albums, genres,
labels, keys, playlists, artwork) holds only its header page, with a blank page
reserved after it for its first rows — the allocation rule the writer follows.
**No user data**: the only strings are colour names, column names, the default
MyTag names, the creation date (`2026-09-27`, rewritten on every export) and the
database version `1000`. Pages 13-14 and 33-38 are byte-identical to the same
pages of a real rekordbox device export of eight tracks.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,62 @@
{
"note": "Rows from a real rekordbox 7.2.18 device export (export.pdb), for byte-level tests. Only the Loopmasters demo tracks and generic key names; see README.md. The track row's u3/u4 (the exporting computer's rekordbox masterDbId) are zeroed.",
"track_row_demo_track_2": "2400200000070c0044ac000000000000f6304e0011a8a6040000000000000000000000000000000001000000000000004001000000000000e02e000000000000000000000100000002000000000000000000100080002900000001000300880089008a008c008e00910092009500980099009a00a500a600a700a800d400df00fd000a010b011c0103030531053107313103074f4e074f4e030317323031382d30352d3235030303592f50494f4e4545522f555342414e4c5a2f503035332f30303031443231462f414e4c5a303030302e44415417323032362d30392d31373d547261636b73206279207777772e6c6f6f706d6173746572732e636f6d1b44656d6f20547261636b2032032344656d6f20547261636b20322e6d7033692f436f6e74656e74732f4c6f6f706d6173746572732f556e6b6e6f776e416c62756d2f44656d6f20547261636b20322e6d7033",
"track_row_demo_track_2_fields": {
"subtype": 36,
"index_shift": 32,
"bitmask": 788224,
"sample_rate": 44100,
"composer_id": 0,
"file_size": 5124342,
"u2": 78030865,
"u3": 0,
"u4": 0,
"artwork_id": 0,
"key_id": 0,
"original_artist_id": 0,
"label_id": 1,
"remixer_id": 0,
"bitrate": 320,
"track_number": 0,
"tempo": 12000,
"genre_id": 0,
"album_id": 0,
"artist_id": 1,
"id": 2,
"disc_number": 0,
"play_count": 0,
"year": 0,
"sample_depth": 16,
"duration": 128,
"u5": 41,
"color_id": 0,
"rating": 0,
"u6": 1,
"u7": 3,
"isrc": "",
"texter": "",
"unknown_string_2": "1",
"unknown_string_3": "1",
"unknown_string_4": "11",
"message": "",
"kuvo_public": "ON",
"autoload_hotcues": "ON",
"unknown_string_5": "",
"unknown_string_6": "",
"date_added": "2018-05-25",
"release_date": "",
"mix_name": "",
"unknown_string_7": "",
"analyze_path": "/PIONEER/USBANLZ/P053/0001D21F/ANLZ0000.DAT",
"analyze_date": "2026-09-17",
"comment": "Tracks by www.loopmasters.com",
"title": "Demo Track 2",
"unknown_string_8": "",
"filename": "Demo Track 2.mp3",
"file_path": "/Contents/Loopmasters/UnknownAlbum/Demo Track 2.mp3"
},
"artist_row_loopmasters": "6000000001000000030a194c6f6f706d617374657273000000000000",
"playlist_row_demos": "00000000000000000100000001000000000000000d64656d6f730000",
"keys_page_index": 12,
"keys_page": "000000000c0000000500000034000000140000000000000002400024b80f1800010001000000000001000000010000000941626d020000000200000007456d0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000Line truncated
}
+344
View File
@@ -0,0 +1,344 @@
-- master.db schema, extracted from a real Rekordbox 7 library.
--
-- NOT generated from pyrekordbox's SQLAlchemy models: `create_all()` marks
-- columns NOT NULL that Rekordbox itself leaves nullable (agentRegistry.id_1
-- is the one that caught this), so a database built from the ORM rejects rows
-- Rekordbox writes every day. The DDL is the authority; the models are not.
--
-- Contains no user data — table and index definitions only.
CREATE TABLE `agentNotification` (`ID` BIGINT PRIMARY KEY, `graphic_area` TINYINT(1) DEFAULT 0, `text_area` TINYINT(1) DEFAULT 0, `os_notification` TINYINT(1) DEFAULT 0, `start_datetime` DATETIME DEFAULT NULL, `end_datetime` DATETIME DEFAULT NULL, `display_datetime` DATETIME DEFAULT NULL, `interval` INTEGER DEFAULT 0, `category` VARCHAR(255) DEFAULT NULL, `category_color` VARCHAR(255) DEFAULT NULL, `title` TEXT DEFAULT NULL, `description` TEXT DEFAULT NULL, `url` VARCHAR(255) DEFAULT NULL, `image` VARCHAR(255) DEFAULT NULL, `image_path` VARCHAR(255) DEFAULT NULL, `read_status` INTEGER DEFAULT 0, `last_displayed_datetime` DATETIME DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `agentNotificationLog` (`ID` INTEGER PRIMARY KEY AUTOINCREMENT, `gigya_uid` VARCHAR(255) DEFAULT NULL, `event_date` INTEGER DEFAULT NULL, `reported_datetime` DATETIME DEFAULT NULL, `kind` INTEGER DEFAULT NULL, `value` INTEGER DEFAULT NULL, `notification_id` BIGINT DEFAULT NULL, `link` VARCHAR(255) DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `agentRegistry` (`registry_id` VARCHAR(255) PRIMARY KEY, `id_1` VARCHAR(255) DEFAULT NULL, `id_2` VARCHAR(255) DEFAULT NULL, `int_1` BIGINT DEFAULT NULL, `int_2` BIGINT DEFAULT NULL, `str_1` VARCHAR(255) DEFAULT NULL, `str_2` VARCHAR(255) DEFAULT NULL, `date_1` DATETIME DEFAULT NULL, `date_2` DATETIME DEFAULT NULL, `text_1` TEXT DEFAULT NULL, `text_2` TEXT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `cloudAgentRegistry` (`ID` VARCHAR(255) PRIMARY KEY, `int_1` BIGINT DEFAULT NULL, `int_2` BIGINT DEFAULT NULL, `str_1` VARCHAR(255) DEFAULT NULL, `str_2` VARCHAR(255) DEFAULT NULL, `date_1` DATETIME DEFAULT NULL, `date_2` DATETIME DEFAULT NULL, `text_1` TEXT DEFAULT NULL, `text_2` TEXT DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `contentActiveCensor` (`ID` VARCHAR(255) PRIMARY KEY, `ContentID` VARCHAR(255) DEFAULT NULL, `ActiveCensors` TEXT DEFAULT NULL, `rb_activecensor_count` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `contentCue` (`ID` VARCHAR(255) PRIMARY KEY, `ContentID` VARCHAR(255) DEFAULT NULL, `Cues` TEXT DEFAULT NULL, `rb_cue_count` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `contentFile` (`ID` VARCHAR(255) PRIMARY KEY, `ContentID` VARCHAR(255) DEFAULT NULL, `Path` VARCHAR(255) DEFAULT NULL, `Hash` VARCHAR(255) DEFAULT NULL, `Size` INTEGER DEFAULT NULL, `rb_local_path` VARCHAR(255) DEFAULT NULL, `rb_insync_hash` VARCHAR(255) DEFAULT NULL, `rb_insync_local_usn` BIGINT DEFAULT NULL, `rb_file_hash_dirty` INTEGER DEFAULT 0, `rb_local_file_status` INTEGER DEFAULT 0, `rb_in_progress` TINYINT(1) DEFAULT 0, `rb_process_type` INTEGER DEFAULT 0, `rb_temp_path` VARCHAR(255) DEFAULT NULL, `rb_priority` INTEGER DEFAULT 50, `rb_file_size_dirty` INTEGER DEFAULT 0, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdActiveCensor` (`ID` VARCHAR(255) PRIMARY KEY, `ContentID` VARCHAR(255) DEFAULT NULL, `InMsec` INTEGER DEFAULT NULL, `OutMsec` INTEGER DEFAULT NULL, `Info` INTEGER DEFAULT NULL, `ParameterList` TEXT DEFAULT NULL, `ContentUUID` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdAlbum` (`ID` VARCHAR(255) PRIMARY KEY, `Name` VARCHAR(255) DEFAULT NULL, `AlbumArtistID` VARCHAR(255) DEFAULT NULL, `ImagePath` VARCHAR(255) DEFAULT NULL, `Compilation` INTEGER DEFAULT NULL, `SearchStr` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdArtist` (`ID` VARCHAR(255) PRIMARY KEY, `Name` VARCHAR(255) DEFAULT NULL, `SearchStr` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdCategory` (`ID` VARCHAR(255) PRIMARY KEY, `MenuItemID` VARCHAR(255) DEFAULT NULL, `Seq` INTEGER DEFAULT NULL, `Disable` INTEGER DEFAULT NULL, `InfoOrder` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdCloudExportPlaylist` (`ID` VARCHAR(255) PRIMARY KEY, `Seq` INTEGER DEFAULT NULL, `Name` VARCHAR(255) DEFAULT NULL, `ImagePath` VARCHAR(255) DEFAULT NULL, `Attribute` INTEGER DEFAULT NULL, `ParentID` VARCHAR(255) DEFAULT NULL, `SmartList` TEXT DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdCloudExportSongPlaylist` (`ID` VARCHAR(255) PRIMARY KEY, `CloudExportPlaylistID` VARCHAR(255) DEFAULT NULL, `ContentID` VARCHAR(255) DEFAULT NULL, `TrackNo` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdCloudFilterPlaylist` (`ID` VARCHAR(255) PRIMARY KEY, `PlaylistUUID` VARCHAR(255) DEFAULT NULL, `Seq` INTEGER DEFAULT 0, `ParentID` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdCloudProperty` (`ID` VARCHAR(255) PRIMARY KEY, `Reserved1` TEXT DEFAULT NULL, `Reserved2` TEXT DEFAULT NULL, `Reserved3` TEXT DEFAULT NULL, `Reserved4` TEXT DEFAULT NULL, `Reserved5` TEXT DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdColor` (`ID` VARCHAR(255) PRIMARY KEY, `ColorCode` INTEGER DEFAULT NULL, `SortKey` INTEGER DEFAULT NULL, `Commnt` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdContent` (`ID` VARCHAR(255) PRIMARY KEY, `FolderPath` VARCHAR(255) DEFAULT NULL, `FileNameL` VARCHAR(255) DEFAULT NULL, `FileNameS` VARCHAR(255) DEFAULT NULL, `Title` VARCHAR(255) DEFAULT NULL, `ArtistID` VARCHAR(255) DEFAULT NULL, `AlbumID` VARCHAR(255) DEFAULT NULL, `GenreID` VARCHAR(255) DEFAULT NULL, `BPM` INTEGER DEFAULT NULL, `Length` INTEGER DEFAULT NULL, `TrackNo` INTEGER DEFAULT NULL, `BitRate` INTEGER DEFAULT NULL, `BitDepth` INTEGER DEFAULT NULL, `Commnt` TEXT DEFAULT NULL, `FileType` INTEGER DEFAULT NULL, `Rating` INTEGER DEFAULT NULL, `ReleaseYear` INTEGER DEFAULT NULL, `RemixerID` VARCHAR(255) DEFAULT NULL, `LabelID` VARCHAR(255) DEFAULT NULL, `OrgArtistID` VARCHAR(255) DEFAULT NULL, `KeyID` VARCHAR(255) DEFAULT NULL, `StockDate` VARCHAR(255) DEFAULT NULL, `ColorID` VARCHAR(255) DEFAULT NULL, `DJPlayCount` INTEGER DEFAULT NULL, `ImagePath` VARCHAR(255) DEFAULT NULL, `MasterDBID` VARCHAR(255) DEFAULT NULL, `MasterSongID` VARCHAR(255) DEFAULT NULL, `AnalysisDataPath` VARCHAR(255) DEFAULT NULL, `SearchStr` VARCHAR(255) DEFAULT NULL, `FileSize` INTEGER DEFAULT NULL, `DiscNo` INTEGER DEFAULT NULL, `ComposerID` VARCHAR(255) DEFAULT NULL, `Subtitle` VARCHAR(255) DEFAULT NULL, `SampleRate` INTEGER DEFAULT NULL, `DisableQuantize` INTEGER DEFAULT NULL, `Analysed` INTEGER DEFAULT NULL, `ReleaseDate` VARCHAR(255) DEFAULT NULL, `DateCreated` VARCHAR(255) DEFAULT NULL, `ContentLink` INTEGER DEFAULT NULL, `Tag` VARCHAR(255) DEFAULT NULL, `ModifiedByRBM` VARCHAR(255) DEFAULT NULL, `HotCueAutoLoad` VARCHAR(255) DEFAULT NULL, `DeliveryControl` VARCHAR(255) DEFAULT NULL, `DeliveryComment` VARCHAR(255) DEFAULT NULL, `CueUpdated` VARCHAR(255) DEFAULT NULL, `AnalysisUpdated` VARCHAR(255) DEFAULT NULL, `TrackInfoUpdated` VARCHAR(255) DEFAULT NULL, `Lyricist` VARCHAR(255) DEFAULT NULL, `ISRC` VARCHAR(255) DEFAULT NULL, `SamplerTrackInfo` INTEGER DEFAULT NULL, `SamplerPlayOffset` INTEGER DEFAULT NULL, `SamplerGain` FLOAT DEFAULT NULL, `VideoAssociate` VARCHAR(255) DEFAULT NULL, `LyricStatus` INTEGER DEFAULT NULL, `ServiceID` INTEGER DEFAULT NULL, `OrgFolderPath` VARCHAR(255) DEFAULT NULL, `Reserved1` TEXT DEFAULT NULL, `Reserved2` TEXT DEFAULT NULL, `Reserved3` TEXT DEFAULT NULL, `Reserved4` TEXT DEFAULT NULL, `ExtInfo` TEXT DEFAULT NULL, `rb_file_id` VARCHAR(255) DEFAULT NULL, `DeviceID` VARCHAR(255) DEFAULT NULL, `rb_LocalFolderPath` VARCHAR(255) DEFAULT NULL, `SrcID` VARCHAR(255) DEFAULT NULL, `SrcTitle` VARCHAR(255) DEFAULT NULL, `SrcArtistName` VARCHAR(255) DEFAULT NULL, `SrcAlbumName` VARCHAR(255) DEFAULT NULL, `SrcLength` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdCue` (`ID` VARCHAR(255) PRIMARY KEY, `ContentID` VARCHAR(255) DEFAULT NULL, `InMsec` INTEGER DEFAULT NULL, `InFrame` INTEGER DEFAULT NULL, `InMpegFrame` INTEGER DEFAULT NULL, `InMpegAbs` INTEGER DEFAULT NULL, `OutMsec` INTEGER DEFAULT NULL, `OutFrame` INTEGER DEFAULT NULL, `OutMpegFrame` INTEGER DEFAULT NULL, `OutMpegAbs` INTEGER DEFAULT NULL, `Kind` INTEGER DEFAULT NULL, `Color` INTEGER DEFAULT NULL, `ColorTableIndex` INTEGER DEFAULT NULL, `ActiveLoop` INTEGER DEFAULT NULL, `Comment` VARCHAR(255) DEFAULT NULL, `BeatLoopSize` INTEGER DEFAULT NULL, `CueMicrosec` INTEGER DEFAULT NULL, `InPointSeekInfo` VARCHAR(255) DEFAULT NULL, `OutPointSeekInfo` VARCHAR(255) DEFAULT NULL, `ContentUUID` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdDevice` (`ID` VARCHAR(255) PRIMARY KEY, `MasterDBID` VARCHAR(255) DEFAULT NULL, `Name` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdGenre` (`ID` VARCHAR(255) PRIMARY KEY, `Name` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdHistory` (`ID` VARCHAR(255) PRIMARY KEY, `Seq` INTEGER DEFAULT NULL, `Name` VARCHAR(255) DEFAULT NULL, `Attribute` INTEGER DEFAULT NULL, `ParentID` VARCHAR(255) DEFAULT NULL, `DateCreated` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdHotCueBanklist` (`ID` VARCHAR(255) PRIMARY KEY, `Seq` INTEGER DEFAULT NULL, `Name` VARCHAR(255) DEFAULT NULL, `ImagePath` VARCHAR(255) DEFAULT NULL, `Attribute` INTEGER DEFAULT NULL, `ParentID` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdKey` (`ID` VARCHAR(255) PRIMARY KEY, `ScaleName` VARCHAR(255) DEFAULT NULL, `Seq` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdLabel` (`ID` VARCHAR(255) PRIMARY KEY, `Name` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdMenuItems` (`ID` VARCHAR(255) PRIMARY KEY, `Class` INTEGER DEFAULT NULL, `Name` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdMixerParam` (`ID` VARCHAR(255) PRIMARY KEY, `ContentID` VARCHAR(255) DEFAULT NULL, `GainHigh` INTEGER DEFAULT NULL, `GainLow` INTEGER DEFAULT NULL, `PeakHigh` INTEGER DEFAULT NULL, `PeakLow` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdMyTag` (`ID` VARCHAR(255) PRIMARY KEY, `Seq` INTEGER DEFAULT NULL, `Name` VARCHAR(255) DEFAULT NULL, `Attribute` INTEGER DEFAULT NULL, `ParentID` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdPlaylist` (`ID` VARCHAR(255) PRIMARY KEY, `Seq` INTEGER DEFAULT NULL, `Name` VARCHAR(255) DEFAULT NULL, `ImagePath` VARCHAR(255) DEFAULT NULL, `Attribute` INTEGER DEFAULT NULL, `ParentID` VARCHAR(255) DEFAULT NULL, `SmartList` TEXT DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdProperty` (`DBID` VARCHAR(255) PRIMARY KEY, `DBVersion` VARCHAR(255) DEFAULT NULL, `BaseDBDrive` VARCHAR(255) DEFAULT NULL, `CurrentDBDrive` VARCHAR(255) DEFAULT NULL, `DeviceID` VARCHAR(255) DEFAULT NULL, `Reserved1` TEXT DEFAULT NULL, `Reserved2` TEXT DEFAULT NULL, `Reserved3` TEXT DEFAULT NULL, `Reserved4` TEXT DEFAULT NULL, `Reserved5` TEXT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdRecommendLike` (`ID` VARCHAR(255) PRIMARY KEY, `ContentID1` VARCHAR(255) DEFAULT NULL, `ContentID2` VARCHAR(255) DEFAULT NULL, `LikeRate` INTEGER DEFAULT NULL, `DataCreatedH` INTEGER DEFAULT NULL, `DataCreatedL` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdRelatedTracks` (`ID` VARCHAR(255) PRIMARY KEY, `Seq` INTEGER DEFAULT NULL, `Name` VARCHAR(255) DEFAULT NULL, `Attribute` INTEGER DEFAULT NULL, `ParentID` VARCHAR(255) DEFAULT NULL, `Criteria` TEXT DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdSampler` (`ID` VARCHAR(255) PRIMARY KEY, `Seq` INTEGER DEFAULT NULL, `Name` VARCHAR(255) DEFAULT NULL, `Attribute` INTEGER DEFAULT NULL, `ParentID` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdSharedPlaylist` (`ID` VARCHAR(255) PRIMARY KEY, `data_selection` TINYINT DEFAULT 0, `edited_at` DATETIME DEFAULT NULL, `int_1` INTEGER DEFAULT NULL, `int_2` INTEGER DEFAULT NULL, `str_1` VARCHAR(255) DEFAULT NULL, `str_2` VARCHAR(255) DEFAULT NULL, `text_1` TEXT DEFAULT NULL, `text_2` TEXT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdSharedPlaylistUser` (`ID` VARCHAR(255) NOT NULL, `member_type` TINYINT DEFAULT 0, `member_id` VARCHAR(255) NOT NULL, `status` TINYINT DEFAULT 0, `invitation_expires_at` DATETIME DEFAULT NULL, `invited_at` DATETIME DEFAULT NULL, `joined_at` DATETIME DEFAULT NULL, `int_1` INTEGER DEFAULT NULL, `int_2` INTEGER DEFAULT NULL, `str_1` VARCHAR(255) DEFAULT NULL, `str_2` VARCHAR(255) DEFAULT NULL, `text_1` TEXT DEFAULT NULL, `text_2` TEXT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL, PRIMARY KEY (`ID`, `member_id`));
CREATE TABLE `djmdSongHistory` (`ID` VARCHAR(255) PRIMARY KEY, `HistoryID` VARCHAR(255) DEFAULT NULL, `ContentID` VARCHAR(255) DEFAULT NULL, `TrackNo` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdSongHotCueBanklist` (`ID` VARCHAR(255) PRIMARY KEY, `HotCueBanklistID` VARCHAR(255) DEFAULT NULL, `ContentID` VARCHAR(255) DEFAULT NULL, `TrackNo` INTEGER DEFAULT NULL, `CueID` VARCHAR(255) DEFAULT NULL, `InMsec` INTEGER DEFAULT NULL, `InFrame` INTEGER DEFAULT NULL, `InMpegFrame` INTEGER DEFAULT NULL, `InMpegAbs` INTEGER DEFAULT NULL, `OutMsec` INTEGER DEFAULT NULL, `OutFrame` INTEGER DEFAULT NULL, `OutMpegFrame` INTEGER DEFAULT NULL, `OutMpegAbs` INTEGER DEFAULT NULL, `Color` INTEGER DEFAULT NULL, `ColorTableIndex` INTEGER DEFAULT NULL, `ActiveLoop` INTEGER DEFAULT NULL, `Comment` VARCHAR(255) DEFAULT NULL, `BeatLoopSize` INTEGER DEFAULT NULL, `CueMicrosec` INTEGER DEFAULT NULL, `InPointSeekInfo` VARCHAR(255) DEFAULT NULL, `OutPointSeekInfo` VARCHAR(255) DEFAULT NULL, `HotCueBanklistUUID` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdSongMyTag` (`ID` VARCHAR(255) PRIMARY KEY, `MyTagID` VARCHAR(255) DEFAULT NULL, `ContentID` VARCHAR(255) DEFAULT NULL, `TrackNo` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdSongPlaylist` (`ID` VARCHAR(255) PRIMARY KEY, `PlaylistID` VARCHAR(255) DEFAULT NULL, `ContentID` VARCHAR(255) DEFAULT NULL, `TrackNo` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdSongRelatedTracks` (`ID` VARCHAR(255) PRIMARY KEY, `RelatedTracksID` VARCHAR(255) DEFAULT NULL, `ContentID` VARCHAR(255) DEFAULT NULL, `TrackNo` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdSongRequestList` (`ID` VARCHAR(255) PRIMARY KEY, `ContentID` VARCHAR(255) DEFAULT NULL, `TrackNo` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdSongSampler` (`ID` VARCHAR(255) PRIMARY KEY, `SamplerID` VARCHAR(255) DEFAULT NULL, `ContentID` VARCHAR(255) DEFAULT NULL, `TrackNo` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdSongTagList` (`ID` VARCHAR(255) PRIMARY KEY, `ContentID` VARCHAR(255) DEFAULT NULL, `TrackNo` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `djmdSort` (`ID` VARCHAR(255) PRIMARY KEY, `MenuItemID` VARCHAR(255) DEFAULT NULL, `Seq` INTEGER DEFAULT NULL, `Disable` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `hotCueBanklistCue` (`ID` VARCHAR(255) PRIMARY KEY, `HotCueBanklistID` VARCHAR(255) DEFAULT NULL, `Cues` TEXT DEFAULT NULL, `rb_cue_count` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `imageFile` (`ID` VARCHAR(255) PRIMARY KEY, `TableName` VARCHAR(255) DEFAULT NULL, `TargetUUID` VARCHAR(255) DEFAULT NULL, `TargetID` VARCHAR(255) DEFAULT NULL, `Path` VARCHAR(255) DEFAULT NULL, `Hash` VARCHAR(255) DEFAULT NULL, `Size` INTEGER DEFAULT NULL, `rb_local_path` VARCHAR(255) DEFAULT NULL, `rb_insync_hash` VARCHAR(255) DEFAULT NULL, `rb_insync_local_usn` BIGINT DEFAULT NULL, `rb_file_hash_dirty` INTEGER DEFAULT 0, `rb_local_file_status` INTEGER DEFAULT 0, `rb_in_progress` TINYINT(1) DEFAULT 0, `rb_process_type` INTEGER DEFAULT 0, `rb_temp_path` VARCHAR(255) DEFAULT NULL, `rb_priority` INTEGER DEFAULT 50, `rb_file_size_dirty` INTEGER DEFAULT 0, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `settingFile` (`ID` VARCHAR(255) PRIMARY KEY, `Path` VARCHAR(255) DEFAULT NULL, `Hash` VARCHAR(255) DEFAULT NULL, `Size` INTEGER DEFAULT NULL, `rb_local_path` VARCHAR(255) DEFAULT NULL, `rb_insync_hash` VARCHAR(255) DEFAULT NULL, `rb_insync_local_usn` BIGINT DEFAULT NULL, `rb_file_hash_dirty` INTEGER DEFAULT 0, `rb_file_size_dirty` INTEGER DEFAULT 0, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `uuidIDMap` (`ID` VARCHAR(255) PRIMARY KEY, `TableName` VARCHAR(255) DEFAULT NULL, `TargetUUID` VARCHAR(255) DEFAULT NULL, `CurrentID` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE INDEX `agent_notification_log_gigya_uid_event_date_kind_notification_id` ON `agentNotificationLog` (`gigya_uid`, `event_date`, `kind`, `notification_id`);
CREATE INDEX `agent_notification_log_reported_datetime_event_date` ON `agentNotificationLog` (`reported_datetime`, `event_date`);
CREATE INDEX `agent_notification_start_datetime_end_datetime` ON `agentNotification` (`start_datetime`, `end_datetime`);
CREATE INDEX `agent_registry_id_1_id_2` ON `agentRegistry` (`id_1`, `id_2`);
CREATE INDEX `cloud_agent_registry__u_u_i_d` ON `cloudAgentRegistry` (`UUID`);
CREATE INDEX `cloud_agent_registry_rb_data_status` ON `cloudAgentRegistry` (`rb_data_status`);
CREATE INDEX `cloud_agent_registry_rb_local_data_status` ON `cloudAgentRegistry` (`rb_local_data_status`);
CREATE INDEX `cloud_agent_registry_rb_local_deleted` ON `cloudAgentRegistry` (`rb_local_deleted`);
CREATE INDEX `cloud_agent_registry_rb_local_usn__i_d` ON `cloudAgentRegistry` (`rb_local_usn`, `ID`);
CREATE INDEX `content_active_censor__content_i_d` ON `contentActiveCensor` (`ContentID`);
CREATE INDEX `content_active_censor__u_u_i_d` ON `contentActiveCensor` (`UUID`);
CREATE INDEX `content_active_censor_rb_data_status` ON `contentActiveCensor` (`rb_data_status`);
CREATE INDEX `content_active_censor_rb_local_data_status` ON `contentActiveCensor` (`rb_local_data_status`);
CREATE INDEX `content_active_censor_rb_local_deleted` ON `contentActiveCensor` (`rb_local_deleted`);
CREATE INDEX `content_active_censor_rb_local_usn__i_d` ON `contentActiveCensor` (`rb_local_usn`, `ID`);
CREATE INDEX `content_cue__content_i_d` ON `contentCue` (`ContentID`);
CREATE INDEX `content_cue__u_u_i_d` ON `contentCue` (`UUID`);
CREATE INDEX `content_cue_rb_cue_count` ON `contentCue` (`rb_cue_count`);
CREATE INDEX `content_cue_rb_data_status` ON `contentCue` (`rb_data_status`);
CREATE INDEX `content_cue_rb_local_data_status` ON `contentCue` (`rb_local_data_status`);
CREATE INDEX `content_cue_rb_local_deleted` ON `contentCue` (`rb_local_deleted`);
CREATE INDEX `content_cue_rb_local_usn__i_d` ON `contentCue` (`rb_local_usn`, `ID`);
CREATE INDEX `content_file__content_i_d` ON `contentFile` (`ContentID`);
CREATE INDEX `content_file__u_u_i_d` ON `contentFile` (`UUID`);
CREATE INDEX `content_file_rb_data_status` ON `contentFile` (`rb_data_status`);
CREATE INDEX `content_file_rb_file_hash_dirty` ON `contentFile` (`rb_file_hash_dirty`);
CREATE INDEX `content_file_rb_file_size_dirty` ON `contentFile` (`rb_file_size_dirty`);
CREATE INDEX `content_file_rb_local_data_status` ON `contentFile` (`rb_local_data_status`);
CREATE INDEX `content_file_rb_local_deleted` ON `contentFile` (`rb_local_deleted`);
CREATE INDEX `content_file_rb_local_deleted_rb_in_progress_rb_local_file_status_rb_process_type_rb_priority` ON `contentFile` (`rb_local_deleted`, `rb_in_progress`, `rb_local_file_status`, `rb_process_type`, `rb_priority`);
CREATE INDEX `content_file_rb_local_usn__i_d` ON `contentFile` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_active_censor__content_i_d` ON `djmdActiveCensor` (`ContentID`);
CREATE INDEX `djmd_active_censor__content_u_u_i_d` ON `djmdActiveCensor` (`ContentUUID`);
CREATE INDEX `djmd_active_censor__u_u_i_d` ON `djmdActiveCensor` (`UUID`);
CREATE INDEX `djmd_active_censor_rb_data_status` ON `djmdActiveCensor` (`rb_data_status`);
CREATE INDEX `djmd_active_censor_rb_local_data_status` ON `djmdActiveCensor` (`rb_local_data_status`);
CREATE INDEX `djmd_active_censor_rb_local_deleted` ON `djmdActiveCensor` (`rb_local_deleted`);
CREATE INDEX `djmd_active_censor_rb_local_usn__i_d` ON `djmdActiveCensor` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_album__album_artist_i_d` ON `djmdAlbum` (`AlbumArtistID`);
CREATE INDEX `djmd_album__name` ON `djmdAlbum` (`Name`);
CREATE INDEX `djmd_album__u_u_i_d` ON `djmdAlbum` (`UUID`);
CREATE INDEX `djmd_album_rb_data_status` ON `djmdAlbum` (`rb_data_status`);
CREATE INDEX `djmd_album_rb_local_data_status` ON `djmdAlbum` (`rb_local_data_status`);
CREATE INDEX `djmd_album_rb_local_deleted` ON `djmdAlbum` (`rb_local_deleted`);
CREATE INDEX `djmd_album_rb_local_usn__i_d` ON `djmdAlbum` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_artist__name` ON `djmdArtist` (`Name`);
CREATE INDEX `djmd_artist__u_u_i_d` ON `djmdArtist` (`UUID`);
CREATE INDEX `djmd_artist_rb_data_status` ON `djmdArtist` (`rb_data_status`);
CREATE INDEX `djmd_artist_rb_local_data_status` ON `djmdArtist` (`rb_local_data_status`);
CREATE INDEX `djmd_artist_rb_local_deleted` ON `djmdArtist` (`rb_local_deleted`);
CREATE INDEX `djmd_artist_rb_local_usn__i_d` ON `djmdArtist` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_category__u_u_i_d` ON `djmdCategory` (`UUID`);
CREATE INDEX `djmd_category_rb_data_status` ON `djmdCategory` (`rb_data_status`);
CREATE INDEX `djmd_category_rb_local_data_status` ON `djmdCategory` (`rb_local_data_status`);
CREATE INDEX `djmd_category_rb_local_deleted` ON `djmdCategory` (`rb_local_deleted`);
CREATE INDEX `djmd_category_rb_local_usn__i_d` ON `djmdCategory` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_cloud_export_playlist__attribute` ON `djmdCloudExportPlaylist` (`Attribute`);
CREATE INDEX `djmd_cloud_export_playlist__name` ON `djmdCloudExportPlaylist` (`Name`);
CREATE INDEX `djmd_cloud_export_playlist__parent_i_d` ON `djmdCloudExportPlaylist` (`ParentID`);
CREATE INDEX `djmd_cloud_export_playlist__seq` ON `djmdCloudExportPlaylist` (`Seq`);
CREATE INDEX `djmd_cloud_export_playlist__u_u_i_d` ON `djmdCloudExportPlaylist` (`UUID`);
CREATE INDEX `djmd_cloud_export_playlist_rb_data_status` ON `djmdCloudExportPlaylist` (`rb_data_status`);
CREATE INDEX `djmd_cloud_export_playlist_rb_local_data_status` ON `djmdCloudExportPlaylist` (`rb_local_data_status`);
CREATE INDEX `djmd_cloud_export_playlist_rb_local_deleted` ON `djmdCloudExportPlaylist` (`rb_local_deleted`);
CREATE INDEX `djmd_cloud_export_playlist_rb_local_usn__i_d` ON `djmdCloudExportPlaylist` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_cloud_export_song_playlist__cloud_export_playlist_i_d__i_d` ON `djmdCloudExportSongPlaylist` (`CloudExportPlaylistID`, `ID`);
CREATE INDEX `djmd_cloud_export_song_playlist__content_i_d_rb_local_deleted` ON `djmdCloudExportSongPlaylist` (`ContentID`, `rb_local_deleted`);
CREATE INDEX `djmd_cloud_export_song_playlist__u_u_i_d` ON `djmdCloudExportSongPlaylist` (`UUID`);
CREATE INDEX `djmd_cloud_export_song_playlist_rb_data_status` ON `djmdCloudExportSongPlaylist` (`rb_data_status`);
CREATE INDEX `djmd_cloud_export_song_playlist_rb_local_data_status` ON `djmdCloudExportSongPlaylist` (`rb_local_data_status`);
CREATE INDEX `djmd_cloud_export_song_playlist_rb_local_deleted` ON `djmdCloudExportSongPlaylist` (`rb_local_deleted`);
CREATE INDEX `djmd_cloud_export_song_playlist_rb_local_usn__i_d` ON `djmdCloudExportSongPlaylist` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_cloud_filter_playlist__u_u_i_d` ON `djmdCloudFilterPlaylist` (`UUID`);
CREATE INDEX `djmd_cloud_filter_playlist_rb_data_status` ON `djmdCloudFilterPlaylist` (`rb_data_status`);
CREATE INDEX `djmd_cloud_filter_playlist_rb_local_data_status` ON `djmdCloudFilterPlaylist` (`rb_local_data_status`);
CREATE INDEX `djmd_cloud_filter_playlist_rb_local_deleted` ON `djmdCloudFilterPlaylist` (`rb_local_deleted`);
CREATE INDEX `djmd_cloud_filter_playlist_rb_local_usn__i_d` ON `djmdCloudFilterPlaylist` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_cloud_property__u_u_i_d` ON `djmdCloudProperty` (`UUID`);
CREATE INDEX `djmd_cloud_property_rb_data_status` ON `djmdCloudProperty` (`rb_data_status`);
CREATE INDEX `djmd_cloud_property_rb_local_data_status` ON `djmdCloudProperty` (`rb_local_data_status`);
CREATE INDEX `djmd_cloud_property_rb_local_deleted` ON `djmdCloudProperty` (`rb_local_deleted`);
CREATE INDEX `djmd_cloud_property_rb_local_usn__i_d` ON `djmdCloudProperty` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_color__u_u_i_d` ON `djmdColor` (`UUID`);
CREATE INDEX `djmd_color_rb_data_status` ON `djmdColor` (`rb_data_status`);
CREATE INDEX `djmd_color_rb_local_data_status` ON `djmdColor` (`rb_local_data_status`);
CREATE INDEX `djmd_color_rb_local_deleted` ON `djmdColor` (`rb_local_deleted`);
CREATE INDEX `djmd_color_rb_local_usn__i_d` ON `djmdColor` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_content__album_i_d` ON `djmdContent` (`AlbumID`);
CREATE INDEX `djmd_content__artist_i_d` ON `djmdContent` (`ArtistID`);
CREATE INDEX `djmd_content__composer_i_d` ON `djmdContent` (`ComposerID`);
CREATE INDEX `djmd_content__genre_i_d` ON `djmdContent` (`GenreID`);
CREATE INDEX `djmd_content__key_i_d` ON `djmdContent` (`KeyID`);
CREATE INDEX `djmd_content__label_i_d` ON `djmdContent` (`LabelID`);
CREATE INDEX `djmd_content__master_d_b_i_d__master_song_i_d` ON `djmdContent` (`MasterDBID`, `MasterSongID`);
CREATE INDEX `djmd_content__org_artist_i_d` ON `djmdContent` (`OrgArtistID`);
CREATE INDEX `djmd_content__remixer_i_d` ON `djmdContent` (`RemixerID`);
CREATE INDEX `djmd_content__u_u_i_d` ON `djmdContent` (`UUID`);
CREATE INDEX `djmd_content_rb_data_status` ON `djmdContent` (`rb_data_status`);
CREATE INDEX `djmd_content_rb_local_data_status` ON `djmdContent` (`rb_local_data_status`);
CREATE INDEX `djmd_content_rb_local_deleted` ON `djmdContent` (`rb_local_deleted`);
CREATE INDEX `djmd_content_rb_local_deleted__bit_depth` ON `djmdContent` (`rb_local_deleted`, `BitDepth`);
CREATE INDEX `djmd_content_rb_local_deleted__bit_rate` ON `djmdContent` (`rb_local_deleted`, `BitRate`);
CREATE INDEX `djmd_content_rb_local_deleted__file_type` ON `djmdContent` (`rb_local_deleted`, `FileType`);
CREATE INDEX `djmd_content_rb_local_deleted__service_i_d` ON `djmdContent` (`rb_local_deleted`, `ServiceID`);
CREATE INDEX `djmd_content_rb_local_usn__i_d` ON `djmdContent` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_cue__content_i_d_rb_local_deleted` ON `djmdCue` (`ContentID`, `rb_local_deleted`);
CREATE INDEX `djmd_cue__content_u_u_i_d` ON `djmdCue` (`ContentUUID`);
CREATE INDEX `djmd_cue__u_u_i_d` ON `djmdCue` (`UUID`);
CREATE INDEX `djmd_cue_rb_data_status` ON `djmdCue` (`rb_data_status`);
CREATE INDEX `djmd_cue_rb_local_data_status` ON `djmdCue` (`rb_local_data_status`);
CREATE INDEX `djmd_cue_rb_local_deleted` ON `djmdCue` (`rb_local_deleted`);
CREATE INDEX `djmd_cue_rb_local_usn__i_d` ON `djmdCue` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_device__u_u_i_d` ON `djmdDevice` (`UUID`);
CREATE INDEX `djmd_device_rb_data_status` ON `djmdDevice` (`rb_data_status`);
CREATE INDEX `djmd_device_rb_local_data_status` ON `djmdDevice` (`rb_local_data_status`);
CREATE INDEX `djmd_device_rb_local_deleted` ON `djmdDevice` (`rb_local_deleted`);
CREATE INDEX `djmd_device_rb_local_usn__i_d` ON `djmdDevice` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_genre__name` ON `djmdGenre` (`Name`);
CREATE INDEX `djmd_genre__u_u_i_d` ON `djmdGenre` (`UUID`);
CREATE INDEX `djmd_genre_rb_data_status` ON `djmdGenre` (`rb_data_status`);
CREATE INDEX `djmd_genre_rb_local_data_status` ON `djmdGenre` (`rb_local_data_status`);
CREATE INDEX `djmd_genre_rb_local_deleted` ON `djmdGenre` (`rb_local_deleted`);
CREATE INDEX `djmd_genre_rb_local_usn__i_d` ON `djmdGenre` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_history__name` ON `djmdHistory` (`Name`);
CREATE INDEX `djmd_history__parent_i_d` ON `djmdHistory` (`ParentID`);
CREATE INDEX `djmd_history__u_u_i_d` ON `djmdHistory` (`UUID`);
CREATE INDEX `djmd_history_rb_data_status` ON `djmdHistory` (`rb_data_status`);
CREATE INDEX `djmd_history_rb_local_data_status` ON `djmdHistory` (`rb_local_data_status`);
CREATE INDEX `djmd_history_rb_local_deleted` ON `djmdHistory` (`rb_local_deleted`);
CREATE INDEX `djmd_history_rb_local_usn__i_d` ON `djmdHistory` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_hot_cue_banklist__name` ON `djmdHotCueBanklist` (`Name`);
CREATE INDEX `djmd_hot_cue_banklist__parent_i_d` ON `djmdHotCueBanklist` (`ParentID`);
CREATE INDEX `djmd_hot_cue_banklist__u_u_i_d` ON `djmdHotCueBanklist` (`UUID`);
CREATE INDEX `djmd_hot_cue_banklist_rb_data_status` ON `djmdHotCueBanklist` (`rb_data_status`);
CREATE INDEX `djmd_hot_cue_banklist_rb_local_data_status` ON `djmdHotCueBanklist` (`rb_local_data_status`);
CREATE INDEX `djmd_hot_cue_banklist_rb_local_deleted` ON `djmdHotCueBanklist` (`rb_local_deleted`);
CREATE INDEX `djmd_hot_cue_banklist_rb_local_usn__i_d` ON `djmdHotCueBanklist` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_key__scale_name` ON `djmdKey` (`ScaleName`);
CREATE INDEX `djmd_key__u_u_i_d` ON `djmdKey` (`UUID`);
CREATE INDEX `djmd_key_rb_data_status` ON `djmdKey` (`rb_data_status`);
CREATE INDEX `djmd_key_rb_local_data_status` ON `djmdKey` (`rb_local_data_status`);
CREATE INDEX `djmd_key_rb_local_deleted` ON `djmdKey` (`rb_local_deleted`);
CREATE INDEX `djmd_key_rb_local_usn__i_d` ON `djmdKey` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_label__name` ON `djmdLabel` (`Name`);
CREATE INDEX `djmd_label__u_u_i_d` ON `djmdLabel` (`UUID`);
CREATE INDEX `djmd_label_rb_data_status` ON `djmdLabel` (`rb_data_status`);
CREATE INDEX `djmd_label_rb_local_data_status` ON `djmdLabel` (`rb_local_data_status`);
CREATE INDEX `djmd_label_rb_local_deleted` ON `djmdLabel` (`rb_local_deleted`);
CREATE INDEX `djmd_label_rb_local_usn__i_d` ON `djmdLabel` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_menu_items__u_u_i_d` ON `djmdMenuItems` (`UUID`);
CREATE INDEX `djmd_menu_items_rb_data_status` ON `djmdMenuItems` (`rb_data_status`);
CREATE INDEX `djmd_menu_items_rb_local_data_status` ON `djmdMenuItems` (`rb_local_data_status`);
CREATE INDEX `djmd_menu_items_rb_local_deleted` ON `djmdMenuItems` (`rb_local_deleted`);
CREATE INDEX `djmd_menu_items_rb_local_usn__i_d` ON `djmdMenuItems` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_mixer_param__content_i_d_rb_local_deleted` ON `djmdMixerParam` (`ContentID`, `rb_local_deleted`);
CREATE INDEX `djmd_mixer_param__u_u_i_d` ON `djmdMixerParam` (`UUID`);
CREATE INDEX `djmd_mixer_param_rb_data_status` ON `djmdMixerParam` (`rb_data_status`);
CREATE INDEX `djmd_mixer_param_rb_local_data_status` ON `djmdMixerParam` (`rb_local_data_status`);
CREATE INDEX `djmd_mixer_param_rb_local_deleted` ON `djmdMixerParam` (`rb_local_deleted`);
CREATE INDEX `djmd_mixer_param_rb_local_usn__i_d` ON `djmdMixerParam` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_my_tag__parent_i_d` ON `djmdMyTag` (`ParentID`);
CREATE INDEX `djmd_my_tag__seq` ON `djmdMyTag` (`Seq`);
CREATE INDEX `djmd_my_tag__u_u_i_d` ON `djmdMyTag` (`UUID`);
CREATE INDEX `djmd_my_tag_rb_data_status` ON `djmdMyTag` (`rb_data_status`);
CREATE INDEX `djmd_my_tag_rb_local_data_status` ON `djmdMyTag` (`rb_local_data_status`);
CREATE INDEX `djmd_my_tag_rb_local_deleted` ON `djmdMyTag` (`rb_local_deleted`);
CREATE INDEX `djmd_my_tag_rb_local_usn__i_d` ON `djmdMyTag` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_playlist__attribute` ON `djmdPlaylist` (`Attribute`);
CREATE INDEX `djmd_playlist__name` ON `djmdPlaylist` (`Name`);
CREATE INDEX `djmd_playlist__parent_i_d` ON `djmdPlaylist` (`ParentID`);
CREATE INDEX `djmd_playlist__seq` ON `djmdPlaylist` (`Seq`);
CREATE INDEX `djmd_playlist__u_u_i_d` ON `djmdPlaylist` (`UUID`);
CREATE INDEX `djmd_playlist_rb_data_status` ON `djmdPlaylist` (`rb_data_status`);
CREATE INDEX `djmd_playlist_rb_local_data_status` ON `djmdPlaylist` (`rb_local_data_status`);
CREATE INDEX `djmd_playlist_rb_local_deleted` ON `djmdPlaylist` (`rb_local_deleted`);
CREATE INDEX `djmd_playlist_rb_local_usn__i_d` ON `djmdPlaylist` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_recommend_like__content_i_d1__content_i_d2` ON `djmdRecommendLike` (`ContentID1`, `ContentID2`);
CREATE INDEX `djmd_recommend_like__content_i_d2` ON `djmdRecommendLike` (`ContentID2`);
CREATE INDEX `djmd_recommend_like__u_u_i_d` ON `djmdRecommendLike` (`UUID`);
CREATE INDEX `djmd_recommend_like_rb_data_status` ON `djmdRecommendLike` (`rb_data_status`);
CREATE INDEX `djmd_recommend_like_rb_local_data_status` ON `djmdRecommendLike` (`rb_local_data_status`);
CREATE INDEX `djmd_recommend_like_rb_local_deleted` ON `djmdRecommendLike` (`rb_local_deleted`);
CREATE INDEX `djmd_recommend_like_rb_local_usn__i_d` ON `djmdRecommendLike` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_related_tracks__name` ON `djmdRelatedTracks` (`Name`);
CREATE INDEX `djmd_related_tracks__parent_i_d` ON `djmdRelatedTracks` (`ParentID`);
CREATE INDEX `djmd_related_tracks__seq` ON `djmdRelatedTracks` (`Seq`);
CREATE INDEX `djmd_related_tracks__u_u_i_d` ON `djmdRelatedTracks` (`UUID`);
CREATE INDEX `djmd_related_tracks_rb_data_status` ON `djmdRelatedTracks` (`rb_data_status`);
CREATE INDEX `djmd_related_tracks_rb_local_data_status` ON `djmdRelatedTracks` (`rb_local_data_status`);
CREATE INDEX `djmd_related_tracks_rb_local_deleted` ON `djmdRelatedTracks` (`rb_local_deleted`);
CREATE INDEX `djmd_related_tracks_rb_local_usn__i_d` ON `djmdRelatedTracks` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_sampler__name` ON `djmdSampler` (`Name`);
CREATE INDEX `djmd_sampler__parent_i_d` ON `djmdSampler` (`ParentID`);
CREATE INDEX `djmd_sampler__seq` ON `djmdSampler` (`Seq`);
CREATE INDEX `djmd_sampler__u_u_i_d` ON `djmdSampler` (`UUID`);
CREATE INDEX `djmd_sampler_rb_data_status` ON `djmdSampler` (`rb_data_status`);
CREATE INDEX `djmd_sampler_rb_local_data_status` ON `djmdSampler` (`rb_local_data_status`);
CREATE INDEX `djmd_sampler_rb_local_deleted` ON `djmdSampler` (`rb_local_deleted`);
CREATE INDEX `djmd_sampler_rb_local_usn__i_d` ON `djmdSampler` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_song_history__content_i_d_rb_local_deleted` ON `djmdSongHistory` (`ContentID`, `rb_local_deleted`);
CREATE INDEX `djmd_song_history__history_i_d` ON `djmdSongHistory` (`HistoryID`);
CREATE INDEX `djmd_song_history__u_u_i_d` ON `djmdSongHistory` (`UUID`);
CREATE INDEX `djmd_song_history_rb_data_status` ON `djmdSongHistory` (`rb_data_status`);
CREATE INDEX `djmd_song_history_rb_local_data_status` ON `djmdSongHistory` (`rb_local_data_status`);
CREATE INDEX `djmd_song_history_rb_local_deleted` ON `djmdSongHistory` (`rb_local_deleted`);
CREATE INDEX `djmd_song_history_rb_local_usn__i_d` ON `djmdSongHistory` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_song_hot_cue_banklist__content_i_d` ON `djmdSongHotCueBanklist` (`ContentID`);
CREATE INDEX `djmd_song_hot_cue_banklist__hot_cue_banklist_i_d` ON `djmdSongHotCueBanklist` (`HotCueBanklistID`);
CREATE INDEX `djmd_song_hot_cue_banklist__hot_cue_banklist_u_u_i_d` ON `djmdSongHotCueBanklist` (`HotCueBanklistUUID`);
CREATE INDEX `djmd_song_hot_cue_banklist__u_u_i_d` ON `djmdSongHotCueBanklist` (`UUID`);
CREATE INDEX `djmd_song_hot_cue_banklist_rb_data_status` ON `djmdSongHotCueBanklist` (`rb_data_status`);
CREATE INDEX `djmd_song_hot_cue_banklist_rb_local_data_status` ON `djmdSongHotCueBanklist` (`rb_local_data_status`);
CREATE INDEX `djmd_song_hot_cue_banklist_rb_local_deleted` ON `djmdSongHotCueBanklist` (`rb_local_deleted`);
CREATE INDEX `djmd_song_hot_cue_banklist_rb_local_usn__i_d` ON `djmdSongHotCueBanklist` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_song_my_tag__content_i_d_rb_local_deleted` ON `djmdSongMyTag` (`ContentID`, `rb_local_deleted`);
CREATE INDEX `djmd_song_my_tag__my_tag_i_d_rb_local_deleted__i_d` ON `djmdSongMyTag` (`MyTagID`, `rb_local_deleted`, `ID`);
CREATE INDEX `djmd_song_my_tag__u_u_i_d` ON `djmdSongMyTag` (`UUID`);
CREATE INDEX `djmd_song_my_tag_rb_data_status` ON `djmdSongMyTag` (`rb_data_status`);
CREATE INDEX `djmd_song_my_tag_rb_local_data_status` ON `djmdSongMyTag` (`rb_local_data_status`);
CREATE INDEX `djmd_song_my_tag_rb_local_deleted` ON `djmdSongMyTag` (`rb_local_deleted`);
CREATE INDEX `djmd_song_my_tag_rb_local_usn__i_d` ON `djmdSongMyTag` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_song_playlist__content_i_d_rb_local_deleted` ON `djmdSongPlaylist` (`ContentID`, `rb_local_deleted`);
CREATE INDEX `djmd_song_playlist__playlist_i_d__i_d` ON `djmdSongPlaylist` (`PlaylistID`, `ID`);
CREATE INDEX `djmd_song_playlist__u_u_i_d` ON `djmdSongPlaylist` (`UUID`);
CREATE INDEX `djmd_song_playlist_rb_data_status` ON `djmdSongPlaylist` (`rb_data_status`);
CREATE INDEX `djmd_song_playlist_rb_local_data_status` ON `djmdSongPlaylist` (`rb_local_data_status`);
CREATE INDEX `djmd_song_playlist_rb_local_deleted` ON `djmdSongPlaylist` (`rb_local_deleted`);
CREATE INDEX `djmd_song_playlist_rb_local_usn__i_d` ON `djmdSongPlaylist` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_song_related_tracks__content_i_d` ON `djmdSongRelatedTracks` (`ContentID`);
CREATE INDEX `djmd_song_related_tracks__related_tracks_i_d` ON `djmdSongRelatedTracks` (`RelatedTracksID`);
CREATE INDEX `djmd_song_related_tracks__u_u_i_d` ON `djmdSongRelatedTracks` (`UUID`);
CREATE INDEX `djmd_song_related_tracks_rb_data_status` ON `djmdSongRelatedTracks` (`rb_data_status`);
CREATE INDEX `djmd_song_related_tracks_rb_local_data_status` ON `djmdSongRelatedTracks` (`rb_local_data_status`);
CREATE INDEX `djmd_song_related_tracks_rb_local_deleted` ON `djmdSongRelatedTracks` (`rb_local_deleted`);
CREATE INDEX `djmd_song_related_tracks_rb_local_usn__i_d` ON `djmdSongRelatedTracks` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_song_request_list__content_i_d` ON `djmdSongRequestList` (`ContentID`);
CREATE INDEX `djmd_song_request_list__u_u_i_d` ON `djmdSongRequestList` (`UUID`);
CREATE INDEX `djmd_song_request_list_rb_data_status` ON `djmdSongRequestList` (`rb_data_status`);
CREATE INDEX `djmd_song_request_list_rb_local_data_status` ON `djmdSongRequestList` (`rb_local_data_status`);
CREATE INDEX `djmd_song_request_list_rb_local_deleted` ON `djmdSongRequestList` (`rb_local_deleted`);
CREATE INDEX `djmd_song_request_list_rb_local_usn__i_d` ON `djmdSongRequestList` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_song_sampler__content_i_d` ON `djmdSongSampler` (`ContentID`);
CREATE INDEX `djmd_song_sampler__sampler_i_d` ON `djmdSongSampler` (`SamplerID`);
CREATE INDEX `djmd_song_sampler__u_u_i_d` ON `djmdSongSampler` (`UUID`);
CREATE INDEX `djmd_song_sampler_rb_data_status` ON `djmdSongSampler` (`rb_data_status`);
CREATE INDEX `djmd_song_sampler_rb_local_data_status` ON `djmdSongSampler` (`rb_local_data_status`);
CREATE INDEX `djmd_song_sampler_rb_local_deleted` ON `djmdSongSampler` (`rb_local_deleted`);
CREATE INDEX `djmd_song_sampler_rb_local_usn__i_d` ON `djmdSongSampler` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_song_tag_list__content_i_d` ON `djmdSongTagList` (`ContentID`);
CREATE INDEX `djmd_song_tag_list__u_u_i_d` ON `djmdSongTagList` (`UUID`);
CREATE INDEX `djmd_song_tag_list_rb_data_status` ON `djmdSongTagList` (`rb_data_status`);
CREATE INDEX `djmd_song_tag_list_rb_local_data_status` ON `djmdSongTagList` (`rb_local_data_status`);
CREATE INDEX `djmd_song_tag_list_rb_local_deleted` ON `djmdSongTagList` (`rb_local_deleted`);
CREATE INDEX `djmd_song_tag_list_rb_local_usn__i_d` ON `djmdSongTagList` (`rb_local_usn`, `ID`);
CREATE INDEX `djmd_sort__u_u_i_d` ON `djmdSort` (`UUID`);
CREATE INDEX `djmd_sort_rb_data_status` ON `djmdSort` (`rb_data_status`);
CREATE INDEX `djmd_sort_rb_local_data_status` ON `djmdSort` (`rb_local_data_status`);
CREATE INDEX `djmd_sort_rb_local_deleted` ON `djmdSort` (`rb_local_deleted`);
CREATE INDEX `djmd_sort_rb_local_usn__i_d` ON `djmdSort` (`rb_local_usn`, `ID`);
CREATE INDEX `hot_cue_banklist_cue__hot_cue_banklist_i_d` ON `hotCueBanklistCue` (`HotCueBanklistID`);
CREATE INDEX `hot_cue_banklist_cue__u_u_i_d` ON `hotCueBanklistCue` (`UUID`);
CREATE INDEX `hot_cue_banklist_cue_rb_cue_count` ON `hotCueBanklistCue` (`rb_cue_count`);
CREATE INDEX `hot_cue_banklist_cue_rb_data_status` ON `hotCueBanklistCue` (`rb_data_status`);
CREATE INDEX `hot_cue_banklist_cue_rb_local_data_status` ON `hotCueBanklistCue` (`rb_local_data_status`);
CREATE INDEX `hot_cue_banklist_cue_rb_local_deleted` ON `hotCueBanklistCue` (`rb_local_deleted`);
CREATE INDEX `hot_cue_banklist_cue_rb_local_usn__i_d` ON `hotCueBanklistCue` (`rb_local_usn`, `ID`);
CREATE INDEX `image_file__table_name__target_i_d` ON `imageFile` (`TableName`, `TargetID`);
CREATE INDEX `image_file__table_name__target_u_u_i_d__i_d` ON `imageFile` (`TableName`, `TargetUUID`, `ID`);
CREATE INDEX `image_file__u_u_i_d` ON `imageFile` (`UUID`);
CREATE INDEX `image_file_rb_data_status` ON `imageFile` (`rb_data_status`);
CREATE INDEX `image_file_rb_file_hash_dirty` ON `imageFile` (`rb_file_hash_dirty`);
CREATE INDEX `image_file_rb_file_size_dirty` ON `imageFile` (`rb_file_size_dirty`);
CREATE INDEX `image_file_rb_local_data_status` ON `imageFile` (`rb_local_data_status`);
CREATE INDEX `image_file_rb_local_deleted` ON `imageFile` (`rb_local_deleted`);
CREATE INDEX `image_file_rb_local_deleted_rb_in_progress_rb_local_file_status_rb_process_type_rb_priority` ON `imageFile` (`rb_local_deleted`, `rb_in_progress`, `rb_local_file_status`, `rb_process_type`, `rb_priority`);
CREATE INDEX `image_file_rb_local_usn__i_d` ON `imageFile` (`rb_local_usn`, `ID`);
CREATE INDEX `setting_file__u_u_i_d` ON `settingFile` (`UUID`);
CREATE INDEX `setting_file_rb_data_status` ON `settingFile` (`rb_data_status`);
CREATE INDEX `setting_file_rb_file_hash_dirty` ON `settingFile` (`rb_file_hash_dirty`);
CREATE INDEX `setting_file_rb_file_size_dirty` ON `settingFile` (`rb_file_size_dirty`);
CREATE INDEX `setting_file_rb_local_data_status` ON `settingFile` (`rb_local_data_status`);
CREATE INDEX `setting_file_rb_local_deleted` ON `settingFile` (`rb_local_deleted`);
CREATE INDEX `setting_file_rb_local_usn__i_d` ON `settingFile` (`rb_local_usn`, `ID`);
CREATE INDEX `uuid_i_d_map__u_u_i_d` ON `uuidIDMap` (`UUID`);
CREATE INDEX `uuid_i_d_map_rb_data_status` ON `uuidIDMap` (`rb_data_status`);
CREATE INDEX `uuid_i_d_map_rb_local_data_status` ON `uuidIDMap` (`rb_local_data_status`);
CREATE INDEX `uuid_i_d_map_rb_local_deleted` ON `uuidIDMap` (`rb_local_deleted`);
CREATE INDEX `uuid_i_d_map_rb_local_usn__i_d` ON `uuidIDMap` (`rb_local_usn`, `ID`);
+88
View File
@@ -0,0 +1,88 @@
-- Rekordbox's own scaffolding rows, needed before any track can be added:
-- `add_content` looks up djmdMenuItems('TRACK') and fails on an empty table.
--
-- Static UI data only — menu items, colours, categories, sort options.
-- djmdDevice and djmdProperty are DELIBERATELY absent: they carry the
-- machine's name and UUIDs, so the exporter generates those fresh instead.
-- djmdMenuItems: 27 rows
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('1', -128, 'GENRE', '1', 0, 0, 0, 0, NULL, 10, '2026-09-17 20:53:21.658 +00:00', '2026-09-17 20:53:21.658 +00:00');
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('2', -127, 'ARTIST', '2', 0, 0, 0, 0, NULL, 11, '2026-09-17 20:53:21.658 +00:00', '2026-09-17 20:53:21.658 +00:00');
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('3', -126, 'ALBUM', '3', 0, 0, 0, 0, NULL, 12, '2026-09-17 20:53:21.658 +00:00', '2026-09-17 20:53:21.658 +00:00');
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('4', -125, 'TRACK', '4', 0, 0, 0, 0, NULL, 13, '2026-09-17 20:53:21.658 +00:00', '2026-09-17 20:53:21.658 +00:00');
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('5', -123, 'BPM', '5', 0, 0, 0, 0, NULL, 14, '2026-09-17 20:53:21.658 +00:00', '2026-09-17 20:53:21.658 +00:00');
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('6', -122, 'RATING', '6', 0, 0, 0, 0, NULL, 15, '2026-09-17 20:53:21.659 +00:00', '2026-09-17 20:53:21.659 +00:00');
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('7', -121, 'YEAR', '7', 0, 0, 0, 0, NULL, 16, '2026-09-17 20:53:21.659 +00:00', '2026-09-17 20:53:21.659 +00:00');
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('8', -120, 'REMIXER', '8', 0, 0, 0, 0, NULL, 17, '2026-09-17 20:53:21.659 +00:00', '2026-09-17 20:53:21.659 +00:00');
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('9', -119, 'LABEL', '9', 0, 0, 0, 0, NULL, 18, '2026-09-17 20:53:21.659 +00:00', '2026-09-17 20:53:21.659 +00:00');
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('10', -118, 'ORIGINAL ARTIST', '10', 0, 0, 0, 0, NULL, 19, '2026-09-17 20:53:21.659 +00:00', '2026-09-17 20:53:21.659 +00:00');
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('11', -117, 'KEY', '11', 0, 0, 0, 0, NULL, 20, '2026-09-17 20:53:21.659 +00:00', '2026-09-17 20:53:21.659 +00:00');
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('12', -115, 'CUE', '12', 0, 0, 0, 0, NULL, 21, '2026-09-17 20:53:21.659 +00:00', '2026-09-17 20:53:21.659 +00:00');
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('13', -114, 'COLOR', '13', 0, 0, 0, 0, NULL, 22, '2026-09-17 20:53:21.659 +00:00', '2026-09-17 20:53:21.659 +00:00');
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('14', -110, 'TIME', '14', 0, 0, 0, 0, NULL, 23, '2026-09-17 20:53:21.660 +00:00', '2026-09-17 20:53:21.660 +00:00');
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('15', -109, 'BITRATE', '15', 0, 0, 0, 0, NULL, 24, '2026-09-17 20:53:21.660 +00:00', '2026-09-17 20:53:21.660 +00:00');
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('16', -108, 'FILE NAME', '16', 0, 0, 0, 0, NULL, 25, '2026-09-17 20:53:21.660 +00:00', '2026-09-17 20:53:21.660 +00:00');
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('17', -124, 'PLAYLIST', '17', 0, 0, 0, 0, NULL, 26, '2026-09-17 20:53:21.660 +00:00', '2026-09-17 20:53:21.660 +00:00');
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('18', -104, 'HOT CUE BANK', '18', 0, 0, 0, 0, NULL, 27, '2026-09-17 20:53:21.660 +00:00', '2026-09-17 20:53:21.660 +00:00');
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('19', -107, 'HISTORY', '19', 0, 0, 0, 0, NULL, 28, '2026-09-17 20:53:21.660 +00:00', '2026-09-17 20:53:21.660 +00:00');
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('20', -111, 'SEARCH', '20', 0, 0, 0, 0, NULL, 29, '2026-09-17 20:53:21.660 +00:00', '2026-09-17 20:53:21.660 +00:00');
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('21', -106, 'COMMENTS', '21', 0, 0, 0, 0, NULL, 30, '2026-09-17 20:53:21.660 +00:00', '2026-09-17 20:53:21.660 +00:00');
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('22', -116, 'DATE ADDED', '22', 0, 0, 0, 0, NULL, 31, '2026-09-17 20:53:21.660 +00:00', '2026-09-17 20:53:21.660 +00:00');
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('23', -105, 'DJ PLAY COUNT', '23', 0, 0, 0, 0, NULL, 32, '2026-09-17 20:53:21.661 +00:00', '2026-09-17 20:53:21.661 +00:00');
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('24', -112, 'FOLDER', '24', 0, 0, 0, 0, NULL, 33, '2026-09-17 20:53:21.661 +00:00', '2026-09-17 20:53:21.661 +00:00');
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('25', -95, 'DEFAULT', '25', 0, 0, 0, 0, NULL, 34, '2026-09-17 20:53:21.661 +00:00', '2026-09-17 20:53:21.661 +00:00');
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('26', -94, 'ALPHABET', '26', 0, 0, 0, 0, NULL, 35, '2026-09-17 20:53:21.661 +00:00', '2026-09-17 20:53:21.661 +00:00');
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('27', -86, 'MATCHING', '27', 0, 0, 0, 0, NULL, 36, '2026-09-17 20:53:21.661 +00:00', '2026-09-17 20:53:21.661 +00:00');
-- djmdColor: 8 rows
INSERT INTO "djmdColor" ("ID", "ColorCode", "SortKey", "Commnt", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('1', NULL, 1, 'Pink', '1', 0, 0, 0, 0, NULL, 2, '2026-09-17 20:53:21.657 +00:00', '2026-09-17 20:53:21.657 +00:00');
INSERT INTO "djmdColor" ("ID", "ColorCode", "SortKey", "Commnt", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('2', NULL, 2, 'Red', '2', 0, 0, 0, 0, NULL, 3, '2026-09-17 20:53:21.657 +00:00', '2026-09-17 20:53:21.657 +00:00');
INSERT INTO "djmdColor" ("ID", "ColorCode", "SortKey", "Commnt", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('3', NULL, 3, 'Orange', '3', 0, 0, 0, 0, NULL, 4, '2026-09-17 20:53:21.657 +00:00', '2026-09-17 20:53:21.657 +00:00');
INSERT INTO "djmdColor" ("ID", "ColorCode", "SortKey", "Commnt", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('4', NULL, 4, 'Yellow', '4', 0, 0, 0, 0, NULL, 5, '2026-09-17 20:53:21.657 +00:00', '2026-09-17 20:53:21.657 +00:00');
INSERT INTO "djmdColor" ("ID", "ColorCode", "SortKey", "Commnt", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('5', NULL, 5, 'Green', '5', 0, 0, 0, 0, NULL, 6, '2026-09-17 20:53:21.657 +00:00', '2026-09-17 20:53:21.657 +00:00');
INSERT INTO "djmdColor" ("ID", "ColorCode", "SortKey", "Commnt", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('6', NULL, 6, 'Aqua', '6', 0, 0, 0, 0, NULL, 7, '2026-09-17 20:53:21.657 +00:00', '2026-09-17 20:53:21.657 +00:00');
INSERT INTO "djmdColor" ("ID", "ColorCode", "SortKey", "Commnt", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('7', NULL, 7, 'Blue', '7', 0, 0, 0, 0, NULL, 8, '2026-09-17 20:53:21.658 +00:00', '2026-09-17 20:53:21.658 +00:00');
INSERT INTO "djmdColor" ("ID", "ColorCode", "SortKey", "Commnt", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('8', NULL, 8, 'Purple', '8', 0, 0, 0, 0, NULL, 9, '2026-09-17 20:53:21.658 +00:00', '2026-09-17 20:53:21.658 +00:00');
-- djmdCategory: 22 rows
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('1', '1', 0, 1, 99, '1', 0, 0, 0, 0, NULL, 37, '2026-09-17 20:53:25.758 +00:00', '2026-09-17 20:53:25.758 +00:00');
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('2', '2', 1, 0, 2, '2', 0, 0, 0, 0, NULL, 38, '2026-09-17 20:53:25.769 +00:00', '2026-09-17 20:53:25.769 +00:00');
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('3', '3', 2, 0, 3, '3', 0, 0, 0, 0, NULL, 39, '2026-09-17 20:53:25.774 +00:00', '2026-09-17 20:53:25.774 +00:00');
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('4', '4', 3, 0, 1, '4', 0, 0, 0, 0, NULL, 40, '2026-09-17 20:53:25.780 +00:00', '2026-09-17 20:53:25.780 +00:00');
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('5', '17', 5, 0, 99, '5', 0, 0, 0, 0, NULL, 41, '2026-09-17 20:53:25.786 +00:00', '2026-09-17 20:53:25.786 +00:00');
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('6', '5', 0, 1, 5, '6', 0, 0, 0, 0, NULL, 42, '2026-09-17 20:53:25.793 +00:00', '2026-09-17 20:53:25.793 +00:00');
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('7', '6', 0, 1, 99, '7', 0, 0, 0, 0, NULL, 43, '2026-09-17 20:53:25.799 +00:00', '2026-09-17 20:53:25.799 +00:00');
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('8', '7', 0, 1, 99, '8', 0, 0, 0, 0, NULL, 44, '2026-09-17 20:53:25.804 +00:00', '2026-09-17 20:53:25.804 +00:00');
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('9', '8', 0, 1, 99, '9', 0, 0, 0, 0, NULL, 45, '2026-09-17 20:53:25.811 +00:00', '2026-09-17 20:53:25.811 +00:00');
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('10', '9', 0, 1, 99, '10', 0, 0, 0, 0, NULL, 46, '2026-09-17 20:53:25.817 +00:00', '2026-09-17 20:53:25.817 +00:00');
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('11', '10', 0, 1, 99, '11', 0, 0, 0, 0, NULL, 47, '2026-09-17 20:53:25.823 +00:00', '2026-09-17 20:53:25.823 +00:00');
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('12', '11', 4, 0, 99, '12', 0, 0, 0, 0, NULL, 48, '2026-09-17 20:53:25.829 +00:00', '2026-09-17 20:53:25.829 +00:00');
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('15', '13', 0, 1, 99, '15', 0, 0, 0, 0, NULL, 49, '2026-09-17 20:53:25.836 +00:00', '2026-09-17 20:53:25.836 +00:00');
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('17', '24', 9, 0, 99, '17', 0, 0, 0, 0, NULL, 50, '2026-09-17 20:53:25.842 +00:00', '2026-09-17 20:53:25.842 +00:00');
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('18', '20', 7, 0, 99, '18', 0, 0, 0, 0, NULL, 51, '2026-09-17 20:53:25.848 +00:00', '2026-09-17 20:53:25.848 +00:00');
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('19', '14', 0, 1, 4, '19', 0, 0, 0, 0, NULL, 52, '2026-09-17 20:53:25.854 +00:00', '2026-09-17 20:53:25.854 +00:00');
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('20', '15', 0, 1, 6, '20', 0, 0, 0, 0, NULL, 53, '2026-09-17 20:53:25.860 +00:00', '2026-09-17 20:53:25.860 +00:00');
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('21', '16', 0, 1, 99, '21', 0, 0, 0, 0, NULL, 54, '2026-09-17 20:53:25.865 +00:00', '2026-09-17 20:53:25.865 +00:00');
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('22', '19', 6, 0, 99, '22', 0, 0, 0, 0, NULL, 55, '2026-09-17 20:53:25.870 +00:00', '2026-09-17 20:53:25.870 +00:00');
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('23', '18', 0, 1, 99, '23', 0, 0, 0, 0, NULL, 56, '2026-09-17 20:53:25.875 +00:00', '2026-09-17 20:53:25.875 +00:00');
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('26', '27', 8, 2, 99, '26', 0, 0, 0, 0, NULL, 57, '2026-09-17 20:53:25.881 +00:00', '2026-09-17 20:53:25.881 +00:00');
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('27', '22', 10, 0, 99, '27', 0, 0, 0, 0, NULL, 58, '2026-09-17 20:53:25.886 +00:00', '2026-09-17 20:53:25.886 +00:00');
-- djmdSort: 17 rows
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('0', '25', 1, 0, '0', 0, 0, 0, 0, NULL, 59, '2026-09-17 20:53:25.893 +00:00', '2026-09-17 20:53:25.893 +00:00');
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('1', '26', 2, 0, '1', 0, 0, 0, 0, NULL, 60, '2026-09-17 20:53:25.900 +00:00', '2026-09-17 20:53:25.900 +00:00');
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('2', '2', 3, 0, '2', 0, 0, 0, 0, NULL, 61, '2026-09-17 20:53:25.907 +00:00', '2026-09-17 20:53:25.907 +00:00');
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('3', '3', 4, 0, '3', 0, 0, 0, 0, NULL, 62, '2026-09-17 20:53:25.913 +00:00', '2026-09-17 20:53:25.913 +00:00');
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('4', '5', 5, 0, '4', 0, 0, 0, 0, NULL, 63, '2026-09-17 20:53:25.920 +00:00', '2026-09-17 20:53:25.920 +00:00');
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('5', '6', 6, 0, '5', 0, 0, 0, 0, NULL, 64, '2026-09-17 20:53:25.925 +00:00', '2026-09-17 20:53:25.925 +00:00');
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('6', '1', 0, 1, '6', 0, 0, 0, 0, NULL, 65, '2026-09-17 20:53:25.931 +00:00', '2026-09-17 20:53:25.931 +00:00');
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('7', '21', 0, 1, '7', 0, 0, 0, 0, NULL, 66, '2026-09-17 20:53:25.937 +00:00', '2026-09-17 20:53:25.937 +00:00');
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('8', '14', 0, 1, '8', 0, 0, 0, 0, NULL, 67, '2026-09-17 20:53:25.943 +00:00', '2026-09-17 20:53:25.943 +00:00');
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('9', '8', 0, 1, '9', 0, 0, 0, 0, NULL, 68, '2026-09-17 20:53:25.950 +00:00', '2026-09-17 20:53:25.950 +00:00');
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('10', '9', 0, 1, '10', 0, 0, 0, 0, NULL, 69, '2026-09-17 20:53:25.957 +00:00', '2026-09-17 20:53:25.957 +00:00');
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('11', '10', 0, 1, '11', 0, 0, 0, 0, NULL, 70, '2026-09-17 20:53:25.963 +00:00', '2026-09-17 20:53:25.963 +00:00');
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('12', '11', 7, 0, '12', 0, 0, 0, 0, NULL, 71, '2026-09-17 20:53:25.971 +00:00', '2026-09-17 20:53:25.971 +00:00');
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('13', '15', 0, 1, '13', 0, 0, 0, 0, NULL, 72, '2026-09-17 20:53:25.978 +00:00', '2026-09-17 20:53:25.978 +00:00');
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('15', '13', 0, 1, '15', 0, 0, 0, 0, NULL, 73, '2026-09-17 20:53:25.985 +00:00', '2026-09-17 20:53:25.985 +00:00');
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('16', '23', 0, 1, '16', 0, 0, 0, 0, NULL, 74, '2026-09-17 20:53:25.992 +00:00', '2026-09-17 20:53:25.992 +00:00');
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('17', '22', 0, 1, '17', 0, 0, 0, 0, NULL, 75, '2026-09-17 20:53:25.998 +00:00', '2026-09-17 20:53:25.998 +00:00');
+31 -3
View File
@@ -10,7 +10,7 @@
# - python-multipart is imported as `multipart` by starlette → hidden import
# - dulwich (version-history backups) imports git backends dynamically →
# collect_submodules('dulwich')
from PyInstaller.utils.hooks import collect_submodules, collect_all
from PyInstaller.utils.hooks import collect_all, collect_submodules, copy_metadata
hiddenimports = []
datas = []
@@ -20,8 +20,9 @@ binaries = []
for pkg in ("uvicorn", "xsdata", "dulwich"):
hiddenimports += collect_submodules(pkg)
# Native standard extras — grab modules + shared libs + any data.
for pkg in ("uvloop", "httptools", "websockets"):
# Native standard extras — grab modules + shared libs + any data. PyAV (`av`)
# carries FFmpeg's shared libraries, which the export's waveform analysis needs.
for pkg in ("uvloop", "httptools", "websockets", "av"):
d, b, h = collect_all(pkg)
datas += d
binaries += b
@@ -30,11 +31,38 @@ for pkg in ("uvloop", "httptools", "websockets"):
# Imported by name, not statically discoverable.
hiddenimports += ["multipart", "anyio"]
# A remote library's password lives in the OS keychain through `keyring`, which
# finds its backends (macOS Keychain, Windows Credential Manager) by entry point
# — so both the modules AND the package metadata that names them must ship.
hiddenimports += collect_submodules("keyring")
datas += copy_metadata("keyring")
# Bundle the canonical version file so konduktor.__version__ can read it at
# runtime from sys._MEIPASS (frontend/package.json is the single source of the
# app version — see konduktor/__init__.py). Path is relative to this spec.
datas += [("../frontend/package.json", ".")]
# The Rekordbox and OneLibrary exporters build their databases from the real
# DDL + scaffolding rows under fixtures/, found at `parents[3] / "fixtures"` —
# i.e. the bundle root. Without these a packaged app cannot export to either.
datas += [
("fixtures/rekordbox/schema.sql", "fixtures/rekordbox"),
("fixtures/rekordbox/seed.sql", "fixtures/rekordbox"),
("fixtures/onelibrary/schema.sql", "fixtures/onelibrary"),
("fixtures/onelibrary/seed.sql", "fixtures/onelibrary"),
# The "Rekordbox Export" target starts from rekordbox's own empty device library.
("fixtures/rekordbox/device/export.pdb", "fixtures/rekordbox/device"),
("fixtures/rekordbox/device/exportExt.pdb", "fixtures/rekordbox/device"),
]
# Which stem engine this build needs, and the pinned weights (read at import by
# konduktor/stems/engine_manager.py).
datas += [
("konduktor/stems/engine.json", "konduktor/stems"),
("konduktor/stems/weights.json", "konduktor/stems"),
]
# The key-detection network's weights (konduktor/core/key_detect.py).
datas += [("konduktor/core/key_model.npz", "konduktor/core")]
a = Analysis(
["sidecar.py"],
pathex=[],
+13
View File
@@ -0,0 +1,13 @@
"""Per-platform adapters. Each owns a native library model and translates the
generic commands onto it; nothing outside an adapter package sees a native type.
Importing this package registers every adapter. Order matters only for the
registry's ``can_open()`` probe, and the probes are mutually exclusive: Traktor
requires an NML header, Rekordbox an encrypted database with its own schema, and
OneLibrary a drive laid out around ``PIONEER/rekordbox/exportLibrary.db``. The
two encrypted databases cannot be confused for one another — they use different
SQLCipher keys, so each driver's decrypt fails outright on the other's file.
"""
from . import onelibrary # noqa: F401 — registers the OneLibrary driver
from . import rekordbox # noqa: F401 — registers the Rekordbox driver
from . import traktor # noqa: F401 — registers the Traktor driver
@@ -0,0 +1,16 @@
"""The OneLibrary adapter: the cross-vendor USB export format.
Importing this package registers the platform for READING (a plugged-in drive)
and as an export TARGET (writing a fresh drive). Two registries, because opening
a library and creating one from nothing are different capabilities.
"""
from ...core import export as core_export
from ...core import registry
from .driver import OneLibraryDriver
from .export import OneLibraryExporter
ONELIBRARY = OneLibraryDriver()
registry.register(ONELIBRARY)
ONELIBRARY_EXPORTER = OneLibraryExporter()
core_export.register(ONELIBRARY_EXPORTER)
@@ -0,0 +1,535 @@
"""The OneLibrary adapter: owns the drive's database and the generic projection.
Mirrors `adapters.rekordbox.adapter`. It holds:
* a ``OneLibraryStore`` — the retained NATIVE model (the open drive),
* a ``TrackIndex`` — the generic READ projection built from it.
**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.
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 InvalidCommand, Unsupported, local_audio_facts
from ...core.capabilities import Capabilities
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
# `playlist.attribute`, from pyrekordbox's own enum. A drive carries no smart
# playlists — rekordbox resolves them to static lists on export, because a CDJ
# cannot evaluate rules — but the value is handled rather than assumed absent.
ATTRIBUTE_PLAYLIST = 0
ATTRIBUTE_FOLDER = 1
ATTRIBUTE_SMART = 4
class OneLibraryAdapter:
platform = "onelibrary"
def __init__(self, path: Path, *, read_only: bool = False):
self.path = Path(path)
self.read_only = read_only
self._store = OneLibraryStore(self.path, read_only=read_only)
self._index = TrackIndex()
self._rebuild()
# ---- projection maintenance -----------------------------------------
def _rebuild(self) -> None:
from ...core.stem_file import is_stem_file
tracks = []
for row in self._store.iter_content():
path = self._drive_path(row)
tracks.append(projection.to_track(
row, path, stem=bool(path) and is_stem_file(path)))
self._index.rebuild(tracks)
def _drive_path(self, row) -> str | 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:
"""Release the database and its file handle.
More than housekeeping here: the library is on a removable drive, and a
held handle is what stops it ejecting.
"""
self._store.close()
def reload(self) -> None:
"""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 ------------------------------------------------------------
@property
def tracks(self) -> list[Track]:
return self._index.tracks
@property
def by_key(self) -> dict[str, Track]:
return self._index.by_key
def track(self, track_id: str) -> Track | None:
return self._index.get(track_id)
def query_tracks(self, **kw):
return self._index.query_tracks(**kw)
def facets(self):
return self._index.facets()
def stats(self, playlist_count: int):
return self._index.stats(playlist_count)
def playlist_count(self) -> int:
return self._store.count_playlists()
def track_cues(self, track_id: str) -> TrackCues | None:
"""A track's cues and beatgrid — and where the approximate counts get fixed.
`projection.to_track` cannot afford the track's analysis files at open
(~23 ms each for the `.EXT`), so it reports no cues and a guessed marker
count. This is the moment the real numbers exist, so the projected track
is corrected here rather than being left disagreeing with the deck.
"""
if self._index.get(track_id) is None:
return None
cues = self._store.cues(track_id)
grid = self._store.anlz_grid(track_id)
from . import beatgrid
markers = beatgrid.markers_from_beats(*grid) if grid is not None else []
result = projection.to_track_cues(cues, markers)
track = self._index.get(track_id)
if track is not None:
track.grid_marker_count = len(result.grid_markers)
track.cue_count = len(result.cues)
track.hotcues = sorted(
(
HotcueChip(slot=c.slot, type=c.type, color=c.color)
for c in result.cues
if c.role == "hotcue" and c.slot is not None
),
key=lambda chip: chip.slot,
)
track.hotcue_count = len(track.hotcues)
return result
# ---- playlists -------------------------------------------------------
def playlist_tree(self) -> list[PlaylistNode]:
"""The drive's playlist tree: a flat table with `playlist_id_parent` links.
A root node's parent is 0, not NULL — so "no parent" is a value here
rather than an absence, and treating 0 as a real id would orphan every
top-level playlist.
"""
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] = {}
for r in rows:
attribute = int(getattr(r, "attribute", 0) or 0)
if attribute == ATTRIBUTE_FOLDER:
kind = "folder"
elif attribute == ATTRIBUTE_SMART:
kind = "smart"
else:
kind = "playlist"
node_id = str(getattr(r, "playlist_id", ""))
nodes[node_id] = PlaylistNode(
id=node_id,
name=getattr(r, "name", "") or "",
kind=kind,
count=(0 if kind == "folder" else len(self._store.playlist_song_ids(node_id))),
children=[],
selectable=kind == "playlist",
# Opened read-only, every flag is False and
# `capabilities.writable` tells the UI why, once.
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)
parents[node_id] = "root" if parent in ("0", "", "None") else parent
roots: list[PlaylistNode] = []
for node_id, node in nodes.items():
parent = nodes.get(parents.get(node_id, "root"))
if parent is None:
roots.append(node)
else:
parent.children.append(node)
return roots
def playlist_entries(self, node_id: str) -> list[str] | None:
ids = self._store.playlist_song_ids(node_id)
return ids if ids or self._is_playlist(node_id) else None
def playlist_tracks(self, node_id: str) -> list[Track] | None:
keys = self.playlist_entries(node_id)
if keys is None:
return None
return [t for k in keys if (t := self._index.get(k)) is not None]
def _is_playlist(self, node_id: str) -> bool:
return any(str(getattr(r, "playlist_id", "")) == str(node_id) for r in self._store.playlists())
# ---- audio / paths ----------------------------------------------------
def audio_path(self, track_id: str):
return self._store.audio_path(track_id)
def audio_facts(self, track_ids: list[str]):
return local_audio_facts(self, track_ids)
def set_path_mapping(self, mapping: PathMapping) -> None:
"""Ignored: a drive's paths are relative to wherever it is mounted.
Path remapping exists because a desktop library stores absolute paths
that go stale when music moves. A OneLibrary drive stores everything
relative to its own root, so it is self-contained by construction and
there is nothing for a mapping to fix.
"""
return None
def unresolved_path_groups(self) -> list:
"""None, ever: a drive's paths are relative to its own mount point."""
return []
def set_session_mappings(self, mappings: list[PathMapping]) -> None:
return None
def path_prefix_suggestions(self) -> dict:
paths = self._store.all_audio_paths()
primary = common_dir_prefix(paths)
return {
"primary": primary,
"groups": [{"prefix": primary, "count": len(paths)}] if primary else [],
}
def remap_preview(self, mapping: PathMapping) -> dict:
paths = [Path(p) for p in self._store.all_audio_paths()]
return {"total": len(paths), "matched": 0, "existing": 0, "samples": []}
def remap_locations(self, mapping: PathMapping) -> dict[str, str]:
raise Unsupported(self._readonly_reason("Rewriting stored paths"))
# ---- save -------------------------------------------------------------
@property
def dirty(self) -> bool:
return self._store.dirty
def save(self):
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 -----------------------------------------------------------
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]:
"""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, key_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}))
# A file with no key of its own gets one, as it gets a grid.
track = key_detect.with_detected_key(item.track, samples, waveform.SR)
export_track = ExportTrack(track=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 = track.length or (int(measured.duration) if measured else None)
prepared.append((item, track, audio, rel, exporter.anlz_files(export_track, rel), jpegs,
markers, hot, length))
added: list[str] = []
for item, track, audio, rel, anlz, jpegs, markers, hot, length in prepared:
track_id = self._store.add_track(
audio, track, rel=rel, anlz_rel=self._store._anlz_rel(rel), anlz=anlz,
jpegs=jpegs, bpm=markers[0].bpm if markers else 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:
"""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._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_key(self, track_id: str, wheel: int, mode: str) -> Track | None:
self._require_writable("Setting the key")
self._store.set_key(track_id, wheel, mode)
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")
def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
return self._store.cover_art(track_id)
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
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._require_writable("Creating playlist folders")
return self._store.create_folder(name, parent_id)
def rename_playlist(self, node_id: str, name: str) -> None:
self._require_writable("Renaming playlists")
self._store.rename_playlist(node_id, name)
def delete_playlist(self, node_id: str) -> None:
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._require_writable("Editing playlists")
return self._store.set_playlist_entries(node_id, track_ids)
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._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._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._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._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._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._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._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._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._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:
"""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._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")
@@ -0,0 +1,66 @@
"""A OneLibrary beatgrid -> the generic marker list.
**The beatgrid is not in the database.** `exportLibrary.db` has no grid table at
all — `content.bpmx100` is a single display tempo — and the real grid is the
`PQTZ` tag of the track's ANLZ `.DAT`, holding EVERY BEAT explicitly. That is the
same arrangement, and the same tag, as a desktop Rekordbox library: a drive is
exported from one, and rekordbox regenerates the analysis files rather than
inventing a new format for them.
Verified end to end on a track whose flexible grid Konduktor itself had written
into `master.db`: exporting it to a OneLibrary drive preserved both tempo
segments exactly (128.00 BPM to 60 s, then 90.00 BPM), so multi-tempo grids
survive the whole chain and the marker list is the right generic shape.
The collapse rule is shared with the Rekordbox adapter deliberately rather than
copied. Two implementations of "when is this a new marker?" would be free to
drift apart by a rounding tolerance, and a drifting grid is a silent corruption
rather than a visible bug. If a third AlphaTheta-format adapter ever appears,
this and `rekordbox.beatgrid` should be promoted to one shared ANLZ module; the
import direction here is the cheapest way to stay honest until then.
"""
from __future__ import annotations
from ...core.model import GridMarker
from ..rekordbox.beatgrid import BPM_EPSILON, markers_from_beats # noqa: F401
__all__ = ["BPM_EPSILON", "markers_from_beats", "beats_from_pqtz", "markers_from_anlz"]
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
(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
file with no beatgrid in it.
`PQTZ` stores time in milliseconds and tempo in hundredths of a BPM.
"""
for tag in getattr(anlz, "tags", []):
if tag.type != "PQTZ":
continue
entries = tag.entries
if not entries:
return None
times: list[float] = []
bpms: list[float] = []
beats: list[int] = []
for e in entries:
try:
time, tempo, beat = int(e.time) / 1000.0, int(e.tempo) / 100.0, int(e.beat)
except (AttributeError, TypeError, ValueError):
continue
times.append(time)
bpms.append(tempo)
beats.append(beat)
return (times, bpms, beats) if times else None
return None
def markers_from_anlz(anlz) -> list[GridMarker]:
"""The generic marker list for a parsed ANLZ file."""
grid = beats_from_pqtz(anlz)
if grid is None:
return []
return markers_from_beats(*grid)
@@ -0,0 +1,117 @@
"""What a OneLibrary drive can persist.
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.
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 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.
"""
from __future__ import annotations
from ...core.capabilities import (
Capabilities,
CueCapabilities,
GridCapabilities,
PlaylistCapabilities,
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,
*,
read_only: bool = False,
editable_fields: list[str] | None = None,
managed_by_export: bool = False,
) -> Capabilities:
return Capabilities(
platform="onelibrary",
version=version,
writable=not read_only,
readonly_cause="browsing" if read_only else None,
cues=CueCapabilities(
editable=True,
hotcue_slots=HOTCUE_SLOTS,
slot_labels="letter",
# 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=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; 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
# The Rekordbox adapter's set: `producer`/`mix` have no column.
editable_fields=sorted(editable_fields or []),
media_kinds=["audio", "stem"],
# 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,
key_writable=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,
),
playlists=PlaylistCapabilities(
folders=True, # `playlist.attribute` 1, nested via playlist_id_parent
# A drive carries no smart playlists: rekordbox resolves them to
# static lists on export, because a CDJ cannot evaluate rules.
smart="none",
reorder=True,
),
save=SaveCapabilities(
# 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.
history=False,
),
)
@@ -0,0 +1,201 @@
"""OneLibrary cues: read from the ANLZ analysis files, not the database.
**The `cue` table is not where a drive's cues are.** It exists in the schema —
and has columns for everything a cue needs — but rekordbox exports an empty one
and puts the cues in the track's ANLZ file instead. Measured on a real rekordbox
7 export of a track carrying four hot cues and a looped memory cue: the `cue`
table held zero rows and every cue was present in the analysis files. The table
appears to be for hardware writing edits BACK to the drive, which is a different
direction than this adapter reads.
Two tags carry cues, and they are not equivalent:
* **`PCOB`** is the original list, and it is SPLIT BY PAD. The `.DAT` holds
only hot cues 1-3 — the three pads the earliest CDJs had — and the `.EXT`
holds 4 and up. Reading only the `.DAT` silently loses pads D-H.
* **`PCO2`** is the extended list in the `.EXT`, and it holds the COMPLETE set
in one tag plus three things `PCOB` has nowhere to put: an RGB colour, a
comment, and the loop length expressed in BEATS.
So `PCO2` is preferred and `PCOB` is the fallback for a drive old enough not to
have one. Both are merged across files before that choice is made, because "the
complete list" must not depend on which file happened to be read.
**Slot numbering differs from `master.db` and this is the trap.** In the desktop
database a hot cue's `djmdCue.Kind` is a sparse bank that SKIPS 4 (`1,2,3,5,…`
for pads A-H). In ANLZ, `hot_cue` is a plain dense 1-based index (1=A, 2=B, …),
and `0` means the cue is a memory cue rather than a pad. The two were aligned
against each other on one track: `Kind` 1/2/3/5 at 40.000 s, 18.773 s, 90.667 s
and 120.000 s came out as `hot_cue` 1/2/3/4 at exactly the same times. Carry the
Rekordbox adapter's mapping over here unchanged and every cue from pad D onward
lands one pad too far along.
Times are MILLISECONDS here, where the desktop database counts frames at 150 fps.
"""
from __future__ import annotations
import logging
from ...core.model import CuePoint
from ..rekordbox import palette
log = logging.getLogger(__name__)
# `loop_time` when a cue is not a loop. Stored as an unsigned 32-bit -1 rather
# than 0, so a plain falsiness test would read it as "a loop ending at zero".
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.
ENTRY_CUE = 1
ENTRY_LOOP = 2
def _entry_kind(value) -> int:
"""An entry's kind as an int, defaulting to a point cue if unreadable."""
try:
return int(value)
except (TypeError, ValueError):
return ENTRY_CUE
def _color(entry) -> str | None:
"""A cue's colour as ``#RRGGBB``, when the tag carries one.
Only `PCO2` stores RGB. A cue with no colour set stores 0,0,0 — which is a
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
if (r, g, b) == (0, 0, 0):
return None
return f"#{r:02X}{g:02X}{b:02X}"
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)
start_ms = int(entry.time)
except (AttributeError, TypeError, ValueError):
return None
loop_ms = getattr(entry, "loop_time", NO_LOOP)
try:
loop_ms = int(loop_ms)
except (TypeError, ValueError):
loop_ms = NO_LOOP
is_loop = _entry_kind(getattr(entry, "type", ENTRY_CUE)) == ENTRY_LOOP
length = 0.0
if is_loop and loop_ms != NO_LOOP and loop_ms > start_ms:
length = (loop_ms - start_ms) / 1000.0
# hot_cue 0 is the memory list; 1..N are the pads, dense and 1-based, so the
# generic 0-based slot is simply one less.
role = "memory" if hot_cue == MEMORY_SLOT else "hotcue"
slot = None if role == "memory" else hot_cue - 1
comment = getattr(entry, "comment", None)
return CuePoint(
name=(str(comment) or None) if comment else None,
type="loop" if length > 0 else "cue",
role=role,
start=start_ms / 1000.0,
length=length,
slot=slot,
color=_color(entry) if with_color else None,
# 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,
)
def _entries(anlz, tag_type: str) -> list:
"""Every entry of every `tag_type` tag in one parsed ANLZ file.
A file carries the tag twice — once for hot cues and once for memory cues —
so both are collected and the entry's own `hot_cue` decides which it is.
That is more robust than trusting the container's type field, which is
absent on some tags in real files.
"""
out: list = []
for tag in getattr(anlz, "tags", []):
if tag.type == tag_type:
out.extend(tag.entries)
return out
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.
"""
files = [f for f in (dat, ext) if f is not None]
if not files:
return []
# PCO2 first: it is the complete list and the only one with colour, comment
# and beat-denominated loops. It lives only in the .EXT.
pco2: list = []
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, 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, editable=editable)) is not None]
return _dedupe(cues)
def _dedupe(cues: list[CuePoint]) -> list[CuePoint]:
"""Collapse the same cue appearing in more than one tag or file.
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] = set()
out: list[CuePoint] = []
for c in cues:
key = (c.role, c.slot, round(c.start * 1000), c.type, round(c.length * 1000))
if key in seen:
continue
seen.add(key)
out.append(c)
out.sort(key=lambda c: (c.start, c.slot if c.slot is not None else -1))
return out
@@ -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
@@ -0,0 +1,67 @@
"""Find OneLibrary drives that are plugged in right now.
This is the one platform whose libraries have no fixed location: Traktor and
Rekordbox each keep theirs at a known per-OS path, but a OneLibrary library is
whatever USB stick happens to be mounted. So detection scans mount points rather
than probing a list of known paths, and what it finds legitimately changes
between two calls a second apart.
Only the mount ROOTS are scanned, never their contents recursively. A drive can
hold tens of thousands of files, the database is at a fixed place within it, and
walking a slow USB stick at startup is exactly the kind of thing that makes an
app feel broken.
"""
from __future__ import annotations
import logging
from pathlib import Path
# Where this OS mounts drives is not adapter knowledge — the file browser needs
# the same answer, and two scanners would drift. It grew here because this is
# the platform whose libraries ARE drives; it lives in core now.
from ...core.places import mount_points as _mount_points
from .layout import DriveLayout
log = logging.getLogger(__name__)
def describe(path: Path) -> dict:
"""A candidate record for a drive or database path, shaped for the picker."""
path = Path(path)
layout = DriveLayout.locate(path)
database = layout.database if layout is not None else path
exists = False
try:
exists = database.is_file()
except OSError:
pass
# The drive's name is what a person recognises — "Hardy", not
# "exportLibrary.db" — so the mount point supplies the label.
root_name = layout.root.name if layout is not None else path.name
return {
"path": str(database),
"label": f"OneLibrary — {root_name}" if root_name else "OneLibrary",
"version": None,
"modified": (database.stat().st_mtime if exists else None),
"exists": exists,
}
def detect_libraries() -> list[dict]:
"""Every mounted drive that carries a OneLibrary database, newest first."""
found: list[dict] = []
seen: set[str] = set()
for root in _mount_points():
layout = DriveLayout.locate(root)
if layout is None:
continue
try:
key = str(layout.database.resolve())
except OSError:
continue
if key in seen:
continue
seen.add(key)
found.append(describe(layout.root))
found.sort(key=lambda c: c["modified"] or 0.0, reverse=True)
return found
@@ -0,0 +1,105 @@
"""Opening OneLibrary drives: recognition and discovery."""
from __future__ import annotations
import logging
from pathlib import Path
from . import discovery
from .adapter import OneLibraryAdapter
from .layout import DriveLayout
log = logging.getLogger(__name__)
class OneLibraryDriver:
platform = "onelibrary"
display_name = "OneLibrary"
# This platform's libraries live on plugged-in drives rather than at a
# fixed path, so `detect()` genuinely changes between calls and the app
# offers them as IMPORT SOURCES. Declared rather than inferred from the
# platform name, so a future Serato-on-a-stick needs no change upstream.
removable = True
suffixes = (".db",)
library_label = "exportLibrary.db"
# What a user PICKS is the mount point, not the database buried three levels
# down inside it — `DriveLayout.locate()` accepts either, but only one of
# them is a thing anybody browses to. The file browser reads this to offer
# folders rather than files.
selects = "directory"
def can_open(self, path: Path) -> bool:
"""Recognise a OneLibrary drive, by layout and then by schema.
Both halves are needed. The layout check alone would accept any file
called ``exportLibrary.db``; the schema check alone cannot run on a
directory, and a drive is what a user actually picks.
It must also not collide with the Rekordbox driver, which probes for
`master.db`. It cannot: both files are SQLCipher databases with no
readable header, but they use DIFFERENT keys, so each driver's decrypt
simply fails on the other's file. The table probe then makes it explicit
rather than leaving the two relying on a key mismatch.
"""
layout = DriveLayout.locate(Path(path))
if layout is None:
return False
return self._has_onelibrary_schema(layout.database)
@staticmethod
def _has_onelibrary_schema(path: Path) -> bool:
try:
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.devicelib_plus.database import BLOB
from pyrekordbox.utils import deobfuscate
except ImportError: # pragma: no cover — dependency missing
return False
con = None
try:
con = sqlcipher.connect(str(path))
con.execute(f"PRAGMA key='{deobfuscate(BLOB)}'")
# `content` is too generic a name to trust on its own, so the probe
# asks for a pair only this schema has together.
rows = con.execute(
"SELECT name FROM sqlite_master WHERE type='table' "
"AND name IN ('content','hotCueBankList')"
).fetchall()
return len(rows) == 2
except Exception: # noqa: BLE001 — wrong key or not a database
return False
finally:
if con is not None:
try:
con.close()
except Exception: # noqa: BLE001
pass
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()
def describe(self, path: Path) -> dict:
return discovery.describe(path)
def display_name_for(self, path: Path) -> str:
"""What to call this library on screen: the DRIVE's name.
The filename is not a stable answer here. A OneLibrary library can be
opened by its mount point OR by the database three levels inside it —
`DriveLayout.locate()` accepts both on purpose — so the same stick would
be "Hardy" opened one way and "exportLibrary.db" opened the other.
"""
layout = DriveLayout.locate(Path(path))
return layout.root.name if layout is not None else Path(path).name
def restore(self, path: Path, data: bytes) -> None:
"""Not supported: a drive is a database plus analysis files plus audio.
`capabilities.save.history` is False for the same reason, so nothing
should reach this.
"""
raise NotImplementedError(
"Konduktor does not version OneLibrary drives: the library is a "
"database, N analysis files and the audio itself."
)
@@ -0,0 +1,486 @@
"""Writing a OneLibrary USB drive from nothing.
The export target that matters most for a DJ: a stick CDJ-class hardware reads.
## What a drive is
The destination folder IS the drive root. Three things go in it:
<root>/PIONEER/rekordbox/exportLibrary.db the library (SQLCipher)
<root>/PIONEER/USBANLZ/P0xx/xxxxxxxx/ANLZ0000.{DAT,EXT} per-track analysis
<root>/… the audio, already copied
Audio is already on disk when this runs, laid out by the runner mirroring the
source tree. Every path the database stores is **drive-relative with a leading
slash** — `/House/track.mp3` — which is not a host path, and the reader's
`DriveLayout.resolve()` is what joins it back to a mount point.
## What could not be reused, and why
`master.db`'s schema comes free from `pyrekordbox`'s ORM. This one has no ORM, so
the DDL is the checked-in `fixtures/onelibrary/schema.sql` — 22 tables extracted
from a real rekordbox 7 export, which is also what the read tests run against.
Cues are **not** in the `cue` table: rekordbox exports it empty and puts them in
the analysis files. So `anlz_writer` builds those, with ANLZ's own **dense
1-based** `hot_cue` numbering — not `master.db`'s sparse bank that skips 4.
## Deliberately not written
`PWAV`/`PWV2`-`PWV7` waveform tags, and the `cue` table's eight MPEG seek
columns. Both are documented unknowns (see the OneLibrary handoff §7): a CDJ
draws its waveform from those tags and seeks VBR MP3s with those columns, and
whether their absence is unplayable, ugly or fine has never been measured. A
guess here fails in a club rather than at a desk, so they are left out and said
so rather than invented.
"""
from __future__ import annotations
import hashlib
import logging
from datetime import date
from pathlib import Path
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
from ...core.cue_colors import effective_color
from ..rekordbox import anlz_writer as W
from ..rekordbox import artwork, palette, timebase
from ..rekordbox.beatgrid import beats_from_markers
from ..rekordbox.projection import render_key
from .capabilities import capabilities_for
from .layout import DB_SUBPATH
log = logging.getLogger(__name__)
SCHEMA = Path(__file__).resolve().parents[3] / "fixtures" / "onelibrary" / "schema.sql"
#: rekordbox's scaffolding rows — browse menu items, categories, sort columns,
#: the colour palette — copied from a real export. See the file's header.
SEED = SCHEMA.with_name("seed.sql")
#: rekordbox writes this in `property.dbVersion` on a real export.
DB_VERSION = "1000"
#: Seen on every track of a real export; semantics undocumented, copied as-is.
ANALYSED_BITS = 41
#: `content.contentLink`, as rekordbox 7 writes it beside `analysedBits` 41 (a
#: re-analysed track carried 1902336 beside 105; what the bits mean is unknown).
#: NOT optional: measured by blanking it on one track of a rekordbox-written
#: stick — that row's song-list preview fell back to plain blue and gained a "?"
#: beside CUE, exactly as every row of Konduktor's exports did while it was NULL.
#: `masterDbId`/`masterContentId` were cleared the same way and changed nothing.
CONTENT_LINK = 788224
OTHER_PLAYLIST = "Other"
def _drive_relative(path: Path, root: Path) -> str:
"""`/House/track.mp3` — drive-relative, WITH the leading slash.
The slash is not a host root. Joining one of these naively discards the
mount point and silently yields a path that looks like an empty drive.
"""
return "/" + path.relative_to(root).as_posix()
def _anlz_dir(drive_relative: str) -> str:
"""`/PIONEER/USBANLZ/P0xx/xxxxxxxx` for a track.
rekordbox derives these two levels from a hash whose algorithm is not
published. It does not need to match: the database stores the resulting path
in `content.analysisDataFilePath` and that column is what a player follows.
So this derives its own stable value in the same SHAPE, which keeps a drive
recognisable to a human without pretending to reproduce rekordbox's scheme.
"""
digest = hashlib.sha1(drive_relative.encode("utf-8")).hexdigest().upper()
return f"/PIONEER/USBANLZ/P0{digest[:2]}/{digest[2:10]}"
class OneLibraryExporter:
platform = "onelibrary"
menu_order = 10
#: Relative to the drive root, which is what the destination folder is.
library_filename = str(Path("PIONEER") / DB_SUBPATH)
#: A CDJ looks for `PIONEER/` at the root of the stick and nowhere else.
drive_root = True
def capabilities(self):
"""What a drive can hold — no device, no path, no library to read.
`writable` is overridden to True. The adapter's own set says False
because Konduktor cannot EDIT a plugged-in drive in place; an export
target is a different question, and it is one Konduktor can now answer
yes to. Leaving the adapter's answer here would have the UI report that
the thing it just wrote cannot be written.
"""
caps = capabilities_for()
# An exported drive CARRIES artwork (`_write_art`); the adapter's False
# means "cannot edit a plugged-in drive's art", a different question.
return caps.model_copy(update={
"writable": True, "readonly_cause": None,
"tracks": caps.tracks.model_copy(update={"artwork": True}),
})
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.devicelib_plus.database import BLOB
from pyrekordbox.utils import deobfuscate
root = Path(destination)
library = root / "PIONEER" / DB_SUBPATH
library.parent.mkdir(parents=True, exist_ok=True)
# SQLCipher will not re-key an existing file — and the WAL and shared
# memory files beside it must go too. rekordbox leaves both on a stick
# it has mounted, and SQLite REPLAYS a leftover WAL into whatever
# database it finds, so a fresh library would open with the old one's
# pages written over it.
for stale in (library, *(library.with_name(library.name + s) for s in ("-wal", "-shm"))):
if stale.exists():
stale.unlink()
extra: list[Path] = []
con = sqlcipher.connect(str(library))
try:
# The same universal key every vendor's drive uses — a OneLibrary
# stick is readable by any of them, which is the point of it.
con.execute(f"PRAGMA key='{deobfuscate(BLOB)}'")
con.executescript(SCHEMA.read_text())
con.executescript(SEED.read_text(encoding="utf-8"))
extra += self._fill(con, payload, root)
con.commit()
finally:
con.close()
return WrittenLibrary(library=library, extra=extra)
# ---- the database --------------------------------------------------------
def _fill(self, con, payload: ExportPayload, root: Path) -> list[Path]:
lookups = {name: {} for name in ("artist", "album", "genre", "label", "key")}
# Image ids are handed out in track order, one per track that HAS art —
# rekordbox does not share an image between tracks, even identical ones.
lookups["image"] = {"next": 0}
written: list[Path] = []
by_source: dict[str, int] = {}
total = len(payload.tracks)
for n, item in enumerate(payload.tracks, start=1):
# Each track is DECODED for its waveform, so this loop is the slow
# part of the write — report it, and let a cancel land between tracks.
payload.checkpoint(f"Analysing {item.track.title or item.destination.name} ({n}/{total})", step=n, of=total)
by_source[item.source_id] = n
written += self._write_track(con, n, item, root, lookups)
self._write_playlists(con, payload, by_source)
con.execute(
"INSERT INTO property (deviceName, dbVersion, numberOfContents, "
"createdDate, backGroundColorType, myTagMasterDBID) VALUES (?,?,?,?,?,?)",
(payload.name, DB_VERSION, len(payload.tracks),
date.today().isoformat(), 0, 0),
)
return written
@staticmethod
def _lookup(con, table: str, cache: dict, name: str | None) -> int | None:
"""Find-or-create a row in one of the name tables."""
if not name:
return None
if name in cache:
return cache[name]
column = f"{table}_id"
row = con.execute(f"SELECT {column} FROM {table} WHERE name = ?", (name,)).fetchone()
if row:
cache[name] = row[0]
return row[0]
cur = con.execute(f"INSERT INTO {table} (name) VALUES (?)", (name,))
cache[name] = cur.lastrowid
return cur.lastrowid
def _write_track(self, con, content_id: int, item: ExportTrack,
root: Path, lookups: dict) -> list[Path]:
track = item.track
rel = _drive_relative(item.destination, root)
anlz_rel = f"{_anlz_dir(rel)}/ANLZ0000.DAT"
try:
size = item.destination.stat().st_size
except OSError:
size = 0
sample_rate, bit_depth = _audio_format(item.destination)
image_id, art_files = self._write_art(con, item, root, lookups["image"])
con.execute(
"INSERT INTO content (content_id, title, titleForSearch, bpmx100, length, "
"trackNo, artist_id_artist, album_id, genre_id, label_id, key_id, image_id, "
"djComment, rating, releaseDate, dateAdded, path, fileName, fileSize, "
"fileType, bitrate, bitDepth, samplingRate, isHotCueAutoLoadOn, "
"isKuvoDeliverStatusOn, masterDbId, masterContentId, "
"analysisDataFilePath, analysedBits, contentLink, hasModified, cueUpdateCount, "
"analysisDataUpdateCount, informationUpdateCount) "
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
(
content_id, track.title, (track.title or "").lower(),
int(round((track.bpm or 0) * 100)) or None, track.length,
None,
self._lookup(con, "artist", lookups["artist"], track.artist),
self._lookup(con, "album", lookups["album"], track.album),
self._lookup(con, "genre", lookups["genre"], track.genre),
self._lookup(con, "label", lookups["label"], track.label),
# NOT `track.key` — that is the SOURCE platform's notation, and
# writing Traktor's "10m" into a Pioneer library shows "10m"
# where the deck expects "Cm". Rendered from the parsed wheel.
self._lookup(con, "key", lookups["key"],
render_key(track.key_wheel, track.key_mode)),
image_id,
track.comment, track.rating or 0, track.release_date,
date.today().isoformat(), rel, item.destination.name, size,
# kbps, as every Pioneer library stores it; the generic model
# carries bits per second.
_file_type(item.destination), _kbps(track.bitrate),
bit_depth, sample_rate, 1, 1, 0, content_id,
anlz_rel, ANALYSED_BITS, CONTENT_LINK, 0, 0, 0, 0,
),
)
return art_files + self._write_anlz(item, rel, root / anlz_rel.lstrip("/"))
# ---- artwork -------------------------------------------------------------
@staticmethod
def _write_art(con, item: ExportTrack, root: Path, counter: dict) -> tuple[int | None, list[Path]]:
"""One track's cover: four JPEGs and an `image` row, as rekordbox 7 writes.
`PIONEER/Artwork/00001/` holds `a<n>.jpg` / `a<n>_m.jpg` and a byte-
identical `b<n>.jpg` / `b<n>_m.jpg` (80 and 240 px); `image.path` names the
`b` file and `content.image_id` points at the row. rekordbox's own export
writes both letters — the `a` pair presumably for the legacy `export.pdb`
readers — so both are written here too.
Everything goes in folder `00001`. How rekordbox splits a large library
across folders is not known (the reference export has 6 images); a single
folder is what it demonstrably reads.
"""
if not item.art:
return None, []
jpegs = artwork.pioneer_jpegs(item.art[0])
if jpegs is None:
return None, []
counter["next"] += 1
n = counter["next"]
folder = root / "PIONEER" / "Artwork" / "00001"
folder.mkdir(parents=True, exist_ok=True)
files = []
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 (?, ?)",
(n, f"/PIONEER/Artwork/00001/b{n}.jpg"))
return n, files
# ---- the analysis files --------------------------------------------------
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,
which readers prefer — lives only in the `.EXT`.
**The `.DAT` must carry `PVBR` and the preview waveforms**, or rekordbox
shows neither the grid nor the cues (see `anlz_writer`). The `.EXT` and
`.2EX` waveforms only affect drawing: the song-list preview and the
deck's scrolling waveform. Tag order is rekordbox's in each file:
.DAT PPTH PVBR PQTZ PWAV PWV2 PCOB PCOB
.EXT PPTH PWV3 PCOB PCOB PCO2 PCO2 PWV5 PWV4
.2EX PPTH PWV7 PWV6 PWVC
An undecodable file still gets the `.DAT` (with a flat preview) and the
`.EXT` cue lists — its grid and cues must show — but no drawn waveforms.
"""
# rekordbox's clock runs ~25 ms behind the decoded audio on MP3/AAC (see
# `timebase`): beats and cues are computed in the decoded time base and
# shifted as they are packed, and the waveform frames are measured with
# the same lead so they line up with the beats.
off = timebase.offset(item.destination)
measured = item.waveform(lead=off)
# The DECODED length where there is one: `Track.length` is whole seconds
# rounded down, and a grid expanded to it loses the track's last beat.
beats = self._beats(item, measured.duration if measured else None)
cues = self._cue_dicts(item, beats, off)
if measured:
previews = W.preview_tags(measured.columns.rms, measured.columns.brightness)
ext_waves, two_ex = W.waveform_tags(measured.frames.bands)
else:
previews, ext_waves, two_ex = W.flat_preview_tags(), [], []
tags = [W.path_tag(rel), W.vbr_tag(W.mp3_samples(item.destination))]
if beats:
tags.append(W.beatgrid_tag([(n, bpm, timebase.to_pioneer(t, off))
for n, bpm, t in beats]))
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:]]
files = [(".DAT", W.anlz_bytes(tags)), (".EXT", W.anlz_bytes(ext))]
if 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
def _beats(item: ExportTrack, duration: float | None = None) -> list[tuple[int, float, float]]:
"""Every beat, expanded from the generic marker list.
A Pioneer grid has no tempo markers — it is a flat list of beats — so a
flexible multi-tempo grid crosses by expansion here and is collapsed
back by `markers_from_beats` on read. Both directions share one
definition of where a tempo change starts.
"""
cues = item.cues
if not cues or not cues.grid_markers:
return []
duration = (duration or float(item.track.length or 0)
or (cues.grid_markers[-1].start + 60.0))
nums, bpms, times = beats_from_markers(cues.grid_markers, duration)
return list(zip(nums, bpms, times))
@staticmethod
def _cue_dicts(item: ExportTrack, beats: list | None = None, off: float = 0.0) -> list[dict]:
"""Generic cues in the shape `anlz_writer` packs.
Slot numbering is ANLZ's own: **dense 1-based**, 0 for a memory cue.
The generic model's `slot` is 0-based, so every hot cue is +1. Reuse
`master.db`'s sparse bank here and every cue from pad D lands one pad
too far along.
"""
out: list[dict] = []
for cue in (item.cues.cues if item.cues else []):
is_loop = cue.type == "loop" or cue.length > 0
# A hot cue carries what Konduktor SHOWS — stored colour, else the
# type's (blue cue, green loop) — as a rekordbox palette CODE, which
# is what rekordbox draws from; "unset" draws its own defaults. A
# memory cue keeps rekordbox's own "unset".
code, rgb = palette.code_for(cue.color if cue.role == "memory" else effective_color(cue))
out.append({
"hot_cue": 0 if cue.role == "memory" or cue.slot is None else cue.slot + 1,
"kind": 2 if is_loop else 1,
"time_ms": int(round(timebase.to_pioneer(cue.start, off) * 1000)),
"loop_ms": (int(round(timebase.to_pioneer(cue.start + cue.length, off) * 1000))
if is_loop else None),
"rgb": rgb,
"code": code,
"beats": _loop_beats(cue.start, cue.length, beats or []) if is_loop else None,
})
return out
# ---- playlists -----------------------------------------------------------
def _write_playlists(self, con, payload: ExportPayload, by_source: dict) -> None:
"""One folder named after the export, with the tree preserved under it.
`playlist` is a flat table with `playlist_id_parent`, so folders and
playlists are the same row kind told apart by `attribute` (1 = folder).
"""
next_id = [0]
def add(name: str, parent: int | None, *, folder: bool) -> int:
next_id[0] += 1
con.execute(
"INSERT INTO playlist (playlist_id, sequenceNo, name, attribute, "
"playlist_id_parent) VALUES (?,?,?,?,?)",
(next_id[0], next_id[0], name, 1 if folder else 0, parent),
)
return next_id[0]
root = add(payload.name, None, folder=True)
folders: dict[tuple[str, ...], int] = {(): root}
for playlist in payload.playlists:
parent = root
for depth in range(1, len(playlist.folders) + 1):
branch = tuple(playlist.folders[:depth])
if branch not in folders:
folders[branch] = add(branch[-1], folders[branch[:-1]], folder=True)
parent = folders[branch]
self._fill_playlist(con, add(playlist.name, parent, folder=False),
playlist.track_ids, by_source)
claimed = {t for p in payload.playlists for t in p.track_ids}
loose = [t.source_id for t in payload.tracks if t.source_id not in claimed]
if loose:
self._fill_playlist(con, add(OTHER_PLAYLIST, root, folder=False),
loose, by_source)
@staticmethod
def _fill_playlist(con, playlist_id: int, track_ids: list[str], by_source: dict) -> None:
for seq, source_id in enumerate(track_ids, start=1):
content_id = by_source.get(source_id)
if content_id is not None:
con.execute(
"INSERT INTO playlist_content (playlist_id, content_id, sequenceNo) "
"VALUES (?,?,?)", (playlist_id, content_id, seq)
)
#: rekordbox's `fileType` codes, as `pyrekordbox.devicelib_plus.FileType` has them.
#: `.stem.m4a` (a Traktor STEM) is an M4A to a Pioneer player.
_FILE_TYPES = {".mp3": 1, ".m4a": 4, ".mp4": 4, ".aac": 4, ".flac": 5, ".wav": 11,
".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)
def _kbps(bitrate: int | None) -> int | None:
"""Generic bits per second → Pioneer's kbps."""
if not bitrate:
return None
return int(round(bitrate / 1000))
def _audio_format(path: Path) -> tuple[int | None, int | None]:
"""(sample rate, bit depth) read from the COPIED file, or Nones.
Not in the generic model, and not worth adding for one target: the file is
right here, and reading its header costs a millisecond.
"""
try:
import mutagen
info = getattr(mutagen.File(str(path)), "info", None)
except Exception: # an unreadable file still exports; these stay empty
return None, None
rate = getattr(info, "sample_rate", None)
depth = getattr(info, "bits_per_sample", None)
return (int(rate) if rate else None), (int(depth) if depth else None)
def _loop_beats(start: float, length: float, beats: list[tuple[int, float, float]]) -> int | None:
"""A loop's length in whole beats at the tempo governing its start.
rekordbox stores it (`loop_num`/`loop_den`, e.g. 4/1). A loop that is not a
whole number of beats — or a track with no grid — gets none, as rekordbox
itself writes for a loop set by hand.
"""
bpm = next((b for _, b, t in reversed(beats) if t <= start + 1e-3), None)
if not bpm or length <= 0:
return None
count = length * bpm / 60.0
whole = round(count)
return whole if whole >= 1 and abs(count - whole) < 0.05 else None
@@ -0,0 +1,103 @@
"""Where things live on a OneLibrary drive.
A OneLibrary library is a **removable drive**, not a file, and that is the one
structural fact that separates this adapter from every other one. Everything the
library refers to — the audio, the analysis files, the artwork — is stored
DRIVE-RELATIVE (``/Contents/Loopmasters/Demo Track 1.mp3``), because the same
stick must resolve on a CDJ, on macOS and on Windows, where it is mounted at
three different places. Nothing inside the database is an absolute host path.
So resolving a stored path means joining it to the mount point, and that is what
this module exists to do. It is kept separate from the store because it is also
the knowledge a future *export* would need to lay a drive out from nothing.
Two layout details are measured from a real rekordbox 7 export rather than
assumed:
* the database is at ``PIONEER/rekordbox/exportLibrary.db``, alongside — not
instead of — the legacy ``export.pdb``. Both formats coexist on one drive,
and newer players prefer OneLibrary when they find it.
* analysis files sit under ``PIONEER/USBANLZ/P0<xx>/<8 hex>/ANLZ0000.*``,
where the two directory levels are a hash of the track's path. Konduktor
never has to compute that hash to READ, because ``content.analysisDataFilePath``
stores the resulting path outright — it would only matter for writing.
``.PIONEER`` is accepted as well as ``PIONEER``. Traktor's own OneLibrary writer
looks for both, so a drive written by it may use the dot-prefixed (hidden) form.
"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
# In preference order: a drive may legitimately carry either spelling, and the
# visible one is what rekordbox itself writes.
PIONEER_DIRS = ("PIONEER", ".PIONEER")
DB_SUBPATH = Path("rekordbox") / "exportLibrary.db"
# The analysis file the database points at is the `.DAT`; its siblings differ
# only by extension. `.EXT` carries the complete cue list and the colour
# waveforms, `.2EX` the newer high-resolution ones.
ANLZ_EXTENDED = ".EXT"
@dataclass(frozen=True)
class DriveLayout:
"""A located OneLibrary drive: its mount point and its database."""
root: Path
database: Path
@classmethod
def locate(cls, path: Path) -> "DriveLayout | None":
"""Find the layout for `path`, or None if it is not a OneLibrary drive.
Accepts either end of the drive deliberately: the MOUNT POINT, which is
what discovery finds and what a user picks in a file browser, or the
``exportLibrary.db`` ITSELF, which is what someone reaches by drilling
into the folder or by re-opening a remembered path. Both name the same
library, and refusing one of them would make the picker and the
last-opened shortcut disagree about what a valid library is.
"""
path = Path(path)
try:
if path.is_file():
# .../PIONEER/rekordbox/exportLibrary.db -> the drive is 3 up.
if path.name.lower() != "exportLibrary.db".lower():
return None
root = path.parent.parent.parent
if path.parent.parent.name not in PIONEER_DIRS:
return None
return cls(root=root, database=path)
if path.is_dir():
for pioneer in PIONEER_DIRS:
db = path / pioneer / DB_SUBPATH
if db.is_file():
return cls(root=path, database=db)
except OSError:
return None
return None
def resolve(self, drive_relative: str | None) -> Path | None:
"""A stored drive-relative path as a real path on this host.
Stored paths are POSIX-style and lead with a slash. That leading slash is
NOT a host root — treating it as one is the mistake this method exists to
prevent, since ``Path('/Volumes/X') / '/Contents/a.mp3'`` silently
discards the mount point and yields ``/Contents/a.mp3``.
"""
if not drive_relative:
return None
relative = str(drive_relative).replace("\\", "/").lstrip("/")
if not relative:
return None
return self.root / relative
def extended_anlz(self, dat_path: Path) -> Path:
"""The `.EXT` beside a given `.DAT`.
Cues are read from the `.EXT`, not the `.DAT` the database points at:
see `cues.py` for why that distinction is load-bearing rather than a
preference.
"""
return dat_path.with_suffix(ANLZ_EXTENDED)
@@ -0,0 +1,120 @@
"""OneLibrary rows -> the generic projection.
The only place a ``devicelib_plus`` ORM object becomes a generic `Track` /
`TrackCues`. Everything above this file sees generic types exclusively.
Field conventions are read off a real rekordbox 7 export rather than guessed:
* ``bpmx100`` is the tempo in hundredths, and it is a DISPLAY value — the real
grid is per-beat in the ANLZ file, and a variable-tempo track stores only its
first tempo here.
* ``rating`` is 0-5 directly, like `master.db` and unlike Traktor's /51.
* ``length`` is whole seconds.
* ``path`` is drive-relative with a leading slash; the store resolves it.
* dates arrive as `datetime` from the ORM, not as strings.
"""
from __future__ import annotations
from ...core.model import GridMarker, Track, TrackCues
from ..rekordbox.projection import parse_key
def _name_of(related) -> str | None:
"""A joined lookup row's display name, or None when unset."""
if related is None:
return None
value = getattr(related, "name", None)
return str(value) if value else None
def _iso_date(value) -> str | None:
"""`YYYY-MM-DD` from whatever the column holds.
The ORM converts the stored strings to `datetime`, so this takes the date
part of one — but a drive written by another vendor's software may well
store a plain string, and passing that through unchanged is better than
losing it.
"""
if not value:
return None
date = getattr(value, "date", None)
if callable(date):
try:
return date().isoformat()
except Exception: # noqa: BLE001
pass
text = str(value).strip()
return text.split(" ")[0] if text else None
def _bpm(row) -> float | None:
raw = getattr(row, "bpmx100", None)
if not raw:
return None
return round(int(raw) / 100.0, 2)
def to_track(row, drive_path: str | None = None, *, stem: bool = False) -> Track:
"""Project one ``Content`` row.
**The three count fields are approximations here**, and deliberately so. Cues
and the beatgrid both live in the track's ANLZ files, and parsing a track's
`.EXT` costs ~23 ms — ~23 s for a 1,000-track drive if done at open. So a
track that has an analysis file and a tempo is reported as having one grid
marker (constant tempo, true for all but a fraction of a percent of tracks)
and no cues, and all three are corrected the moment the track's cues are
actually read. `adapter.track_cues` is where that happens.
Reporting zero cues rather than a guess is the honest direction to be wrong
in: a count that appears from nowhere on selection reads as the detail
arriving, whereas one that shrinks reads as data being lost.
"""
key_name = _name_of(getattr(row, "key", None))
wheel, mode = parse_key(key_name)
has_analysis = bool(getattr(row, "analysisDataFilePath", None))
bpm = _bpm(row)
return Track(
id=str(getattr(row, "path", "") or ""),
artist=_name_of(getattr(row, "artist", None)),
title=getattr(row, "title", None),
album=_name_of(getattr(row, "album", None)),
genre=_name_of(getattr(row, "genre", None)),
label=_name_of(getattr(row, "label", None)),
remixer=_name_of(getattr(row, "remixer", None)),
# OneLibrary has `composer` and `lyricist`, neither of which is Traktor's
# "producer" or "mix", so nothing is mapped onto them approximately.
producer=None,
mix=None,
comment=getattr(row, "djComment", None),
bpm=bpm,
key=key_name,
key_wheel=wheel,
key_mode=mode,
rating=max(0, min(5, int(getattr(row, "rating", 0) or 0))),
playcount=getattr(row, "djPlayCount", None),
length=getattr(row, "length", None),
# kbps here; the generic model (and the table) carry bits per second.
bitrate=(getattr(row, "bitrate", None) or 0) * 1000 or None,
import_date=_iso_date(getattr(row, "dateAdded", None)),
last_played=None, # the drive records history as playlists, not per track
release_date=_iso_date(getattr(row, "releaseDate", None))
or (str(getattr(row, "releaseYear", "") or "") or None),
filepath=drive_path,
cue_count=0,
hotcue_count=0,
grid_marker_count=1 if (bpm and has_analysis) else 0,
grid_locked=False, # OneLibrary has no grid lock
# What the FILE is, as the deck plays it — see the Rekordbox projection.
media_kind="stem" if stem else "audio",
)
def to_track_cues(cues: list, grid_markers: list[GridMarker]) -> TrackCues:
"""Project a track's cues and beatgrid.
`cues` are already generic — see `store.cues` for why that boundary sits
where it does — so this is the assembly point rather than a translation.
Nothing here is editable: a OneLibrary drive is read-only in Konduktor, and
`capabilities.writable` says so at the library level.
"""
return TrackCues(grid_markers=grid_markers, grid_locked=False, cues=list(cues))
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,23 @@
"""The Rekordbox adapter: ``master.db`` (SQLCipher) via ``pyrekordbox``.
Importing this package registers the platform for READING and editing a library
in place, and as an export TARGET for writing a fresh one. Two registries,
because opening a library and creating one from nothing are different
capabilities.
"""
from ...core import export as core_export
from ...core import registry
from .driver import RekordboxDriver
from .device_export import RekordboxDeviceExporter
from .export import RekordboxExporter
REKORDBOX = RekordboxDriver()
registry.register(REKORDBOX)
REKORDBOX_EXPORTER = RekordboxExporter()
core_export.register(REKORDBOX_EXPORTER)
# The stick's legacy Device Library (`export.pdb`): a separate TARGET with no
# reader of its own — Konduktor reads a stick through its OneLibrary database.
REKORDBOX_DEVICE_EXPORTER = RekordboxDeviceExporter()
core_export.register(REKORDBOX_DEVICE_EXPORTER)
@@ -0,0 +1,554 @@
"""The Rekordbox adapter: owns the native database and the generic projection.
Mirrors `adapters.traktor.adapter`. It holds:
* a ``RekordboxStore`` — the retained NATIVE model (the open ``master.db``),
* a ``TrackIndex`` — the generic READ projection built from it.
**Track metadata and playlists are writable; cues and the beatgrid are not
yet.** Those two are separate native stores (two DB tables kept consistent, and
the per-track ANLZ analysis files), so they keep refusing until milestone 3 —
and `capabilities.cues.editable` / `grid.editable` say so, which is what the UI
actually gates on. The raise is the backstop, not the mechanism.
Writes are refused entirely, and permanently, on a **cloud-synced** library:
propagating a bad sync state to the user's other machines is not something
version history can undo — especially here, where there is no version history at
all. That check lives at the top of every command path so no future command can
forget it.
"""
from __future__ import annotations
from pathlib import Path
from ...core.adapter import InvalidCommand, Unsupported, local_audio_facts
from ...core.capabilities import Capabilities
from ...core.model import GridMarker, PlaylistNode, Track, TrackCues
from ...core.pathmap import PathMapping, common_dir_prefix
from ...core.query import TrackIndex
from . import capabilities as caps
from . import palette, projection, timebase
from ...core import add_analysis
from .store import RekordboxStore
class RekordboxAdapter:
platform = "rekordbox"
def __init__(self, path: Path):
self.path = Path(path)
self._store = RekordboxStore(self.path)
self._index = TrackIndex()
self._cloud_synced = self._store.cloud_synced
self._rebuild()
# ---- projection maintenance -----------------------------------------
def _rebuild(self) -> None:
kinds = self._store.cue_kinds()
self._index.rebuild(
[
projection.to_track(row, kinds.get(str(row.ID), ()),
stem=self._store.is_stem(str(row.ID)))
for row in self._store.iter_content()
]
)
def _refresh_cues(self, track_id: str) -> TrackCues:
"""Re-project a track AND return its fresh cues.
Every mutating cue/grid command ends here: the contract is that a command
returns the refreshed projection, so a route can never serve a stale one.
"""
self._refresh(track_id)
return self.track_cues(track_id) or TrackCues()
def _refresh(self, track_id: str) -> None:
"""Re-project one track after a command, so the UI cannot go stale.
Every mutating command must end in this — a forgotten refresh is a
silently stale projection that no byte- or row-level test would catch.
"""
kinds = self._store.cue_kinds()
row = self._store.content(track_id)
self._index.replace(projection.to_track(row, kinds.get(str(row.ID), ()),
stem=self._store.is_stem(str(row.ID))))
def close(self) -> None:
"""Release the database connection.
Rekordbox's library is a live SQLite file, not a document parsed into
memory: leaving the connection open keeps a file handle (and possibly a
`-wal`) around, so an adapter that is being replaced must be closed.
"""
self._store.close()
def reload(self) -> None:
"""Re-read the library from disk, DISCARDING unsaved edits (see
`RekordboxStore.discard` for why a plain re-open is not enough)."""
self._store.discard()
self._cloud_synced = self._store.cloud_synced
self._rebuild()
# ---- identity --------------------------------------------------------
def capabilities(self) -> Capabilities:
return caps.capabilities_for(
self.path,
cloud_synced=self._cloud_synced,
editable_fields=sorted(RekordboxStore.EDITABLE_FIELDS),
)
@property
def cloud_synced(self) -> bool:
return self._cloud_synced
# ---- read ------------------------------------------------------------
@property
def tracks(self) -> list[Track]:
return self._index.tracks
@property
def by_key(self) -> dict[str, Track]:
return self._index.by_key
def track(self, track_id: str) -> Track | None:
return self._index.get(track_id)
def query_tracks(self, **kw):
return self._index.query_tracks(**kw)
def facets(self):
return self._index.facets()
def stats(self, playlist_count: int):
return self._index.stats(playlist_count)
def playlist_count(self) -> int:
return self._store.count_playlists()
def track_cues(self, track_id: str) -> TrackCues | None:
if self._index.get(track_id) is None:
return None
cues = projection.to_track_cues(
self._store.cues(track_id), self._store.anlz_grid(track_id),
self._store.time_offset(track_id),
)
# The track projection carries an APPROXIMATE grid_marker_count until the
# grid is actually read (see projection.to_track). This is that moment —
# correct it, so the library table stops showing the guess.
track = self._index.get(track_id)
if track is not None:
track.grid_marker_count = len(cues.grid_markers)
return cues
# ---- playlists -------------------------------------------------------
def playlist_tree(self) -> list[PlaylistNode]:
"""Rekordbox stores the tree as a flat table with ``ParentID`` links."""
from pyrekordbox.masterdb import models as tables
rows = self._store.playlists()
folder = int(tables.PlaylistType.FOLDER)
smart = int(tables.PlaylistType.SMART_PLAYLIST)
writable = not self._cloud_synced
nodes: dict[str, PlaylistNode] = {}
parents: dict[str, str] = {}
for r in rows:
attribute = int(r.Attribute or 0)
kind = "folder" if attribute == folder else ("smart" if attribute == smart else "playlist")
node_id = str(r.ID)
nodes[node_id] = PlaylistNode(
id=node_id,
name=r.Name or "",
kind=kind,
count=(0 if kind == "folder" else len(self._store.playlist_song_ids(node_id))),
children=[],
# A smart playlist has no static entry list; a folder has no tracks.
selectable=kind == "playlist",
# Rekordbox's own working lists are filtered out by the store, so
# everything reaching here is the user's and may be edited — as
# long as the library itself is writable at all.
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(r.ParentID or "root")
parents[node_id] = "root" if parent in ("0", "", "root", "None") else parent
roots: list[PlaylistNode] = []
for node_id, node in nodes.items():
parent_id = parents.get(node_id, "root")
parent = nodes.get(parent_id)
if parent is None:
roots.append(node)
else:
parent.children.append(node)
return roots
def playlist_entries(self, node_id: str) -> list[str] | None:
ids = self._store.playlist_song_ids(node_id)
return ids if ids or self._is_playlist(node_id) else None
def playlist_tracks(self, node_id: str) -> list[Track] | None:
keys = self.playlist_entries(node_id)
if keys is None:
return None
return [t for k in keys if (t := self._index.get(k)) is not None]
def _is_playlist(self, node_id: str) -> bool:
return any(str(r.ID) == str(node_id) for r in self._store.playlists())
# ---- audio / paths ----------------------------------------------------
def audio_path(self, track_id: str):
return self._store.audio_path(track_id)
def audio_facts(self, track_ids: list[str]):
return local_audio_facts(self, track_ids)
def set_path_mapping(self, mapping: PathMapping) -> None:
self._store.set_path_mapping(mapping)
# The FILE decides a track's media kind, and the mapping moves files.
self._rebuild()
def unresolved_path_groups(self) -> list:
"""Not checked yet: the open-time missing-files check is Traktor-only
for now. Rekordbox's `FolderPath` is absolute too, so it will qualify."""
return []
def set_session_mappings(self, mappings: list[PathMapping]) -> None:
return None
def set_write_stored_paths(self, enabled: bool) -> None:
"""OPTIONAL: see `TraktorAdapter.set_write_stored_paths`."""
self._store.set_write_stored_paths(enabled)
def path_prefix_suggestions(self) -> dict:
paths = self._store.all_audio_paths()
primary = common_dir_prefix(paths)
return {"primary": primary, "groups": [{"prefix": primary, "count": len(paths)}] if primary else []}
def remap_preview(self, mapping: PathMapping) -> dict:
paths = [Path(p) for p in self._store.all_audio_paths()]
matched = [p for p in paths if mapping.matches(p)]
samples = []
for p in matched[:5]:
target = mapping.apply(p)
samples.append({"from": str(p), "to": str(target), "exists": target.exists()})
existing = sum(1 for p in matched if mapping.apply(p).exists())
return {
"total": len(paths),
"matched": len(matched),
"existing": existing,
"samples": samples,
}
def remap_locations(self, mapping: PathMapping) -> dict[str, str]:
raise Unsupported(self._readonly_reason("Rewriting stored paths"))
# ---- commands: track metadata ----------------------------------------
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None:
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_key(self, track_id: str, wheel: int, mode: str) -> Track | None:
self._require_writable("Setting the key")
self._store.set_key(track_id, wheel, mode)
self._refresh(track_id)
return self._index.get(track_id)
# ---- commands: playlists ----------------------------------------------
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
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._require_writable("Creating playlist folders")
return self._store.create_folder(name, parent_id)
def rename_playlist(self, node_id: str, name: str) -> None:
self._require_writable("Renaming playlists")
self._store.rename_playlist(node_id, name)
def delete_playlist(self, node_id: str) -> None:
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._require_writable("Editing playlists")
return self._store.set_playlist_entries(node_id, track_ids)
# ---- commands: cues ---------------------------------------------------
def _check_cue_type(self, cue_type: str) -> None:
if cue_type not in caps.WRITABLE_CUE_TYPES:
raise Unsupported(f"Rekordbox 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":
# Rekordbox is the ONLY platform with memory cues, so under the
# two-platform promotion rule they stay preserved-but-uneditable:
# they are projected and shown, never written.
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._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._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._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._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 -----------------------------------------------
def _markers_from(self, markers: list) -> list:
"""Accept either GridMarkers or the (start, bpm) tuples routes send."""
out = []
for m in markers:
if isinstance(m, GridMarker):
out.append(m)
else:
start, bpm = m
out.append(GridMarker(start=float(start), bpm=float(bpm)))
return out
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> TrackCues:
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._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._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._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._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:
"""Write an analysis result the way Rekordbox's own analyser would.
Rekordbox pairs nothing with a grid marker — the companion cue is a
Traktor convention — so this is just a replace.
"""
return self.replace_grid(track_id, markers)
def delete_grid(self, track_id: str) -> TrackCues:
self._require_writable("Deleting the beatgrid")
self._store.delete_grid(track_id)
return self._refresh_cues(track_id)
# ---- save -------------------------------------------------------------
@property
def dirty(self) -> bool:
return self._store.dirty
def edit_summary(self) -> str:
"""OPTIONAL: this session's unsaved edits in one line ("edited 3
tracks; added 6 hotcues") — what a server tells the next computer to
open the library about the edits it is inheriting."""
return self._store._journal.summary()
def save(self):
self._require_writable("Saving")
return self._store.save()
def snapshot(self) -> bytes:
"""The library's bytes, for version history.
`master.db` alone is NOT a complete snapshot of a Rekordbox library (the
beatgrids live in separate ANLZ files, and restoring the database
wholesale would also roll back Rekordbox's own auth and sampler state),
which is why `capabilities.save.history` is False. Nothing should be
calling this.
"""
raise Unsupported("Rekordbox libraries are not versioned by Konduktor")
# ---- commands: all refused in this milestone -------------------------
def _readonly_reason(self, what: str) -> str:
if self._cloud_synced:
return (
f"{what} is not possible: this Rekordbox library is synced with "
"Rekordbox Cloud, and Konduktor will not write to a cloud-synced "
"library."
)
return f"{what} is not supported yet for Rekordbox libraries."
def _refuse(self, what: str):
raise Unsupported(self._readonly_reason(what))
def _require_writable(self, what: str) -> None:
"""Every write passes through here, so the cloud-sync refusal cannot be
forgotten by a command added later."""
if self._cloud_synced:
raise Unsupported(self._readonly_reason(what))
def analysis_lead(self, audio: Path) -> float:
"""The time-base lead `add_tracks` measures a file's waveform with —
rekordbox's clock against the decoded audio, read from the file's
header (`timebase.py`). OPTIONAL on the protocol: a platform that does
not analyse what it adds has none, and whoever prepares an analysis
for this one (a client of a server-held library) asks for it."""
return timebase.offset(Path(audio))
def add_tracks(self, items: list, *, checkpoint=None) -> list[str]:
"""Add tracks that came from somewhere else, with their prep.
Rekordbox keeps the beatgrid AND the waveforms in per-track analysis
files, and shows neither grid nor cues for a track without them — so
unlike Traktor, which re-analyses on load, every file is decoded here.
A file that brings no grid gets one from Konduktor's own detector
(decided 2026-10-01: a track should arrive ready to prep).
Two phases, and the split is the point. FIRST every file is decoded and
analysed, which is slow and may be cancelled through `checkpoint` —
before the library is touched, so a cancel leaves it as it was. THEN
each row is added and its grid and cues replayed through the ordinary
store commands (`replace_grid`, `set_cue`), so an added track inherits
their conventions and tests rather than growing a second copy.
Nothing is lost on the way in: Rekordbox has memory cues and coloured
cues, so both cross as themselves. A hot cue whose pad is out of the
bank or already taken becomes a memory cue at the same position rather
than being dropped.
"""
from ...core import audio_tags
self._require_writable("Adding tracks")
held = set(self._store.all_audio_paths())
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}")
if str(audio) in held:
raise InvalidCommand(f"The library already holds {audio}")
held.add(str(audio))
markers = list(item.cues.grid_markers) if item.cues else []
if item.analysis is not None:
# Measured by whoever added it — a library held by a server is
# never asked to decode audio (see `PreparedAnalysis`).
analysed = item.analysis
if not markers:
markers = list(analysed.markers)
else:
analysed = add_analysis.prepare(audio, lead=self.analysis_lead(audio),
detect=not markers,
detect_key=item.track.key_wheel is None)
markers = markers or list(analysed.markers)
measured = analysed.measured
# A file with no key of its own gets one, as it gets a grid
# (decided: arrive ready to prep). Rekordbox's own add analyses one.
track = add_analysis.with_key(item.track, analysed.key)
art = item.art or audio_tags.read_cover(audio)
prepared.append((item, track, audio, measured, markers, art[0] if art else None))
added: list[str] = []
for item, track, audio, measured, markers, art in prepared:
track_id = self._store.add_track(
audio, track, measured=measured, with_grid=bool(markers), art=art)
self._index.add(projection.to_track(self._store.content(track_id), (),
stem=self._store.is_stem(track_id)))
if markers:
self._store.replace_grid(track_id, markers)
if item.cues is not None:
self._place_imported_cues(track_id, item.cues)
self._refresh(track_id)
added.append(track_id)
return added
def _place_imported_cues(self, track_id: str, cues) -> None:
"""Hot cues on their own pads; memory cues — and a hot cue with no
free pad — as memory cues. Colour as the nearest palette swatch."""
taken: set[int] = set()
for cue in sorted(cues.cues or [], key=lambda c: c.start):
cue_type = "loop" if getattr(cue, "length", 0) else "cue"
code, _rgb = palette.code_for(cue.color)
common = dict(start_sec=cue.start, cue_type=cue_type,
length_sec=getattr(cue, "length", 0.0) or 0.0,
name=getattr(cue, "name", None), color_code=code or None)
slot = cue.slot if cue.role == "hotcue" else None
if slot is not None and 0 <= slot < caps.HOTCUE_SLOTS and slot not in taken:
self._store.set_cue(track_id, slot=slot, **common)
taken.add(slot)
else:
self._store.add_memory_cue(track_id, **common)
def remove_tracks(self, track_ids: list[str]) -> int:
# What goes with a track was measured in Rekordbox 7 — see the store.
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):
# Rekordbox does not play native-instruments stem files as stems.
self._refuse("Converting tracks to stems")
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
self._refuse("Editing cover art")
def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
return self._store.cover_art(track_id)
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues:
# Rekordbox has no per-track grid lock; capabilities.grid.lockable says so.
raise Unsupported("Rekordbox has no beatgrid lock")
@@ -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",
]
@@ -0,0 +1,455 @@
"""Building ANLZ analysis files from nothing.
Lives here rather than in the OneLibrary adapter because the format is Pioneer's,
not one product's: a `master.db` track and a USB drive track carry the same tags.
OneLibrary borrows it, the same direction it already borrows `beatgrid`.
The read path parses these with `pyrekordbox`; writing needs the inverse, and
two things stand in the way of simply reusing its `construct` structs.
**`AnlzTag.content` is a Switch**, so a tag is built by handing it the parsed
STRUCTURE rather than bytes. Fine once known, surprising until then.
**The cue-entry structs cannot be built at all.** `AnlzCuePoint` and
`AnlzCuePoint2` each declare `"type"` twice — once as a `Const` magic string
(`PCPT`/`PCP2`) and once as the cue's kind. Parsing works because the second
silently overwrites the first in the result; BUILDING is impossible, because
`construct` reads one value out of the dict for both and no single value can
satisfy a string `Const` and an integer field. So cue entries are packed here by
hand, to the layout `pyrekordbox`'s own structs document:
PCP2: 4s magic · I len_header · I len_entry · I hot_cue · B kind · x
H 1000 · I time · I loop_time · B color_id · B 1 · 6x
H loop_num · H loop_den · I len_comment · {n}s comment(utf-16-be)
4B colour · {pad}x
**`pyrekordbox` accepting the result is NOT enough.** Its parser ignores
`len_header` and the constants, so an early version with a 12-byte `PCPT`
header round-tripped through Konduktor's own reader perfectly. The cue layout is
therefore pinned to a real rekordbox 7 export byte-for-byte
(`test_export_pioneer.py`).
**Which tags a file needs was measured, not assumed** — by stripping tags from a
rekordbox-written stick one at a time and loading each track in rekordbox 7:
* `.DAT` needs `PVBR` AND the preview waveform (`PWAV`/`PWV2`) before rekordbox
shows the grid OR the hot cues. The grid and cue tags alone — rekordbox's
own bytes — show nothing. (This, not the cue bytes, was why an early
Konduktor export had no grid.)
* rekordbox follows the database's analysis-path column; the folder names
need not match its own path hash.
* `.EXT` extras (`PWV3`-`PWV5`, `PQT2`, `PSSI`) and the whole `.2EX` affect
only the drawn waveforms.
Slot numbering here is ANLZ's own — a **dense 1-based** `hot_cue` where 0 means a
memory cue. That is NOT `master.db`'s sparse `Kind` bank, which skips 4.
"""
from __future__ import annotations
import logging
import struct
from pathlib import Path
from construct import Container, ListContainer
from pyrekordbox.anlz import structs
from ...core.waveform import even_slices
log = logging.getLogger(__name__)
NO_LOOP = 0xFFFFFFFF
#: `len_entry` rekordbox itself writes for a comment-less PCP2 entry.
PCP2_ENTRY_LEN = 88
PCPT_ENTRY_LEN = 56
#: Copied from a rekordbox-written file; zeros here would be a guess.
FILE_HEADER_U1, FILE_HEADER_U2, FILE_HEADER_U3 = 1, 0x10000, 0x10000
#: The three fields every tag starts with: magic, len_header, len_tag.
_TAG_PREFIX = 12
#: Each tag counts a different number of its leading CONTENT fields as part of
#: its header. Read off `pyrekordbox`'s own tag classes rather than guessed.
_LEN_HEADER = {"PPTH": 16, "PQTZ": 24, "PCOB": 24, "PCO2": 20,
"PVBR": 16, "PWAV": 20, "PWV2": 20,
"PWV3": 24, "PWV5": 24, "PWV4": 24, "PWV7": 24, "PWV6": 20, "PWVC": 14}
def _wrap(kind: str, body: bytes) -> bytes:
"""An AnlzTag around already-built content bytes.
Returns BYTES, not a tag object. `AnlzFile.build()` cannot be used on the
write side at all: it re-builds every tag from its parsed struct, which puts
the cue tags straight back through the unbuildable duplicate-`type` structs.
So the whole file is assembled here and `pyrekordbox` is used only to read
the result back — which is the direction that has to work anyway.
"""
return struct.pack(">4sII", kind.encode("ascii"), _LEN_HEADER[kind],
_TAG_PREFIX + len(body)) + body
def path_tag(drive_relative: str) -> bytes:
"""`PPTH` — the track's own path, as the drive stores it."""
raw_len = (len(drive_relative) + 1) * 2
body = structs.PPTH.build(Container(len_path=raw_len, path=drive_relative))
return _wrap("PPTH", body)
def beatgrid_tag(beats: list[tuple[int, float, float]]) -> bytes:
"""`PQTZ` — EVERY beat, as (beat-in-bar 1-4, bpm, seconds).
The grid is per-beat here, not per-marker: a OneLibrary/Rekordbox grid has
no concept of a tempo marker, so the generic marker list is expanded into
individual beats on the way out and collapsed back on the way in.
"""
entries = ListContainer([
Container(beat=beat, tempo=int(round(bpm * 100)), time=int(round(sec * 1000)))
for beat, bpm, sec in beats
])
body = structs.PQTZ.build(Container(entry_count=len(entries), entries=entries))
return _wrap("PQTZ", body)
# ---- what rekordbox needs before it will show a grid or cues ------------------
#
# Measured on a rekordbox-written stick by removing tags one at a time: with
# only PPTH + PQTZ + PCOB in the `.DAT` — the grid and cue tags byte-for-byte
# rekordbox's own — rekordbox shows NO grid and NO hot cues. Adding PVBR alone
# is not enough, nor PWAV + PWV2 alone; the full `.DAT` is. So every `.DAT`
# carries all three. (The `.EXT` and `.2EX` waveforms only affect drawing.)
#: PVBR's entry count: 400 seek points plus one trailing value.
_PVBR_ENTRIES = 401
def vbr_tag(total_samples: int = 0) -> bytes:
"""`PVBR` as rekordbox writes it for a constant-rate file.
400 zero seek offsets, then the track's length in SAMPLES — for an MP3,
frames x 1152 (Demo Track 1: 6601 x 1152 = 7604352). An `.m4a` gets zero
there too. A VBR MP3 presumably gets real offsets; none of the reference
tracks is VBR, so that is unmeasured, and a zero index is what an `.m4a`
carries and rekordbox accepts.
"""
body = struct.pack(">I", 0) + bytes(4 * (_PVBR_ENTRIES - 1)) + struct.pack(
">I", max(0, int(total_samples)))
return _wrap("PVBR", body)
def mp3_samples(path: Path) -> int:
"""An MP3's length in samples — frames x 1152 — for `PVBR`; 0 otherwise.
rekordbox writes this value only for MP3s (every `.m4a` carries 0).
"""
if path.suffix.lower() != ".mp3":
return 0
try:
import mutagen
info = mutagen.File(str(path)).info
return int(round(info.length * info.sample_rate / 1152)) * 1152
except Exception: # an unreadable header costs the seek hint, not the export
return 0
#: PWAV height = K * sqrt(rms) + B, fitted against rekordbox's own previews of
#: eight tracks (mean error 3.4 on the 0-31 scale, correlation 0.8). An absolute
#: scale, not normalised per track — a quiet master draws smaller, as in rekordbox.
_PWAV_K, _PWAV_B = 37.6, -5.2
def preview_tags(rms, brightness) -> list[bytes]:
"""`PWAV` (400 columns) and `PWV2` (100) from per-column RMS and brightness.
`PWAV`: one byte per column — whiteness (3 bits) << 5 | height (5 bits).
`PWV2`: a 4-bit height per group of four `PWAV` columns, scaled so the
track's tallest column is 15; that reproduces rekordbox's own to a mean
error of 1.7. Whiteness loosely follows brightness in rekordbox's output
(it is cosmetic: the colour of the blue-to-white preview).
"""
import numpy as np
rms = np.asarray(rms, dtype=float)
heights = np.clip(np.round(_PWAV_K * np.sqrt(rms) + _PWAV_B), 0, 31).astype(int)
white = np.clip(np.round(2.5 + 10.0 * np.asarray(brightness, dtype=float)), 0, 5).astype(int)
pwav = bytes(int((w << 5) | h) for w, h in zip(white, heights))
tallest = max(int(heights.max()), 1)
grouped = heights.reshape(100, 4).max(axis=1)
pwv2 = bytes(int(v) for v in np.clip(np.round(grouped * 15 / tallest), 0, 15))
return [
_wrap("PWAV", struct.pack(">II", len(pwav), 0x10000) + pwav),
_wrap("PWV2", struct.pack(">II", len(pwv2), 0x10000) + pwv2),
]
# ---- the detail and 3-band waveforms (`.EXT` / `.2EX`) -------------------------
#
# These only affect DRAWING — rekordbox shows the grid and cues without them — but
# without them its song list has no preview and its deck draws a flat blue line,
# and it warns the device was "analyzed by an older version". All constants are
# fitted against rekordbox 7's own files for 12 local tracks, measured through
# `core.waveform` exactly as the exporter measures (per-band mean error ~8 on the
# 0-127 scale). rekordbox 7's song list draws `PWV6` — but ONLY for a track
# whose `content.contentLink` is set (see the OneLibrary exporter); with it NULL
# the row is plain blue whatever the files hold. `PWV4` is written by
# distribution matching, not per-column fitting (see `_PWV4_MAPS`).
#: PWV7 byte per band = top * (energy / its 99.5th percentile) ** gamma.
_PWV7 = ((88, 0.6), (92, 0.9), (68, 1.7)) # low, mid, high
#: PWV6: the same, over 1200 overview columns (column = mean of its frames).
_PWV6 = ((40, 0.5), (34, 0.5), (34, 0.5))
#: PWVC: a per-band gain, = C / (the band's 99.5th percentile), floored at 80 —
#: rekordbox's own values follow this to about +/-20%. What rekordbox does with
#: it is not known; it is reproduced rather than invented.
_PWVC_C, _PWVC_FLOOR = (20763.0, 15220.0, 12571.0), 80
#: PWV3/PWV5 height (5 bits) from overall energy: 28 * x ** 1.5.
_HEIGHT = (28, 1.5)
#: PWV5 colour (3 bits each) from each band's SHARE of the frame's energy.
_RGB = ((8.47, 0.54), (7.60, 0.47), (13.78, 1.83)) # red<-low, green<-mid, blue<-high
_OVERVIEW_COLUMNS = 1200
#: PWV4 — the 6-byte colour overview. NOT what rekordbox 7's song list draws
#: (that is PWV6: removing PWV6 from a rekordbox-written track left its row
#: empty, removing PWV4 changed nothing); written because every rekordbox file
#: carries it and its RGB mode and older players may read it. Per column: b0 overall level, b1 a
#: companion of b0, b2 the height, b3/b4/b5 the low/mid/high (red/green/blue)
#: levels. Two measured facts shape it: b4 and b5 are sampled at ONE instant per
#: column (their column-to-column correlation is 0.05 and 0.16, against ~0.6 for
#: the rest), and rekordbox's per-column bytes are too jumpy to reproduce one by
#: one — so each byte is a QUANTILE MAP, (normalised measurement knots, byte
#: knots), fitted on 12 tracks so the distribution matches rekordbox's (held-out
#: medians within a few levels, the same spiky top end). b2 and b1 follow from
#: the others by linear fits on rekordbox's own bytes (mean error 10 and 12).
_PWV4_MAPS = {
"b0": ((0.0, 0.1027, 0.1843, 0.3094, 0.3971, 0.4832, 0.5759, 0.6569, 0.731, 0.8102, 0.8973, 0.9419, 0.971, 1.1784),
(0, 17, 28, 45, 56, 62, 65, 69, 74, 115, 127, 127, 127, 127)),
"b3": ((0.0, 0.0135, 0.0473, 0.1407, 0.26, 0.3841, 0.5027, 0.5911, 0.6686, 0.7617, 0.8646, 0.9209, 0.9645, 1.1825),
(0, 1, 4, 15, 24.7, 37, 44, 54, 62, 68, 89, 107, 120, 127)),
"b4": ((0.0, 0.0305, 0.0654, 0.1307, 0.1855, 0.2325, 0.2819, 0.3342, 0.3977, 0.4809, 0.6036, 0.708, 0.8719, 1.2804),
(0, 2, 7, 12, 17, 21, 25, 30, 35, 43, 62, 109, 127, 127)),
"b5": ((0.0, 0.0077, 0.0223, 0.0511, 0.09, 0.1298, 0.1809, 0.2427, 0.3167, 0.4143, 0.5749, 0.7209, 0.863, 1.4313),
(0, 1, 4, 7, 10, 12, 16, 20, 24, 31, 60, 127, 127, 127)),
}
def _pwv4(bands) -> bytes:
import numpy as np
full = np.sqrt((bands ** 2).sum(axis=1))
x = np.column_stack([bands, full]) # low, mid, high, full
cols = [np.arange(len(x))[s] for s in even_slices(len(x), _OVERVIEW_COLUMNS)]
mean = np.array([x[i].mean(axis=0) if len(i) else np.zeros(4) for i in cols])
instant = np.array([x[i[len(i) // 2]] if len(i) else np.zeros(4) for i in cols])
def mapped(values, key):
ref = float(np.percentile(values, 99.5)) or 1.0
knots_x, knots_y = _PWV4_MAPS[key]
return np.clip(np.round(np.interp(values / ref, knots_x, knots_y)), 0, 127).astype(int)
b0, b3 = mapped(mean[:, 3], "b0"), mapped(mean[:, 0], "b3")
b4, b5 = mapped(instant[:, 1], "b4"), mapped(instant[:, 2], "b5")
b2 = np.clip(np.round(0.83 * np.maximum(b3, np.maximum(b4, b5)) + 11.6), 0, 127).astype(int)
b1 = np.clip(np.round(235.2 - 0.77 * b0), 0, 255).astype(int)
return np.column_stack([b0, b1, b2, b3, b4, b5]).astype(np.uint8).tobytes()
def _norm(x, top: float, gamma: float, cap: int):
import numpy as np
ref = float(np.percentile(x, 99.5)) or 1.0
return np.clip(np.round(top * np.clip(x / ref, 0, None) ** gamma), 0, cap).astype(int)
def waveform_tags(bands) -> tuple[list[bytes], list[bytes]]:
"""(`.EXT` tags, `.2EX` tags) from 150-per-second low/mid/high band energy.
`.EXT`: `PWV3` (detail, 1 byte: whiteness << 5 | height), `PWV5` (detail
colour, 2 bytes: rrr ggg bbb hhhhh 00) and `PWV4` (the RGB-mode colour
overview, 1200 x 6 bytes — see `_PWV4_MAPS`). `.2EX`: `PWV7` (3-band detail, one
byte per band), `PWV6` (3-band overview, 1200 columns) and `PWVC`. The frames
must already be on rekordbox's clock (`waveform.analyse(lead=offset)`).
"""
import numpy as np
bands = np.asarray(bands, dtype=float)
n = len(bands)
full = np.sqrt((bands ** 2).sum(axis=1))
share = bands / (bands.sum(axis=1, keepdims=True) + 1e-12)
height = _norm(full, *_HEIGHT, 31)
white = np.clip(np.round(2.5 + 10.0 * share[:, 2]), 0, 7).astype(int)
pwv3 = bytes(int((w << 5) | h) for w, h in zip(white, height))
rgb = [np.clip(np.round(k * share[:, i] + c), 0, 7).astype(int)
for i, (k, c) in enumerate(_RGB)]
pwv5 = b"".join(struct.pack(">H", (int(r) << 13) | (int(g) << 10) | (int(b) << 7) | (int(h) << 2))
for r, g, b, h in zip(*rgb, height))
pwv7 = np.stack([_norm(bands[:, i], top, g, 127) for i, (top, g) in enumerate(_PWV7)], axis=1)
cols = np.array([bands[s].mean(axis=0) if n else np.zeros(3)
for s in even_slices(n, _OVERVIEW_COLUMNS)])
pwv6 = np.stack([_norm(cols[:, i], top, g, 127) for i, (top, g) in enumerate(_PWV6)], axis=1)
gains = [max(_PWVC_FLOOR, int(round(c / (float(np.percentile(bands[:, i], 99.5)) or 1.0))))
for i, c in enumerate(_PWVC_C)]
ext = [
_wrap("PWV3", struct.pack(">III", 1, n, 0x00960000) + pwv3),
_wrap("PWV5", struct.pack(">III", 2, n, 0x00960305) + pwv5),
_wrap("PWV4", struct.pack(">III", 6, _OVERVIEW_COLUMNS, 0) + _pwv4(bands)),
]
two_ex = [
_wrap("PWV7", struct.pack(">III", 3, n, 0x00960000) + pwv7.astype(np.uint8).tobytes()),
_wrap("PWV6", struct.pack(">II", 3, _OVERVIEW_COLUMNS) + pwv6.astype(np.uint8).tobytes()),
_wrap("PWVC", struct.pack(">H", 0) + struct.pack(">HHH", *[min(g, 0xFFFF) for g in gains])),
]
return ext, two_ex
def flat_preview_tags() -> list[bytes]:
"""Empty previews, for a file nothing could decode, so the grid and cues can
still show. That an all-zero preview satisfies rekordbox is an assumption,
by analogy with the all-zero PVBR every `.m4a` carries — not measured."""
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,
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_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, 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_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_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:
"""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
bytes early.
Status is 0 on a hot cue and 4 on a memory cue, and rekordbox leaves the
linked-list order fields at 0xFFFF rather than linking the entries.
"""
return struct.pack(
">4sIIIIIHHBxHII",
b"PCPT", 28, PCPT_ENTRY_LEN, hot_cue,
0 if hot_cue else 4,
0x10000, 0xFFFF, 0xFFFF, kind, 1000,
int(time_ms), NO_LOOP if loop_ms is None else int(loop_ms),
) + bytes(16)
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 (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:
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), comment=c.get("comment"))
for c in chosen
])
#: `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]:
"""The cue tags for one file, in the order and shape rekordbox writes them.
`.DAT`: `PCOB` hot (pads 1-3), `PCOB` memory (every memory cue).
`.EXT`: `PCOB` hot (pads 4 and up), `PCOB` memory (EMPTY), then `PCO2` hot
and `PCO2` memory — each the complete list of its kind.
**Every list is written even when empty.** A rekordbox file always carries
all of them, and a file missing one is not a shape rekordbox produces.
Hot cues are ordered by pad, HIGHEST first, which is also what it does.
"""
hot = sorted((c for c in cues if c["hot_cue"]), key=lambda c: -c["hot_cue"])
memory = sorted((c for c in cues if not c["hot_cue"]), key=lambda c: c["time_ms"])
if not extended:
return [_pcob(1, [c for c in hot if c["hot_cue"] <= 3]), _pcob(0, memory)]
return [
_pcob(1, [c for c in hot if c["hot_cue"] > 3]),
_pcob(0, []),
_pco2(1, hot),
_pco2(0, memory),
]
#: `PMAI` + len_header + len_file + four unknowns.
_FILE_HEADER_LEN = 28
def anlz_bytes(tags: list[bytes]) -> bytes:
"""Assemble an ANLZ file from built tag bytes."""
body = b"".join(tags)
header = struct.pack(
">4sIIIIII", b"PMAI", _FILE_HEADER_LEN, _FILE_HEADER_LEN + len(body),
FILE_HEADER_U1, FILE_HEADER_U2, FILE_HEADER_U3, 0,
)
return header + body
def write_anlz(path: Path, tags: list[bytes]) -> Path:
"""Assemble and write an ANLZ file from built tag bytes."""
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(anlz_bytes(tags))
return path
@@ -0,0 +1,85 @@
"""Cover art the way a Pioneer library stores it: two small square JPEGs.
Measured on a rekordbox 7 USB export rather than assumed:
* two sizes per image — **80 x 80** (`<n>.jpg`) and **240 x 240** (`<n>_m.jpg`);
* **baseline JPEG at quality 85, 4:2:0** — its quantisation table is libjpeg's
standard table scaled to exactly 85, with no EXIF and a plain JFIF header;
* a non-square cover is **letterboxed onto black**, aspect kept and centred.
Motorola's 4112 x 1112 art matches rekordbox's own to a mean of 1.8 levels
that way; a centre crop is off by 26, a stretch by 19.5.
Where the files go and how the database points at them is the target's business
(a OneLibrary drive: `PIONEER/Artwork/00001/`, see its exporter).
"""
from __future__ import annotations
import io
import logging
log = logging.getLogger(__name__)
SMALL, MEDIUM = 80, 240
#: A master.db library also keeps a LARGE copy: the cover itself, aspect kept,
#: scaled down to fit 800 px (never up) — Motorola's 4112 x 1112 art is stored
#: 800 x 216, a 640 or 300 px cover unchanged.
LARGE = 800
_QUALITY = 85
def _square(image, size: int):
from PIL import Image
fitted = image.copy()
fitted.thumbnail((size, size), Image.BICUBIC) # the closest of Pillow's filters
canvas = Image.new("RGB", (size, size), (0, 0, 0))
canvas.paste(fitted, ((size - fitted.width) // 2, (size - fitted.height) // 2))
return canvas
def _jpeg(image) -> bytes:
out = io.BytesIO()
# subsampling=2 is 4:2:0; progressive/optimize off = the baseline rekordbox writes.
image.save(out, format="JPEG", quality=_QUALITY, subsampling=2,
progressive=False, optimize=False)
return out.getvalue()
def _open(data: bytes):
from PIL import Image
try:
with Image.open(io.BytesIO(data)) as src:
src.load()
return src.convert("RGB") # PNG alpha / palette / CMYK -> RGB
except Exception as ex: # noqa: BLE001 — any unreadable image
log.warning("could not read cover art (%s); exporting without it", ex)
return None
def library_jpegs(data: bytes) -> tuple[bytes, bytes, bytes] | None:
"""(large, 240 px, 80 px) for a `master.db` library — `artwork.jpg`,
`artwork_m.jpg`, `artwork_s.jpg` — or None when the image cannot be read."""
from PIL import Image
rgb = _open(data)
if rgb is None:
return None
large = rgb.copy()
large.thumbnail((LARGE, LARGE), Image.BICUBIC)
return _jpeg(large), _jpeg(_square(rgb, MEDIUM)), _jpeg(_square(rgb, SMALL))
def pioneer_jpegs(data: bytes) -> tuple[bytes, bytes] | None:
"""(80 px JPEG, 240 px JPEG) from any image the source library holds, or None
when it cannot be read — a bad cover costs the artwork, not the export."""
try:
from PIL import Image
with Image.open(io.BytesIO(data)) as src:
src.load()
rgb = src.convert("RGB") # PNG alpha / palette / CMYK -> RGB
except Exception as ex: # noqa: BLE001 — any unreadable image
log.warning("could not read cover art (%s); exporting without it", ex)
return None
return _jpeg(_square(rgb, SMALL)), _jpeg(_square(rgb, MEDIUM))
@@ -0,0 +1,161 @@
"""Rekordbox's beatgrid <-> the generic marker list.
**Rekordbox does not store markers.** There is no beatgrid table in
``master.db`` at all; the grid lives in the track's ANLZ analysis file as a
``PQTZ`` tag holding EVERY BEAT explicitly — beat-number-in-bar, BPM and time,
one entry per beat (a 4-minute track is ~500 entries).
Konduktor's generic model is a marker list, so this module is the projection
between the two:
* read — collapse runs of equal BPM into one marker each, so a constant-tempo
track becomes a list of length one and a variable-tempo track becomes one
marker per tempo change. This is exactly the shape ``core.model.GridMarker``
describes.
* write — expand a marker list back into a full beat list (milestone 2; the
read direction is what a read-only adapter needs).
BPMs are compared with a tolerance because Rekordbox stores them as hundredths
and floating-point division reintroduces noise; two beats within `BPM_EPSILON`
are the same tempo and must not produce a spurious marker.
"""
from __future__ import annotations
from ...core.model import GridMarker
BPM_EPSILON = 0.005 # half of the 0.01 BPM Rekordbox can actually represent
def markers_from_beats(
times: list[float], bpms: list[float], beats: list[int] | None = None
) -> list[GridMarker]:
"""Collapse a per-beat grid into the generic marker list.
`times` are seconds, `bpms` the tempo in force at each beat, `beats` the
beat-in-bar (1-4) of each. A marker is emitted for the start of the grid and
wherever the tempo changes.
**The first marker goes on the first DOWNBEAT**, not the first beat. In the
generic model the first marker is bar 1 (Traktor's convention), but a
Pioneer grid often starts mid-bar: Motorola's opens on beat 3 at 0.026 s,
with its first downbeat at 0.986 s. Put the marker on the first beat and
every bar lands two beats early — in Traktor after an import, and on the
CDJ after an export. The beats before it are not lost: a grid extends back
to the start of the track from its first marker, and `beats_from_markers`
writes them back numbered as they were.
"""
if not times or not bpms:
return []
out: list[GridMarker] = []
last_bpm: float | None = None
for i, (t, bpm) in enumerate(zip(times, bpms)):
if last_bpm is None or abs(bpm - last_bpm) > BPM_EPSILON:
out.append(GridMarker(start=float(t), bpm=float(bpm), name=None, companion=None))
last_bpm = float(bpm)
if beats and out:
# The first tempo run ends where the second marker starts (or never).
run_end = out[1].start if len(out) > 1 else float("inf")
downbeat = next((t for t, b in zip(times, beats) if int(b) == 1 and t < run_end), None)
if downbeat is not None:
out[0] = out[0].model_copy(update={"start": float(downbeat)})
return out
def beats_from_markers(
markers: list[GridMarker], duration_sec: float
) -> tuple[list[int], list[float], list[float]]:
"""Expand a marker list into the per-beat arrays Rekordbox stores.
Each marker governs until the next one; the last runs to `duration_sec`.
Returns ``(beat_in_bar, bpms, times)`` with beat numbers cycling 1-4 from
each marker, which is how Rekordbox numbers bars.
The first marker's tempo also runs BACKWARDS to the start of the track: a
grid covers the whole track in Traktor and in rekordbox alike, and a marker
placed on the first downbeat (see `markers_from_beats`) has beats before it
— numbered 4, 3, … counting back, which reproduces rekordbox's own grid.
"""
beat_nums: list[int] = []
bpms: list[float] = []
times: list[float] = []
if not markers:
return beat_nums, bpms, times
ordered = sorted(markers, key=lambda m: m.start)
first = next((m for m in ordered if m.bpm > 0), None)
if first is not None:
step = 60.0 / first.bpm
lead = int((first.start + 1e-9) // step) # whole beats that fit before it
for k in range(lead, 0, -1):
beat_nums.append((-k) % 4 + 1)
bpms.append(first.bpm)
times.append(first.start - k * step)
for i, m in enumerate(ordered):
if m.bpm <= 0:
continue
end = ordered[i + 1].start if i + 1 < len(ordered) else duration_sec
step = 60.0 / m.bpm
t = m.start
n = 1
# Guard against a zero/negative span producing an endless loop.
while t < end - 1e-9 and step > 0:
# A beat before the audio starts is skipped but still COUNTED, so the
# next one keeps its place in the bar. The generic model can hold one
# (a Traktor grid anchored inside an MP3's header frame reads
# negative); rekordbox stores no negative times, and clamping it to 0
# would invent a beat there.
if t >= 0.0:
beat_nums.append(n)
bpms.append(m.bpm)
times.append(t)
n = n % 4 + 1
t += step
return beat_nums, bpms, times
# ---- writing the analysis file ----------------------------------------------
#
# The grid lives in the ANLZ files, and only `.DAT`'s `PQTZ` tag is written here.
# `.EXT` carries a second, "extended" grid (`PQT2`) whose per-beat byte and `u3`
# field are NOT decoded — `pyrekordbox` itself calls the field `unkown` — so
# rewriting it would mean guessing at bytes in real user data that has no version
# history. Leaving it alone is the only safe option until it is decoded.
#
# `.DAT`/`.EXT` round-trip byte-identically through parse -> build (verified
# across a whole library), which is what makes this checkable at all: a rebuild
# must differ ONLY inside the tag we touched.
def write_pqtz(path, beat_nums, bpms, times) -> bool:
"""Replace the beat grid in an ANLZ `.DAT`, in place. True if written.
`pyrekordbox`'s own `PQTZAnlzTag.set*()` refuse to change the NUMBER of
beats ("only values of existing beats can be set"), and every real grid edit
changes it — so the entry list is rebuilt directly and the tag's own
`update_len()` recomputes `len_tag`. `check_parse()` then asserts the
declared count and the list agree before anything is written.
"""
import construct
from pyrekordbox.anlz import AnlzFile
anlz = AnlzFile.parse_file(str(path))
tag = next((t for t in anlz.tags if t.type == "PQTZ"), None)
if tag is None:
return False
entries = construct.ListContainer()
for beat, bpm, t in zip(beat_nums, bpms, times):
entries.append(
construct.Container(
beat=int(beat),
tempo=int(round(bpm * 100)), # BPM is stored x100
time=int(round(t * 1000)), # seconds -> ms
)
)
tag.struct.content.entries = entries
tag.struct.content.entry_count = len(entries)
tag.update_len()
tag.check_parse()
data = anlz.build()
with open(path, "wb") as fh:
fh.write(data)
return True
@@ -0,0 +1,110 @@
"""What a Rekordbox library can persist.
**Track metadata and playlists are writable; cues and the beatgrid are not.**
The spike verified that Rekordbox accepts writes which maintain its USN columns
(see the handoff's Findings), and those two write paths use `pyrekordbox`, which
maintains them. Cues and the grid are separate hand-written stores and stay
false until milestone 3 — the capability system exists precisely so the UI never
offers an edit that will not persist.
A **cloud-synced** library reports `writable=False` regardless: Konduktor will
not write one at all.
Two facts are already known and encoded, because getting them wrong later would
be a silent data bug rather than a missing feature:
* a saved loop is a cue with an out-point, NOT a separate bank, so
``loops="cue_type"`` — the same answer as Traktor, and NOT the
``separate_bank`` the original plan assumed;
* cue colour is a PALETTE index (``djmdCue.ColorTableIndex``), not free RGB,
and the palette is a built-in table — `djmdColor` is the *track* colour
palette and is unrelated.
"""
from __future__ import annotations
from ...core.capabilities import (
Capabilities,
CueCapabilities,
GridCapabilities,
PlaylistCapabilities,
SaveCapabilities,
TrackCapabilities,
)
from . import palette
from .cue_types import WRITABLE_CUE_TYPES
# Rekordbox's addressable hot cue bank. The pads are labelled A-H; the stored
# slot number is NOT a plain letter index (see cue_types), so the adapter keeps
# slots numeric and lets the UI label them.
HOTCUE_SLOTS = 8
def capabilities_for(
path,
version: str | None = None,
*,
cloud_synced: bool = False,
editable_fields: list[str] | None = None,
) -> Capabilities:
# A cloud-synced library is refused PERMANENTLY, not pending a milestone:
# a local edit the server did not issue could propagate a broken sync state
# to the user's other machines, which version history cannot undo.
return Capabilities(
platform="rekordbox",
version=version,
writable=not cloud_synced,
readonly_cause="cloud_synced" if cloud_synced else None,
cues=CueCapabilities(
# Hot cues are writable: djmdCue rows plus the contentCue JSON
# mirror, kept in step. MEMORY cues stay preserved-but-uneditable —
# Rekordbox is the only platform that has them, and the two-platform
# promotion rule says a one-platform concept does not become an
# editing feature.
editable=True,
hotcue_slots=HOTCUE_SLOTS,
slot_labels="letter",
# Rekordbox is the only platform with memory cues, so they are
# projected and PRESERVED but not editable (two-platform rule).
memory_cues=True,
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 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
loops="cue_type",
),
# The grid is written into the track's ANLZ .DAT (PQTZ). Verified:
# Rekordbox reads the grid and its BPM readout from there, and leaves a
# Konduktor-written file alone. It has no per-track grid lock.
grid=GridCapabilities(editable=True, flexible=True, lockable=False),
tracks=TrackCapabilities(
rating_max=5, # Rekordbox stores 0-5 directly, unlike Traktor's /51
# Narrower than Traktor's: `producer` and `mix` have no Rekordbox
# column (its Composer is a different field), so they are absent
# rather than mapped onto something approximate.
editable_fields=sorted(editable_fields or []),
# A stem file is held (and played by Rekordbox as its mix);
# Konduktor's deck plays its stems.
media_kinds=["audio", "stem"],
removable=True,
addable=True,
key_writable=True,
artwork=False,
artwork_note=None,
),
playlists=PlaylistCapabilities(folders=True, smart="read_only", reorder=True),
save=SaveCapabilities(
app_name="Rekordbox",
library_label="master.db",
# Rekordbox holds master.db open while running and cloud-syncs it,
# so a concurrent write is riskier than Traktor's overwrite-on-exit.
overwrite_risk="while_running",
# The artefact set is master.db + N ANLZ files + masterPlaylists6.xml,
# and history.py tracks a single blob. Also, restoring master.db
# wholesale would roll back Rekordbox's auth token and sampler state.
history=False,
),
)
@@ -0,0 +1,103 @@
"""Rekordbox's ``djmdCue.Kind`` encoding <-> the generic cue vocabulary.
The only place these integers are given meaning. Verified against a real
library (see the handoff's Findings section):
* ``Kind == 0`` -> a MEMORY cue: no bank slot, and Rekordbox allows any
number of them.
* ``Kind >= 1`` -> a HOT CUE.
**``Kind`` is 1-based AND it skips 4.** Konduktor's generic model numbers bank
slots from zero — slot 0 is the pad the UI labels "A", which is also how Traktor
stores its ``HOTCUE`` attribute. Rekordbox's first pad is ``Kind=1``, and the
value ``4`` is reserved: the bank runs 1, 2, 3, 5, 6, 7, 8, 9.
Measured, not guessed. A loop was written at every ``Kind`` from 1 to 8, ten
seconds apart, and read off a real deck:
Kind 1 2 3 4 5 6 7 8 9
pad A B C - D E F G H
``Kind=4`` appears on no pad at all; Rekordbox shows such a cue as a memory cue.
That one gap explains two earlier puzzles: a Rekordbox-authored loop on pad F
stored ``Kind=7``, and a Konduktor cue written as ``Kind=4`` vanished from the
bank. Getting this wrong silently moves cues to the wrong pad — or loses them
from the bank entirely.
**``Kind`` is treated as an opaque slot id.** Setting cues on pads A and C
stored 1 and 3, but the pad in the 6th position stored 7, so the slot -> letter
mapping is NOT a plain index and has not been pinned down. Nothing here depends
on it: the adapter addresses cues by slot number and the UI labels them, which
is what ``capabilities.cues.slot_labels`` is for.
Loop-ness is NOT carried by ``Kind``. A loop is an ordinary cue row that also
has an out-point, so a loop can sit in a hot cue slot or be a memory cue.
"""
from __future__ import annotations
MEMORY_KIND = 0
# Rekordbox has no fade-in/fade-out/load cues; those are Traktor-only.
CUE_TYPES = ["cue", "loop"]
# What Konduktor will write. Loops were disabled for a while because a loop
# written at `Kind=4` disappeared from the bank — which turned out to be the
# reserved-Kind gap above, not anything to do with loops. Both types write.
WRITABLE_CUE_TYPES = ["cue", "loop"]
# The Kind value that is not a bank slot. Everything at or above it is shifted
# by one relative to the pad index.
RESERVED_KIND = 4
def role_and_slot(kind: int | None) -> tuple[str, int | None]:
"""(role, 0-based slot) for a native ``Kind``.
A cue at `RESERVED_KIND` occupies no pad, so it is projected as a memory cue
— which is how Rekordbox itself displays one.
"""
if kind is None or kind == MEMORY_KIND or int(kind) == RESERVED_KIND:
return "memory", None
kind = int(kind)
return "hotcue", kind - 1 if kind < RESERVED_KIND else kind - 2
def kind_for(role: str, slot: int | None) -> int:
"""The native ``Kind`` for a generic (role, 0-based slot).
Inverse of `role_and_slot`; skips `RESERVED_KIND`.
"""
if role == "memory":
return MEMORY_KIND
if slot is None:
raise ValueError("a hot cue needs a slot")
slot = int(slot)
if slot < 0:
raise ValueError(f"a hot cue slot cannot be negative, got {slot}")
return slot + 1 if slot < RESERVED_KIND - 1 else slot + 2
def cue_type(out_msec: int | None) -> str:
"""A cue with a real out-point is a loop; everything else is a plain cue.
Rekordbox writes ``OutMsec = -1`` for a non-loop.
"""
return "loop" if out_msec is not None and out_msec > 0 else "cue"
def beat_loop_size(beats: int) -> int:
"""Encode a loop's musical length.
``BeatLoopSize = (beats << 16) | 1`` — verified against two real loops at
different tempos (1 beat @125 BPM = 0x10001, 4 beats @120 BPM = 0x40001),
each agreeing with the measured millisecond span.
"""
return (int(beats) << 16) | 1
def beats_in_loop(beat_loop_size: int | None) -> int | None:
"""Decode `beat_loop_size`. None when unset."""
if not beat_loop_size:
return None
return beat_loop_size >> 16
@@ -0,0 +1,237 @@
"""The "Rekordbox Export" target: a USB stick's legacy Device Library (`export.pdb`).
What Rekordbox lists as a stick's **Device Library**, and what pre-OneLibrary
players (CDJ-2000NXS2, many XDJs) read. Not to be confused with the "Rekordbox
Library" target (`export.py`), which writes a COMPUTER library (`master.db`)
that Rekordbox never reads from a stick.
## Shared with the OneLibrary target — deliberately
Rekordbox's own device export writes `export.pdb` AND `exportLibrary.db`, both
pointing at ONE set of audio, analysis files and artwork. This target does the
same: the analysis files are written by the OneLibrary exporter's own
`_write_anlz`, at the same paths (`PIONEER/USBANLZ/P0xx/xxxxxxxx/`), and the
artwork is the `a<n>.jpg` pair the OneLibrary target also writes (rekordbox's
`a` files are the ones `export.pdb` names; OneLibrary's `image` table names the
byte-identical `b` files). When both targets are ticked, whichever runs second
finds the analysis already on the stick — written moments ago by the first, as
the runner clears the previous export before copying — and reuses it rather
than decoding every track again.
## The database
`pdb.PdbWriter` fills rekordbox's own empty device library (a template) with
rows; see `pdb.py` for the format and why a template. Values follow a real
rekordbox 7 device export:
* `bitmask` 0xC0700 — the same value as OneLibrary's `content.contentLink`,
which is what makes rekordbox draw a track's song-list preview there;
* `u2` = the track id + 0x600 (rekordbox: masterContentId + 0x600);
* `u3`/`u4` = 0: they are the halves of rekordbox's `masterDbId`, the link to a
computer's collection, which a Konduktor export does not claim;
* `u5` 0x29 (= `analysedBits` 41), `u6` the file type, `u7` 3;
* strings "ON" for kuvo_public / autoload_hotcues; the three unnamed strings
rekordbox fills from its phrase analysis are left EMPTY — this exporter
writes no phrases, and whether players care is what the device test checks.
"""
from __future__ import annotations
import logging
from datetime import date
from pathlib import Path
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
from . import artwork, pdb
from .projection import render_key
log = logging.getLogger(__name__)
PDB_DIR = Path("PIONEER") / "rekordbox"
OTHER_PLAYLIST = "Other"
BITMASK = 0xC0700
ANALYSED = 0x29
class RekordboxDeviceExporter:
platform = "rekordbox_export"
menu_order = 30
display_name = "Rekordbox Export"
library_filename = str(PDB_DIR / "export.pdb")
#: A player looks for `PIONEER/` at the root of the stick.
drive_root = True
def capabilities(self):
"""What a stick's device library can hold — the OneLibrary target's
answer, since both describe the same drive and its analysis files."""
from ..onelibrary.export import OneLibraryExporter
return OneLibraryExporter().capabilities()
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
# Imported here, not at module level: the OneLibrary package imports this
# package's modules, and a module-level import would be circular.
from ..onelibrary.export import (
OneLibraryExporter, _anlz_dir, _audio_format, _drive_relative, _file_type, _kbps,
)
root = Path(destination)
(root / PDB_DIR).mkdir(parents=True, exist_ok=True)
today = date.today().isoformat()
drive = OneLibraryExporter()
extra: list[Path] = []
ids = {name: {} for name in ("artist", "album", "genre", "label", "key")}
rows = {t: [] for t in (pdb.TRACKS, pdb.ARTISTS, pdb.ALBUMS, pdb.GENRES,
pdb.LABELS, pdb.KEYS, pdb.ARTWORK)}
builders = {"artist": (pdb.ARTISTS, pdb.artist_row), "album": (pdb.ALBUMS, pdb.album_row),
"genre": (pdb.GENRES, pdb.id_string_row), "label": (pdb.LABELS, pdb.id_string_row),
"key": (pdb.KEYS, pdb.key_row)}
def lookup(kind: str, name: str | None) -> int:
if not name:
return 0
table = ids[kind]
if name not in table:
table[name] = len(table) + 1
t, build = builders[kind]
rows[t].append(build(table[name], name))
return table[name]
by_source: dict[str, int] = {}
art_n = 0
total = len(payload.tracks)
for n, item in enumerate(payload.tracks, start=1):
payload.checkpoint(f"Writing the device library: {item.track.title or item.destination.name} ({n}/{total})", step=n, of=total)
track = item.track
by_source[item.source_id] = n
rel = _drive_relative(item.destination, root)
anlz_rel = f"{_anlz_dir(rel)}/ANLZ0000.DAT"
dat = root / anlz_rel.lstrip("/")
extra += self._analysis(drive, item, rel, dat)
artwork_id = 0
art = self._art(item, root, art_n + 1)
if art:
art_n += 1
artwork_id = art_n
extra += art
rows[pdb.ARTWORK].append(pdb.id_string_row(art_n, f"/PIONEER/Artwork/00001/a{art_n}.jpg"))
sample_rate, bit_depth = _audio_format(item.destination)
try:
size = item.destination.stat().st_size
except OSError:
size = 0
year = int(track.release_date[:4]) if (track.release_date or "")[:4].isdigit() else 0
rows[pdb.TRACKS].append(pdb.track_row(
{
"subtype": 0x24, "bitmask": BITMASK, "sample_rate": sample_rate or 0,
"file_size": size, "u2": n + 0x600,
"artwork_id": artwork_id,
"key_id": lookup("key", render_key(track.key_wheel, track.key_mode)),
"label_id": lookup("label", track.label),
"bitrate": _kbps(track.bitrate) or 0,
"tempo": int(round((track.bpm or 0) * 100)),
"genre_id": lookup("genre", track.genre),
"album_id": lookup("album", track.album),
"artist_id": lookup("artist", track.artist),
"id": n, "year": year, "sample_depth": bit_depth or 0,
"duration": min(int(track.length or 0), 0xFFFF),
"u5": ANALYSED, "rating": max(0, min(5, int(track.rating or 0))),
"u6": _file_type(item.destination), "u7": 3,
},
{
"kuvo_public": "ON", "autoload_hotcues": "ON",
"date_added": today, "release_date": track.release_date or "",
"mix_name": track.mix or "", "analyze_path": anlz_rel,
"analyze_date": today, "comment": track.comment or "",
"title": track.title or item.destination.stem,
"filename": item.destination.name, "file_path": rel,
},
))
tree, entries = self._playlists(payload, by_source)
writer = pdb.PdbWriter(pdb.template("export.pdb"))
for table in (pdb.TRACKS, pdb.GENRES, pdb.ARTISTS, pdb.ALBUMS, pdb.LABELS, pdb.KEYS, pdb.ARTWORK):
writer.fill(table, rows[table])
writer.fill(pdb.PLAYLIST_TREE, tree)
writer.fill(pdb.PLAYLIST_ENTRIES, entries)
writer.stamp_history_date(date.today())
writer.stamp_track_count(len(rows[pdb.TRACKS]))
library = root / self.library_filename
library.write_bytes(writer.render())
ext = root / PDB_DIR / "exportExt.pdb"
ext.write_bytes(pdb.template("exportExt.pdb"))
return WrittenLibrary(library=library, extra=[ext, *extra])
# ---- shared drive files ---------------------------------------------------
@staticmethod
def _analysis(drive, item: ExportTrack, rel: str, dat: Path) -> list[Path]:
"""This track's analysis files — reused when the OneLibrary target has
just written them in this same export, else written the same way."""
existing = [dat.with_suffix(s) for s in (".DAT", ".EXT", ".2EX") if dat.with_suffix(s).exists()]
if dat.exists() and dat.with_suffix(".EXT").exists():
return existing
return drive._write_anlz(item, rel, dat)
@staticmethod
def _art(item: ExportTrack, root: Path, n: int) -> list[Path]:
"""`a<n>.jpg` / `a<n>_m.jpg` — the pair export.pdb's artwork table names,
numbered in track order exactly as the OneLibrary target numbers them."""
if not item.art:
return []
folder = root / "PIONEER" / "Artwork" / "00001"
small, medium = folder / f"a{n}.jpg", folder / f"a{n}_m.jpg"
if small.exists() and medium.exists():
return [small, medium]
jpegs = artwork.pioneer_jpegs(item.art[0])
if jpegs is None:
return []
folder.mkdir(parents=True, exist_ok=True)
small.write_bytes(jpegs[0])
medium.write_bytes(jpegs[1])
return [small, medium]
# ---- playlists ------------------------------------------------------------
@staticmethod
def _playlists(payload: ExportPayload, by_source: dict) -> tuple[list[bytes], list[bytes]]:
"""The tree under one folder named after the export, as the other
targets build it. `sort_order` is a node's position among its siblings."""
tree: list[bytes] = []
entries: list[bytes] = []
next_id = [0]
siblings: dict[int, int] = {}
def add(name: str, parent: int, *, folder: bool) -> int:
next_id[0] += 1
order = siblings.get(parent, 0)
siblings[parent] = order + 1
tree.append(pdb.playlist_tree_row(next_id[0], parent, order, name, folder=folder))
return next_id[0]
def fill(playlist_id: int, source_ids: list[str]) -> None:
index = 0
for source_id in source_ids:
track_id = by_source.get(source_id)
if track_id is not None:
index += 1
entries.append(pdb.playlist_entry_row(index, track_id, playlist_id))
root = add(payload.name, 0, folder=True)
folders: dict[tuple[str, ...], int] = {(): root}
for playlist in payload.playlists:
parent = root
for depth in range(1, len(playlist.folders) + 1):
branch = tuple(playlist.folders[:depth])
if branch not in folders:
folders[branch] = add(branch[-1], folders[branch[:-1]], folder=True)
parent = folders[branch]
fill(add(playlist.name, parent, folder=False), playlist.track_ids)
claimed = {t for p in payload.playlists for t in p.track_ids}
loose = [t.source_id for t in payload.tracks if t.source_id not in claimed]
if loose:
fill(add(OTHER_PLAYLIST, root, folder=False), loose)
return tree, entries
@@ -0,0 +1,78 @@
"""Locate Rekordbox libraries in their default install locations.
Rekordbox keeps one library per install, at a fixed per-OS path:
macOS ~/Library/Pioneer/rekordbox/master.db
Windows %APPDATA%/Pioneer/rekordbox/master.db
``pyrekordbox`` already resolves this (including the v6/v7 split and any
non-default location recorded in Rekordbox's own settings), so that is the
primary source and the hard-coded paths are the fallback.
"""
from __future__ import annotations
from pathlib import Path
_RELATIVE = Path("Pioneer") / "rekordbox" / "master.db"
def _configured_paths() -> list[Path]:
"""Library paths pyrekordbox finds from Rekordbox's own configuration."""
out: list[Path] = []
try:
from pyrekordbox.config import get_config
except Exception: # noqa: BLE001 — never let discovery break startup
return out
for version in ("rekordbox7", "rekordbox6"):
try:
conf = get_config(version)
except Exception: # noqa: BLE001
continue
if not conf:
continue
p = conf.get("db_path")
if p:
out.append(Path(p))
return out
def _default_paths() -> list[Path]:
home = Path.home()
return [
home / "Library" / _RELATIVE, # macOS
home / "AppData" / "Roaming" / _RELATIVE, # Windows
]
def describe(path: Path) -> dict:
"""A candidate record for a master.db path, shaped like the picker wants."""
path = Path(path)
exists = path.is_file()
# The version Rekordbox itself is, not a schema version stamped in the file:
# master.db carries no version field, so the folder is the best label there is.
return {
"path": str(path),
"label": "Rekordbox",
"version": None,
"modified": (path.stat().st_mtime if exists else None),
"exists": exists,
}
def detect_libraries() -> list[dict]:
"""Every Rekordbox master.db found in a default location, newest first."""
seen: set[str] = set()
found: list[dict] = []
for p in _configured_paths() + _default_paths():
try:
if not p.is_file():
continue
except OSError:
continue
key = str(p.resolve())
if key in seen:
continue
seen.add(key)
found.append(describe(p))
found.sort(key=lambda c: c["modified"] or 0.0, reverse=True)
return found
@@ -0,0 +1,86 @@
"""Opening Rekordbox libraries: recognition, discovery and restore."""
from __future__ import annotations
import logging
from pathlib import Path
from . import discovery
from .adapter import RekordboxAdapter
log = logging.getLogger(__name__)
_SQLITE_MAGIC = b"SQLite format 3\x00"
class RekordboxDriver:
platform = "rekordbox"
display_name = "Rekordbox"
suffixes = (".db",)
library_label = "master.db"
selects = "file"
def can_open(self, path: Path) -> bool:
"""Recognise an encrypted Rekordbox database.
Extension is not enough — plenty of things are called ``.db`` — and a
SQLCipher file has no readable header at all (its first page is
encrypted, so it does NOT start with the SQLite magic). So the probe
decrypts just far enough to look for a table only Rekordbox has. That is
one page read, and it is the only way to answer honestly.
"""
try:
if not path.is_file() or path.suffix.lower() != ".db":
return False
with path.open("rb") as fh:
if fh.read(len(_SQLITE_MAGIC)) == _SQLITE_MAGIC:
return False # a plain, unencrypted SQLite file
except OSError:
return False
return self._has_rekordbox_schema(path)
@staticmethod
def _has_rekordbox_schema(path: Path) -> bool:
try:
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.masterdb.database import BLOB
from pyrekordbox.utils import deobfuscate
except ImportError: # pragma: no cover — dependency missing
return False
con = None
try:
con = sqlcipher.connect(str(path))
con.execute(f"PRAGMA key='{deobfuscate(BLOB)}'")
row = con.execute(
"SELECT name FROM sqlite_master WHERE type='table' AND name='djmdContent'"
).fetchone()
return row is not None
except Exception: # noqa: BLE001 — wrong key or not a database
return False
finally:
if con is not None:
try:
con.close()
except Exception: # noqa: BLE001
pass
def open(self, path: Path, *, read_only: bool = False) -> RekordboxAdapter:
return RekordboxAdapter(path)
def detect(self) -> list[dict]:
return discovery.detect_libraries()
def describe(self, path: Path) -> dict:
return discovery.describe(path)
def restore(self, path: Path, data: bytes) -> None:
"""Not supported: a Rekordbox library is more than one file.
`master.db` carries neither the beatgrids (ANLZ files) nor the playlist
XML, and putting an old database back would also revert Rekordbox's auth
token and sampler state. `capabilities.save.history` is False for the
same reason, so nothing should reach this.
"""
raise NotImplementedError(
"Konduktor does not version Rekordbox libraries: a restore would need "
"the analysis files and would roll back Rekordbox's own app state."
)
@@ -0,0 +1,416 @@
"""Writing a fresh Rekordbox `master.db` from nothing.
## The shape, and why it is not a hand-built schema
The handoff expected this to be the hard target — "a from-scratch SQLCipher
master.db, lookup-table FKs, USN bookkeeping". Most of that turned out to be
available:
* the **schema** is the checked-in DDL of a real Rekordbox 7 library,
`fixtures/rekordbox/schema.sql`. NOT `Base.metadata.create_all()`, which was
the plan until it failed: the ORM models 37 tables where the real thing has
47, and marks columns NOT NULL that Rekordbox leaves nullable — a database
built from the models refuses `agentRegistry` rows Rekordbox writes daily;
* the **key** is the same one reading uses, `deobfuscate(BLOB)`, so an
exported database is readable by any Rekordbox that reads the user's own;
* `add_content`, `create_playlist`, `create_playlist_folder` and
`add_to_playlist` already exist and assign the ids, UUIDs and USNs.
So this fills a new database through the library's own API rather than inventing
row shapes — the same "create, then use the ordinary write path" the Traktor
exporter uses, for the same reason: a second definition would drift from the one
the read path is tested against.
## What is genuinely written here
**Cue rows and their JSON mirror.** Rekordbox keeps cues in `djmdCue` AND in a
`contentCue.Cues` mirror that must agree; leaving the mirror stale is this
platform's version of Traktor's companion-cue desync. Field conventions are the
adapter's, not guessed: positions in frames at **150 fps**, `ContentUUID` is the
TRACK's UUID, an uncoloured cue is `Color=-1`, a loop is `Color=255` with
`BeatLoopSize = (beats << 16) | 1`, and `Kind` is the **sparse** bank
`1,2,3,5,6,7,8,9` that skips 4 — taken from `cue_types.kind_for`, not
redefined, because two copies of a mapping that subtle would drift.
**Analysis files.** The grid lives in a per-track ANLZ `PQTZ` tag, not in the
database, so each track gets one built by the shared `anlz_writer` and pointed
at by `djmdContent.AnalysisDataPath`. Rekordbox derives that path from the
track's UUID — `/PIONEER/USBANLZ/<first 3>/<rest>/ANLZ0000.DAT` — which is
reproduced here because the column and the file have to agree. That path is
rooted at a **`share/` directory beside `master.db`**, not at the library root.
## The catch worth knowing
`djmdContent.FolderPath` is an **absolute host path**, unlike Traktor's
volume-relative LOCATION and OneLibrary's drive-relative path. A Rekordbox
export is therefore NOT portable to another machine by copying the folder: it
describes files where they are right now. Swapping it into a Rekordbox install
on the same machine works; carrying it to a gig does not.
"""
from __future__ import annotations
import logging
import uuid as uuidlib
from datetime import datetime
from pathlib import Path
from sqlalchemy import text
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
from ...core.cue_colors import effective_color
from . import new_content, palette
from . import timebase
from .beatgrid import beats_from_markers
from .capabilities import capabilities_for
from .cue_types import kind_for
from .projection import render_key
from .store import rekordbox_probe_suppressed
log = logging.getLogger(__name__)
#: A real Rekordbox 7 library's DDL. See the fixture's README for why the ORM's
#: `create_all()` is not used.
_FIXTURES = Path(__file__).resolve().parents[3] / "fixtures" / "rekordbox"
SCHEMA = _FIXTURES / "schema.sql"
#: Rekordbox's own scaffolding rows — menu items, colours, categories, sort
#: options. Not optional: `add_content` looks up djmdMenuItems('TRACK') and
#: raises on an empty table. Carries no user data and no machine identity;
#: `djmdDevice`/`djmdProperty` are generated per export instead.
SEED = _FIXTURES / "seed.sql"
#: Rekordbox counts cue positions in frames at 150 fps, not milliseconds.
FRAMES_PER_SECOND = 150
#: `djmdContent.ContentLink` — see `new_content`, where its bits are measured.
CONTENT_LINK = new_content.CONTENT_LINK
#: Rekordbox's playlist side file, beside master.db. It lists every playlist
#: node with a `Timestamp` matching the row's `updated_at` (ms); a playlist the
#: file does not vouch for is not shown. The skeleton is a real Rekordbox 7
#: file's, minus its nodes — pyrekordbox adds ours as it creates them.
PLAYLISTS_XML = "masterPlaylists6.xml"
PLAYLISTS_XML_SKELETON = (
'<?xml version="1.0" encoding="UTF-8"?>\n\n'
'<MASTER_PLAYLIST Version="3.0.0" AutomaticSync="0">\n'
' <PRODUCT Name="rekordbox" Version="7.2.18" Company="Pioneer DJ"/>\n'
' <PLAYLISTS>\n </PLAYLISTS>\n'
'</MASTER_PLAYLIST>\n'
)
OTHER_PLAYLIST = "Other"
class RekordboxExporter:
platform = "rekordbox"
menu_order = 40
#: A COMPUTER library (master.db), which Rekordbox never reads from a stick —
#: named so, beside "Rekordbox Export" (the stick's Device Library).
display_name = "Rekordbox Library"
#: Rekordbox opens a master.db only from its own library folder.
computer_only = True
library_filename = "master.db"
drive_root = False
def capabilities(self):
"""What a Rekordbox library can hold, with no library to read.
`capabilities_for` normally takes the loaded library's version and cloud
state; a brand-new one has no version and is definitionally not synced.
"""
return capabilities_for(
None,
editable_fields=[
"title", "artist", "album", "genre", "label", "remixer",
"release_date", "comment", "rating",
],
)
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
# `masterdb`'s OWN key blob. `devicelib_plus` has a different one — a
# OneLibrary drive uses a universal key shared across vendors, and
# master.db does not. Mixing them up produces a database Rekordbox
# cannot open, and pyrekordbox rejects the wrong one outright.
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.masterdb import MasterDatabase, models
from pyrekordbox.masterdb.database import BLOB
from pyrekordbox.utils import deobfuscate
root = Path(destination)
root.mkdir(parents=True, exist_ok=True)
library = root / self.library_filename
if library.exists():
library.unlink() # SQLCipher will not re-key an existing file
key = deobfuscate(BLOB)
con = sqlcipher.connect(str(library))
try:
con.execute(f"PRAGMA key='{key}'")
con.executescript(SCHEMA.read_text())
con.executescript(SEED.read_text())
con.commit()
finally:
con.close()
# BEFORE the database is opened: pyrekordbox keeps masterPlaylists6.xml
# in step with every playlist it creates — but only if the file exists
# at open time. Without it Rekordbox opened the library, generated its
# own file listing our playlists with Timestamp 0, and showed NONE of
# them (measured by swapping an export into a real Rekordbox 7).
playlists_xml = root / PLAYLISTS_XML
playlists_xml.write_text(PLAYLISTS_XML_SKELETON, encoding="utf-8")
db = MasterDatabase(path=str(library), key=key)
extra: list[Path] = [playlists_xml]
ids: dict[str, str] = {}
try:
self._seed_registry(db, models)
self._seed_device(db, payload)
rows = {}
total = len(payload.tracks)
for n, item in enumerate(payload.tracks, start=1):
# Each track is decoded for its waveform: the slow part.
payload.checkpoint(f"Analysing {item.track.title or item.destination.name} ({n}/{total})", step=n, of=total)
content = self._add_track(db, item)
rows[item.source_id] = content
ids[item.source_id] = str(content.ID)
extra += self._write_anlz(item, content, root, db)
extra += self._write_art(item, content, root)
self._write_playlists(db, payload, rows)
# A brand-new file: a running Rekordbox cannot have it open, so its
# process-wide veto protects nothing here.
with rekordbox_probe_suppressed():
db.commit()
finally:
db.close()
self._replay_cues(library, payload, ids)
return WrittenLibrary(library=library, extra=extra)
@staticmethod
def _replay_cues(library: Path, payload: ExportPayload, ids: dict) -> None:
"""Write the cues through the ORDINARY cue-row code, not by hand.
Same reason the Traktor exporter replays commands: `set_cue` already
owns every convention a cue row needs — the sparse `Kind` bank, frames
at 150 fps, the loop encoding, and `_sync_content_cue`, which rebuilds
the `contentCue` JSON mirror the rows must agree with. Writing those
again here would be a second definition of all of it, untested, and a
stale mirror is this platform's version of a desynced companion cue.
"""
from .adapter import RekordboxAdapter
adapter = RekordboxAdapter(library)
# The store, not the adapter's commands: the adapter refuses memory cues
# (editing them in a user's library is off-limits) and takes no colour.
# Building a NEW library is neither an edit nor lossy by choice, so the
# exporter writes both — through the same `_write_cue` every edit uses.
store = adapter._store
try:
for item in payload.tracks:
track_id = ids.get(item.source_id)
if track_id is None or not item.cues:
continue
for cue in item.cues.cues:
if cue.role == "memory" or cue.slot is None:
# rekordbox's own "unset" for a memory cue with no colour.
code, _rgb = palette.code_for(cue.color)
store.add_memory_cue(
track_id, start_sec=cue.start, cue_type=cue.type,
length_sec=cue.length, name=cue.name, color_code=code or None,
)
continue
# What Konduktor SHOWS — stored colour, else the type's (blue
# cue, green loop) — as a palette code, which is what
# rekordbox draws from. White (a grid companion) has no swatch:
# code 0, i.e. uncoloured.
code, _rgb = palette.code_for(effective_color(cue))
store.set_cue(
track_id, slot=cue.slot, start_sec=cue.start, cue_type=cue.type,
length_sec=cue.length, name=cue.name, color_code=code or None,
)
adapter.save()
finally:
adapter.close()
# ---- rows -----------------------------------------------------------------
@staticmethod
def _seed_registry(db, models) -> None:
"""`agentRegistry.localUpdateCount` is where Rekordbox's USNs come from.
A database with no row there has nothing for the library's own
bookkeeping to increment, so it is created before anything else.
"""
existing = db.query(models.AgentRegistry).filter_by(
registry_id="localUpdateCount").first()
if existing is not None:
return
# Inserted with raw SQL, NOT the ORM. `AgentRegistry`'s DateTime columns
# bind through a processor that calls `.astimezone()` unconditionally,
# so a NULL `date_1` — which is exactly what a real Rekordbox library
# has — raises on INSERT. Reading such a row works; writing one does
# not. Raw SQL sidesteps the processor and stores what Rekordbox stores.
now = datetime.now().isoformat(sep=" ", timespec="milliseconds")
db.session.execute(
text('INSERT INTO "agentRegistry" (registry_id, int_1, created_at, '
"updated_at) VALUES (:k, 1, :now, :now)"),
{"k": "localUpdateCount", "now": now},
)
db.flush()
@staticmethod
def _seed_device(db, payload: ExportPayload) -> None:
"""This library's own identity — a fresh device and DB id per export.
Deliberately NOT copied from the fixture: a real `djmdDevice` row holds
the machine's NAME and UUIDs, which have no business in a repo or in
somebody else's exported library. Rekordbox stamps content rows with
`MasterDBID`, so the value has to exist; it just has to be ours.
"""
now = datetime.now().isoformat(sep=" ", timespec="milliseconds")
device_id = str(uuidlib.uuid4())
db_id = str(uuidlib.uuid4().int % 2_147_483_647)
db.session.execute(
text('INSERT INTO "djmdProperty" (DBID, DBVersion, DeviceID, '
"created_at, updated_at) VALUES (:db, '6000', :dev, :now, :now)"),
{"db": db_id, "dev": device_id, "now": now},
)
db.session.execute(
text('INSERT INTO "djmdDevice" (ID, MasterDBID, Name, UUID, '
"rb_local_usn, created_at, updated_at) "
"VALUES (:dev, :db, :name, :uuid, 1, :now, :now)"),
{"dev": device_id, "db": db_id, "name": payload.name,
"uuid": str(uuidlib.uuid4()), "now": now},
)
db.flush()
def _add_track(self, db, item: ExportTrack):
"""One `djmdContent` row, through pyrekordbox's own helper."""
track = item.track
content = db.add_content(
str(item.destination),
Title=track.title,
BPM=int(round((track.bpm or 0) * 100)) or None,
Length=track.length,
Rating=track.rating or 0,
Commnt=track.comment,
ReleaseDate=track.release_date,
)
# Lookups are foreign keys; pyrekordbox's add_* RAISES on an existing
# name, so every one is find-or-create — the same rule the in-place
# adapter follows.
content.ArtistID = self._lookup(db, "artist", track.artist)
content.AlbumID = self._lookup(db, "album", track.album)
content.GenreID = self._lookup(db, "genre", track.genre)
content.LabelID = self._lookup(db, "label", track.label)
# NOT `track.key`: that is the SOURCE platform's notation, so a Traktor
# export would put "10m" where Rekordbox shows "Cm".
content.KeyID = self._lookup(db, "key", render_key(track.key_wheel, track.key_mode))
content.ContentLink = CONTENT_LINK
db.flush()
return content
@staticmethod
def _lookup(db, kind: str, name: str | None):
return new_content.lookup(db, kind, name)
# ---- analysis ---------------------------------------------------------------
def _write_anlz(self, item: ExportTrack, content, root: Path, db) -> list[Path]:
"""The ANLZ file carrying this track's grid, and the column pointing at it.
Rekordbox derives the path from the track's UUID, and the database column
and the file on disk have to agree — so the same derivation is used here
rather than a path of our own choosing.
"""
rel = new_content.anlz_rel(str(content.UUID))
content.AnalysisDataPath = rel
content.Analysed = 105 # what a rekordbox-analysed track carries
content.AnalysisUpdated = 1
db.flush()
off = timebase.offset(item.destination)
measured = item.waveform(lead=off)
beats = None
markers = item.cues.grid_markers if item.cues else []
if markers:
duration = ((measured.duration if measured else 0.0)
or float(item.track.length or 0) or (markers[-1].start + 60.0))
nums, bpms, times = beats_from_markers(markers, duration)
if nums:
# Onto rekordbox's clock (~25 ms behind on MP3/AAC — `timebase`).
# The cues need no such line: they are replayed through
# `set_cue`, which applies the same offset itself.
beats = [(n, bpm, timebase.to_pioneer(t, off))
for n, bpm, t in zip(nums, bpms, times)]
# AnalysisDataPath is rooted at a `share` directory BESIDE master.db,
# not at the library root — the read path joins it that way, and writing
# it anywhere else produces a track whose grid silently reads as empty.
dat = root / "share" / rel.lstrip("/")
written = []
for suffix, data in new_content.anlz_files(item.destination, measured, beats).items():
target = dat.with_suffix(suffix)
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(data)
written.append(target)
return written
# ---- artwork ------------------------------------------------------------------
@staticmethod
def _write_art(item: ExportTrack, content, root: Path) -> list[Path]:
"""The cover, as a rekordbox-managed track carries it.
Three JPEGs under `share/PIONEER/Artwork/<uuid[:3]>/<uuid[3:]>/` — the
same UUID split as the analysis folder — named `artwork.jpg` (the cover,
fit to 800 px), `artwork_m.jpg` (240) and `artwork_s.jpg` (80), the last
two letterboxed square. `djmdContent.ImagePath` names `artwork.jpg`,
rooted at `share/` like `AnalysisDataPath`. All measured on a real
Rekordbox 7 library.
"""
files = new_content.artwork_files(item.art[0] if item.art else None)
if files is None:
return []
rel = new_content.artwork_rel(str(content.UUID))
folder = root / "share" / rel.lstrip("/")
folder.mkdir(parents=True, exist_ok=True)
written = []
for name, data in files.items():
(folder / name).write_bytes(data)
written.append(folder / name)
content.ImagePath = f"{rel}/artwork.jpg"
return written
# ---- playlists ---------------------------------------------------------------
def _write_playlists(self, db, payload: ExportPayload, rows: dict) -> None:
"""The tree, under one folder named after the export."""
root = db.create_playlist_folder(payload.name)
db.flush()
folders: dict[tuple[str, ...], object] = {(): root}
for playlist in payload.playlists:
parent = root
for depth in range(1, len(playlist.folders) + 1):
branch = tuple(playlist.folders[:depth])
if branch not in folders:
folders[branch] = db.create_playlist_folder(
branch[-1], parent=folders[branch[:-1]])
db.flush()
parent = folders[branch]
self._fill(db, db.create_playlist(playlist.name, parent=parent),
playlist.track_ids, rows)
claimed = {t for p in payload.playlists for t in p.track_ids}
loose = [t.source_id for t in payload.tracks if t.source_id not in claimed]
if loose:
self._fill(db, db.create_playlist(OTHER_PLAYLIST, parent=root), loose, rows)
@staticmethod
def _fill(db, playlist, track_ids: list[str], rows: dict) -> None:
db.flush()
for source_id in track_ids:
content = rows.get(source_id)
if content is not None:
db.add_to_playlist(playlist, content)
db.flush()
@@ -0,0 +1,138 @@
"""A NEW track's rows and files in a `master.db` library.
Shared by the two places a track is created rather than edited: the Rekordbox
Library exporter (a `master.db` from nothing) and `RekordboxStore.add_tracks`
(a track added to the user's own library). One definition, because a track
row, its lookups and its analysis files are the same thing in both, and two
copies would drift.
What a track Rekordbox itself adds looks like was MEASURED (two files dragged
into Rekordbox 7.2's collection, 2026-10-01, every row and file diffed): a
`djmdContent` row, three ANLZ files plus a `.3EX`, the embedded cover as three
JPEGs, one `contentFile` row per file (its `Hash` the file's MD5), and its own
analysis results — key, mixer gain, phrases — which nothing here can produce.
"""
from __future__ import annotations
import uuid as uuidlib
from datetime import datetime
from pathlib import Path
from sqlalchemy import text
from . import anlz_writer as W
from . import artwork
#: `djmdContent.ContentLink` — NOT optional, and a bit field. Measured by giving
#: five tracks of a Konduktor-written library different values and loading it
#: in Rekordbox 7: with it NULL the song-list preview is plain blue with a "?"
#: beside CUE; any value colours the preview; the 0x200000 bit (0x2C060E here,
#: 0x0C060E without it) clears the "?"; and 0x3D060E — what the real library's
#: MP3/M4A tracks carry, and what Rekordbox writes for a track it analyses
#: itself — adds two more bits that draw an extra badge, most likely claiming
#: phrase/vocal analysis Konduktor does not write. So the value that claims
#: only what is written: 0x2C060E.
CONTENT_LINK = 2885134
def anlz_rel(track_uuid: str) -> str:
"""`djmdContent.AnalysisDataPath` for a track. Rekordbox derives it from
the track's UUID, and the column and the file have to agree."""
return f"/PIONEER/USBANLZ/{track_uuid[:3]}/{track_uuid[3:]}/ANLZ0000.DAT"
def artwork_rel(track_uuid: str) -> str:
"""The track's artwork FOLDER — the same UUID split as its analysis."""
return f"/PIONEER/Artwork/{track_uuid[:3]}/{track_uuid[3:]}"
def anlz_files(audio: Path, measured, beats: list | None) -> dict[str, bytes]:
"""The analysis files for a track, by suffix: `.DAT`, `.EXT`, `.2EX`.
The same files as a rekordbox-analysed track. The `.DAT` needs PVBR and the
preview waveforms before rekordbox shows a grid at all (measured on a
OneLibrary stick; the same Pioneer file here); the `.EXT`/`.2EX` carry the
drawn waveforms. Cue lists are present but EMPTY — master.db keeps cues in
djmdCue. `measured` is `waveform.analyse`'s result (None: flat previews).
`beats` is `(beat-in-bar, bpm, seconds)` ON REKORDBOX'S CLOCK; None writes
no `PQTZ`, and `[]` an empty one for `write_pqtz` to fill later.
"""
path = str(audio)
tags = [W.path_tag(path), W.vbr_tag(W.mp3_samples(audio))]
if beats is not None:
tags.append(W.beatgrid_tag(beats))
if measured:
tags += W.preview_tags(measured.columns.rms, measured.columns.brightness)
ext_waves, two_ex = W.waveform_tags(measured.frames.bands)
else:
tags += W.flat_preview_tags()
ext_waves, two_ex = [], []
tags += W.cue_tags([], extended=False)
out = {
".DAT": W.anlz_bytes(tags),
".EXT": W.anlz_bytes([W.path_tag(path), *ext_waves[:1],
*W.cue_tags([], extended=True), *ext_waves[1:]]),
}
if two_ex:
out[".2EX"] = W.anlz_bytes([W.path_tag(path), *two_ex])
return out
def artwork_files(art: bytes | None) -> dict[str, bytes] | None:
"""The cover as a rekordbox-managed track carries it, by file name.
`artwork.jpg` (the cover, fit to 800 px), `artwork_m.jpg` (240) and
`artwork_s.jpg` (80), the last two letterboxed square; `djmdContent.
ImagePath` names `artwork.jpg`. All measured on a real Rekordbox 7 library.
None when there is no art or it cannot be read.
"""
if not art:
return None
jpegs = artwork.library_jpegs(art)
if jpegs is None:
return None
return dict(zip(("artwork.jpg", "artwork_m.jpg", "artwork_s.jpg"), jpegs))
def lookup(db, kind: str, name: str | None):
"""Find-or-create a lookup row, returning its id.
Lookups are foreign keys; pyrekordbox's `add_*` RAISES on an existing name,
so every one is find-or-create — the same rule the in-place adapter follows.
`djmdKey` is the odd one out twice over: its name column is `ScaleName`,
not `Name`, and pyrekordbox has no `add_key`. So keys are inserted
directly, with a `Seq` that keeps them in wheel order in Rekordbox's UI.
"""
if not name:
return None
if kind == "key":
found = db.get_key(ScaleName=name).first()
if found is not None:
return found.ID
return insert_key(db, name)
found = {"artist": db.get_artist, "album": db.get_album,
"genre": db.get_genre, "label": db.get_label}[kind](Name=name).first()
if found is not None:
return found.ID
created = {"artist": db.add_artist, "album": db.add_album,
"genre": db.add_genre, "label": db.add_label}[kind](name)
db.flush()
return created.ID
def insert_key(db, name: str) -> str:
"""A `djmdKey` row. Raw SQL: the ORM's DateTime binder raises on the NULLs
a real row carries."""
from pyrekordbox.masterdb import models
now = datetime.now().isoformat(sep=" ", timespec="milliseconds")
seq = (db.query(models.DjmdKey).count() or 0) + 1
key_id = str(uuidlib.uuid4().int % 2_147_483_647)
db.session.execute(
text('INSERT INTO "djmdKey" (ID, ScaleName, Seq, UUID, created_at, '
"updated_at) VALUES (:id, :name, :seq, :uuid, :now, :now)"),
{"id": key_id, "name": name, "seq": seq,
"uuid": str(uuidlib.uuid4()), "now": now},
)
db.flush()
return key_id
@@ -0,0 +1,119 @@
"""rekordbox's hot-cue colour palette: a generic `#RRGGBB` -> (palette code, RGB).
**rekordbox draws a hot cue from its palette CODE, not from its RGB bytes.** An
export that wrote only RGB (code 0) had every cue drawn in rekordbox's defaults
— green cues, orange loops. The code is `PCP2`'s colour byte (offset 44, before
the RGB triple) in the ANLZ `.EXT`, and `djmdCue.ColorTableIndex` in `master.db`.
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.
* 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
all Traktor's white grid-marker companion — gets code 0 with its RGB. rekordbox
produces that state itself (the reference fixture's cues are code 0 + RGB);
what rekordbox DRAWS for it is not yet verified.
"""
from __future__ import annotations
import colorsys
#: code -> RGB, exactly as rekordbox 7 writes them.
PALETTE: dict[int, tuple[int, int, int]] = {
0x31: (0xFF, 0x00, 0xA1), # magenta
0x38: (0xB3, 0x00, 0xFF), # purple
0x3C: (0x4D, 0x00, 0xFF), # violet
0x3E: (0x1A, 0x00, 0xFF), # blue-violet
0x01: (0x00, 0x00, 0xFF), # blue
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
0x20: (0xFF, 0xE8, 0x00), # yellow
0x26: (0xFF, 0x5E, 0x00), # orange
0x2A: (0xFF, 0x00, 0x00), # red
0x2B: (0xFF, 0x00, 0x17), # red (observed, not a swatch)
0x2D: (0xFF, 0x00, 0x45), # pink-red
}
#: Konduktor's TYPE colours (`core.cue_colors`) -> the swatch a DJ would call by
#: the same name. Nearest-hue alone sends the mint loop green to TEAL, and a
#: Traktor user reads a loop as green; so the type colours are pinned by intent.
_BY_INTENT: dict[str, int] = {
"#4D94FF": 0x05, # cue -> light blue
"#3DDC84": 0x16, # loop -> green
"#FF9A3D": 0x26, # fade -> orange
"#FFD23D": 0x20, # load -> yellow
}
#: Below this saturation a colour is white/grey, which the palette cannot show.
_GREY = 0.2
def _parse(color: str) -> tuple[int, int, int] | None:
c = (color or "").strip().lstrip("#")
if len(c) != 6:
return None
try:
return int(c[0:2], 16), int(c[2:4], 16), int(c[4:6], 16)
except ValueError:
return None
def code_for(color: str | None) -> tuple[int, tuple[int, int, int]]:
"""(palette code, RGB to store) for a generic `#RRGGBB`; (0, black) for none.
An exact palette RGB keeps its code; a type colour maps by intent; a
white/grey keeps its RGB with code 0; anything else takes the swatch of the
nearest hue, and stores THAT swatch's RGB so code and colour agree.
"""
rgb = _parse(color) if color else None
if rgb is None:
return 0, (0, 0, 0)
for code, value in PALETTE.items():
if value == rgb:
return code, value
intent = _BY_INTENT.get(f"#{rgb[0]:02X}{rgb[1]:02X}{rgb[2]:02X}")
if intent is not None:
return intent, PALETTE[intent]
h, _l, s = colorsys.rgb_to_hls(*(v / 255 for v in rgb))
if s < _GREY or max(rgb) - min(rgb) < 40:
return 0, rgb
def hue_gap(code: int) -> float:
ph = colorsys.rgb_to_hls(*(v / 255 for v in PALETTE[code]))[0]
d = abs(ph - h)
return min(d, 1 - d)
best = min((c for c in PALETTE if c != 0x2B), key=hue_gap)
return best, PALETTE[best]
#: The swatches a user can pick, in rekordbox's own order — what
#: `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 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}"
def swatch_code(color: str) -> int | None:
"""The code of an EXACT palette colour, else None — for a user's pick, which
must be a swatch, unlike `code_for`'s nearest-hue mapping for exports."""
rgb = _parse(color)
return next((code for code, value in PALETTE.items() if value == rgb), None)
+595
View File
@@ -0,0 +1,595 @@
"""The legacy rekordbox device library: `export.pdb` (DeviceSQL), read and written.
What Rekordbox lists as a stick's **Device Library** and what pre-OneLibrary
players (CDJ-2000NXS2, many XDJs) read. Rekordbox writes it beside the
OneLibrary `exportLibrary.db`; both point at the same audio, analysis files and
artwork.
## The format
There is no public specification. The layout used here is the one Deep
Symmetry's crate-digger documents, CONFIRMED byte for byte against a real
rekordbox 7 device export of eight tracks (every row of every table decodes, and
the page arithmetic below reproduces rekordbox's header fields exactly):
* the file is 4096-byte pages; page 0 is a header listing 20 tables, each a
chain of pages `first -> ... -> last -> empty_candidate` (the candidate is a
reserved page, possibly beyond the end of the file);
* every table starts with a HEADER page that holds no rows (flags 0x64) but
DOES hold an index: the table's first data page, and for tracks, the
playlist tree and history an entry per data page (`page << 3 | flag`, 3 =
has room). A first Konduktor export left these pointing nowhere and
rekordbox 7 called the device library corrupted; rows live in DATA pages
(flags 0x34 for tracks and the playlist tree, else 0x24);
* a data page is a 0x28-byte header, a heap of rows (each 4-byte aligned) from
the top, and a row index growing from the bottom in groups of 16: per group
16 u16 heap offsets, a u16 "present" bitmask and a u16 bitmask of the last
row written;
* strings are DeviceSQL strings: short ASCII `((len+1)<<1)|1` + bytes, long
ASCII `0x40` + u16 length + pad, or UTF-16LE `0x90` + u16 length + pad.
## Writing
**From a template, not from nothing** (`fixtures/rekordbox/device/`): the empty
library rekordbox itself writes for a new stick. It carries the tables that are
the same on every stick and cannot be derived (colours, browse columns, menus,
the history header), and reserves a blank page after each data table's header
page. Filling a table follows rekordbox's own allocation, read off a real
export: the first data page is the table's reserved candidate, further pages and
the new candidate come from the file header's next-unused counter, and any
reserved page left inside the file stays blank.
Data pages are written the way a rekordbox EXPORT writes them (rows appended
one by one): `u5` = 1, `num_rows_large` = rows - 1, and each index group's
"last written" mask names its final row.
"""
from __future__ import annotations
import re
import struct
from dataclasses import dataclass, field
from datetime import date
from pathlib import Path
PAGE = 4096
_HEADER = 0x28
_GROUP = 0x24 # one row-index group: 16 offsets + present + last-written
TRACKS, GENRES, ARTISTS, ALBUMS, LABELS, KEYS, COLORS = 0, 1, 2, 3, 4, 5, 6
PLAYLIST_TREE, PLAYLIST_ENTRIES, ARTWORK, HISTORY = 7, 8, 13, 19
#: Data-page flags per table, as rekordbox writes them.
_PAGE_FLAGS = {TRACKS: 0x34, PLAYLIST_TREE: 0x34}
_DEFAULT_FLAGS = 0x24
_HEADER_PAGE = 0x40 # bit set on header / non-data pages
TEMPLATE_DIR = Path(__file__).resolve().parents[3] / "fixtures" / "rekordbox" / "device"
# ---- strings -------------------------------------------------------------------
def dsql(text: str | None) -> bytes:
"""A DeviceSQL string."""
text = text or ""
try:
raw = text.encode("ascii")
except UnicodeEncodeError:
wide = text.encode("utf-16-le")
return struct.pack("<BHB", 0x90, len(wide) + 4, 0) + wide
if len(raw) <= 126:
return bytes([((len(raw) + 1) << 1) | 1]) + raw
return struct.pack("<BHB", 0x40, len(raw) + 4, 0) + raw
def read_dsql(buf: bytes, off: int) -> str:
head = buf[off]
if head & 1:
n = (head >> 1) - 1
return buf[off + 1:off + 1 + n].decode("ascii", "replace")
n = struct.unpack_from("<H", buf, off + 1)[0]
body = buf[off + 4:off + n]
return body.decode("utf-16-le" if head == 0x90 else "ascii", "replace")
def _pad4(row: bytes) -> bytes:
return row + bytes(-len(row) % 4)
# ---- rows ----------------------------------------------------------------------
#: The track row's fixed part, in order: 94 bytes.
_TRACK_FIELDS = (
("subtype", "H"), ("index_shift", "H"), ("bitmask", "I"), ("sample_rate", "I"),
("composer_id", "I"), ("file_size", "I"), ("u2", "I"), ("u3", "H"), ("u4", "H"),
("artwork_id", "I"), ("key_id", "I"), ("original_artist_id", "I"), ("label_id", "I"),
("remixer_id", "I"), ("bitrate", "I"), ("track_number", "I"), ("tempo", "I"),
("genre_id", "I"), ("album_id", "I"), ("artist_id", "I"), ("id", "I"),
("disc_number", "H"), ("play_count", "H"), ("year", "H"), ("sample_depth", "H"),
("duration", "H"), ("u5", "H"), ("color_id", "B"), ("rating", "B"), ("u6", "H"), ("u7", "H"),
)
_TRACK_FMT = "<" + "".join(f for _, f in _TRACK_FIELDS)
_TRACK_FIXED = struct.calcsize(_TRACK_FMT) # 94
#: The 21 string slots, in the order their offsets follow the fixed part.
TRACK_STRINGS = (
"isrc", "texter", "unknown_string_2", "unknown_string_3", "unknown_string_4",
"message", "kuvo_public", "autoload_hotcues", "unknown_string_5", "unknown_string_6",
"date_added", "release_date", "mix_name", "unknown_string_7", "analyze_path",
"analyze_date", "comment", "title", "unknown_string_8", "filename", "file_path",
)
_INDEX_SHIFT_AT = 2 # tracks, artists and albums carry their slot << 5 here
#: Tables whose header page indexes every data page (the rest only point at the
#: first). History (19) is already indexed in the template.
_INDEXED = (TRACKS, PLAYLIST_TREE)
_NONE = 0x1FFF
def track_row(fields: dict, strings: dict) -> bytes:
"""A tracks-table row. `fields` fills the fixed part (missing = 0);
`strings` the string slots (missing = empty)."""
values = [fields.get(name, 0) for name, _ in _TRACK_FIELDS]
fixed = struct.pack(_TRACK_FMT, *values)
offsets, heap = [], b""
base = _TRACK_FIXED + 2 * len(TRACK_STRINGS)
for name in TRACK_STRINGS:
offsets.append(base + len(heap))
heap += dsql(strings.get(name))
return _pad4(fixed + struct.pack(f"<{len(offsets)}H", *offsets) + heap)
def id_string_row(row_id: int, text: str) -> bytes:
"""Genres, labels and artwork: u32 id + string."""
return _pad4(struct.pack("<I", row_id) + dsql(text))
def key_row(row_id: int, name: str) -> bytes:
"""Keys store their id twice."""
return _pad4(struct.pack("<II", row_id, row_id) + dsql(name))
def artist_row(row_id: int, name: str) -> bytes:
"""Subtype 0x60: the name starts at a fixed offset of 10."""
return _pad4(struct.pack("<HHIBB", 0x60, 0, row_id, 0x03, 10) + dsql(name))
def album_row(row_id: int, name: str, artist_id: int = 0) -> bytes:
"""Subtype 0x80: the name starts at 22. rekordbox's own export leaves the
album's artist 0 even when the track has one, so the default follows it."""
return _pad4(struct.pack("<HHIIIIBB", 0x80, 0, 0, artist_id, row_id, 0, 0x03, 22) + dsql(name))
def playlist_tree_row(row_id: int, parent_id: int, sort_order: int, name: str, *, folder: bool) -> bytes:
return _pad4(struct.pack("<IIIII", parent_id, 0, sort_order, row_id, 1 if folder else 0) + dsql(name))
def playlist_entry_row(entry_index: int, track_id: int, playlist_id: int) -> bytes:
return struct.pack("<III", entry_index, track_id, playlist_id)
# ---- pages ---------------------------------------------------------------------
def _index_space(n: int) -> int:
"""Bytes the row index occupies at the bottom of a page holding `n` rows."""
return ((n + 15) // 16) * _GROUP
def _chunk(rows: list[bytes]) -> list[list[bytes]]:
"""Greedy: as many rows per page as fit beside their index."""
pages, cur, used = [], [], 0
for row in rows:
if cur and _HEADER + used + len(row) + _index_space(len(cur) + 1) > PAGE:
pages.append(cur)
cur, used = [], 0
if _HEADER + len(row) + _index_space(1) > PAGE:
raise ValueError(f"a {len(row)}-byte row cannot fit in a page")
cur.append(row)
used += len(row)
if cur:
pages.append(cur)
return pages
def _data_page(index: int, table: int, next_page: int, rows: list[bytes], sequence: int,
*, shift_at: int | None, fill: tuple[int, int] | None = None) -> bytes:
page = bytearray(PAGE)
heap = bytearray()
offsets = []
for slot, row in enumerate(rows):
row = bytearray(row)
if shift_at is not None:
struct.pack_into("<H", row, shift_at, slot << 5)
offsets.append(len(heap))
heap += row
n = len(rows)
groups = (n + 15) // 16
page[_HEADER:_HEADER + len(heap)] = heap
for g in range(groups):
base = PAGE - g * _GROUP
k = min(16, n - 16 * g)
struct.pack_into("<H", page, base - 4, (1 << k) - 1) # present
struct.pack_into("<H", page, base - 2, 1 << (k - 1)) # last written
for r in range(k):
struct.pack_into("<H", page, base - 6 - 2 * r, offsets[16 * g + r])
used = len(heap)
free = PAGE - _HEADER - used - (2 * n + 4 * groups)
struct.pack_into("<6I", page, 0, 0, index, table, next_page, sequence, 0)
page[0x18] = n & 0xFF
page[0x19] = ((n >> 8) & 0x1F) | ((n & 0x07) << 5)
page[0x1A] = (n >> 3) & 0xFF
page[0x1B] = _PAGE_FLAGS.get(table, _DEFAULT_FLAGS)
u5, nrl = fill if fill is not None else (1, n - 1)
struct.pack_into("<6H", page, 0x1C, free, used, u5, nrl, 0, 0)
return bytes(page)
# ---- the writer ----------------------------------------------------------------
class PdbWriter:
"""Fills an empty rekordbox device library (the template) with rows."""
def __init__(self, template: bytes):
self.buf = bytearray(template)
self.pages: dict[int, bytes] = {}
n_tables = struct.unpack_from("<I", self.buf, 8)[0]
self.next_unused = struct.unpack_from("<I", self.buf, 12)[0]
self.sequence = struct.unpack_from("<I", self.buf, 20)[0]
self.tables = {}
self.pages_with_room = 0
for i in range(n_tables):
t, empty, first, last = struct.unpack_from("<4I", self.buf, 28 + 16 * i)
self.tables[t] = [i, empty, first, last]
def _alloc(self) -> int:
page = self.next_unused
self.next_unused += 1
return page
def fill(self, table: int, rows: list[bytes]) -> None:
"""Write `rows` into `table`, which must still be empty (header page only)."""
if not rows:
return
slot, empty, first, last = self.tables[table]
if first != last:
raise ValueError(f"table {table} already has data pages")
chunks = _chunk(rows)
indices = [empty] + [self._alloc() for _ in chunks[1:]]
candidate = self._alloc()
shift_at = _INDEX_SHIFT_AT if table in (TRACKS, ARTISTS, ALBUMS) else None
indexed = table in _INDEXED
for i, chunk in enumerate(chunks):
nxt = indices[i + 1] if i + 1 < len(indices) else candidate
last_page = i + 1 == len(chunks)
# Indexed tables mark a full page 0x1FFF/0x1FFF and a page with room
# rows+1 / 0 — as a real export's tracks and playlist pages do.
fill = None
if indexed:
fill = (len(chunk) + 1, 0) if last_page else (_NONE, _NONE)
self.sequence += 1
self.pages[indices[i]] = _data_page(indices[i], table, nxt, chunk, self.sequence,
shift_at=shift_at, fill=fill)
self._index(first, indices, indexed=indexed)
self.tables[table] = [slot, candidate, first, indices[-1]]
def _index(self, header_page: int, data_pages: list[int], *, indexed: bool) -> None:
"""Point the table's HEADER page at its data.
A header page is not empty: past its 0x28-byte header it holds an index —
its own number, the FIRST DATA PAGE, 0x03FFFFFF, 0, a u16 entry count,
0x1FFF, then entries `page << 3 | flag` padded with 0x1FFFFFF8. Every
table with data points at its first data page (left at 0x03FFFFFF,
rekordbox calls the library corrupted); the indexed tables (tracks, the
playlist tree, history) also list every data page — flag 3 for a page
with room, 0 for a full one — and the header's u7 is that count, u5 the
number of pages with room and num_rows_large the first of them.
"""
o = header_page * PAGE
struct.pack_into("<I", self.buf, o + _HEADER + 4, data_pages[0])
if not indexed:
return
flags = [3 if i + 1 == len(data_pages) else 0 for i in range(len(data_pages))]
struct.pack_into("<HH", self.buf, o + _HEADER + 16, len(data_pages), 0x1FFF)
for k, (page, flag) in enumerate(zip(data_pages, flags)):
struct.pack_into("<I", self.buf, o + _HEADER + 20 + 4 * k, (page << 3) | flag)
room = [k for k, flag in enumerate(flags) if flag == 3]
struct.pack_into("<HH", self.buf, o + 0x20, len(room) or _NONE, room[0] if room else _NONE)
struct.pack_into("<H", self.buf, o + 0x26, len(data_pages))
self.pages_with_room += len(room)
def stamp_track_count(self, n: int) -> None:
"""The history header row counts the library's tracks (and flags that
it has any): 8 on a real 8-track export, 0 in the empty template."""
_, _, first, last = self.tables[HISTORY]
for _header, row in _rows(bytes(self.buf), first, last):
if row is not None:
self.buf[row + 3] = 1 if n else 0
struct.pack_into("<I", self.buf, row + 4, n)
break
if n:
# A library with tracks also INDEXES its history page — entry
# `page << 3 | 0`, count 1, u7 1 — which the empty template does not.
o = first * PAGE
struct.pack_into("<HH", self.buf, o + _HEADER + 16, 1, 0x1FFF)
struct.pack_into("<I", self.buf, o + _HEADER + 20, last << 3)
struct.pack_into("<H", self.buf, o + 0x26, 1)
def stamp_history_date(self, when: date) -> None:
"""The history header row records the library's creation date."""
_, _, first, last = self.tables[HISTORY]
o = last * PAGE
page = self.buf[o:o + PAGE]
m = re.search(rb"\d{4}-\d{2}-\d{2}", page[_HEADER:])
if m:
at = o + _HEADER + m.start()
self.buf[at:at + 10] = when.isoformat().encode("ascii")
def render(self) -> bytes:
for t, (slot, empty, first, last) in self.tables.items():
struct.pack_into("<4I", self.buf, 28 + 16 * slot, t, empty, first, last)
struct.pack_into("<I", self.buf, 12, self.next_unused)
# 1 in the empty template, 4 on a real export whose index lists three
# pages with room: 1 + that count fits both. The least certain field here.
struct.pack_into("<I", self.buf, 16, 1 + self.pages_with_room)
struct.pack_into("<I", self.buf, 20, self.sequence + 1)
top = max([len(self.buf) // PAGE - 1, *self.pages])
out = bytearray(self.buf) + bytes((top + 1) * PAGE - len(self.buf))
for index, page in self.pages.items():
out[index * PAGE:(index + 1) * PAGE] = page
return bytes(out)
def template(name: str = "export.pdb") -> bytes:
return (TEMPLATE_DIR / name).read_bytes()
# ---- the reader ----------------------------------------------------------------
@dataclass
class Library:
"""What a device library holds, decoded — for tests and diagnostics."""
tracks: list[dict] = field(default_factory=list)
genres: dict[int, str] = field(default_factory=dict)
artists: dict[int, str] = field(default_factory=dict)
albums: dict[int, str] = field(default_factory=dict)
labels: dict[int, str] = field(default_factory=dict)
keys: dict[int, str] = field(default_factory=dict)
artwork: dict[int, str] = field(default_factory=dict)
playlists: list[dict] = field(default_factory=list)
entries: list[tuple[int, int, int]] = field(default_factory=list)
pages: dict[int, list[dict]] = field(default_factory=dict) # table -> page headers
def _rows(buf: bytes, first: int, last: int):
"""(page header dict, row offset) for every present row of a table."""
p, seen = first, 0
while True:
o = p * PAGE
if o + PAGE > len(buf):
return
flags = buf[o + 0x1B]
n = (buf[o + 0x19] >> 5) | (buf[o + 0x1A] << 3)
header = {"index": p, "flags": flags, "rows": n,
"next": struct.unpack_from("<I", buf, o + 12)[0],
"free": struct.unpack_from("<H", buf, o + 0x1C)[0],
"used": struct.unpack_from("<H", buf, o + 0x1E)[0]}
yield header, None
if not flags & _HEADER_PAGE:
for g in range((n + 15) // 16):
base = o + PAGE - g * _GROUP
present = struct.unpack_from("<H", buf, base - 4)[0]
for r in range(16):
if present & (1 << r):
yield header, o + _HEADER + struct.unpack_from("<H", buf, base - 6 - 2 * r)[0]
if p == last or seen > 10000:
return
p, seen = header["next"], seen + 1
def read(buf: bytes) -> Library:
lib = Library()
n_tables = struct.unpack_from("<I", buf, 8)[0]
for i in range(n_tables):
t, _empty, first, last = struct.unpack_from("<4I", buf, 28 + 16 * i)
for header, row in _rows(buf, first, last):
if row is None:
lib.pages.setdefault(t, []).append(header)
continue
if t == TRACKS:
values = dict(zip([n for n, _ in _TRACK_FIELDS], struct.unpack_from(_TRACK_FMT, buf, row)))
offs = struct.unpack_from(f"<{len(TRACK_STRINGS)}H", buf, row + _TRACK_FIXED)
values.update({name: read_dsql(buf, row + o) for name, o in zip(TRACK_STRINGS, offs)})
lib.tracks.append(values)
elif t in (GENRES, LABELS, ARTWORK):
target = {GENRES: lib.genres, LABELS: lib.labels, ARTWORK: lib.artwork}[t]
target[struct.unpack_from("<I", buf, row)[0]] = read_dsql(buf, row + 4)
elif t == KEYS:
lib.keys[struct.unpack_from("<I", buf, row)[0]] = read_dsql(buf, row + 8)
elif t == ARTISTS:
sub, _shift, rid, _b, ofs = struct.unpack_from("<HHIBB", buf, row)
if sub == 0x64:
ofs = struct.unpack_from("<H", buf, row + 10)[0]
lib.artists[rid] = read_dsql(buf, row + ofs)
elif t == ALBUMS:
sub, _shift, _u, artist, rid, _u3, _b, ofs = struct.unpack_from("<HHIIIIBB", buf, row)
lib.albums[rid] = read_dsql(buf, row + ofs)
elif t == PLAYLIST_TREE:
parent, _u, sort, rid, folder = struct.unpack_from("<5I", buf, row)
lib.playlists.append({"id": rid, "parent": parent, "sort": sort,
"folder": bool(folder), "name": read_dsql(buf, row + 20)})
elif t == PLAYLIST_ENTRIES:
lib.entries.append(struct.unpack_from("<3I", buf, row))
return lib
__all__ = [
"ALBUMS", "ARTISTS", "ARTWORK", "GENRES", "KEYS", "LABELS", "Library", "PAGE",
"PLAYLIST_ENTRIES", "PLAYLIST_TREE", "PdbWriter", "TRACKS", "TRACK_STRINGS",
"album_row", "artist_row", "dsql", "id_string_row", "key_row", "playlist_entry_row",
"playlist_tree_row", "read", "read_dsql", "template", "track_row",
]
# ---- 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)
@@ -0,0 +1,184 @@
"""Rekordbox native rows -> the generic projection.
The only place a ``pyrekordbox`` ORM object becomes a generic `Track` /
`TrackCues`. Everything above this file sees generic types exclusively.
"""
from __future__ import annotations
from ...core import musical_key
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
from . import beatgrid, palette, timebase
from .cue_types import cue_type, role_and_slot
# Rekordbox names keys musically ("Abm", "F", "Ebm") — but its key table also
# holds whatever text a track's key TAG carried when it was imported, so a real
# stick has "12A" beside "Abm". Parsing therefore accepts every notation.
def parse_key(key: str | None) -> tuple[int | None, str | None]:
"""(Camelot wheel position 1-12, mode) for a key name in any notation."""
return musical_key.parse(key)
# The inverse, for writing. A track arriving from Traktor carries `key` as
# Traktor's own display string ("10m") and `key_wheel`/`key_mode` as the parsed
# position — so writing the string verbatim into a Pioneer library would show
# "10m" where the deck expects "Cm". Rendering from the wheel is the only
# correct crossing. Shared by the adapter and both Pioneer exporters.
def render_key(wheel: int | None, mode: str | None) -> str | None:
"""A Pioneer key name ("Abm", "F") for a Camelot position + mode, spelt as
rekordbox spells its own (flats; see `core/musical_key`).
Returns None when the position is unknown, which is honest: a made-up key is
worse than a blank one, and Pioneer software shows blanks without complaint.
"""
return musical_key.render(wheel, mode, "musical")
def _iso_date(value) -> str | None:
"""Rekordbox already stores ISO-ish 'YYYY-MM-DD'; blanks become None."""
if not value:
return None
s = str(value).strip()
return s or None
def _bpm(row) -> float | None:
"""``djmdContent.BPM`` is the tempo x100, and 0 means 'not known'.
It is a display value only — the real grid is in the ANLZ file — and it is
genuinely 0 for analysed tracks in real libraries.
"""
raw = getattr(row, "BPM", None)
if not raw:
return None
return round(raw / 100.0, 2)
def _name_of(related) -> str | None:
"""A joined lookup row's display name, or None when unset."""
if related is None:
return None
for attr in ("Name", "ScaleName"):
value = getattr(related, attr, None)
if value:
return str(value)
return None
def to_track(row, cue_kinds=(), *, stem: bool = False) -> Track:
"""Project one ``DjmdContent`` row.
`cue_kinds` is this track's ``(Kind, OutMsec, ColorTableIndex)`` from the store's single
query — passed in rather than read off the row, which would be a per-track
round trip. "Is this a hot cue, and on which pad?" is `role_and_slot`, the
same definition `to_track_cues` uses, so the table's count and dots agree
with the pads shown in the deck (it also rules out the reserved Kind).
**`grid_marker_count` is an approximation here**: the real count needs the
track's ANLZ file, which is far too slow to read for every track at open
(~12 s on a library of 8,500). A track with a BPM is reported as 1 (constant
tempo, true for all but a fraction of a percent of real tracks) and the value
is corrected the moment the track's grid is actually read.
BPM — not the presence of an analysis file — is the signal, because Rekordbox
analyses one-shot samples too and gives them an ANLZ with no beatgrid at all.
On the reference library the two sets agree exactly: all 22 tracks with no
BPM are precisely the 22 with no grid.
"""
chips: list[HotcueChip] = []
for kind, out_msec, color_code in cue_kinds:
role, slot = role_and_slot(kind)
if role == "hotcue" and slot is not None:
chips.append(HotcueChip(slot=slot, type=cue_type(out_msec),
color=palette.hex_for(color_code)))
chips.sort(key=lambda chip: chip.slot)
key_name = _name_of(getattr(row, "Key", None))
wheel, mode = parse_key(key_name)
return Track(
id=str(row.ID),
artist=_name_of(getattr(row, "Artist", None)),
title=getattr(row, "Title", None),
album=_name_of(getattr(row, "Album", None)),
genre=_name_of(getattr(row, "Genre", None)),
label=_name_of(getattr(row, "Label", None)),
remixer=_name_of(getattr(row, "Remixer", None)),
producer=None, # Rekordbox has Composer, which is not the same field
mix=None,
comment=getattr(row, "Commnt", None),
bpm=_bpm(row),
key=key_name,
key_wheel=wheel,
key_mode=mode,
# Rekordbox stores 0-5 stars directly — no /51 conversion, unlike Traktor.
rating=max(0, min(5, int(getattr(row, "Rating", 0) or 0))),
playcount=getattr(row, "DJPlayCount", None),
length=getattr(row, "Length", None),
# kbps here; the generic model (and the table) carry bits per second.
bitrate=(getattr(row, "BitRate", None) or 0) * 1000 or None,
import_date=_iso_date(getattr(row, "StockDate", None)),
last_played=None, # not modelled as a date in master.db
release_date=_iso_date(getattr(row, "ReleaseDate", None)),
filepath=str(getattr(row, "FolderPath", "") or "") or None,
cue_count=len(cue_kinds),
hotcue_count=len(chips),
hotcues=chips,
grid_marker_count=1 if (_bpm(row) and getattr(row, "AnalysisDataPath", None)) else 0,
grid_locked=False, # Rekordbox has no per-track grid lock
# What the FILE is (`store.is_stem`): Rekordbox itself plays a stem
# file's mix, but Konduktor's deck plays its stems, and the Type column
# must not disagree with the deck.
media_kind="stem" if stem else "audio",
)
def to_track_cues(cue_rows: list, grid: tuple | None, time_offset: float = 0.0) -> TrackCues:
"""Project a track's cues and beatgrid.
`grid` is the per-beat ``(times, bpms, beats)`` from the ANLZ file, collapsed here
into the generic marker list. Rekordbox pairs nothing with a grid marker, so
`companion` is always None — that is a Traktor convention.
`editable` says whether the adapter will accept a command on THIS cue, which
is the only thing the UI gates on. Every hot cue is editable, loops included.
**Memory cues are not**: Rekordbox is the only platform that has them, so
under the two-platform promotion rule they are shown and never written. A cue
sitting on the reserved `Kind` occupies no pad and is projected the same way,
because that is how Rekordbox itself displays one.
"""
markers: list[GridMarker] = []
if grid is not None:
markers = beatgrid.markers_from_beats(*grid)
cues: list[CuePoint] = []
for c in cue_rows:
role, slot = role_and_slot(getattr(c, "Kind", None))
out_msec = getattr(c, "OutMsec", None)
in_msec = getattr(c, "InMsec", 0) or 0
kind = cue_type(out_msec)
length = 0.0
if out_msec is not None and out_msec > 0:
length = max(0.0, (out_msec - in_msec) / 1000.0)
editable = role == "hotcue"
cues.append(
CuePoint(
name=(getattr(c, "Comment", None) or None),
type=kind,
role=role,
# rekordbox's clock -> the decoded audio's (see `timebase`); the
# grid arrives already converted by the store.
start=timebase.from_pioneer(in_msec / 1000.0, time_offset),
length=length,
slot=slot,
color=_cue_color(c),
editable=editable,
readonly_reason=None if editable else "platform_managed",
grid_marker=None,
)
)
return TrackCues(grid_markers=markers, grid_locked=False, cues=cues)
def _cue_color(row) -> str | None:
"""Rekordbox stores a PALETTE CODE (`ColorTableIndex`), not an RGB value;
`Color` is -1 on a coloured cue. A loop's uncoloured convention is code 0."""
return palette.hex_for(getattr(row, "ColorTableIndex", None))
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,107 @@
"""Pioneer's clock vs the decoded audio's — one rule, used at every boundary.
**rekordbox's time 0 is not always the decoded audio's time 0**, and by how much
depends on the FILE, not just its format. rekordbox does not trim the start
padding a gapless decoder removes, so every position it stores — beats, cues,
loops — sits LATER than the same moment in the decoded audio by exactly that
padding:
* **MP3 with a Xing/Info header**: the header's encoder delay + 529 decoder
delay — 1105 samples (~25 ms at 44.1 kHz) for LAME's usual 576. rekordbox
SKIPS the header frame (Traktor does not — see `adapters/traktor/timebase.py`),
it just does not trim.
* **MP3 without a header**: 0. No decoder knows the delay, so none trims it.
* **AAC / M4A** (incl. a Traktor `.stem.m4a`): the edit list's priming, which
rekordbox ignores — 1024 samples from FFmpeg's encoder, 2112 from Apple's.
* **Lossless**: 0.
Measured 2026-09-30 in rekordbox 7 with kit 4 (see the stem-conversion discussion
log): blinded hotcues Konduktor wrote on a synthetic kick landed on it only at
these offsets, hot cues placed by hand read back at them to rekordbox's 1 ms
resolution, and rekordbox's own grids agree. It replaced a fixed 1105 samples
for every lossy file, fitted to a library of MP3s that all had headers and
FFmpeg-encoded M4As — right for those, 25 ms wrong on a header-less MP3 and
22 ms wrong on Apple-encoded AAC.
Derived, not measured: an MP3 header whose delay field a decoder does not trust
(no LAME/Lavf/Lavc tag, or VBRI) — nothing is trimmed, so 0.
A file that cannot be READ (offline, or a path that does not resolve) falls back
to the old 1105 samples for a lossy suffix: the overwhelmingly common case, and
what every position written before this rule assumed.
The generic model is in the DECODED time base — what Konduktor's deck plays and
the grid detector measures. So a Pioneer adapter ADDS the offset on every write
and SUBTRACTS it on every read. Get it wrong and nothing fails: every cue and
beat is simply early in rekordbox (as the first OneLibrary exports were), or
late in Konduktor.
"""
from __future__ import annotations
from functools import lru_cache
from pathlib import Path
from ...core import mp3_gapless, mp4_edit
#: The fallback for a lossy file that cannot be read: MP3's classic codec delay.
CODEC_DELAY_SAMPLES = 1105
#: Formats that carry a start padding. `.stem.m4a` (a Traktor STEM) is AAC.
LOSSY = frozenset({".mp3", ".m4a", ".mp4", ".aac"})
_MP4 = frozenset({".m4a", ".mp4"})
_DEFAULT_RATE = 44100
@lru_cache(maxsize=4096)
def _sample_rate(path: str) -> int:
try:
import mutagen
rate = getattr(getattr(mutagen.File(path), "info", None), "sample_rate", None)
return int(rate) if rate else _DEFAULT_RATE
except Exception: # an unreadable header: assume the overwhelmingly common rate
return _DEFAULT_RATE
def _measured(p: Path) -> float | None:
"""The per-file offset, or None when the file cannot be read."""
suffix = p.suffix.lower()
if suffix == ".mp3":
start = mp3_gapless.read(p)
if start is None:
return None
return start.trimmed / start.sample_rate if start.header_frame else 0.0
if suffix in _MP4:
return mp4_edit.priming_seconds(p)
return None # raw ADTS .aac: nothing to read, keep the fallback
def offset(path: Path | str | None) -> float:
"""Seconds to ADD to a decoded-audio time to get rekordbox's; 0 if lossless.
A missing path (a track whose audio cannot be located) gets 0: there is no
file to say which format it is, and guessing lossy would move a lossless
track's cues. A path to a lossy file that cannot be read gets the fallback.
"""
if not path:
return 0.0
p = Path(path)
if p.suffix.lower() not in LOSSY:
return 0.0
measured = _measured(p)
if measured is not None:
return measured
return CODEC_DELAY_SAMPLES / _sample_rate(str(p))
def to_pioneer(seconds: float, off: float) -> float:
"""A decoded-audio time -> rekordbox's, never before its own time 0: the
generic model can hold a position before the decoded audio starts (a
Traktor grid anchored inside an MP3's header frame), which no Pioneer field
can store."""
return max(0.0, seconds + off)
def from_pioneer(seconds: float, off: float) -> float:
"""Back to the decoded time base, never before the start of the track: a
rekordbox position inside the codec delay is the track's first sample."""
return max(0.0, seconds - off)
@@ -0,0 +1,99 @@
"""Remote libraries: a library held by a Konduktor server, opened from here.
NOT a registered driver: a remote is not a file `can_open` could probe, and it
is chosen from the picker's own "Remote" step, by the saved remote's id. What
opening one returns is everything `AppState.open_remote` installs — the
adapter, the services that keep history and export sets on the server, and the
session that keeps this computer's hold on it.
Imports no platform adapter (`test_layering.py`): what platform the server
holds is the server's business, and reaches this side only as capabilities.
"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from ... import exports
from . import config
from .adapter import RemoteAdapter
from .client import AuthFailed, InUse, RemoteClient, SessionLost, Unreachable, VersionMismatch
from .services import RemotePending, RemoteServices, RemoteSetStore
from .session import RemoteSession
__all__ = [
"AuthFailed", "InUse", "Opened", "RemoteAdapter", "SessionLost", "Unreachable",
"VersionMismatch", "handshake", "open_remote",
]
@dataclass
class Opened:
remote: config.Remote
path: Path
adapter: RemoteAdapter
services: RemoteServices
session: RemoteSession
library_id: str
pending: object | None
#: Edits another computer left unsaved: {machine, summary}, or None.
pending_edits: dict | None
def open_remote(remote: config.Remote, *, takeover: bool = False, batch_probe=None,
password: str | None = None, cache=None) -> Opened:
"""Connect, take the session, and mirror the library. Raises `InUse` when
another computer holds it (and `takeover` is not set), `AuthFailed`,
`VersionMismatch` or `Unreachable` — all before anything is installed."""
secret = password if password is not None else config.password(remote.id)
if not secret:
raise AuthFailed("No password is saved for this remote — edit it to enter one")
client = RemoteClient(remote, secret)
try:
client_id = config.client_id()
hello = client.hello(client_id)
machine = config.machine_name()
acquired = client.acquire(client_id, machine, takeover=takeover)
session = RemoteSession(client, batch_probe=batch_probe, identity=(client_id, machine))
adapter = RemoteAdapter(client, session, hello, cache=cache)
session.on_reacquired = adapter.refresh
except Exception:
client.release()
client.close()
raise
# The server's id for the library, namespaced: this computer's export-set
# store for it is the SERVER (`RemoteSetStore`), and nothing this computer
# keeps under the server's own id may be mistaken for it.
library_id = f"remote:{hello['library_id']}"
exports.use_store(library_id, RemoteSetStore(client))
session.start()
return Opened(
remote=remote, path=Path(hello.get("path") or remote.name), adapter=adapter,
services=RemoteServices(client), session=session, library_id=library_id,
pending=RemotePending(client), pending_edits=acquired.get("pending_edits"),
)
def handshake(remote: config.Remote, password: str) -> list[dict]:
"""Try each of the remote's addresses on its own: what a Save of the
remote's settings reports. Each result is {address, url, ok, error, kind},
`kind` one of ok / unreachable / auth / version / other."""
results = []
for label, url in remote.addresses():
single = config.Remote(id=remote.id, name=remote.name, host=url, username=remote.username)
client = RemoteClient(single, password, timeout=8.0)
try:
info = client.hello()
results.append({"address": label, "url": url, "ok": True, "error": None, "kind": "ok",
"name": info.get("name"), "platform": info.get("platform")})
except Unreachable as ex:
results.append({"address": label, "url": url, "ok": False, "error": str(ex), "kind": "unreachable"})
except AuthFailed as ex:
results.append({"address": label, "url": url, "ok": False, "error": str(ex), "kind": "auth"})
except VersionMismatch as ex:
results.append({"address": label, "url": url, "ok": False, "error": str(ex), "kind": "version"})
except Exception as ex: # noqa: BLE001 — anything else is that address's answer
results.append({"address": label, "url": url, "ok": False, "error": str(ex), "kind": "other"})
finally:
client.close()
return results
@@ -0,0 +1,446 @@
"""`RemoteAdapter`: a library held by a Konduktor server, as a `LibraryAdapter`.
Everything above the adapter layer — routes, export, import, batches, the UI —
works on a remote library unchanged, because this IS the adapter: the server
holds the native model (`konduktor.server`), and every command travels to it
over `remote_protocol`.
* **The projection is mirrored here.** The server's tracks are fetched once
into a local `TrackIndex`, and each command's answer carries the tracks it
changed — so filtering, sorting, facets and stats are as instant as on a
local library, and use the SAME query code (`core/query.py`). Every answer
carries the server's revision; a gap (an answer out of order, a reconnect)
re-fetches the whole projection rather than guessing.
* **`audio_path` downloads.** It must return a readable file on THIS
computer, so it fetches the track into the shared cache (`cache.py`).
Anything that only needs to know WHICH file a track is asks `audio_facts`,
which never downloads.
* **Read-only when the session is not ours** — taken over, or the server out
of reach — through `capabilities()`, so the UI gates itself as it does for
any read-only library. A command the server refuses for that reason (423)
turns the session `taken_over` on the spot, not at the next heartbeat.
"""
from __future__ import annotations
import base64
import threading
from pathlib import Path
from ... import remote_protocol as rp
from ...core.adapter import (
AudioFacts,
FileTagResult,
SaveOutcome,
Unavailable,
Unsupported,
)
from ...core.capabilities import Capabilities
from ...core.query import TrackIndex
from .cache import RemoteAudioCache, StaleFacts
from .cache import shared as shared_cache
from .client import RemoteClient, SessionLost
from .session import RemoteSession
_NOT_HERE = "A remote library's paths are the server's configuration"
class RemoteAdapter:
def __init__(self, client: RemoteClient, session: RemoteSession, hello: dict, *,
cache: RemoteAudioCache | None = None):
self.platform = hello["platform"]
self.path = Path(hello.get("path") or "")
self.hello = hello
self.client = client
self.session = session
self.cache = cache or shared_cache()
self._index = TrackIndex()
self._lock = threading.RLock()
self._rev: int | None = None
self._caps: tuple[int, Capabilities] | None = None
self._facts: dict[str, AudioFacts] = {}
#: Server path of an upload → (the local file it came from, its analysis lead).
self._uploads: dict[str, tuple[Path, float | None]] = {}
self._dirty = bool(hello.get("dirty"))
self._load()
# ---- following the server ---------------------------------------------------
def _load(self) -> None:
envelope = self.client.rpc("tracks")
with self._lock:
self._index.rebuild(list(envelope["result"]))
self._rev = envelope["rev"]
self._facts.clear()
self._caps = None
def _apply(self, envelope: dict) -> None:
"""Fold a command's answer into the mirror — or re-fetch on any gap."""
with self._lock:
rev = envelope.get("rev")
if envelope.get("reset") or self._rev is None or rev != self._rev + 1:
in_order = False
else:
in_order = True
from ...core.model import Track
removed = set(envelope.get("removed") or [])
if removed:
self._index.rebuild([t for t in self._index.tracks if t.id not in removed])
for raw in envelope.get("changed") or []:
track = Track.model_validate(raw)
self._index.add(track)
self._facts.pop(track.id, None)
for track_id in removed:
self._facts.pop(track_id, None)
self._rev = rev
if not in_order:
self._load()
def _call(self, method: str, /, **args):
try:
envelope = self.client.rpc(method, **args)
except SessionLost as ex:
self.session.lost(ex.holder)
raise
if rp.RPC[method].mutating:
self.session.reached()
self._apply(envelope)
return envelope["result"]
def refresh(self) -> None:
"""Re-read everything from the server (after a restore, a reconnect)."""
self._load()
# ---- identity -----------------------------------------------------------------
def capabilities(self) -> Capabilities:
with self._lock:
cached = self._caps
if cached is None or cached[0] != self._rev:
try:
caps = self._call("capabilities")
except Unavailable:
# Out of reach: the last answer, read-only (below) — the UI
# must still render, and gate every edit.
if cached is None:
raise
caps = cached[1]
else:
with self._lock:
self._caps = (self._rev, caps)
else:
caps = cached[1]
if self.session.writable:
return caps
return caps.model_copy(update={"writable": False, "readonly_cause": self.session.readonly_cause})
def reload(self) -> None:
# The server is what holds (and drops) the edits — `AppState.discard`
# asks it to discard first; this is the mirror following.
self._load()
# ---- read projection (the mirror) -------------------------------------------
@property
def tracks(self):
return self._index.tracks
def track(self, track_id: str):
return self._index.get(track_id)
def query_tracks(self, **kw):
return self._index.query_tracks(**kw)
def facets(self):
return self._index.facets()
def stats(self, playlist_count: int):
return self._index.stats(playlist_count)
# ---- read projection (the server) -------------------------------------------
def playlist_tree(self):
return self._call("playlist_tree")
def playlist_count(self) -> int:
return self._call("playlist_count")
def playlist_entries(self, node_id: str):
return self._call("playlist_entries", node_id=node_id)
def playlist_tracks(self, node_id: str):
entries = self.playlist_entries(node_id)
if entries is None:
return None
return [t for k in entries if (t := self._index.get(k)) is not None]
def track_cues(self, track_id: str):
return self._call("track_cues", track_id=track_id)
@property
def dirty(self) -> bool:
try:
self._dirty = self._call("dirty")
except Unavailable:
pass # out of reach: what it was
return self._dirty
# ---- commands -------------------------------------------------------------------
def create_playlist(self, name, parent_id=None):
return self._call("create_playlist", name=name, parent_id=parent_id)
def create_folder(self, name, parent_id=None):
return self._call("create_folder", name=name, parent_id=parent_id)
def rename_playlist(self, node_id, name):
return self._call("rename_playlist", node_id=node_id, name=name)
def delete_playlist(self, node_id):
return self._call("delete_playlist", node_id=node_id)
def set_playlist_entries(self, node_id, track_ids):
return self._call("set_playlist_entries", node_id=node_id, track_ids=list(track_ids))
def remove_tracks(self, track_ids):
return self._call("remove_tracks", track_ids=list(track_ids))
def set_track_metadata(self, track_id, fields):
return self._call("set_track_metadata", track_id=track_id, fields=fields)
def set_key(self, track_id, wheel, mode):
return self._call("set_key", track_id=track_id, wheel=wheel, mode=mode)
def set_cue(self, track_id, *, slot, start_sec, cue_type, length_sec=0.0, role="hotcue", name=None):
return self._call("set_cue", track_id=track_id, slot=slot, start_sec=start_sec,
cue_type=cue_type, length_sec=length_sec, role=role, name=name)
def set_cue_type(self, track_id, slot, cue_type):
return self._call("set_cue_type", track_id=track_id, slot=slot, cue_type=cue_type)
def set_cue_color(self, track_id, slot, color):
return self._call("set_cue_color", track_id=track_id, slot=slot, color=color)
def delete_cue(self, track_id, slot):
return self._call("delete_cue", track_id=track_id, slot=slot)
def place_cues(self, track_id, cues, *, overwrite=False):
return self._call("place_cues", track_id=track_id, cues=list(cues), overwrite=overwrite)
def add_grid_marker(self, track_id, start_sec, bpm=None):
return self._call("add_grid_marker", track_id=track_id, start_sec=start_sec, bpm=bpm)
def move_grid_marker(self, track_id, index, start_sec):
return self._call("move_grid_marker", track_id=track_id, index=index, start_sec=start_sec)
def set_grid_marker_bpm(self, track_id, index, bpm):
return self._call("set_grid_marker_bpm", track_id=track_id, index=index, bpm=bpm)
def delete_grid_marker(self, track_id, index):
return self._call("delete_grid_marker", track_id=track_id, index=index)
def replace_grid(self, track_id, markers):
return self._call("replace_grid", track_id=track_id, markers=_pairs(markers))
def set_analysed_grid(self, track_id, markers):
return self._call("set_analysed_grid", track_id=track_id, markers=_pairs(markers))
def delete_grid(self, track_id):
return self._call("delete_grid", track_id=track_id)
def set_grid_lock(self, track_id, locked):
return self._call("set_grid_lock", track_id=track_id, locked=locked)
# ---- adding tracks ------------------------------------------------------------------
def upload_audio(self, source: Path, folder: str, name: str, *, progress=None) -> Path:
"""Send `source` into `folder` on the server; the path it landed at (a
taken name gets `-2`…, as a local copy does). What a local import's
file copy becomes when the library's destination is the server's."""
try:
landed = self.client.upload(Path(source), folder, name, progress=progress)
except SessionLost as ex:
self.session.lost(ex.holder)
raise
self._uploads[landed["path"]] = (Path(source), landed.get("analysis_lead"))
return Path(landed["path"])
def free_space(self, path: str) -> int:
"""Free space on the SERVER's disk at `path` (an import's destination)."""
return self.client.fs_space(path)
def delete_upload(self, path) -> None:
"""Undo `upload_audio` (a cancelled or failed import)."""
self._uploads.pop(str(path), None)
self.client.delete_upload(str(path))
def add_tracks(self, items, *, checkpoint=None):
"""Add uploaded files. Where the platform analyses what it adds (the
server said so with an analysis lead), the analysis is done HERE, on
the copy this computer uploaded — the server never decodes audio."""
from ...core import add_analysis
wire = []
total = len(items)
for n, item in enumerate(items, start=1):
key = str(item.audio_path)
source, lead = self._uploads.get(key, (None, None))
analysis = item.analysis
if analysis is None and lead is not None and source is not None:
if checkpoint is not None:
checkpoint(f"Analysing {item.track.title or source.name} ({n}/{total})", step=n, of=total)
has_grid = bool(item.cues and item.cues.grid_markers)
analysis = add_analysis.prepare(source, lead=lead, detect=not has_grid,
detect_key=item.track.key_wheel is None)
art = rp.WireArt(data=base64.b64encode(item.art[0]).decode("ascii"), mime=item.art[1]) \
if item.art else None
wire.append(rp.WireNewTrack(track=item.track, audio_path=key, cues=item.cues, art=art,
analysis=rp.pack_analysis(analysis)))
if checkpoint is not None:
checkpoint(f"Adding {total} track{'' if total == 1 else 's'} on the server",
step=total, of=total)
try:
envelope = self.client.rpc("add_tracks", items=wire, timeout=None)
except SessionLost as ex:
self.session.lost(ex.holder)
raise
self._apply(envelope)
for item in items:
self._uploads.pop(str(item.audio_path), None)
return envelope["result"]
def apply_stem_swaps(self, swaps, *, add_to_playlist=None):
raise Unsupported("A remote library's stem files are swapped in on the server")
# ---- Convert to Stems (the library side lives on the server) ---------------------
# `stems/remote_convert.py` drives these: the server plans and swaps, this
# computer separates. See the server's stem routes for why.
def stems_plan(self, body: dict) -> dict:
return self.client.stems_plan(body)
def stage_stem(self, track_id: str, target: str, local: Path, *, bit_rate: int,
duration: float, progress=None) -> dict:
import hashlib
digest = hashlib.sha256()
with open(local, "rb") as f:
while chunk := f.read(1 << 20):
digest.update(chunk)
try:
return self.client.stems_stage(track_id, target, local, sha256=digest.hexdigest(),
bit_rate=bit_rate, duration=duration, progress=progress)
except SessionLost as ex:
self.session.lost(ex.holder)
raise
def abandon_stems(self, targets: list[str]) -> None:
self.client.stems_abandon(targets)
def publish_stems(self, items: list[dict], options: dict) -> dict:
try:
result = self.client.stems_publish(items, options)
except SessionLost as ex:
self.session.lost(ex.holder)
raise
self._load() # ids changed (repoint) or entries were added
return result
# ---- metadata / art ------------------------------------------------------------------
def set_cover_art(self, track_id, data, mime):
try:
envelope = self.client.put_art(track_id, data, mime)
except SessionLost as ex:
self.session.lost(ex.holder)
raise
self._apply({**envelope, "removed": [], "reset": False})
def cover_art(self, track_id):
return self.client.art(track_id)
# ---- audio ------------------------------------------------------------------------------
def audio_facts(self, track_ids):
wanted = list(dict.fromkeys(track_ids))
with self._lock:
missing = [t for t in wanted if t not in self._facts]
if missing:
found = {}
for start in range(0, len(missing), 2000):
found.update(self._call("audio_facts", track_ids=missing[start:start + 2000]))
with self._lock:
self._facts.update(found)
with self._lock:
return {t: self._facts[t] for t in wanted if t in self._facts}
def audio_path(self, track_id, *, progress=None):
"""A local copy of the track's audio, downloaded if this computer has
none of this version. None when the server has no file for it."""
for attempt in range(2):
facts = self.audio_facts([track_id]).get(track_id)
if facts is None:
return None
cached = self.cache.get(facts)
if cached is not None:
return cached
try:
return self.cache.fetch(
facts, lambda partial: self.client.download(track_id, partial, progress=progress))
except StaleFacts:
with self._lock:
self._facts.pop(track_id, None)
if attempt:
raise
return None
def cached_audio(self, track_id) -> Path | None:
"""The local copy if there already is one — never downloads."""
facts = self.audio_facts([track_id]).get(track_id)
return self.cache.get(facts) if facts else None
# ---- paths: the server's business ------------------------------------------------
def set_path_mapping(self, mapping):
raise Unsupported(_NOT_HERE)
def set_session_mappings(self, mappings):
raise Unsupported(_NOT_HERE)
def unresolved_path_groups(self):
return []
def path_prefix_suggestions(self):
raise Unsupported(_NOT_HERE)
def remap_preview(self, mapping):
raise Unsupported(_NOT_HERE)
def remap_locations(self, mapping):
raise Unsupported(_NOT_HERE)
# ---- save ----------------------------------------------------------------------------
def save(self):
try:
result = self.client.save()
except SessionLost as ex:
self.session.lost(ex.holder)
raise
outcome = SaveOutcome(
summary=result.get("summary") or "",
snapshot=None,
tag_results=[FileTagResult(**r) for r in result.get("tag_results") or []],
)
# Versioned on the server; `RemoteServices.commit_save` hands it on.
outcome.commit = result.get("commit")
self._load()
return outcome
def snapshot(self) -> bytes:
raise Unsupported("A remote library's version history is kept on the server")
def close(self) -> None:
self.session.stop()
self.client.release()
self.client.close()
def _pairs(markers) -> list[tuple[float, float]]:
out = []
for m in markers:
if hasattr(m, "start"):
out.append((float(m.start), float(m.bpm)))
else:
start, bpm = m
out.append((float(start), float(bpm)))
return out
+194
View File
@@ -0,0 +1,194 @@
"""This computer's copies of a remote library's audio.
Everything that needs a track's audio as a FILE runs here, not on the server —
the deck's decode, grid and cue analysis, stem separation and extraction, an
export's copy onto a stick. One cache serves them all, so a track analysed and
then exported downloads once.
* **Keyed by what the server says the file IS** — its path there, size and
mtime (`AudioFacts`) — never by when it was fetched: an edited file (Save
writes tags into it) is a new entry, and the same file fetched again after
an eviction, or by another computer exporting the same set, is recognised.
* **A partial, renamed into place**, so a cut connection never leaves a
truncated file under a real entry's name, and a download whose size does
not match the facts is refused rather than kept.
* **Least recently used, under a cap** (`remoteCacheBytes` in prefs). The
entry just written and anything touched in the last few minutes are never
the ones evicted: they are being played or copied right now.
"""
from __future__ import annotations
import hashlib
import os
import shutil
import threading
import time
from pathlib import Path
from ... import paths, prefs
from ...core.adapter import AudioFacts, Unavailable
DEFAULT_CAP = 10 * 1024 ** 3
_RECENT = 300.0 # seconds: an entry touched this recently is in use
_PART = ".part"
class StaleFacts(Unavailable):
"""The server's file changed between asking about it and downloading it."""
def cache_root() -> Path:
return paths.app_data_dir() / "remote-cache"
def cap_bytes() -> int:
try:
value = int(prefs.load_prefs().get("remoteCacheBytes") or DEFAULT_CAP)
except (TypeError, ValueError):
value = DEFAULT_CAP
return max(value, 256 * 1024 ** 2)
class RemoteAudioCache:
def __init__(self, root: Path | None = None, *, cap=None, clock=time.time):
self.root = Path(root) if root is not None else cache_root()
self._cap = cap if cap is not None else cap_bytes
self._clock = clock
self._locks: dict[str, threading.Lock] = {}
self._guard = threading.Lock()
#: Recent download speeds (bytes/s), newest last — for time estimates.
self._speeds: list[float] = []
# ---- naming ----------------------------------------------------------------
@staticmethod
def key(facts: AudioFacts) -> str:
text = f"{facts.key}|{facts.size}|{facts.mtime_ns}"
return hashlib.sha256(text.encode("utf-8")).hexdigest()[:32]
def path_for(self, facts: AudioFacts) -> Path:
# The original's suffix, so a MIME type and a decoder's guess still work.
suffix = Path(facts.key.replace("\\", "/")).suffix.lower()
return self.root / f"{self.key(facts)}{suffix}"
def _lock_for(self, key: str) -> threading.Lock:
with self._guard:
return self._locks.setdefault(key, threading.Lock())
# ---- use -------------------------------------------------------------------
def get(self, facts: AudioFacts) -> Path | None:
path = self.path_for(facts)
if path.is_file():
self._touch(path)
return path
return None
def fetch(self, facts: AudioFacts, download) -> Path:
"""The cached copy, downloading it first if needed. `download(partial)`
writes the file and returns the server's `{size, mtime_ns}` for it."""
path = self.path_for(facts)
with self._lock_for(path.name):
if path.is_file():
self._touch(path)
return path
self.root.mkdir(parents=True, exist_ok=True)
partial = path.with_name(f"{path.name}.{os.getpid()}.{threading.get_ident()}{_PART}")
started = time.monotonic()
try:
meta = download(partial) or {}
got = partial.stat().st_size
if got != facts.size or (meta.get("size") and meta["size"] != facts.size):
raise StaleFacts(f"{Path(facts.key).name} changed on the server while downloading")
os.replace(partial, path)
finally:
partial.unlink(missing_ok=True)
elapsed = max(time.monotonic() - started, 1e-3)
if facts.size > 1 << 20:
self._speeds = (self._speeds + [facts.size / elapsed])[-8:]
self._touch(path)
self.prune(keep={path})
return path
def speed(self) -> float | None:
"""A recent download speed in bytes/s, or None before the first."""
if not self._speeds:
return None
ordered = sorted(self._speeds)
return ordered[len(ordered) // 2]
def _touch(self, path: Path) -> None:
now = self._clock()
try:
os.utime(path, (now, now))
except OSError:
pass
# ---- housekeeping ------------------------------------------------------------
def _entries(self) -> list[tuple[float, int, Path]]:
out = []
if not self.root.is_dir():
return out
for p in self.root.iterdir():
if p.name.endswith(_PART) or not p.is_file():
continue
try:
st = p.stat()
except OSError:
continue
out.append((st.st_mtime, st.st_size, p))
return out
def prune(self, keep: set[Path] | None = None) -> int:
"""Evict least-recently-used entries until under the cap. Returns bytes freed."""
cap = self._cap() if callable(self._cap) else self._cap
entries = sorted(self._entries())
total = sum(size for _, size, _ in entries)
freed = 0
now = self._clock()
for used, size, p in entries:
if total <= cap:
break
if (keep and p in keep) or now - used < _RECENT:
continue
try:
p.unlink()
except OSError:
continue # held open (Windows): next time
total -= size
freed += size
return freed
def usage(self) -> dict:
entries = self._entries()
cap = self._cap() if callable(self._cap) else self._cap
return {"bytes": sum(s for _, s, _ in entries), "files": len(entries), "cap": cap,
"free": _free(self.root)}
def clear(self) -> int:
freed = 0
for _, size, p in self._entries():
try:
p.unlink()
freed += size
except OSError:
pass
return freed
def _free(folder: Path) -> int:
probe = folder
while not probe.exists() and probe != probe.parent:
probe = probe.parent
try:
return shutil.disk_usage(probe).free
except OSError:
return 0
_shared: RemoteAudioCache | None = None
def shared() -> RemoteAudioCache:
global _shared
if _shared is None:
_shared = RemoteAudioCache()
return _shared
+302
View File
@@ -0,0 +1,302 @@
"""Talking to a Konduktor server: addresses, sign-in, and the error vocabulary.
Every request tries the address that last worked, then the others in the
remote's order (primary, then fallback) — so a laptop that leaves the house
moves from the LAN address to the VPN one without being asked, and back again.
Only a CONNECT failure moves on: the request never reached that server, so
sending it to the other one cannot apply it twice. A request that reached a
server and then failed is that server's answer.
The server's refusals come back as the adapter's own error classes (the same
status codes `main.py` maps them from), so a route on this computer reports a
remote library's refusal exactly as it would a local one's.
"""
from __future__ import annotations
import logging
import threading
from pathlib import Path
import httpx
from ... import remote_protocol as rp
from ...core.adapter import (
AdapterError,
InvalidCommand,
LibraryNotSupported,
NotFound,
Unavailable,
Unsupported,
)
from .config import Remote
log = logging.getLogger(__name__)
_CONNECT_ERRORS = (httpx.ConnectError, httpx.ConnectTimeout)
class Unreachable(Unavailable):
"""No address of the remote answered."""
class AuthFailed(LibraryNotSupported):
"""The server refused the username or password."""
class VersionMismatch(LibraryNotSupported):
def __init__(self, update: str, server_version: str):
side = "Konduktor on this computer" if update == "app" else "the Konduktor server"
super().__init__(
f"This server speaks a different version of Konduktor's protocol "
f"(server {server_version}): update {side}."
)
self.update = update
class InUse(AdapterError):
"""Another computer holds the session: `holder` = {machine, since, batch}."""
def __init__(self, holder: dict):
super().__init__(f"In use by {holder.get('machine') or 'another computer'}")
self.holder = holder
class SessionLost(Unavailable):
"""This computer no longer holds the session (another one took over)."""
def __init__(self, holder: dict | None):
who = (holder or {}).get("machine")
super().__init__(
f"{who} has taken over this library — it is read-only here" if who
else "This computer no longer holds the library's session"
)
self.holder = holder
def _detail(response: httpx.Response):
try:
return response.json().get("detail")
except Exception: # noqa: BLE001
return response.text[:300]
class RemoteClient:
def __init__(self, remote: Remote, password: str, *, timeout: float = 30.0):
self.remote = remote
self._addresses = remote.addresses()
self._active: int | None = None
self.token: str | None = None
self._lock = threading.Lock()
self._http = httpx.Client(
auth=(remote.username, password),
timeout=httpx.Timeout(timeout, connect=4.0),
follow_redirects=False,
)
def close(self) -> None:
self._http.close()
@property
def via(self) -> str | None:
"""Which address is in use: "primary" / "fallback" (None until one answers)."""
return None if self._active is None else self._addresses[self._active][0]
# ---- transport ----------------------------------------------------------------
def _order(self) -> list[int]:
everything = list(range(len(self._addresses)))
if self._active is None:
return everything
return [self._active] + [i for i in everything if i != self._active]
def request(self, method: str, path: str, *, retry: bool = True, session: bool = True,
**kw) -> httpx.Response:
headers = dict(kw.pop("headers", None) or {})
if session and self.token:
headers[rp.SESSION_HEADER] = self.token
order = self._order() if retry else ([self._active] if self._active is not None else [0])
last: Exception | None = None
for i in order:
base = self._addresses[i][1]
try:
response = self._http.request(method, base + path, headers=headers, **kw)
except _CONNECT_ERRORS as ex:
last = ex
continue
except httpx.TimeoutException as ex:
self._active = i
raise Unreachable(f"The server at {base} stopped answering") from ex
except httpx.TransportError as ex:
last = ex
continue
self._active = i
return self.check(response)
names = " or ".join(b for _, b in (self._addresses[i] for i in order))
raise Unreachable(f"Cannot reach the server at {names}") from last
def stream(self, method: str, path: str, **kw):
"""A streaming request on the address in use (a download)."""
headers = dict(kw.pop("headers", None) or {})
if self.token:
headers[rp.SESSION_HEADER] = self.token
# Pick the address first with a cheap call, so the stream itself is not
# the request that discovers the primary is gone.
if self._active is None:
self.request("GET", "/v1/hello", session=False)
base = self._addresses[self._active][1]
return self._http.stream(method, base + path, headers=headers, **kw)
@staticmethod
def check(response: httpx.Response) -> httpx.Response:
status = response.status_code
if status < 400:
return response
detail = _detail(response)
if status == 401:
raise AuthFailed("The server refused the username or password")
if status == 423:
raise SessionLost((detail or {}).get("holder") if isinstance(detail, dict) else None)
if status == 409 and isinstance(detail, dict) and detail.get("code") == "in_use":
raise InUse(detail)
text = detail if isinstance(detail, str) else (detail or {}).get("message", str(detail))
cls = {404: NotFound, 400: InvalidCommand, 422: Unsupported, 503: Unavailable}.get(status)
if cls is not None:
raise cls(text)
raise AdapterError(f"The server answered {status}: {text}")
# ---- handshake + session ----------------------------------------------------------
def hello(self, client_id: str | None = None) -> dict:
info = self.request("GET", "/v1/hello", params={"client_id": client_id} if client_id else None,
session=False).json()
server_version = tuple(info.get("api_version") or (0, 0))
update = rp.compatible(rp.API_VERSION, (int(server_version[0]), int(server_version[1])))
if update:
raise VersionMismatch(update, info.get("app_version") or ".".join(map(str, server_version)))
return info
def acquire(self, client_id: str, machine: str, *, takeover: bool = False) -> dict:
body = self.request("POST", "/v1/session/acquire", session=False,
json={"client_id": client_id, "machine": machine, "takeover": takeover}).json()
self.token = body["token"]
return body
def heartbeat(self, batch: str | None) -> dict:
return self.request("POST", "/v1/session/heartbeat", json={"batch": batch}).json()
def release(self, *, timeout: float | None = None) -> None:
if not self.token:
return
try:
kw = {"timeout": timeout} if timeout is not None else {}
self.request("POST", "/v1/session/release", retry=False, **kw)
except AdapterError:
pass
self.token = None
# ---- the protocol -------------------------------------------------------------------
def rpc(self, method: str, /, *, timeout=..., **args) -> dict:
"""Call one protocol method; the envelope `{result, rev, changed, removed, reset}`
with `result` already deserialised."""
kw = {} if timeout is ... else {"timeout": timeout}
body = self.request("POST", f"/v1/rpc/{method}", json={"args": rp.dump_args(method, args)}, **kw).json()
body["result"] = rp.load_result(method, body.get("result"))
return body
# ---- bytes -----------------------------------------------------------------------------
def download(self, track_id: str, target: Path, *, progress=None) -> dict:
"""Stream a track's audio into `target`; its server-side size and mtime."""
with self.stream("GET", "/v1/audio", params={"track_id": track_id}, timeout=None) as response:
if response.status_code >= 400:
response.read()
self.check(response)
with open(target, "wb") as out:
for chunk in response.iter_bytes(1 << 20):
out.write(chunk)
if progress is not None:
progress(len(chunk))
return {
"size": int(response.headers.get("X-Konduktor-Size") or 0),
"mtime_ns": int(response.headers.get("X-Konduktor-Mtime-Ns") or 0),
}
def upload(self, source: Path, folder: str, name: str, *, progress=None) -> dict:
def body():
with open(source, "rb") as f:
while chunk := f.read(1 << 20):
if progress is not None:
progress(len(chunk))
yield chunk
return self.request("POST", "/v1/upload", params={"dir": folder, "name": name},
content=body(), retry=False, timeout=None).json()
def delete_upload(self, path: str) -> None:
self.request("DELETE", "/v1/upload", params={"path": path})
def art(self, track_id: str) -> tuple[bytes, str] | None:
try:
r = self.request("GET", "/v1/art", params={"track_id": track_id})
except NotFound:
return None
return r.content, r.headers.get("content-type", "image/jpeg").split(";")[0]
def put_art(self, track_id: str, data: bytes, mime: str) -> dict:
return self.request("PUT", "/v1/art", params={"track_id": track_id, "mime": mime},
content=data).json()
def fs_list(self, path: str | None) -> dict:
return self.request("GET", "/v1/fs/list", params={"path": path} if path else None).json()
def fs_space(self, path: str | None) -> int:
return int(self.request("GET", "/v1/fs/space", params={"path": path} if path else None).json()["free"])
# ---- Convert to Stems ----------------------------------------------------------------
def stems_plan(self, body: dict) -> dict:
return self.request("POST", "/v1/stems/plan", json=body, timeout=None).json()
def stems_stage(self, track_id: str, target: str, source: Path, *, sha256: str,
bit_rate: int, duration: float, progress=None) -> dict:
def body():
with open(source, "rb") as f:
while chunk := f.read(1 << 20):
if progress is not None:
progress(len(chunk))
yield chunk
return self.request(
"PUT", "/v1/stems/stage",
params={"track_id": track_id, "target": target, "sha256": sha256,
"bit_rate": bit_rate, "duration": duration},
content=body(), retry=False, timeout=None,
).json()
def stems_abandon(self, targets: list[str]) -> None:
self.request("POST", "/v1/stems/abandon", json={"targets": targets})
def stems_publish(self, items: list[dict], options: dict) -> dict:
return self.request("POST", "/v1/stems/publish", json={"items": items, "options": options},
timeout=None).json()
def stems_pending(self) -> dict:
return self.request("GET", "/v1/stems/pending").json()
# ---- save / history / export sets -------------------------------------------------
def save(self) -> dict:
return self.request("POST", "/v1/save", timeout=None).json()
def discard(self) -> dict:
return self.request("POST", "/v1/discard", timeout=None).json()
def history(self) -> list[dict]:
return self.request("GET", "/v1/history").json()
def restore(self, commit_id: str) -> dict:
return self.request("POST", f"/v1/history/{commit_id}/restore", timeout=None).json()
def clear_history(self) -> None:
self.request("DELETE", "/v1/history")
def export_sets(self) -> dict:
return self.request("GET", "/v1/export-sets").json()
def put_export_sets(self, doc: dict) -> None:
self.request("PUT", "/v1/export-sets", json=doc)
+199
View File
@@ -0,0 +1,199 @@
"""Saved remotes: the servers this computer knows how to reach.
A remote is where a Konduktor server is (an address, an optional port, and a
fallback address — typically the LAN address first and a VPN one second) and
who to sign in as. Everything but the password is a plain preference
(`userprefs.json`, key `remotes`); the password lives in the OS keychain
(macOS Keychain, Windows Credential Manager) through `keyring`, never in a JSON
file beside the app's other data.
This computer also has a stable `client_id`, which is how a server tells "the
same laptop back from sleep" (renew its session silently) from "another
computer" (offer a takeover).
"""
from __future__ import annotations
import socket
import uuid
from dataclasses import asdict, dataclass
from ... import prefs
DEFAULT_PORT = 8765
_PREFS_KEY = "remotes"
_CLIENT_KEY = "remoteClientId"
_KEYRING_SERVICE = "Konduktor"
@dataclass
class Remote:
id: str
name: str
host: str
port: int | None = None
fallback_host: str | None = None
fallback_port: int | None = None
username: str = ""
def addresses(self) -> list[tuple[str, str]]:
"""`(label, base url)`, primary first — the order every connect tries.
Each address keeps its OWN port. The fallback once borrowed the
primary's, so a reverse-proxied fallback (`konduktor.example.net`,
served on 443) was tried at `:8765` because the LAN address named it.
"""
out = [("primary", _base(self.host, self.port))]
if self.fallback_host:
out.append(("fallback", _base(self.fallback_host, self.fallback_port)))
return out
def public(self) -> dict:
return asdict(self)
def _base(host: str, port: int | None) -> str:
"""An address as typed → a base URL. A full URL (`https://…`, the way to
reach a server behind the user's own reverse proxy) is taken exactly as
given, port and all; anything else is plain HTTP on its port, else 8765."""
host = host.strip()
if host.startswith("http://") or host.startswith("https://"):
return host.rstrip("/")
bare, inline = split_host(host)
if inline is not None:
host, port = bare, port or inline
if ":" in host and not host.startswith("["):
host = f"[{host}]" # an IPv6 literal
return f"http://{host}:{port or DEFAULT_PORT}"
def split_host(text: str) -> tuple[str, int | None]:
"""`"nas.local:9000"` → `("nas.local", 9000)`; a bare host keeps no port."""
text = (text or "").strip()
if text.startswith("http://") or text.startswith("https://"):
return text, None
if text.count(":") == 1:
host, _, port = text.partition(":")
if port.isdigit():
return host, int(port)
return text, None
# ---- the list ------------------------------------------------------------------
def remotes() -> list[Remote]:
raw = prefs.load_prefs().get(_PREFS_KEY) or []
out = []
for item in raw if isinstance(raw, list) else []:
try:
out.append(Remote(**{k: item.get(k) for k in Remote.__dataclass_fields__ if k in item}))
except TypeError:
continue
return out
def get(remote_id: str) -> Remote | None:
return next((r for r in remotes() if r.id == remote_id), None)
def save(remote: Remote) -> Remote:
items = [r for r in remotes() if r.id != remote.id] + [remote]
prefs.update_prefs({_PREFS_KEY: [r.public() for r in items]})
return remote
def delete(remote_id: str) -> bool:
before = remotes()
items = [r for r in before if r.id != remote_id]
prefs.update_prefs({_PREFS_KEY: [r.public() for r in items]})
forget_password(remote_id)
return len(items) != len(before)
def new_id() -> str:
return uuid.uuid4().hex[:12]
# ---- this computer ---------------------------------------------------------------
def client_id() -> str:
current = prefs.load_prefs().get(_CLIENT_KEY)
if isinstance(current, str) and current:
return current
fresh = uuid.uuid4().hex
prefs.update_prefs({_CLIENT_KEY: fresh})
return fresh
def machine_name() -> str:
"""What another computer is told holds the library ("Ben's MacBook")."""
try:
import subprocess
import sys
if sys.platform == "darwin":
name = subprocess.run(["scutil", "--get", "ComputerName"], capture_output=True,
text=True, timeout=2).stdout.strip()
if name:
return name
except Exception: # noqa: BLE001
pass
name = socket.gethostname()
return name[:-6] if name.endswith(".local") else name
# ---- the password ------------------------------------------------------------------
# A seam for tests (and any machine without a keychain): `use_password_store`.
class _Keyring:
def get(self, account: str) -> str | None:
import keyring
return keyring.get_password(_KEYRING_SERVICE, account)
def set(self, account: str, password: str) -> None:
import keyring
keyring.set_password(_KEYRING_SERVICE, account, password)
def delete(self, account: str) -> None:
import keyring
from keyring.errors import PasswordDeleteError
try:
keyring.delete_password(_KEYRING_SERVICE, account)
except PasswordDeleteError:
pass
_store = _Keyring()
def use_password_store(store) -> None:
"""Replace the keychain (`get`/`set`/`delete` by account) — tests only."""
global _store
_store = store if store is not None else _Keyring()
def _account(remote_id: str) -> str:
return f"remote:{remote_id}"
def password(remote_id: str) -> str | None:
try:
return _store.get(_account(remote_id))
except Exception: # noqa: BLE001 — a locked keychain reads as "no password"
return None
def set_password(remote_id: str, value: str) -> None:
_store.set(_account(remote_id), value)
def forget_password(remote_id: str) -> None:
try:
_store.delete(_account(remote_id))
except Exception: # noqa: BLE001
pass
Loaded 100 of 356 files, more files were not shown because too many files have changed in this diff. Show more