Compare commits

..
Author SHA1 Message Date
patben8 f655bb4cf2 Implemented demucs engine 2026-09-30 19:26:00 +02:00
patben8 e4e98eda3f Implemented Discard changes button 2026-09-30 17:07:26 +02:00
patben8 4e875958a7 Implemented foundation of STEM support 2026-09-30 17:07:06 +02:00
patben8 387f97853d Fixed track collision bug 2026-09-30 15:54:49 +02:00
patben8 3c4238f60c Refined Rekordbox timing fix 2026-09-30 13:18:56 +02:00
patben8 d087310a9d Refined traktor timing fix 2026-09-30 11:18:10 +02:00
patben8 2a4c403d43 Implemented traktor utility fixes 2026-09-30 10:10:37 +02:00
124 changed files with 606 additions and 9950 deletions

No files matched your search

+27 -331
View File
@@ -47,10 +47,6 @@ Two independent apps that talk over HTTP:
- `registry.py` — adapter selection by **`can_open()` probe**, not extension
(Rekordbox is a `.db`, Serato is a directory).
- `audio_tags.py`, `pathmap.py` — format-agnostic helpers.
- `grid_edit.py` (`ReplaceGridCommands`) — the marker-level grid commands
(add / move-with-clamp / retempo / delete) for a store whose one primitive
is `replace_grid`: Rekordbox's and OneLibrary's, whose grids are per-beat
lists. Traktor keeps its own, companion-aware versions.
- `relocate.py` — **auto path remapping's search** (see `relocation.py`).
Fixes ONE thing: a stored prefix changed and the layout under it did not
(a collection built on Windows with the SSD as `X:`, opened on a Mac where
@@ -162,8 +158,7 @@ Two independent apps that talk over HTTP:
only a file a scan found is streamed, so `/api/folder/tracks/audio` cannot
read an arbitrary path. Tagged keys are deliberately dropped (every
notation there is). The listed suffixes are the collection's
`tracks.audio_formats` capability. A stem file lists as
`media_kind: "stem"` (its `stem` box, read at scan time).
`tracks.audio_formats` capability.
- `adapters/traktor/` — everything that knows NML exists.
- `store.py` (`TraktorStore`) — the retained native model: owns the parsed
dataclass NML, applies every edit, renders + saves. See "Write path".
@@ -258,21 +253,6 @@ Two independent apps that talk over HTTP:
bank. Point cues AND loops both write; `cue_types` owns the translation.
**Memory cues stay preserved-but-uneditable** (Rekordbox is the only
platform with them — the two-platform promotion rule).
**Hot cue colour is writable** (`set_cue_color`, `PATCH
/api/tracks/cue/color`) from `palette.SWATCHES` — all 16 of rekordbox's
swatches, MEASURED (the teal-green, 0x13 #00FF30, came last: rekordbox
wrote it as its default for a hot cue added on a stick); a pick must
be an exact swatch (`swatch_code`), unlike the exporter's nearest-hue
`code_for`. Not a breach of the promotion rule: Rekordbox, OneLibrary and
Serato all colour cues — Traktor is the odd one out, by type only, so it
reports `color="none"`. **The colour belongs to the PAD**: `set_cue` with
no colour keeps the slot's existing code, so rename, type change and an
Auto Hotcues Replace keep it; only Delete or "Default" clear it. Both
columns go through `RekordboxStore._apply_color` (coloured: code +
`Color=-1`; uncoloured loop: `255/0`; uncoloured cue: `-1/NULL`). An
unknown code projects as no colour but stays on the row. Uncoloured cues
still DRAW in Konduktor's type colours, not rekordbox's green/orange
defaults (decided 2026-10-01: those defaults are unmeasured).
- **Saving warns but does not block when Rekordbox is running.**
`pyrekordbox.commit()` refuses outright, and its check is process-wide
rather than per-file, so `RekordboxStore._commit()` suppresses that veto
@@ -300,73 +280,9 @@ Two independent apps that talk over HTTP:
`close()` disposes the SQLAlchemy engine, not just the session — otherwise
the OS file handle stays open and `master.db` cannot be replaced. `AppState`
closes the previous adapter when opening a new library.
- `adapters/onelibrary/` — **editable when opened as THE library; read-only
when browsed from the sidebar's Devices** (`read_only=True`, cause `browsing`).
The cross-vendor USB export format (AlphaTheta + Algoriddim + Native
Instruments), read by CDJ-class hardware. Editing is landing in steps toward
parity with the Rekordbox adapter — track metadata, playlists, hot cues and
the beatgrid, and the `export.pdb` rebuild done and VERIFIED in rekordbox 7
(both library views matched); adding/removing tracks done (checked
in rekordbox too) and the UI ("Open for editing…" on a Devices row) — all
VERIFIED in rekordbox 7 on a real stick (2026-10-01) — decided in
[the editing discussion](.claude/discussions/discuss-onelibrary-editing-2026-10-01.md),
which also holds what rekordbox 7 was MEASURED writing when it edits a stick
(no update counter moves, the `cue` table stays empty, a new playlist goes on
top). **The store never opens the database ON the drive**: it works on a copy
in app-data and Save writes it back whole — fingerprint check (refuses if
another app wrote the stick since open), backup to app-data, temp file beside
the database, stale `-wal`/`-shm` deleted, rename — then writes edited text
fields into the audio files' tags as rekordbox does (not the rating). Cue tags
are read by Konduktor's own `rekordbox/anlz_file.py`, NOT pyrekordbox: rekordbox
writes COMPACT cue entries when it edits (48 / 44 bytes, export: 88), and
pyrekordbox's parser raised on the 44-byte one and lost the whole `.EXT`.
**Cue and grid edits rewrite only the cue LISTS they touch, and inside them
only the entries they touch** (`anlz_file.raw_entries` keeps the rest as
rekordbox wrote them), held as edited in-memory copies of the `.DAT`/`.EXT`
that every read serves, written at Save BEFORE the database (temp + rename,
fingerprinted, backed up). Each rule reproduces rekordbox's own measured edit
byte for byte: a recolour changes only the `PCP2` colour bytes (palette code
+ RGB — rekordbox draws the CODE, so `cues.color` is `palette`, like
master.db); a new pad is APPENDED to its lists; a grid edit rewrites `PQTZ`,
BLANKS `.EXT`'s `PQT2` (`anlz_writer.blank_pqt2`), clears every loop's beat
length to 0/0, leaves `.2EX` alone, and sets `bpmx100` from the first marker.
A pad keeps its colour and (unless given one) its name through a move or
retype. An `.EXT` without `PCO2` gets both lists seeded from its `PCOB`s on
the first edit — readers prefer `PCO2`, so a one-pad list would hide the rest.
A track with no analysis files refuses cue/grid edits. Memory cues stay
preserved-but-uneditable.
**`device_library.py` keeps the stick's legacy `export.pdb` in step** at
every Save (rekordbox's own edits let its playlists drift — measured). The
stick's own pdb is EDITED (`pdb.PdbEditor`), not regenerated: ids are
mirrored from OneLibrary (rekordbox exports both from the same ids), only the
tracks / lookup / playlist tables are candidates, a table is rewritten only if
a row changed, an unchanged row keeps rekordbox's bytes, and a changed track
row is the old row with the edited fields overwritten — so phrase strings,
`masterDbId` halves and play counts survive. A track row ends at its last
string (`pdb.track_extent`), NOT at the next row: rekordbox's heap holds stale
tails between rows. Keys and artwork are mirrored too (pdb artwork row =
`a<n>.jpg` beside OneLibrary's `b<n>`); history and `exportExt.pdb` are
untouched.
**Adding and removing tracks** (`tracks.places_audio`: the LIBRARY places
added audio, so the importer asks `place_audio` instead of the user, and the
routes check space at `audio_home()`): a file already on the stick is used in
place, anything else is copied to `Contents/<Artist>/<Album>/` (rekordbox's
layout: `UnknownArtist`/`UnknownAlbum`, file names cut to 48 characters) via
`<stick>/.konduktor-incoming/`, playable from there until Save moves it into
place; Discard deletes it, and a crashed session's incoming folder is cleared
on the next EDITABLE open (never a browsing one). Each added track is decoded
once and gets the OneLibrary exporter's own `.DAT`/`.EXT`/`.2EX`
(`OneLibraryExporter.anlz_files` builds bytes rather than writing) and art
(`art_files`), held in memory and written at Save; hot cues replay through
`set_cue`, memory cues (and a hot cue with no free pad) cross as memory cues.
The row copies a rekordbox stick row column for column (search columns NULL,
no counters) and `property.numberOfContents` follows. Removing deletes every
row naming the track (playlist entries renumbered from 1) and, AFTER the
database is saved, its audio, analysis files and unshared artwork, pruning
emptied folders. The adapter re-projects after every save, since Save moves
files. `save.managed_by_export` is set when the drive's root carries an
export set's `.konduktor-export.json`, and SaveBar warns that the next export
run replaces edits made in place.
- `adapters/onelibrary/` — **read-only.** The cross-vendor USB export format
(AlphaTheta + Algoriddim + Native Instruments), read by CDJ-class hardware.
Built as the source half of a future "import a stick into Traktor" feature.
Full research, incl. the schema, is in
[.claude/handoffs/onelibrary-adapter.md](.claude/handoffs/onelibrary-adapter.md);
the four things that make it unlike the Rekordbox adapter:
@@ -397,18 +313,6 @@ Two independent apps that talk over HTTP:
`track_cues()`. The `PQTZ` beatgrid is the same tag as Rekordbox's, and the
collapse rule is **shared by import** rather than copied — two definitions of
"when does a tempo change start a marker" would drift silently.
- **A stem file ADDED to a Traktor collection** (folder add, import, the
Traktor exporter — all `TraktorStore.add_entry`) gets `<STEMS>` rendered
from its OWN box by `stem_file.traktor_stems_json` (keys sorted, compact,
whole floats as integers, else 16 significant digits) — measured to give
Traktor's value for every local stem file and to re-render all 3,678 in the
big collection unchanged, though every one of those is NI's default
layout. Without it the entry read as plain audio (Type column, playlist
`TYPE="TRACK"`) while the deck, which reads the file, played stems.
Rekordbox and OneLibrary have no such element, so their projections take
`media_kind` from the FILE (`stem_file.is_stem_file`, only `.m4a`/`.mp4`
opened, ~0.7 ms each, cached per path in `RekordboxStore.is_stem`) — the
same mismatch otherwise: Type said audio while the deck played stems.
- `importer.py` also serves the folder add: `reference=True` adds each file
where it is (nothing to copy or roll back), and every planned file the
destination already points at (matched on `audio_path`, never the display
@@ -418,62 +322,6 @@ Two independent apps that talk over HTTP:
the view's, so browsing elsewhere cannot point it at endpoints that do not
know the track. `trackAudioUrl`/`trackCuesFor` in `api.ts` are the one place
that choice is made.
- `stems/` — Convert to Stems around the file itself. `engine_manager.py`:
the engine version THIS build needs (`engine.json`) and the pinned weights
(`weights.json`, a copy of `engine/weights.json` a test keeps equal).
Installs under app-data (Windows: a SHORT `%LOCALAPPDATA%\Konduktor\engine`
for the 260-char limit); an install counts only after every part's hash,
the archive's, AND the unpacked engine starting and naming the expected
version (`probe`) — `installed.json` is written last. One engine at a time;
CUDA offered only for driver r580+ and capability 7.5+ (`nvidia-smi`).
Side-loading (offline) verifies against the release manifest, cached once
seen. `download.py`: resumable (`Range`, restarts if ignored), SHA-verified,
certifi TLS (a frozen macOS Python has no CA store). `engine_process.py`:
one `serve` per batch — progress, cancel-by-message, crash reported with
the engine's stderr tail, raw work files deleted as read, a Windows Job
Object and `keep_awake` (caffeinate / SetThreadExecutionState). Routes:
`GET /api/stems/engine`, `POST .../install` (a `stem-engine-install` job in
bytes, engine + weights), `POST .../sideload`, `DELETE`.
**`convert.py` — the batch** (`POST /api/tracks/stems/preview` and
`/convert`, a `stem-conversion` job in `BATCH_JOBS`, exclusive with the
engine install and import). The collection is UNTOUCHED while tracks
convert (hours, on a big batch): each becomes a verified
`<target>.konduktor-partial`, so edits made meanwhile carry over and Cancel
only deletes new files. One short END STEP under `STATE.mutation` then
publishes each (a rename that refuses to overwrite: link+unlink on POSIX),
parks each original in Replace mode (`.<name>.<ext>.konduktor-parked`,
same folder, hidden on Windows, retried while Windows holds it open) and
swaps every entry at once. Skips (reported, not failed): already a stem file
BY CONTENT, missing file, target exists (never overwritten), two sources
onto one (case-folded) target, a target the collection names; disk space is
preflighted per volume (both copies coexist until Save) and for the work
folder. Replace implies repoint; destination mode mirrors the tree (full
path, volume first, when the tracks share no folder) and may repoint or add
(+ existing / new playlist). **`pending.py` — the ledger** of conversions
awaiting Save (per library id, atomic): `AppState._save` COMMITS (deletes
parked originals, retargets export sets — inside `_save`, so import and
remap saves count too), `discard()` and opening another library RESTORE,
and `_open` RECOVERS a crash before the missing-files check (parked
originals would look missing): each item decided by whether the SAVED
library names the stem file. Every step works from what is on disk, never
the recorded state alone; only a stem file the batch PUBLISHED is ever
deleted; an uncommitted verified stem file is kept under its partial name
and REUSED by the next batch converting the same (unchanged) source.
While conversions are pending or running, remap-paths, path mapping,
relocation, import, folder add, history restore and reload answer 409
(`_require_no_pending_stems`): each would save or drop the swap.
`/api/state` reports `pending_stems`, `stem_job`, `stem_recovery`.
**`stream_cache.py` — stem PLAYBACK.** A browser decodes only an MP4's
FIRST audio stream (the mix), so each stem is served as a file of its own:
the three audio routes (collection / `source` / `folder`) take
`?stem=0..3`, and `/api/…/tracks/stems` report `[{name, color}]` read from
the FILE (`stem_file.stem_layout`: the box, and enough streams — never the
library's `<STEMS>`, which plain MP3s carry). `stem_file.extract_stream`
COPIES packets into an `ipod` MP4 — measured bit-identical to decoding the
stream in place, edit list and priming (1024 / 2112) intact, on commercial
stems too, so stems stay sample-locked to the mix and the cues. Cached in
app-data keyed by path + size + mtime, LRU under 2 GB, written partial →
rename; ~0.1 s per stem uncached.
- `app_state.py` — the one loaded library, and the **version-history commit**.
**`discard()`** (`POST /api/discard`, SaveBar's "Discard changes…", the
quit prompt's Discard) drops every unsaved edit through the adapter's own
@@ -636,20 +484,12 @@ Two independent apps that talk over HTTP:
clicking a folder is the `folder` source kind — its audio in the ordinary
table, read-only via `readonly_cause: 'not_in_library'`, with files the
collection already holds checked off in the # column (`TrackTable`'s
`marked`). A browsed device is read-only (cause `browsing`); **"Open for
editing…"** — the drive row's right-click menu, and a button while browsing
a device whose caps say `browsing` — opens it as THE library via App's
`openForEditing` (unsaved-edits confirm, source closed, library opened).
Capped at 40% of the sidebar and self-scrolling so a deep tree
`marked`). Capped at 40% of the sidebar and self-scrolling so a deep tree
gives way before the playlists do) + `AddFilesDialog` (copy vs. leave in
place is **asked every time with nothing preselected** — the answer depends
on the drive — and warns that a referenced file on an external drive goes
missing on unplug. A playlist/export target adds to the collection first
and says so; it runs through `importer.run(reference=…, into_playlist=…)`.
A library with `tracks.places_audio` (a stick) is the exception: no
question and no destination — the dialog STATES how many files are copied
and how many stay in place (`platformCopy.placedAudioSummary`), and
`ImportDialog` drops its destination folder the same way),
and says so; it runs through `importer.run(reference=…, into_playlist=…)`),
`CollectionPicker` (**two steps: which PLATFORM, then which
library** — Automatic / Open last / Find manually, the last revealing a file
browser. The platform comes first because every later answer depends on it:
@@ -697,28 +537,6 @@ Two independent apps that talk over HTTP:
flushSync-driven measurement — which is why playlists were once a separate,
non-virtualized `PlaylistTable`. Fixed 44 px rows make the drop index just
pointer-y / ROW_HEIGHT. dnd-kit still reorders the header's columns.)
`ConvertStemsDialog` (**Convert to Stems**, one dialog — decided: Where =
Replace the originals (its option STATES that Save deletes them, since
the choice is remembered and may be preselected) or Save to a folder; In
the collection = point at the stem file / add as new tracks + playlist
(folder mode only); a live preview from `POST /api/tracks/stems/preview`
— N to convert, skipped ▸ with reasons, a time estimate from measured
real-time factors, space; the engine download INLINE, offering the GPU
engine when `nvidia` is set, which keeps running if the dialog closes
(App shows it in the status bar). Every option persists as `stemConvert`),
`StemReportDialog` (the Details behind a finished run's toast — every
skipped/failed track with its reason), `StemsSettings` (Settings → Stems:
engine status / download / install from a folder / remove, compute device
`stemDevice`, the remembered defaults, originals awaiting Save). App
follows a finished run's `{old: new}` ids with the deck and the selection,
picks a running conversion back up from `/api/state.stem_job` after a
reload, and reports `stem_recovery` once. The menu item is shown DISABLED
with a reason (`MenuItem.title` — rendered `aria-disabled`, not
`disabled`, since browsers show no tooltip on a disabled button) where the
platform cannot play stem files as stems. SaveBar adds "Saving deletes N
original files" while conversions are pending (decided: the consequence is
shown where Save is pressed). `Toast` takes an optional `action`;
`StatusJob.unit: 'bytes'` shows a download in MB. Every background job's status-bar entry reads label + count · a bar SPLIT horizontally when the job reports per-item progress (top = the current item's `fraction`, 0-100 %; bottom = the whole job, (done + fraction) / total, so 99 % into the first of two tracks reads ~50 %) — a single bar otherwise; two colours in one bar was tried and read as confusing · its `status` ("separating 41 %") at its natural width · the item's name LAST (the only part that truncates; full name on hover). The section is a FIXED width (560 px; the view name on the left gives way instead) and everything BEFORE the bar is fixed (count sized for its largest value, "cancelling…" as a status, not a label), so neither a long name nor a phase change moves the bar. The status deliberately has no fixed slot: it is after the bar, and a slot left a gap before the name. `Job.fraction`/`status` come from `JobHandle.progress(fraction=, status=)` and reset whenever `done` advances; a stem conversion maps decode / separate / encode onto a track's 0-1 by measured shares.
`AutoCueDialog` (the Auto Hotcues slot template: event + beat offset per
slot, a per-slot Replace tick for occupied slots — never remembered, since
overwriting is a decision about THIS track — and the template itself
@@ -746,24 +564,6 @@ Two independent apps that talk over HTTP:
browser via `@tauri-apps/plugin-shell` `open` — falls back to `window.open`
outside Tauri; "Skip this version" persists `skippedUpdateVersion` to
userprefs via `/api/prefs`; all failures are silent).
- **Stem playback** (decided 2026-09-30): a stem FILE always loads its four
stems (`trackStemsFor` / `trackStemUrl` in `api.ts`) and the deck plays
their SUM, as Traktor's stem deck does — the mix stream is never decoded,
which also saves a full-length buffer. `PlaybackEngine.load` takes several
buffers: one source + gain each, all started at ONE scheduled context
time (so they stay sample-locked through seeks and loops), mute/solo as
ramped gains, never a restart. `ScratchEngine.loadStems` keeps ONE summed
copy of the audible stems (not four), re-summed in slices on a mute change.
`analyzeStems` returns the overview's three-band columns (of the sum) plus
one amplitude lane per stem, each normalised to its own 99.5th percentile
but never below 5% of the loudest (a silent stem stays silent).
`MainWaveform` draws the lanes in the file's own colours with a mute
button at each lane's left edge (click = mute, Alt/Option-click = solo);
Q W E R mute stems 1-4, Shift+ solos. **Solo is not a mode**: it SETS the
mutes (every other stem muted), so each stem stays freely mutable after
it; soloing the one stem still playing unmutes all. Mutes reset per track. Memory is
the cost: ~140 MB per stem for 6 minutes, i.e. the same four buffers as
the file holds streams, and no more.
- **Prep strip** (DJ deck across the top of the window): `PrepStrip` owns it,
in three rows. **Header**: cover, title/artist · album · genre, a Read-only
badge, the readout well (ELAPSED / REMAIN to tenths, KEY, and `BpmReadout` —
@@ -798,9 +598,8 @@ Two independent apps that talk over HTTP:
loop BEFORE seeking: `PlaybackEngine.seek` honours the loop in force, so
seeking first wraps the playhead back into the old loop.
- **Hotcue edits live on the pad's right-click menu** (type as one-click
choices, a colour swatch grid + Default where `cues.color` is `palette` —
`ContextMenu`'s `swatches` item, Rename…, Delete); there is no standalone
type dropdown or delete button. Rename re-sets the slot with its own start/type/length plus the
choices, Rename…, Delete); there is no standalone type dropdown or delete
button. Rename re-sets the slot with its own start/type/length plus the
new name, since `set_cue` replaces a slot. A non-editable cue gets the
same menu disabled, not no menu.
Prep libs live in `src/lib/`: `playbackEngine.ts` (Web Audio, seamless loops),
@@ -823,12 +622,11 @@ Two independent apps that talk over HTTP:
listening, and shows a "Read-only" badge).
- Capability-gated today: hotcue bank size (`HotcueBar`, the auto-cue guard and
the digit shortcuts all read `cues.hotcue_slots`), the cue-type dropdown
(`cues.types`), the cue colour swatches (`cues.color === 'palette'` +
`cues.palette`; a `free` platform gets no picker yet), the rating scale
(`tracks.rating_max`), the grid Lock button (`grid.lockable`). Per-node playlist flags (`can_rename`, `can_delete`,
(`cues.types`), the rating scale (`tracks.rating_max`), the grid Lock button
(`grid.lockable`). Per-node playlist flags (`can_rename`, `can_delete`,
`can_add_tracks`) gate the sidebar and the context menu's "Add to" — each on its OWN flag,
since a platform may allow renaming but not deleting. Carried but deliberately unused until a second adapter
exists: `slot_labels: 'letter'`, `loops: 'separate_bank'`, and
exists: `slot_labels: 'letter'`, `palette`, `loops: 'separate_bank'`, and
memory-cue *editing* (one-platform features stay preserved-but-uneditable).
- `lib/trackColumns.tsx` — single source of truth for the library table's
columns (defs, default widths/visibility/order, the Columns-menu list, the
@@ -910,34 +708,6 @@ serialization path.** It enforces:
save round-trip; anchor-before-0 moves a whole beat with its companion, a
hotcue clamps and is reported; "add" appends, keeps the original, joins a
playlist, carries pending tag fields; clashes refused with nothing changed.
- `test_engine_manager.py` — the engine manager and process against a LOCAL
Range-aware server and a FAKE engine script (no network, no torch): resume,
restart when Range is ignored, checksum refusal, cancel keeps the `.part`;
install from split parts with byte progress and a probe; a wrong-version
engine or corrupt part leaves nothing installed; side-load and weights
verified; the CUDA offer's driver/capability floors; the process relays
progress, cancels without dying, reports a crash with its reason, keeps the
Mac awake; the routes (install job in bytes, 409 while one runs, remove).
- `test_stems_batch.py` — the Convert to Stems batch through the routes with
the FAKE engine (`stem_test_support.py`, shared with
`test_engine_manager.py`), on temp collections pointed at generated MP3s:
skips with reasons (an existing target is never overwritten); Replace parks,
swaps at the end, leaves the saved file untouched, keeps prep in decoded time
and 409s the blocked routes; Save deletes parked originals and retargets an
export set; Discard and switching library restore; Cancel leaves no file;
one bad track fails alone; destination+add mirrors into a new playlist;
crash recovery restores (or finishes a committed save) and a re-run REUSES
the kept stem files without calling the engine.
- `test_stem_playback.py` — stem playback's backend half on a generated stem
file (fake stems = distinct scalings of the mix): the layout is read from
the FILE (an MP3 whose entry carries `<STEMS>` has none); each served stem
is its own MP4, bit-identical to that stream in place and the RIGHT stem;
out-of-range / non-stem requests 404; the cache reuses, follows an edited
file, evicts LRU but never what it just wrote; the folder origin serves too
and lists the file as a stem track; a stem file ADDED from a folder gets
`<STEMS>` and a `TYPE="STEM"` playlist key, the MP3 beside it neither. On a
Rekordbox copy, an added stem file projects as a stem track (also after a
reopen) and the deck is offered its stems.
- `test_traktor_adapter.py` — the **generic layer**: one parse per open, the
projection refreshing after every command family, cue-type translation,
capabilities, and `set_analysed_grid` vs `replace_grid`. `test_save_fidelity`
@@ -952,24 +722,7 @@ serialization path.** It enforces:
against SQLite). Asserts a no-op save changes zero rows; a one-field edit
changes exactly two — the track and `agentRegistry.localUpdateCount` — with the
counter up by one and the edited row stamped with it; edits are invisible on
disk until save; and playlist create/fill/rename/delete round-trip. And
**removing a track** deletes exactly the rows Rekordbox 7 deletes (measured
2026-10-01 by diffing a removal made in Rekordbox itself: `djmdContent`,
`djmdCue`, `contentCue`, `contentFile`, `djmdMixerParam`, `djmdSongPlaylist`
— DELETED, never `rb_local_deleted`; the playlist row untouched, later
entries renumbered) plus, after the commit, its ANLZ files and their emptied
folder. Artwork is left (unmeasured: `_m`/`_s` sizes are not in
`contentFile`), and a track in a table that was empty when measured (Sampler,
History, Tag List, My Tag, …) is refused with nothing changed. And **adding
tracks** (J) on generated kick-track MP3s: a raising `checkpoint` cancels
before the library is touched; nothing reaches disk before save; afterwards
only INSERTs (plus the counter) into the tables Rekordbox writes for a new
track, the row filled from the file and stamped with the library's device,
one `contentFile` per analysis file + `artwork.jpg` whose Hash is the MD5;
a plain file gets Konduktor's grid ON the kick, a source's grid, hot cue
(pad, colour), loop and memory cue cross as themselves; and removing it
deletes its analysis files. `test_folders.py` drives the same through
`/api/folder/add` on a Rekordbox copy, and a non-addable library 422s.
disk until save; and playlist create/fill/rename/delete round-trip.
- `test_onelibrary_adapter.py` — the third adapter against the same contract.
Unlike the Rekordbox tests it needs **nothing installed and nothing plugged
in**: it runs against `fixtures/onelibrary/`, a real rekordbox 7 export trimmed
@@ -978,42 +731,6 @@ serialization path.** It enforces:
Konduktor wrote. Pins the drive-relative path resolution, the `PCOB`/`PCO2`
merge, and — cross-checked against the same cues in `master.db` — the dense
ANLZ slot numbering, which is the thing most likely to be silently wrong.
Also reads `fixtures/onelibrary/rekordbox-edited/` (a stick after rekordbox
itself edited it: compact cue entries) and pins browsing vs editable mode. It
opens a temp COPY of the fixture — a stray save once rewrote the checked-in one.
- `test_onelibrary_fidelity.py` — the row-level diff for OneLibrary writes, on a
temp copy of the fixture: nothing reaches the drive before Save, a no-op save
changes zero rows, a title edit exactly `content.title` (no counter, as
rekordbox), dates as `YYYY-MM-DD` text, lookups found-or-created with
`nameForSearch` NULL, a new playlist on top with siblings shifted, entries
from 1; and the stick hazards — another app's write refused, an unplugged
drive keeps the edits, stale `-shm` deleted, the backup holds the old rows,
the drive never held open, file tags written (title yes, rating no).
- `test_onelibrary_anlz.py` — cue and grid edits in the ANLZ files. First
against **rekordbox's own edit** of the same thing
(`fixtures/onelibrary-goober/after/`): a recolour's `PCO2` and a grid edit's
blanked `PQT2` and cleared loop beats are rekordbox's bytes exactly, and the
new `PQTZ` keeps the marker where it was (rekordbox's own halving moved its
anchor 6 ms; within 10 ms). Then fidelity on the demo drive: nothing on the
drive before Save, only the touched tags change (in place, order kept), a
moved pad keeps colour and name, memory cues refused, swatches only, a
same-tempo marker collapses (a per-beat grid has no markers), another app's
ANLZ write refused, an `.EXT` with no `PCO2` keeps every pad, a track with no
analysis files refuses.
- `test_onelibrary_pdb.py` — the Device Library rebuild on Goober's own
`export.pdb`: every track row reads (rows end at their last string; stale
heap tails ignored), a no-op rebuild returns None and a no-op save leaves the
file byte-identical (ids are mirrored), an edit changes only the edited
fields, a new playlist and a reorder reach it, every untouched table and
`exportExt.pdb` stay byte-identical, another app's pdb write is refused, and a
stick without one never gets one.
- `test_onelibrary_tracks.py` — adding and removing through `importer.run` on
Goober: placement (in place on the stick, else `Contents/<Artist>/<Album>/`,
Unknown*, FAT-safe names, 48 chars, suffixed on collision), the prep crossing
(pad + colour + name, memory cues, a taken pad -> memory, a detected grid),
the row's shape, art as a/b pairs, the Device Library rows; a cancel
mid-copy, a Discard and a crash leave nothing; removal deletes rows at once
and files only at Save, renumbers playlists and prunes empty folders.
- `test_import.py` — the import feature end to end: a drive's tracks into a temp
copy of the real collection. Asserts the prep survives (hot cues keep their
PAD, memory cues fill spare ones, the flexible grid crosses intact, no
@@ -1052,9 +769,10 @@ serialization path.** It enforces:
projection AND its playlists while its audio file is untouched, removal is
gated on `tracks.removable`, and all three are refused while a batch
analysis runs. `remove_tracks` is the protocol's only DESTROYING verb for
tracks; Traktor and Rekordbox implement it, OneLibrary (read-only) refuses.
The journal records it as `track/remove`, NOT an edit — otherwise history
would read "edited 40 tracks".
tracks; Traktor implements it, Rekordbox and OneLibrary refuse (a Rekordbox
track spans rows in several tables plus ANLZ files, and which Rekordbox
expects deleted together is unmeasured). The journal records it as
`track/remove`, NOT an edit — otherwise history would read "edited 40 tracks".
- `test_folders.py` — the Files trees and adding loose files, through the
routes, on generated FLACs and a temp copy of the collection: a folder lists
only the visible audio DIRECTLY in it; the audio route refuses anything a
@@ -1345,26 +1063,6 @@ that number and nothing else — everything derives from it:
`AUDIO_ID` and `LOUDNESS` are left empty — they are Traktor's own analysis
outputs and cannot be computed; **verified that Traktor loads and plays such
entries** and re-analyses them.
**Rekordbox implements it too** (2026-10-01; gated on `tracks.addable`,
which the folder menu, the folder header and the device Import button read
from the COLLECTION's capabilities). Unlike Traktor it must ANALYSE: a
Rekordbox grid and waveform live in the ANLZ files, without which Rekordbox
shows neither grid nor cues. So `add_tracks` decodes each file once
(`waveform.decode` → `analyse_samples` + `grid_detect`), in a first phase
that may be cancelled through `checkpoint` before the library is touched;
a file with no grid of its own gets Konduktor's (decided: arrive ready to
prep). Then `RekordboxStore.add_track` writes the row the way Rekordbox's
own add was MEASURED to (file facts, `DateCreated` from the file's birth
time, this library's device) and the grid/cues replay through
`replace_grid`/`set_cue`/`add_memory_cue` — memory cues and colours cross
as themselves, a hot cue with no free pad becomes a memory cue. Its ANLZ
files and artwork (`NewTrack.art`, else the file's embedded cover) are
held until save and written BEFORE the grids and commit, then
`contentFile` rows hash what was written (`_m`/`_s` unlisted, as
Rekordbox does); a failed save removes them. Key, mixer gain and phrases
are Rekordbox's own analysis and are not written. The row and file
builders live in `adapters/rekordbox/new_content.py`, shared with the
Rekordbox Library exporter.
- **`jobs.py` + `importer.py`** — the app's first long-running operation.
Thread per job, polling, cooperative cancel; deliberately not asyncio or SSE.
**Ordering is the safety property**: audio copies first and the library is
@@ -1381,17 +1079,15 @@ that number and nothing else — everything derives from it:
library. Lossiness follows the settled rule: memory cues become hot cues in
spare pads (earliest first), cue colour is dropped (Traktor derives it from
type).
- ✅ OneLibrary adapter — **reading and editing done**, at parity with the
Rekordbox adapter (2026-10-01, [decisions](.claude/discussions/discuss-onelibrary-editing-2026-10-01.md)).
A OneLibrary USB drive opens, projects, browses and searches: tracks,
playlists, hot cues, memory cues, loops and flexible beatgrids. Done: track
metadata (+ file tags), playlists, hot cues and the beatgrid (in the ANLZ
files, each rule matching rekordbox's measured edit), the `export.pdb` rebuild
on save, adding/removing tracks (the library places the audio), Save via a
working copy, and "Open for editing…" on a Devices row — all verified in
rekordbox 7. Same gaps as Rekordbox: cover-art writing, memory-cue editing,
stem conversion. All format research — including the schema, which has no
public spec — is in [.claude/handoffs/onelibrary-adapter.md](.claude/handoffs/onelibrary-adapter.md).
- 🟡 OneLibrary adapter — **read-only, done**. A OneLibrary USB drive opens,
projects, browses and searches: tracks, playlists, hot cues, memory cues, loops
and flexible beatgrids. Built as the readable SOURCE half of a future
**"import a OneLibrary stick into a Traktor library"** feature, which is the
motivating use case. Everything unknown about the format is on the write side
(the `cue` table's MPEG seek columns, the waveform tags a CDJ draws from, the
update counters), so read-only is a deliberate boundary rather than an
unfinished one. All research — including the schema, which has no public spec —
is in [.claude/handoffs/onelibrary-adapter.md](.claude/handoffs/onelibrary-adapter.md).
- 🟡 **Export/conversion** — **in progress.** Both the design AND the user flow
are settled; see
[the export discussion doc](.claude/discussions/discuss-export-implementation-2026-09-22.md),
@@ -1523,8 +1219,8 @@ that number and nothing else — everything derives from it:
rekordbox draw its own defaults (green/orange). **rekordbox draws a hot cue
from its palette CODE** (`PCP2` byte 44, before the RGB; `djmdCue.ColorTableIndex`
in master.db), not the RGB — `adapters/rekordbox/palette.py` holds the 16-swatch
table MEASURED from a rekordbox 7 export (the teal-green, 0x13 #00FF30, measured
later from a rekordbox-edited stick). Type colours map by intent (cue -> light blue 0x05, loop -> green
table MEASURED from a rekordbox 7 export (one swatch, ~0x12 teal-green, still
unmeasured). Type colours map by intent (cue -> light blue 0x05, loop -> green
0x16), anything else to the nearest hue; the palette has NO white, so a grid
companion is code 0 + RGB white (what rekordbox draws for it: unverified). The
**Artwork** (`adapters/rekordbox/artwork.py`, Pillow), measured on a rekordbox 7
@@ -1,32 +0,0 @@
# Goober: a rekordbox-written stick, before and after rekordbox edited it
The stick Ben keeps for measuring the Pioneer formats, as rekordbox 7 left it:
11 tracks, 2 playlists, **both** libraries (`exportLibrary.db` and the legacy
`export.pdb` + `exportExt.pdb`). `test_onelibrary_anlz.py`,
`test_onelibrary_pdb.py` and `test_onelibrary_tracks.py` run against copies of it.
## What is here
- `PIONEER/rekordbox/` holds the three databases, **untouched**: bytes rekordbox
wrote (snapshot `s0`, 2026-10-01).
- `PIONEER/USBANLZ/` holds every track's `.DAT` and `.EXT`, trimmed by dropping
whole tags: only `PPTH`, `PQTZ`, `PCOB`, `PCO2` and `PQT2` are kept, byte for
byte. The waveforms are gone, and so are the `.2EX` files.
- `after/` holds the same tags after **rekordbox 7 itself** edited the stick
(snapshot `s1`, one edit per track):
- `black-bloc-recoloured.EXT`: pad C recoloured to `0x2D` `#FF0045`.
- `wtf-87bpm.DAT` / `.EXT`: "Result – WTF" changed from 174 to 87 BPM.
- `demo2-pad-e-added.EXT`: a hot cue added on pad E of "Demo Track 2".
There is no audio. The adapter resolves paths and never needs the files, so the
time base falls back to rekordbox's MP3 default, the same offset for reading and
writing.
## Why
Konduktor's edits are pinned against what rekordbox wrote for the SAME edit, not
against Konduktor's own reader. A recolour and a grid edit must reproduce
rekordbox's bytes exactly (colour bytes, the blanked `PQT2`, loop beats cleared).
The pdb tests prove that an in-place edit of a rekordbox-written `export.pdb`
leaves everything else as rekordbox wrote it. The full diff of the measurement is
in `.claude/discussions/discuss-onelibrary-editing-2026-10-01.md`.
-13
View File
@@ -56,16 +56,3 @@ 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`.
-6
View File
@@ -48,12 +48,6 @@ datas += [
("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"),
]
a = Analysis(
["sidecar.py"],
+53 -256
View File
@@ -5,30 +5,28 @@ 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.
**Read-only.** Every command is refused and `capabilities.writable` is False with
cause `platform_incomplete`, so the UI never offers an edit in the first place;
the raises here are the backstop, not the mechanism.
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.
That scope is deliberate rather than provisional. The purpose of this adapter is
to make a OneLibrary drive a readable SOURCE — the half an import into another
library needs — and every genuinely unknown part of the format sits on the write
side: the `cue` table's eight MPEG frame/offset columns, whose values a player
needs to seek accurately in a VBR file; the waveform tags a CDJ draws from; and
the update counters a drive uses to reconcile edits made on hardware. None of
those has to be guessed at to read a drive, and none of them should be guessed at
at all.
"""
from __future__ import annotations
from pathlib import Path
from ...core.adapter import InvalidCommand, Unsupported
from ...core.adapter import Unsupported
from ...core.capabilities import Capabilities
from ...core.model import GridMarker, HotcueChip, PlaylistNode, Track, TrackCues
from ...core.model import 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
@@ -44,28 +42,23 @@ ATTRIBUTE_SMART = 4
class OneLibraryAdapter:
platform = "onelibrary"
def __init__(self, path: Path, *, read_only: bool = False):
def __init__(self, path: Path):
self.path = Path(path)
self.read_only = read_only
self._store = OneLibraryStore(self.path, read_only=read_only)
self._store = OneLibraryStore(self.path)
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)
self._index.rebuild(
[
projection.to_track(row, self._drive_path(row))
for row in self._store.iter_content()
]
)
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))
resolved = self._store.layout.resolve(getattr(row, "path", None))
return str(resolved) if resolved is not None else None
def close(self) -> None:
@@ -77,27 +70,14 @@ class OneLibraryAdapter:
self._store.close()
def reload(self) -> None:
"""Re-read the drive, DISCARDING unsaved edits."""
self._store.discard()
self._store._load()
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 ------------------------------------------------------------
@@ -164,9 +144,7 @@ class OneLibraryAdapter:
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
rows = self._store.playlists()
nodes: dict[str, PlaylistNode] = {}
parents: dict[str, str] = {}
@@ -186,12 +164,12 @@ class OneLibraryAdapter:
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
# Read-only: every per-node 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_add_tracks=False,
can_reorder=False,
can_rename=False,
can_delete=False,
can_contain_children=kind == "folder",
)
parent = str(getattr(r, "playlist_id_parent", 0) or 0)
@@ -258,139 +236,32 @@ class OneLibraryAdapter:
# ---- save -------------------------------------------------------------
@property
def dirty(self) -> bool:
return self._store.dirty
return False
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
raise Unsupported(self._readonly_reason("Saving"))
def snapshot(self) -> bytes:
raise Unsupported("OneLibrary drives are not versioned by Konduktor")
# ---- commands -----------------------------------------------------------
# ---- commands: all refused -------------------------------------------
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, waveform
from ...core.export import ExportTrack
from ..rekordbox import artwork, timebase
from .export import OneLibraryExporter
self._require_writable("Adding tracks")
exporter = OneLibraryExporter()
prepared = []
total = len(items)
for n, item in enumerate(items, start=1):
audio = Path(item.audio_path)
if checkpoint is not None:
checkpoint(f"Analysing {item.track.title or audio.name} ({n}/{total})", step=n, of=total)
if not audio.is_file():
raise InvalidCommand(f"No audio file at {audio}")
try:
rel = self._store.drive_relative(self._store.final_of(audio))
except ValueError:
raise InvalidCommand(f"{audio} is not on this drive") from None
samples = waveform.decode(audio)
measured = waveform.analyse_samples(samples, lead=timebase.offset(audio))
markers = list(item.cues.grid_markers) if item.cues else []
if not markers and samples is not None:
try:
found = grid_detect.detect_grid(str(audio), y=samples, sr=waveform.SR)
markers = [GridMarker(start=found.anchor, bpm=found.bpm)]
except ValueError:
pass # no pulse to fit (a one-shot, silence): no grid
hot, memory, taken = [], [], set()
for cue in sorted((item.cues.cues if item.cues else []), key=lambda c: c.start):
if (cue.role == "hotcue" and cue.slot is not None
and 0 <= cue.slot < caps.HOTCUE_SLOTS and cue.slot not in taken):
hot.append(cue)
taken.add(cue.slot)
else:
memory.append(cue.model_copy(update={"role": "memory", "slot": None}))
export_track = ExportTrack(track=item.track, destination=audio,
cues=TrackCues(grid_markers=markers, cues=memory))
# Decoded once above; the writer must not decode it again.
export_track.waveform = lambda *, lead=0.0, m=measured: m
art = item.art or audio_tags.read_cover(audio)
jpegs = artwork.pioneer_jpegs(art[0]) if art else None
length = item.track.length or (int(measured.duration) if measured else None)
prepared.append((item, audio, rel, exporter.anlz_files(export_track, rel), jpegs,
markers, hot, length))
added: list[str] = []
for item, audio, rel, anlz, jpegs, markers, hot, length in prepared:
track_id = self._store.add_track(
audio, item.track, rel=rel, anlz_rel=self._store._anlz_rel(rel), anlz=anlz,
jpegs=jpegs, bpm=markers[0].bpm if markers else item.track.bpm, length=length)
for cue in hot:
self._store.set_cue(track_id, slot=cue.slot, start_sec=cue.start,
cue_type="loop" if cue.length else "cue",
length_sec=cue.length or 0.0, name=cue.name)
code, _rgb = palette.code_for(cue.color)
if cue.color and code:
self._store.set_cue_color(track_id, cue.slot, code)
added.append(track_id)
self._rebuild()
return added
def add_tracks(self, items: list) -> list[str]:
self._refuse("Adding tracks")
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
self._refuse("Removing tracks")
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)
self._refuse("Editing track metadata")
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
self._refuse("Editing cover art")
@@ -399,126 +270,52 @@ class OneLibraryAdapter:
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)
self._refuse("Creating playlists")
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)
self._refuse("Creating playlist folders")
def rename_playlist(self, node_id: str, name: str) -> None:
self._require_writable("Renaming playlists")
self._store.rename_playlist(node_id, name)
self._refuse("Renaming playlists")
def delete_playlist(self, node_id: str) -> None:
self._require_writable("Deleting playlists")
self._store.delete_playlist(node_id)
self._refuse("Deleting playlists")
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)
self._refuse("Editing playlists")
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(self, track_id: str, **kw) -> TrackCues:
self._refuse("Editing cues")
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)
self._refuse("Editing cues")
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)
self._refuse("Deleting cues")
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]
self._refuse("Placing cues")
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)
self._refuse("Editing the beatgrid")
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)
self._refuse("Editing the beatgrid")
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)
self._refuse("Editing the beatgrid")
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)
self._refuse("Editing the beatgrid")
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)
self._refuse("Editing the beatgrid")
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)
self._refuse("Editing the beatgrid")
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)
self._refuse("Deleting the beatgrid")
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues:
raise Unsupported("OneLibrary has no beatgrid lock")
@@ -28,8 +28,7 @@ __all__ = ["BPM_EPSILON", "markers_from_beats", "beats_from_pqtz", "markers_from
def beats_from_pqtz(anlz) -> tuple[list[float], list[float], list[int]] | None:
"""Per-beat ``(times_sec, bpms, beat_in_bar)`` from a parsed ANLZ file's `PQTZ` tag
(an `anlz_file.AnlzFile`).
"""Per-beat ``(times_sec, bpms, beat_in_bar)`` from a parsed ANLZ file's `PQTZ` tag.
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
@@ -40,7 +39,7 @@ def beats_from_pqtz(anlz) -> tuple[list[float], list[float], list[int]] | None:
for tag in getattr(anlz, "tags", []):
if tag.type != "PQTZ":
continue
entries = tag.entries
entries = getattr(getattr(tag.struct, "content", None), "entries", None)
if not entries:
return None
times: list[float] = []
@@ -1,27 +1,25 @@
"""What a OneLibrary drive can persist.
"""What a OneLibrary drive can persist: nothing, for now.
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.
`writable` is False with cause `platform_incomplete`. That is the distinction the
capability system exists to draw — this is a ROADMAP GAP, not a refusal. A
cloud-synced Rekordbox library is refused permanently to protect the user's other
machines; a OneLibrary drive simply has no write path yet, and the UI must word
those two very differently.
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.
The per-feature flags below still report what the FORMAT supports rather than
being blanked to false, because that is what `writable=False` is for: the UI can
show a drive's cues and grid honestly, and say once, in one place, that the whole
library is read-only. Blanking them would claim OneLibrary has no hot cues.
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.)
* cue colour is **free RGB**, not a palette index. The `PCO2` tag stores three
bytes per cue, and the reference drive held #4D00FF, #33FF00, #00C4FF and
#FF8C00. This differs from the desktop Rekordbox adapter, which reports
"palette" because `djmdCue` stores an index into a built-in table — the same
vendor, two genuinely different representations.
* 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.
@@ -36,58 +34,44 @@ from ...core.capabilities import (
SaveCapabilities,
TrackCapabilities,
)
from ..rekordbox import palette
from ..rekordbox.cue_types import WRITABLE_CUE_TYPES
# Pads A-H. Unlike `djmdCue.Kind`, the ANLZ slot number is a dense 1-based index,
# so the bank really is 1..8 (see `cues.py`).
HOTCUE_SLOTS = 8
def capabilities_for(
device_name: str | None = None,
version: str | None = None,
*,
read_only: bool = False,
editable_fields: list[str] | None = None,
managed_by_export: bool = False,
) -> Capabilities:
def capabilities_for(device_name: str | None = None, version: str | None = None) -> Capabilities:
return Capabilities(
platform="onelibrary",
version=version,
writable=not read_only,
readonly_cause="browsing" if read_only else None,
# A roadmap gap, not a protective refusal — the UI words the two
# differently, which is the whole reason `readonly_cause` exists.
writable=False,
readonly_cause="platform_incomplete",
cues=CueCapabilities(
editable=True,
editable=False,
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).
# OneLibrary carries memory cues, as Rekordbox does. They are
# projected and preserved; nothing here is editable anyway.
memory_cues=True,
max_memory_cues=None,
types=WRITABLE_CUE_TYPES,
color="palette",
palette=[palette.hex_for(code) for code in palette.SWATCHES],
types=["cue", "loop"],
color="free", # PCO2 stores RGB per cue, not a palette index
palette=[],
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),
# The grid is the ANLZ `PQTZ` tag, per beat, and multi-tempo grids do
# survive an export — so the format is flexible even though Konduktor
# does not write it here.
grid=GridCapabilities(editable=False, flexible=True, lockable=False),
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,
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`.
editable_fields=[],
media_kinds=["audio"],
# `artwork` gates EDITING, and a drive is read-only here. Reading
# works: `store.cover_art` follows `content.image_id` -> `image.path`.
artwork=False,
artwork_note=None,
),
@@ -96,18 +80,13 @@ def capabilities_for(
# A drive carries no smart playlists: rekordbox resolves them to
# static lists on export, because a CDJ cannot evaluate rules.
smart="none",
reorder=True,
reorder=False,
),
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.
app_name="OneLibrary",
library_label=device_name or "exportLibrary.db",
# Nothing is written, so nothing can be overwritten by another app.
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.
+23 -36
View File
@@ -37,7 +37,6 @@ from __future__ import annotations
import logging
from ...core.model import CuePoint
from ..rekordbox import palette
log = logging.getLogger(__name__)
@@ -48,13 +47,14 @@ 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.
# PCO2/PCOB entry kinds. The value is the same in both tags; PCOB exposes it as
# a construct enum and PCO2 as a plain int, so both are normalised to an int.
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."""
"""PCOB gives an enum, PCO2 an int — one number out of either."""
try:
return int(value)
except (TypeError, ValueError):
@@ -68,17 +68,8 @@ def _color(entry) -> str | None:
real black in principle, but rekordbox uses it as "unset" and shows such a
cue in the default colour, so it is reported as no colour rather than as
black. Memory cues in the reference export are exactly this case.
rekordbox DRAWS a cue from its palette CODE (`rekordbox.palette`), so a known
code is reported as that swatch; a cue with code 0 and an RGB (older
exports, the reference fixture) is reported by its RGB.
"""
swatch = palette.hex_for(getattr(entry, "color_code", None))
if swatch is not None:
return swatch
try:
# None on an entry too short to carry a colour: every PCPT, and the
# compact 44-byte PCP2 rekordbox writes for a memory cue it added.
r, g, b = int(entry.color_red), int(entry.color_green), int(entry.color_blue)
except (AttributeError, TypeError, ValueError):
return None
@@ -87,7 +78,7 @@ def _color(entry) -> str | None:
return f"#{r:02X}{g:02X}{b:02X}"
def _to_cue(entry, *, with_color: bool, editable: bool = False) -> CuePoint | None:
def _to_cue(entry, *, with_color: bool) -> CuePoint | None:
"""One ANLZ cue entry as a generic `CuePoint`, or None if unreadable."""
try:
hot_cue = int(entry.hot_cue)
@@ -120,11 +111,11 @@ def _to_cue(entry, *, with_color: bool, editable: bool = False) -> CuePoint | No
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",
# A OneLibrary drive is read-only in Konduktor, so no cue accepts a
# command. `capabilities.writable` is what the UI actually gates on;
# this keeps the per-cue answer consistent with it.
editable=False,
readonly_reason="platform_managed",
grid_marker=None,
)
@@ -139,14 +130,15 @@ def _entries(anlz, tag_type: str) -> list:
"""
out: list = []
for tag in getattr(anlz, "tags", []):
if tag.type == tag_type:
out.extend(tag.entries)
if tag.type != tag_type:
continue
content = getattr(tag.struct, "content", None)
out.extend(getattr(content, "entries", None) or [])
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).
def cues_from_anlz(dat, ext) -> list[CuePoint]:
"""The track's complete cue list, from its parsed `.DAT` and `.EXT`.
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.
@@ -161,14 +153,14 @@ def cues_from_anlz(dat, ext, *, editable: bool = False) -> list[CuePoint]:
for f in files:
pco2.extend(_entries(f, "PCO2"))
if pco2:
cues = [c for e in pco2 if (c := _to_cue(e, with_color=True, editable=editable)) is not None]
cues = [c for e in pco2 if (c := _to_cue(e, with_color=True)) 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]
cues = [c for e in pcob if (c := _to_cue(e, with_color=False)) is not None]
return _dedupe(cues)
@@ -176,23 +168,18 @@ def cues_from_anlz(dat, ext, *, editable: bool = False) -> list[CuePoint]:
def _dedupe(cues: list[CuePoint]) -> list[CuePoint]:
"""Collapse the same cue appearing in more than one tag or file.
Identity is (role, slot, start, 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.
Identity is (role, slot, start) rather than the whole cue: the same pad can
be described by both `PCOB` and `PCO2`, and by both files, and those copies
agree on position while differing in how much detail they carry. The first
one wins, which — given PCO2 is read first — is the richest.
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()
seen: set[tuple[str, int | None, int]] = set()
out: list[CuePoint] = []
for c in cues:
key = (c.role, c.slot, round(c.start * 1000), c.type, round(c.length * 1000))
key = (c.role, c.slot, round(c.start * 1000))
if key in seen:
continue
seen.add(key)
@@ -1,208 +0,0 @@
"""Keeping a stick's legacy Device Library (`export.pdb`) in step with its OneLibrary.
Most rekordbox sticks carry BOTH: `exportLibrary.db` (OneLibrary, newer players)
and `export.pdb` (the Device Library, older players and rekordbox's own "Device
Library" view). Cues and the grid live in the analysis files both share, so they
follow an edit by themselves; titles and playlists live in each database
separately. **rekordbox itself lets them drift**: measured on Goober
(2026-10-01), its edits updated the pdb's track metadata but not a new playlist
or a reorder. Konduktor rebuilds the pdb at Save instead (decision 2 of the
editing discussion), so a stick never shows different playlists depending on
which player reads it.
**Ids are mirrored, not assigned.** rekordbox exports both libraries from the
same ids — pdb track id = `content_id`, the artist/album/genre/label/key ids, the
playlist ids, playlist `sort` = `sequenceNo`, entries `(sequenceNo, content_id,
playlist_id)`, artwork id = `image_id` — all checked on Goober. So the OneLibrary
database IS the answer for every row the pdb shares with it.
**An edit, not a regeneration.** The stick's own `export.pdb` is edited in place
(`pdb.PdbEditor`): only the tracks, the lookup tables (artist, album, genre,
label, key), artwork and the playlist tree and entries are candidates, a table is rewritten only if one of its rows changed,
and an unchanged row keeps rekordbox's bytes. A changed TRACK row is the old row
with the edited fields overwritten, so everything the pdb holds that OneLibrary
does not — the phrase-analysis strings, the `masterDbId` halves, play counts,
dates — survives. History, colours, menus and `exportExt.pdb` are never touched.
"""
from __future__ import annotations
import re
import struct
from pathlib import Path
from ..rekordbox import pdb
#: Tables this rebuild owns. Everything else in the file is left as it is.
_OWNED = (pdb.TRACKS, pdb.ARTISTS, pdb.ALBUMS, pdb.GENRES, pdb.LABELS, pdb.KEYS,
pdb.ARTWORK, pdb.PLAYLIST_TREE, pdb.PLAYLIST_ENTRIES)
def _lookup_name(table: int, row: bytes) -> str:
if table == pdb.ARTISTS:
sub, _shift, _rid, _b, ofs = struct.unpack_from("<HHIBB", row, 0)
if sub == 0x64:
ofs = struct.unpack_from("<H", row, 10)[0]
return pdb.read_dsql(row, ofs)
if table == pdb.ALBUMS:
sub, _shift, _u, _artist, _rid, _u3, _b, ofs = struct.unpack_from("<HHIIIIBB", row, 0)
return pdb.read_dsql(row, ofs)
if table == pdb.KEYS:
return pdb.read_dsql(row, 8)
return pdb.read_dsql(row, 4)
def _pdb_art_path(path: str | None) -> str:
"""OneLibrary's `image.path` names the `b<n>` file; export.pdb's artwork row
the byte-identical `a<n>` beside it (as on Goober, and as rekordbox writes)."""
return re.sub(r"/b(\d+)(\.jpg)$", r"/a\1\2", path or "")
def _tree_value(row: bytes) -> tuple:
parent, _u, sort, rid, folder = struct.unpack_from("<5I", row, 0)
return parent, sort, rid, bool(folder), pdb.read_dsql(row, 20)
def _merge(old: list[bytes], new: dict, table: int, same) -> list[bytes] | None:
"""The table's rows: old ORDER kept, an unchanged row's old BYTES kept, new
rows appended by id. None when nothing changed (the table is not rewritten).
`new` maps row id -> (value, encode()); `same(old_row, value)` says whether
an old row already says `value`.
"""
out, changed, seen = [], False, set()
for row in old:
rid = pdb.row_id(table, row)
if rid not in new:
changed = True # removed
continue
seen.add(rid)
value, encode = new[rid]
if same(row, value):
out.append(row)
else:
out.append(encode())
changed = True
for rid in sorted((r for r in new if r not in seen), key=str):
out.append(new[rid][1]())
changed = True
return out if changed else None
def rebuild(existing: bytes, session) -> bytes | None:
"""`export.pdb` edited to match the OneLibrary database open in `session`
(the working copy, edits committed); None if it already matches."""
from sqlalchemy import text
tables: dict[int, list[bytes]] = {}
# ---- lookups ----------------------------------------------------------------
for table, sql, build in (
(pdb.ARTISTS, "SELECT artist_id, name FROM artist", pdb.artist_row),
# rekordbox's export leaves an album's artist 0 (see `pdb.album_row`).
(pdb.ALBUMS, "SELECT album_id, name FROM album", pdb.album_row),
(pdb.GENRES, "SELECT genre_id, name FROM genre", pdb.id_string_row),
(pdb.LABELS, "SELECT label_id, name FROM label", pdb.id_string_row),
(pdb.KEYS, "SELECT key_id, name FROM key", pdb.key_row),
):
want = {int(i): (name or "", (lambda i=i, n=name, b=build: b(int(i), n or "")))
for i, name in session.execute(text(sql))}
merged = _merge(pdb.table_rows(existing, table), want, table,
lambda row, value, t=table: _lookup_name(t, row) == value)
if merged is not None:
tables[table] = merged
want = {int(i): (_pdb_art_path(path), (lambda i=i, p=path: pdb.id_string_row(int(i), _pdb_art_path(p))))
for i, path in session.execute(text("SELECT image_id, path FROM image"))}
merged = _merge(pdb.table_rows(existing, pdb.ARTWORK), want, pdb.ARTWORK,
lambda row, value: pdb.read_dsql(row, 4) == value)
if merged is not None:
tables[pdb.ARTWORK] = merged
# ---- tracks -----------------------------------------------------------------
old_tracks = {pdb.row_id(pdb.TRACKS, r): r for r in pdb.table_rows(existing, pdb.TRACKS)}
want = {}
for (cid, title, artist, remixer, album, genre, label, rating, bpm, year, released,
comment, *fresh) in session.execute(text(
"SELECT content_id, title, artist_id_artist, artist_id_remixer, album_id, genre_id, "
"label_id, rating, bpmx100, releaseYear, releaseDate, djComment, "
"path, fileName, fileSize, fileType, bitrate, bitDepth, samplingRate, length, "
"analysisDataFilePath, dateAdded, key_id, image_id FROM content")):
cid = int(cid)
if cid in old_tracks:
fields, strings = pdb.track_fields(old_tracks[cid])
else:
fields, strings = _fresh_track(cid, *fresh)
fields = {**fields, "artist_id": artist or 0, "remixer_id": remixer or 0,
"album_id": album or 0, "genre_id": genre or 0, "label_id": label or 0,
"rating": max(0, min(5, int(rating or 0))), "tempo": int(bpm or 0),
"year": int(year or 0)}
strings = {**strings, "title": title or "", "comment": comment or "",
"release_date": released or ""}
want[cid] = ((fields, strings),
(lambda f=fields, s=strings: pdb.track_row(f, s)))
merged = _merge(list(old_tracks.values()), want, pdb.TRACKS,
lambda row, value: _same_track(pdb.track_fields(row), value))
if merged is not None:
tables[pdb.TRACKS] = merged
# ---- playlists ----------------------------------------------------------------
want = {int(pid): ((int(parent or 0), int(seq or 0), int(pid), int(attr or 0) == 1, name or ""),
(lambda p=pid, par=parent, s=seq, n=name, a=attr:
pdb.playlist_tree_row(int(p), int(par or 0), int(s or 0), n or "",
folder=int(a or 0) == 1)))
for pid, parent, seq, name, attr in session.execute(text(
"SELECT playlist_id, playlist_id_parent, sequenceNo, name, attribute FROM playlist"))}
merged = _merge(pdb.table_rows(existing, pdb.PLAYLIST_TREE), want, pdb.PLAYLIST_TREE,
lambda row, value: _tree_value(row) == value)
if merged is not None:
tables[pdb.PLAYLIST_TREE] = merged
want = {}
for pid, cid, seq in session.execute(text(
"SELECT playlist_id, content_id, sequenceNo FROM playlist_content "
"ORDER BY playlist_id, sequenceNo")):
key = (int(seq), int(cid), int(pid))
want[key] = (key, (lambda k=key: pdb.playlist_entry_row(*k)))
merged = _merge(pdb.table_rows(existing, pdb.PLAYLIST_ENTRIES), want, pdb.PLAYLIST_ENTRIES,
lambda row, value: True)
if merged is not None:
tables[pdb.PLAYLIST_ENTRIES] = merged
if not tables:
return None
editor = pdb.PdbEditor(existing)
for table in _OWNED:
if table in tables:
editor.refill(table, tables[table])
return editor.render()
def _same_track(old: tuple[dict, dict], new: tuple[dict, dict]) -> bool:
"""Equal in every field that means something: `index_shift` is the row's slot
in its page, re-stamped whenever a page is written."""
(of, os_), (nf, ns) = old, new
return ({k: v for k, v in of.items() if k != "index_shift"}
== {k: v for k, v in nf.items() if k != "index_shift"} and os_ == ns)
def _fresh_track(cid: int, path, file_name, file_size, file_type, bitrate, bit_depth,
sample_rate, length, analysis, date_added, key_id, image_id) -> tuple[dict, dict]:
"""A track the pdb has never listed (one added to the stick by Konduktor), in
the shape `device_export` writes one — the values a rekordbox device export
was measured to carry (see that module)."""
from ..rekordbox.device_export import ANALYSED, BITMASK
added = str(date_added or "")[:10]
fields = {
"subtype": 0x24, "bitmask": BITMASK, "sample_rate": int(sample_rate or 0),
"file_size": int(file_size or 0), "u2": cid + 0x600, "artwork_id": int(image_id or 0),
"key_id": int(key_id or 0), "bitrate": int(bitrate or 0), "id": cid,
"sample_depth": int(bit_depth or 0), "duration": min(int(length or 0), 0xFFFF),
"u5": ANALYSED, "u6": int(file_type or 0), "u7": 3,
}
strings = {
"kuvo_public": "ON", "autoload_hotcues": "ON", "date_added": added,
"analyze_path": analysis or "", "analyze_date": added,
"filename": file_name or Path(str(path or "")).name, "file_path": path or "",
}
return fields, strings
@@ -73,8 +73,8 @@ class OneLibraryDriver:
except Exception: # noqa: BLE001
pass
def open(self, path: Path, *, read_only: bool = False) -> OneLibraryAdapter:
return OneLibraryAdapter(path, read_only=read_only)
def open(self, path: Path) -> OneLibraryAdapter:
return OneLibraryAdapter(path)
def detect(self) -> list[dict]:
return discovery.detect_libraries()
+10 -28
View File
@@ -265,21 +265,21 @@ class OneLibraryExporter:
n = counter["next"]
folder = root / "PIONEER" / "Artwork" / "00001"
folder.mkdir(parents=True, exist_ok=True)
small, medium = jpegs
files = []
for rel, data in art_files(n, jpegs):
path = root / rel.lstrip("/")
path.write_bytes(data)
files.append(path)
for letter in ("a", "b"):
for suffix, data in (("", small), ("_m", medium)):
path = folder / f"{letter}{n}{suffix}.jpg"
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`).
def _write_anlz(self, item: ExportTrack, rel: str, dat: Path) -> list[Path]:
"""The `.DAT`, `.EXT` and `.2EX`, as rekordbox 7 writes them.
All three, and every cue list, even for a track with no cues: rekordbox
never produces a track without them, and `PCO2` — the complete list,
@@ -318,18 +318,9 @@ class OneLibraryExporter:
tags += previews
tags += W.cue_tags(cues, extended=False)
ext = [W.path_tag(rel), *ext_waves[:1], *W.cue_tags(cues, extended=True), *ext_waves[1:]]
files = [(".DAT", W.anlz_bytes(tags)), (".EXT", W.anlz_bytes(ext))]
written = [W.write_anlz(dat, tags), W.write_anlz(dat.with_suffix(".EXT"), 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)
written.append(W.write_anlz(dat.with_suffix(".2EX"), [W.path_tag(rel), *two_ex]))
return written
@staticmethod
@@ -433,15 +424,6 @@ _FILE_TYPES = {".mp3": 1, ".m4a": 4, ".mp4": 4, ".aac": 4, ".flac": 5, ".wav": 1
".aif": 12, ".aiff": 12}
def art_files(n: int, jpegs: tuple[bytes, bytes]) -> list[tuple[str, bytes]]:
"""Image `n`'s four files as `(drive-relative path, bytes)`: `a<n>`/`b<n>`
and their `_m`, byte-identical pairs, in `Artwork/00001/` (see `_write_art`).
`image.path` names the `b` file; `export.pdb`'s artwork table the `a` one."""
small, medium = jpegs
return [(f"/PIONEER/Artwork/00001/{letter}{n}{suffix}.jpg", data)
for letter in ("a", "b") for suffix, data in (("", small), ("_m", medium))]
def _file_type(path: Path) -> int:
return _FILE_TYPES.get(path.suffix.lower(), 1)
@@ -54,7 +54,7 @@ def _bpm(row) -> float | None:
return round(int(raw) / 100.0, 2)
def to_track(row, drive_path: str | None = None, *, stem: bool = False) -> Track:
def to_track(row, drive_path: str | None = None) -> Track:
"""Project one ``Content`` row.
**The three count fields are approximations here**, and deliberately so. Cues
@@ -104,8 +104,7 @@ def to_track(row, drive_path: str | None = None, *, stem: bool = False) -> Track
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",
media_kind="audio",
)
File diff suppressed because it is too large. Load diff
+15 -105
View File
@@ -21,13 +21,13 @@ from __future__ import annotations
from pathlib import Path
from ...core.adapter import InvalidCommand, Unsupported
from ...core.adapter import Unsupported
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 . import projection
from .store import RekordboxStore
@@ -46,8 +46,7 @@ class RekordboxAdapter:
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)))
projection.to_track(row, kinds.get(str(row.ID), ()))
for row in self._store.iter_content()
]
)
@@ -69,8 +68,7 @@ class RekordboxAdapter:
"""
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))))
self._index.replace(projection.to_track(row, kinds.get(str(row.ID), ())))
def close(self) -> None:
"""Release the database connection.
@@ -204,8 +202,6 @@ class RekordboxAdapter:
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
@@ -303,18 +299,6 @@ class RekordboxAdapter:
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)
@@ -416,93 +400,19 @@ class RekordboxAdapter:
if self._cloud_synced:
raise Unsupported(self._readonly_reason(what))
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, grid_detect, waveform
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))
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
art = item.art or audio_tags.read_cover(audio)
prepared.append((item, audio, measured, markers, art[0] if art else None))
added: list[str] = []
for item, audio, measured, markers, art in prepared:
track_id = self._store.add_track(
audio, item.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 add_tracks(self, items: list) -> list[str]:
# Not a refusal in principle — Rekordbox could receive imported
# tracks — but adding one means a djmdContent row, its lookup-table
# foreign keys, a USN, and an ANLZ file built from scratch, which
# is unexplored (see the export handoff). Traktor is the only
# import target for now.
self._refuse("Adding tracks")
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
# Same shape as adding: a track is a djmdContent row plus its cues,
# playlist rows, contentCue/contentFile mirrors and ANLZ files, and
# which of those Rekordbox expects to be deleted together is unmeasured.
self._refuse("Removing tracks")
def apply_stem_swaps(self, swaps, *, add_to_playlist=None):
# Rekordbox does not play native-instruments stem files as stems.
@@ -1,291 +0,0 @@
"""Reading an ANLZ analysis file at the TAG level, by hand.
The writer half is `anlz_writer`; this is its reader. Like the writer it lives
here because the format is Pioneer's, not one product's.
**Why not `pyrekordbox`'s parser.** It decodes a cue entry with a FIXED layout,
and rekordbox does not write one. An exported entry is 88 bytes, but when
rekordbox 7 EDITS a stick it writes compact ones (measured on Goober,
2026-10-01): a hot cue added in rekordbox was a 48-byte `PCP2` (colour, no
padding), and a memory cue a 44-byte one (no colour bytes at all). pyrekordbox
raises `PaddingError` on the 44-byte form, the whole `.EXT` fails to parse, and
a reader that falls back to the `.DAT` silently loses pads D-H and every colour.
So every entry here is read at its own `len_entry`, and a field the entry is too
short to hold is simply absent.
A file is also split into its RAW tags, kept byte for byte. Editing a stick
replaces one or two tags of a file rekordbox wrote; everything else (the
waveforms, `PVBR`, tags nobody has decoded) must go back exactly as it was, and
re-serialising through a parser is how bytes get lost.
"""
from __future__ import annotations
import struct
from dataclasses import dataclass, field
#: `PMAI` · len_header · len_file · …
FILE_MAGIC = b"PMAI"
NO_LOOP = 0xFFFFFFFF
#: The cue-list kinds in `PCOB`/`PCO2`'s own header.
LIST_MEMORY = 0
LIST_HOT = 1
@dataclass
class Tag:
"""One tag, raw. `data` is the WHOLE tag: magic, both lengths, and body."""
type: str
data: bytes
_entries: list | None = field(default=None, repr=False, compare=False)
@property
def len_header(self) -> int:
return struct.unpack_from(">I", self.data, 4)[0]
@property
def list_kind(self) -> int | None:
"""`PCOB`/`PCO2`: whether this is the hot cue or the memory list."""
if self.type in ("PCOB", "PCO2") and len(self.data) >= 16:
return struct.unpack_from(">I", self.data, 12)[0]
return None
@property
def entries(self) -> list:
"""The tag's decoded entries (cues, or beats for `PQTZ`); [] otherwise."""
if self._entries is None:
decode = _DECODERS.get(self.type)
self._entries = decode(self.data) if decode else []
return self._entries
@dataclass
class AnlzFile:
"""An analysis file split into its header and raw tags."""
header: bytes
tags: list[Tag]
def to_bytes(self) -> bytes:
"""Reassemble, fixing only the header's file length."""
body = b"".join(t.data for t in self.tags)
head = bytearray(self.header)
struct.pack_into(">I", head, 8, len(head) + len(body))
return bytes(head) + body
def copy(self) -> "AnlzFile":
return AnlzFile(self.header, [Tag(t.type, t.data) for t in self.tags])
def find(self, kind: str, list_kind: int | None = None) -> int | None:
"""Index of the first `kind` tag (of that cue-list kind, if given)."""
for i, t in enumerate(self.tags):
if t.type == kind and (list_kind is None or t.list_kind == list_kind):
return i
return None
def put(self, kind: str, data: bytes, *, list_kind: int | None = None,
after: tuple[str, ...] = ()) -> None:
"""Replace the `kind` tag IN PLACE, keeping every other tag where it is.
A file without one gets it inserted after the last tag named in
`after` (rekordbox's order), else at the end.
"""
tag = Tag(kind, data)
i = self.find(kind, list_kind)
if i is not None:
self.tags[i] = tag
return
at = max((j for j, t in enumerate(self.tags) if t.type in after), default=len(self.tags) - 1)
self.tags.insert(at + 1, tag)
class AnlzError(ValueError):
pass
def parse(data: bytes) -> AnlzFile:
"""Split a file into its tags. Raises `AnlzError` on a malformed file.
Lengths are trusted only as far as the file reaches: a tag claiming more
bytes than remain ends the walk with an error rather than a short read.
"""
if len(data) < 12 or data[:4] != FILE_MAGIC:
raise AnlzError("not an ANLZ file")
len_header = struct.unpack_from(">I", data, 4)[0]
if not 12 <= len_header <= len(data):
raise AnlzError(f"bad file header length {len_header}")
tags: list[Tag] = []
off = len_header
while off < len(data):
if off + 12 > len(data):
raise AnlzError(f"truncated tag at {off}")
kind = data[off:off + 4].decode("latin-1")
len_tag = struct.unpack_from(">I", data, off + 8)[0]
if len_tag < 12 or off + len_tag > len(data):
raise AnlzError(f"bad length {len_tag} for {kind} at {off}")
tags.append(Tag(kind, data[off:off + len_tag]))
off += len_tag
return AnlzFile(header=data[:len_header], tags=tags)
def parse_file(path) -> AnlzFile:
with open(path, "rb") as f:
return parse(f.read())
# ---- cue entries ------------------------------------------------------------
@dataclass
class CueEntry:
"""One `PCPT` or `PCP2` entry. Attribute names follow pyrekordbox's, which
is what `onelibrary.cues` was written against.
`color_code` / RGB are None when the entry is too short to carry them (every
`PCPT`, and rekordbox's compact 44-byte `PCP2`).
"""
hot_cue: int
type: int
time: int
loop_time: int
comment: str = ""
loop_numerator: int = 0
loop_denominator: int = 0
color_code: int | None = None
color_red: int | None = None
color_green: int | None = None
color_blue: int | None = None
len_entry: int = 0
def raw_entries(tag: Tag) -> list[bytes]:
"""A `PCOB`/`PCO2` tag's entries as their own bytes, each at its own length —
so an entry Konduktor does not change goes back exactly as rekordbox wrote it."""
if tag.type == "PCOB":
count, first, magic = struct.unpack_from(">H", tag.data, 18)[0], 24, b"PCPT"
elif tag.type == "PCO2":
count, first, magic = struct.unpack_from(">H", tag.data, 16)[0], 20, b"PCP2"
else:
return []
return [tag.data[off:off + n] for off, n in _walk(tag.data, first, magic, count)]
def decode_entry(entry: bytes) -> CueEntry:
"""One raw `PCPT` or `PCP2` entry, decoded."""
if entry[:4] == b"PCPT":
return _pcob(struct.pack(">4sIIIHHi", b"PCOB", 24, 24 + len(entry), 0, 0, 1, -1) + entry)[0]
return _pco2(struct.pack(">4sIIIHH", b"PCO2", 20, 20 + len(entry), 0, 1, 0) + entry)[0]
def entry_hot_cue(entry: bytes) -> int:
"""A PCPT/PCP2 entry's `hot_cue`: its pad, 1-based; 0 for a memory cue."""
return struct.unpack_from(">I", entry, 12)[0]
def entry_with_colour(entry: bytes, code: int, rgb: tuple[int, int, int]) -> bytes | None:
"""A `PCP2` entry with ONLY its colour bytes changed — what rekordbox itself
does to recolour a cue (measured: those 4 bytes and nothing else). None if
the entry is too short to carry a colour (rekordbox's 44-byte form)."""
if len(entry) < 44:
return None
len_comment = struct.unpack_from(">I", entry, 40)[0]
at = 44 + len_comment
if at + 4 > len(entry):
return None
return entry[:at] + bytes([code & 0xFF, *rgb]) + entry[at + 4:]
def entry_without_loop_beats(entry: bytes) -> bytes:
"""A `PCP2` entry with its loop length in beats cleared to 0/0 — what
rekordbox does to every loop when the grid changes (measured: 32/1 -> 0/0),
rather than recomputing it."""
if len(entry) < 40 or entry[36:40] == b"\0\0\0\0":
return entry
return entry[:36] + bytes(4) + entry[40:]
def _walk(data: bytes, first: int, magic: bytes, count: int):
"""(offset, len_entry) for each entry, trusting each entry's own length."""
off = first
for _ in range(count):
if off + 12 > len(data) or data[off:off + 4] != magic:
return
len_entry = struct.unpack_from(">I", data, off + 8)[0]
if len_entry < 12 or off + len_entry > len(data):
return
yield off, len_entry
off += len_entry
def _pcob(data: bytes) -> list[CueEntry]:
# tag prefix(12) · I list kind · H 0 · H count · i last
count = struct.unpack_from(">H", data, 18)[0]
out = []
for off, n in _walk(data, 24, b"PCPT", count):
if n < 44:
continue
# 4s · I len_header · I len_entry · I hot_cue · I status · I 0x10000 ·
# H order_first · H order_last · B kind · x · H 1000 · I time · I loop
hot_cue, = struct.unpack_from(">I", data, off + 12)
kind = data[off + 28]
time, loop = struct.unpack_from(">II", data, off + 32)
out.append(CueEntry(hot_cue=hot_cue, type=kind, time=time, loop_time=loop, len_entry=n))
return out
def _pco2(data: bytes) -> list[CueEntry]:
# tag prefix(12) · I list kind · H count · H 0
count = struct.unpack_from(">H", data, 16)[0]
out = []
for off, n in _walk(data, 20, b"PCP2", count):
if n < 28:
continue
hot_cue, = struct.unpack_from(">I", data, off + 12)
kind = data[off + 16]
time, loop = struct.unpack_from(">II", data, off + 20)
e = CueEntry(hot_cue=hot_cue, type=kind, time=time, loop_time=loop, len_entry=n)
if n >= 44:
e.loop_numerator, e.loop_denominator, len_comment = struct.unpack_from(">HHI", data, off + 36)
colour_at = off + 44 + len_comment
if len_comment and colour_at <= off + n:
e.comment = data[off + 44:colour_at].decode("utf-16-be", "replace").rstrip("\x00")
if colour_at + 4 <= off + n:
e.color_code, e.color_red, e.color_green, e.color_blue = data[colour_at:colour_at + 4]
out.append(e)
return out
# ---- the beatgrid -----------------------------------------------------------
@dataclass
class Beat:
beat: int # 1-4, position in the bar
tempo: int # BPM x 100
time: int # ms
def _pqtz(data: bytes) -> list[Beat]:
# tag prefix(12) · I 0 · I 0x80000 · I count, then 8-byte entries
count = struct.unpack_from(">I", data, 20)[0]
first = struct.unpack_from(">I", data, 4)[0]
out = []
for i in range(count):
off = first + 8 * i
if off + 8 > len(data):
break
beat, tempo, time = struct.unpack_from(">HHI", data, off)
out.append(Beat(beat=beat, tempo=tempo, time=time))
return out
_DECODERS = {"PCOB": _pcob, "PCO2": _pco2, "PQTZ": _pqtz}
__all__ = [
"AnlzError", "AnlzFile", "Beat", "CueEntry", "LIST_HOT", "LIST_MEMORY",
"NO_LOOP", "Tag", "decode_entry", "entry_hot_cue", "entry_with_colour", "entry_without_loop_beats",
"parse", "parse_file", "raw_entries",
]
@@ -313,38 +313,30 @@ def flat_preview_tags() -> list[bytes]:
return preview_tags([0.0] * 400, [0.0] * 400)
def pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
rgb: tuple[int, int, int] | None, beats: int | None, code: int = 0,
comment: str | None = None) -> bytes:
def _pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
rgb: tuple[int, int, int] | None, beats: int | None, code: int = 0) -> 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""
comment = 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,
b"PCP2", 16, PCP2_ENTRY_LEN, 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),
0, 1, beats or 0, 1 if beats else 0, len(comment),
# 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)
) + comment + struct.pack(">4B", code & 0xFF, red, green, blue) + bytes(
PCP2_ENTRY_LEN - 48 - len(comment)
)
def pcpt_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None) -> bytes:
def _pcpt_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None) -> bytes:
"""One `PCPT` entry, byte-for-byte as rekordbox 7 writes it.
`len_header` is **28**, not 12: a reader that trusts it finds the body 16
@@ -361,54 +353,28 @@ def pcpt_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None) ->
) + 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`)."""
def _pcob(cue_type: int, chosen: list[dict]) -> bytes:
blob = b"".join(
_pcpt_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
loop_ms=c["loop_ms"])
for c in chosen
)
# 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
])
# writes it.
last = -1 if cue_type == 1 else len(chosen) - 1
return _wrap("PCOB", struct.pack(">IHHi", cue_type, 0, len(chosen), last) + blob)
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"))
blob = b"".join(
_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))
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)
)
return _wrap("PCO2", struct.pack(">IHH", cue_type, len(chosen), 0) + blob)
def cue_tags(cues: list[dict], *, extended: bool) -> list[bytes]:
@@ -438,18 +404,13 @@ def cue_tags(cues: list[dict], *, extended: bool) -> list[bytes]:
_FILE_HEADER_LEN = 28
def anlz_bytes(tags: list[bytes]) -> bytes:
"""Assemble an ANLZ file from built tag bytes."""
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)
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))
path.write_bytes(header + body)
return path
@@ -30,7 +30,6 @@ from ...core.capabilities import (
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
@@ -69,10 +68,8 @@ def capabilities_for(
max_memory_cues=None, # unlimited
# Both cue types write; Rekordbox has no fade/load types.
types=WRITABLE_CUE_TYPES,
# A hot cue's colour is one of rekordbox's 16 swatches (all
# measured, see `palette`), offered in rekordbox's own order.
color="palette",
palette=[palette.hex_for(code) for code in palette.SWATCHES],
palette=[], # TODO milestone 2: the built-in cue colour table
named=True, # djmdCue.Comment
loops="cue_type",
),
@@ -86,11 +83,7 @@ def capabilities_for(
# 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,
media_kinds=["audio"],
artwork=False,
artwork_note=None,
),
@@ -63,7 +63,7 @@ class RekordboxDriver:
except Exception: # noqa: BLE001
pass
def open(self, path: Path, *, read_only: bool = False) -> RekordboxAdapter:
def open(self, path: Path) -> RekordboxAdapter:
return RekordboxAdapter(path)
def detect(self) -> list[dict]:
+83 -18
View File
@@ -58,7 +58,8 @@ 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 anlz_writer as W
from . import artwork, palette
from . import timebase
from .beatgrid import beats_from_markers
from .capabilities import capabilities_for
@@ -81,8 +82,15 @@ 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
#: `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 — adds two more bits that draw an extra badge, most
#: likely claiming phrase/vocal analysis this exporter does not write. So the
#: value that claims only what is written: 0x2C060E.
CONTENT_LINK = 2885134
#: 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
@@ -311,7 +319,27 @@ class RekordboxExporter:
@staticmethod
def _lookup(db, kind: str, name: str | None):
return new_content.lookup(db, kind, name)
"""Find-or-create a lookup row, returning its id.
`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
# ---- analysis ---------------------------------------------------------------
@@ -322,15 +350,24 @@ class RekordboxExporter:
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))
track_uuid = str(content.UUID)
# Rekordbox derives these two levels from the track's UUID, and the
# column and the file have to agree — so the same derivation is used.
rel = f"/PIONEER/USBANLZ/{track_uuid[:3]}/{track_uuid[3:]}/ANLZ0000.DAT"
content.AnalysisDataPath = rel
content.Analysed = 105 # what a rekordbox-analysed track carries
content.AnalysisUpdated = 1
db.flush()
# The same three 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.
off = timebase.offset(item.destination)
measured = item.waveform(lead=off)
beats = None
path = str(item.destination)
tags = [W.path_tag(path), W.vbr_tag(W.mp3_samples(item.destination))]
markers = item.cues.grid_markers if item.cues else []
if markers:
duration = ((measured.duration if measured else 0.0)
@@ -340,18 +377,26 @@ class RekordboxExporter:
# 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)]
tags.append(W.beatgrid_tag(
[(n, bpm, timebase.to_pioneer(t, off)) for n, bpm, t in zip(nums, bpms, times)]))
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)
# 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)
written = [
W.write_anlz(dat, tags),
W.write_anlz(dat.with_suffix(".EXT"), [W.path_tag(path), *ext_waves[:1],
*W.cue_tags([], extended=True), *ext_waves[1:]]),
]
if two_ex:
written.append(W.write_anlz(dat.with_suffix(".2EX"), [W.path_tag(path), *two_ex]))
return written
# ---- artwork ------------------------------------------------------------------
@@ -367,14 +412,17 @@ class RekordboxExporter:
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:
if not item.art:
return []
rel = new_content.artwork_rel(str(content.UUID))
jpegs = artwork.library_jpegs(item.art[0])
if jpegs is None:
return []
track_uuid = str(content.UUID)
rel = f"/PIONEER/Artwork/{track_uuid[:3]}/{track_uuid[3:]}"
folder = root / "share" / rel.lstrip("/")
folder.mkdir(parents=True, exist_ok=True)
written = []
for name, data in files.items():
for name, data in zip(("artwork.jpg", "artwork_m.jpg", "artwork_s.jpg"), jpegs):
(folder / name).write_bytes(data)
written.append(folder / name)
content.ImagePath = f"{rel}/artwork.jpg"
@@ -414,3 +462,20 @@ class RekordboxExporter:
db.add_to_playlist(playlist, content)
db.flush()
def _insert_key(db, name: str) -> str:
"""A `djmdKey` row. Raw SQL for the same reason the registry row is: 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
@@ -1,138 +0,0 @@
"""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
@@ -9,9 +9,8 @@ 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).
* One palette colour went unmeasured — the teal-green between 0x0E and 0x16
(probably code 0x12); a cue that should be it maps to its nearest neighbour.
* 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
@@ -33,7 +32,6 @@ PALETTE: dict[int, tuple[int, int, int]] = {
0x05: (0x00, 0x70, 0xFF), # light blue
0x09: (0x00, 0xE0, 0xFF), # cyan
0x0E: (0x00, 0xFF, 0xA3), # teal
0x13: (0x00, 0xFF, 0x30), # teal-green (rekordbox's default for a new hot cue)
0x16: (0x1A, 0xFF, 0x00), # green
0x1A: (0x80, 0xFF, 0x00), # lime
0x1E: (0xE6, 0xFF, 0x00), # yellow-lime
@@ -93,27 +91,3 @@ def code_for(color: str | None) -> tuple[int, tuple[int, int, int]]:
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)
-163
View File
@@ -430,166 +430,3 @@ __all__ = [
"album_row", "artist_row", "dsql", "id_string_row", "key_row", "playlist_entry_row",
"playlist_tree_row", "read", "read_dsql", "template", "track_row",
]
# ---- editing an existing library -----------------------------------------------
#
# Editing a stick rekordbox wrote, rather than writing one from the template:
# only the tables whose rows change are rewritten, and inside them a row that
# does not change keeps rekordbox's own bytes. Every other table — history,
# colours, menus, artwork — stays byte-identical, and so does exportExt.pdb.
def _chain(buf: bytes, first: int, last: int) -> list[int]:
"""A table's page chain, header page first."""
pages, p = [first], first
while p != last and len(pages) < 100000:
p = struct.unpack_from("<I", buf, p * PAGE + 12)[0]
pages.append(p)
return pages
def table_rows(buf: bytes, table: int) -> list[bytes]:
"""Every present row of `table`, in page order, as its own bytes (padding
included) — a row's extent is up to the next row's heap offset, or the end
of the page's used heap."""
n_tables = struct.unpack_from("<I", buf, 8)[0]
for i in range(n_tables):
t, _empty, first, last = struct.unpack_from("<4I", buf, 28 + 16 * i)
if t != table:
continue
out = []
for p in _chain(buf, first, last)[1:]:
o = p * PAGE
if buf[o + 0x1B] & _HEADER_PAGE:
continue
n = (buf[o + 0x19] >> 5) | (buf[o + 0x1A] << 3)
used = struct.unpack_from("<H", buf, o + 0x1E)[0]
offs, present = [], []
# As `_rows` reads them: every bit of every group, since a page
# rekordbox has edited holds more row slots than its small count.
for g in range((n + 15) // 16):
base = o + PAGE - g * _GROUP
mask = struct.unpack_from("<H", buf, base - 4)[0]
for r in range(16):
if mask & (1 << r):
offs.append(struct.unpack_from("<H", buf, base - 6 - 2 * r)[0])
present.append(True)
ends = sorted(set(offs)) + [used]
for off, ok in zip(offs, present):
if ok:
end = next(e for e in ends if e > off)
row = bytes(buf[o + _HEADER + off:o + _HEADER + end])
if table == TRACKS:
row = row[:track_extent(row)]
out.append(row)
return out
return []
def _dsql_len(buf: bytes, off: int) -> int:
head = buf[off]
return (head >> 1) if head & 1 else struct.unpack_from("<H", buf, off + 1)[0]
def track_extent(row: bytes) -> int:
"""Where a track row really ends: past its last string, 4-aligned.
NOT the next row's offset: rekordbox reuses its heap, and the bytes between
a row and the next can be a stale tail of an older, longer string (seen on
Goober: `...mp3` followed by `ing.stem.m4a`)."""
offs = struct.unpack_from(f"<{len(TRACK_STRINGS)}H", row, _TRACK_FIXED)
end = max(o + _dsql_len(row, o) for o in offs)
return end + (-end % 4)
def track_fields(row: bytes) -> tuple[dict, dict]:
"""A raw track row as (`fields`, `strings`) — what `track_row` takes back."""
fields = dict(zip([n for n, _ in _TRACK_FIELDS], struct.unpack_from(_TRACK_FMT, row, 0)))
offs = struct.unpack_from(f"<{len(TRACK_STRINGS)}H", row, _TRACK_FIXED)
return fields, {name: read_dsql(row, o) for name, o in zip(TRACK_STRINGS, offs)}
def row_id(table: int, row: bytes) -> int | tuple:
"""A row's identity within its table (the triple, for playlist entries)."""
if table == TRACKS:
return track_fields(row)[0]["id"]
if table == ARTISTS:
return struct.unpack_from("<I", row, 4)[0]
if table == ALBUMS:
return struct.unpack_from("<I", row, 12)[0]
if table == PLAYLIST_TREE:
return struct.unpack_from("<I", row, 12)[0]
if table == PLAYLIST_ENTRIES:
return struct.unpack_from("<3I", row, 0)
return struct.unpack_from("<I", row, 0)[0]
class PdbEditor(PdbWriter):
"""`PdbWriter` over an EXISTING library: `refill` replaces one table's rows.
The table keeps its pages — overwritten in place, more taken from the
next-unused counter if needed, any left over unlinked and blanked (a blank
reserved page inside the file is a state rekordbox's own template has) —
and keeps its empty candidate. `render` leaves the header's
pages-with-room field as it was: rekordbox did not touch it when it edited
Goober, and it is the least understood field in the file.
"""
def __init__(self, existing: bytes):
super().__init__(existing)
self._room_field = struct.unpack_from("<I", self.buf, 16)[0]
self._blank: set[int] = set()
def refill(self, table: int, rows: list[bytes]) -> None:
slot, candidate, first, last = self.tables[table]
old = _chain(bytes(self.buf), first, last)[1:]
if candidate in old:
old.remove(candidate)
chunks = _chunk(rows) if rows else []
indices = old[:len(chunks)] + [self._alloc() for _ in chunks[len(old):]]
for p in old[len(chunks):]:
self._blank.add(p)
shift_at = _INDEX_SHIFT_AT if table in (TRACKS, ARTISTS, ALBUMS) else None
indexed = table in _INDEXED
for i, chunk in enumerate(chunks):
nxt = indices[i + 1] if i + 1 < len(indices) else candidate
fill = None
if indexed:
fill = (len(chunk) + 1, 0) if i + 1 == len(chunks) else (_NONE, _NONE)
self.sequence += 1
self.pages[indices[i]] = _data_page(indices[i], table, nxt, chunk, self.sequence,
shift_at=shift_at, fill=fill)
self._reindex(first, indices, indexed=indexed)
self.tables[table] = [slot, candidate, first, indices[-1] if indices else first]
if not indices:
# No rows: the header page points straight at the candidate again.
struct.pack_into("<I", self.buf, first * PAGE + 12, candidate)
def _reindex(self, header_page: int, data_pages: list[int], *, indexed: bool) -> None:
o = header_page * PAGE
struct.pack_into("<I", self.buf, o + 12, data_pages[0] if data_pages else
struct.unpack_from("<I", self.buf, o + 12)[0])
if indexed:
# Clear the old entries first: a table that shrank must not keep
# listing pages it no longer has.
count = struct.unpack_from("<H", self.buf, o + _HEADER + 16)[0]
for k in range(max(count, len(data_pages))):
struct.pack_into("<I", self.buf, o + _HEADER + 20 + 4 * k, 0x1FFFFFF8)
if data_pages:
pages_with_room = self.pages_with_room
self._index(header_page, data_pages, indexed=indexed)
self.pages_with_room = pages_with_room
else:
struct.pack_into("<I", self.buf, o + _HEADER + 4, 0x03FFFFFF)
if indexed:
struct.pack_into("<HH", self.buf, o + _HEADER + 16, 0, 0x1FFF)
struct.pack_into("<HH", self.buf, o + 0x20, _NONE, _NONE)
struct.pack_into("<H", self.buf, o + 0x26, 0)
def render(self) -> bytes:
out = bytearray(super().render())
struct.pack_into("<I", out, 16, self._room_field)
for p in self._blank - set(self.pages):
out[p * PAGE:(p + 1) * PAGE] = bytes(PAGE)
return bytes(out)
@@ -8,7 +8,7 @@ from __future__ import annotations
import re
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
from . import beatgrid, palette, timebase
from . import beatgrid, timebase
from .cue_types import cue_type, role_and_slot
# Rekordbox names keys musically ("Abm", "F", "Ebm") rather than in Camelot or
@@ -97,10 +97,10 @@ def _name_of(related) -> str | None:
return None
def to_track(row, cue_kinds=(), *, stem: bool = False) -> Track:
def to_track(row, cue_kinds=()) -> Track:
"""Project one ``DjmdContent`` row.
`cue_kinds` is this track's ``(Kind, OutMsec, ColorTableIndex)`` from the store's single
`cue_kinds` is this track's ``(Kind, OutMsec)`` pairs 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
@@ -118,11 +118,12 @@ def to_track(row, cue_kinds=(), *, stem: bool = False) -> Track:
BPM are precisely the 22 with no grid.
"""
chips: list[HotcueChip] = []
for kind, out_msec, color_code in cue_kinds:
for kind, out_msec 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)))
# Rekordbox's colour is a palette index nobody has decoded yet (see
# `_cue_color`), so no colour is claimed and the UI uses the type's.
chips.append(HotcueChip(slot=slot, type=cue_type(out_msec), color=None))
chips.sort(key=lambda chip: chip.slot)
key_name = _name_of(getattr(row, "Key", None))
wheel, mode = parse_key(key_name)
@@ -156,10 +157,7 @@ def to_track(row, cue_kinds=(), *, stem: bool = False) -> Track:
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",
media_kind="audio",
)
@@ -212,6 +210,11 @@ def to_track_cues(cue_rows: list, grid: tuple | None, time_offset: float = 0.0)
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))
"""Rekordbox stores a PALETTE INDEX, not an RGB value.
The generic model carries ``#RRGGBB``, and the built-in palette that index
refers to is not yet known, so no colour is claimed rather than a wrong one
being invented. `capabilities.cues.color` already says "palette", so the UI
knows not to offer a free colour picker.
"""
return None
+73 -382
View File
@@ -37,15 +37,8 @@ from sqlalchemy import func, select, text
from sqlalchemy.exc import OperationalError
from sqlalchemy.orm import joinedload
from ...core.adapter import (
InvalidCommand,
LibraryNotSupported,
NotFound,
SaveOutcome,
Unsupported,
)
from ...core.adapter import InvalidCommand, LibraryNotSupported, NotFound, SaveOutcome
from ...core.edit_journal import EditJournal
from ...core.grid_edit import ReplaceGridCommands
from ...core.pathmap import PathMapping
from . import timebase
from .cue_types import beat_loop_size, kind_for, role_and_slot
@@ -53,36 +46,6 @@ from .cue_types import beat_loop_size, kind_for, role_and_slot
log = logging.getLogger(__name__)
def _file_facts(audio: Path) -> dict:
"""What Rekordbox reads off the file itself for a new track's row."""
from datetime import date
out: dict = {}
try:
st = audio.stat()
born = getattr(st, "st_birthtime", None) or st.st_mtime
out["created"] = date.fromtimestamp(born)
except OSError:
pass
try:
import mutagen
info = mutagen.File(str(audio)).info
out["length"] = int(round(info.length)) if info.length else None
if getattr(info, "bitrate", None):
out["bitrate"] = int(round(info.bitrate / 1000)) # kbps, as Rekordbox stores it
if getattr(info, "sample_rate", None):
out["sample_rate"] = int(info.sample_rate)
if getattr(info, "bits_per_sample", None):
out["bit_depth"] = int(info.bits_per_sample)
except Exception: # noqa: BLE001 — facts are a nicety; the row stands without them
log.debug("could not read %s", audio, exc_info=True)
return out
# Where a track's analysis files live, as `contentFile.Path` spells it.
_ANLZ_ROOT = "/PIONEER/USBANLZ/"
@contextmanager
def rekordbox_probe_suppressed():
"""Stop `pyrekordbox.commit()` refusing because a Rekordbox process exists.
@@ -111,7 +74,7 @@ def _iso_stamp(value) -> str:
return str(value)
class RekordboxStore(ReplaceGridCommands):
class RekordboxStore:
"""One open Rekordbox library."""
def __init__(self, path: Path):
@@ -122,12 +85,6 @@ class RekordboxStore(ReplaceGridCommands):
# Grid edits buffered until save(): ANLZ files are written to disk, so
# applying them at command time would break the save contract.
self._pending_grids: dict[str, tuple[list, list, list]] = {}
# Analysis/artwork files of removed tracks, `share`-relative, deleted
# by save() AFTER the commit — a failed commit must leave them in place.
self._pending_file_removals: set[str] = set()
# Files of ADDED tracks, `share`-relative path -> bytes, written by
# save() BEFORE the commit (and removed again if it fails).
self._pending_new_files: dict[str, bytes] = {}
self._load()
# ---- open ------------------------------------------------------------
@@ -141,7 +98,6 @@ class RekordboxStore(ReplaceGridCommands):
except Exception as ex: # noqa: BLE001 — surfaced as a clean 4xx
raise LibraryNotSupported(f"Could not open Rekordbox library: {ex}") from ex
self._grid_cache.clear()
self._stem_cache: dict[str, bool] = {}
self._content_cache: list | None = None
self._by_id: dict[str, object] | None = None
@@ -161,8 +117,6 @@ class RekordboxStore(ReplaceGridCommands):
self.close()
self._journal = EditJournal()
self._pending_grids.clear()
self._pending_file_removals.clear()
self._pending_new_files.clear()
self._load()
def close(self) -> None:
@@ -256,9 +210,8 @@ class RekordboxStore(ReplaceGridCommands):
raise NotFound(f"No track {track_id!r}")
return row
def cue_kinds(self) -> dict[str, list[tuple[int | None, int | None, int | None]]]:
"""``{track_id: [(Kind, OutMsec, ColorTableIndex), ...]}`` for every live
cue, in one query.
def cue_kinds(self) -> dict[str, list[tuple[int | None, int | None]]]:
"""``{track_id: [(Kind, OutMsec), ...]}`` for every live cue, in one query.
Just enough per cue for the library table's count and hotcue dots,
without a per-track round trip. What a ``Kind`` means is decided in the
@@ -267,13 +220,12 @@ class RekordboxStore(ReplaceGridCommands):
"""
t = self._tables
rows = self._db.session.execute(
select(t.DjmdCue.ContentID, t.DjmdCue.Kind, t.DjmdCue.OutMsec,
t.DjmdCue.ColorTableIndex)
select(t.DjmdCue.ContentID, t.DjmdCue.Kind, t.DjmdCue.OutMsec)
.where(t.DjmdCue.rb_local_deleted == 0)
).all()
out: dict[str, list[tuple[int | None, int | None, int | None]]] = {}
for content_id, kind, out_msec, color_code in rows:
out.setdefault(str(content_id), []).append((kind, out_msec, color_code))
out: dict[str, list[tuple[int | None, int | None]]] = {}
for content_id, kind, out_msec in rows:
out.setdefault(str(content_id), []).append((kind, out_msec))
return out
def cues(self, track_id: str) -> list:
@@ -375,20 +327,6 @@ class RekordboxStore(ReplaceGridCommands):
def set_path_mapping(self, mapping: PathMapping) -> None:
self._mapping = mapping or PathMapping()
def is_stem(self, track_id: str) -> bool:
"""Whether the track's FILE is a native-instruments stem file — read
from its contents (only `.m4a`/`.mp4` are opened, ~0.7 ms each), and
cached per path, since the projection asks for every track at open."""
from ...core.stem_file import is_stem_file
path = self.audio_path(track_id)
if path is None:
return False
key = str(path)
if key not in self._stem_cache:
self._stem_cache[key] = is_stem_file(path)
return self._stem_cache[key]
@property
def path_mapping(self) -> PathMapping:
return self._mapping
@@ -579,274 +517,13 @@ class RekordboxStore(ReplaceGridCommands):
.filter(t.DjmdSongPlaylist.PlaylistID == str(node_id))
.all()
)
# NOT `remove_from_playlist`: it commits, which wrote an unsaved edit
# to disk (beyond Discard's reach) and raised while Rekordbox ran.
# The list is rebuilt from 1 below, so no renumbering is needed.
for song in existing:
self._db.delete(song)
self._db.flush()
self._db.remove_from_playlist(playlist, song)
for n, track_id in enumerate(track_ids, start=1):
self._db.add_to_playlist(playlist, str(track_id), track_no=n)
self._journal.record("playlist", "entries", playlist.Name, after=len(track_ids))
return len(track_ids)
# ---- writes: adding tracks ---------------------------------------------
#
# MEASURED, by dragging two files into Rekordbox 7.2's collection and
# diffing (2026-10-01): see `new_content`. Rekordbox fills the row from the
# FILE (size, sample rate, bit rate, and `DateCreated` from the file's
# creation date), stamps it with this library's device, and lists every
# file it writes for the track in `contentFile` with the file's MD5.
def add_track(self, audio: Path, track, *, measured, with_grid: bool,
art: bytes | None) -> str:
"""Add one track's row, return its id. Its analysis files and artwork
are held until save(); its grid and cues are the caller's to replay
through the ordinary commands. `with_grid` reserves an empty `PQTZ`
in the `.DAT` for `replace_grid` to fill."""
from . import new_content
from .projection import render_key
audio = Path(audio)
if not audio.is_file():
raise InvalidCommand(f"No audio file at {audio}")
t = self._tables
if self._db.session.query(t.DjmdContent).filter_by(FolderPath=str(audio)).count():
raise InvalidCommand(f"The library already holds {audio}")
facts = _file_facts(audio)
content = self._db.add_content(
str(audio),
Title=track.title or audio.stem,
Length=facts.get("length") or track.length,
BitRate=facts.get("bitrate") or (int(track.bitrate / 1000) if track.bitrate else None),
SampleRate=facts.get("sample_rate"),
BitDepth=facts.get("bit_depth", 16),
Rating=track.rating or 0,
Commnt=track.comment or "",
ReleaseDate=track.release_date or "",
)
year = str(track.release_date or "")[:4]
if year.isdigit():
content.ReleaseYear = int(year)
if facts.get("created"):
content.DateCreated = facts["created"]
content.ArtistID = new_content.lookup(self._db, "artist", track.artist)
content.AlbumID = new_content.lookup(self._db, "album", track.album)
content.GenreID = new_content.lookup(self._db, "genre", track.genre)
content.LabelID = new_content.lookup(self._db, "label", track.label)
# Rendered from the wheel, never copied: the source's notation is not
# Rekordbox's ("10m" is "Cm" here).
content.KeyID = new_content.lookup(
self._db, "key", render_key(track.key_wheel, track.key_mode))
content.ContentLink = new_content.CONTENT_LINK
track_uuid = str(content.UUID)
rel = new_content.anlz_rel(track_uuid)
content.AnalysisDataPath = rel
content.Analysed = 105 # what a rekordbox-analysed track carries
content.AnalysisUpdated = 1
files = new_content.anlz_files(audio, measured, [] if with_grid else None)
for suffix, data in files.items():
self._pending_new_files[str(Path(rel).with_suffix(suffix))] = data
art_files = new_content.artwork_files(art)
if art_files:
folder = new_content.artwork_rel(track_uuid)
for name, data in art_files.items():
self._pending_new_files[f"{folder}/{name}"] = data
content.ImagePath = f"{folder}/artwork.jpg"
self._db.flush()
track_id = str(content.ID)
if self._content_cache is not None and self._by_id is not None:
self._content_cache.append(content)
self._by_id[track_id] = content
self._grid_cache.pop(track_id, None)
self._journal.record("track", "add", track_id)
return track_id
def _write_new_files(self) -> list[Path]:
"""Write added tracks' files; return what was written."""
share = self.path.parent / "share"
written: list[Path] = []
try:
for rel, data in self._pending_new_files.items():
path = share / rel.lstrip("/")
path.parent.mkdir(parents=True, exist_ok=True)
written.append(path) # before the write: a partial file is cleaned too
path.write_bytes(data)
except BaseException:
for path in written:
path.unlink(missing_ok=True)
raise
return written
def _add_content_files(self, written: list[Path]) -> None:
"""One `contentFile` row per file an added track carries, as Rekordbox
writes them: `Hash` is the file's MD5, and its `_m`/`_s` artwork sizes
are not listed."""
import hashlib
from urllib.parse import quote
t = self._tables
share = self.path.parent / "share"
by_folder = {}
for row in self.iter_content():
for rel in (row.AnalysisDataPath, row.ImagePath):
if rel:
by_folder[str(Path(rel).parent)] = row
for path in written:
if path.name in ("artwork_m.jpg", "artwork_s.jpg"):
continue
rel = "/" + path.relative_to(share).as_posix()
row = by_folder.get(str(Path(rel).parent))
if row is None:
continue
self._db.add(t.ContentFile(
ID=f"{row.UUID}_{quote(rel, safe='')}",
ContentID=str(row.ID),
Path=rel,
Hash=hashlib.md5(path.read_bytes()).hexdigest(),
Size=path.stat().st_size,
rb_local_path=str(path),
UUID=str(uuid.uuid4()),
created_at=datetime.now(),
updated_at=datetime.now(),
))
self._db.flush()
# ---- writes: removing tracks -------------------------------------------
#
# MEASURED, by removing a track in Rekordbox 7.2 and diffing every row and
# every file under `share/` (Demo Track 2, 2026-10-01): Rekordbox DELETES
# the rows — it does not set `rb_local_deleted` — from these tables, leaves
# the playlist row itself alone, and deletes the files `contentFile` lists
# (there, the four ANLZ files) together with their emptied folders. That
# track had no artwork, and an Artwork folder holds `_m`/`_s` sizes that
# `contentFile` does not list, so artwork is left in place: an orphaned
# image is harmless, a guessed deletion is not.
_REMOVED_WITH_TRACK = ("DjmdCue", "ContentCue", "ContentFile", "DjmdMixerParam",
"DjmdSongPlaylist")
# Also keyed by ContentID, but empty in the measured library, so what
# Rekordbox does with them is unknown. A track that appears in one is
# refused rather than guessed at.
_UNMEASURED_LINKS = {
"djmdSongHistory": "a History list",
"djmdSongSampler": "the Sampler",
"djmdSongTagList": "the Tag List",
"djmdSongMyTag": "My Tag",
"djmdSongHotCueBanklist": "a Hot Cue Bank List",
"djmdSongRelatedTracks": "Related Tracks",
"djmdSongRequestList": "a request list",
"djmdActiveCensor": "an Active Censor",
"contentActiveCensor": "an Active Censor",
"djmdCloudExportSongPlaylist": "a cloud export",
}
def _unmeasured_links(self, ids: list[str]) -> list[tuple[str, str]]:
"""``(track_id, where)`` for each track named by an unmeasured table."""
params = {f"i{n}": tid for n, tid in enumerate(ids)}
marks = ", ".join(f":{k}" for k in params)
found: list[tuple[str, str]] = []
for table, where in self._UNMEASURED_LINKS.items():
try:
rows = self._db.session.execute(
text(f'SELECT DISTINCT ContentID FROM "{table}" '
f"WHERE ContentID IN ({marks})"), params
).all()
except Exception: # noqa: BLE001 — table absent in this schema version
continue
found += [(str(r[0]), where) for r in rows]
return found
def remove_tracks(self, track_ids: list[str]) -> int:
"""Remove tracks from the library and every playlist; return how many.
Validated as a whole first, so a refused batch changes nothing. The
audio files are never touched; the analysis files go at save().
"""
t = self._tables
self.iter_content()
assert self._by_id is not None
ids = [str(tid) for tid in dict.fromkeys(track_ids) if str(tid) in self._by_id]
if not ids:
return 0
blocked = self._unmeasured_links(ids)
if blocked:
tid, where = blocked[0]
title = self._by_id[tid].Title or tid
more = f" (and {len(blocked) - 1} more)" if len(blocked) > 1 else ""
raise Unsupported(
f"“{title}” is in {where} in Rekordbox{more}, and Konduktor does not "
"yet know how Rekordbox removes a track from there. Remove it in "
"Rekordbox instead — nothing was changed."
)
playlists: set[str] = set()
for tid in ids:
for name in self._REMOVED_WITH_TRACK:
table = getattr(t, name)
for row in self._db.session.query(table).filter(table.ContentID == tid):
if name == "ContentFile" and str(row.Path or "").startswith(_ANLZ_ROOT):
self._pending_file_removals.add(str(row.Path))
elif name == "DjmdSongPlaylist":
playlists.add(str(row.PlaylistID))
self._db.delete(row)
self._db.delete(self._by_id[tid])
self._pending_grids.pop(tid, None)
self._grid_cache.pop(tid, None)
self._journal.record("track", "remove", tid)
self._db.flush()
for playlist_id in playlists:
self._renumber(playlist_id)
self._content_cache = None
self._by_id = None
return len(ids)
def _renumber(self, playlist_id: str) -> None:
"""Close the gaps removed entries left in a playlist's `TrackNo`s, as
`pyrekordbox.remove_from_playlist` does — one 'move' for the registry,
not an update per row."""
t = self._tables
moved = []
now = datetime.now()
rows = (
self._db.session.query(t.DjmdSongPlaylist)
.filter(t.DjmdSongPlaylist.PlaylistID == playlist_id)
.order_by(t.DjmdSongPlaylist.TrackNo)
)
with self._db.registry.disabled():
for n, row in enumerate(rows, start=1):
if row.TrackNo != n:
row.TrackNo = n
row.updated_at = now
moved.append(row)
if moved:
self._db.registry.on_move(moved)
def _delete_removed_files(self) -> None:
"""Delete removed tracks' analysis/artwork files, then their emptied
folders. Called after the commit; a file another track still lists is
kept, and a failure only leaves an orphan behind, so it is logged."""
t = self._tables
share = (self.path.parent / "share").resolve()
still_listed = {str(p) for (p,) in self._db.session.query(t.ContentFile.Path)}
for rel in sorted(self._pending_file_removals - still_listed):
parts = Path(rel.lstrip("/\\")).parts
path = (share / Path(*parts)).resolve()
# Folders below e.g. `PIONEER/USBANLZ` are the track's own; that
# level and above are Rekordbox's and stay even when emptied.
keep = (share / Path(*parts[:2])).resolve()
if len(parts) < 3 or keep not in path.parents:
continue
try:
path.unlink(missing_ok=True)
folder = path.parent
while folder != keep and not any(folder.iterdir()):
folder.rmdir()
folder = folder.parent
except OSError as ex:
log.warning("Could not delete %s: %s", path, ex)
self._pending_file_removals.clear()
# ---- save --------------------------------------------------------------
@property
def dirty(self) -> bool:
@@ -869,20 +546,9 @@ class RekordboxStore(ReplaceGridCommands):
"""
summary = self._journal.summary()
# Files first: if an analysis file cannot be written, nothing should have
# been committed to the database either. An added track's files go
# before the grids, which write into them, and their `contentFile`
# rows after, which hash what was finally written.
written = self._write_new_files()
try:
self._flush_grids()
self._add_content_files(written)
self._commit()
except BaseException:
for path in written:
path.unlink(missing_ok=True)
raise
self._pending_new_files.clear()
self._delete_removed_files()
# been committed to the database either.
self._flush_grids()
self._commit()
self._journal.clear()
# Reads go through the same session, so nothing needs re-projecting from
# scratch — but the grid cache is keyed by track and survives a save.
@@ -1003,17 +669,13 @@ class RekordboxStore(ReplaceGridCommands):
) -> None:
"""Create or replace the cue in `slot`. A loop is a cue with a length.
`color_code` is a rekordbox palette code (`palette.PALETTE`). None KEEPS
the colour of the cue already in the slot — the colour belongs to the
pad, so a rename, a type change or an Auto Hotcues Replace leaves it as
the user set it — and a new cue is uncoloured. Only `set_cue_color`
clears one.
`color_code` is a rekordbox palette code (`palette.PALETTE`); None or 0
writes the uncoloured convention, which is what every edit through the
adapter does — only the exporter passes a colour.
"""
if int(slot) < 0:
raise InvalidCommand(f"Hot cue slot cannot be negative, got {slot}")
existing = self._cue_row(track_id, slot)
if color_code is None and existing is not None:
color_code = existing.ColorTableIndex or None
self._write_cue(
track_id, existing, kind=kind_for("hotcue", slot), start_sec=start_sec,
cue_type=cue_type, length_sec=length_sec, name=name, color_code=color_code,
@@ -1086,44 +748,26 @@ class RekordboxStore(ReplaceGridCommands):
cue.BeatLoopSize = beat_loop_size(beats) if beats else None
cue.ActiveLoop = 0
cue.CueMicrosec = 0
cue.Color = 255
cue.ColorTableIndex = 0
else:
cue.BeatLoopSize = None
cue.ActiveLoop = None
cue.CueMicrosec = None
self._apply_color(cue, color_code, is_loop)
cue.Color = -1
cue.ColorTableIndex = None
if color_code:
# A palette-coloured cue, as the real library stores one: the code in
# ColorTableIndex (22 = green), Color -1. How rekordbox stores a
# COLOURED LOOP is not in the reference library; the same column is
# assumed and is what the smoke test checks.
cue.ColorTableIndex = int(color_code)
cue.Color = -1
cue.Comment = name or None
self._db.flush()
self._sync_content_cue(track_id)
@staticmethod
def _apply_color(cue, color_code: int | None, is_loop: bool) -> None:
"""A row's two colour columns — the one definition of both conventions."""
if color_code:
# A palette-coloured cue, as the real library stores one: the code in
# ColorTableIndex (22 = green), Color -1. Coloured loops store the
# same; verified in Rekordbox 7 through the master.db export.
cue.ColorTableIndex = int(color_code)
cue.Color = -1
elif is_loop:
# What Rekordbox writes on the loops and auto-cues it creates.
cue.Color = 255
cue.ColorTableIndex = 0
else:
cue.Color = -1
cue.ColorTableIndex = None
def set_cue_color(self, track_id: str, slot: int, color_code: int | None) -> None:
"""Recolour the cue in `slot`; None makes it uncoloured. Touches only the
colour columns, so the position does not take a time-base round trip."""
cue = self._cue_row(track_id, slot)
if cue is None:
raise NotFound(f"No cue in slot {slot}")
self._apply_color(cue, color_code, (cue.OutMsec or 0) > 0)
self._db.flush()
self._sync_content_cue(track_id)
self._journal.record("cue", "modify", track_id, f"slot:{slot}")
def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> None:
cue = self._cue_row(track_id, slot)
if cue is None:
@@ -1286,6 +930,53 @@ class RekordboxStore(ReplaceGridCommands):
row.BPM = int(round(ordered[0].bpm * 100)) if ordered else 0
self._journal.record("grid", "replace" if ordered else "delete", track_id)
def delete_grid(self, track_id: str) -> None:
self.replace_grid(track_id, [])
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> None:
from ...core.model import GridMarker
markers = self.current_markers(track_id)
if bpm is None:
# Inherit the tempo governing this point, like Traktor's add does.
governing = [m for m in markers if m.start <= start_sec]
bpm = governing[-1].bpm if governing else (markers[0].bpm if markers else None)
if not bpm:
raise InvalidCommand("The first marker on an ungridded track needs a tempo")
if any(abs(m.start - start_sec) < 0.001 for m in markers):
raise InvalidCommand("There is already a marker here")
markers.append(GridMarker(start=float(start_sec), bpm=float(bpm)))
self.replace_grid(track_id, markers)
def _marker_at(self, track_id: str, index: int) -> tuple[list, int]:
markers = self.current_markers(track_id)
if not 0 <= index < len(markers):
raise NotFound(f"No grid marker {index}")
return markers, index
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> None:
markers, i = self._marker_at(track_id, index)
# Clamp between neighbours so the list cannot reorder under the caller.
low = markers[i - 1].start + 0.001 if i > 0 else 0.0
high = markers[i + 1].start - 0.001 if i + 1 < len(markers) else None
target = max(low, float(start_sec))
if high is not None:
target = min(target, high)
markers[i] = markers[i].model_copy(update={"start": target})
self.replace_grid(track_id, markers)
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> None:
markers, i = self._marker_at(track_id, index)
if bpm <= 0:
raise InvalidCommand(f"A tempo must be positive, got {bpm}")
markers[i] = markers[i].model_copy(update={"bpm": float(bpm)})
self.replace_grid(track_id, markers)
def delete_grid_marker(self, track_id: str, index: int) -> None:
markers, i = self._marker_at(track_id, index)
del markers[i]
self.replace_grid(track_id, markers)
def _flush_grids(self) -> None:
"""Write buffered grids into their ANLZ files. Called by save().
@@ -173,7 +173,7 @@ class TraktorAdapter:
return result
# ---- adding tracks ----------------------------------------------------
def add_tracks(self, items: list, *, checkpoint=None) -> list[str]:
def add_tracks(self, items: list) -> list[str]:
"""Add tracks that came from somewhere else, with their prep.
Two steps, and the split is the point. The store creates a bare ENTRY —
@@ -195,7 +195,6 @@ class TraktorAdapter:
type, so a free RGB value has nowhere to go.
Returns the new track ids, in the order the items were given.
`checkpoint` is unused: nothing here is slow (Traktor analyses on load).
"""
added: list[str] = []
for item in items:
@@ -299,10 +298,6 @@ class TraktorAdapter:
self._store.set_hotcue_type(track_id, slot, self._native_cue_type(cue_type))
return self._refresh(track_id)
def set_cue_color(self, track_id: str, slot: int, color: str | None) -> TrackCues:
# Traktor colours a cue by its type (capabilities.cues.color = "none").
raise Unsupported("Traktor colours cues by their type")
def delete_cue(self, track_id: str, slot: int) -> TrackCues:
with _translate():
self._store.delete_hotcue(track_id, slot)
@@ -49,9 +49,7 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
# Traktor has no memory cues — every cue occupies a bank slot.
memory_cues=False,
types=CUE_TYPES,
# Traktor colours a cue by its TYPE; the only COLOR it stores is a
# grid marker's white companion, so there is nothing to pick.
color="none",
color="free",
named=True,
# A saved loop is a cue TYPE in Traktor, not a separate bank.
loops="cue_type",
@@ -62,7 +60,6 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
editable_fields=sorted(editable_fields),
media_kinds=["audio", "stem"],
removable=True,
addable=True,
stem_convertible=True,
# `.mp4` covers stem files (`.stem.mp4`). Traktor also reads WMA,
# but only on Windows, and a file added on one OS must play on both.
+1 -1
View File
@@ -25,7 +25,7 @@ class TraktorDriver:
return False
return b"<NML" in head and b"VERSION=" in head
def open(self, path: Path, *, read_only: bool = False) -> TraktorAdapter:
def open(self, path: Path) -> TraktorAdapter:
return TraktorAdapter(path)
def detect(self) -> list[dict]:
+12 -10
View File
@@ -22,6 +22,7 @@ import copy
import math
import threading
import uuid as uuidlib
from dataclasses import dataclass
from pathlib import Path
from traktor_nml_utils import (
@@ -45,12 +46,12 @@ from traktor_nml_utils.models.collection import (
)
from xsdata.formats.dataclass.serializers import XmlSerializer
from ...core.adapter import FileTagResult, InvalidCommand, SaveOutcome, StemSwapResult
from ...core.adapter import InvalidCommand, SaveOutcome, StemSwapResult
from ...core.edit_journal import EditJournal
from ...core.pathmap import common_dir_prefix
from ...core.pathmap import PathMapping
from ...core.relocate import PathGroup
from ...core.stem_file import NML_STEMS_JSON, nml_stems_for
from ...core.stem_file import NML_STEMS_JSON
from ...schemas import PlaylistNode
from . import beatgrid, timebase
from .locations import os_path_to_location, resolve_path
@@ -70,6 +71,15 @@ class PlaylistError(InvalidCommand):
"""
@dataclass
class FileTagResult:
track_id: str
file: str
ok: bool
status: str # "written" | "file-not-found" | "unsupported-format" | "error"
detail: str = ""
class TraktorStore:
def __init__(self, nml_path: Path):
self.nml_path = Path(nml_path)
@@ -419,14 +429,7 @@ class TraktorStore:
and ``loudness``. Both are outputs of Traktor's own analysis and cannot
be computed here; Traktor re-analyses a track that has none. Writing a
plausible-looking fingerprint would be inventing data.
A stem FILE gets ``<STEMS>``, rendered from its own ``stem`` box as
Traktor renders it: that element is what makes the entry a stem track
(its playlist keys ``TYPE="STEM"``, the Type column), and without it a
stem file added here read as plain audio.
"""
# Read before the lock: it opens the file.
stems = nml_stems_for(audio_path)
with self._lock:
volume, dir_, file = os_path_to_location(Path(audio_path))
key = f"{volume}{dir_}{file}"
@@ -470,7 +473,6 @@ class TraktorStore:
# `replace_grid` overwrites it from the markers when they land.
tempo=Tempotype(bpm=float(bpm)) if bpm else None,
cue_v2=[],
stems=Stemstype(stems=stems) if stems else None,
)
self._nml.collection.entry.append(entry)
self._entry_by_key[key] = entry
+5 -33
View File
@@ -57,10 +57,6 @@ class AppState:
# the middle of another would commit a half-applied state; reentrant so
# one of them may call another.
self.mutation = threading.RLock()
# Converted-to-stem tracks awaiting Save or Discard (see stems/pending.py),
# and what the last open's crash recovery did about any left over.
self.pending = None
self.recovery: dict | None = None
@property
def loaded(self) -> bool:
@@ -79,7 +75,7 @@ class AppState:
rests on, and an adapter is the thing that knows whether it is true —
so it is asserted here rather than assumed everywhere else.
"""
adapter = registry.open_library(path, read_only=True)
adapter = registry.open_library(path)
if adapter.capabilities().writable:
if hasattr(adapter, "close"):
try:
@@ -87,7 +83,7 @@ class AppState:
except Exception: # noqa: BLE001
pass
raise ValueError(
f"{path} cannot be opened read-only; only a library that can "
f"{path} is a writable library; only read-only sources "
"(such as a OneLibrary drive) can be opened as a source"
)
self.close_source()
@@ -121,10 +117,6 @@ class AppState:
# library gets corrupted. Only close once the new one has parsed, so a
# failed open leaves the current library intact.
previous = self.adapter
# Leaving a library discards its unsaved edits (the UI has confirmed), so
# a stem conversion's parked originals go back under their own names.
if self.pending is not None and self.pending.items:
self.pending.restore()
if previous is not None and hasattr(previous, "close"):
try:
previous.close()
@@ -136,6 +128,9 @@ class AppState:
if saved:
adapter.set_path_mapping(PathMapping.make(saved["from"], saved["to"]))
self.path, self.adapter = path, adapter
# Started after the saved mapping is applied, so a volume that mapping
# already fixes is not asked about.
self.relocation = RelocationCheck(adapter)
caps = adapter.capabilities()
# No sidecar beside a removable library: writing to a user's USB stick to
# satisfy Konduktor's own bookkeeping is not a trade worth making. Those
@@ -149,18 +144,6 @@ class AppState:
label=Path(str(path)).name,
sidecar=not getattr(driver, "removable", False),
)
# A crash may have left converted tracks mid-lifecycle: settle them from
# what the SAVED library says, BEFORE the missing-files check — a parked
# original is exactly what that check would report as missing.
from .stems.pending import Pending
self.pending = Pending(self.library_id)
self.recovery = None
if self.pending.items:
self.recovery = self.pending.recover(lambda item: adapter.track(item["new_id"]) is not None)
# Started after the saved mapping is applied, so a volume that mapping
# already fixes is not asked about.
self.relocation = RelocationCheck(adapter)
# Version history: record an "as I found it" baseline (deduped, so
# re-opening an unchanged library is a no-op). Best-effort.
history.ensure_baseline(path)
@@ -187,15 +170,6 @@ class AppState:
commit = history.commit(
self.path, outcome.snapshot, outcome.summary, __version__
)
# The swap is now on disk: what it replaced can go. After the library
# write, so a failed save deletes nothing; here rather than in the save
# route, because import and path remap save too.
if self.pending is not None and self.pending.swapped():
renames = self.pending.commit()
if renames and self.library_id:
from . import exports
exports.retarget(self.library_id, renames)
return outcome, commit
def discard(self) -> None:
@@ -207,8 +181,6 @@ class AppState:
"""
assert self.adapter is not None
with self.mutation:
if self.pending is not None and self.pending.items:
self.pending.restore()
self.adapter.reload()
+4 -44
View File
@@ -28,21 +28,6 @@ from .pathmap import PathMapping
from .relocate import PathGroup
@dataclass
class FileTagResult:
"""One audio-file tag write a save made — the `SaveOutcome.tag_results` item.
Promoted from the Traktor store when OneLibrary became the second platform
that writes edited fields into the audio files themselves.
"""
track_id: str
file: str
ok: bool
status: str # "written" | "file-not-found" | "unsupported-format" | "error"
detail: str = ""
@dataclass
class SaveOutcome:
"""What a save produced, in terms every platform can answer.
@@ -88,11 +73,6 @@ class NewTrack:
track: Track
audio_path: Path
cues: TrackCues | None = None
# The cover as the SOURCE library shows it — `(bytes, mime)` from its
# `cover_art` — since a library's art is not always embedded in the file.
# For a platform that keeps its own copy of the art (Rekordbox); one that
# reads the file's tags (Traktor) ignores it.
art: tuple[bytes, str] | None = None
@dataclass(frozen=True)
@@ -193,25 +173,12 @@ class LibraryAdapter(Protocol):
# fidelity guarantee hold. A new entry has no parsed original, so the rule
# becomes "an added entry must not perturb any existing one" — which is
# what `test_save_fidelity.py` checks rather than taking on trust.
#
# `checkpoint(message, step, of)` is called before each slow step (a
# platform that must ANALYSE what it adds, like Rekordbox, decodes every
# file) and may raise to cancel; it is only ever called before the library
# is touched, so a cancel leaves it as it was. Gated on
# `capabilities().tracks.addable`.
def add_tracks(self, items: list["NewTrack"], *, checkpoint=None) -> list[str]: ...
# OPTIONAL, where `capabilities().tracks.places_audio`: the library decides
# where added audio goes. `place_audio(source, track)` returns the path the
# importer must COPY `source` to (which becomes `NewTrack.audio_path`), or
# None when the file is already where the library can use it in place;
# `audio_home()` is where that audio lands, for the free-space check.
# (A protocol member would make every adapter implement them.)
def add_tracks(self, items: list["NewTrack"]) -> list[str]: ...
# Remove tracks from the library — and so from every playlist, since an
# entry naming a track the library no longer has is a dangling reference.
# Never touches audio files, except where `tracks.places_audio` (a stick's
# audio belongs to its library): there the file goes too, at Save. Returns
# how many were removed; gated on `capabilities().tracks.removable`.
# Never touches audio files. Returns how many were removed; gated on
# `capabilities().tracks.removable`.
def remove_tracks(self, track_ids: list[str]) -> int: ...
# Swap converted stem files into the library (see `StemSwap`), all at once:
@@ -239,9 +206,6 @@ class LibraryAdapter(Protocol):
name: str | None = None,
) -> TrackCues: ...
def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> TrackCues: ...
# `color` is "#RRGGBB" from `capabilities().cues.palette`, or None for the
# platform's uncoloured cue. Any other cue command keeps a slot's colour.
def set_cue_color(self, track_id: str, slot: int, color: str | None) -> TrackCues: ...
def delete_cue(self, track_id: str, slot: int) -> TrackCues: ...
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues: ...
@@ -296,11 +260,7 @@ class LibraryDriver(Protocol):
selects: str
def can_open(self, path: Path) -> bool: ...
# `read_only` opens a library only to READ it, alongside the loaded one (the
# sidebar's Devices). An adapter that honours it reports `writable=False`
# with cause `browsing`; one that ignores it still reports writable, and the
# caller — `AppState.open_source` — refuses it, so ignoring is safe.
def open(self, path: Path, *, read_only: bool = False) -> LibraryAdapter: ...
def open(self, path: Path) -> LibraryAdapter: ...
# OPTIONAL. What to call an opened library on screen. Only the adapter can
# answer for a platform where one library has more than one valid path —
# the filename is otherwise assumed, and that assumption is wrong for a
+2 -17
View File
@@ -22,10 +22,7 @@ from pydantic import BaseModel
# permanent refusal protecting their other machines.
# `not_in_library` is a folder of loose files being browsed: nothing there is a
# library to write to, and the way to edit one is to add it to the collection.
# `browsing` is an editable library opened only to READ alongside the loaded one
# (a OneLibrary stick in the sidebar's Devices): the way to edit it is to open it
# as THE library, which one SaveBar and one dirty state can then follow.
ReadonlyCause = Literal["platform_incomplete", "cloud_synced", "not_in_library", "browsing"]
ReadonlyCause = Literal["platform_incomplete", "cloud_synced", "not_in_library"]
CueType = Literal["cue", "fade_in", "fade_out", "load", "loop"]
CueRole = Literal["hotcue", "memory"]
@@ -64,17 +61,8 @@ class TrackCapabilities(BaseModel):
editable_fields: list[str] = []
media_kinds: list[MediaKind] = ["audio"]
# Tracks can be removed from the library (and so from its playlists). The
# audio file is never touched — except where `places_audio`: a library that
# owns where its audio lives (a stick) deletes it with the track, at Save.
# audio file is never touched either way.
removable: bool = False
# Tracks can be added to the library (`add_tracks`): an import from a
# device, or browsed files added to the collection.
addable: bool = False
# The LIBRARY decides where added audio goes (`place_audio`), so the user is
# neither asked "copy or leave in place?" nor for a destination: a OneLibrary
# stick can only point at files on itself, and lays them out as rekordbox
# does. False: the user chooses, as for a desktop collection.
places_audio: bool = False
# Tracks can be converted to native-instruments STEM files, which this
# platform plays as stems (`apply_stem_swaps`).
stem_convertible: bool = False
@@ -104,9 +92,6 @@ class SaveCapabilities(BaseModel):
library_label: str
overwrite_risk: Literal["none", "on_exit", "while_running"] = "none"
history: bool = True
# The library was written by one of Konduktor's EXPORT sets, whose next run
# replaces it — so an edit made here directly is undone by the next export.
managed_by_export: bool = False
class Capabilities(BaseModel):
+2 -4
View File
@@ -31,7 +31,6 @@ from pathlib import Path
from .capabilities import Capabilities, SaveCapabilities, TrackCapabilities
from .model import PlaylistNode, Track, TrackCues
from .places import is_hidden
from .stem_file import is_stem_file
log = logging.getLogger(__name__)
@@ -60,8 +59,7 @@ def _bpm(tags) -> float | None:
def read_track(path: Path) -> Track:
"""Project one audio file. Never raises: an unreadable tag is an untitled track."""
track = Track(id=str(path), title=path.stem, filepath=str(path),
media_kind="stem" if is_stem_file(path) else "audio")
track = Track(id=str(path), title=path.stem, filepath=str(path))
try:
import mutagen
@@ -114,7 +112,7 @@ def capabilities_for(folder: Path) -> Capabilities:
platform="folder",
writable=False,
readonly_cause="not_in_library",
tracks=TrackCapabilities(editable_fields=[], artwork=False, media_kinds=["audio", "stem"]),
tracks=TrackCapabilities(editable_fields=[], artwork=False),
save=SaveCapabilities(
app_name="Files",
library_label=folder.name or str(folder),
-69
View File
@@ -1,69 +0,0 @@
"""Marker-level beatgrid commands, for a store whose one primitive is "replace".
A platform that stores the grid as a flat list of beats (Rekordbox's `PQTZ`, and
so OneLibrary's) has no native "move this marker": every marker-level command is
a read-modify-replace of the generic marker list. Promoted here when OneLibrary
became the second store needing exactly that, so "where does a moved marker
clamp" cannot mean two things. (Traktor's store has markers natively and keeps
its own, companion-cue-aware versions.)
A store using it provides `current_markers(track_id)` and
`replace_grid(track_id, markers)`.
"""
from __future__ import annotations
from .adapter import InvalidCommand, NotFound
from .model import GridMarker
class ReplaceGridCommands:
def current_markers(self, track_id: str) -> list[GridMarker]: # pragma: no cover
raise NotImplementedError
def replace_grid(self, track_id: str, markers: list[GridMarker]) -> None: # pragma: no cover
raise NotImplementedError
def delete_grid(self, track_id: str) -> None:
self.replace_grid(track_id, [])
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> None:
markers = self.current_markers(track_id)
if bpm is None:
# Inherit the tempo governing this point, like Traktor's add does.
governing = [m for m in markers if m.start <= start_sec]
bpm = governing[-1].bpm if governing else (markers[0].bpm if markers else None)
if not bpm:
raise InvalidCommand("The first marker on an ungridded track needs a tempo")
if any(abs(m.start - start_sec) < 0.001 for m in markers):
raise InvalidCommand("There is already a marker here")
markers.append(GridMarker(start=float(start_sec), bpm=float(bpm)))
self.replace_grid(track_id, markers)
def _marker_at(self, track_id: str, index: int) -> tuple[list, int]:
markers = self.current_markers(track_id)
if not 0 <= index < len(markers):
raise NotFound(f"No grid marker {index}")
return markers, index
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> None:
markers, i = self._marker_at(track_id, index)
# Clamp between neighbours so the list cannot reorder under the caller.
low = markers[i - 1].start + 0.001 if i > 0 else 0.0
high = markers[i + 1].start - 0.001 if i + 1 < len(markers) else None
target = max(low, float(start_sec))
if high is not None:
target = min(target, high)
markers[i] = markers[i].model_copy(update={"start": target})
self.replace_grid(track_id, markers)
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> None:
markers, i = self._marker_at(track_id, index)
if bpm <= 0:
raise InvalidCommand(f"A tempo must be positive, got {bpm}")
markers[i] = markers[i].model_copy(update={"bpm": float(bpm)})
self.replace_grid(track_id, markers)
def delete_grid_marker(self, track_id: str, index: int) -> None:
markers, i = self._marker_at(track_id, index)
del markers[i]
self.replace_grid(track_id, markers)
+2 -2
View File
@@ -44,8 +44,8 @@ def driver_for(path: Path) -> LibraryDriver:
raise LibraryNotSupported(f"No DJ library Konduktor recognises at {path}")
def open_library(path: Path, *, read_only: bool = False):
return driver_for(path).open(path, read_only=read_only)
def open_library(path: Path):
return driver_for(path).open(path)
def describe(path: Path) -> dict:
+1 -94
View File
@@ -36,7 +36,6 @@ Things that were measured and are easy to get wrong:
from __future__ import annotations
import fractions
import json
import struct
import sys
from dataclasses import dataclass
@@ -348,100 +347,8 @@ def is_stem_file(path: Path | str) -> bool:
return False
def stem_layout(path: Path | str) -> list[dict] | None:
"""The stems a file carries, for PLAYBACK: `[{"name", "color"}]` in stream
order (stream k+1 is stem k), or None when the file is not a playable stem
file — no `stem` box, a box that does not parse, or fewer audio streams than
it names. Read from the FILE, never from the library's `<STEMS>`: 105 plain
MP3 entries in the real collection carry that element."""
import json
import av
path = Path(path)
try:
raw = read_stem_box(path)
if raw is None:
return None
stems = json.loads(raw).get("stems") or []
with av.open(str(path), metadata_errors="ignore") as c:
streams = len(c.streams.audio)
except (OSError, ValueError, av.FFmpegError):
return None
if not stems or streams < 1 + len(stems):
return None
return [{"name": str(s.get("name") or f"Stem {i + 1}"), "color": str(s.get("color") or "#FFFFFF")}
for i, s in enumerate(stems)]
def _traktor_json(v) -> str:
if isinstance(v, bool):
return "true" if v else "false"
if isinstance(v, float):
return str(int(v)) if v.is_integer() else "%.16g" % v
if isinstance(v, (int, str)) or v is None:
return json.dumps(v, ensure_ascii=False)
if isinstance(v, list):
return "[" + ",".join(_traktor_json(x) for x in v) + "]"
if isinstance(v, dict):
return "{" + ",".join(f"{json.dumps(k, ensure_ascii=False)}:{_traktor_json(v[k])}"
for k in sorted(v)) + "}"
raise TypeError(f"not JSON: {v!r}")
def traktor_stems_json(box: bytes) -> str:
"""A `stem` box payload as Traktor writes it into `<STEMS STEMS="…">`: keys
sorted, no spaces, a whole float as an integer, any other to 16 significant
digits. Measured: it reproduces Traktor's value for every stem file on this
machine, and re-renders each of the 3,678 `<STEMS>` in the user's big
collection unchanged — but all of those carry ONE layout (NI's defaults),
so a box with other values is the same rule extrapolated. Raises ValueError
on a box that is not JSON."""
return _traktor_json(json.loads(box))
def nml_stems_for(path: Path | str) -> str | None:
"""The `<STEMS>` value a library entry for this file should carry, or None
when it is not a playable stem file (the test `stem_layout` applies)."""
if stem_layout(path) is None:
return None
try:
return traktor_stems_json(read_stem_box(path))
except (OSError, ValueError, TypeError):
return None
def extract_stream(path: Path | str, stream: int, fp) -> None:
"""Copy audio stream `stream` (0 = the mix, 1-4 the stems) into its own MP4,
written to the file object `fp` — packets COPIED, never re-encoded.
A browser decodes only an MP4's first audio stream, so this is how the deck
gets at the stems. Measured bit-identical to decoding the stream in place,
with the edit list (and so the priming: 1024 for FFmpeg's encoder, 2112 for
Apple's) carried across — on Konduktor's files and commercial ones alike, so
every stem stays sample-locked to the mix and to the cue timeline.
"""
import av
with av.open(str(path), metadata_errors="ignore") as inp:
if not 0 <= stream < len(inp.streams.audio):
raise StemFileError(f"The file has no audio stream {stream}")
ist = inp.streams.audio[stream]
out = av.open(fp, "w", format="ipod")
try:
ost = out.add_stream_from_template(ist)
for pkt in inp.demux(ist):
if pkt.dts is None:
continue # the demuxer's end-of-stream flush packet
pkt.stream = ost
out.mux(pkt)
finally:
out.close()
__all__ = [
"DEMUCS_ORDER", "NML_STEMS_JSON", "SR", "STEM_BOX_JSON", "STEM_NAMES", "Source",
"StemFileError", "Written", "add_stem_box", "build", "choose_bitrate", "decode",
"default_encoder", "extract_stream", "is_stem_file", "nml_stems_for", "read_stem_box", "stem_layout",
"stem_target_name", "traktor_stems_json", "verify",
"default_encoder", "is_stem_file", "read_stem_box", "stem_target_name", "verify",
]
+1 -12
View File
@@ -173,18 +173,7 @@ def _frames(y: np.ndarray, lead: float) -> Frames:
def analyse(path: Path, *, n_columns: int = 400, lead: float = 0.0) -> Analysis | None:
"""Decode `path` once and measure both resolutions; None if undecodable."""
return analyse_samples(decode(path), n_columns=n_columns, lead=lead)
def decode(path: Path) -> np.ndarray | None:
"""Mono float32 at `SR` — the same samples `analyse` measures, for a caller
that needs them for something else too (grid detection runs at `SR`)."""
return _decode(path)
def analyse_samples(y: np.ndarray | None, *, n_columns: int = 400,
lead: float = 0.0) -> Analysis | None:
"""`analyse` on samples already decoded by `decode`."""
y = _decode(path)
if y is None or len(y) < max(n_columns, N_FFT):
return None
return Analysis(columns=_columns(y, n_columns), frames=_frames(y, lead))
+5 -52
View File
@@ -290,15 +290,9 @@ def run(
destination and nothing to roll back. `into_playlist` appends every planned
track — the new ones and those the destination already held — to one of the
destination's playlists before the save, so both land in one commit.
A destination that PLACES ITS OWN AUDIO (`tracks.places_audio`: a OneLibrary
stick) overrides both: `dest.place_audio` names each copy's target, or says
the file can be used where it is, and `reference`/`plan.destination` are
ignored.
"""
destination = plan.destination
places = places_audio(dest)
if not reference and not places:
if not reference:
assert destination is not None
destination.mkdir(parents=True, exist_ok=True)
@@ -324,18 +318,11 @@ def run(
for planned in importable:
handle.raise_if_cancelled()
assert planned.source_path is not None
if places:
target = dest.place_audio(planned.source_path, source.track(planned.track_id))
if target is None:
copied.append((planned, planned.source_path))
continue
target.parent.mkdir(parents=True, exist_ok=True)
elif reference:
if reference:
copied.append((planned, planned.source_path))
continue
else:
target = _unique_target(destination, planned.source_path.name, taken)
handle.progress(message=f"Copying {planned.title}")
target = _unique_target(destination, planned.source_path.name, taken)
created.append(target) # registered BEFORE the write, so a cancel
copy_file(planned.source_path, target, handle, bump) # mid-file is cleaned
copied.append((planned, target))
@@ -353,23 +340,9 @@ def run(
cues = source.track_cues(planned.track_id)
except Exception: # noqa: BLE001 — prep is a bonus, not a blocker
log.debug("could not read cues for %s", planned.track_id, exc_info=True)
art = None
cover_art = getattr(source, "cover_art", None)
if cover_art is not None:
try:
art = cover_art(planned.track_id)
except Exception: # noqa: BLE001 — art is a bonus too
log.debug("could not read art for %s", planned.track_id, exc_info=True)
items.append(NewTrack(track=track, audio_path=target, cues=cues, art=art))
items.append(NewTrack(track=track, audio_path=target, cues=cues))
def checkpoint(message: str, *, step: int, of: int) -> None:
# A platform that analyses what it adds (Rekordbox) is slow here,
# and calls this before touching the library — so a cancel still
# leaves it untouched and the copies are cleaned up below.
handle.raise_if_cancelled()
handle.progress(done=step - 1, total=of, message=message)
new_ids = dest.add_tracks(items, checkpoint=checkpoint)
new_ids = dest.add_tracks(items)
by_source = {
planned.track_id: new_id
for (planned, _), new_id in zip(copied, new_ids)
@@ -412,26 +385,6 @@ def run(
raise
def places_audio(dest) -> bool:
"""Whether the destination decides where added audio goes (a stick)."""
try:
return bool(dest.capabilities().tracks.places_audio) and hasattr(dest, "place_audio")
except Exception: # noqa: BLE001
return False
def placed_bytes(dest, plan: ImportPlan) -> int:
"""What an import into a self-placing library will COPY: a file already under
its `audio_home()` is used in place and costs nothing."""
home = dest.audio_home()
total = 0
for planned in plan.importable:
path = planned.source_path
if path is not None and not path.resolve().is_relative_to(home.resolve()):
total += planned.size
return total
def _save(dest):
"""Save through AppState so the version-history commit is not skipped."""
from .app_state import STATE
+1 -18
View File
@@ -53,13 +53,6 @@ class Job:
#: library is written — so the UI can word them. Empty = unspecified.
unit: str = ""
message: str = ""
#: How far the CURRENT unit of work has got, 0..1 — so the overall bar can
#: move within a long item: at 99 % of the first of two tracks it reads
#: ~50 %, not 0. Reset whenever `done` advances.
fraction: float = 0.0
#: What the current item is doing ("separating 41 %"), shown beside its name
#: and never truncated in its place. Reset whenever `done` advances.
status: str = ""
result: Any = None
error: str | None = None
started_at: float = field(default_factory=time.time)
@@ -82,8 +75,6 @@ class Job:
"done": self.done,
"unit": self.unit,
"message": self.message,
"fraction": self.fraction,
"status": self.status,
"result": self.result,
"error": self.error,
"started_at": self.started_at,
@@ -103,19 +94,11 @@ class JobHandle:
self._job = job
def progress(self, done: int | None = None, total: int | None = None,
message: str | None = None, unit: str | None = None,
fraction: float | None = None, status: str | None = None) -> None:
message: str | None = None, unit: str | None = None) -> None:
if unit is not None:
self._job.unit = unit
if done is not None:
if done != self._job.done: # a new item: its progress starts over
self._job.fraction = 0.0
self._job.status = ""
self._job.done = done
if fraction is not None:
self._job.fraction = max(0.0, min(1.0, fraction))
if status is not None:
self._job.status = status
if total is not None:
self._job.total = total
if message is not None:
+17 -280
View File
@@ -89,16 +89,12 @@ from .schemas import (
SourceCandidate,
SourceStatus,
SetCue,
SetCueColor,
SetCueType,
SetGridLock,
Stats,
Track,
TrackCues,
TrackPage,
StemEngineInstall,
StemSideLoad,
StemConvert,
)
log = logging.getLogger(__name__)
@@ -218,7 +214,6 @@ def put_path_mapping(body: PathMappingInfo) -> PathMappingInfo:
"""Set (or, with blank prefixes, clear) the current collection's remapping.
Persists to userprefs AND updates the live store so playback/analysis
re-resolve immediately — no reopen needed. Never touches the .nml."""
_require_no_pending_stems("Changing the path mapping")
a = require_adapter()
mapping = PathMapping.make(body.from_, body.to)
prefs.set_path_mapping(
@@ -254,7 +249,6 @@ def remap_paths(body: PathMappingInfo) -> RemapResult:
playlist references that join to them) to the `to` prefix, then save (a
version-history commit is written). Destructive and OS-specific — the UI
warns accordingly."""
_require_no_pending_stems("Rewriting paths")
mapping = PathMapping.make(body.from_, body.to)
if mapping.empty:
raise HTTPException(400, "Both a `from` and `to` prefix are required")
@@ -315,7 +309,6 @@ def answer_relocation(body: RelocationApply) -> RelocationApplied:
"""Answer the check: apply the chosen mappings for THIS SESSION only (no
mappings = "Not now"). Nothing is written to the library or to prefs, and a
reopen asks again."""
_require_no_pending_stems("Relocating files")
require_adapter()
check = STATE.relocation
if check is None:
@@ -734,175 +727,7 @@ def capabilities() -> Capabilities:
@app.get("/api/state", response_model=EditState)
def state() -> EditState:
stem_job = JOBS.active(STEM_JOB)
pending = STATE.pending.summary() if STATE.pending is not None else None
return EditState(dirty=require_adapter().dirty, library=_library_info(),
pending_stems=pending if pending and pending["tracks"] else None,
stem_job=stem_job[0].id if stem_job else None,
stem_recovery=STATE.recovery)
# ---- stem engine (download / side-load / remove) --------------------------
# The engine and its weights live outside the app (see stems/engine_manager.py).
ENGINE_JOB = "stem-engine-install"
STEM_JOB = "stem-conversion"
@app.get("/api/stems/engine")
def stem_engine_status() -> dict:
"""What is installed, what this computer can run, and what a download costs."""
from .stems import engine_manager as em
mgr = em.default_manager()
running = JOBS.active(ENGINE_JOB)
return {**mgr.status(), "device": prefs.load_prefs().get("stemDevice", "auto"),
"install_job": running[0].id if running else None}
@app.post("/api/stems/engine/install", response_model=JobStatus)
def install_stem_engine(body: StemEngineInstall) -> JobStatus:
"""Download the engine (and the weights) as a job, in bytes."""
from .jobs import JobCancelled
from .stems import download
from .stems import engine_manager as em
mgr = em.default_manager()
if mgr.base_target is None:
raise HTTPException(422, "There is no stem engine for this computer")
target = body.target or mgr.base_target
if target not in mgr.status(network=False)["offered_targets"]:
raise HTTPException(400, f"The {target} engine is not offered on this computer")
def run(handle):
info = mgr.target_info(target)
if info is None:
raise em.EngineError("Could not reach the engine download — check the internet connection")
installed = mgr.installed()
need_engine = not (installed and installed["target"] == target)
need_weights = body.weights and not mgr.weights_installed()
total = (info["size"] if need_engine else 0) + (mgr.weights_size() if need_weights else 0)
handle.progress(done=0, total=total, unit="bytes", message="Downloading the stem engine…")
done = [0]
def on_bytes(n: int) -> None:
done[0] += n
handle.progress(done=done[0])
try:
if need_engine:
mgr.install_engine(target, on_bytes=on_bytes, cancelled=lambda: handle.cancelled)
if need_weights:
handle.progress(message="Downloading the separation model…")
mgr.install_weights(on_bytes=on_bytes, cancelled=lambda: handle.cancelled)
except download.DownloadCancelled:
raise JobCancelled()
return {"target": target, "ready": mgr.ready()}
try:
job = JOBS.submit(ENGINE_JOB, run, exclusive_with=(ENGINE_JOB, STEM_JOB))
except JobBusy:
raise HTTPException(409, "The stem engine is already downloading, or a conversion is running")
return JobStatus(**job.as_dict())
def _require_no_pending_stems(what: str) -> None:
"""Refuse an operation that would SAVE or DROP a stem conversion's swap as a
side effect — import and remap save pending edits, reload and restore drop
them — while converted tracks await Save/Discard or a conversion runs."""
if JOBS.active(STEM_JOB):
raise HTTPException(409, f"{what} is not possible while tracks are being converted to stems")
if STATE.pending is not None and STATE.pending.blocking():
raise HTTPException(409, f"{what} is not possible until the converted tracks are saved or discarded")
def _stem_options(body):
from .stems import convert
return convert.Options(
mode=body.mode, destination=Path(body.destination).expanduser() if body.destination else None,
collection=body.collection, playlist_id=body.playlist_id, new_playlist=body.new_playlist,
device=prefs.load_prefs().get("stemDevice", "auto"),
)
def _stem_plan(body):
from .stems import convert
adapter = require_adapter()
caps = adapter.capabilities()
if not (caps.writable and caps.tracks.stem_convertible):
raise HTTPException(422, "This library cannot hold stem files")
try:
return adapter, convert.plan(adapter, body.track_ids, _stem_options(body), STATE.pending)
except convert.ConvertError as ex:
raise HTTPException(400, str(ex))
@app.post("/api/tracks/stems/preview")
def preview_stem_conversion(body: StemConvert) -> dict:
"""What a conversion would do — converted, skipped (and why), disk space."""
_adapter, planned = _stem_plan(body)
return planned.as_dict()
@app.post("/api/tracks/stems/convert", response_model=JobStatus)
def convert_to_stems(body: StemConvert) -> JobStatus:
"""Convert tracks to stem files as a job; the swap lands at its end."""
from .stems import convert
from .stems import engine_manager as em
_require_no_batch()
if JOBS.active("import"):
raise HTTPException(409, "Wait for the import to finish")
adapter, planned = _stem_plan(body)
if planned.blocked:
raise HTTPException(409, planned.blocked)
if not planned.items:
raise HTTPException(400, "None of these tracks can be converted")
if any(p.reuse is None for p in planned.items) and not em.default_manager().ready():
raise HTTPException(409, "The stem engine is not installed")
opts = _stem_options(body)
def run(handle):
return convert.run(handle, adapter, planned, opts, STATE.pending, mutation=STATE.mutation,
still_current=lambda: STATE.adapter is adapter)
try:
job = JOBS.submit(STEM_JOB, run, exclusive_with=BATCH_JOBS + (ENGINE_JOB, "import"))
except JobBusy:
raise HTTPException(409, "Another batch, download or import is running")
return JobStatus(**job.as_dict())
@app.post("/api/stems/engine/sideload")
def side_load_stem_engine(body: StemSideLoad) -> dict:
"""Install the engine or the weights from files the user already has."""
from .stems import engine_manager as em
if JOBS.active(ENGINE_JOB) or JOBS.active(STEM_JOB):
raise HTTPException(409, "Wait for the running download or conversion to finish")
mgr = em.default_manager()
path = Path(body.path).expanduser()
if not path.exists():
raise HTTPException(400, f"Not found: {path}")
try:
if body.kind == "engine":
mgr.side_load_engine(path)
else:
mgr.side_load_weights(path)
except em.EngineError as ex:
raise HTTPException(400, str(ex))
return stem_engine_status()
@app.delete("/api/stems/engine")
def remove_stem_engine() -> dict:
from .stems import engine_manager as em
if JOBS.active(ENGINE_JOB) or JOBS.active(STEM_JOB):
raise HTTPException(409, "Wait for the running download or conversion to finish")
em.default_manager().remove()
return stem_engine_status()
return EditState(dirty=require_adapter().dirty, library=_library_info())
@app.post("/api/discard", response_model=EditState)
@@ -923,7 +748,6 @@ def discard_changes() -> EditState:
@app.post("/api/reload")
def reload_collection() -> dict:
_require_no_pending_stems("Reloading")
if not STATE.loaded:
raise HTTPException(409, "No collection loaded")
STATE.open(STATE.path) # re-parse current file from disk
@@ -1080,47 +904,14 @@ _AUDIO_MIME = {
}
def _stem_audio(path: Path, stem: int) -> FileResponse:
"""One stem of a stem file as a file of its own (see stems/stream_cache.py):
a browser only ever decodes an MP4's first stream, which is the mix."""
from .core import stem_file
from .stems import stream_cache
layout = stem_file.stem_layout(path)
if layout is None or not 0 <= stem < len(layout):
raise HTTPException(404, "That file has no such stem")
try:
return FileResponse(stream_cache.stem_file_for(path, stem), media_type="audio/mp4")
except (stem_file.StemFileError, OSError) as ex:
raise HTTPException(500, f"Could not read the stem: {ex}")
def _stem_layout_of(path: Path | None) -> dict:
from .core import stem_file
if path is None or not path.exists():
raise HTTPException(404, "Audio file not found")
return {"stems": stem_file.stem_layout(path) or []}
@app.get("/api/tracks/stems")
def track_stems(track_id: str) -> dict:
"""The stems a track's FILE carries for playback — `[{name, color}]`, empty
for anything that is not a stem file (whatever the library says)."""
return _stem_layout_of(require_adapter().audio_path(track_id))
@app.get("/api/tracks/audio")
def track_audio(track_id: str, stem: int | None = None) -> FileResponse:
"""Stream a track's audio file for playback (supports HTTP Range/seeking);
with `stem`, that stem of a stem file (0-based) instead."""
def track_audio(track_id: str) -> FileResponse:
"""Stream a track's audio file for playback (supports HTTP Range/seeking)."""
path = require_adapter().audio_path(track_id)
if path is None:
raise HTTPException(404, "Track not found")
if not path.exists():
raise HTTPException(404, f"Audio file not found: {path}")
if stem is not None:
return _stem_audio(path, stem)
# .stem.m4a and other MP4s serve as audio/mp4; browsers play the first track.
mime = _AUDIO_MIME.get(path.suffix.lower(), "application/octet-stream")
# Cacheable so the waveform's decode-fetch and the <audio> element can share
@@ -1252,7 +1043,7 @@ class _AnalysisError(Exception):
# beats that no longer exist.
GRID_JOB = "grid-analysis"
CUE_JOB = "auto-hotcues"
BATCH_JOBS = (GRID_JOB, CUE_JOB, STEM_JOB)
BATCH_JOBS = (GRID_JOB, CUE_JOB)
def _stop_batches() -> None:
@@ -1401,12 +1192,6 @@ def edit_cue_type(body: SetCueType) -> TrackCues:
return require_adapter().set_cue_type(body.track_id, body.slot, body.type)
@app.patch("/api/tracks/cue/color", response_model=TrackCues)
def edit_cue_color(body: SetCueColor) -> TrackCues:
"""Recolour an existing cue from the platform's palette (None = uncoloured)."""
return require_adapter().set_cue_color(body.track_id, body.slot, body.color)
@app.delete("/api/tracks/cue", response_model=TrackCues)
def delete_cue(track_id: str, slot: int) -> TrackCues:
"""Remove the hotcue in a slot."""
@@ -1569,7 +1354,6 @@ def restore_version(commit_id: str) -> CollectionStatus:
"""Restore the collection to a past version. Writes that version back as a
NEW forward save (a fresh commit on top of history — never a rewind), then
reloads. The user should close Traktor first (it overwrites on exit)."""
_require_no_pending_stems("Restoring a version")
require_adapter()
data = history.read_version(STATE.path, commit_id)
if data is None:
@@ -1738,7 +1522,7 @@ def source_track_cues(track_id: str) -> TrackCues:
@app.get("/api/source/tracks/audio")
def source_track_audio(track_id: str, stem: int | None = None) -> FileResponse:
def source_track_audio(track_id: str) -> FileResponse:
"""Stream a track's audio straight off the source drive.
So the deck can audition a track BEFORE importing it, which is most of the
@@ -1750,17 +1534,10 @@ def source_track_audio(track_id: str, stem: int | None = None) -> FileResponse:
raise HTTPException(404, "Track not found")
if not path.exists():
raise HTTPException(404, f"Audio file not found: {path}")
if stem is not None:
return _stem_audio(path, stem)
mime = _AUDIO_MIME.get(path.suffix.lower(), "application/octet-stream")
return FileResponse(path, media_type=mime)
@app.get("/api/source/tracks/stems")
def source_track_stems(track_id: str) -> dict:
return _stem_layout_of(require_source().audio_path(track_id))
# ---- drives and folders -----------------------------------------------
#
# The sidebar's Devices and Local Storage trees. Browsing a folder is READ-ONLY
@@ -1860,30 +1637,16 @@ def folder_track_cues(track_id: str) -> TrackCues:
@app.get("/api/folder/tracks/audio")
def folder_track_audio(track_id: str, stem: int | None = None) -> FileResponse:
def folder_track_audio(track_id: str) -> FileResponse:
path = _folder_track(track_id).audio_path(track_id)
if path is None or not path.is_file():
raise HTTPException(404, "Audio file not found")
if stem is not None:
return _stem_audio(path, stem)
mime = _AUDIO_MIME.get(path.suffix.lower(), "application/octet-stream")
return FileResponse(path, media_type=mime)
@app.get("/api/folder/tracks/stems")
def folder_track_stems(track_id: str) -> dict:
return _stem_layout_of(_folder_track(track_id).audio_path(track_id))
def _require_addable(dest) -> None:
caps = dest.capabilities()
if not (caps.writable and caps.tracks.addable):
raise HTTPException(422, "Tracks cannot be added to this library")
def _folder_add_plan(body: FolderAddRequest):
dest = require_adapter()
_require_addable(dest)
tracks = []
for track_id in body.track_ids:
track = _folder_track(track_id).track(track_id)
@@ -1894,10 +1657,7 @@ def _folder_add_plan(body: FolderAddRequest):
# One source across however many folders the ids came from.
source = FolderSource(Path(tracks[0].id).parent, tracks)
destination = None
if importer.places_audio(dest):
# The library decides (a stick): no mode, no destination to ask for.
destination = dest.audio_home()
elif body.mode == "copy":
if body.mode == "copy":
if not body.destination:
raise HTTPException(400, "Copying needs a destination folder")
destination = Path(body.destination).expanduser()
@@ -1913,11 +1673,9 @@ def _folder_add_plan(body: FolderAddRequest):
@app.post("/api/folder/add/preview")
def folder_add_preview(body: FolderAddRequest) -> dict:
_source, dest, destination, plan = _folder_add_plan(body)
_source, _dest, destination, plan = _folder_add_plan(body)
out = plan.as_dict(free_bytes=importer.free_bytes(destination) if destination else None)
if importer.places_audio(dest):
_placed_space(out, dest, plan, destination)
elif body.mode == "reference":
if body.mode == "reference":
# Nothing is copied, so there is no size to fit anywhere.
out.update(total_bytes=0, free_bytes=None, enough_space=None)
drive = _drive_of(Path(body.track_ids[0]), places.drives()) if body.track_ids else None
@@ -1928,17 +1686,15 @@ def folder_add_preview(body: FolderAddRequest) -> dict:
@app.post("/api/folder/add", response_model=JobStatus)
def folder_add(body: FolderAddRequest) -> JobStatus:
"""Add browsed files to the collection. A job, like import: copying can be long."""
_require_no_pending_stems("Adding files")
source, dest, destination, plan = _folder_add_plan(body)
if not plan.importable and not plan.existing:
raise HTTPException(400, "Nothing to add (none of those files exist)")
if body.mode == "copy" or importer.places_audio(dest):
if body.mode == "copy":
free = importer.free_bytes(destination)
needed = importer.placed_bytes(dest, plan) if importer.places_audio(dest) else plan.total_bytes
if free is not None and free < needed + importer.SPACE_HEADROOM:
if free is not None and free < plan.total_bytes + importer.SPACE_HEADROOM:
raise HTTPException(
400,
f"Not enough space: {needed / 1e9:.1f} GB needed, "
f"Not enough space: {plan.total_bytes / 1e9:.1f} GB needed, "
f"{free / 1e9:.1f} GB free at {destination}",
)
if JOBS.active("import"):
@@ -1968,23 +1724,9 @@ def folder_add(body: FolderAddRequest) -> JobStatus:
# threads rather than something fancier.
def _placed_space(out: dict, dest, plan, destination: Path) -> None:
"""A self-placing library's preview: only what is really COPIED needs room,
and the preview says how many files will be copied vs used in place."""
needed = importer.placed_bytes(dest, plan)
free = importer.free_bytes(destination)
in_place = sum(1 for t in plan.importable if t.source_path is not None
and t.source_path.resolve().is_relative_to(destination.resolve()))
out.update(total_bytes=needed, free_bytes=free,
enough_space=None if free is None else free >= needed + importer.SPACE_HEADROOM,
places_audio=True, in_place=in_place, copied=len(plan.importable) - in_place)
def _import_plan(body: ImportRequest):
source, dest = require_source(), require_adapter()
_require_addable(dest)
destination = (dest.audio_home() if importer.places_audio(dest)
else Path(body.destination).expanduser())
destination = Path(body.destination).expanduser()
return source, dest, destination, importer.plan(
source,
dest,
@@ -2001,26 +1743,21 @@ def import_preview(body: ImportRequest) -> dict:
Computed fresh on every call and never stored — a stick can be re-exported
between the preview and the import, and a stale preview is worse than none.
"""
_source, dest, destination, plan = _import_plan(body)
out = plan.as_dict(free_bytes=importer.free_bytes(destination))
if importer.places_audio(dest):
_placed_space(out, dest, plan, destination)
return out
_source, _dest, destination, plan = _import_plan(body)
return plan.as_dict(free_bytes=importer.free_bytes(destination))
@app.post("/api/import", response_model=JobStatus)
def start_import(body: ImportRequest) -> JobStatus:
"""Start an import. Returns immediately; poll the job for progress."""
_require_no_pending_stems("Importing")
source, dest, destination, plan = _import_plan(body)
if not plan.importable:
raise HTTPException(400, "Nothing to import (no tracks, or none of their files exist)")
free = importer.free_bytes(destination)
needed = importer.placed_bytes(dest, plan) if importer.places_audio(dest) else plan.total_bytes
if free is not None and free < needed + importer.SPACE_HEADROOM:
if free is not None and free < plan.total_bytes + importer.SPACE_HEADROOM:
raise HTTPException(
400,
f"Not enough space: {needed / 1e9:.1f} GB needed, "
f"Not enough space: {plan.total_bytes / 1e9:.1f} GB needed, "
f"{free / 1e9:.1f} GB free at {destination}",
)
# One at a time: two concurrent imports would race on filename collisions and
-41
View File
@@ -146,47 +146,9 @@ class SetCueType(BaseModel):
type: CueType
class SetCueColor(BaseModel):
track_id: str
slot: int
color: str | None = None # a capabilities.cues.palette entry; None = uncoloured
class StemEngineInstall(BaseModel):
# None = this computer's default engine; "windows-x64-cuda" to take the GPU one.
target: str | None = None
# Also fetch the model weights (the engine is useless without them).
weights: bool = True
class StemSideLoad(BaseModel):
path: str
kind: Literal["engine", "weights"]
class StemConvert(BaseModel):
track_ids: list[str]
# "replace": the stem file supersedes the original where it lives (the
# original is parked until Save deletes it); "destination": a chosen folder,
# originals never touched.
mode: Literal["replace", "destination"]
destination: str | None = None
# "repoint": the entry now names the stem file; "add": a new entry beside it
# (destination mode only).
collection: Literal["repoint", "add"] = "repoint"
playlist_id: str | None = None # add mode: into this existing playlist…
new_playlist: str | None = None # …or a new one with this name
class EditState(BaseModel):
dirty: bool # unsaved in-memory changes exist
library: LibraryInfo
# Converted tracks awaiting Save/Discard: {tracks, parked, bytes}.
pending_stems: dict | None = None
# A running stem conversion's job id, so a reloaded page finds it again.
stem_job: str | None = None
# What this open's crash recovery did about an interrupted conversion.
stem_recovery: dict | None = None
# ---- collection selection ----
@@ -489,9 +451,6 @@ class JobStatus(BaseModel):
# needs to tell a byte count from a track count.
unit: str = ""
message: str
# The current item's own progress (0..1) and what it is doing — see jobs.Job.
fraction: float = 0.0
status: str = ""
result: dict | None = None
error: str | None = None
started_at: float
-8
View File
@@ -1,8 +0,0 @@
"""Convert to Stems: everything outside the stem FILE itself.
`core/stem_file.py` writes a stem file from a separation callback; the Traktor
adapter swaps it into the collection (`apply_stem_swaps`). This package is what
sits around them: the downloadable engine and weights (`engine_manager`), the
engine process (`engine_process`), and — next — the batch and the parked-
originals lifecycle.
"""
-379
View File
@@ -1,379 +0,0 @@
"""The Convert to Stems batch: plan it, run it, swap it in.
**The collection is untouched while tracks convert** — for hours, on a big batch
— so edits made meanwhile carry over, and Cancel only deletes new files. Each
track becomes a verified `<target>.konduktor-partial`. Then one short END STEP,
under the app's mutation lock, publishes each file (a rename that refuses to
overwrite), parks each original in Replace mode, and swaps every entry at once
(`adapter.apply_stem_swaps`). From there the swap is an unsaved edit that Save
commits and Discard undoes (`pending.py`).
Skipped and reported, never failed (decided): a file that is already a stem
container (by its CONTENTS — the collection's `<STEMS>` element is on some
plain MP3s), a missing file, a target that already exists, two sources that
would write one target, a target the collection already names. A track that
fails keeps its original and is reported; the rest carry on.
"""
from __future__ import annotations
import contextlib
import shutil
import sys
from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable
from .. import paths
from ..core import stem_file as sf
from ..core.adapter import AdapterError, StemSwap
from ..core.pathmap import common_dir_prefix
from ..importer import SPACE_HEADROOM, free_bytes
from . import engine_manager as em
from .engine_process import EngineCancelled, EngineProcess, keep_awake
from .pending import Pending, _replace_no_overwrite, _retrying, parked_name, partial_name, source_facts
_LOSSLESS = (".wav", ".aif", ".aiff", ".flac")
#: Five AAC streams at up to 320 kbps plus container overhead.
_BYTES_PER_SECOND = {256_000: 5 * 256_000 / 8 * 1.03, 320_000: 5 * 320_000 / 8 * 1.03}
#: Raw float32 stereo, mix + four stems, while a track is being separated.
_WORK_BYTES_PER_SECOND = 5 * 2 * 4 * sf.SR
#: Shares of ONE track's conversion time, for the status bar's within-track
#: progress (measured on the M3 Pro: decode ~1 s, separate ~50 s, encode +
#: verify ~4 s for a 4-minute track).
_DECODE_SHARE = 0.03
_SEPARATE_SHARE = 0.90
class ConvertError(Exception):
"""User-facing; refuses the whole batch."""
class _Cancel(Exception):
pass
@dataclass
class Options:
mode: str # "replace" | "destination"
destination: Path | None = None
collection: str = "repoint" # "repoint" | "add"
playlist_id: str | None = None # add mode: an existing playlist
new_playlist: str | None = None # add mode: create one with this name
device: str = "auto"
@dataclass
class Planned:
track_id: str
title: str
source: Path
target: Path
seconds: float
reuse: dict | None = None
@dataclass
class Plan:
items: list[Planned] = field(default_factory=list)
skipped: list[dict] = field(default_factory=list)
space: list[dict] = field(default_factory=list)
blocked: str | None = None
def as_dict(self) -> dict:
return {"convert": [{"track_id": p.track_id, "title": p.title, "target": str(p.target),
"reuse": p.reuse is not None} for p in self.items],
"skipped": self.skipped, "space": self.space, "blocked": self.blocked,
# For the dialog's estimate: audio still to SEPARATE (reused
# leftovers cost nothing), and what the new files will take.
"seconds": sum(p.seconds for p in self.items if p.reuse is None),
"bytes": sum(e["bytes"] for e in self.space),
# What Save would delete in Replace mode — the dialog says so.
"original_bytes": sum(p.source.stat().st_size for p in self.items if p.source.exists())}
def _title(track) -> str:
"""How a track is named in progress, skip lists and reports: the track's
name FIRST — it is what tells one track from another when the end is cut
off in the status bar."""
if track is None:
return "?"
if track.artist and track.title:
return f"{track.title} - {track.artist}"
return track.title or Path(track.filepath or "").name or track.id
def _mirror(sources: list[Path], destination: Path) -> dict[Path, Path]:
"""Target folder per source: the source tree under `destination`, relative
to the sources' common folder, so same-named files cannot collide. Tracks
on different drives share no folder; each then keeps its full path (drive
or volume first)."""
prefix = common_dir_prefix([str(s) for s in sources])
out: dict[Path, Path] = {}
for s in sources:
if prefix:
rel = Path(str(s.parent)[len(prefix):].lstrip("/\\"))
else:
parts = s.parent.parts[1:]
head = s.drive.rstrip(":") if s.drive else ""
rel = Path(head, *parts) if head else Path(*parts)
out[s] = destination / rel
return out
def _output_rate(track, source: Path) -> int:
if source.suffix.lower() in _LOSSLESS:
return 320_000
bitrate = getattr(track, "bitrate", None) or 0
return 256_000 if 0 < bitrate < 256_000 else 320_000
def plan(adapter, track_ids: list[str], opts: Options, pending: Pending | None) -> Plan:
"""What the batch would do, without touching anything."""
result = Plan()
if opts.mode not in ("replace", "destination"):
raise ConvertError(f"Unknown mode {opts.mode!r}")
if opts.mode == "replace" and opts.collection != "repoint":
raise ConvertError("Replace mode replaces the entry; adding a second one needs a destination folder")
if opts.mode == "destination" and not opts.destination:
raise ConvertError("Choose a destination folder")
in_library = {str(p) for t in adapter.tracks if (p := adapter.audio_path(t.id)) is not None}
candidates: list[tuple[str, object, Path]] = []
for tid in dict.fromkeys(track_ids):
track = adapter.track(tid)
src = adapter.audio_path(tid) if track is not None else None
if track is None:
result.skipped.append({"track_id": tid, "title": tid, "reason": "not in the library"})
elif src is None or not Path(src).is_file():
result.skipped.append({"track_id": tid, "title": _title(track), "reason": "the file is missing"})
elif sf.is_stem_file(src):
result.skipped.append({"track_id": tid, "title": _title(track), "reason": "already a stem file"})
else:
candidates.append((tid, track, Path(src)))
folders = ({s: s.parent for _, _, s in candidates} if opts.mode == "replace"
else _mirror([s for _, _, s in candidates], Path(opts.destination)))
claimed: set[str] = set()
need: dict[str, dict] = {}
for tid, track, src in candidates:
target = folders[src] / sf.stem_target_name(src.name)
key = str(target).casefold() # APFS and NTFS are case-insensitive by default
reuse = pending.find_leftover(src) if pending is not None else None
if reuse is not None and Path(reuse["partial"]) != partial_name(target):
reuse = None
if key in claimed:
reason = "another selected track converts to the same file"
elif target.exists():
reason = f"a stem file already exists: {target.name}"
elif str(target) in in_library:
reason = f"the collection already has {target.name}"
else:
reason = None
if reason:
result.skipped.append({"track_id": tid, "title": _title(track), "reason": reason})
continue
claimed.add(key)
seconds = float(getattr(track, "length", 0) or 0) or src.stat().st_size / (320_000 / 8)
result.items.append(Planned(tid, _title(track), src, target, seconds, reuse))
vol = _volume_key(target)
entry = need.setdefault(vol, {"folder": str(target.parent), "bytes": 0})
entry["bytes"] += int(seconds * _BYTES_PER_SECOND[_output_rate(track, src)]) if reuse is None else 0
# Both copies coexist until Save, so every target volume needs the stem files'
# room on top of what is there; the work folder needs the largest track's.
for vol, entry in need.items():
free = free_bytes(Path(entry["folder"]))
entry.update(volume=vol, free=free)
result.space.append(entry)
if free is not None and entry["bytes"] + SPACE_HEADROOM > free:
result.blocked = (f"Not enough space on {vol}: the stem files need about "
f"{entry['bytes'] / 1e9:.1f} GB and {free / 1e9:.1f} GB is free")
if result.items and result.blocked is None:
work = work_root()
biggest = max(p.seconds for p in result.items) * _WORK_BYTES_PER_SECOND
free = free_bytes(work)
if free is not None and biggest + SPACE_HEADROOM > free:
result.blocked = (f"Not enough space for working files: about {biggest / 1e9:.1f} GB is "
f"needed while a track converts, {free / 1e9:.1f} GB is free")
return result
def _volume_key(path: Path) -> str:
p = path
while not p.exists() and p != p.parent:
p = p.parent
if sys.platform == "win32":
return (p.drive or str(p))
parts = p.parts
return f"/{parts[1]}/{parts[2]}" if len(parts) > 2 and parts[1] == "Volumes" else "this computer"
def work_root() -> Path:
root = paths.app_data_dir() / "stems" / "work"
root.mkdir(parents=True, exist_ok=True)
return root
def run(handle, adapter, planned: Plan, opts: Options, pending: Pending, *,
mutation, still_current: Callable[[], bool], manager: em.EngineManager | None = None) -> dict:
"""The job. Returns the result dict; the job's state says cancelled/done."""
mgr = manager or em.default_manager()
result = {"converted": [], "renamed": {}, "added": {}, "skipped": list(planned.skipped),
"failed": [], "clamped": {}, "cancelled": False}
items = planned.items
handle.progress(done=0, total=len(items), unit="tracks", message="Starting the stem engine…")
work = work_root() / f"batch-{id(handle):x}"
finished: list[tuple[Planned, dict, sf.Written]] = []
needs_engine = any(p.reuse is None for p in items)
if needs_engine and not mgr.ready():
raise ConvertError("The stem engine is not installed")
def checkpoint() -> None:
if handle.cancelled:
raise _Cancel()
with contextlib.ExitStack() as stack:
engine: EngineProcess | None = None
try:
for i, item in enumerate(items):
checkpoint()
handle.progress(done=i, message=item.title, fraction=0.0, status="")
partial = partial_name(item.target)
if item.reuse is not None:
written = sf.Written(path=partial, **{k: item.reuse["written"][k] for k in ("bit_rate", "duration", "size")},
tags={})
pitem = pending.add({"track_id": item.track_id, "mode": opts.collection, "source": str(item.source),
"stem": str(item.target), "state": "converted", "facts": source_facts(item.source),
"written": item.reuse["written"]})
pending.forget_leftover(item.reuse, delete=False)
finished.append((item, pitem, written))
continue
if engine is None:
handle.progress(status="starting…")
engine = stack.enter_context(EngineProcess(mgr.executable(), mgr.weights_dir(), device=opts.device))
stack.enter_context(keep_awake(engine.proc.pid))
pitem = pending.add({"track_id": item.track_id, "mode": opts.collection, "source": str(item.source),
"stem": str(item.target), "state": "converting", "facts": source_facts(item.source)})
item.target.parent.mkdir(parents=True, exist_ok=True)
# Of a TRACK's time, separation is nearly all (~90 % on MPS);
# decoding before it and encoding + verifying after share the rest.
def on_progress(f: float) -> None:
frac = _DECODE_SHARE + f * (_SEPARATE_SHARE)
handle.progress(fraction=frac, status=f"separating {frac * 100:.0f} %")
def separate(pcm):
handle.progress(fraction=_DECODE_SHARE, status=f"separating {_DECODE_SHARE * 100:.0f} %")
stems = engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled)
done_at = _DECODE_SHARE + _SEPARATE_SHARE
handle.progress(fraction=done_at, status=f"encoding {done_at * 100:.0f} %")
return stems
handle.progress(status="decoding 0 %")
try:
written = sf.build(item.source, partial, separate, checkpoint=checkpoint)
except (_Cancel, EngineCancelled):
partial.unlink(missing_ok=True)
pending.drop([pitem])
raise
except Exception as ex: # noqa: BLE001 — one track's failure is reported, not fatal
partial.unlink(missing_ok=True)
pending.drop([pitem])
result["failed"].append({"track_id": item.track_id, "title": item.title, "reason": str(ex) or type(ex).__name__})
if isinstance(ex, em.EngineError) and engine.proc.poll() is not None:
engine = None # it died: the next track starts a fresh one
continue
pending.update(pitem, state="converted",
written={"bit_rate": written.bit_rate, "duration": written.duration, "size": written.size})
finished.append((item, pitem, written))
except (_Cancel, EngineCancelled):
# Cancel = delete what this run made; nothing else was touched.
for _item, pitem, written in finished:
if pitem.get("state") == "converted":
Path(written.path).unlink(missing_ok=True)
pending.drop([p for _, p, _ in finished])
result["cancelled"] = True
return result
finally:
shutil.rmtree(work, ignore_errors=True)
handle.progress(done=len(items), message="Swapping the converted tracks into the collection…", status="")
with mutation:
if not still_current():
for _item, pitem, written in finished:
Path(written.path).unlink(missing_ok=True)
pending.drop([p for _, p, _ in finished])
raise ConvertError("The library changed while converting; nothing was swapped in")
_end_step(adapter, finished, opts, pending, result)
return result
def _end_step(adapter, finished, opts: Options, pending: Pending, result: dict) -> None:
swaps: list[StemSwap] = []
staged: list[tuple[Planned, dict]] = []
for item, pitem, written in finished:
partial = Path(written.path)
try:
_replace_no_overwrite(partial, item.target)
except FileExistsError:
partial.unlink(missing_ok=True)
pending.drop([pitem])
result["failed"].append({"track_id": item.track_id, "title": item.title,
"reason": f"a file appeared at {item.target.name} while converting"})
continue
pending.update(pitem, state="published")
original_now = item.source
if opts.mode == "replace":
parked = parked_name(item.source)
try:
_retrying(lambda: _replace_no_overwrite(item.source, parked))
except OSError as ex:
item.target.unlink(missing_ok=True)
pending.drop([pitem])
result["failed"].append({"track_id": item.track_id, "title": item.title,
"reason": f"the original could not be moved aside (in use?): {ex}"})
continue
_hide(parked)
pending.update(pitem, state="parked", parked=str(parked))
original_now = parked
swaps.append(StemSwap(item.track_id, item.target, opts.collection, original_now,
written.bit_rate, written.duration, written.size))
staged.append((item, pitem))
if not swaps:
return
playlist = opts.playlist_id
try:
if opts.collection == "add" and opts.new_playlist:
playlist = adapter.create_playlist(opts.new_playlist)
elif playlist is not None and adapter.playlist_entries(playlist) is None:
result["playlist_missing"] = True # deleted while converting: the tracks are still added
playlist = None
res = adapter.apply_stem_swaps(swaps, add_to_playlist=playlist if opts.collection == "add" else None)
except AdapterError as ex:
# Nothing was swapped (the command validates everything first): undo the files.
for item, pitem in staged:
pending._undo(pitem, keep_leftover=False)
pending.drop([pitem])
result["failed"].append({"track_id": item.track_id, "title": item.title, "reason": str(ex)})
return
for item, pitem in staged:
new_id = res.renamed[item.track_id]
pending.update(pitem, state="swapped", new_id=new_id)
result["converted"].append({"track_id": item.track_id, "new_id": new_id, "title": item.title})
(result["renamed"] if opts.collection == "repoint" else result["added"])[item.track_id] = new_id
result["clamped"] = res.clamped
def _hide(path: Path) -> None:
"""Windows ignores dot-names; set the hidden attribute so a parked original
does not show in Explorer (or a naive folder scan)."""
if sys.platform != "win32":
return
try:
import ctypes
ctypes.windll.kernel32.SetFileAttributesW(str(path), 0x02)
except Exception: # noqa: BLE001
pass
-99
View File
@@ -1,99 +0,0 @@
"""A resumable, verified download — the engine's parts and the weights.
Big files over home connections get interrupted, so a download resumes from
its `.part` file with an HTTP `Range` request (and starts over if the server
ignores it), and a file only takes its final name once its SHA-256 matches.
GitHub release assets and Hugging Face files both redirect to a CDN; urllib
carries the `Range` header across the redirect.
TLS uses certifi's bundle: a frozen Python on macOS has no system CA store of
its own, so the default context would reject every HTTPS certificate.
"""
from __future__ import annotations
import hashlib
import os
import ssl
import urllib.request
from pathlib import Path
from typing import Callable
CHUNK = 1 << 20
_UA = "Konduktor (stem engine download)"
class DownloadError(Exception):
"""User-facing."""
class DownloadCancelled(Exception):
pass
def ssl_context() -> ssl.SSLContext:
try:
import certifi
return ssl.create_default_context(cafile=certifi.where())
except Exception: # noqa: BLE001 — fall back to the platform's own store
return ssl.create_default_context()
def sha256_file(path: Path) -> str:
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(CHUNK), b""):
h.update(chunk)
return h.hexdigest()
def fetch(url: str, dest: Path, *, sha256: str, size: int | None = None,
on_bytes: Callable[[int], None] = lambda n: None,
cancelled: Callable[[], bool] = lambda: False,
context: ssl.SSLContext | None = None, timeout: float = 60) -> None:
"""Download `url` to `dest`, resuming a previous `.part`, verified.
`on_bytes` is told about every chunk INCLUDING what an earlier attempt
already fetched (once, up front), so a progress bar resumes where it was.
"""
dest = Path(dest)
dest.parent.mkdir(parents=True, exist_ok=True)
if dest.exists() and (size is None or dest.stat().st_size == size) and sha256_file(dest) == sha256:
on_bytes(dest.stat().st_size)
return
partial = dest.with_name(dest.name + ".part")
have = partial.stat().st_size if partial.exists() else 0
if size is not None and have > size:
partial.unlink()
have = 0
if have:
on_bytes(have)
if size is None or have < size:
headers = {"User-Agent": _UA}
if have:
headers["Range"] = f"bytes={have}-"
req = urllib.request.Request(url, headers=headers)
try:
with urllib.request.urlopen(req, timeout=timeout, context=context) as r:
if have and r.status != 206:
# The server ignored the range: start over, and un-count it.
on_bytes(-have)
have = 0
with open(partial, "ab" if have else "wb") as f:
while True:
if cancelled():
raise DownloadCancelled()
chunk = r.read(CHUNK)
if not chunk:
break
f.write(chunk)
on_bytes(len(chunk))
except DownloadCancelled:
raise
except OSError as ex: # URLError, timeouts, connection resets
raise DownloadError(f"Could not download {dest.name}: {ex}") from ex
got = sha256_file(partial)
if got != sha256:
partial.unlink(missing_ok=True)
raise DownloadError(f"{dest.name} did not arrive intact (checksum mismatch); try again")
os.replace(partial, dest)
-7
View File
@@ -1,7 +0,0 @@
{
"comment": "The stem engine THIS app build needs. Engines are released on their own channel (engine-v<version>, .github/workflows/engine.yml); the manifest lists each target's archive parts and hashes. `cuda` is the CUDA engine's floor, used to decide whether to OFFER it; the engine's own `info` confirms the card once installed.",
"version": "1.0.0",
"manifest_url": "https://github.com/MrPatben8/konduktor/releases/download/engine-v{version}/engine-manifest.json",
"asset_url": "https://github.com/MrPatben8/konduktor/releases/download/engine-v{version}/{name}",
"cuda": {"min_driver": 580, "min_capability": 7.5}
}
-375
View File
@@ -1,375 +0,0 @@
"""The stem engine and its weights on THIS machine: what is installed, getting
it, getting rid of it.
The engine is a separate frozen program, released on its own channel
(`engine-v<version>`; see `engine/` and `.github/workflows/engine.yml`) and
named by `engine.json` — the version this app build needs. The weights are
pinned by revision and SHA-256 in `weights.json` (a copy of
`engine/weights.json`; a test keeps them equal) and fetched from Hugging Face,
never re-hosted.
Layout under `root` — app-data on macOS; on Windows a SHORT root,
`%LOCALAPPDATA%\\Konduktor\\engine`, because torch's tree is deep and Windows
paths stop at 260 characters:
<root>/<version>/<target>/konduktor-engine/konduktor-engine[.exe]
<root>/installed.json what is installed, written LAST
<root>/weights/<revision>/... the four .safetensors + htdemucs_ft.yaml
<root>/downloads/ resumable .part files
An install is verified three times before it counts: each part's SHA-256, the
whole archive's, and — once unpacked into a temporary folder — the engine
actually starting and reporting the expected version. Only then is it moved
into place and `installed.json` written, so a half-finished or corrupt install
can never look like a working one. One engine is installed at a time (on
Windows the CUDA engine also runs on the CPU, so it replaces the CPU one).
"""
from __future__ import annotations
import json
import os
import platform
import shutil
import subprocess
import sys
import tarfile
from dataclasses import dataclass
from pathlib import Path
from typing import Callable
from .. import paths
from . import download
_HERE = Path(__file__).resolve().parent
CONFIG = json.loads((_HERE / "engine.json").read_text())
WEIGHTS = json.loads((_HERE / "weights.json").read_text())
TARGETS = ("macos-arm64", "windows-x64-cpu", "windows-x64-cuda")
class EngineError(Exception):
"""User-facing."""
def default_root() -> Path:
override = os.environ.get("KONDUKTOR_DATA_DIR")
if override:
return Path(override) / "engine"
if sys.platform == "win32" and os.environ.get("LOCALAPPDATA"):
return Path(os.environ["LOCALAPPDATA"]) / "Konduktor" / "engine"
return paths.app_data_dir() / "engine"
def base_target() -> str | None:
"""The engine this computer can run at all; None = no engine for it
(Intel Macs, Linux)."""
machine = platform.machine().lower()
if sys.platform == "darwin" and machine in ("arm64", "aarch64"):
return "macos-arm64"
if sys.platform == "win32" and machine in ("amd64", "x86_64"):
return "windows-x64-cpu"
return None
@dataclass(frozen=True)
class NvidiaGpu:
name: str
driver: str
capability: float
def detect_nvidia() -> list[NvidiaGpu]:
"""NVIDIA cards per `nvidia-smi` (installed with the driver). Empty when
there is none, or no driver — the case for every Mac."""
if sys.platform != "win32":
return []
try:
out = subprocess.run(
["nvidia-smi", "--query-gpu=name,driver_version,compute_cap", "--format=csv,noheader"],
capture_output=True, text=True, timeout=10,
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
).stdout
except (OSError, subprocess.SubprocessError):
return []
gpus = []
for line in out.splitlines():
parts = [p.strip() for p in line.split(",")]
if len(parts) == 3:
try:
gpus.append(NvidiaGpu(parts[0], parts[1], float(parts[2])))
except ValueError:
continue
return gpus
def cuda_suitable(gpus: list[NvidiaGpu], config: dict = CONFIG) -> NvidiaGpu | None:
"""The first card the CUDA engine can use: a new enough driver and compute
capability. Offering it to anyone else would be offering gigabytes for an
engine that falls back to the CPU."""
floor = config.get("cuda", {})
for g in gpus:
try:
major = int(g.driver.split(".")[0])
except ValueError:
continue
if major >= floor.get("min_driver", 0) and g.capability >= floor.get("min_capability", 0):
return g
return None
class EngineManager:
def __init__(self, root: Path | None = None, config: dict | None = None,
weights: dict | None = None, target: str | None = "auto") -> None:
self.root = Path(root) if root else default_root()
self.config = config or CONFIG
self.weights = weights or WEIGHTS
self._base_target = base_target() if target == "auto" else target
self._manifest: dict | None = None
# ---- where things are --------------------------------------------------
@property
def version(self) -> str:
return self.config["version"]
@property
def base_target(self) -> str | None:
return self._base_target
def _installed_record(self) -> dict | None:
return paths.read_json(self.root / "installed.json", None)
def installed(self) -> dict | None:
"""The installed engine, if it is this app's version and still there."""
rec = self._installed_record()
if not rec or rec.get("version") != self.version:
return None
exe = Path(rec.get("executable", ""))
return rec if exe.is_file() else None
def executable(self) -> Path | None:
rec = self.installed()
return Path(rec["executable"]) if rec else None
def weights_dir(self) -> Path:
return self.root / "weights" / self.weights["revision"]
def weights_installed(self) -> bool:
"""Present at the right sizes. (Hashes were checked when they arrived;
re-hashing 337 MB on every status call is not worth it.)"""
d = self.weights_dir()
return all((d / f["name"]).is_file() and (d / f["name"]).stat().st_size == f["size"]
for f in self.weights["files"])
def weights_size(self) -> int:
return sum(f["size"] for f in self.weights["files"])
# ---- manifest ------------------------------------------------------------
def manifest(self, *, fetch: bool = True) -> dict | None:
"""The release's manifest (each target's parts and hashes). Cached on
disk: once fetched, an install or side-load needs no network for it."""
if self._manifest is not None:
return self._manifest
cached = self.root / f"manifest-{self.version}.json"
data = paths.read_json(cached, None)
if data is None and fetch:
url = self.config["manifest_url"].format(version=self.version)
import urllib.request
try:
req = urllib.request.Request(url, headers={"User-Agent": "Konduktor"})
with urllib.request.urlopen(req, timeout=20, context=download.ssl_context()) as r:
data = json.loads(r.read())
except (OSError, ValueError):
return None
if data.get("version") != self.version:
return None
self.root.mkdir(parents=True, exist_ok=True)
paths.write_json(cached, data)
self._manifest = data
return data
def target_info(self, target: str) -> dict | None:
m = self.manifest()
return (m or {}).get("targets", {}).get(target)
# ---- status ----------------------------------------------------------------
def status(self, *, network: bool = True) -> dict:
installed = self.installed()
gpus = detect_nvidia()
cuda = cuda_suitable(gpus, self.config)
offered = [self.base_target] if self.base_target else []
if self.base_target == "windows-x64-cpu" and cuda is not None:
offered.append("windows-x64-cuda")
manifest = self.manifest(fetch=network) if offered else None
sizes = {t: (manifest or {}).get("targets", {}).get(t, {}).get("size") for t in offered}
return {
"supported": self.base_target is not None,
"required_version": self.version,
"installed": ({k: installed[k] for k in ("version", "target", "size")} if installed else None),
"offered_targets": offered,
"download_sizes": sizes,
"manifest_available": manifest is not None,
"nvidia": ({"name": cuda.name, "driver": cuda.driver, "capability": cuda.capability} if cuda else None),
"weights": {"installed": self.weights_installed(), "size": self.weights_size(),
"revision": self.weights["revision"]},
"root": str(self.root),
}
def ready(self) -> bool:
return self.executable() is not None and self.weights_installed()
# ---- installing the engine ---------------------------------------------------
def install_engine(self, target: str | None = None, *,
on_bytes: Callable[[int], None] = lambda n: None,
cancelled: Callable[[], bool] = lambda: False) -> dict:
target = target or self.base_target
if target is None or target not in TARGETS:
raise EngineError("There is no stem engine for this computer")
info = self.target_info(target)
if info is None:
raise EngineError("Could not reach the engine download — check the internet connection")
downloads = self.root / "downloads"
ctx = download.ssl_context()
for part in info["parts"]:
url = self.config["asset_url"].format(version=self.version, name=part["name"])
download.fetch(url, downloads / part["name"], sha256=part["sha256"], size=part["size"],
on_bytes=on_bytes, cancelled=cancelled, context=ctx)
archive = self._join_parts(info, downloads)
rec = self._install_archive(archive, target, info)
for part in info["parts"]:
(downloads / part["name"]).unlink(missing_ok=True)
archive.unlink(missing_ok=True)
return rec
def _join_parts(self, info: dict, folder: Path) -> Path:
parts = [folder / p["name"] for p in info["parts"]]
if len(parts) == 1:
archive = parts[0]
else:
archive = folder / info["archive"]
with open(archive, "wb") as out:
for p in parts:
with open(p, "rb") as f:
shutil.copyfileobj(f, out, 1 << 20)
if download.sha256_file(archive) != info["sha256"]:
raise EngineError("The engine download is damaged (checksum mismatch); try again")
return archive
def _install_archive(self, archive: Path, target: str, info: dict) -> dict:
"""Unpack, prove the engine starts, THEN move it into place."""
final = self.root / self.version / target
staging = self.root / self.version / f".{target}.installing"
shutil.rmtree(staging, ignore_errors=True)
staging.mkdir(parents=True)
try:
with tarfile.open(archive, "r:gz") as tar:
tar.extractall(staging, filter="tar")
exe = staging / "konduktor-engine" / ("konduktor-engine.exe" if sys.platform == "win32" else "konduktor-engine")
if not exe.is_file():
raise EngineError("The engine archive does not contain the engine")
reported = probe(exe)
if reported.get("version") != self.version:
raise EngineError(f"The engine reports version {reported.get('version')!r}, "
f"this app needs {self.version}")
shutil.rmtree(final, ignore_errors=True)
os.replace(staging, final)
except BaseException:
shutil.rmtree(staging, ignore_errors=True)
raise
rec = {"version": self.version, "target": target, "size": info.get("unpacked_size"),
"executable": str(final / "konduktor-engine" / exe.name), "info": reported}
paths.write_json(self.root / "installed.json", rec)
self._remove_others(keep=final)
return rec
def _remove_others(self, keep: Path) -> None:
"""One engine at a time: other targets and older versions go."""
for version_dir in self.root.iterdir():
if not version_dir.is_dir() or version_dir.name in ("weights", "downloads"):
continue
for target_dir in version_dir.iterdir():
if target_dir != keep and target_dir.is_dir():
shutil.rmtree(target_dir, ignore_errors=True)
if not any(version_dir.iterdir()):
version_dir.rmdir()
# ---- installing the weights ------------------------------------------------------
def install_weights(self, *, on_bytes: Callable[[int], None] = lambda n: None,
cancelled: Callable[[], bool] = lambda: False) -> None:
folder = self.weights_dir()
ctx = download.ssl_context()
for f in self.weights["files"]:
url = self.weights["url"].format(repo=self.weights["repo"], revision=self.weights["revision"],
name=f["name"])
download.fetch(url, folder / f["name"], sha256=f["sha256"], size=f["size"],
on_bytes=on_bytes, cancelled=cancelled, context=ctx)
# ---- side-loading (offline machines) ------------------------------------------
def side_load_engine(self, path: Path | str, target: str | None = None) -> dict:
"""Install from an engine archive the user already has — the `.tar.gz`,
or a folder holding all of its parts. Its hash must match the release
manifest (fetched now, or cached from an earlier look)."""
target = target or self.base_target
info = self.target_info(target) if target else None
if info is None:
raise EngineError("The engine's checksums are not known yet — connect once, or open the "
"Stems panel while online, so the file can be verified")
src = Path(path)
if src.is_dir():
archive = self._join_parts(info, src)
else:
if download.sha256_file(src) != info["sha256"]:
raise EngineError("That file is not the engine this app needs (checksum mismatch)")
archive = src
return self._install_archive(archive, target, info)
def side_load_weights(self, folder: Path | str) -> None:
"""Copy the weights from a folder the user supplies, each file verified."""
src = Path(folder)
dest = self.weights_dir()
dest.mkdir(parents=True, exist_ok=True)
for f in self.weights["files"]:
p = src / f["name"]
if not p.is_file() or download.sha256_file(p) != f["sha256"]:
raise EngineError(f"{f['name']} is missing from that folder or is not the right file")
for f in self.weights["files"]:
shutil.copy2(src / f["name"], dest / f["name"])
# ---- removal -------------------------------------------------------------------
def remove(self) -> None:
"""The engine, its weights and any unfinished downloads."""
(self.root / "installed.json").unlink(missing_ok=True)
if self.root.exists():
for child in self.root.iterdir():
if child.is_dir():
shutil.rmtree(child, ignore_errors=True)
elif child.name != "installed.json":
child.unlink(missing_ok=True)
_DEFAULT: "EngineManager | None" = None
def default_manager() -> EngineManager:
"""The app's one manager (the routes and the batch share it)."""
global _DEFAULT
if _DEFAULT is None:
_DEFAULT = EngineManager()
return _DEFAULT
def probe(executable: Path, timeout: float = 120) -> dict:
"""Run `engine info` — proves the unpacked engine actually starts."""
try:
out = subprocess.run([str(executable), "info"], capture_output=True, text=True, timeout=timeout,
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
except (OSError, subprocess.SubprocessError) as ex:
raise EngineError(f"The engine would not start: {ex}") from ex
for line in out.stdout.splitlines():
try:
msg = json.loads(line)
except ValueError:
continue
if msg.get("event") == "info":
return msg
raise EngineError("The engine started but did not identify itself")
-234
View File
@@ -1,234 +0,0 @@
"""Driving the stem engine: one `serve` process per batch.
The engine's protocol is documented in `engine/konduktor_engine/serve.py`.
Audio crosses as raw planar float32 files in a work folder.
Lifetime is the part that must not go wrong — a batch can run for hours:
* The engine ends itself when its stdin closes, so if this backend dies the
engine follows. On Windows it is ALSO put in a Job Object that kills it
when the last handle closes, which covers a hard kill of the backend.
* Cancel is a message (the model stays loaded); `close()` ends the process.
* The machine is kept awake for the batch — macOS `caffeinate` tied to the
engine's pid, Windows `SetThreadExecutionState` on the calling thread —
or a laptop sleeping at 1 am stops a 4-hour conversion at track 30.
* stderr is drained on a thread (a full pipe would block the engine) and its
tail kept, so an engine crash can be reported with its reason.
"""
from __future__ import annotations
import collections
import json
import queue
import shutil
import subprocess
import sys
import threading
import time
from contextlib import contextmanager
from pathlib import Path
from typing import Callable
import numpy as np
from .engine_manager import EngineError
SOURCES = ("drums", "bass", "other", "vocals")
class EngineCancelled(Exception):
pass
def _job_object_kill_on_close(pid_handle) -> object | None:
"""Windows: a Job Object with KILL_ON_JOB_CLOSE holding the engine. The
returned handle must stay referenced for as long as the engine may live."""
if sys.platform != "win32":
return None
try:
import ctypes
from ctypes import wintypes
k32 = ctypes.windll.kernel32
class IO_COUNTERS(ctypes.Structure):
_fields_ = [(n, ctypes.c_ulonglong) for n in (
"ReadOperationCount", "WriteOperationCount", "OtherOperationCount",
"ReadTransferCount", "WriteTransferCount", "OtherTransferCount")]
class BASIC(ctypes.Structure):
_fields_ = [("PerProcessUserTimeLimit", ctypes.c_int64), ("PerJobUserTimeLimit", ctypes.c_int64),
("LimitFlags", wintypes.DWORD), ("MinimumWorkingSetSize", ctypes.c_size_t),
("MaximumWorkingSetSize", ctypes.c_size_t), ("ActiveProcessLimit", wintypes.DWORD),
("Affinity", ctypes.c_size_t), ("PriorityClass", wintypes.DWORD),
("SchedulingClass", wintypes.DWORD)]
class EXTENDED(ctypes.Structure):
_fields_ = [("BasicLimitInformation", BASIC), ("IoInfo", IO_COUNTERS),
("ProcessMemoryLimit", ctypes.c_size_t), ("JobMemoryLimit", ctypes.c_size_t),
("PeakProcessMemoryUsed", ctypes.c_size_t), ("PeakJobMemoryUsed", ctypes.c_size_t)]
job = k32.CreateJobObjectW(None, None)
info = EXTENDED()
info.BasicLimitInformation.LimitFlags = 0x2000 # JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
k32.SetInformationJobObject(job, 9, ctypes.byref(info), ctypes.sizeof(info)) # ExtendedLimitInformation
k32.AssignProcessToJobObject(job, int(pid_handle))
return job
except Exception: # noqa: BLE001 — the stdin watchdog still covers the common case
return None
@contextmanager
def keep_awake(pid: int | None = None):
"""Stop the computer sleeping while a batch runs (not the display)."""
proc = None
if sys.platform == "darwin" and pid:
try:
proc = subprocess.Popen(["caffeinate", "-i", "-w", str(pid)],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except OSError:
proc = None
elif sys.platform == "win32":
try:
import ctypes
ES_CONTINUOUS, ES_SYSTEM_REQUIRED = 0x80000000, 0x00000001
ctypes.windll.kernel32.SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED)
except Exception: # noqa: BLE001
pass
try:
yield
finally:
if proc is not None:
proc.terminate()
if sys.platform == "win32":
try:
import ctypes
ctypes.windll.kernel32.SetThreadExecutionState(0x80000000)
except Exception: # noqa: BLE001
pass
class EngineProcess:
"""One running `serve`. Not thread-safe: one batch drives it."""
def __init__(self, executable: Path | str, weights: Path | str, *, device: str = "auto",
ready_timeout: float = 180) -> None:
flags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
self.proc = subprocess.Popen(
[str(executable), "serve", "--weights", str(weights), "--device", device],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, bufsize=1, creationflags=flags,
)
self._job = _job_object_kill_on_close(getattr(self.proc, "_handle", 0))
self._messages: "queue.Queue[dict | None]" = queue.Queue()
self._stderr: collections.deque[str] = collections.deque(maxlen=40)
threading.Thread(target=self._read_stdout, daemon=True, name="engine-stdout").start()
threading.Thread(target=self._read_stderr, daemon=True, name="engine-stderr").start()
self.device = device
msg = self._next(ready_timeout)
if msg is None or msg.get("event") != "ready":
self.close()
raise EngineError(f"The stem engine did not start: {self._reason(msg)}")
self.device = msg.get("device", device)
self._n = 0
# ---- plumbing ---------------------------------------------------------------
def _read_stdout(self) -> None:
for line in self.proc.stdout:
try:
self._messages.put(json.loads(line))
except ValueError:
self._stderr.append(line.rstrip())
self._messages.put(None) # the engine closed its output: it has exited
def _read_stderr(self) -> None:
for line in self.proc.stderr:
self._stderr.append(line.rstrip())
def _next(self, timeout: float | None) -> dict | None:
try:
return self._messages.get(timeout=timeout)
except queue.Empty:
return {"event": "timeout"}
def _reason(self, msg: dict | None) -> str:
if msg and msg.get("message"):
return msg["message"]
tail = [l for l in self._stderr if l.strip()][-3:]
return " / ".join(tail) or "no reason given"
def _send(self, **msg) -> None:
try:
self.proc.stdin.write(json.dumps(msg) + "\n")
self.proc.stdin.flush()
except (BrokenPipeError, OSError, ValueError) as ex:
raise EngineError(f"The stem engine has stopped: {self._reason(None)}") from ex
# ---- the one command ------------------------------------------------------------
def separate(self, pcm: np.ndarray, work: Path | str, *, seed: int = 0,
on_progress: Callable[[float], None] = lambda f: None,
cancelled: Callable[[], bool] = lambda: False) -> list[np.ndarray]:
"""Four stems in `SOURCES` order, each shaped like `pcm` (2, n)."""
work = Path(work)
work.mkdir(parents=True, exist_ok=True)
self._n += 1
rid = f"t{self._n}"
mix = work / f"{rid}.f32"
np.ascontiguousarray(pcm, dtype=np.float32).tofile(mix)
out = work / rid
self._send(cmd="separate", id=rid, input=str(mix), samples=int(pcm.shape[1]),
output_dir=str(out), seed=seed)
asked_to_stop = False
try:
while True:
if cancelled() and not asked_to_stop:
self._send(cmd="cancel", id=rid)
asked_to_stop = True
msg = self._next(0.5)
if msg is None:
raise EngineError(f"The stem engine stopped: {self._reason(None)}")
if msg.get("event") == "timeout" or msg.get("id") not in (rid, None):
continue
event = msg.get("event")
if event == "progress":
on_progress(float(msg.get("fraction", 0.0)))
elif event == "done":
stems = [np.fromfile(out / f"{name}.f32", dtype=np.float32).reshape(2, -1)
for name in SOURCES]
# ~100 MB of raw float per minute of audio: never leave it.
shutil.rmtree(out, ignore_errors=True)
return stems
elif event == "cancelled":
raise EngineCancelled()
elif event == "error":
raise EngineError(f"Separation failed: {self._reason(msg)}")
finally:
mix.unlink(missing_ok=True)
def close(self) -> None:
try:
if self.proc.stdin:
self.proc.stdin.close() # the engine ends itself on EOF
except OSError:
pass
try:
self.proc.wait(timeout=5)
except subprocess.TimeoutExpired:
self.proc.kill()
self.proc.wait(timeout=5)
def __enter__(self):
return self
def __exit__(self, *exc):
self.close()
def wait_until(predicate: Callable[[], bool], timeout: float) -> bool:
end = time.time() + timeout
while time.time() < end:
if predicate():
return True
time.sleep(0.02)
return predicate()
-237
View File
@@ -1,237 +0,0 @@
"""Conversions that are done on disk but not yet committed by a Save.
A Convert to Stems batch leaves, per track: a stem file, and — in Replace mode —
the original PARKED beside it (`.<name>.<ext>.konduktor-parked`, the same
folder, so the rename is atomic and nothing looks like audio). The collection
swap itself is an ordinary unsaved edit. So the files must follow what happens
to the edits:
* **Save** commits them: parked originals are deleted (the user chose Replace,
and was told Save deletes them), export sets follow the new ids.
* **Discard** — or opening another library, after its confirm — undoes them:
originals go back under their own names, the stem files are removed.
* **A crash** leaves this ledger on disk. The next open of the library
decides each item from the SAVED collection: if it names the stem file the
swap was committed (finish deleting the original), otherwise it was not
(put the original back). Verified stem files of an uncommitted item are
kept — renamed to their `.konduktor-partial` name, so neither the user nor
Traktor mistakes them for finished files — and a later batch converting the
same source reuses one instead of spending minutes separating it again.
The ledger is Konduktor's own curated state, written atomically
(`paths.write_json`), one file per library id. Every step is taken from what is
actually ON DISK, never from the recorded state alone: a crash can fall between
any two renames.
"""
from __future__ import annotations
import os
import threading
import time
from pathlib import Path
from .. import paths
PARTIAL = ".konduktor-partial"
PARKED = ".konduktor-parked"
def parked_name(original: Path) -> Path:
return original.with_name(f".{original.name}{PARKED}")
def partial_name(stem: Path) -> Path:
return stem.with_name(stem.name + PARTIAL)
def source_facts(path: Path) -> dict | None:
try:
st = path.stat()
except OSError:
return None
return {"size": st.st_size, "mtime_ns": st.st_mtime_ns}
def _replace_no_overwrite(src: Path, dst: Path) -> None:
"""Rename refusing to overwrite: POSIX link+unlink (link fails if dst
exists), Windows rename (which already refuses)."""
if os.name == "nt":
os.rename(src, dst)
return
os.link(src, dst)
os.unlink(src)
def _retrying(fn, *, attempts: int = 6, delay: float = 0.25):
"""Windows cannot rename a file another process has open (Traktor, the
deck's stream, an antivirus scan of a file just written): retry briefly."""
for i in range(attempts):
try:
return fn()
except PermissionError:
if os.name != "nt" or i == attempts - 1:
raise
time.sleep(delay * (2 ** i))
class Pending:
"""The ledger for ONE library."""
def __init__(self, library_id: str | None) -> None:
self.library_id = library_id
self._lock = threading.RLock()
self._path = (paths.app_data_dir() / "stems" / f"pending-{library_id}.json") if library_id else None
data = paths.read_json(self._path, None) if self._path else None
self.items: list[dict] = (data or {}).get("items", [])
self.leftovers: list[dict] = (data or {}).get("leftovers", [])
# ---- persistence ----------------------------------------------------------
def _write(self) -> None:
if self._path is None:
return
if not self.items and not self.leftovers:
self._path.unlink(missing_ok=True)
return
self._path.parent.mkdir(parents=True, exist_ok=True)
paths.write_json(self._path, {"items": self.items, "leftovers": self.leftovers})
def add(self, item: dict) -> dict:
with self._lock:
self.items.append(item)
self._write()
return item
def update(self, item: dict, **fields) -> None:
with self._lock:
item.update(fields)
self._write()
def drop(self, items: list[dict]) -> None:
with self._lock:
ids = {id(i) for i in items}
self.items = [i for i in self.items if id(i) not in ids]
self._write()
# ---- what the rest of the app asks ----------------------------------------------
def swapped(self) -> list[dict]:
return [i for i in self.items if i.get("state") == "swapped"]
def blocking(self) -> bool:
"""Conversions awaiting Save or Discard — while there are any, import,
remap, reload and history restore must refuse: each would save or drop
the swap as a side effect."""
return bool(self.swapped())
def summary(self) -> dict:
parked = [Path(i["parked"]) for i in self.swapped() if i.get("parked")]
return {"tracks": len(self.swapped()),
"parked": len(parked),
"bytes": sum(p.stat().st_size for p in parked if p.exists())}
# ---- leftovers (reuse after a crash) -----------------------------------------------
def find_leftover(self, source: Path) -> dict | None:
facts = source_facts(source)
for lo in self.leftovers:
if lo["source"] == str(source) and lo.get("facts") == facts and Path(lo["partial"]).is_file():
return lo
return None
def forget_leftover(self, leftover: dict, *, delete: bool) -> None:
with self._lock:
if delete:
Path(leftover["partial"]).unlink(missing_ok=True)
self.leftovers = [lo for lo in self.leftovers if lo is not leftover]
self._write()
def _keep_as_leftover(self, item: dict) -> None:
"""A verified stem file whose swap was not committed: keep it under its
partial name for reuse (rather than hours of separation lost)."""
stem = Path(item["stem"])
partial = partial_name(stem)
try:
if _published(item) and stem.is_file() and not partial.exists():
os.replace(stem, partial)
except OSError:
return
if partial.is_file() and item.get("written"):
self.leftovers.append({"source": item["source"], "facts": item.get("facts"),
"partial": str(partial), "written": item["written"]})
# ---- Save / Discard / recovery ---------------------------------------------------
def commit(self) -> dict[str, str]:
"""After a successful Save: delete what the swap replaced. Returns the
repoint renames so the caller retargets export sets."""
renames: dict[str, str] = {}
with self._lock:
for item in self.swapped():
if item.get("parked"):
try:
Path(item["parked"]).unlink(missing_ok=True)
except OSError:
pass # a file still open on Windows: recovery tries again
if item.get("mode") == "repoint" and item.get("new_id"):
renames[item["track_id"]] = item["new_id"]
item["state"] = "committed"
self.items = [i for i in self.items if i.get("state") != "committed"
or (i.get("parked") and Path(i["parked"]).exists())]
self._write()
return renames
def restore(self) -> int:
"""Undo every uncommitted conversion: originals back, stem files gone.
Returns how many originals were put back."""
restored = 0
with self._lock:
for item in list(self.items):
restored += self._undo(item, keep_leftover=False)
self.items = []
self._write()
return restored
def recover(self, is_committed) -> dict:
"""At open, after a crash: decide each leftover item from the SAVED
collection (`is_committed(item)` — does it name the stem file?)."""
report = {"committed": 0, "restored": 0, "kept": 0}
with self._lock:
before = len(self.leftovers)
for item in list(self.items):
if item.get("new_id") and is_committed(item):
if item.get("parked"):
Path(item["parked"]).unlink(missing_ok=True)
report["committed"] += 1
else:
report["restored"] += self._undo(item, keep_leftover=True)
report["kept"] = len(self.leftovers) - before
self.items = []
self._write()
return report
def _undo(self, item: dict, *, keep_leftover: bool) -> int:
"""Put one item's files back as they were. Filesystem-driven."""
restored = 0
original = Path(item["source"])
parked = Path(item["parked"]) if item.get("parked") else None
if parked is not None and parked.exists() and not original.exists():
_retrying(lambda: _replace_no_overwrite(parked, original))
restored = 1
stem = Path(item["stem"])
if keep_leftover and item.get("written"):
self._keep_as_leftover(item)
else:
try:
# Only a stem file THIS batch published is ours to delete: before
# that, a file at the target name belongs to someone else.
if _published(item):
stem.unlink(missing_ok=True)
partial_name(stem).unlink(missing_ok=True) # unverified: worthless
except OSError:
pass
return restored
def _published(item: dict) -> bool:
return item.get("state") in ("published", "parked", "swapped", "committed")
__all__ = ["PARKED", "PARTIAL", "Pending", "parked_name", "partial_name", "source_facts",
"_replace_no_overwrite", "_retrying"]
-75
View File
@@ -1,75 +0,0 @@
"""The deck's stem audio: one stream of a stem file, as a file of its own.
A browser decodes only the FIRST audio stream of an MP4, so the deck cannot get
at a stem file's stems from the file itself. Each is copied out (packets, not
re-encoded — `stem_file.extract_stream`) into a small cache in app-data, keyed
by the source's path, size and mtime, so an edited or replaced file is never
served stale and loading the same track twice costs nothing the second time.
The cache is bounded (`LIMIT` bytes, least recently used first) — a stem is
2-10 MB, so the limit holds a few hundred tracks' worth. Files are written as a
partial then renamed, so two requests racing for the same stem, or a crash
mid-write, can never serve a truncated file.
"""
from __future__ import annotations
import hashlib
import os
import threading
from pathlib import Path
from .. import paths
from ..core import stem_file
LIMIT = 2 * 1024 ** 3
_lock = threading.Lock()
def root() -> Path:
d = paths.app_data_dir() / "stems" / "playback"
d.mkdir(parents=True, exist_ok=True)
return d
def _key(path: Path, stream: int) -> str:
st = path.stat()
raw = f"{path.resolve()}\0{st.st_size}\0{st.st_mtime_ns}\0{stream}".encode()
return hashlib.sha256(raw).hexdigest()[:32]
def stem_file_for(path: Path, stem: int) -> Path:
"""The cached single-stream file for stem `stem` (0-based: stream stem+1)."""
path = Path(path)
stream = stem + 1
target = root() / f"{_key(path, stream)}.m4a"
if target.exists():
os.utime(target) # most recently used
return target
partial = target.with_name(f"{target.name}.{os.getpid()}.{threading.get_ident()}.part")
try:
with open(partial, "wb") as fp:
stem_file.extract_stream(path, stream, fp)
os.replace(partial, target)
finally:
partial.unlink(missing_ok=True)
_prune(keep=target)
return target
def _prune(keep: Path) -> None:
with _lock:
files = []
for p in root().glob("*.m4a"):
try:
st = p.stat()
except OSError:
continue
files.append((st.st_mtime, st.st_size, p))
total = sum(size for _, size, _ in files)
for _, size, p in sorted(files):
if total <= LIMIT:
break
if p == keep:
continue
p.unlink(missing_ok=True)
total -= size
-13
View File
@@ -1,13 +0,0 @@
{
"comment": "The htdemucs_ft weights, pinned. Fetched from the official Hugging Face repo on each machine and verified here; never re-hosted (their licence is ambiguous — see the stem-conversion discussion log). Konduktor's engine manager and CI both read this file.",
"repo": "adefossez/HTDemucs-ft",
"revision": "d74ac89c3a1e874fc78f152555cf4d8533f06cd4",
"url": "https://huggingface.co/{repo}/resolve/{revision}/{name}",
"files": [
{"name": "htdemucs_ft.yaml", "size": 149, "sha256": "69470b8c1bbd674437b51bc9fb491327a10ab0396b702c93389b9cf750016346"},
{"name": "f7e0c4bc.safetensors", "size": 84025440, "sha256": "2c85ab3c62dd6edd8e0b965e38b16fd1cdde357cc25de6b6bc9ce7c83f60925f"},
{"name": "d12395a8.safetensors", "size": 84025440, "sha256": "5b01a97567ae9a3178a6236fb520251045c03eb8834bc8c24a4eec11d6c8fb56"},
{"name": "92cfc3b6.safetensors", "size": 84025440, "sha256": "a241863551f30d01c42bd7b97da40839922ead3acb0f1fcab25682f55b4eeb59"},
{"name": "04573f0d.safetensors", "size": 84025440, "sha256": "68854b0d7c2b3274723b5761f6fd9f5aec5f1bcd3f0de7c1669546fdb7871b7c"}
]
}
-3
View File
@@ -31,6 +31,3 @@ traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git
# deprecated alias and is removed in 0.6.0, so the Rekordbox adapter keeps
# running as-is — but that rename is the thing to fix before taking 0.6.
pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git
# The stem engine and its weights are downloaded over HTTPS by the sidecar; a
# frozen Python on macOS has no system CA bundle of its own.
certifi>=2024.7
+1 -1
View File
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
source .venv/bin/activate
fail=0
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py test_discard.py; do
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py test_discard.py; do
echo "──────────────────────────────────────────"
echo "▶ $t"
echo "──────────────────────────────────────────"
-107
View File
@@ -1,107 +0,0 @@
"""Test helpers for Convert to Stems: a FAKE engine and generated audio.
Not a test itself. The fake engine speaks the real `serve` protocol
(`engine/konduktor_engine/serve.py`) — no torch — returning scaled copies of
the mix as its "stems". Environment switches, read per separation:
FAKE_DELAY seconds per progress step (10 steps) FAKE_ERROR reply "error"
FAKE_CRASH die mid-request (stderr says why) FAKE_COUNT append a line
per separation to this file
"""
from __future__ import annotations
import hashlib
import json
import stat
import sys
from pathlib import Path
import av
import numpy as np
FAKE_ENGINE = r'''#!{python}
import json, os, queue, sys, threading, time
import numpy as np
if sys.argv[1] == "info":
print(json.dumps({{"event": "info", "version": "{version}", "devices": ["cpu"]}}))
sys.exit(0)
print(json.dumps({{"event": "ready", "device": "cpu"}}), flush=True)
cancel, Q = set(), queue.Queue()
def reader():
for line in sys.stdin:
m = json.loads(line)
(cancel.add(m["id"]) if m.get("cmd") == "cancel" else Q.put(m))
os._exit(0)
threading.Thread(target=reader, daemon=True).start()
while True:
m = Q.get()
rid = m["id"]
x = np.fromfile(m["input"], dtype=np.float32).reshape(2, -1)
if os.environ.get("FAKE_COUNT"):
with open(os.environ["FAKE_COUNT"], "a") as f:
f.write(rid + "\n")
if os.environ.get("FAKE_CRASH"):
print("boom: out of cheese", file=sys.stderr, flush=True); os._exit(3)
if os.environ.get("FAKE_ERROR"):
print(json.dumps({{"id": rid, "event": "error", "message": "bad input"}}), flush=True); continue
stopped = False
for i in range(10):
time.sleep(float(os.environ.get("FAKE_DELAY", "0.005")))
if rid in cancel:
print(json.dumps({{"id": rid, "event": "cancelled"}}), flush=True); stopped = True; break
print(json.dumps({{"id": rid, "event": "progress", "fraction": (i + 1) / 10}}), flush=True)
if stopped:
continue
os.makedirs(m["output_dir"], exist_ok=True)
for k, g in zip(("drums", "bass", "other", "vocals"), (0.5, 0.25, -0.2, 0.1)):
(x * g).astype(np.float32).tofile(os.path.join(m["output_dir"], k + ".f32"))
print(json.dumps({{"id": rid, "event": "done", "device": "cpu"}}), flush=True)
'''
def write_fake_engine(path: Path, version: str) -> Path:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(FAKE_ENGINE.format(python=sys.executable, version=version))
path.chmod(path.stat().st_mode | stat.S_IEXEC)
return path
def install_fake_engine(root: Path):
"""An `EngineManager` whose engine is the fake one and whose weights are two
tiny files — `ready()` without any download."""
from konduktor.stems import engine_manager as em
files = [("htdemucs_ft.yaml", b"models: [a]\n"), ("a.safetensors", b"\0" * 64)]
weights = {"repo": "x/y", "revision": "fake", "url": "http://invalid/{name}",
"files": [{"name": n, "size": len(d), "sha256": hashlib.sha256(d).hexdigest()} for n, d in files]}
mgr = em.EngineManager(root=root, weights=weights, target="macos-arm64")
exe = write_fake_engine(root / mgr.version / "macos-arm64" / "konduktor-engine" / "konduktor-engine", mgr.version)
(root / "installed.json").write_text(json.dumps(
{"version": mgr.version, "target": "macos-arm64", "size": 1, "executable": str(exe), "info": {}}))
wd = mgr.weights_dir()
wd.mkdir(parents=True, exist_ok=True)
for n, d in files:
(wd / n).write_bytes(d)
assert mgr.ready()
return mgr
def make_mp3(path: Path, seconds: float = 4, seed: int = 3) -> Path:
"""An MP3 WITH a Xing/Info header (so Traktor's 2257-sample offset applies)."""
sr = 44100
rng = np.random.default_rng(seed)
n = int(sr * seconds)
x = np.zeros((2, n), np.float32)
for start in range(sr // 2, n - sr // 10, sr // 2):
x[:, start:start + 2000] = rng.uniform(-0.5, 0.5, (2, 2000))
path.parent.mkdir(parents=True, exist_ok=True)
with av.open(str(path), "w", format="mp3") as c:
s = c.add_stream("libmp3lame", rate=sr, layout="stereo")
s.bit_rate = 320_000
for o in range(0, n, 1152):
f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, o:o + 1152]), format="fltp", layout="stereo")
f.sample_rate, f.pts = sr, o
for p in s.encode(f):
c.mux(p)
for p in s.encode(None):
c.mux(p)
return path
+5 -15
View File
@@ -118,24 +118,14 @@ else:
RekordboxAdapter(work).track(track.id).title == title)
del before
print("== a OneLibrary drive (editable as THE library) ==")
# A COPY: an editable drive must never be the checked-in fixture.
print("== read-only ==")
os.environ["KONDUKTOR_NML"] = ""
drive = Path(tempfile.mkdtemp()) / "Dingus"
shutil.copytree(FIXTURE, drive, ignore=shutil.ignore_patterns("rekordbox-edited"))
db_file = drive / "PIONEER" / "rekordbox" / "exportLibrary.db"
on_disk = db_file.read_bytes()
track_id = "/Contents/Loopmasters/UnknownAlbum/Demo Track 1.mp3"
with TestClient(main.app) as c:
r = c.post("/api/library/open", json={"path": str(drive)})
check("the drive opens as the library", r.status_code == 200, f"{r.status_code} {r.text[:200]}")
r = c.post("/api/library/open", json={"path": str(FIXTURE)})
if r.status_code == 200:
c.patch("/api/tracks", json={"track_id": track_id, "fields": {"title": "Thrown away"}})
check("the edit is held", main.STATE.adapter.dirty)
check("discard succeeds", c.post("/api/discard").status_code == 200)
check("and drops the edit",
main.STATE.adapter.track(track_id).title.startswith("Demo Track 1"))
check("the drive was never written", db_file.read_bytes() == on_disk)
check("a read-only library has nothing to discard (409)", c.post("/api/discard").status_code == 409)
else:
print(f" (skipped: fixture did not open: {r.status_code})")
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
-330
View File
@@ -1,330 +0,0 @@
"""The stem engine manager and process, against a LOCAL server and a FAKE engine.
No network, no torch: a tiny HTTP server (Range-aware, and able to ignore Range)
serves a fake engine archive split into parts plus fake weights, and the fake
engine is a script speaking the real protocol. Pins what fails silently:
* a download resumes from its `.part`, restarts if the server ignores the
range, and never keeps a file whose checksum is wrong;
* an install counts only once parts, archive AND a started engine all check
out — a corrupt part or a wrong-version engine leaves nothing installed;
* side-loading verifies against the release manifest; weights are verified;
* the process driver relays progress, cancels without killing the engine,
reports a crash WITH its reason, and ends the engine on close;
* the CUDA engine is offered only for a new enough driver and card.
"""
from __future__ import annotations
import hashlib
import http.server
import json
import os
import stat
import sys
import tarfile
import tempfile
import threading
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-enginemgr-appdata-")
import numpy as np # noqa: E402
from konduktor.stems import download, engine_manager as em # noqa: E402
from konduktor.stems.engine_process import EngineCancelled, EngineProcess, keep_awake # noqa: E402
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
from stem_test_support import FAKE_ENGINE # noqa: E402 — the one fake engine, shared
class Handler(http.server.BaseHTTPRequestHandler):
root: Path
ignore_range = False
requests: list = []
def log_message(self, *a):
pass
def do_GET(self):
path = self.root / self.path.lstrip("/")
type(self).requests.append((self.path, self.headers.get("Range")))
if not path.is_file():
self.send_error(404)
return
data = path.read_bytes()
rng = self.headers.get("Range")
if rng and not type(self).ignore_range:
start = int(rng.split("=")[1].split("-")[0])
body = data[start:]
self.send_response(206)
self.send_header("Content-Range", f"bytes {start}-{len(data) - 1}/{len(data)}")
else:
body = data
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
try:
self.wfile.write(body)
except (BrokenPipeError, ConnectionResetError):
pass # the cancel test hangs up mid-download, on purpose
def sha(b: bytes) -> str:
return hashlib.sha256(b).hexdigest()
tmp = Path(tempfile.mkdtemp(prefix="konduktor-enginemgr-"))
site = tmp / "site"
site.mkdir()
Handler.root = site
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
BASE = f"http://127.0.0.1:{server.server_address[1]}"
print("== the weights manifest ==")
repo_copy = json.loads((Path(__file__).resolve().parents[1] / "engine" / "weights.json").read_text())
check("the backend's weights.json is the engine's (no drift)", em.WEIGHTS == repo_copy)
print("== download: resume, restart, verify, cancel ==")
blob = os.urandom(3_000_000)
(site / "blob.bin").write_bytes(blob)
dest = tmp / "dl" / "blob.bin"
dest.parent.mkdir()
(dest.parent / "blob.bin.part").write_bytes(blob[:1_000_000])
seen = []
Handler.requests.clear()
download.fetch(f"{BASE}/blob.bin", dest, sha256=sha(blob), size=len(blob), on_bytes=seen.append)
check("a download resumes from its .part with a Range request",
Handler.requests[-1][1] == "bytes=1000000-" and dest.read_bytes() == blob, str(Handler.requests[-1]))
check("…and progress counts the resumed bytes once", sum(seen) == len(blob), str(sum(seen)))
dest.unlink()
(dest.parent / "blob.bin.part").write_bytes(blob[:1_000_000])
Handler.ignore_range = True
seen.clear()
download.fetch(f"{BASE}/blob.bin", dest, sha256=sha(blob), size=len(blob), on_bytes=seen.append)
Handler.ignore_range = False
check("a server that ignores Range makes it start over, correctly", dest.read_bytes() == blob and sum(seen) == len(blob))
dest.unlink()
try:
download.fetch(f"{BASE}/blob.bin", dest, sha256="0" * 64, size=len(blob))
check("a checksum mismatch is refused", False, "kept it")
except download.DownloadError:
check("a checksum mismatch is refused, and nothing is kept",
not dest.exists() and not (dest.parent / "blob.bin.part").exists())
calls = {"n": 0}
def cancel_soon():
calls["n"] += 1
return calls["n"] > 1
try:
download.fetch(f"{BASE}/blob.bin", dest, sha256=sha(blob), size=len(blob), cancelled=cancel_soon)
check("a cancelled download stops", False, "finished")
except download.DownloadCancelled:
check("a cancelled download stops, keeping its .part to resume", (dest.parent / "blob.bin.part").exists()
and not dest.exists())
print("== engine install ==")
VERSION = em.CONFIG["version"]
def make_release(version_reported: str, name: str, parts: int = 2) -> dict:
"""A fake engine archive, split into `parts`, plus its manifest entry."""
src = tmp / f"build-{name}"
exe = src / "konduktor-engine" / "konduktor-engine"
exe.parent.mkdir(parents=True, exist_ok=True)
exe.write_text(FAKE_ENGINE.format(python=sys.executable, version=version_reported))
exe.chmod(exe.stat().st_mode | stat.S_IEXEC)
archive = tmp / f"{name}.tar.gz"
with tarfile.open(archive, "w:gz") as tar:
tar.add(src / "konduktor-engine", arcname="konduktor-engine")
data = archive.read_bytes()
size = -(-len(data) // parts)
entry = {"archive": archive.name, "size": len(data), "sha256": sha(data), "unpacked_size": 1234, "parts": []}
for i in range(parts):
chunk = data[i * size:(i + 1) * size]
part = f"{name}.tar.gz.part{i:02d}"
(site / part).write_bytes(chunk)
entry["parts"].append({"name": part, "size": len(chunk), "sha256": sha(chunk)})
return entry, archive
good, good_archive = make_release(VERSION, "good")
wrong, _ = make_release("0.0.1", "wrong")
config = dict(em.CONFIG, manifest_url=f"{BASE}/manifest-{{version}}.json", asset_url=f"{BASE}/{{name}}")
(site / f"manifest-{VERSION}.json").write_text(json.dumps(
{"version": VERSION, "targets": {"macos-arm64": good, "windows-x64-cpu": wrong}}))
root = tmp / "root"
mgr = em.EngineManager(root=root, config=config, target="macos-arm64")
check("nothing is installed to begin with", mgr.installed() is None and not mgr.ready())
status = mgr.status()
check("status offers this computer's engine, with its download size",
status["offered_targets"] == ["macos-arm64"] and status["download_sizes"]["macos-arm64"] == good["size"], str(status))
got = []
rec = mgr.install_engine(on_bytes=got.append)
check("the engine installs from its parts", mgr.installed() is not None and Path(rec["executable"]).is_file())
check("…with byte progress for the whole download", sum(got) == good["size"], str(sum(got)))
check("…and the installed engine was PROBED (it started and named its version)", rec["info"]["version"] == VERSION)
check("the downloaded parts are cleaned up", not any((root / "downloads").glob("*")))
mgr2 = em.EngineManager(root=tmp / "root2", config=config, target="windows-x64-cpu")
try:
mgr2.install_engine()
check("an engine reporting the wrong version is refused", False, "installed")
except em.EngineError as ex:
check("an engine reporting the wrong version is refused, and nothing is installed",
mgr2.installed() is None and not any((tmp / "root2" / VERSION).glob("*")), str(ex))
(site / good["parts"][1]["name"]).write_bytes(b"corrupt")
mgr3 = em.EngineManager(root=tmp / "root3", config=config, target="macos-arm64")
try:
mgr3.install_engine()
check("a corrupt part is refused", False, "installed")
except (download.DownloadError, em.EngineError):
check("a corrupt part is refused, and nothing is installed", mgr3.installed() is None)
print("== side-loading ==")
mgr4 = em.EngineManager(root=tmp / "root4", config=config, target="macos-arm64")
mgr4.side_load_engine(good_archive)
check("an engine archive the user has is installed after its hash checks out", mgr4.installed() is not None)
bogus = tmp / "bogus.tar.gz"
bogus.write_bytes(b"not an engine")
try:
em.EngineManager(root=tmp / "root5", config=config, target="macos-arm64").side_load_engine(bogus)
check("a file that is not the engine is refused", False, "installed")
except em.EngineError:
check("a file that is not the engine is refused", True)
print("== weights ==")
files = [("htdemucs_ft.yaml", b"models: [a]\n"), ("a.safetensors", os.urandom(200_000))]
for name, data in files:
(site / "w" / "rev1").mkdir(parents=True, exist_ok=True)
(site / "w" / "rev1" / name).write_bytes(data)
wmanifest = {"repo": "x/y", "revision": "rev1", "url": f"{BASE}/w/{{revision}}/{{name}}",
"files": [{"name": n, "size": len(d), "sha256": sha(d)} for n, d in files]}
wm = em.EngineManager(root=tmp / "root6", config=config, weights=wmanifest, target="macos-arm64")
check("weights are not installed to begin with", not wm.weights_installed())
wm.install_weights()
check("the weights install, verified", wm.weights_installed())
side = tmp / "side-weights"
side.mkdir()
for name, data in files:
(side / name).write_bytes(data)
wm2 = em.EngineManager(root=tmp / "root7", config=config, weights=wmanifest, target="macos-arm64")
wm2.side_load_weights(side)
check("weights from a folder the user supplies are accepted when they verify", wm2.weights_installed())
(side / "a.safetensors").write_bytes(b"tampered")
try:
em.EngineManager(root=tmp / "root8", config=config, weights=wmanifest, target="macos-arm64").side_load_weights(side)
check("tampered weights are refused", False, "accepted")
except em.EngineError:
check("tampered weights are refused", True)
mgr.remove()
check("remove takes the engine away", mgr.installed() is None and not (root / VERSION).exists())
print("== CUDA is offered only where it will run ==")
G = em.NvidiaGpu
check("RTX 40-series, current driver: offered", em.cuda_suitable([G("RTX 4070", "581.08", 8.9)]) is not None)
check("an old driver: not offered", em.cuda_suitable([G("RTX 4070", "552.22", 8.9)]) is None)
check("a GTX 1060 (Pascal, 6.1): not offered", em.cuda_suitable([G("GTX 1060", "581.08", 6.1)]) is None)
check("no card: not offered", em.cuda_suitable([]) is None)
print("== the engine process ==")
exe = Path(mgr4.executable())
pcm = np.random.default_rng(0).uniform(-0.5, 0.5, (2, 44100)).astype(np.float32)
work = tmp / "work"
with EngineProcess(exe, tmp, device="cpu") as eng:
prog = []
stems = eng.separate(pcm, work, on_progress=prog.append)
check("separate returns four stems in drums/bass/other/vocals order",
len(stems) == 4 and np.allclose(stems[0], pcm * 0.5) and np.allclose(stems[3], pcm * 0.1))
check("…relaying progress", prog and prog[-1] == 1.0, str(prog))
check("…and leaves no work files behind", not any(work.rglob("*.f32")), str(list(work.rglob("*"))))
os.environ["FAKE_DELAY"] = "0.05"
try:
eng.separate(pcm, work, cancelled=lambda: True)
check("a cancel stops the track", False, "finished")
except EngineCancelled:
check("a cancel stops the track", True)
os.environ.pop("FAKE_DELAY")
check("…and the engine is still usable", len(eng.separate(pcm, work)) == 4)
proc = eng.proc
check("closing ends the engine process", proc.poll() is not None)
os.environ["FAKE_ERROR"] = "1"
with EngineProcess(exe, tmp) as eng:
try:
eng.separate(pcm, work)
check("an engine error is reported", False)
except em.EngineError as ex:
check("an engine error is reported with its message", "bad input" in str(ex), str(ex))
os.environ.pop("FAKE_ERROR")
os.environ["FAKE_CRASH"] = "1"
with EngineProcess(exe, tmp) as eng:
try:
eng.separate(pcm, work)
check("an engine crash is reported", False)
except em.EngineError as ex:
check("an engine crash is reported WITH its reason", "out of cheese" in str(ex), str(ex))
os.environ.pop("FAKE_CRASH")
if sys.platform == "darwin":
import subprocess
with EngineProcess(exe, tmp) as eng, keep_awake(eng.proc.pid):
running = subprocess.run(["pgrep", "-f", f"caffeinate -i -w {eng.proc.pid}"], capture_output=True).returncode == 0
check("the machine is kept awake while the engine runs (caffeinate)", running)
print("== the routes ==")
from fastapi.testclient import TestClient # noqa: E402
import time as _time # noqa: E402
import konduktor.main as main # noqa: E402
# A fresh, uncorrupted release for the routes (an earlier check corrupted `good`).
fresh, _ = make_release(VERSION, "fresh")
(site / f"manifest-{VERSION}.json").write_text(json.dumps({"version": VERSION, "targets": {"macos-arm64": fresh}}))
em._DEFAULT = em.EngineManager(root=tmp / "root-routes", config=config, weights=wmanifest, target="macos-arm64")
with TestClient(main.app) as c:
st = c.get("/api/stems/engine").json()
check("status: supported, nothing installed, a download size known",
st["supported"] and st["installed"] is None and st["download_sizes"]["macos-arm64"] == fresh["size"], str(st)[:300])
os.environ["FAKE_DELAY"] = "0"
gate = threading.Event()
blocker = main.JOBS.submit(main.ENGINE_JOB, lambda h: gate.wait(10))
second = c.post("/api/stems/engine/install", json={})
gate.set()
main.JOBS.wait(blocker.id, 10)
job = c.post("/api/stems/engine/install", json={}).json()
end = _time.time() + 30
while _time.time() < end:
j = c.get(f"/api/jobs/{job['id']}").json()
if j["state"] != "running":
break
_time.sleep(0.05)
check("install runs as a job counting BYTES (engine + weights)",
j["state"] == "done" and j["unit"] == "bytes"
and j["total"] == fresh["size"] + sum(f["size"] for f in wmanifest["files"]), str(j)[:300])
check("…that ends ready to convert", j["result"] == {"target": "macos-arm64", "ready": True}, str(j["result"]))
check("an install while another runs is refused (409)", second.status_code == 409, str(second.status_code))
st = c.get("/api/stems/engine").json()
check("status now shows the engine and the weights", st["installed"] is not None and st["weights"]["installed"])
r = c.post("/api/stems/engine/sideload", json={"path": str(bogus), "kind": "engine"})
check("side-loading a file that is not the engine is refused (400)", r.status_code == 400, r.text[:200])
r = c.delete("/api/stems/engine")
check("remove answers with nothing installed", r.status_code == 200 and r.json()["installed"] is None)
server.shutdown()
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
-60
View File
@@ -193,66 +193,6 @@ with TestClient(main.app, raise_server_exceptions=False) as c:
c.post("/api/folder/add/preview",
json={"track_ids": ["/etc/passwd"], "mode": "reference"}).status_code == 404)
print("== Rekordbox: the same route adds to a master.db ==")
from konduktor.adapters.rekordbox import discovery as rb_discovery
found = rb_discovery.detect_libraries()
if not found:
print(" (skipped: no Rekordbox library on this machine)")
else:
rb_src = Path(found[0]["path"]).parent
rb_dir = Path(tempfile.mkdtemp()) / "rekordbox"
rb_dir.mkdir()
for name in ("master.db", "masterPlaylists6.xml"):
if (rb_src / name).exists():
shutil.copy2(rb_src / name, rb_dir / name)
if (rb_src / "share").is_dir():
shutil.copytree(rb_src / "share", rb_dir / "share")
r = c.post("/api/library/open", json={"path": str(rb_dir / "master.db")})
check("a Rekordbox copy opens", r.status_code == 200, r.text[:300])
caps = c.get("/api/capabilities").json()
check("it advertises adding", caps["tracks"]["addable"] is True)
rb = main.require_adapter()
n_before = len(rb.tracks)
req = {"track_ids": [str(two)], "mode": "reference"}
job = wait(c, c.post("/api/folder/add", json=req).json())
check("the job finishes", job["state"] == "done", str(job))
new_ids = (job.get("result") or {}).get("track_ids") or []
check("one track was added", len(rb.tracks) == n_before + 1 and len(new_ids) == 1)
if new_ids:
check("it points at the original file", rb.audio_path(new_ids[0]) == two)
row = rb._store.content(new_ids[0])
dat = rb_dir / "share" / row.AnalysisDataPath.lstrip("/")
check("its analysis file was written", dat.is_file(), str(dat))
check("and saved, not left pending", not rb.dirty)
rb.close()
print("== a stick places its own audio; a library that cannot add refuses ==")
# A COPY: opened as THE library, a OneLibrary drive is editable.
fixture = Path(tempfile.mkdtemp()) / "onelibrary"
shutil.copytree(Path(__file__).resolve().parent / "fixtures" / "onelibrary", fixture)
r = c.post("/api/library/open", json={"path": str(fixture)})
if r.status_code == 200:
# No mode and no destination: the library decides (decision 7).
r = c.post("/api/folder/add/preview", json={"track_ids": [str(two)], "mode": "copy"})
body = r.json() if r.status_code == 200 else {}
check("a stick's preview needs no destination, and counts the copy",
r.status_code == 200 and body.get("places_audio") and body.get("copied") == 1
and body.get("in_place") == 0, f"{r.status_code} {r.text[:200]}")
adapter = main.STATE.adapter
real = adapter.capabilities
caps = real()
adapter.capabilities = lambda: caps.model_copy(
update={"tracks": caps.tracks.model_copy(update={"addable": False})})
try:
check("a library whose capabilities say it cannot add refuses the route (422)",
c.post("/api/folder/add/preview",
json={"track_ids": [str(two)], "mode": "reference"}).status_code == 422)
finally:
adapter.capabilities = real
else:
print(f" (skipped: fixture did not open — {r.status_code})")
print("== hidden entries ==")
check("AppleDouble twins are hidden", places.is_hidden(music / "._one.flac"))
check("OS housekeeping is hidden", places.is_hidden(music / ".Trashes"))
-18
View File
@@ -213,24 +213,6 @@ with tempfile.TemporaryDirectory() as d:
gate.set()
check("…and returns once it has finished", main.JOBS.wait(first.id, timeout=5) is True)
# Within-item progress: what lets the overall bar move inside a long
# track (99 % of the first of two = ~50 %), and it starts over per item.
from konduktor.jobs import Job, JobHandle
j = Job(id="x", kind="t")
h = JobHandle(j)
h.progress(done=0, total=2, fraction=0.99, status="separating 99 %")
d = j.as_dict()
check("a job reports its current item's fraction and status",
d["fraction"] == 0.99 and d["status"] == "separating 99 %", str(d))
h.progress(done=1)
check("…both reset when the next item starts", j.fraction == 0.0 and j.status == "")
h.progress(fraction=1.7)
check("…and the fraction is clamped to 0..1", j.fraction == 1.0)
from konduktor.schemas import JobStatus
r = JobStatus(**j.as_dict()).model_dump()
check("the job's response model carries fraction and status (not silently dropped)",
r["fraction"] == 1.0 and "status" in r, str(r)[:200])
check("nothing was written to disk (edits stay in memory until Save)",
work.read_bytes() == REAL.read_bytes())
+1 -2
View File
@@ -89,8 +89,7 @@ def stage(src: OneLibraryAdapter, music: Path) -> list[NewTrack]:
print("== a drive's tracks land in the collection ==")
nml, music, original = fresh_collection()
# As the app opens a device: read-only (a drive opened as THE library is editable).
source = OneLibraryAdapter(FIXTURE, read_only=True)
source = OneLibraryAdapter(FIXTURE)
dest = TraktorAdapter(nml)
before = len(dest.tracks)
items = stage(source, music)
+18 -116
View File
@@ -112,11 +112,9 @@ class _Entry(dict):
class _Tag:
"""A stand-in for `anlz_file.Tag`: a type and its decoded entries."""
def __init__(self, tag_type, entries):
self.type = tag_type
self.entries = entries
self.struct = type("S", (), {"content": type("C", (), {"entries": entries})()})()
class _Anlz:
@@ -176,49 +174,6 @@ check("nothing read from a drive claims to be editable",
all(not c.editable for c in merged))
print("== a stick rekordbox has EDITED ==")
# rekordbox 7 writes COMPACT cue entries when it edits a stick, where an export
# writes 88-byte ones: a hot cue it added is a 48-byte PCP2, a memory cue a
# 44-byte one with no colour at all. pyrekordbox raised PaddingError on the
# latter, the whole .EXT failed to parse, and the reader fell back to the .DAT —
# losing pads D-E and every colour. These files are Goober's after Ben edited it
# in rekordbox 7 (2026-10-01), trimmed to PPTH + the cue tags, byte for byte.
from konduktor.adapters.rekordbox import anlz_file # noqa: E402
EDITED = FIXTURE / "rekordbox-edited"
for f in sorted(FIXTURE.glob("PIONEER/USBANLZ/*/*/ANLZ*")) + sorted(EDITED.glob("*.*")):
raw = f.read_bytes()
if anlz_file.parse(raw).to_bytes() != raw:
check(f"{f.name} round-trips through the tag reader byte for byte", False)
break
else:
check("every analysis file round-trips through the tag reader byte for byte", True)
nemean = cues_from_anlz(anlz_file.parse_file(EDITED / "nemean.DAT"),
anlz_file.parse_file(EDITED / "nemean.EXT"))
hot = [c for c in nemean if c.role == "hotcue"]
check("the .EXT holding a 44-byte memory entry still parses: all five pads",
[c.slot for c in sorted(hot, key=lambda c: c.slot)] == [0, 1, 2, 3, 4],
str([c.slot for c in hot]))
check("and their colours survive",
{c.slot: c.color for c in hot} == {0: "#1AFF00", 1: "#00E0FF", 2: "#FF5E00",
3: "#B300FF", 4: "#FF0000"},
str({c.slot: c.color for c in hot}))
memory = sorted((c for c in nemean if c.role == "memory"), key=lambda c: (c.start, c.type))
check("a memory cue ON a memory loop's start is not merged into it",
[(round(c.start * 1000), c.type) for c in memory] == [(23, "cue"), (121402, "cue"), (121402, "loop")],
str([(c.start, c.type) for c in memory]))
check("the compact memory entry has no colour, rather than black",
all(c.color is None for c in memory))
demo2 = cues_from_anlz(anlz_file.parse_file(EDITED / "demo-track-2.DAT"),
anlz_file.parse_file(EDITED / "demo-track-2.EXT"))
pad_e = [c for c in demo2 if c.slot == 4]
check("a 48-byte hot cue (added in rekordbox) reads with its colour",
len(pad_e) == 1 and pad_e[0].color == "#00FF30" and round(pad_e[0].start * 1000) == 47525,
str(pad_e))
# ---- the real drive ------------------------------------------------------
if not (FIXTURE / "PIONEER" / "rekordbox" / "exportLibrary.db").is_file():
print(f"\nSKIP: no fixture drive at {FIXTURE}")
@@ -239,13 +194,7 @@ fake.parent.mkdir(parents=True)
shutil.copy(Path(__file__), fake) # a plain text file wearing the right name
check("can_open rejects a non-database in the right place", not driver.can_open(fake.parent.parent.parent))
# A drive is now WRITABLE, so the adapter under test opens a COPY — a stray save
# here once rewrote the checked-in fixture. The copy keeps the fixture's folder
# name, which is what the drive's label is checked against.
DRIVE = Path(tempfile.mkdtemp(prefix="konduktor-ol-drive-")) / FIXTURE.name
shutil.copytree(FIXTURE, DRIVE)
FIXTURE_DB_BYTES = (FIXTURE / "PIONEER" / "rekordbox" / "exportLibrary.db").read_bytes()
adapter = OneLibraryAdapter(DRIVE)
adapter = OneLibraryAdapter(FIXTURE)
check("implements the LibraryAdapter protocol", isinstance(adapter, LibraryAdapter))
print("== the projection ==")
@@ -267,7 +216,7 @@ check("comment comes through", (one.comment or "").startswith("Tracks by"))
check("the track id is its drive-relative path",
one.id == "/Contents/Loopmasters/UnknownAlbum/Demo Track 1.mp3", one.id)
check("filepath resolves under the mount point",
one.filepath == str(DRIVE / "Contents/Loopmasters/UnknownAlbum/Demo Track 1.mp3"))
one.filepath == str(FIXTURE / "Contents/Loopmasters/UnknownAlbum/Demo Track 1.mp3"))
check("and the resolved file is really there", Path(one.filepath).is_file())
check("audio_path agrees with the projection", str(adapter.audio_path(one.id)) == one.filepath)
@@ -317,12 +266,7 @@ memory = [c for c in cues.cues if c.role == "memory"]
check("the memory cue is preserved", len(memory) == 1)
check("it has no slot", memory[0].slot is None)
check("it is the same loop, at the same place", abs(memory[0].start - (40.0 - OFF)) < 0.001)
check("on an editable drive every hot cue is editable, no memory cue is",
all(c.editable == (c.role == "hotcue") for c in cues.cues))
_browse = OneLibraryAdapter(DRIVE, read_only=True)
check("on a browsing drive no cue is editable",
all(not c.editable for c in _browse.track_cues(one.id).cues))
_browse.close()
check("no cue on a read-only drive is editable", all(not c.editable for c in cues.cues))
print("== playlists ==")
tree = adapter.playlist_tree()
@@ -336,8 +280,8 @@ check("its entries are track ids, in order",
entries == [t.id for t in (adapter.playlist_tracks(node.id) or [])])
check("and they resolve to the two tracks", len(adapter.playlist_tracks(node.id)) == 2)
check("a root playlist's parent 0 is not treated as a real node id", len(tree) == 1)
check("on an editable drive a playlist offers every edit",
all(n.can_rename and n.can_delete and n.can_add_tracks and n.can_reorder for n in tree))
check("nothing on the drive claims to be editable",
not any(n.can_rename or n.can_delete or n.can_add_tracks or n.can_reorder for n in tree))
check("entries for an unknown node are None", adapter.playlist_entries("999999") is None)
print("== capabilities gate the UI ==")
@@ -345,44 +289,27 @@ caps = adapter.capabilities()
check("platform is onelibrary", caps.platform == "onelibrary")
# The distinction the whole capability system exists for: this is a roadmap gap,
# not a protective refusal, and the UI must word the two differently.
check("opened as THE library, a drive is writable", caps.writable is True and caps.readonly_cause is None)
check("the library is read-only", caps.writable is False)
check("because the platform is incomplete, not because of a sync state",
caps.readonly_cause == "platform_incomplete")
check("the version is the drive's dbVersion", caps.version == "1000", str(caps.version))
# The per-feature flags still describe the FORMAT. Blanking them to false would
# claim OneLibrary has no hot cues, which is not what read-only means.
check("the format is still reported as having hot cues", caps.cues.hotcue_slots == 8)
check("cue colour is rekordbox's palette (rekordbox draws the PCP2 code)",
caps.cues.color == "palette" and len(caps.cues.palette) == 16)
check("cue colour is free RGB here, unlike master.db's palette", caps.cues.color == "free")
check("loops are a cue type, not a separate bank", caps.cues.loops == "cue_type")
check("memory cues are acknowledged", caps.cues.memory_cues is True)
check("the grid is flexible even though we do not write it", caps.grid.flexible is True)
check("hot cues and the grid are editable", caps.cues.editable and caps.grid.editable)
check("the editable fields are the Rekordbox adapter's set",
caps.tracks.editable_fields == sorted(["title", "artist", "album", "genre", "label",
"remixer", "comment", "rating", "release_date"]),
str(caps.tracks.editable_fields))
check("tracks can be added and removed, the library placing the audio",
caps.tracks.addable and caps.tracks.removable and caps.tracks.places_audio)
check("playlists can be reordered", caps.playlists.reorder is True)
check("nothing is editable", not caps.cues.editable and not caps.grid.editable)
check("no metadata field is editable", caps.tracks.editable_fields == [])
check("ratings are 0-5", caps.tracks.rating_max == 5)
check("folders are supported by the format", caps.playlists.folders is True)
check("a drive carries no smart playlists", caps.playlists.smart == "none")
check("drives are not versioned", caps.save.history is False)
check("another app's write is caught at save, not risked", caps.save.overwrite_risk == "none")
check("Save is named for the drive", caps.save.app_name == FIXTURE.name, caps.save.app_name)
check("nothing else can overwrite it, because we never write", caps.save.overwrite_risk == "none")
check("the label is the drive's name", caps.save.library_label == FIXTURE.name)
print("== opened for BROWSING (the sidebar's Devices) ==")
browse = OneLibraryAdapter(DRIVE, read_only=True)
bcaps = browse.capabilities()
check("a browsing drive is read-only", bcaps.writable is False)
check("because it is being browsed, not because the platform is incomplete",
bcaps.readonly_cause == "browsing", str(bcaps.readonly_cause))
check("and the registry opens it that way when asked",
registry.open_library(DRIVE, read_only=True).capabilities().readonly_cause == "browsing")
bnode = browse.playlist_tree()[0]
check("its playlists offer nothing",
not (bnode.can_add_tracks or bnode.can_reorder or bnode.can_rename or bnode.can_delete))
print("== what is refused ==")
print("== every command is refused ==")
COMMANDS = [
("set_track_metadata", lambda: adapter.set_track_metadata(one.id, {"title": "x"})),
("set_cover_art", lambda: adapter.set_cover_art(one.id, b"", "image/png")),
@@ -393,7 +320,6 @@ COMMANDS = [
("set_playlist_entries", lambda: adapter.set_playlist_entries(node.id, [])),
("set_cue", lambda: adapter.set_cue(one.id, slot=0, start_sec=1.0, cue_type="cue")),
("set_cue_type", lambda: adapter.set_cue_type(one.id, 0, "loop")),
("set_cue_color", lambda: adapter.set_cue_color(one.id, 0, "#FF0000")),
("delete_cue", lambda: adapter.delete_cue(one.id, 0)),
("place_cues", lambda: adapter.place_cues(one.id, [])),
("add_grid_marker", lambda: adapter.add_grid_marker(one.id, 1.0)),
@@ -408,31 +334,9 @@ COMMANDS = [
("save", lambda: adapter.save()),
("snapshot", lambda: adapter.snapshot()),
]
# Browsing: EVERY command refuses — the ones that work on an editable drive too.
BROWSE = [(n, (lambda f=f: f(browse))) for n, f in [
("set_track_metadata", lambda a: a.set_track_metadata(one.id, {"title": "x"})),
("create_playlist", lambda a: a.create_playlist("x")),
("create_folder", lambda a: a.create_folder("x")),
("rename_playlist", lambda a: a.rename_playlist(node.id, "x")),
("delete_playlist", lambda a: a.delete_playlist(node.id)),
("set_playlist_entries", lambda a: a.set_playlist_entries(node.id, [])),
("save", lambda a: a.save()),
]]
refused = [name for name, fn in BROWSE if not _raises(fn, Unsupported)]
check("a browsing drive refuses every edit, Save included", not refused, "; ".join(refused))
check("and is never dirty", browse.dirty is False)
browse.close()
# Editable: what has not landed yet still refuses (each with its flag False).
LANDED = {"set_track_metadata", "create_playlist", "rename_playlist", "delete_playlist",
"set_playlist_entries", "save",
"set_cue", "set_cue_type", "set_cue_color", "delete_cue", "place_cues",
"add_grid_marker", "move_grid_marker", "set_grid_marker_bpm", "delete_grid_marker",
"replace_grid", "set_analysed_grid", "delete_grid", "remove_tracks"}
pending = [(n, fn) for n, fn in COMMANDS if n not in LANDED]
refused = [name for name, fn in pending if not _raises(fn, Unsupported)]
check(f"the {len(pending)} commands not written yet raise Unsupported", not refused, "; ".join(refused))
check("refusing leaves nothing dirty", adapter.dirty is False)
refused = [name for name, fn in COMMANDS if not _raises(fn, Unsupported)]
check(f"all {len(COMMANDS)} commands raise Unsupported", not refused, "; ".join(refused))
check("nothing is ever dirty", adapter.dirty is False)
check("an unknown track is a NotFound, not an Unsupported",
_raises(lambda: adapter.audio_path("no-such-track"), NotFound))
@@ -455,8 +359,6 @@ check("detection of unplugged drives is empty, not an error",
adapter.close()
check("closing twice is safe", adapter.close() is None)
check("the checked-in fixture was never written",
(FIXTURE / "PIONEER" / "rekordbox" / "exportLibrary.db").read_bytes() == FIXTURE_DB_BYTES)
print()
print("RESULT:", "FAILED" if failed else "ALL PASSED")
-261
View File
@@ -1,261 +0,0 @@
"""Cue and beatgrid edits on a OneLibrary stick: the ANLZ files.
Two kinds of check, on temp copies of two real rekordbox-written drives:
* **against rekordbox's own edit** (`fixtures/onelibrary-goober/after/`): the
same edit made in rekordbox 7 and in Konduktor must produce the same bytes —
a recolour changes only the colour bytes, a grid edit blanks `PQT2` and
clears the loop beat lengths exactly as rekordbox did;
* **fidelity**: nothing reaches the drive before Save, only the tags an edit
touches change (in place, order kept), a pad keeps its colour and name
through a move, memory cues stay uneditable, and an `.EXT` with no `PCO2`
keeps every pad when the first edit creates one.
"""
import os
import shutil
import sys
import tempfile
import time
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
APPDATA = Path(tempfile.mkdtemp(prefix="konduktor-olanlz-appdata-"))
os.environ["KONDUKTOR_DATA_DIR"] = str(APPDATA)
from konduktor.adapters.onelibrary.adapter import OneLibraryAdapter # noqa: E402
from konduktor.adapters.rekordbox import anlz_file as A # noqa: E402
from konduktor.adapters.rekordbox import anlz_writer as W # noqa: E402
from konduktor.core.adapter import InvalidCommand, NotFound, Unsupported # noqa: E402
from konduktor.core.model import CuePoint, GridMarker # noqa: E402
HERE = Path(__file__).resolve().parent
GOOBER = HERE / "fixtures" / "onelibrary-goober"
DEMO = HERE / "fixtures" / "onelibrary"
TRACK_1 = "/Contents/Loopmasters/UnknownAlbum/Demo Track 1.mp3"
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
def _raises(fn, exc) -> bool:
try:
fn()
except exc:
return True
except Exception: # noqa: BLE001
return False
return False
def copy_of(fixture: Path, name: str) -> Path:
root = Path(tempfile.mkdtemp(prefix="konduktor-olanlz-")) / name
shutil.copytree(fixture, root, ignore=shutil.ignore_patterns("after", "rekordbox-edited", "README.md"))
return root
def tag(path: Path, kind: str, list_kind: int | None = None) -> bytes | None:
f = A.parse_file(path)
return next((t.data for t in f.tags
if t.type == kind and (list_kind is None or t.list_kind == list_kind)), None)
def tags_by_key(source) -> dict:
"""Tags keyed by (type, list kind), from a path or from bytes."""
out = {}
parsed = A.parse(source) if isinstance(source, bytes) else A.parse_file(source)
for t in parsed.tags:
key = (t.type, t.list_kind)
out[key if key not in out else (*key, len(out))] = t.data
return out
def dat_of(adapter, track_id: str) -> Path:
return adapter._store.layout.resolve(adapter._store.content(track_id).analysisDataFilePath)
# ---- against rekordbox's own edits -----------------------------------------------
print("== the same edit as rekordbox 7 made, the same bytes ==")
drive = copy_of(GOOBER, "Goober")
a = OneLibraryAdapter(drive)
by = lambda prefix: next(t for t in a.tracks if t.title.startswith(prefix)) # noqa: E731
black_bloc, wtf, demo2 = by("Justin Hawkes"), by("Result"), by("Demo Track 2")
before_dat = dat_of(a, black_bloc.id).read_bytes()
a.set_cue_color(black_bloc.id, 2, "#FF0045")
a.set_grid_marker_bpm(wtf.id, 0, 87.0)
a.set_cue(demo2.id, slot=4, start_sec=47.5, cue_type="cue")
a.save()
ext = dat_of(a, black_bloc.id).with_suffix(".EXT")
check("a recolour: the PCO2 hot list is rekordbox's, byte for byte",
tag(ext, "PCO2", A.LIST_HOT) == tag(GOOBER / "after" / "black-bloc-recoloured.EXT", "PCO2", A.LIST_HOT))
check("and the .DAT, which holds no colour, is untouched", dat_of(a, black_bloc.id).read_bytes() == before_dat)
ext = dat_of(a, wtf.id).with_suffix(".EXT")
check("a grid edit blanks PQT2 exactly as rekordbox does",
tag(ext, "PQT2") == tag(GOOBER / "after" / "wtf-87bpm.EXT", "PQT2"))
check("and clears the memory loop's beat length exactly as rekordbox does",
tag(ext, "PCO2", A.LIST_MEMORY) == tag(GOOBER / "after" / "wtf-87bpm.EXT", "PCO2", A.LIST_MEMORY))
ours = [e.time for t in A.parse_file(dat_of(a, wtf.id)).tags if t.type == "PQTZ" for e in t.entries]
theirs = [e.time for t in A.parse_file(GOOBER / "after" / "wtf-87bpm.DAT").tags if t.type == "PQTZ"
for e in t.entries]
check("PQTZ: the same number of beats as rekordbox's", len(ours) == len(theirs), f"{len(ours)} vs {len(theirs)}")
# rekordbox re-derives its anchor and works at its own tempo precision (its first
# beat moved 83 -> 89 ms, steps alternate 689/690); Konduktor keeps the marker.
check("each within 10 ms of rekordbox's (its anchor moves; ours stays put)",
max(abs(x - y) for x, y in zip(ours, theirs)) <= 10)
check("from the marker where it was, 60/87 s apart",
ours[0] == 83 and all(abs(ours[k] - 83 - k * 60000 / 87) <= 0.5 for k in range(len(ours))))
check("bpmx100 follows the first marker, as rekordbox's did", a._store.content(wtf.id).bpmx100 == 8700)
pads = {c.slot: c for c in a.track_cues(demo2.id).cues if c.role == "hotcue"}
theirs = {e.hot_cue - 1: e for t in A.parse_file(GOOBER / "after" / "demo2-pad-e-added.EXT").tags
if t.type == "PCO2" and t.list_kind == A.LIST_HOT for e in t.entries}
check("a new pad lands where rekordbox's did, the other pads as they were",
sorted(pads) == sorted(theirs) and all(abs(pads[s].start * 1000 - theirs[s].time) < 30
or s == 4 for s in pads), str(sorted(pads)))
a.close()
# ---- fidelity on the demo drive --------------------------------------------------
print("== nothing reaches the drive before Save; only touched tags change ==")
drive = copy_of(DEMO, "Dingus")
a = OneLibraryAdapter(drive)
dat = dat_of(a, TRACK_1)
ext = dat.with_suffix(".EXT")
original = {p: p.read_bytes() for p in (dat, ext)}
cues = {c.slot: c for c in a.track_cues(TRACK_1).cues if c.role == "hotcue"}
check("hot cues are editable, memory cues are not",
all(c.editable == (c.role == "hotcue") for c in a.track_cues(TRACK_1).cues))
a.set_cue(TRACK_1, slot=5, start_sec=10.0, cue_type="cue", name="Drop")
a.set_cue_color(TRACK_1, 5, "#FF0045")
a.set_cue(TRACK_1, slot=5, start_sec=11.0, cue_type="cue")
pad = next(c for c in a.track_cues(TRACK_1).cues if c.slot == 5)
check("a moved pad keeps its colour and its name",
(round(pad.start, 3), pad.color, pad.name) == (11.0, "#FF0045", "Drop"), str(pad))
check("the edit shows at once", a.dirty and round(pad.start, 3) == 11.0)
check("but the drive's files are untouched", all(p.read_bytes() == b for p, b in original.items()))
a.set_cue_type(TRACK_1, 0, "cue") # pad A was a loop
check("a loop retyped to a cue loses its length",
next(c for c in a.track_cues(TRACK_1).cues if c.slot == 0).length == 0.0)
check("a cue cannot become a loop without a length",
_raises(lambda: a.set_cue_type(TRACK_1, 5, "loop"), InvalidCommand))
a.delete_cue(TRACK_1, 3)
check("a pad can be deleted (pad D, which lives in the .EXT's PCOB)",
3 not in {c.slot for c in a.track_cues(TRACK_1).cues if c.role == "hotcue"})
check("deleting an empty pad is NotFound", _raises(lambda: a.delete_cue(TRACK_1, 7), NotFound))
check("a pad beyond the bank is refused",
_raises(lambda: a.set_cue(TRACK_1, slot=8, start_sec=1.0, cue_type="cue"), InvalidCommand))
check("memory cues are not editable",
_raises(lambda: a.set_cue(TRACK_1, slot=0, start_sec=1.0, cue_type="cue", role="memory"), Unsupported))
check("a colour must be one of rekordbox's swatches",
_raises(lambda: a.set_cue_color(TRACK_1, 5, "#123456"), InvalidCommand))
a.place_cues(TRACK_1, [CuePoint(slot=1, start=30.0, length=0.0, type="cue"),
CuePoint(slot=6, start=31.0, length=0.0, type="cue")])
starts = {c.slot: round(c.start, 2) for c in a.track_cues(TRACK_1).cues if c.role == "hotcue"}
check("place_cues fills empty pads and leaves occupied ones", starts.get(6) == 31.0 and starts.get(1) != 30.0)
markers = a.track_cues(TRACK_1).grid_markers
# A per-beat grid has no markers: one at the governing tempo, on its beats, is
# indistinguishable from none and collapses on read (as on the Rekordbox side).
a.add_grid_marker(TRACK_1, markers[-1].start + 10 * 60 / markers[-1].bpm)
check("a marker at the governing tempo collapses into it",
len(a.track_cues(TRACK_1).grid_markers) == len(markers))
a.add_grid_marker(TRACK_1, 100.0, 100.0)
check("a marker with a new tempo is a new segment",
[m.bpm for m in a.track_cues(TRACK_1).grid_markers] == [128.0, 90.0, 100.0])
a.move_grid_marker(TRACK_1, 1, 200.0)
moved = a.track_cues(TRACK_1).grid_markers
check("a moved marker is clamped before its neighbour", moved[1].start < moved[2].start)
a.delete_grid_marker(TRACK_1, 2)
check("and deleted", len(a.track_cues(TRACK_1).grid_markers) == len(markers))
a.save()
after = {p: tags_by_key(p) for p in (dat, ext)}
before = {p: tags_by_key(b) for p, b in original.items()}
changed = {p.suffix: sorted(f"{k[0]}/{k[1]}" for k in before[p] if before[p][k] != after[p].get(k))
for p in original}
check("the .DAT: only the pad 1-3 list and the grid changed",
changed[".DAT"] == ["PCOB/1", "PQTZ/None"], str(changed[".DAT"]))
check("the .EXT: only its cue lists changed (memory: the loop beats a grid edit clears)",
set(changed[".EXT"]) <= {"PCOB/1", "PCO2/1", "PCO2/0"}, str(changed[".EXT"]))
check("tag order is kept in both files",
all([t.type for t in A.parse(original[p]).tags] == [t.type for t in A.parse_file(p).tags]
for p in original))
check("the .DAT's memory list (no beat field there) is byte-identical",
tag(dat, "PCOB", A.LIST_MEMORY) == before[dat][("PCOB", A.LIST_MEMORY)])
backups = sorted((APPDATA / "onelibrary" / "backups" / "Dingus").iterdir())
check("both analysis files were backed up first",
all((backups[-1] / p.relative_to(drive)).read_bytes() == b for p, b in original.items()))
a.close()
b = OneLibraryAdapter(drive)
check("everything reads back after a reopen",
{c.slot: round(c.start, 2) for c in b.track_cues(TRACK_1).cues if c.role == "hotcue"} == starts
and next(c for c in b.track_cues(TRACK_1).cues if c.slot == 5).name == "Drop")
b.close()
print("== another app wrote an analysis file since Konduktor read it ==")
drive = copy_of(DEMO, "Dingus")
a = OneLibraryAdapter(drive)
a.set_cue(TRACK_1, slot=6, start_sec=5.0, cue_type="cue")
time.sleep(0.01)
os.utime(dat_of(a, TRACK_1).with_suffix(".EXT"))
check("Save refuses rather than undo it", _raises(a.save, InvalidCommand) and a.dirty)
a.close()
print("== an .EXT with no PCO2 keeps every pad on the first edit ==")
drive = copy_of(DEMO, "Dingus")
probe = OneLibraryAdapter(drive)
ext = dat_of(probe, TRACK_1).with_suffix(".EXT")
want = sorted(c.slot for c in probe.track_cues(TRACK_1).cues if c.role == "hotcue")
memory = sum(c.role == "memory" for c in probe.track_cues(TRACK_1).cues)
probe.close()
f = A.parse_file(ext)
f.tags = [t for t in f.tags if t.type != "PCO2"]
ext.write_bytes(f.to_bytes())
a = OneLibraryAdapter(drive)
check("read from PCOB alone, the pads are all there", sorted(
c.slot for c in a.track_cues(TRACK_1).cues if c.role == "hotcue") == want)
a.set_cue(TRACK_1, slot=6, start_sec=5.0, cue_type="cue")
got = a.track_cues(TRACK_1).cues
check("after the edit creates PCO2, every old pad AND the new one read",
sorted(c.slot for c in got if c.role == "hotcue") == sorted(want + [6]), str([c.slot for c in got]))
check("and the memory cue survives", sum(c.role == "memory" for c in got) == memory)
a.close()
print("== a track without analysis files ==")
drive = copy_of(DEMO, "Dingus")
probe = OneLibraryAdapter(drive)
dat = dat_of(probe, TRACK_1)
probe.close()
for p in (dat, dat.with_suffix(".EXT")):
p.unlink()
a = OneLibraryAdapter(drive)
check("refuses a cue edit (it has nowhere to store one)",
_raises(lambda: a.set_cue(TRACK_1, slot=0, start_sec=1.0, cue_type="cue"), InvalidCommand))
check("and a grid edit", _raises(lambda: a.replace_grid(TRACK_1, [GridMarker(start=0, bpm=120)]),
InvalidCommand))
a.close()
print("== the entry helpers ==")
e = W.pcp2_entry(hot_cue=2, kind=1, time_ms=5, loop_ms=None, rgb=(1, 2, 3), beats=None, code=9,
comment="A name longer than forty bytes in UTF-16")
d = A.decode_entry(e)
check("a long name grows the entry past 88 bytes and round-trips",
len(e) > 88 and d.comment == "A name longer than forty bytes in UTF-16" and d.color_code == 9)
check("a 44-byte compact entry has no colour bytes to patch",
A.entry_with_colour(A.raw_entries(A.Tag("PCO2", tag(HERE / "fixtures" / "onelibrary" / "rekordbox-edited"
/ "nemean.EXT", "PCO2", A.LIST_MEMORY)))[-1],
9, (1, 2, 3)) is None)
print()
print("RESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
-354
View File
@@ -1,354 +0,0 @@
"""OneLibrary's analogue of `test_rekordbox_fidelity.py`: an edit changes only
what it was supposed to change, checked as a FULL TABLE DUMP before and after
(a byte diff means nothing against SQLite), on a temp copy of the fixture drive.
The expected diffs are rekordbox's own, MEASURED on Goober (2026-10-01; see the
editing discussion log): a title edit changes `content.title` and nothing else —
no update counter moves — a new playlist goes on top with its siblings shifted
down one, and a reorder renumbers that playlist's entries from 1.
And the properties a STICK needs that a desktop library does not: nothing
reaches the drive before Save, the drive is replaced in one rename, another
app's write since open is refused rather than undone, an unplugged drive keeps
the edits for a retry, stale `-wal`/`-shm` files are deleted, and a backup of
the drive's database lands in app-data first.
"""
import os
import shutil
import sys
import tempfile
import time
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
APPDATA = Path(tempfile.mkdtemp(prefix="konduktor-olfid-appdata-"))
os.environ["KONDUKTOR_DATA_DIR"] = str(APPDATA)
from konduktor.adapters.onelibrary.adapter import OneLibraryAdapter # noqa: E402
from konduktor.core.adapter import InvalidCommand # noqa: E402
FIXTURE = Path(__file__).resolve().parent / "fixtures" / "onelibrary"
TRACK_1 = "/Contents/Loopmasters/UnknownAlbum/Demo Track 1.mp3"
TRACK_2 = "/Contents/Loopmasters/UnknownAlbum/Demo Track 2.mp3"
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
def _raises(fn, exc) -> bool:
try:
fn()
except exc:
return True
except Exception: # noqa: BLE001
return False
return False
# ---- the row-level dump/diff harness -------------------------------------
LINK_TABLES = {"playlist_content", "history_content", "myTag_content", "hotCueBankList_cue"}
def dump(db: Path) -> dict:
"""Every row of every table; keyed by primary key, or by the whole row for
the link tables, which have none."""
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.devicelib_plus.database import BLOB
from pyrekordbox.utils import deobfuscate
con = sqlcipher.connect(str(db))
con.execute(f"PRAGMA key='{deobfuscate(BLOB)}'")
cur = con.cursor()
names = [r[0] for r in cur.execute(
"SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").fetchall()]
out: dict[str, dict] = {}
for table in names:
cols = [r[1] for r in cur.execute(f'PRAGMA table_info("{table}")').fetchall()]
rows = {}
for r in cur.execute(f'SELECT * FROM "{table}"').fetchall():
d = dict(zip(cols, r))
key = "|".join(map(str, r)) if table in LINK_TABLES else str(r[0])
rows[key] = d
out[table] = rows
con.close()
return out
def diff(before: dict, after: dict) -> list:
changes = []
for table in sorted(set(before) | set(after)):
a, b = before.get(table, {}), after.get(table, {})
for pk in sorted(set(a) | set(b)):
if pk not in a:
changes.append((table, pk, "INSERT", b[pk]))
elif pk not in b:
changes.append((table, pk, "DELETE", a[pk]))
else:
fields = {k: (a[pk][k], b[pk].get(k)) for k in a[pk] if a[pk][k] != b[pk].get(k)}
if fields:
changes.append((table, pk, "UPDATE", fields))
return changes
def describe(changes) -> str:
return "; ".join(f"{t}/{pk} {kind}" for t, pk, kind, _ in changes) or "(none)"
def fresh_drive() -> Path:
root = Path(tempfile.mkdtemp(prefix="konduktor-olfid-")) / "Dingus"
shutil.copytree(FIXTURE, root, ignore=shutil.ignore_patterns("rekordbox-edited"))
return root
def db_of(root: Path) -> Path:
return root / "PIONEER" / "rekordbox" / "exportLibrary.db"
# ---- A: nothing reaches the drive until Save --------------------------------
print("== edits stay off the drive until Save ==")
drive = fresh_drive()
before_bytes = db_of(drive).read_bytes()
before = dump(db_of(drive))
a = OneLibraryAdapter(drive)
check("opening writes nothing", db_of(drive).read_bytes() == before_bytes)
check("and leaves no -wal/-shm on the drive",
not any(db_of(drive).with_name(db_of(drive).name + s).exists() for s in ("-wal", "-shm")))
a.set_track_metadata(TRACK_1, {"title": "Edited"})
check("an edit makes the library dirty", a.dirty is True)
check("and the projection shows it at once", a.track(TRACK_1).title == "Edited")
check("but the drive's database is byte-identical", db_of(drive).read_bytes() == before_bytes)
print("== Discard ==")
a.reload()
check("discarding drops the edit", a.track(TRACK_1).title.startswith("Demo Track 1"), a.track(TRACK_1).title)
check("and leaves nothing dirty", a.dirty is False)
check("and the drive untouched", db_of(drive).read_bytes() == before_bytes)
# ---- B: a no-op save ----------------------------------------------------------
print("== a no-op save ==")
a.save()
check("changes zero rows", diff(before, dump(db_of(drive))) == [], describe(diff(before, dump(db_of(drive)))))
a.close()
# ---- C: one field, one column ---------------------------------------------------
print("== a one-field edit changes exactly that column ==")
drive = fresh_drive()
before = dump(db_of(drive))
a = OneLibraryAdapter(drive)
a.set_track_metadata(TRACK_1, {"title": "Edited"})
outcome = a.save()
changes = diff(before, dump(db_of(drive)))
check("exactly one row changed", len(changes) == 1, describe(changes))
check("content.title, and no update counter (measured: rekordbox moves none)",
changes and changes[0][0] == "content" and set(changes[0][3]) == {"title"}
and changes[0][3]["title"][1] == "Edited", str(changes))
check("the save is not dirty afterwards", a.dirty is False)
check("and the adapter reads the saved drive", a.track(TRACK_1).title == "Edited")
check("the save reports a summary of the edit", bool(outcome.summary), outcome.summary)
check("no version-history snapshot (a drive is many files)", outcome.snapshot is None)
backups = sorted((APPDATA / "onelibrary" / "backups" / "Dingus").iterdir())
check("a backup was written to app-data, not the drive", len(backups) >= 1)
check("holding the database as it was BEFORE the save",
dump(backups[-1] / "exportLibrary.db") == before)
check("no partial file is left beside the database",
not list(db_of(drive).parent.glob("*.konduktor-partial")))
a.close()
print("== rating, comment, release date ==")
drive = fresh_drive()
before = dump(db_of(drive))
a = OneLibraryAdapter(drive)
a.set_track_metadata(TRACK_1, {"rating": 3})
a.set_track_metadata(TRACK_2, {"comment": "", "release_date": "2021-03-04"})
check("an out-of-range rating is refused", _raises(lambda: a.set_track_metadata(TRACK_1, {"rating": 6}),
InvalidCommand))
check("a malformed date is refused", _raises(lambda: a.set_track_metadata(TRACK_1, {"release_date": "soon"}),
InvalidCommand))
a.save()
changes = {(t, pk): f for t, pk, kind, f in diff(before, dump(db_of(drive)))}
row1 = next(f for (t, pk), f in changes.items() if t == "content" and pk == "1")
row2 = next(f for (t, pk), f in changes.items() if t == "content" and pk == "2")
check("rating is stored 0-5 directly", row1 == {"rating": (0, 3)}, str(row1))
check("a cleared comment is '' as rekordbox stores it, not NULL",
row2.get("djComment", (None, None))[1] == "", str(row2))
check("a full date sets releaseYear AND releaseDate as YYYY-MM-DD text",
row2.get("releaseYear", (0, 0))[1] == 2021 and row2.get("releaseDate", ("", ""))[1] == "2021-03-04",
str(row2))
check("and reads back", a.track(TRACK_2).release_date == "2021-03-04", str(a.track(TRACK_2).release_date))
check("nothing else changed", len(changes) == 2, str(list(changes)))
a.set_track_metadata(TRACK_2, {"release_date": "2019"})
check("a bare year is releaseYear with an empty releaseDate",
a._store.content(TRACK_2).releaseYear == 2019 and a.track(TRACK_2).release_date == "2019",
str(a.track(TRACK_2).release_date))
a.close()
print("== lookups are found or created ==")
drive = fresh_drive()
before = dump(db_of(drive))
a = OneLibraryAdapter(drive)
a.set_track_metadata(TRACK_1, {"artist": "Loopmasters"}) # already there
check("an existing name is reused, not duplicated", a.dirty and a._store.content(TRACK_1).artist_id_artist == 1)
a.set_track_metadata(TRACK_1, {"artist": "New Artist", "genre": "Techno"})
check("the projection reads the NEW names (not the stale relationship)",
a.track(TRACK_1).artist == "New Artist" and a.track(TRACK_1).genre == "Techno",
f"{a.track(TRACK_1).artist} / {a.track(TRACK_1).genre}")
a.set_track_metadata(TRACK_2, {"label": ""})
check("clearing a lookup unsets it", a.track(TRACK_2).label is None)
a.save()
changes = diff(before, dump(db_of(drive)))
inserts = [(t, f) for t, pk, kind, f in changes if kind == "INSERT"]
check("one new artist and one new genre row",
sorted(t for t, _ in inserts) == ["artist", "genre"], describe(changes))
check("with nameForSearch NULL, as rekordbox leaves it",
all(f.get("nameForSearch") is None for t, f in inserts if t == "artist"))
a.close()
# ---- D: playlists, as rekordbox writes them ---------------------------------------
print("== playlists ==")
drive = fresh_drive()
before = dump(db_of(drive))
a = OneLibraryAdapter(drive)
demos = a.playlist_tree()[0]
new_id = a.create_playlist("Probe")
tree = a.playlist_tree()
check("a new playlist is listed FIRST (rekordbox puts it on top)",
[n.name for n in tree] == ["Probe", "demos"], str([n.name for n in tree]))
a.set_playlist_entries(new_id, [TRACK_2])
a.set_playlist_entries(demos.id, [TRACK_2, TRACK_1])
check("a reorder reads back in the new order", a.playlist_entries(demos.id) == [TRACK_2, TRACK_1])
a.save()
changes = diff(before, dump(db_of(drive)))
pl = {pk: (kind, f) for t, pk, kind, f in changes if t == "playlist"}
check("the new playlist row has sequenceNo 0, attribute 0, parent 0",
pl.get(new_id, ("", {}))[0] == "INSERT"
and {k: pl[new_id][1][k] for k in ("sequenceNo", "attribute", "playlist_id_parent")}
== {"sequenceNo": 0, "attribute": 0, "playlist_id_parent": 0}, str(pl.get(new_id)))
check("and its sibling moved down one", pl.get(demos.id) == ("UPDATE", {"sequenceNo": (0, 1)})
or pl.get(demos.id, ("", {}))[1].get("sequenceNo", (None, None))[1]
== before["playlist"][demos.id]["sequenceNo"] + 1, str(pl.get(demos.id)))
entries = sorted((f["playlist_id"], f["content_id"], f["sequenceNo"])
for t, pk, kind, f in changes if t == "playlist_content" and kind == "INSERT")
check("entries are numbered from 1 (measured)",
entries == sorted([(int(new_id), 2, 1), (int(demos.id), 2, 1), (int(demos.id), 1, 2)]), str(entries))
check("no other table changed", {t for t, *_ in changes} == {"playlist", "playlist_content"},
describe(changes))
folder = a.create_folder("Gigs")
inner = a.create_playlist("Friday", folder)
a.set_playlist_entries(inner, [TRACK_1])
check("a playlist can only be created inside a FOLDER",
_raises(lambda: a.create_playlist("x", demos.id), InvalidCommand))
check("a nameless playlist is refused", _raises(lambda: a.create_playlist(" "), InvalidCommand))
a.rename_playlist(inner, "Saturday")
gigs = next(n for n in a.playlist_tree() if n.id == folder)
check("a folder nests its playlist", [c.name for c in gigs.children] == ["Saturday"])
a.save()
mid = dump(db_of(drive))
a.delete_playlist(folder)
a.save()
after = dump(db_of(drive))
changes = diff(mid, after)
check("deleting a folder deletes what is in it, entries included",
sorted((t, kind) for t, pk, kind, _ in changes if kind == "DELETE")
== [("playlist", "DELETE"), ("playlist", "DELETE"), ("playlist_content", "DELETE")],
describe(changes))
seqs = sorted(r["sequenceNo"] for r in after["playlist"].values() if r["playlist_id_parent"] == 0)
check("and closes the gap among its siblings", seqs == list(range(len(seqs))), str(seqs))
a.close()
# ---- E: a stick's hazards ------------------------------------------------------------
print("== another app wrote the drive since it was opened ==")
drive = fresh_drive()
a = OneLibraryAdapter(drive)
a.set_track_metadata(TRACK_1, {"title": "Mine"})
theirs = db_of(drive).read_bytes()
time.sleep(0.01)
os.utime(db_of(drive)) # e.g. rekordbox saving the stick meanwhile
check("Save refuses rather than undo it", _raises(a.save, InvalidCommand))
check("the drive is exactly as the other app left it", db_of(drive).read_bytes() == theirs)
check("and the edit is still pending", a.dirty and a.track(TRACK_1).title == "Mine")
a.close()
print("== an unplugged drive ==")
drive = fresh_drive()
a = OneLibraryAdapter(drive)
a.set_track_metadata(TRACK_1, {"title": "Kept"})
parked = drive.parent / "unplugged"
(drive / "PIONEER").rename(parked)
check("Save refuses cleanly", _raises(a.save, InvalidCommand))
check("keeping the edit", a.dirty and a.track(TRACK_1).title == "Kept")
parked.rename(drive / "PIONEER")
a.save()
check("and saves it once the drive is back",
dump(db_of(drive))["content"]["1"]["title"] == "Kept" and not a.dirty)
a.close()
print("== stale SQLite sidecars ==")
drive = fresh_drive()
shm = db_of(drive).with_name("exportLibrary.db-shm")
shm.write_bytes(b"\0" * 32768) # rekordbox leaves one on a stick it mounted
a = OneLibraryAdapter(drive)
a.set_track_metadata(TRACK_1, {"title": "x"})
a.save()
check("a stale -shm is deleted on save (SQLite would trust it)", not shm.exists())
check("and the saved database opens", dump(db_of(drive))["content"]["1"]["title"] == "x")
a.close()
print("== the drive is never held open ==")
drive = fresh_drive()
a = OneLibraryAdapter(drive)
try:
import subprocess
mine = subprocess.run(["lsof", "-Fn", "-p", str(os.getpid())], capture_output=True,
text=True).stdout
check("no file on the drive is open in this process",
str(db_of(drive)) not in mine, "exportLibrary.db is open")
except FileNotFoundError:
print(" (lsof unavailable — skipped)")
a.close()
print("== a read-only (browsing) drive ==")
drive = fresh_drive()
b = OneLibraryAdapter(drive, read_only=True)
check("is not writable", b.capabilities().writable is False)
b.close()
check("closing removes its working copy",
not any((APPDATA / "onelibrary" / "work").iterdir()))
print("== file tags (decision 5: as rekordbox does) ==")
drive = fresh_drive()
from stem_test_support import make_mp3 # noqa: E402
audio = drive / TRACK_1.lstrip("/")
make_mp3(audio) # the fixture's MP3s are 12-byte placeholders
a = OneLibraryAdapter(drive)
a.set_track_metadata(TRACK_1, {"title": "Tagged", "artist": "Somebody", "rating": 4})
outcome = a.save()
import mutagen # noqa: E402
tags = mutagen.File(str(audio)).tags
check("the edited title reaches the file's TIT2", str(tags.get("TIT2")) == "Tagged", str(tags.get("TIT2")))
check("and the artist its TPE1", str(tags.get("TPE1")) == "Somebody")
check("the rating does NOT (rekordbox keeps it library-only)", not tags.getall("POPM"))
check("the write is reported", any(r.ok and r.track_id == TRACK_1 for r in outcome.tag_results),
str(outcome.tag_results))
(drive / TRACK_2.lstrip("/")).unlink() # its audio gone from the stick
a.set_track_metadata(TRACK_2, {"title": "Missing"})
outcome = a.save()
check("a missing audio file is reported, not fatal",
[r.status for r in outcome.tag_results] == ["file-not-found"] and not a.dirty
and dump(db_of(drive))["content"]["2"]["title"] == "Missing", str(outcome.tag_results))
a.close()
print()
print("RESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
-152
View File
@@ -1,152 +0,0 @@
"""The legacy Device Library (`export.pdb`) kept in step with a stick's OneLibrary.
On a temp copy of Goober (`fixtures/onelibrary-goober/`), whose three databases
are rekordbox's own bytes. Pins:
* reading: every rekordbox track row decodes, and re-encodes to the same
meaningful bytes (rekordbox leaves stale bytes in alignment padding and
between rows — `track_extent`);
* ids are mirrored: rekordbox exported both libraries from the same ids, so a
no-op rebuild changes NOTHING, and a no-op save leaves the file byte-identical;
* an edit reaches the pdb (title, rating, artist, a new playlist, a reorder —
the last two are what rekordbox's own edits failed to carry over), every table
the edit does not touch stays byte-identical, and `exportExt.pdb` is never
written;
* another app's write to `export.pdb` since open is refused, not undone.
Verified in rekordbox 7 on the real Goober (2026-10-01): both library views
matched after exactly these edits.
"""
import os
import shutil
import sys
import tempfile
import time
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-olpdb-appdata-")
from konduktor.adapters.onelibrary import device_library # noqa: E402
from konduktor.adapters.onelibrary.adapter import OneLibraryAdapter # noqa: E402
from konduktor.adapters.rekordbox import pdb # noqa: E402
from konduktor.core.adapter import InvalidCommand # noqa: E402
HERE = Path(__file__).resolve().parent
GOOBER = HERE / "fixtures" / "onelibrary-goober"
DEMO = HERE / "fixtures" / "onelibrary"
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
def copy_of(fixture: Path, name: str) -> Path:
root = Path(tempfile.mkdtemp(prefix="konduktor-olpdb-")) / name
shutil.copytree(fixture, root, ignore=shutil.ignore_patterns("after", "rekordbox-edited", "README.md"))
return root
PDB = GOOBER / "PIONEER" / "rekordbox" / "export.pdb"
raw = PDB.read_bytes()
print("== reading rekordbox's rows ==")
tracks = pdb.table_rows(raw, pdb.TRACKS)
check("every track row is found (as many as the reader sees)", len(tracks) == len(pdb.read(raw).tracks) == 11)
same = [pdb.track_row(*pdb.track_fields(r)) for r in tracks]
check("each re-encodes to the same bytes up to its 4-byte alignment padding",
all(a[:len(a) - 3] == b[:len(a) - 3] and len(a) == len(b) for a, b in zip(tracks, same)))
check("a row ends at its last string, not at the next row (stale heap tails)",
all(pdb.track_extent(r) == len(r) for r in tracks))
check("artists, keys, artwork and the playlist tree all read",
[len(pdb.table_rows(raw, t)) for t in (pdb.ARTISTS, pdb.KEYS, pdb.ARTWORK, pdb.PLAYLIST_TREE)]
== [5, 4, 3, 2])
print("== ids are mirrored: nothing to do on an unedited stick ==")
drive = copy_of(GOOBER, "Goober")
a = OneLibraryAdapter(drive)
rebuilt = device_library.rebuild(raw, a._store._require_db().session)
check("a rebuild of an unedited stick changes nothing", rebuilt is None)
a.set_track_metadata(a.tracks[0].id, {"title": a.tracks[0].title}) # dirty, but a no-op
a.save()
check("a save that changes nothing in it leaves export.pdb byte-identical",
(drive / "PIONEER" / "rekordbox" / "export.pdb").read_bytes() == raw)
a.close()
print("== an edit reaches the Device Library, and only the edit ==")
drive = copy_of(GOOBER, "Goober")
P = drive / "PIONEER" / "rekordbox"
ext_before = (P / "exportExt.pdb").read_bytes()
a = OneLibraryAdapter(drive)
by = lambda prefix: next(t for t in a.tracks if t.title.startswith(prefix)) # noqa: E731
tian, bensley, alkyn = by("Tian"), by("Bensley"), by("Alkyn")
a.set_track_metadata(tian.id, {"title": tian.title + " X"})
a.set_track_metadata(bensley.id, {"rating": 3})
a.set_track_metadata(alkyn.id, {"artist": "Alkyn"})
demos = next(n for n in a.playlist_tree() if n.name == "demos")
order = a.playlist_entries(demos.id)
a.set_playlist_entries(demos.id, order[::-1])
probe = a.create_playlist("Probe")
a.set_playlist_entries(probe, [alkyn.id])
a.save()
after = (P / "export.pdb").read_bytes()
A, B = pdb.read(raw), pdb.read(after)
old = {t["id"]: t for t in A.tracks}
new = {t["id"]: t for t in B.tracks}
diffs = {i: {k for k in old[i] if old[i][k] != new[i][k] and k != "index_shift"} for i in old}
check("only the edited fields of the edited tracks changed",
{i: d for i, d in diffs.items() if d} == {6: {"title"}, 7: {"rating"}, 8: {"artist_id"}},
str({i: d for i, d in diffs.items() if d}))
check("the new artist is mirrored under OneLibrary's own id",
B.artists.get(new[8]["artist_id"]) == "Alkyn" and new[8]["artist_id"] == 6)
tree = sorted((p["name"], p["sort"]) for p in B.playlists)
check("the new playlist reached it, on top (rekordbox's own edit did not carry it over)",
tree == [("Para Ben", 1), ("Probe", 0), ("demos", 2)], str(tree))
demos_entries = [t for _i, t, p in sorted(B.entries) if p == int(demos.id)]
check("and so did the reorder", [new[t]["file_path"] for t in demos_entries] == order[::-1])
for table, name in ((pdb.COLORS, "colours"), (pdb.KEYS, "keys"), (pdb.ARTWORK, "artwork"),
(pdb.GENRES, "genres"), (pdb.LABELS, "labels"), (pdb.ALBUMS, "albums"),
(pdb.HISTORY, "history"), (16, "browse columns"), (17, "menus")):
check(f"untouched table ({name}) is byte-identical",
pdb.table_rows(raw, table) == pdb.table_rows(after, table))
check("an unchanged track row keeps rekordbox's own bytes (stale padding and all)",
[r for r in pdb.table_rows(after, pdb.TRACKS) if pdb.row_id(pdb.TRACKS, r) == 1]
== [r for r in tracks if pdb.row_id(pdb.TRACKS, r) == 1])
check("the file did not grow", len(after) == len(raw))
check("exportExt.pdb is never written", (P / "exportExt.pdb").read_bytes() == ext_before)
check("the previous export.pdb was backed up",
any(p.read_bytes() == raw for p in
(Path(os.environ["KONDUKTOR_DATA_DIR"]) / "onelibrary" / "backups").rglob("export.pdb")))
a.close()
print("== another app wrote export.pdb since open ==")
drive = copy_of(GOOBER, "Goober")
a = OneLibraryAdapter(drive)
a.set_track_metadata(a.tracks[0].id, {"rating": 5})
time.sleep(0.01)
os.utime(drive / "PIONEER" / "rekordbox" / "export.pdb")
try:
a.save()
refused = False
except InvalidCommand:
refused = True
check("Save refuses", refused and a.dirty)
a.close()
print("== a stick with no Device Library ==")
drive = copy_of(DEMO, "Dingus")
a = OneLibraryAdapter(drive)
a.set_track_metadata(a.tracks[0].id, {"rating": 2})
a.save()
check("saving does not create one", not (drive / "PIONEER" / "rekordbox" / "export.pdb").exists())
a.close()
print()
print("RESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
-312
View File
@@ -1,312 +0,0 @@
"""Adding tracks to a OneLibrary stick and removing them (decisions 3, 6 and 7).
On temp copies of Goober (`fixtures/onelibrary-goober/`, with its Device Library)
and generated MP3s, through `importer.run` — the path every add route takes:
* placement: the LIBRARY decides — a file already on the stick is used in
place; anything else goes to `Contents/<Artist>/<Album>/` as rekordbox lays a
stick out (`UnknownArtist`/`UnknownAlbum`, names cut to 48 characters),
through `.konduktor-incoming/`;
* an added track arrives ready to prep: analysis files (grid, cues, memory
cues), artwork, a row shaped like rekordbox's, the track count, and its row
in the Device Library;
* nothing is left behind: a cancel mid-copy, a Discard, a crash (cleared on the
next EDITABLE open only);
* removal: every row naming the track goes (playlists renumbered), and its
audio, analysis files and unshared artwork are deleted AFTER the save that
stopped naming them — never before.
"""
import hashlib
import io
import os
import shutil
import sys
import tempfile
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-oltracks-appdata-")
from stem_test_support import make_mp3 # noqa: E402
from konduktor import importer # noqa: E402
from konduktor.adapters.onelibrary.adapter import OneLibraryAdapter # noqa: E402
from konduktor.adapters.rekordbox import pdb # noqa: E402
from konduktor.core.adapter import NewTrack # noqa: E402
from konduktor.core.model import CuePoint, GridMarker, Track, TrackCues # noqa: E402
from konduktor.jobs import Job, JobCancelled, JobHandle # noqa: E402
HERE = Path(__file__).resolve().parent
GOOBER = HERE / "fixtures" / "onelibrary-goober"
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
def copy_of(name: str = "Goober") -> Path:
root = Path(tempfile.mkdtemp(prefix="konduktor-oltracks-")) / name
shutil.copytree(GOOBER, root, ignore=shutil.ignore_patterns("after", "README.md"))
return root
def fingerprint(root: Path) -> str:
h = hashlib.sha1()
for p in sorted(root.rglob("*")):
if p.is_file():
h.update(str(p.relative_to(root)).encode() + p.read_bytes())
return h.hexdigest()
def rows(root: Path, sql: str):
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.devicelib_plus.database import BLOB
from pyrekordbox.utils import deobfuscate
con = sqlcipher.connect(str(root / "PIONEER" / "rekordbox" / "exportLibrary.db"))
con.execute(f"PRAGMA key='{deobfuscate(BLOB)}'")
con.row_factory = lambda cur, row: dict(zip([d[0] for d in cur.description], row))
try:
return con.execute(sql).fetchall()
finally:
con.close()
def jpeg() -> bytes:
from PIL import Image
buf = io.BytesIO()
Image.new("RGB", (300, 200), (200, 40, 90)).save(buf, "JPEG")
return buf.getvalue()
SRC = Path(tempfile.mkdtemp(prefix="konduktor-oltracks-src-"))
ONE = make_mp3(SRC / "Kick One.mp3", seconds=20)
TWO = make_mp3(SRC / "Kick Two.mp3", seconds=20, seed=5)
COVER = jpeg()
class Source:
"""Two tracks: one fully prepped (grid, hot cue, memory loop, cover), one bare."""
def __init__(self):
self.t = {
str(ONE): Track(id=str(ONE), title="Kick One", artist="Konduktor: Test", album="Probe EP",
bpm=120.0, length=20, rating=4, filepath=str(ONE)),
str(TWO): Track(id=str(TWO), title="Kick Two", length=20, filepath=str(TWO)),
}
@property
def tracks(self):
return list(self.t.values())
def track(self, i):
return self.t.get(i)
def track_cues(self, i):
if i != str(ONE):
return None
return TrackCues(grid_markers=[GridMarker(start=0.5, bpm=120.0)], cues=[
CuePoint(role="hotcue", slot=1, start=2.5, length=0.0, type="cue", color="#FF0045", name="In"),
CuePoint(role="hotcue", slot=1, start=4.5, length=0.0, type="cue"), # pad taken -> memory
CuePoint(role="memory", start=8.5, length=2.0, type="loop"),
])
def cover_art(self, i):
return (COVER, "image/jpeg") if i == str(ONE) else None
class CancelOnFirstBytes(JobHandle):
def progress(self, done=None, **kw):
super().progress(done=done, **kw)
if done:
self._job._cancel.set()
def run(adapter, handle_cls=JobHandle, track_ids=(str(ONE), str(TWO))):
plan = importer.plan(Source(), adapter, None, track_ids=list(track_ids))
return importer.run(Source(), adapter, plan, handle_cls(Job(id="t", kind="import")))
# ---- placement -----------------------------------------------------------------
print("== the library places the audio ==")
drive = copy_of()
a = OneLibraryAdapter(drive)
caps = a.capabilities()
check("an editable stick adds, removes, and places its own audio",
caps.tracks.addable and caps.tracks.removable and caps.tracks.places_audio)
check("a browsing one does neither", not OneLibraryAdapter(drive, read_only=True).capabilities().tracks.addable)
on_stick = drive / "Contents" / "Here.mp3"
on_stick.parent.mkdir(parents=True, exist_ok=True)
on_stick.write_bytes(b"x")
check("a file already on the stick is used where it is", a.place_audio(on_stick, Track(id="x")) is None)
target = a.place_audio(ONE, Track(id="x", artist="A/B: C", album="Album."))
final = a._store.final_of(target)
check("anything else is copied in through .konduktor-incoming/",
target.parent == drive / ".konduktor-incoming" and target.suffix == ".mp3")
check("to Contents/<Artist>/<Album>/, with characters FAT refuses replaced",
final == drive / "Contents" / "A_B_ C" / "Album" / "Kick One.mp3", str(final))
check("no artist or album: UnknownArtist / UnknownAlbum (rekordbox's names)",
a._store.final_of(a.place_audio(TWO, Track(id="y"))).parent
== drive / "Contents" / "UnknownArtist" / "UnknownAlbum")
long = SRC / ("L" * 60 + ".mp3")
long.write_bytes(b"x")
check("a long file name is cut to 48 characters, as rekordbox does",
len(a._store.final_of(a.place_audio(long, Track(id="z"))).name) == 48)
taken = drive / "Contents" / "UnknownArtist" / "UnknownAlbum" / "Kick Two.mp3"
taken.parent.mkdir(parents=True, exist_ok=True)
taken.write_bytes(b"x")
check("a name already taken on the stick gets a suffix",
a._store.final_of(a.place_audio(TWO, Track(id="y"))).name == "Kick Two-2.mp3")
a.close()
# ---- adding ----------------------------------------------------------------------
print("== an import into the stick ==")
drive = copy_of()
a = OneLibraryAdapter(drive)
before_n = rows(drive, "SELECT numberOfContents AS n FROM property")[0]["n"]
result = run(a)
one_id, two_id = result["track_ids"]
check("both tracks are added", result["tracks"] == 2)
check("the import saved, so the copies are in place and the incoming folder is gone",
(drive / one_id.lstrip("/")).is_file() and (drive / two_id.lstrip("/")).is_file()
and not (drive / ".konduktor-incoming").exists())
check("laid out as rekordbox does",
one_id == "/Contents/Konduktor_ Test/Probe EP/Kick One.mp3"
and two_id == "/Contents/UnknownArtist/UnknownAlbum/Kick Two.mp3", f"{one_id} {two_id}")
check("the projection plays them from there", a.track(one_id).filepath == str(drive / one_id.lstrip("/")))
cues = a.track_cues(one_id)
hot = [c for c in cues.cues if c.role == "hotcue"]
memory = sorted((c for c in cues.cues if c.role == "memory"), key=lambda c: c.start)
check("a hot cue keeps its pad, colour and name",
[(c.slot, round(c.start, 2), c.color, c.name) for c in hot] == [(1, 2.5, "#FF0045", "In")], str(hot))
check("a memory loop, and a hot cue whose pad was taken, cross as memory cues",
[(round(c.start, 2), c.type) for c in memory] == [(4.5, "cue"), (8.5, "loop")], str(memory))
check("its grid crosses", [(round(m.start, 3), m.bpm) for m in cues.grid_markers] == [(0.5, 120.0)],
str(cues.grid_markers))
check("a file with no grid gets Konduktor's", len(a.track_cues(two_id).grid_markers) == 1)
dat = drive / rows(drive, f"SELECT analysisDataFilePath AS p FROM content WHERE path = '{one_id}'")[0]["p"].lstrip("/")
check("its .DAT, .EXT and .2EX are on the stick",
all(dat.with_suffix(s).is_file() for s in (".DAT", ".EXT", ".2EX")))
row = rows(drive, f"SELECT * FROM content WHERE path = '{one_id}'")[0]
check("the row is shaped like rekordbox's own (search NULL, no counters, '' texts)",
row["titleForSearch"] is None and row["cueUpdateCount"] is None and row["hasModified"] == 0
and row["subtitle"] == "" and row["isrc"] == "" and row["contentLink"] == 788224
and row["analysedBits"] == 41, str(row))
check("with the file's facts", row["fileName"] == "Kick One.mp3" and row["fileType"] == 1
and row["samplingRate"] == 44100 and row["bpmx100"] == 12000 and row["rating"] == 4)
check("dates as YYYY-MM-DD text", len(row["dateAdded"]) == 10 and len(row["dateCreated"] or "") == 10)
check("the track count follows",
rows(drive, "SELECT numberOfContents AS n FROM property")[0]["n"] == before_n + 2)
image = rows(drive, f"SELECT path FROM image WHERE image_id = {row['image_id']}")[0]["path"]
art = drive / "PIONEER" / "Artwork" / "00001"
n = row["image_id"]
check("the cover is written as rekordbox writes it: a/b pairs, 80 and 240 px",
image == f"/PIONEER/Artwork/00001/b{n}.jpg"
and all((art / f"{x}{n}{s}.jpg").is_file() for x in "ab" for s in ("", "_m")))
check("and served as the track's art", a.cover_art(one_id)[1] == "image/jpeg")
lib = pdb.read((drive / "PIONEER" / "rekordbox" / "export.pdb").read_bytes())
new = {t["file_path"]: t for t in lib.tracks}
check("the Device Library lists both, with OneLibrary's ids",
new.get(one_id, {}).get("id") == row["content_id"] and two_id in new)
check("their analysis paths and artwork (the a<n> file) reach it too",
new[one_id]["analyze_path"] == row["analysisDataFilePath"]
and lib.artwork.get(new[one_id]["artwork_id"]) == f"/PIONEER/Artwork/00001/a{n}.jpg")
a.close()
print("== nothing is left behind ==")
drive = copy_of()
before = fingerprint(drive)
a = OneLibraryAdapter(drive)
try:
run(a, CancelOnFirstBytes)
cancelled = False
except JobCancelled:
cancelled = True
check("a cancel mid-copy leaves the stick exactly as it was",
cancelled and fingerprint(drive) == before and not a.dirty)
target = a.place_audio(ONE, Track(id="x", title="Kick"))
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(ONE, target)
[pending] = a.add_tracks([NewTrack(track=Track(id="x", title="Kick"), audio_path=target)])
check("an unsaved add plays from its incoming copy", a.track(pending).filepath == str(target))
a.reload()
check("Discard deletes the copy and leaves the stick as it was",
not target.exists() and fingerprint(drive) == before and a.track(pending) is None)
a.close()
(drive / ".konduktor-incoming").mkdir()
(drive / ".konduktor-incoming" / "crashed.mp3").write_bytes(b"x")
OneLibraryAdapter(drive, read_only=True).close()
check("a crash's leftovers survive a BROWSING open", (drive / ".konduktor-incoming").exists())
OneLibraryAdapter(drive).close()
check("and are cleared by the next editable one", not (drive / ".konduktor-incoming").exists())
# ---- removing ----------------------------------------------------------------------
print("== removing tracks ==")
drive = copy_of()
a = OneLibraryAdapter(drive)
by = lambda prefix: next(t for t in a.tracks if t.title.startswith(prefix)) # noqa: E731
victim = by("Demo Track 1")
audio = drive / victim.id.lstrip("/")
audio.parent.mkdir(parents=True, exist_ok=True)
audio.write_bytes(b"audio") # the fixture carries no audio
dat = a._store.layout.resolve(a._store.content(victim.id).analysisDataFilePath)
tian = by("Tian") # holds image 3, shared with nobody
n = a._store.content(tian.id).image_id
art = drive / "PIONEER" / "Artwork" / "00001"
art.mkdir(parents=True, exist_ok=True)
for x in "ab":
for s in ("", "_m"):
(art / f"{x}{n}{s}.jpg").write_bytes(b"jpg")
demos = next(p for p in a.playlist_tree() if p.name == "demos")
count = rows(drive, "SELECT numberOfContents AS n FROM property")[0]["n"]
check("removing two tracks reports two", a.remove_tracks([victim.id, tian.id]) == 2)
check("they leave the library and its playlists at once",
a.track(victim.id) is None and victim.id not in (a.playlist_entries(demos.id) or []))
check("but nothing is deleted before Save", audio.exists() and dat.exists() and (art / f"b{n}.jpg").exists())
a.save()
check("Save deletes the audio, the analysis files and the unshared artwork",
not audio.exists() and not dat.exists() and not dat.with_suffix(".EXT").exists()
and not any((art / f"{x}{n}{s}.jpg").exists() for x in "ab" for s in ("", "_m")))
check("and prunes the folders that left empty", not dat.parent.exists())
check("the drive's top-level folders stay", (drive / "Contents").is_dir() and (drive / "PIONEER" / "USBANLZ").is_dir())
seqs = [r["sequenceNo"] for r in rows(drive, f"SELECT sequenceNo FROM playlist_content "
f"WHERE playlist_id = {demos.id} ORDER BY sequenceNo")]
check("the playlist is renumbered from 1", seqs == list(range(1, len(seqs) + 1)), str(seqs))
check("no row anywhere names them",
not rows(drive, f"SELECT 1 FROM content WHERE path IN ('{victim.id}', '{tian.id}')")
and not rows(drive, f"SELECT 1 FROM image WHERE image_id = {n}"))
check("the track count follows", rows(drive, "SELECT numberOfContents AS n FROM property")[0]["n"] == count - 2)
lib = pdb.read((drive / "PIONEER" / "rekordbox" / "export.pdb").read_bytes())
check("and the Device Library drops them, their entries and the artwork row",
not {victim.id, tian.id} & {t["file_path"] for t in lib.tracks}
and all(t != 1 for _i, t, _p in lib.entries) and n not in lib.artwork)
a.close()
print("== removing a track added this session, before Save ==")
drive = copy_of()
before = fingerprint(drive)
a = OneLibraryAdapter(drive)
target = a.place_audio(ONE, Track(id="x", title="Kick"))
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(ONE, target)
[pending] = a.add_tracks([NewTrack(track=Track(id="x", title="Kick"), audio_path=target)])
a.remove_tracks([pending])
check("its copy is deleted at once", not target.exists())
a.save()
check("and the save leaves no trace of it",
not rows(drive, f"SELECT 1 FROM content WHERE path = '{pending}'")
and not (drive / pending.lstrip("/")).exists())
a.close()
print()
print("RESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+3 -85
View File
@@ -14,7 +14,6 @@ import shutil
import sys
import tempfile
import warnings
from types import SimpleNamespace
from pathlib import Path
warnings.filterwarnings("ignore")
@@ -32,7 +31,6 @@ from konduktor.adapters.rekordbox.cue_types import ( # noqa: E402
kind_for,
role_and_slot,
)
from konduktor.adapters.rekordbox import palette # noqa: E402
from konduktor.adapters.rekordbox.driver import RekordboxDriver # noqa: E402
from konduktor.adapters.rekordbox.projection import parse_key # noqa: E402
from konduktor.core import registry # noqa: E402
@@ -90,21 +88,6 @@ check("pad H is Kind 9", kind_for("hotcue", 7) == 9)
check("BeatLoopSize encodes (beats << 16) | 1", beat_loop_size(4) == 262145 and beat_loop_size(1) == 65537)
check("and decodes back", beats_in_loop(262145) == 4 and beats_in_loop(None) is None)
print("== hot cue colour palette ==")
# rekordbox has 16; the teal-green between 0x0E and 0x16 was never measured, and
# is left out rather than offered with a guessed RGB.
check("16 pickable swatches, without the observed-only red",
len(palette.SWATCHES) == 16 and 0x2B not in palette.SWATCHES)
check("a code projects as its measured RGB", palette.hex_for(0x16) == "#1AFF00")
check("uncoloured (None, or a loop's 0) projects as no colour",
palette.hex_for(None) is None and palette.hex_for(0) is None)
# The unmeasured teal-green is probably 0x12: claim nothing rather than guess.
check("an unknown code projects as no colour", palette.hex_for(0x12) is None)
check("a swatch maps back to its code, case-insensitively",
all(palette.swatch_code(palette.hex_for(c).lower()) == c for c in palette.SWATCHES))
# A user's pick must BE a swatch; nearest-hue is the exporter's rule, not an edit's.
check("a non-palette colour is not a swatch", palette.swatch_code("#123456") is None)
print("== key parsing (Rekordbox names keys musically, not in Camelot) ==")
check("Fm -> 4A", parse_key("Fm") == (4, "minor"))
check("Am -> 8A", parse_key("Am") == (8, "minor"))
@@ -320,9 +303,6 @@ with tempfile.TemporaryDirectory() as d:
# library, and the opposite of what the original plan assumed.
check("a loop is a cue type, not a separate bank", caps.cues.loops == "cue_type")
check("cue colour is a palette, not free RGB", caps.cues.color == "palette")
check("and the palette is the measured swatches",
caps.cues.palette == [palette.hex_for(c) for c in palette.SWATCHES],
str(caps.cues.palette))
check("the editable field set is advertised", bool(caps.tracks.editable_fields))
# Rekordbox has no column for these; Traktor does. Mapping them onto its
# Composer field would silently write the wrong thing.
@@ -337,6 +317,9 @@ with tempfile.TemporaryDirectory() as d:
print("== what Rekordbox genuinely cannot do still refuses, with a reason ==")
commands = {
"set_cover_art": lambda: adapter.set_cover_art(sample.id, b"", "image/jpeg"),
# A track spans rows in several tables plus ANLZ files; which of them
# Rekordbox expects deleted together is unmeasured.
"remove_tracks": lambda: adapter.remove_tracks([sample.id]),
# Rekordbox genuinely has no per-track grid lock, unlike Traktor's LOCK.
"set_grid_lock": lambda: adapter.set_grid_lock(sample.id, True),
"remap_locations": lambda: adapter.remap_locations(None),
@@ -445,71 +428,6 @@ with tempfile.TemporaryDirectory() as d:
_raises(lambda: adapter.set_cue(cue_track.id, slot=2, start_sec=-1.0,
cue_type="cue"), InvalidCommand))
print("== hot cue colours ==")
# Slot 0 holds a point cue at 1.0 s; put a loop in slot 7.
adapter.set_cue(cue_track.id, slot=7, start_sec=60.0, cue_type="loop", length_sec=1.92)
red, green = palette.hex_for(0x2A), palette.hex_for(0x16)
def slot_cue(tc, slot):
return next((c for c in tc.cues if c.slot == slot), None)
def mirror_of(slot):
import json
store = adapter._store
t = store._tables
row = store._db.session.query(t.ContentCue).filter(
t.ContentCue.ContentID == str(cue_track.id)).first()
kind = kind_for("hotcue", slot)
return next((r for r in json.loads(row.Cues) if r.get("Kind") == kind), None)
before = slot_cue(adapter.track_cues(cue_track.id), 0)
tc = adapter.set_cue_color(cue_track.id, 0, red.lower())
c0 = slot_cue(tc, 0)
check("a cue takes a palette colour", c0 is not None and c0.color == red, str(c0 and c0.color))
check("recolouring does not move it", c0 is not None and before is not None
and c0.start == before.start, f"{before and before.start} -> {c0 and c0.start}")
raw = adapter._store._cue_row(cue_track.id, 0)
check("stored as the palette code with Color -1",
raw.ColorTableIndex == 0x2A and raw.Color == -1, f"{raw.ColorTableIndex}/{raw.Color}")
m = mirror_of(0)
check("the contentCue mirror carries the colour",
m is not None and m.get("ColorTableIndex") == 0x2A and m.get("Color") == -1, str(m))
chip = next((h for h in adapter.track(cue_track.id).hotcues if h.slot == 0), None)
check("the table's hotcue dot shows it", chip is not None and chip.color == red,
str(chip))
# The colour belongs to the PAD: a rename, a move or a type change keeps it.
tc = adapter.set_cue(cue_track.id, slot=0, start_sec=3.0, cue_type="cue", name="Renamed")
check("re-setting the slot keeps its colour", slot_cue(tc, 0).color == red,
str(slot_cue(tc, 0).color))
tc = adapter.set_cue_color(cue_track.id, 7, green)
check("a loop takes a colour too", slot_cue(tc, 7).color == green)
raw = adapter._store._cue_row(cue_track.id, 7)
check("a coloured loop stores the code, not the loop's 255/0",
raw.ColorTableIndex == 0x16 and raw.Color == -1, f"{raw.ColorTableIndex}/{raw.Color}")
tc = adapter.set_cue_type(cue_track.id, 7, "cue")
check("a type change keeps the colour", slot_cue(tc, 7).color == green)
tc = adapter.place_cues(cue_track.id, [SimpleNamespace(slot=7, start=70.0, type="cue",
length=0.0, name="Drop")],
overwrite=True)
check("an Auto Hotcues Replace keeps the slot's colour", slot_cue(tc, 7).color == green)
tc = adapter.set_cue_color(cue_track.id, 0, None)
raw = adapter._store._cue_row(cue_track.id, 0)
check("Default makes it uncoloured again",
slot_cue(tc, 0).color is None and raw.ColorTableIndex is None and raw.Color == -1,
f"{raw.ColorTableIndex}/{raw.Color}")
adapter.set_cue(cue_track.id, slot=7, start_sec=60.0, cue_type="loop", length_sec=1.92)
adapter.set_cue_color(cue_track.id, 7, None)
raw = adapter._store._cue_row(cue_track.id, 7)
check("an uncoloured loop is back to Rekordbox's own 255/0",
raw.ColorTableIndex == 0 and raw.Color == 255, f"{raw.ColorTableIndex}/{raw.Color}")
adapter.delete_cue(cue_track.id, 0)
tc = adapter.set_cue(cue_track.id, slot=0, start_sec=1.0, cue_type="cue")
check("a new cue in an emptied slot starts uncoloured", slot_cue(tc, 0).color is None)
check("a colour outside the palette is refused",
_raises(lambda: adapter.set_cue_color(cue_track.id, 0, "#123456"), InvalidCommand))
check("recolouring an empty slot is NotFound",
_raises(lambda: adapter.set_cue_color(cue_track.id, 6, red), NotFound))
print("== beatgrid edits ==")
grid_track = next((t for t in adapter.tracks if t.bpm), None)
if grid_track:
-318
View File
@@ -202,52 +202,6 @@ with tempfile.TemporaryDirectory() as d:
changes = diff(before, dump(work))
check("an unsaved edit has written nothing to disk", not changes, describe(changes))
# ---- D2: the same for a playlist that already has entries -------------
# pyrekordbox's `remove_from_playlist` COMMITS, so replacing a non-empty
# list once wrote to disk at once — and raised while Rekordbox was running.
print("== D2: replacing a playlist's entries is held until save too ==")
from pyrekordbox.masterdb import database as rb_database # noqa: E402
clean_copy(REAL, work, closing=[adapter])
before = dump(work)
adapter = RekordboxAdapter(work)
filled = next((p for p in adapter.playlist_tree()
if p.kind == "playlist" and len(adapter.playlist_entries(p.id) or []) > 1),
None)
if filled is None:
print(" (skipped: no playlist with two entries)")
else:
original = adapter.playlist_entries(filled.id)
edited = list(reversed(original))[:-1] # reorder AND drop one
adapter.set_playlist_entries(filled.id, edited)
check("the projection shows the new order",
adapter.playlist_entries(filled.id) == edited)
changes = diff(before, dump(work))
check("nothing is on disk before save", not changes, describe(changes))
adapter.reload()
check("discarding restores the original entries",
adapter.playlist_entries(filled.id) == original)
real_probe = rb_database.get_rekordbox_pid
rb_database.get_rekordbox_pid = lambda: 4242 # "Rekordbox is running"
try:
adapter.set_playlist_entries(filled.id, edited)
check("an edit while Rekordbox runs does not fail", True)
except Exception as ex: # noqa: BLE001
check("an edit while Rekordbox runs does not fail", False, repr(ex))
finally:
rb_database.get_rekordbox_pid = real_probe
adapter.reload()
adapter.set_playlist_entries(filled.id, edited)
adapter.save()
adapter.close()
adapter = RekordboxAdapter(work)
check("after save the new entries are on disk",
adapter.playlist_entries(filled.id) == edited)
changes = diff(before, dump(work))
check("and nothing outside the playlist's rows and the counter changed",
{t for t, _, _, _ in changes} <= {"djmdSongPlaylist", "agentRegistry"},
describe(changes))
# ---- E: playlist edits -----------------------------------------------
print("== E: a playlist round-trips ==")
clean_copy(REAL, work, closing=[adapter])
@@ -464,277 +418,5 @@ with tempfile.TemporaryDirectory() as d:
str(fields.get("BPM")))
adapter.close()
# ---- I: removing a track does what Rekordbox 7 itself does -----------
# Measured 2026-10-01 by removing a track in Rekordbox and diffing: its
# rows are DELETED (not flagged) from djmdContent, djmdCue, contentCue,
# contentFile, djmdMixerParam and djmdSongPlaylist, the playlist row is
# left alone, and the files contentFile lists go with their folders.
print("== I: removing a track deletes exactly what Rekordbox deletes ==")
from konduktor.core.adapter import Unsupported # noqa: E402
clean_copy(REAL, work)
before = dump(work)
measured = ("djmdCue", "contentCue", "contentFile", "djmdMixerParam", "djmdSongPlaylist")
sampler = {str(r["ContentID"]) for r in before.get("djmdSongSampler", {}).values()}
songs = before["djmdSongPlaylist"].values()
# The FIRST entry of the longest playlist, so the entries after it must
# be renumbered.
by_list: dict[str, list] = {}
for r in songs:
by_list.setdefault(str(r["PlaylistID"]), []).append(r)
longest = max(by_list.values(), key=len, default=[])
first = min(longest, key=lambda r: r["TrackNo"]) if len(longest) > 1 else None
if first is None or str(first["ContentID"]) in sampler:
print(" (skipped: no playlist with two entries to remove from)")
else:
victim = str(first["ContentID"])
playlist_id = str(first["PlaylistID"])
listed = [r["Path"] for r in before["contentFile"].values()
if str(r["ContentID"]) == victim]
files = [p for p in listed if p.startswith("/PIONEER/USBANLZ/")]
art = [p for p in listed if p.startswith("/PIONEER/Artwork/")]
adapter = RekordboxAdapter(work)
n_tracks = len(adapter.tracks)
check("remove_tracks reports one track removed", adapter.remove_tracks([victim]) == 1)
check("it leaves the projection at once",
adapter.track(victim) is None and len(adapter.tracks) == n_tracks - 1)
check("and its playlist", victim not in adapter.playlist_entries(playlist_id))
check("the adapter is dirty", adapter.dirty is True)
check("nothing is on disk before save", not diff(before, dump(work)))
check("its analysis files are still there before save",
all((Path(d) / "share" / p.lstrip("/")).is_file() for p in files))
adapter.save()
changes = diff(before, dump(work))
expected_deletes = {("djmdContent", victim)} | {
(t, pk) for t in measured for pk, r in before[t].items()
if str(r.get("ContentID")) == victim
}
deletes = {(t, pk) for t, pk, kind, _ in changes if kind == "DELETE"}
check("exactly the measured rows are deleted", deletes == expected_deletes,
f"extra {sorted(deletes - expected_deletes)} missing "
f"{sorted(expected_deletes - deletes)}")
check("nothing is inserted", not [c for c in changes if c[2] == "INSERT"])
updates = {(t, pk): f for t, pk, kind, f in changes if kind == "UPDATE"}
later = {pk for pk, r in before["djmdSongPlaylist"].items()
if str(r["PlaylistID"]) == playlist_id and r["TrackNo"] > first["TrackNo"]}
check("only the counter and the later entries' TrackNo move",
set(updates) == {("agentRegistry", "localUpdateCount")}
| {("djmdSongPlaylist", pk) for pk in later}, describe(changes))
check("each later entry moves up by one",
all(updates[("djmdSongPlaylist", pk)]["TrackNo"][1]
== before["djmdSongPlaylist"][pk]["TrackNo"] - 1 for pk in later))
check("the playlist row itself is left alone",
("djmdPlaylist", playlist_id) not in updates)
check("the track's analysis files are deleted",
not any((Path(d) / "share" / p.lstrip("/")).exists() for p in files), str(files))
check("and their emptied folder",
not any((Path(d) / "share" / p.lstrip("/")).parent.exists() for p in files))
# Unmeasured (the measured track had none), so left in place.
check("its artwork is left alone",
all((Path(d) / "share" / p.lstrip("/")).is_file() for p in art))
check("the analysis root is kept",
(Path(d) / "share" / "PIONEER" / "USBANLZ").is_dir())
adapter.close()
reopened = RekordboxAdapter(work)
check("the track is gone after a reopen", reopened.track(victim) is None)
reopened.close()
# A table that was EMPTY in the measured library is not guessed at.
if sampler:
clean_copy(REAL, work)
adapter = RekordboxAdapter(work)
target = next(iter(sampler))
try:
adapter.remove_tracks([adapter.tracks[0].id, target])
check("a track in the Sampler is refused", False)
except Unsupported as ex:
check("a track in the Sampler is refused", "Sampler" in str(ex), str(ex))
check("and the whole batch changed nothing",
adapter.dirty is False and adapter.track(target) is not None)
adapter.close()
# ---- J: adding tracks writes what Rekordbox 7 itself writes ------------
# Measured 2026-10-01 by dragging two files into Rekordbox and diffing: a
# djmdContent row filled from the FILE, analysis files + artwork under
# share/, and one contentFile row per file whose Hash is its MD5. A plain
# file gets Konduktor's own grid (decided 2026-10-01); one that brings a
# grid keeps it, and its cues cross as themselves.
print("== J: adding tracks writes rows and files the way Rekordbox does ==")
import hashlib # noqa: E402
import av # noqa: E402
import numpy as np # noqa: E402
from konduktor.core.adapter import InvalidCommand, NewTrack # noqa: E402
from konduktor.core.model import CuePoint, GridMarker, Track, TrackCues # noqa: E402
BPM, FIRST, SR = 128.0, 0.5, 44100
def kick_mp3(path: Path, seconds: float = 30.0) -> Path:
"""A kick every beat at BPM from FIRST — a grid with a known answer."""
n = int(seconds * SR)
y = np.zeros(n, dtype=np.float32)
t = np.arange(int(0.12 * SR)) / SR
kick = (np.sin(2 * np.pi * 55 * t) * np.exp(-t * 30)).astype(np.float32)
beat = FIRST
while beat < seconds - 0.2:
i = int(beat * SR)
y[i:i + len(kick)] += kick[: n - i]
beat += 60.0 / BPM
x = np.vstack([y, y]) * 0.8
with av.open(str(path), "w", format="mp3") as c:
s = c.add_stream("libmp3lame", rate=SR, layout="stereo")
s.bit_rate = 320_000
step = s.codec_context.frame_size or 1152
for i in range(0, n, step):
f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, i:i + step]),
format="fltp", layout="stereo")
f.sample_rate, f.pts = SR, i
for p in s.encode(f):
c.mux(p)
for p in s.encode(None):
c.mux(p)
return path
def jpeg() -> bytes:
import io
from PIL import Image
buf = io.BytesIO()
Image.new("RGB", (300, 200), (200, 40, 90)).save(buf, "JPEG")
return buf.getvalue()
audio_dir = Path(d) / "added"
audio_dir.mkdir()
plain = kick_mp3(audio_dir / "plain.mp3")
prepped = kick_mp3(audio_dir / "prepped.mp3")
from mutagen.id3 import APIC, ID3 # noqa: E402
tags = ID3()
tags.add(APIC(encoding=3, mime="image/jpeg", type=3, desc="", data=jpeg()))
tags.save(str(plain)) # embedded art: read off the file
cues = TrackCues(
grid_markers=[GridMarker(start=0.75, bpm=125.0)], # the source's own grid
cues=[
CuePoint(role="hotcue", slot=0, start=2.0, length=0.0, color="#FF0000"),
CuePoint(role="hotcue", slot=2, start=6.0, length=4.0, name="Loop"),
CuePoint(role="memory", slot=None, start=9.0, length=0.0),
],
)
items = [
NewTrack(track=Track(id="src:1", title="Konduktor Add Plain",
artist="Konduktor Add Artist", release_date="2021-03-04"),
audio_path=plain),
NewTrack(track=Track(id="src:2", title="Konduktor Add Prepped",
key_wheel=10, key_mode="minor"),
audio_path=prepped, cues=cues, art=(jpeg(), "image/jpeg")),
]
clean_copy(REAL, work)
before = dump(work)
share_before = {p for p in (Path(d) / "share").rglob("*") if p.is_file()}
adapter = RekordboxAdapter(work)
calls = []
def cancel(message, *, step, of):
calls.append((step, of))
if step == 2:
raise RuntimeError("cancelled")
try:
adapter.add_tracks(items, checkpoint=cancel)
check("a raising checkpoint cancels", False)
except RuntimeError:
check("a raising checkpoint cancels", True)
check("before touching the library", adapter.dirty is False
and len(adapter.tracks) == len(before["djmdContent"]), str(calls))
steps = []
ids = adapter.add_tracks(items, checkpoint=lambda m, *, step, of: steps.append((step, of)))
check("each file is a checkpoint", steps == [(1, 2), (2, 2)], str(steps))
check("two ids come back, in order", len(ids) == 2 and all(adapter.track(i) for i in ids))
check("the projection has them at once",
[adapter.track(i).title for i in ids] == ["Konduktor Add Plain", "Konduktor Add Prepped"])
check("nothing is on disk before save", not diff(before, dump(work)))
check("no file is written before save",
{p for p in (Path(d) / "share").rglob("*") if p.is_file()} == share_before)
try:
adapter.add_tracks([items[0]])
check("adding a file the library holds is refused", False)
except InvalidCommand:
check("adding a file the library holds is refused", True)
adapter.save()
changes = diff(before, dump(work))
new_rows = {t for t, _, kind, _ in changes if kind == "INSERT"}
check("only new rows, plus the counter",
{(t, kind) for t, _, kind, _ in changes} - {(t, "INSERT") for t in new_rows}
== {("agentRegistry", "UPDATE")}, describe(changes))
check("into the tables Rekordbox writes for a new track",
new_rows <= {"djmdContent", "djmdCue", "contentCue", "contentFile",
"djmdArtist", "djmdKey"}, str(sorted(new_rows)))
after = dump(work)
rows = {i: after["djmdContent"][i] for i in ids}
plain_row, prepped_row = rows[ids[0]], rows[ids[1]]
check("the row is filled from the file",
plain_row["SampleRate"] == SR and plain_row["BitRate"] == 320
and plain_row["Length"] == 30 and plain_row["FileSize"] == plain.stat().st_size,
str({k: plain_row[k] for k in ("SampleRate", "BitRate", "Length", "FileSize")}))
check("stamped with this library's device",
plain_row["DeviceID"] == next(iter(before["djmdContent"].values()))["DeviceID"])
check("the release year is kept", plain_row["ReleaseYear"] == 2021)
check("the key is rendered, not copied", prepped_row["KeyID"] is not None)
files: dict[str, list] = {}
for r in after["contentFile"].values():
files.setdefault(str(r["ContentID"]), []).append(r)
for tid, label in ((ids[0], "plain"), (ids[1], "prepped")):
listed = files.get(tid, [])
paths = sorted(Path(r["Path"]).name for r in listed)
check(f"{label}: contentFile lists its analysis and artwork",
paths == ["ANLZ0000.2EX", "ANLZ0000.DAT", "ANLZ0000.EXT", "artwork.jpg"], str(paths))
on_disk = [Path(d) / "share" / r["Path"].lstrip("/") for r in listed]
check(f"{label}: each Hash is the file's MD5 and Size its size",
all(p.is_file() and r["Hash"] == hashlib.md5(p.read_bytes()).hexdigest()
and r["Size"] == p.stat().st_size for p, r in zip(on_disk, listed)))
art_dir = (Path(d) / "share" / rows[tid]["ImagePath"].lstrip("/")).parent
check(f"{label}: artwork in three sizes",
sorted(p.name for p in art_dir.iterdir())
== ["artwork.jpg", "artwork_m.jpg", "artwork_s.jpg"])
adapter.close()
reopened = RekordboxAdapter(work)
plain_cues = reopened.track_cues(ids[0])
markers = plain_cues.grid_markers if plain_cues else []
check("a plain file gets Konduktor's grid", len(markers) == 1
and abs(markers[0].bpm - BPM) < 0.05, str(markers))
if markers:
period = 60.0 / BPM
off = (markers[0].start - FIRST) % period
check("on the kick, in the decoded time base",
min(off, period - off) < 0.015, f"{markers[0].start:.4f}")
check("and its BPM column", rows[ids[0]]["BPM"] == 12800, str(rows[ids[0]]["BPM"]))
got = reopened.track_cues(ids[1])
check("a source's grid is kept as it was",
got and [(round(m.start, 3), m.bpm) for m in got.grid_markers] == [(0.75, 125.0)],
str(got.grid_markers if got else None))
by_role = {(c.role, c.slot): c for c in (got.cues if got else [])}
hot = by_role.get(("hotcue", 0))
check("a hot cue keeps its pad and position",
hot is not None and abs(hot.start - 2.0) < 0.002, str(hot))
check("and its colour, as a palette swatch", hot is not None and hot.color is not None)
loop = by_role.get(("hotcue", 2))
check("a loop stays a loop on its pad",
loop is not None and loop.type == "loop" and abs(loop.length - 4.0) < 0.002, str(loop))
memory = [c for c in (got.cues if got else []) if c.role == "memory"]
check("a memory cue stays a memory cue",
len(memory) == 1 and abs(memory[0].start - 9.0) < 0.002, str(memory))
# Removing an added track takes its analysis files with it.
dat = Path(d) / "share" / rows[ids[0]]["AnalysisDataPath"].lstrip("/")
reopened.remove_tracks([ids[0]])
reopened.save()
check("removing it again deletes its analysis files", not dat.exists())
reopened.close()
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
-20
View File
@@ -108,26 +108,6 @@ if real_nml.is_file():
check("the NML value is the one Traktor wrote on every stem entry", values == {sf.NML_STEMS_JSON}, str(len(values)))
else:
print(" (skipped: the real collection is not on this machine)")
# How a stem file that Konduktor did NOT write gets its `<STEMS>` when added:
# rendered from its own box by Traktor's rule.
check("Traktor's rendering rule turns the box literal into the NML literal",
sf.traktor_stems_json(sf.STEM_BOX_JSON) == sf.NML_STEMS_JSON)
check("…and keeps other names, colours and values (keys sorted, whole floats as integers)",
sf.traktor_stems_json(b'{"version": 1, "stems": [{"name": "Kick \\u00e9", "color": "#010203"}], '
b'"x": {"b": 2.5, "a": 3.0, "c": true}}')
== '{"stems":[{"color":"#010203","name":"Kick é"}],"version":1,"x":{"a":3,"b":2.5,"c":true}}')
nml_stem_entries = {}
for n in (real_nml, Path.home() / "Downloads/collection.nml"):
if n.is_file():
for file, value in re.findall(r'FILE="([^"]+)"(?:(?!</ENTRY>).)*?<STEMS STEMS="([^"]*)"',
n.read_text(encoding="utf-8"), re.S):
nml_stem_entries[html.unescape(file)] = html.unescape(value)
pairs = [(p, nml_stem_entries[p.name]) for p in commercial if p.name in nml_stem_entries]
if pairs:
check(f"…and gives exactly what Traktor wrote for {len(pairs)} stem files in its collections",
all(sf.nml_stems_for(p) == v for p, v in pairs))
else:
print(" (skipped: no stem file with a Traktor entry on this machine)")
print("== 2. decode: mono level, resampling does not move time ==")
m = np.zeros((1, 44100), np.float32)
-241
View File
@@ -1,241 +0,0 @@
"""Stem playback on the deck — the backend half: a stem file's stems served one
by one, because a browser decodes only an MP4's first audio stream (the mix).
Pins what would fail silently:
* a served stem is BIT-IDENTICAL to decoding that stream in place, edit list
and all — a stem shifted by its priming would flam against the others and
sit off every cue;
* "is this a stem file" is read from the FILE: an MP3 whose collection entry
carries `<STEMS>` (105 real ones do) has no stems to play;
* the cache follows the file (an edited file is not served stale) and stays
within its limit without evicting what it just wrote;
* all three origins (collection, device, folder) serve them.
Everything is generated: a stem file built with a FAKE separator whose four
stems are distinct scalings of the mix, so each served stem can be told apart.
"""
from __future__ import annotations
import html
import os
import re
import shutil
import sys
import tempfile
import time
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-stemplay-appdata-")
import av # noqa: E402
import numpy as np # noqa: E402
from fastapi.testclient import TestClient # noqa: E402
import konduktor.main as main # noqa: E402
from konduktor.adapters.traktor.locations import os_path_to_location # noqa: E402
from konduktor.adapters.traktor.store import TraktorStore # noqa: E402
from konduktor.core import stem_file as sf # noqa: E402
from konduktor.stems import stream_cache # noqa: E402
from stem_test_support import make_mp3 # noqa: E402
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
def decode(path: Path, stream: int = 0) -> np.ndarray:
with av.open(str(path)) as c:
return np.concatenate([f.to_ndarray() for f in c.decode(c.streams.audio[stream])], axis=1)
GAINS = (0.5, 0.25, -0.2, 0.1)
ROOT = Path(tempfile.mkdtemp(prefix="konduktor-stemplay-"))
music = ROOT / "Music"
music.mkdir()
stem = music / "Tune.stem.m4a"
sf.build(make_mp3(ROOT / "src.mp3", seconds=6), stem, lambda p: [p * g for g in GAINS])
plain = make_mp3(music / "Plain.mp3", seed=7)
tagged = make_mp3(music / "Tagged.mp3", seed=8) # its ENTRY will carry <STEMS>
print("== stem_file: what a file carries ==")
layout = sf.stem_layout(stem)
check("a stem file lists its four stems with names and colours, in stream order",
[s["name"] for s in layout or []] == ["Drums", "Bass", "Synths", "Vox"]
and all(s["color"].startswith("#") for s in layout), str(layout))
check("a plain MP3 has none", sf.stem_layout(plain) is None)
check("a missing file has none (no exception)", sf.stem_layout(ROOT / "nope.stem.m4a") is None)
print("== a temp collection pointing at them ==")
work = ROOT / "collection.nml"
shutil.copy2(REAL, work)
st = TraktorStore(work)
entries = [e for e in st._nml.collection.entry if e.location][:3]
ids = []
for e, path in zip(entries, (stem, plain, tagged)):
e.location.volume, e.location.dir, e.location.file = os_path_to_location(path)
ids.append(st._key_of(e))
from traktor_nml_utils.models.collection import Stemstype # noqa: E402
entries[2].stems = Stemstype(stems=sf.NML_STEMS_JSON)
st._entry_by_key = {st._key_of(x): x for x in st._nml.collection.entry if x.location}
st.save()
stem_id, plain_id, tagged_id = ids
with TestClient(main.app) as c:
assert c.post("/api/library/open", json={"path": str(work)}).status_code == 200
print("== the collection routes ==")
r = c.get("/api/tracks/stems", params={"track_id": stem_id}).json()
check("/api/tracks/stems lists the stem file's stems", r["stems"] == layout, str(r))
check("…none for a plain MP3", c.get("/api/tracks/stems", params={"track_id": plain_id}).json()["stems"] == [])
tagged_track = c.get("/api/tracks", params={"limit": 20000}).json()
tagged_kind = next((t["media_kind"] for t in tagged_track["items"] if t["id"] == tagged_id), None) \
if isinstance(tagged_track, dict) and "items" in tagged_track else None
check("…and none for an MP3 the COLLECTION calls a stem track (decided by the file)",
c.get("/api/tracks/stems", params={"track_id": tagged_id}).json()["stems"] == [],
f"media_kind={tagged_kind}")
mix = decode(stem, 0)
for k in range(4):
r = c.get("/api/tracks/audio", params={"track_id": stem_id, "stem": k})
ok = r.status_code == 200 and r.headers["content-type"].startswith("audio/mp4")
got = ROOT / f"served-{k}.m4a"
got.write_bytes(r.content if ok else b"")
same = ok and np.array_equal(decode(got), decode(stem, k + 1))
check(f"stem {k} is served as its own MP4, bit-identical to stream {k + 1} in place", same)
if same:
s = decode(got)
n = min(s.shape[1], mix.shape[1])
# The fake stems are the mix scaled: the right stream, not just A stream.
ratio = float(np.dot(s[0, :n], mix[0, :n]) / np.dot(mix[0, :n], mix[0, :n]))
check(f"…and it is stem {k} (gain {GAINS[k]:+.2f}, measured {ratio:+.2f}), same length as the mix",
abs(ratio - GAINS[k]) < 0.05 and s.shape[1] == mix.shape[1], f"{ratio} {s.shape} {mix.shape}")
check("the plain audio route still serves the whole file",
c.get("/api/tracks/audio", params={"track_id": stem_id}).content == stem.read_bytes())
check("a stem out of range is 404",
c.get("/api/tracks/audio", params={"track_id": stem_id, "stem": 4}).status_code == 404)
check("asking a plain MP3 for a stem is 404",
c.get("/api/tracks/audio", params={"track_id": plain_id, "stem": 0}).status_code == 404)
print("== the cache ==")
cached = stream_cache.stem_file_for(stem, 0)
check("a second request reuses the cached file", stream_cache.stem_file_for(stem, 0) == cached)
st_ = stem.stat()
os.utime(stem, ns=(st_.st_atime_ns, st_.st_mtime_ns + 10_000_000_000))
check("an edited source gets a fresh file, never the stale one", stream_cache.stem_file_for(stem, 0) != cached)
before = sorted(stream_cache.root().glob("*.m4a"))
stream_cache.LIMIT = 1 # everything is over the limit now
newest = stream_cache.stem_file_for(stem, 3)
after = sorted(stream_cache.root().glob("*.m4a"))
check("over its limit the cache evicts the least recently used…", len(before) >= 2 and after == [newest],
f"{len(before)} -> {[p.name for p in after]}")
check("…but never the file it just wrote", newest.exists() and newest in after)
check("no partial file is left behind", not list(stream_cache.root().glob("*.part")))
stream_cache.LIMIT = 2 * 1024 ** 3
print("== the folder origin ==")
listing = c.get("/api/folder/tracks", params={"path": str(music)})
check("(setup) the folder lists", listing.status_code == 200, listing.text[:200])
fid = str(stem)
r = c.get("/api/folder/tracks/stems", params={"track_id": fid})
check("a stem file browsed in a folder lists its stems", r.status_code == 200 and r.json()["stems"] == layout,
r.text[:200])
r = c.get("/api/folder/tracks/audio", params={"track_id": fid, "stem": 1})
got = ROOT / "folder-1.m4a"
got.write_bytes(r.content)
check("…and serves them", r.status_code == 200 and np.array_equal(decode(got), decode(stem, 2)))
kinds = {t["id"]: t["media_kind"] for t in listing.json()["tracks"]}
check("the listing marks the stem file as a stem track and the MP3 as audio",
kinds.get(str(stem)) == "stem" and kinds.get(str(plain)) == "audio", str(kinds))
print("== adding a stem file to the collection ==")
extra_dir = ROOT / "More"
extra_dir.mkdir()
extra = extra_dir / "Other.stem.m4a"
shutil.copy2(stem, extra)
extra_plain = make_mp3(extra_dir / "Other.mp3", seed=9)
assert c.get("/api/folder/tracks", params={"path": str(extra_dir)}).status_code == 200
pl_id = c.post("/api/playlists", json={"name": "Stem Adds"}).json()["id"]
job = c.post("/api/folder/add", json={"track_ids": [str(extra), str(extra_plain)],
"mode": "reference", "playlist_id": pl_id}).json()
while job["state"] == "running":
time.sleep(0.05)
job = c.get(f"/api/jobs/{job['id']}").json()
check("(setup) the add finishes", job["state"] == "done", str(job))
new_stem, new_plain = job["result"]["track_ids"]
kinds = {t["id"]: t["media_kind"] for t in c.get("/api/tracks", params={"limit": 20000}).json()["items"]}
check("the added stem file is a stem track, the MP3 beside it audio",
kinds.get(new_stem) == "stem" and kinds.get(new_plain) == "audio", f"{kinds.get(new_stem)} {kinds.get(new_plain)}")
saved = work.read_text(encoding="utf-8")
def entry_of(name: str) -> str:
at = saved.find(f'FILE="{name}"')
return saved[at:saved.find("</ENTRY>", at)] if at >= 0 else ""
m = re.search(r'<STEMS STEMS="([^"]*)"', entry_of(extra.name))
check("…its saved ENTRY carries <STEMS>, rendered as Traktor renders that file's box",
m is not None and html.unescape(m.group(1)) == sf.NML_STEMS_JSON, entry_of(extra.name)[:300])
check("…the MP3's carries none", entry_of(extra_plain.name) != "" and "<STEMS" not in entry_of(extra_plain.name))
check('…and the playlist keys the stem file TYPE="STEM", the MP3 TYPE="TRACK"',
re.search(r'<PRIMARYKEY TYPE="STEM" KEY="[^"]*Other\.stem\.m4a"', saved) is not None
and re.search(r'<PRIMARYKEY TYPE="TRACK" KEY="[^"]*Other\.mp3"', saved) is not None)
# Rekordbox has no <STEMS>: the FILE decides, so the Type column agrees
# with the deck, which plays a stem file's stems on every platform.
print("== adding a stem file to a Rekordbox library ==")
from konduktor.adapters.rekordbox import discovery as rb_discovery
found = rb_discovery.detect_libraries()
if not found:
print(" (skipped: no Rekordbox library on this machine)")
else:
rb_src = Path(found[0]["path"]).parent
rb_dir = ROOT / "rekordbox"
rb_dir.mkdir()
for name in ("master.db", "masterPlaylists6.xml"):
if (rb_src / name).exists():
shutil.copy2(rb_src / name, rb_dir / name)
if (rb_src / "share").is_dir():
shutil.copytree(rb_src / "share", rb_dir / "share")
rb_stem_dir = ROOT / "ForRekordbox"
rb_stem_dir.mkdir()
rb_stem = rb_stem_dir / "Rb.stem.m4a"
shutil.copy2(stem, rb_stem)
rb_plain = make_mp3(rb_stem_dir / "Rb.mp3", seed=11)
r = c.post("/api/library/open", json={"path": str(rb_dir / "master.db")})
check("(setup) a Rekordbox copy opens", r.status_code == 200, r.text[:300])
assert c.get("/api/folder/tracks", params={"path": str(rb_stem_dir)}).status_code == 200
job = c.post("/api/folder/add", json={"track_ids": [str(rb_stem), str(rb_plain)],
"mode": "reference"}).json()
while job["state"] == "running":
time.sleep(0.05)
job = c.get(f"/api/jobs/{job['id']}").json()
check("(setup) the add finishes", job["state"] == "done", str(job))
rb_new_stem, rb_new_plain = (job.get("result") or {}).get("track_ids") or [None, None]
def rb_kinds():
items = c.get("/api/tracks", params={"limit": 20000}).json()["items"]
return {t["id"]: t["media_kind"] for t in items}
kinds = rb_kinds()
check("the added stem file is a stem track, the MP3 beside it audio",
kinds.get(rb_new_stem) == "stem" and kinds.get(rb_new_plain) == "audio",
f"{kinds.get(rb_new_stem)} {kinds.get(rb_new_plain)}")
r = c.post("/api/library/open", json={"path": str(rb_dir / "master.db")})
kinds = rb_kinds()
check("…and still after a reopen",
kinds.get(rb_new_stem) == "stem" and kinds.get(rb_new_plain) == "audio",
f"{kinds.get(rb_new_stem)} {kinds.get(rb_new_plain)}")
r = c.get("/api/tracks/stems", params={"track_id": rb_new_stem})
check("and the deck is offered its stems",
r.status_code == 200 and len(r.json()["stems"]) == 4, r.text[:200])
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
-277
View File
@@ -1,277 +0,0 @@
"""The Convert to Stems batch end to end, through the routes, with a FAKE engine.
Against temp copies of the real collection whose playlisted tracks are pointed
at generated MP3s. What would fail silently or destroy something:
* skips are reported with reasons (missing, already a stem file, target
exists, two sources onto one target) and never converted;
* a Replace batch leaves the SAVED collection untouched, parks the originals,
swaps every entry at the end — prep unmoved in decoded time — and blocks
the operations that would save or drop the swap;
* Save deletes the parked originals and retargets export sets; Discard and
opening another library put them back;
* Cancel deletes what the run made and nothing else; one bad track fails
alone;
* destination + add mirrors the tree, never touches the originals, fills a
new playlist;
* after a CRASH, the next open restores (or, if the save got through,
finishes) from what the saved collection says — and keeps the finished
stem files, which the next batch reuses without separating again.
"""
from __future__ import annotations
import json
import os
import shutil
import sys
import tempfile
import time
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-stemsbatch-appdata-")
os.environ.pop("KONDUKTOR_NML", None)
from fastapi.testclient import TestClient # noqa: E402
import konduktor.main as main # noqa: E402
from konduktor import exports # noqa: E402
from konduktor.adapters.traktor.locations import os_path_to_location # noqa: E402
from konduktor.adapters.traktor.store import TraktorStore # noqa: E402
from konduktor.core import stem_file as sf # noqa: E402
from konduktor.stems import engine_manager as em # noqa: E402
from konduktor.stems.pending import parked_name, partial_name # noqa: E402
from stem_test_support import install_fake_engine, make_mp3 # noqa: E402
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
ROOT = Path(tempfile.mkdtemp(prefix="konduktor-stemsbatch-"))
em._DEFAULT = install_fake_engine(ROOT / "engine")
def library(name: str, files: list[str]) -> tuple[Path, list[str], Path]:
"""A temp collection whose first len(files) playlisted tracks point at
`files` in a music folder (each created as an MP3 unless it is 'missing'),
each with a hotcue at 1.000 s and a grid at 0.500 s, saved."""
d = ROOT / name
music = d / "Music"
music.mkdir(parents=True)
work = d / "collection.nml"
shutil.copy2(REAL, work)
st = TraktorStore(work)
in_pl = {k for n in st._iter_nodes(st._root()) if n.playlist for k in st._entry_keys_of(n.playlist)}
entries = [e for e in st._nml.collection.entry if e.location and st._key_of(e) in in_pl and e.stems is None]
ids = []
for f, e in zip(files, entries):
path = music / f
if f.endswith(".mp3") and not f.startswith("missing"):
make_mp3(path, seed=len(ids) + 1)
old = st._key_of(e)
e.location.volume, e.location.dir, e.location.file = os_path_to_location(path)
new = st._key_of(e)
for n in st._iter_nodes(st._root()):
for pe in (n.playlist.entry if n.playlist else None) or []:
if pe.primarykey and pe.primarykey.key == old:
pe.primarykey.key = new
st._entry_by_key = {st._key_of(x): x for x in st._nml.collection.entry if x.location}
e.cue_v2 = []
if path.exists():
st.set_hotcue(new, 1, 1.0, 0, name="Drop")
st.replace_grid(new, [(0.5, 120.0)])
ids.append(new)
st.save()
return work, ids, music
def open_lib(c, work):
r = c.post("/api/library/open", json={"path": str(work)})
assert r.status_code == 200, r.text
def wait(c, jid, timeout=60):
end = time.time() + timeout
while time.time() < end:
j = c.get(f"/api/jobs/{jid}").json()
if j["state"] != "running":
return j
time.sleep(0.05)
raise AssertionError("job did not finish")
def convert(c, ids, **opts):
r = c.post("/api/tracks/stems/convert", json={"track_ids": ids, "mode": "replace", **opts})
assert r.status_code == 200, r.text
return wait(c, r.json()["id"])
with TestClient(main.app) as c:
print("== preview: skips, with reasons ==")
work, ids, music = library("preview", ["ok.mp3", "missing.mp3", "have.mp3", "dup.mp3", "dup.m4a", "stemsrc.mp3"])
sf.build(make_mp3(ROOT / "tmp-src.mp3"), music / "already.stem.m4a", lambda p: [p * g for g in (0.5, 0.25, -0.2, 0.1)])
(music / "have.stem.m4a").write_bytes(b"a stem the user already owns")
make_mp3(music / "dup.m4a") # (MP3 bytes under an .m4a name: only its target name matters here)
st = TraktorStore(work)
e = st.model_entry(ids[5])
e.location.file = "already.stem.m4a"
st._entry_by_key = {st._key_of(x): x for x in st._nml.collection.entry if x.location}
ids[5] = st._key_of(e)
st.save()
open_lib(c, work)
pv = c.post("/api/tracks/stems/preview", json={"track_ids": ids, "mode": "replace"}).json()
reasons = [s["reason"] for s in pv["skipped"]]
check("the convertible tracks are planned (ok.mp3, dup.mp3)",
sorted(Path(x["target"]).name for x in pv["convert"]) == ["dup.stem.m4a", "ok.stem.m4a"], str(pv["convert"]))
check("a missing file is skipped, saying so", any("missing" in r for r in reasons), str(reasons))
check("a file that is already a stem file is skipped", any("already a stem file" in r for r in reasons))
check("an existing target is skipped, NEVER overwritten", any("already exists" in r for r in reasons)
and (music / "have.stem.m4a").read_bytes() == b"a stem the user already owns")
check("two sources onto one target (dup.mp3 + dup.m4a): the second is skipped",
any("same file" in r for r in reasons), str(reasons))
check("no disk-space block for a few small files", pv["blocked"] is None, str(pv["blocked"]))
print("== Replace: convert, park, swap at the end; the saved file untouched ==")
work, ids, music = library("replace", ["a.mp3", "b.mp3"])
open_lib(c, work)
a = main.require_adapter()
before = {t: a.track_cues(t) for t in ids}
disk = work.read_bytes()
lib_id = main.STATE.library_id
es = exports.create(lib_id, name="Gig", targets=["traktor"], destination=str(ROOT / "stick"))
exports.add(lib_id, es.id, track_ids=[ids[0]])
j = convert(c, ids)
res = j["result"]
check("the job finishes, both converted", j["state"] == "done" and len(res["converted"]) == 2, str(j)[:400])
new = [res["renamed"][t] for t in ids]
check("stem files sit beside the originals", all((music / n).is_file() for n in ("a.stem.m4a", "b.stem.m4a")))
check("the originals are PARKED, not gone",
all(parked_name(music / n).is_file() and not (music / n).exists() for n in ("a.mp3", "b.mp3")))
check("no unfinished files are left", not list(music.glob("*.konduktor-partial")))
check("the saved collection is untouched until Save", work.read_bytes() == disk)
state = c.get("/api/state").json()
check("the library is dirty and reports the pending conversions",
state["dirty"] and state["pending_stems"]["tracks"] == 2 and state["pending_stems"]["parked"] == 2, str(state))
a = main.require_adapter()
check("the entries are stems now", all(a.track(n).media_kind == "stem" for n in new))
check("prep reads back at the same decoded seconds",
all([round(x.start, 6) for x in a.track_cues(n).cues] == [round(x.start, 6) for x in before[o].cues]
for o, n in zip(ids, new)))
for route, body in (("/api/reload", None), ("/api/library/remap-paths", {"from": "/x", "to": "/y"}),
("/api/history/deadbeef/restore", None)):
r = c.post(route, json=body) if body else c.post(route)
check(f"{route} is refused while conversions await Save (409)", r.status_code == 409, f"{r.status_code} {r.text[:120]}")
r = c.post("/api/save")
check("Save succeeds", r.status_code == 200, r.text[:200])
check("…and deletes the parked originals", not any(music.glob(".*.konduktor-parked")))
check("…keeps the stem files", all((music / n).is_file() for n in ("a.stem.m4a", "b.stem.m4a")))
check("…and nothing is pending any more", c.get("/api/state").json()["pending_stems"] is None)
check("the saved collection names the stem files as STEM entries", all(n in TraktorStore(work).stem_keys() for n in new))
check("the export set follows the converted track to its new id", exports.get(lib_id, es.id).track_ids == [new[0]],
str(exports.get(lib_id, es.id).track_ids))
print("== Discard puts everything back ==")
work, ids, music = library("discard", ["a.mp3", "b.mp3"])
open_lib(c, work)
convert(c, ids)
r = c.post("/api/discard")
check("discard succeeds", r.status_code == 200 and r.json()["dirty"] is False, r.text[:200])
check("the originals are back under their own names", all((music / n).is_file() for n in ("a.mp3", "b.mp3")))
check("the stem files are gone, and nothing parked is left",
not list(music.glob("*.stem.m4a")) and not list(music.glob(".*.konduktor-parked")))
check("the entries name the MP3s again", all(main.require_adapter().track(t) is not None for t in ids))
print("== opening another library also puts them back ==")
convert(c, ids)
other, _o, _m = library("other", [])
open_lib(c, other)
check("the originals are back when switching library", all((music / n).is_file() for n in ("a.mp3", "b.mp3"))
and not list(music.glob("*.stem.m4a")))
print("== Cancel deletes what the run made, nothing else ==")
work, ids, music = library("cancel", ["a.mp3", "b.mp3", "c.mp3"])
open_lib(c, work)
os.environ["FAKE_DELAY"] = "0.15"
jid = c.post("/api/tracks/stems/convert", json={"track_ids": ids, "mode": "replace"}).json()["id"]
end = time.time() + 30
while time.time() < end and "separating" not in c.get(f"/api/jobs/{jid}").json()["status"]:
time.sleep(0.05)
time.sleep(1.8) # into the second track
c.post(f"/api/jobs/{jid}/cancel")
j = wait(c, jid)
os.environ.pop("FAKE_DELAY")
check("the job is cancelled", j["state"] == "cancelled" and j["result"]["cancelled"], str(j)[:300])
check("no stem file, no unfinished file is left",
not list(music.glob("*.stem.m4a*")) and not list(music.glob("*.konduktor-partial")), str(list(music.iterdir())))
check("the originals were never touched", all((music / n).is_file() for n in ("a.mp3", "b.mp3", "c.mp3")))
check("nothing is dirty", c.get("/api/state").json()["dirty"] is False)
print("== one bad track fails alone ==")
work, ids, music = library("fail", ["a.mp3", "bad.mp3"])
(music / "bad.mp3").write_bytes(b"not audio at all")
open_lib(c, work)
j = convert(c, ids)
res = j["result"]
check("the good track converts", ids[0] in res["renamed"], str(res)[:300])
check("the bad one is reported with a reason and keeps its original",
len(res["failed"]) == 1 and res["failed"][0]["reason"] and (music / "bad.mp3").is_file(), str(res["failed"]))
c.post("/api/discard")
print("== destination + add: a new playlist, originals untouched ==")
work, ids, music = library("dest", ["x.mp3", "sub/y.mp3"])
open_lib(c, work)
dest = ROOT / "dest-out"
j = convert(c, ids, mode="destination", destination=str(dest), collection="add", new_playlist="Stems")
res = j["result"]
check("both added", len(res["added"]) == 2 and not res["renamed"], str(res)[:300])
check("the source tree is mirrored under the destination",
(dest / "x.stem.m4a").is_file() and (dest / "sub" / "y.stem.m4a").is_file(), str(list(dest.rglob("*"))))
check("the originals are untouched, not parked", (music / "x.mp3").is_file() and not list(music.rglob("*.konduktor-parked")))
a = main.require_adapter()
pl = next(n for n in a.store._iter_nodes(a.store._root()) if n.playlist is not None and n.name == "Stems")
check("the new entries fill the new playlist", a.playlist_entries(pl.playlist.uuid) == [res["added"][t] for t in ids])
check("the original entries are still plain tracks", all(a.track(t).media_kind != "stem" for t in ids))
c.post("/api/discard")
print("== after a crash: restore from the saved file, keep the work, reuse it ==")
work, ids, music = library("crash", ["a.mp3", "b.mp3"])
open_lib(c, work)
convert(c, ids)
main.STATE.pending = None # the process died: nothing ran the discard
open_lib(c, work)
rec = c.get("/api/state").json()["stem_recovery"]
check("the next open restored the originals", all((music / n).is_file() for n in ("a.mp3", "b.mp3")) and rec["restored"] == 2, str(rec))
check("…and kept the finished stem files aside (not as finished files)",
all(partial_name(music / n).is_file() and not (music / n).exists() for n in ("a.stem.m4a", "b.stem.m4a"))
and rec["kept"] == 2, str(list(music.iterdir())))
count = ROOT / "count.txt"
os.environ["FAKE_COUNT"] = str(count)
pv = c.post("/api/tracks/stems/preview", json={"track_ids": ids, "mode": "replace"}).json()
check("a new batch plans to REUSE them", all(x["reuse"] for x in pv["convert"]), str(pv))
j = convert(c, ids)
check("…and converts without separating again", j["state"] == "done" and len(j["result"]["converted"]) == 2
and not count.exists(), f"{j['result']} engine calls: {count.read_text() if count.exists() else 0}")
os.environ.pop("FAKE_COUNT")
c.post("/api/discard")
print("== after a crash between the save and the clean-up ==")
work, ids, music = library("crash2", ["a.mp3"])
open_lib(c, work)
convert(c, ids)
main.require_adapter().save() # the library write happened…
main.STATE.pending = None # …then the process died before deleting the parked original
open_lib(c, work)
rec = c.get("/api/state").json()["stem_recovery"]
check("the next open sees the swap was committed and finishes it",
rec["committed"] == 1 and not list(music.glob(".*.konduktor-parked")) and (music / "a.stem.m4a").is_file(), str(rec))
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff. Show more