mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-28 10:32:51 +01:00
Compare commits
106
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2784879872 | ||
|
|
702e5d86a6 | ||
|
|
d7f8768d4c | ||
|
|
5c193e0ab7 | ||
|
|
badf12b991 | ||
|
|
ecc0e4c8df | ||
|
|
ae03a93f98 | ||
|
|
c560876c02 | ||
|
|
e805635383 | ||
|
|
27471a82cd | ||
|
|
28b705173e | ||
|
|
681add852a | ||
|
|
376569ec75 | ||
|
|
b5b0fa91fe | ||
|
|
34b18893ef | ||
|
|
2c02019bb2 | ||
|
|
08c53e1150 | ||
|
|
9be2c029b2 | ||
|
|
a6f96d5943 | ||
|
|
bd35418a89 | ||
|
|
86b26e3229 | ||
|
|
bb9f6e2bd3 | ||
|
|
3a9dc90344 | ||
|
|
4b9716d47a | ||
|
|
0b909a84f4 | ||
|
|
157c2c0a04 | ||
|
|
4878d82671 | ||
|
|
c2f5191962 | ||
|
|
99d590a051 | ||
|
|
eccd352ae5 | ||
|
|
90beeef226 | ||
|
|
84947bb0bb | ||
|
|
08884ca6bd | ||
|
|
9851c3c056 | ||
|
|
17b68c40bb | ||
|
|
cb76277016 | ||
|
|
24b9dfe49f | ||
|
|
513808a6d2 | ||
|
|
85f01f6723 | ||
|
|
2e04bcb9f6 | ||
|
|
bd425f8cd6 | ||
|
|
b9d43dd7ea | ||
|
|
a3747e887b | ||
|
|
8c875cb6cd | ||
|
|
ce06731dc8 | ||
|
|
c6aaded26d | ||
|
|
c1f121ae1d | ||
|
|
f1087b60fa | ||
|
|
394520c2cf | ||
|
|
642977e9bc | ||
|
|
9f299051fa | ||
|
|
738d04eada | ||
|
|
22f59c5c1e | ||
|
|
805d360907 | ||
|
|
46d3978580 | ||
|
|
0a9764ee89 | ||
|
|
f9497b391b | ||
|
|
be80e572e5 | ||
|
|
2810f24563 | ||
|
|
950352f7ec | ||
|
|
b4dc8949de | ||
|
|
0fd5d56a4e | ||
|
|
88737f2b08 | ||
|
|
efdd0f6203 | ||
|
|
d18db9566c | ||
|
|
76bf142fb4 | ||
|
|
73694fe532 | ||
|
|
532dc5d6ac | ||
|
|
b71436fad6 | ||
|
|
5909c704f4 | ||
|
|
07e85cfdc9 | ||
|
|
6c123e2597 | ||
|
|
46ce3db916 | ||
|
|
6cc73267a6 | ||
|
|
68e0b032b3 | ||
|
|
a5f995562f | ||
|
|
4aeb5d65d3 | ||
|
|
7160fa3978 | ||
|
|
805b95fe5e | ||
|
|
93ec2ef425 | ||
|
|
8d11acd783 | ||
|
|
a081a7a44d | ||
|
|
06137f5c99 | ||
|
|
36cfb96c05 | ||
|
|
ed9dfc9d6b | ||
|
|
ba3e7c251e | ||
|
|
0b38d4826f | ||
|
|
7b0d7e3a07 | ||
|
|
00dd3fe766 | ||
|
|
5aeb9956cd | ||
|
|
30065a94fe | ||
|
|
43e712afbd | ||
|
|
010f67cd2d | ||
|
|
4592e13228 | ||
|
|
6e24f5ef1d | ||
|
|
c9e85bbdb5 | ||
|
|
08c9b8121d | ||
|
|
dd97f27ac7 | ||
|
|
3f51444e2a | ||
|
|
73f7fc4282 | ||
|
|
b8b466b608 | ||
|
|
bd85d6794c | ||
|
|
ed2b72c749 | ||
|
|
f19a662bd3 | ||
|
|
41111c7c4c | ||
|
|
e8d2c66e06 |
No files matched your search
@@ -0,0 +1,635 @@
|
||||
# Discussion: Multi-platform library support (Traktor / Rekordbox / Serato)
|
||||
Date: 2026-09-17
|
||||
Status: Concluded
|
||||
|
||||
## Context
|
||||
Konduktor currently targets Traktor only (NML v20 via `traktor-nml-utils`), with a
|
||||
save path whose central guarantee is byte-exact fidelity: a no-op save is
|
||||
byte-identical, and only edited objects diff (`test_save_fidelity.py`).
|
||||
|
||||
Ben wants to extend to Rekordbox and Serato. Proposed shape:
|
||||
1. A generic library data structure that supports **all** features of **all**
|
||||
platforms ("full support is critical").
|
||||
2. Load any platform's library into that structure.
|
||||
3. Edit/prepare with Konduktor's existing features.
|
||||
4. Save back to the **original** library format.
|
||||
5. Ultimate goal: **convert** a library from one platform to another.
|
||||
|
||||
## Open Questions
|
||||
- [ ] **Command vocabulary for grids** (now evidenced): `set_grid(bpm, anchor_sec)`
|
||||
cannot express per-marker edits. Needs marker-level commands — add / move /
|
||||
set-BPM / delete marker — plus marker selection in `GridControls`. Design these.
|
||||
- [ ] Verification tests: write the per-platform "localized change" analogues —
|
||||
Rekordbox row-level table-dump diff, Serato byte diff excluding the patched GEOB
|
||||
frame + whole-file diff of crates.
|
||||
- [ ] Rekordbox `rb_local_usn` / update-sequence + cloud-sync columns: writing rows
|
||||
without maintaining these may corrupt RB's own sync state. Needs investigation.
|
||||
|
||||
## Decisions Made
|
||||
|
||||
### Write scope: full read/write for all three platforms
|
||||
- **Decision**: Konduktor must edit and save back into each platform's own live
|
||||
library — Traktor NML, Rekordbox (`master.db`), and Serato (binary crates +
|
||||
in-file GEOB tags). Not read-only, not export-only.
|
||||
- **Rationale**: The user's existing library on their chosen platform is the
|
||||
canonical source; Konduktor is a management tool for it, so it must be able to
|
||||
write back wherever the user actually works.
|
||||
- **Alternatives considered**: Traktor-write-only with read+export for the others
|
||||
(smaller, safer v1); Traktor+Serato write with Rekordbox read-only (avoids the
|
||||
encrypted/unsupported RB DB); read-all/export-only (no in-place editing at all).
|
||||
All rejected as too limited.
|
||||
- **Consequence**: Rekordbox and Serato writes carry materially higher risk than
|
||||
NML — both formats are reverse-engineered and neither has a fidelity guarantee
|
||||
equivalent to the current byte-exact NML save. Per-platform backup + verification
|
||||
strategy becomes a first-class requirement.
|
||||
|
||||
### End goal: canonical-library management + converted exports
|
||||
- **Decision**: The user's main platform library remains the canonical source of
|
||||
truth. Konduktor manages and edits it in place, and *additionally* can produce
|
||||
converted exports for other platforms.
|
||||
- **Rationale**: Keeps the user's existing workflow intact — they keep using their
|
||||
DJ software normally — while making conversion a deliberate, separate output.
|
||||
- **Alternatives considered**: one-shot migration only (too narrow); two-way sync
|
||||
between libraries (rejected — requires cross-platform track identity, change
|
||||
detection and conflict resolution; much larger project); Konduktor owning its own
|
||||
canonical library format with platforms as import/export only (rejected — changes
|
||||
the product's identity and displaces the user's real library).
|
||||
- **Consequence**: Two distinct write paths must coexist: a high-fidelity in-place
|
||||
*edit* path per platform, and a lossy-by-design *export* path. They have opposite
|
||||
requirements and should not share an implementation.
|
||||
|
||||
### Track identity: not needed — export always generates a fresh target library
|
||||
- **Decision**: An Export is a one-time conversion that generates a **fresh** target
|
||||
library. It never merges into an existing library on the target platform. The
|
||||
originally-loaded library remains canonical and is the only thing edited in place.
|
||||
- **Rationale**: Keeps the canonical-source model clean — edits go back to the source
|
||||
library, exports are disposable output. Removes the need for any cross-platform
|
||||
track-matching mechanism.
|
||||
- **Alternatives considered**: path-only matching (fails on relocation); path with
|
||||
artist/title/duration tag fallback (false positives); audio content hashing (robust,
|
||||
survives moves, but requires a full library scan); acoustic fingerprinting
|
||||
(Chromaprint/AcoustID — heavy, solves a problem this product doesn't have). All
|
||||
rejected as unnecessary given fresh-export-only.
|
||||
- **Consequence**: The existing `volume + dir + file` primary key remains sufficient.
|
||||
Cross-library identity is deferred indefinitely; it would only return if merge-style
|
||||
export were ever wanted.
|
||||
|
||||
### Serato backup: GEOB-frame sidecar, not full file copies
|
||||
- **Decision**: Before patching a Serato GEOB frame, snapshot the original frame bytes
|
||||
to a sidecar restore file. Do not copy whole audio files. Crate files are copied
|
||||
wholesale (tiny).
|
||||
- **Rationale**: Kilobytes instead of gigabytes per save, and a complete restore for
|
||||
everything Konduktor actually touches, since Konduktor only ever rewrites those frames.
|
||||
- **Alternatives considered**: full audio-file backups — rejected on cost (~1 GB for a
|
||||
100-track save).
|
||||
- **Risk accepted**: does not protect against the tag library corrupting an unrelated
|
||||
region of the audio file. This exposure already exists via `file_tags.py` cover-art
|
||||
writes; Serato support widens it from occasional to routine.
|
||||
|
||||
### Export = a new self-contained library, always including copied audio
|
||||
- **Decision**: An export/conversion always produces a whole new library at a
|
||||
user-chosen destination, complete with copies of the music files — for every target
|
||||
platform, not just Serato. Reference-in-place is not offered.
|
||||
- **Audio folder layout**: a **global, persistent export setting** with two options —
|
||||
**flat single folder (default)** or **mirror source directory structure**.
|
||||
*Rationale*: flat is predictable and simple for the common case; mirroring is there
|
||||
for users who want their original structure preserved. *Alternatives considered*:
|
||||
organised Artist/Album from metadata (clean but depends on metadata quality and needs
|
||||
sanitising); mirror playlist structure (legible on USB, but duplicates tracks that
|
||||
appear in multiple playlists).
|
||||
- **Rationale**: The export is self-contained and portable (USB drive, another machine,
|
||||
handing it to someone else). Consistent behaviour across targets.
|
||||
- **Alternatives considered**: copy only where the format forces it (Serato), letting
|
||||
Traktor/Rekordbox exports reference originals in place for a near-instant export;
|
||||
offering it as a per-export user choice. Both rejected in favour of one predictable
|
||||
behaviour.
|
||||
|
||||
### Export Sets: user-curated export scope
|
||||
- **Decision**: Introduce an **Export Set** (not "Crate" — see naming decision) — a named, persisted list of track and playlist
|
||||
*references* defining what a given export includes. Enables partial exports. Each
|
||||
crate belongs to a specific library, and crate data is persisted in Konduktor's own
|
||||
storage (not in the platform library).
|
||||
- **Flow**: open library → prep tracks → save back to the canonical library → create a
|
||||
crate → drag tracks/playlists into it → export crate (choose target platform +
|
||||
destination) → Konduktor writes the target library files and copies the audio.
|
||||
- **Rationale**: Users rarely want to convert an entire library; export scope needs to
|
||||
be curated and re-usable across repeat exports.
|
||||
- **Naming**: called **Export Set**, not "Crate". *Rationale*: "Crate" is Serato's own
|
||||
term for a playlist and Konduktor imports Serato crates — the collision would be
|
||||
confusing in a multi-platform tool. *Alternatives considered*: keeping "Crate"
|
||||
(familiar DJ vocabulary, but ambiguous); "Bundle"; "Package".
|
||||
- **Reference semantics: live**. An Export Set stores pointers to playlists; export
|
||||
resolves them at export time, so later additions to a playlist are picked up.
|
||||
*Alternatives considered*: snapshot-at-add (frozen and auditable, but stale);
|
||||
live-with-optional-freeze (more flexible, more UI + model complexity).
|
||||
*Consequence*: the export preview must be computed at export time, never stored.
|
||||
- **Storage: own store, keyed by stable library ID**. A dedicated Export Sets store,
|
||||
separate from `userprefs.json`, with each library assigned a stable generated ID so
|
||||
that moving or renaming the collection file does not orphan its export sets.
|
||||
*Alternatives considered*: keying by collection file path (simple, orphans on move);
|
||||
storing inside `userprefs.json` (best-effort I/O, no backup — inadequate for curated
|
||||
user work); a sidecar file next to the user's library (travels automatically, but
|
||||
writes Konduktor files into the user's Traktor/Serato folders).
|
||||
|
||||
### Export mechanics
|
||||
- **Flat-layout filename collisions: counter suffix.** Second and later collisions
|
||||
become `Xtal-2.mp3`, `Xtal-3.mp3`. *Rationale*: human-readable and predictable.
|
||||
*Alternatives considered*: metadata-based disambiguation (`Xtal (Aphex Twin).mp3` —
|
||||
most legible and stable, but depends on metadata quality and needs sanitising); short
|
||||
hash suffix (stable across re-exports regardless of order, but ugly).
|
||||
*Known consequence*: numbering depends on processing order, so repeat exports may
|
||||
assign different suffixes to the same tracks.
|
||||
- **Playlist folder structure: preserve where supported, flatten with path names
|
||||
otherwise.** Keep the tree on Traktor and Rekordbox; on flat targets, flatten to names
|
||||
encoding the path (e.g. `House / Peak Time`). *Rationale*: retains the structural
|
||||
information in readable form on every target and avoids name collisions between
|
||||
same-named playlists in different folders. *Alternatives considered*: flatten to bare
|
||||
names (cleaner, but collides); always flatten (uniform, but discards structure the
|
||||
target could represent).
|
||||
- **Re-export to an occupied destination: warn, then overwrite on confirm.** *Rationale*:
|
||||
the destination stays the single current copy, which is what re-export usually means,
|
||||
with a guard against accidental loss. *Alternatives considered*: always write a new
|
||||
timestamped folder (safe, but fills the drive with copies of a large collection);
|
||||
refuse and require an empty destination (tedious for a routine operation); incremental
|
||||
update in place (fast, but reintroduces target-library matching/diffing, which the
|
||||
fresh-export decision deliberately avoided).
|
||||
- **Whole-library export: an explicit "export entire library" action.** A separate
|
||||
action that skips export-set creation. *Rationale*: wholesale migration is a common
|
||||
real use case and shouldn't require busywork. *Alternatives considered*: export sets
|
||||
only (uniform, but forces a select-everything set); a select-all shortcut inside the
|
||||
export set editor (single code path, but less discoverable).
|
||||
|
||||
### Export set resolution and export UX
|
||||
- **Playlist resolution: auto-include, deduplicate, copy once.** Every track referenced
|
||||
by a playlist in the export set is included automatically; a track appearing in
|
||||
multiple playlists, or also added individually, is copied to disk exactly once.
|
||||
*Alternatives considered*: auto-include but surface the implied tracks in the UI (more
|
||||
transparent, more UI); require explicit inclusion (precise, but surprising).
|
||||
- **Missing audio files: pre-scan, report, let the user decide.** Verify every file
|
||||
exists before copying anything; present what's missing and let the user cancel or
|
||||
proceed without them. *Rationale*: fails fast rather than halfway through a multi-hour
|
||||
copy. *Alternatives considered*: skip silently (incomplete export the user never
|
||||
learns about — worse given the loss report was deferred); abort entirely (one
|
||||
unmounted drive blocks an otherwise fine export).
|
||||
- **Export UX: pre-check space, progress with cancel.** Estimate total size and verify
|
||||
the destination has room before starting; show per-file progress with a working
|
||||
cancel. *Alternatives considered*: cancel with rollback (destination never left
|
||||
half-finished, but deleting files from a user-chosen location needs care);
|
||||
progress-only with no pre-check (discovers a full drive after an hour of copying).
|
||||
*Known consequence*: cancelling leaves a partial export that must be cleaned up or
|
||||
clearly marked incomplete.
|
||||
|
||||
### Serato export copies the audio files
|
||||
- **Decision**: Exporting to Serato copies the original audio files to the export
|
||||
destination and writes the GEOB frames into the **copies**, leaving the canonical
|
||||
library's files untouched.
|
||||
- **Rationale**: Serato's prep data lives inside the audio files, so a Serato export
|
||||
cannot reference the originals without mutating them — and the originals belong to
|
||||
the canonical library.
|
||||
- **Open consequence**: creates an asymmetry with Traktor/Rekordbox exports, whose data
|
||||
lives in a library file and could reference originals in place. See Open Questions.
|
||||
|
||||
### Rekordbox open-app handling: warn and proceed
|
||||
- **Decision**: If Rekordbox appears to be running when the user saves, Konduktor
|
||||
**warns but allows the save to proceed** — it does not hard-refuse.
|
||||
- **Rationale**: Consistent with the existing Traktor behaviour (the user is warned to
|
||||
close Traktor before saving, not blocked).
|
||||
- **Alternatives considered**: detect-and-refuse (safer, but blocks the user on a
|
||||
detection heuristic that may be wrong).
|
||||
- **Risk accepted**: Rekordbox may hold `master.db` open and runs cloud sync, so a
|
||||
concurrent write is riskier than Traktor's overwrite-on-exit behaviour. The backup
|
||||
taken before the write is the mitigation.
|
||||
|
||||
### Backup/verification: same invariant, per-platform mechanism
|
||||
- **Decision**: Keep the existing invariant — *an edit changes only what it was
|
||||
supposed to change* — and implement a per-platform comparison mechanism for it:
|
||||
Traktor byte diff (existing), Rekordbox full table dump with row-level diff, Serato
|
||||
byte diff of the audio file excluding the patched GEOB frame plus whole-file diff of
|
||||
crate files. Backups: copy `collection.nml` / copy `master.db` (+ WAL/SHM) /
|
||||
Serato strategy TBD (see Open Questions).
|
||||
- **Rationale**: Generalizes `test_save_fidelity.py`'s guarantee to formats where a
|
||||
byte-identical whole-file comparison is meaningless.
|
||||
- **Alternatives considered**: dropping the fidelity guarantee for the non-Traktor
|
||||
platforms — rejected, it is the project's core safety property.
|
||||
|
||||
### Cue model: rich core cue, adapters collapse on write
|
||||
- **Decision**: Model a cue richly enough to cover all three platforms:
|
||||
`{ position_sec, length_sec?, role: hotcue|memory, slot?, type: cue|fade_in|fade_out|
|
||||
load|loop, color?, name? }`. Adapters collapse it per platform — Traktor rejects
|
||||
`role: memory`; Rekordbox and Serato have no `fade_in`/`fade_out`/`load` types;
|
||||
Serato keeps loops in a separate saved-loop bank rather than consuming a cue slot.
|
||||
- **Platform differences captured**: Traktor = 8 typed hotcue slots (loop is a cue
|
||||
*type*); Rekordbox = 8 hotcues A–H plus unlimited memory cues, colour per cue;
|
||||
Serato = 8 cues plus a separate saved-loop bank, colour per cue.
|
||||
- **Correction noted during discussion**: Traktor's `CueV2Type` *does* carry a `color`
|
||||
field, so NML supports cue colours — an earlier assumption to the contrary was wrong.
|
||||
**Lesson: establish capabilities empirically per format rather than assuming them.**
|
||||
|
||||
### Lossiness policy: degrade where sensible, drop otherwise
|
||||
- **Decision**: On export, data the target cannot represent is **degraded to the
|
||||
nearest equivalent where one exists, and dropped only where none does** — e.g. a
|
||||
Traktor fade-in cue becomes a plain cue in Serato; Rekordbox memory cues fill spare
|
||||
hotcue slots in Traktor until they run out.
|
||||
- **Rationale**: The project aims for as much feature parity across platforms as
|
||||
possible; silently discarding representable data works against that.
|
||||
- **Alternatives considered**: drop silently (clean output, but the user only discovers
|
||||
the loss on the gear); refuse to export when data would be lost (too rigid).
|
||||
- **No loss report for now**: an export summary of what was degraded or dropped was
|
||||
explicitly deferred ("not for now"). The adapters will know what they collapsed, so
|
||||
it remains cheap to add later.
|
||||
|
||||
### Proposed sequencing (not yet confirmed)
|
||||
1. Fix the flexible-grid bug standalone (small, independent, fixes a present-day data
|
||||
risk). Requires verifying the NML representation first.
|
||||
2. Refactor to generic model + adapter interface with **Traktor as the only adapter** —
|
||||
no new formats, all existing tests must still pass, so `test_save_fidelity.py` proves
|
||||
the projection+command split broke nothing. Takes the architectural risk where it is
|
||||
verifiable.
|
||||
3. Add the second platform — where a one-adapter abstraction gets tested for real.
|
||||
4. Export — only meaningful once two platforms exist.
|
||||
|
||||
### Sequencing: grid fix → Traktor-only refactor → Rekordbox → export
|
||||
- **Decision**:
|
||||
1. Fix the flexible-beatgrid handling as a **standalone change first** (small,
|
||||
independent, and currently writing inconsistent grids to real collections).
|
||||
2. Refactor to the generic model + adapter interface with **Traktor as the only
|
||||
adapter** — no new formats, every existing test must still pass, so
|
||||
`test_save_fidelity.py` proves the projection+command split changed nothing.
|
||||
3. Add **Rekordbox** as the second platform.
|
||||
4. Build the **export** path last (it only becomes meaningful once two platforms
|
||||
exist).
|
||||
- **Rationale**: takes the architectural risk where it is verifiable against existing
|
||||
invariants, before any unverifiable format is introduced. A one-adapter abstraction is
|
||||
always wrong in ways that only surface with the second adapter.
|
||||
- **Second platform — Rekordbox over Serato**: chosen despite the riskier write target
|
||||
(SQLCipher-encrypted DB, cloud sync, version-fragile schema) because `pyrekordbox` is
|
||||
the more mature library. *Alternative considered*: Serato second — no library-file
|
||||
risk, but writes go into users' audio files and the format is entirely
|
||||
reverse-engineered.
|
||||
- **Tauri packaging: dropped from scope for now.**
|
||||
- **CDJ/USB export (`export.pdb` + ANLZ files): explicitly OUT OF SCOPE.** Raised in a
|
||||
forked conversation and rejected as impractical to implement. Recorded here only so
|
||||
it is not rediscovered and re-proposed.
|
||||
- **Bulk metadata editing: dropped from scope for now.** Not built before the refactor;
|
||||
revisit after the adapter architecture exists so it only has to be written once.
|
||||
|
||||
### One library open at a time
|
||||
- **Decision**: `AppState` continues to hold exactly one loaded library. Export always
|
||||
reads the currently-open library.
|
||||
- **Rationale**: Simplest plumbing, no ambiguity about which library an edit or export
|
||||
targets, and the existing collection-picker flow is unchanged.
|
||||
- **Alternatives considered**: multiple loaded with one active (faster switching, but
|
||||
dirty-flag/save-bar/unsaved-changes state all become per-library); fully concurrent
|
||||
multi-library (powerful, but multiplies UI and state complexity and invites the
|
||||
merge/sync expectations already ruled out).
|
||||
|
||||
### Capability detection: version first, probe as fallback
|
||||
- **Decision**: Derive capabilities from the library's declared version where one
|
||||
exists (NML version, Rekordbox schema version); where no version is stamped — Serato
|
||||
— infer capabilities from the data actually present.
|
||||
- **Rationale**: Accurate per-library capability reporting without assuming a floor that
|
||||
denies users features their software actually has.
|
||||
- **Alternatives considered**: probe-only (uniform and empirical, but an empty or simple
|
||||
library under-reports); assume-newest-and-degrade-on-failure (least work, risks
|
||||
writing data older software can't read); static per-platform floor (trivial, but
|
||||
penalises users on current versions).
|
||||
- **Consequence**: each adapter needs its own version-detection story.
|
||||
- **Serato exception**: Serato has no version-stamped library file, so rather than
|
||||
probing the data, Konduktor simply **assumes the latest Serato version** and reports
|
||||
the full capability set. *Rationale*: keeps it simple, and probing under-reports on
|
||||
small or fresh libraries. *Risk accepted*: a user on an older Serato build could be
|
||||
written prep data their install cannot read; mitigated by Serato's aggressive
|
||||
auto-update and the relative stability of the GEOB tag format.
|
||||
|
||||
### Field mapping: normalise, but keep the native value alongside
|
||||
- **Implementation requirement**: this demands **per-field dirty tracking**. The rule
|
||||
"reuse the native value unless the user edited this field" needs to know *which
|
||||
fields* changed, not just which tracks — `PlaylistStore` currently tracks dirtiness at
|
||||
track level. It must exist from the start: retrofitted, it cannot distinguish
|
||||
edited-to-the-same-value from untouched. It pairs well with projection+command, since
|
||||
a command already names the field it changes, so the flag falls out of the command
|
||||
rather than requiring a diff.
|
||||
- **Decision**: Ratings, keys, colours and comments are stored in canonical form in the
|
||||
generic model (rating 0–5, key as canonical pitch-class + mode, colour as RGB), and
|
||||
**each field also retains its untouched native value**. On write-back the native value
|
||||
is reused unless the user actually edited that field, so untouched tracks round-trip
|
||||
exactly and only genuine edits go through conversion.
|
||||
- **Rationale**: Gets a clean, convertible canonical model without introducing
|
||||
round-trip drift on data the user never touched — consistent with the project's
|
||||
fidelity-first posture.
|
||||
- **Alternatives considered**: normalise-in/denormalise-out only (clean model, but
|
||||
round-tripping through a lossy scale shifts values); preserve native and convert only
|
||||
on export (zero round-trip risk, but every UI consumer must interpret
|
||||
platform-specific values).
|
||||
|
||||
### Prep UI: generic model with capability-gated controls
|
||||
- **Decision**: The prep UI (waveform, cues, grid) works purely off the generic model,
|
||||
with capability flags disabling or hiding the individual controls the loaded platform
|
||||
cannot persist (e.g. no memory-cue control on Traktor). No platform branching inside
|
||||
components.
|
||||
- **Rationale**: One UI to maintain, and users are never offered an edit that will
|
||||
silently vanish on save.
|
||||
- **Alternatives considered**: no gating, letting adapters silently collapse on write
|
||||
(simplest, but is precisely the failure mode the capability system exists to prevent);
|
||||
gate-plus-warn with controls left enabled (more discoverable, but risks nagging during
|
||||
normal prep work).
|
||||
|
||||
## Findings
|
||||
|
||||
### VERIFIED: Traktor flexible-grid representation in NML
|
||||
Checked against `All I Need` (Shiba San, Tim Baresko) in
|
||||
`/Users/ben/Documents/Native Instruments/Traktor 4.5.0/collection.nml`. A flexible grid
|
||||
is stored as **multiple `CUE_V2 TYPE="4"` markers, each with its own `<GRID BPM>`
|
||||
child**:
|
||||
|
||||
```
|
||||
TEMPO BPM="124.999908"
|
||||
CUE_V2 TYPE="4" NAME="AutoGrid" START="71.815535" GRID BPM="124.999908"
|
||||
CUE_V2 TYPE="4" NAME="Beat Marker" START="46151.849285" GRID BPM="62.499954"
|
||||
CUE_V2 TYPE="4" NAME="Beat Marker" START="76871.871785" GRID BPM="249.999817"
|
||||
```
|
||||
|
||||
- The first marker is named `AutoGrid`; subsequent ones are `Beat Marker`.
|
||||
- `TEMPO BPM` mirrors the **first** marker's BPM.
|
||||
- The half/double BPMs (62.5 / 250 against a base of 125) are genuine half-time and
|
||||
double-time sections.
|
||||
- A non-flexible track (`Cash Money`) has exactly one `TYPE="4"` marker — so the same
|
||||
structure covers both cases; a constant grid is just a marker list of length one.
|
||||
- Separately, tracks carry a `TYPE="0"` cue named `AutoGrid` in **hotcue slot 0** with
|
||||
`COLOR="#FFFFFF"`, positioned at almost (not exactly) the type-4 anchor's START.
|
||||
- `COLOR` is populated in practice, confirming Traktor does carry per-cue colour.
|
||||
|
||||
### Current `set_grid` is incorrect for flexible beatgrids (present-day bug risk)
|
||||
`PlaylistStore._grid_marker()` ([backend/konduktor/playlist_store.py:395](../../backend/konduktor/playlist_store.py#L395))
|
||||
returns only the **first** `CUE_V2` with a `grid` child. Consequences on a track with
|
||||
a flexible (multi-marker) grid:
|
||||
- `set_grid(bpm=X)` updates `TEMPO` and only the *first* marker's BPM, leaving
|
||||
subsequent markers at their old BPM → internally inconsistent grid written to disk.
|
||||
- `set_grid(anchor_sec=X)` moves only the first marker.
|
||||
- `delete_grid()` removes all grid markers, but **leaves the companion `TYPE="0"`
|
||||
`AutoGrid` hotcue-slot-0 cue behind** as debris, since it only strips cues with a
|
||||
`grid` child.
|
||||
- Concretely on `All I Need`: `set_grid(bpm=130)` would set `TEMPO` and the `AutoGrid`
|
||||
marker to 130 and leave the Beat Markers at 62.5 and 250 — a destroyed grid.
|
||||
- The frontend beatgrid drawing (`cues.ts`) is built around a single BPM + anchor, so
|
||||
a flexible grid would also render incorrectly.
|
||||
|
||||
CLAUDE.md describes the grid as "the grid marker (`CUE_V2` type 4 with a `<GRID BPM>`
|
||||
child)" — singular — so this assumption is baked into the docs as well as the code.
|
||||
|
||||
**Implication for step 1**: this is not a small bug fix. `set_grid(bpm, anchor_sec)`
|
||||
structurally cannot express per-marker edits, so the fix requires a new marker-level
|
||||
command vocabulary and marker selection in the `GridControls` UI.
|
||||
|
||||
## Next Steps
|
||||
1. **Design the grid marker command vocabulary** (plan mode, with
|
||||
`backend/konduktor/playlist_store.py` and `frontend/src/components/GridControls.tsx`
|
||||
open). `set_grid(bpm, anchor_sec)` must be replaced by marker-level commands, and
|
||||
`GridControls` needs marker selection.
|
||||
2. **Fix flexible-beatgrid handling** as a standalone change, including the
|
||||
`delete_grid` debris bug (the companion `TYPE="0"` `AutoGrid` hotcue-0 cue is left
|
||||
behind). Add a test fixture based on `All I Need` (three grid markers at 125 / 62.5 /
|
||||
250 BPM). Update CLAUDE.md, which documents the grid as singular.
|
||||
3. **Refactor to generic model + adapter interface, Traktor-only.** All existing tests
|
||||
must still pass unchanged — `test_save_fidelity.py` is the proof that the
|
||||
projection+command split changed nothing.
|
||||
4. **Add the Rekordbox adapter.** Research `rb_local_usn` / cloud-sync columns first.
|
||||
Write the Rekordbox verification test (row-level table-dump diff).
|
||||
5. **Add the Serato adapter.** GEOB-frame sidecar backups; write the Serato verification
|
||||
test (byte diff excluding the patched frame, plus whole-file crate diff).
|
||||
6. **Build the export path.** Only meaningful once two platforms exist.
|
||||
|
||||
### Command vocabulary: strictly generic, no adapter escape hatches
|
||||
- **Decision**: Every command is defined in generic-model terms and each adapter
|
||||
translates it. Adapters may not expose platform-specific commands.
|
||||
- **Rationale**: Keeps the UI fully platform-agnostic and forces genuine abstraction
|
||||
rather than letting platform specifics leak upward.
|
||||
- **Alternatives considered**: a generic core plus adapter escape hatches (pragmatic,
|
||||
but the hatch gets used and generic coverage quietly erodes); starting generic and
|
||||
adding hatches only on demonstrated need.
|
||||
- **Two-platform promotion rule** (resolves the single-platform-feature problem):
|
||||
- A feature that exists on only **one** platform is **preserved but not editable** —
|
||||
no command, no generic concept, no editing UI. Under projection+command it survives
|
||||
round-trip intact for free, because unmodelled native data never leaves the native
|
||||
model. The strictly-generic vocabulary therefore constrains what Konduktor can
|
||||
**edit**, not what it **preserves**.
|
||||
- A concept is **promoted into the core vocabulary once at least two platforms have
|
||||
it**, at which point there is real evidence of what the shared abstraction should
|
||||
be, rather than a concept invented to accommodate a single format.
|
||||
- *Rationale*: avoids both failure modes — inventing a fake abstraction to house a
|
||||
one-platform feature (e.g. a "performance sequence" concept only Serato ever uses),
|
||||
and opening an escape hatch that quietly erodes generic coverage.
|
||||
- *UI affordance*: show preserved-but-uneditable data as read-only, so users can see
|
||||
that e.g. their Serato Flip data is intact rather than assuming Konduktor discarded
|
||||
it. Makes the limitation honest instead of invisible.
|
||||
- *Consequence accepted*: conversion coverage is capped at what two or more platforms
|
||||
share — which matches the stated parity goal rather than compromising it.
|
||||
|
||||
### Save model: projection + command replay
|
||||
- **Decision**: The generic model is a **read projection**. Edits are expressed as
|
||||
commands and replayed by a per-platform adapter onto the **retained native model**,
|
||||
which remains the write target. Export is a separate, lossy path reading from the
|
||||
projection.
|
||||
- **Rationale**: It is the only model that matches how all three storage formats
|
||||
actually behave — Rekordbox `master.db` requires row `UPDATE`s (cannot be
|
||||
regenerated: internal IDs, FKs, ANLZ pointers, `rb_local_usn` sync columns), Serato
|
||||
requires patching individual GEOB frames inside audio files, and Traktor already
|
||||
deliberately avoids regeneration. It also preserves the byte-exact NML guarantee and
|
||||
`test_save_fidelity.py`, makes unknown native fields survive **for free** (they are
|
||||
never lifted out of the native model), and keeps edit *intent* explicit. Critically,
|
||||
Konduktor already implements this shape for Traktor: `CollectionService` is the read
|
||||
projection, `PlaylistStore` holds the native model with command methods, the HTTP API
|
||||
is already a command bus, and `replace_track()` is the projection refresh. This is a
|
||||
generalization, not a rewrite.
|
||||
- **Alternatives considered**: *Generic model as source of truth* — rejected: would
|
||||
lose unmodelled fields on real irreplaceable data, discards the byte-exact guarantee,
|
||||
cannot work for `master.db`, and its headline benefit (free conversion) is illusory
|
||||
since per-target serializers are needed either way; its only real prize is simpler UI
|
||||
mutation code. *Source of truth + diff-based writeback* — rejected: diffing destroys
|
||||
edit intent exactly where platforms disagree (grid phase-shift vs. retempo is
|
||||
indistinguishable in a marker-position diff), ordered-list diffs are fiddly, and it
|
||||
needs a full deep snapshot at load.
|
||||
- **Cost accepted**: an N×M adapter matrix (~15 commands × 3 platforms), plus careful
|
||||
choice of command altitude.
|
||||
|
||||
### Model shape: rich core + capability system
|
||||
- **Decision**: Model the union of *concepts* at full fidelity in the generic model —
|
||||
beatgrid is always a marker list, a cue always carries position/type/colour/role/slot
|
||||
— and build a per-platform **capability system** so the UI never offers an edit the
|
||||
loaded platform cannot persist.
|
||||
- **Rationale**: The conversion goal requires one shared vocabulary; anything parked in
|
||||
a platform-specific extension namespace cannot be converted. Ben confirmed
|
||||
willingness to build the capability UI.
|
||||
- **Alternatives considered**: *Union superset* — rejected, forces every UI consumer to
|
||||
branch on the loaded platform. *Core + per-platform extensions* — rejected, because
|
||||
the data that would land in extensions (Rekordbox memory cues, Serato saved loops) is
|
||||
central rather than exotic, and extensions do not convert.
|
||||
- **Note from Ben**: Traktor 3.4+ supports **flexible beatgrids**, so the marker-list
|
||||
model is right for all three platforms rather than being a Traktor-side compromise.
|
||||
This also means the current single-marker assumption in the codebase is already wrong
|
||||
(see Findings).
|
||||
|
||||
### Undo/redo: deferred but not precluded
|
||||
- **Decision**: Do not implement undo/redo now, but design the command layer so
|
||||
inverse commands can be added later.
|
||||
- **Rationale**: Keeps the adapter surface smaller for the initial build while
|
||||
retaining the option; the command model makes it cheap to add.
|
||||
- **Alternatives considered**: designing for inverses from day one (more discipline in
|
||||
every adapter method); ruling it out entirely (loses a strong safety feature).
|
||||
|
||||
### Format layers: reuse mature libraries
|
||||
- **Decision**: Use existing libraries for the Rekordbox and Serato format layers
|
||||
(e.g. `pyrekordbox` for `master.db`/SQLCipher/XML/ANLZ, an existing Serato
|
||||
crate+GEOB library), wrapped behind Konduktor's adapter interface.
|
||||
- **Rationale**: Fastest path to coverage; the project already accepts this class of
|
||||
dependency risk with `traktor-nml-utils`.
|
||||
- **Alternatives considered**: reuse for reading but own all write paths (more control
|
||||
over surgical patching and fidelity, more work); build everything in-house (maximum
|
||||
control, very large reverse-engineering effort); spike first and decide per platform.
|
||||
|
||||
## Agent Onboarding
|
||||
|
||||
### Summary
|
||||
Konduktor is today a Traktor-only tool whose defining property is **save fidelity**: it
|
||||
never regenerates `collection.nml`, it surgically patches a parsed dataclass model and
|
||||
renders through the library's own pipeline, so a no-op save is byte-identical and only
|
||||
edited objects diff (`test_save_fidelity.py`, CLAUDE.md gotcha 3).
|
||||
|
||||
Ben wants to extend it to Rekordbox and Serato, with library conversion as the ultimate
|
||||
payoff. His opening proposal was a generic data structure that all platforms load into,
|
||||
are edited through, and are saved back out of.
|
||||
|
||||
The central tension explored was that **"load into a generic model and serialize back
|
||||
out" would destroy the fidelity guarantee**. The discussion resolved it by establishing
|
||||
that for two of the three platforms, whole-model serialization is not even a coherent
|
||||
operation: Rekordbox's `master.db` is SQLite with internal IDs, FKs, ANLZ pointers and
|
||||
sync columns (you `UPDATE` rows, you cannot regenerate), and Serato's prep data lives as
|
||||
binary GEOB frames inside the audio files themselves (you patch a frame). Both are
|
||||
inherently mutation-oriented. This made **projection + command replay** the only model
|
||||
that generalizes — and, critically, Konduktor already implements exactly that shape for
|
||||
Traktor (`CollectionService` = read projection, `PlaylistStore` = native model + command
|
||||
methods, the HTTP API = command bus, `replace_track()` = projection refresh). The work is
|
||||
a generalization, not a rewrite.
|
||||
|
||||
A second thread established that the generic model should be **rich** (model the union
|
||||
of concepts at full fidelity, adapters collapse on write) rather than
|
||||
lowest-common-denominator or core-plus-extensions, because anything parked in a
|
||||
platform-specific namespace cannot be converted. This makes a **capability system**
|
||||
mandatory so the UI never offers an edit that silently won't persist.
|
||||
|
||||
A third thread covered **exports**: always a fresh, self-contained target library with
|
||||
copied audio, scoped by a user-curated **Export Set**. Because exports never merge into
|
||||
an existing target, cross-platform track identity is not needed at all — the existing
|
||||
path-based primary key suffices.
|
||||
|
||||
Along the way the discussion surfaced a **present-day bug**: Ben noted Traktor 3.4+
|
||||
supports flexible beatgrids, and verification against his real collection confirmed
|
||||
Traktor stores them as multiple `CUE_V2 TYPE="4"` markers each with its own `<GRID BPM>`.
|
||||
`PlaylistStore._grid_marker()` only ever reads the first, so `set_grid(bpm=X)` writes
|
||||
internally inconsistent grids to real collections today. This became step 1 of the plan,
|
||||
and it is bigger than a bug fix because the `set_grid(bpm, anchor_sec)` signature
|
||||
structurally cannot express per-marker edits.
|
||||
|
||||
Note: a "CDJ/USB export" requirement appeared in this log mid-discussion from a forked
|
||||
conversation. Ben confirmed it was rejected as impractical and had it removed. **Do not
|
||||
re-propose it.**
|
||||
|
||||
### If Continuing This Discussion
|
||||
All design questions are resolved. Three items remain, none of them decisions:
|
||||
- Grid marker command vocabulary — a design task for plan mode, not an open question.
|
||||
- Per-platform verification tests — implementation work landing with each adapter.
|
||||
- Rekordbox `rb_local_usn` / cloud-sync columns — research for the Rekordbox phase.
|
||||
|
||||
Deliberately deferred, do not reopen without Ben raising them: the export loss report
|
||||
("not for now"), bulk metadata editing, Tauri packaging, and CDJ/USB export (rejected).
|
||||
|
||||
### If Moving to Planning/Implementation
|
||||
|
||||
**Requirements**
|
||||
|
||||
1. **Save model — projection + command replay.** The generic model is a *read
|
||||
projection*. Edits are commands replayed by a per-platform adapter onto the
|
||||
**retained native model**, which stays the write target. Never serialize the generic
|
||||
model back over a native library. This preserves byte-exact NML saves and means
|
||||
unmodelled native fields survive for free.
|
||||
2. **Command vocabulary — strictly generic.** All commands are defined in generic-model
|
||||
terms; adapters translate. **No platform-specific escape hatches.** Single-platform
|
||||
features are *preserved but not editable*; a concept is promoted into the core
|
||||
vocabulary only once **two or more platforms have it**. Surface preserved-but-
|
||||
uneditable data as read-only in the UI.
|
||||
3. **Generic model — rich core.** Model the union of concepts at full fidelity.
|
||||
Beatgrid is **always a marker list** (a constant grid is a list of length one — this
|
||||
is correct for all three platforms, not a compromise). Cue shape:
|
||||
`{ position_sec, length_sec?, role: hotcue|memory, slot?, type: cue|fade_in|fade_out|
|
||||
load|loop, color?, name? }`.
|
||||
4. **Capability system — mandatory.** Capabilities are `f(platform, version)`, derived
|
||||
from the declared version where one exists; **Serato assumes the latest version** for
|
||||
simplicity. The prep UI works purely off the generic model with capability-gated
|
||||
controls — no platform branching inside components.
|
||||
5. **Field mapping — normalise, keep native alongside.** Canonical forms in the model
|
||||
(rating 0–5, canonical key, RGB colour) *plus* the untouched native value. On
|
||||
write-back, reuse the native value unless the user actually edited that field.
|
||||
**This requires per-field dirty tracking** — `PlaylistStore` is track-level today, and
|
||||
it must exist from the start because it cannot be retrofitted (edited-to-same-value
|
||||
becomes indistinguishable from untouched). It falls out of the command, which already
|
||||
names the field it changes.
|
||||
6. **Write scope — full read/write for all three platforms**, in place, to the user's
|
||||
canonical library. One library open at a time (`AppState` keeps holding exactly one).
|
||||
7. **Safety — same invariant, per-platform mechanism.** "An edit changes only what it
|
||||
was supposed to change." Traktor: byte diff (exists). Rekordbox: full table dump,
|
||||
row-level diff; back up `master.db` + WAL/SHM; **warn but proceed** if Rekordbox is
|
||||
running. Serato: byte diff of the audio file excluding the patched GEOB frame, plus
|
||||
whole-file crate diff; **back up GEOB frames to a sidecar, not whole audio files**
|
||||
(KB not GB; accepted risk: no protection if the tag library mangles an unrelated
|
||||
region — an exposure `file_tags.py` already carries).
|
||||
8. **Export — always a fresh, self-contained library** at a user-chosen destination,
|
||||
**including copied audio, for every target** (not just Serato). Never merges into an
|
||||
existing target library, so no cross-platform track identity is required.
|
||||
- Scoped by an **Export Set**: a named, persisted list of track and playlist
|
||||
references. **Live references** — resolved at export time, so the preview must be
|
||||
computed then, never stored. Playlist tracks auto-included, deduplicated, copied
|
||||
once.
|
||||
- Stored in Konduktor's own store (not `userprefs.json`), keyed by a stable library
|
||||
ID held in a **sidecar file next to the user's collection**.
|
||||
- Audio layout: a **global persistent setting** — flat single folder (**default**) or
|
||||
mirror source structure. Flat collisions get a **counter suffix** (`Xtal-2.mp3`).
|
||||
- Playlist folders preserved where the target supports them, otherwise flattened to
|
||||
**path-encoding names** (`House / Peak Time`).
|
||||
- **Pre-scan for missing audio files**, report, let the user decide. **Pre-check disk
|
||||
space**; progress with a working cancel (cancel leaves a partial export — clean up
|
||||
or mark clearly).
|
||||
- Re-export to an occupied destination: **warn, overwrite on confirm**.
|
||||
- Provide an explicit **"export entire library"** action that skips export-set creation.
|
||||
9. **Lossiness — degrade where sensible, drop otherwise.** Goal is maximum feature
|
||||
parity. No loss report for now (deferred, cheap to add later since adapters know what
|
||||
they collapsed).
|
||||
10. **Format layers — reuse mature libraries** (`pyrekordbox` for master.db/SQLCipher/
|
||||
XML/ANLZ; an existing Serato crate+GEOB library) behind Konduktor's adapter
|
||||
interface, consistent with the existing `traktor-nml-utils` dependency posture.
|
||||
11. **Undo/redo — not now, but do not preclude it.** Design commands so inverses can be
|
||||
added later.
|
||||
|
||||
**Sequencing** (see Next Steps for the actionable breakdown)
|
||||
Grid fix → Traktor-only refactor → Rekordbox → Serato → export. Rekordbox was chosen as
|
||||
the second platform over Serato because `pyrekordbox` is the more mature library, despite
|
||||
the riskier write target.
|
||||
|
||||
**Out of scope**: Tauri packaging, bulk metadata editing, CDJ/USB export
|
||||
(`export.pdb` + ANLZ — rejected as impractical), two-way sync, Konduktor owning its own
|
||||
canonical library format.
|
||||
|
||||
**Rejected alternatives worth not relitigating**
|
||||
- Generic model as source of truth, and source-of-truth + diff-based writeback — both
|
||||
rejected; see the save model decision. The claimed "free conversion" benefit is
|
||||
illusory (per-target serializers are needed either way), and diffing destroys edit
|
||||
intent exactly where platforms disagree.
|
||||
- Union superset and core-plus-extensions model shapes.
|
||||
- Cross-platform track matching by path/tags/content-hash/fingerprint — unnecessary
|
||||
given fresh-export-only.
|
||||
- Full audio-file backups for Serato writes.
|
||||
- Reference-in-place exports for non-Serato targets.
|
||||
|
||||
**Standing lesson from this discussion**: establish format capabilities **empirically**
|
||||
against real files rather than assuming them. An assumption that Traktor could not store
|
||||
cue colours was wrong (`CueV2Type` has a `color` field, populated in practice), and the
|
||||
flexible-grid assumption was only settled by reading Ben's actual collection.
|
||||
@@ -0,0 +1,221 @@
|
||||
# Handoff: the export feature
|
||||
|
||||
**For**: an agent picking up Konduktor with no prior context.
|
||||
**Task**: build library export — converting a curated slice of the loaded library
|
||||
into a **fresh, self-contained library for another platform**, with the audio
|
||||
files copied alongside.
|
||||
**Status of the plan**: the multi-platform work is done through the Rekordbox
|
||||
adapter. Export was originally sequenced *after* a Serato adapter; Ben has
|
||||
chosen to bring it forward, so **the only export targets that can exist today are
|
||||
Traktor and Rekordbox**.
|
||||
|
||||
Every *design* decision was settled in
|
||||
[`.claude/discussions/discuss-multi-platform-library-2026-09-17.md`](../discussions/discuss-multi-platform-library-2026-09-17.md)
|
||||
— read its **Export** sections and **"If Moving to Planning/Implementation"**
|
||||
before designing anything. This handoff is the current-state companion: what
|
||||
exists, what to build, and what will bite you. Where they disagree, the
|
||||
discussion doc wins on intent and this one on facts about the code.
|
||||
|
||||
The Rekordbox handoff ([`rekordbox-adapter.md`](rekordbox-adapter.md)) is worth
|
||||
skimming too — its §8 Findings are the format knowledge any Rekordbox *writer*
|
||||
will need, and its history is a good model of how this project verifies things.
|
||||
|
||||
---
|
||||
|
||||
## 1. Where the project is
|
||||
|
||||
Konduktor is a library-management and track-prep tool for DJ software, built on a
|
||||
**generic model + per-platform adapter** architecture. Two adapters exist:
|
||||
|
||||
- **Traktor** (`collection.nml`) — full read/write, byte-exact saves, version
|
||||
history.
|
||||
- **Rekordbox** (`master.db` + ANLZ analysis files) — read/write for metadata,
|
||||
playlists, hot cues and beatgrids. No version history (a deliberate, accepted
|
||||
scope decision). Gaps: cover art, `remap_locations`.
|
||||
|
||||
```
|
||||
backend/konduktor/
|
||||
core/ generic. MUST NOT import a native library type (test_layering.py)
|
||||
model.py Track, CuePoint, GridMarker, TrackCues, PlaylistNode…
|
||||
adapter.py LibraryAdapter / LibraryDriver protocols, SaveOutcome, errors
|
||||
capabilities.py what a loaded library can persist
|
||||
query.py TrackIndex: query/filter/sort/facets/stats
|
||||
registry.py adapter selection by can_open() probe
|
||||
adapters/traktor/ store.py (native model) adapter.py projection.py driver.py …
|
||||
adapters/rekordbox/ same shape; store.py owns the SQLCipher session + ANLZ
|
||||
app_state.py the one loaded library + version-history commits
|
||||
prefs.py userprefs.json in the per-OS app-data dir (paths.app_data_dir())
|
||||
main.py thin FastAPI routes, all under /api
|
||||
```
|
||||
|
||||
**Tests**: `cd backend && ./run_tests.sh` → 331 assertions across
|
||||
`test_layering.py`, `test_save_fidelity.py`, `test_traktor_adapter.py`,
|
||||
`test_rekordbox_adapter.py`, `test_rekordbox_fidelity.py`, `test_phase3.py`,
|
||||
`test_history.py`. Frontend: `npm run build && npm run test`.
|
||||
**The suite must be green at the end of every step** — that discipline is why a
|
||||
1,500-line refactor of the save path landed without a fidelity regression.
|
||||
|
||||
---
|
||||
|
||||
## 2. The one architectural gap, and it is not small
|
||||
|
||||
**No adapter can create a library from nothing.**
|
||||
|
||||
`LibraryDriver` is `can_open` / `open` / `detect` / `describe` / `restore`.
|
||||
`LibraryAdapter` is built entirely around *one already-open library* that commands
|
||||
are replayed onto. Export needs the opposite: **write a brand-new library at a
|
||||
path where nothing exists yet.**
|
||||
|
||||
This is the central design question of the whole feature, and the discussion doc
|
||||
does not settle it. Decide it deliberately and write down why. The obvious
|
||||
shapes:
|
||||
|
||||
1. **A separate `LibraryWriter` protocol** — `create(path)` returning something
|
||||
that accepts tracks, playlists and prep data, implemented per target. Keeps
|
||||
the edit path untouched, which matters because the edit path is the one with
|
||||
the fidelity guarantees. Some duplication with the adapters' write code.
|
||||
2. **Extend `LibraryDriver` with `create(path) -> LibraryAdapter`** — an empty
|
||||
library is then just a library, and the existing commands populate it. Elegant
|
||||
on paper; the risk is that "empty new file" and "the user's real library"
|
||||
start sharing code paths, and the *reason* the current architecture is safe is
|
||||
that the write target is always a retained native model that was parsed from a
|
||||
real file.
|
||||
3. **Target-specific exporters with no shared protocol** — fastest to a working
|
||||
Traktor export, and it will rot.
|
||||
|
||||
The discussion doc's strongest constraint bears on this: *"Two distinct write
|
||||
paths must coexist: a high-fidelity in-place edit path per platform, and a
|
||||
lossy-by-design export path. They have opposite requirements and should not
|
||||
share an implementation."* Read that as pointing at (1), but make the call
|
||||
yourself with the code in front of you.
|
||||
|
||||
---
|
||||
|
||||
## 3. What the design already settles
|
||||
|
||||
Do not relitigate these. They are decided, with rationale and rejected
|
||||
alternatives recorded in the discussion doc.
|
||||
|
||||
**Shape of an export**
|
||||
- Always a **fresh, self-contained library** at a user-chosen destination.
|
||||
**Never merges** into an existing target library. This is what removes any need
|
||||
for cross-platform track identity — there is nothing to match against.
|
||||
- **Always copies the audio files**, for every target, not just Serato.
|
||||
- Audio layout is a **global, persisted setting**: **flat single folder
|
||||
(default)** or **mirror the source directory structure**.
|
||||
- Flat-layout filename collisions get a **counter suffix** (`Xtal-2.mp3`).
|
||||
Known consequence: numbering depends on processing order, so repeat exports may
|
||||
assign different suffixes to the same tracks.
|
||||
- Playlist folders: **preserve where the target supports them**, otherwise
|
||||
flatten to path-encoding names (`House / Peak Time`).
|
||||
- Re-export to an occupied destination: **warn, overwrite on confirm.**
|
||||
- Provide an explicit **"export entire library"** action that skips export-set
|
||||
creation entirely.
|
||||
|
||||
**Export Sets** (the unit of curation)
|
||||
- A named, persisted list of **track and playlist references** scoping an export.
|
||||
Called an **Export Set**, never a "Crate" — Serato uses "crate" for a playlist
|
||||
and Konduktor will import those.
|
||||
- **References are LIVE**: an export set stores pointers, and export resolves
|
||||
them at export time, so later additions to a playlist are picked up.
|
||||
**Consequence: the export preview must be computed at export time, never
|
||||
stored.**
|
||||
- Playlist resolution **auto-includes** referenced tracks, **deduplicates**, and
|
||||
copies each file **exactly once**.
|
||||
- Stored in **Konduktor's own store**, not in the platform library and not in
|
||||
`userprefs.json`, keyed by a **stable library ID**.
|
||||
|
||||
**Running an export**
|
||||
- **Pre-scan for missing audio files**, report them, let the user cancel or
|
||||
proceed without them — fail fast rather than halfway through a multi-hour copy.
|
||||
- **Pre-check disk space** before starting.
|
||||
- **Progress with a working cancel.** Known consequence: cancelling leaves a
|
||||
partial export, which must be cleaned up or clearly marked incomplete.
|
||||
|
||||
**Lossiness**
|
||||
- **Degrade to the nearest equivalent where one exists, drop only where none
|
||||
does.** A Traktor fade-in cue becomes a plain cue on a target without them;
|
||||
Rekordbox memory cues fill spare hot cue slots until they run out.
|
||||
- **No loss report for now** — explicitly deferred. Adapters know what they
|
||||
collapsed, so it stays cheap to add.
|
||||
|
||||
---
|
||||
|
||||
## 4. Landmines, earned
|
||||
|
||||
**There is no stable library ID.** Export sets are specified as keyed by one,
|
||||
held in a sidecar next to the user's collection — and nothing like it exists.
|
||||
Today everything keys off the library's **OS path**: `prefs.get_path_mapping`,
|
||||
`prefs.get_last_collection`, and `history`'s repo directory (a hash of the
|
||||
resolved path). Moving a collection silently orphans all of it. Building export
|
||||
sets on the path would inherit that; building the sidecar is the decided design
|
||||
but is genuinely new work. Do it first — retrofitting an ID once sets exist means
|
||||
migrating them.
|
||||
|
||||
**The lossiness rule needs capabilities the target does not have loaded.**
|
||||
`Capabilities` describes *the currently open library*, via an adapter instance
|
||||
built from a real file. Export needs to know what a target platform can hold
|
||||
*before* any such library exists. Either capabilities must become derivable from
|
||||
a platform alone (not an instance), or exporters must carry their own static
|
||||
declaration. This is exactly where a "what can the target represent?" question
|
||||
will first bite, and `capabilities_for()` in each adapter currently takes a
|
||||
`path`.
|
||||
|
||||
**The two-platform promotion rule still applies.** A concept enters the generic
|
||||
vocabulary only once **two or more** platforms have it. Export will tempt you to
|
||||
add target-specific knobs to generic types; don't. Single-platform concepts stay
|
||||
*preserved but not editable* — for instance Rekordbox **memory cues** are
|
||||
projected and displayed and never written.
|
||||
|
||||
**Rekordbox as an export TARGET is much harder than Traktor.** A Traktor export
|
||||
is one XML file Konduktor already renders byte-exactly. A Rekordbox export needs
|
||||
a `master.db` — SQLCipher, foreign keys into lookup tables, USN bookkeeping — plus
|
||||
per-track ANLZ analysis files containing the beatgrid, plus `masterPlaylists6.xml`.
|
||||
Worse, `.DAT`/`.EXT` analysis files can currently only be *modified*, never
|
||||
created: `beatgrid.write_pqtz()` rebuilds the `PQTZ` tag **inside an existing
|
||||
file**. Generating ANLZ from scratch is unexplored, and `PQT2` (the extended
|
||||
grid) is undecoded — `pyrekordbox` names its per-beat field `unkown`.
|
||||
**Strongly consider shipping Traktor as the only export target first.**
|
||||
|
||||
**CDJ/USB export (`export.pdb` + ANLZ) is rejected as impractical.** It has been
|
||||
re-proposed twice. Do not raise it again.
|
||||
|
||||
---
|
||||
|
||||
## 5. Working agreements
|
||||
|
||||
- **`./run_tests.sh` green at the end of every step.**
|
||||
- **`schemas.py` and `api.ts` land in the same commit** — one contract in two
|
||||
languages.
|
||||
- **Verify against reality, do not infer.** The project's standing lesson, and it
|
||||
has been proved right four times: Traktor cue colours, flexible grid marker
|
||||
naming, whether Rekordbox reads `PQTZ` or `PQT2`, and the hot cue slot
|
||||
encoding. That last one cost two rounds of wrong theory built on three
|
||||
incidental data points; one deliberate probe across the full range settled it.
|
||||
For export the equivalent is: **write an export, then open it in the real DJ
|
||||
software** before believing it works.
|
||||
- **Ben's Rekordbox library is a disposable test library** — write to it directly,
|
||||
no backups needed. **His Traktor collection is real, irreplaceable data**
|
||||
(8,485 entries): always work against copies. `./dev-sandbox.sh` already
|
||||
encodes exactly this split and refuses to start if another server holds the
|
||||
ports.
|
||||
- **Capability-gate every control.** The UI must never offer an edit — or an
|
||||
export target — that cannot actually be produced. This has failed twice and
|
||||
both times it was a stale flag, not missing machinery.
|
||||
|
||||
## 6. Suggested first steps
|
||||
|
||||
1. **Decide the writer architecture** (§2) and record the decision and its
|
||||
rejected alternatives, in the style of the discussion doc.
|
||||
2. **Build the stable library ID sidecar** (§4) — everything else keys off it.
|
||||
3. **Export Sets: model, store, API, UI.** Live references; preview computed at
|
||||
export time.
|
||||
4. **A Traktor exporter end to end**, with the audio copy, the pre-scan, the
|
||||
space check and cancellable progress.
|
||||
5. **Open the result in Traktor.** Not "the tests pass" — actually open it.
|
||||
6. Only then consider a Rekordbox exporter, knowing §4's warning.
|
||||
|
||||
Bulk metadata editing also remains unbuilt and unblocked; it is far smaller than
|
||||
this and was deferred specifically until the adapter architecture existed. If a
|
||||
shippable win is wanted sooner, that is the alternative — confirm with Ben rather
|
||||
than assuming.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,142 @@
|
||||
# The stem engine: a frozen torch + Demucs program, built per target and
|
||||
# published on its OWN release channel (`engine-v<version>`), separate from the
|
||||
# app's `v<version>-b<N>` releases. The app downloads the one it needs on first
|
||||
# use (see backend/konduktor/stems/engine_manager.py).
|
||||
#
|
||||
# * A tag `engine-v1.2.3` builds, tests and publishes — the tag must match
|
||||
# `konduktor_engine.VERSION`.
|
||||
# * A manual run builds and tests only (artifacts, no release).
|
||||
#
|
||||
# Releases are `prerelease: true` and `make_latest: false`: GitHub's "latest"
|
||||
# is what an app would take for itself, and the app's update check reads the
|
||||
# release list (UpdateDialog.tsx) — an engine release must never look like one.
|
||||
#
|
||||
# The weights are NOT in the engine (their licence is ambiguous): CI fetches the
|
||||
# pinned files from Hugging Face only to run the golden test.
|
||||
name: Engine
|
||||
|
||||
on:
|
||||
push:
|
||||
tags: ["engine-v*"]
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: engine-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
build:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- target: macos-arm64
|
||||
os: macos-latest
|
||||
torch_index: ""
|
||||
- target: windows-x64-cpu
|
||||
os: windows-latest
|
||||
torch_index: "" # PyPI's Windows torch is the CPU build
|
||||
- target: windows-x64-cuda
|
||||
os: windows-latest
|
||||
# CUDA 13: Turing (RTX 20) through Blackwell (RTX 50); needs an
|
||||
# NVIDIA driver from r580. Older cards get the CPU engine — the
|
||||
# manager checks `engine info`'s arch list before offering this.
|
||||
torch_index: "https://download.pytorch.org/whl/cu130"
|
||||
runs-on: ${{ matrix.os }}
|
||||
name: ${{ matrix.target }}
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
working-directory: engine
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
- name: Check the tag matches the engine version
|
||||
if: startsWith(github.ref, 'refs/tags/engine-v')
|
||||
run: |
|
||||
want="$(python -c 'import konduktor_engine as e; print(e.VERSION)')"
|
||||
[ "${GITHUB_REF_NAME#engine-v}" = "$want" ] || { echo "tag ${GITHUB_REF_NAME} != engine $want"; exit 1; }
|
||||
|
||||
- name: Install
|
||||
run: |
|
||||
python -m pip install --upgrade pip uv
|
||||
uv venv .venv --python 3.12
|
||||
PY=.venv/bin/python; [ -f .venv/Scripts/python.exe ] && PY=.venv/Scripts/python.exe
|
||||
echo "PY=$PY" >> "$GITHUB_ENV"
|
||||
if [ -n "${{ matrix.torch_index }}" ]; then
|
||||
uv pip install --python "$PY" "torch==2.14.0" --index-url "${{ matrix.torch_index }}"
|
||||
fi
|
||||
uv pip install --python "$PY" -r requirements.txt "pyinstaller==6.21.0"
|
||||
|
||||
- name: Weights (for the golden test only)
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: engine/weights
|
||||
key: htdemucs-ft-d74ac89c3a1e874fc78f152555cf4d8533f06cd4
|
||||
- run: $PY fetch_weights.py weights
|
||||
|
||||
- name: Freeze
|
||||
run: $PY -m PyInstaller --noconfirm --clean konduktor-engine.spec
|
||||
|
||||
- name: Golden test (frozen vs unfrozen, CPU)
|
||||
run: |
|
||||
EXE=dist/konduktor-engine/konduktor-engine; [ -f "$EXE.exe" ] && EXE="$EXE.exe"
|
||||
$PY test_engine.py --weights weights --frozen "$EXE"
|
||||
|
||||
- name: Package
|
||||
run: $PY package.py ${{ matrix.target }} dist out
|
||||
|
||||
- name: Paths fit Windows' limit once installed
|
||||
run: |
|
||||
# Installed under e.g. %LOCALAPPDATA%\Konduktor\engine\<ver>\<target>\
|
||||
# (~70 characters on a typical user name): the tree must stay short.
|
||||
$PY -c "import json,sys; n=json.load(open('out/${{ matrix.target }}.json'))['longest_path']; print('longest', n); sys.exit(n > 180)"
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: engine-${{ matrix.target }}
|
||||
path: engine/out/*
|
||||
if-no-files-found: error
|
||||
|
||||
release:
|
||||
needs: build
|
||||
if: startsWith(github.ref, 'refs/tags/engine-v')
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: artifacts
|
||||
merge-multiple: true
|
||||
- name: Manifest
|
||||
run: |
|
||||
python - <<'PY'
|
||||
import json, glob, os
|
||||
targets = {}
|
||||
for f in glob.glob("artifacts/*.json"):
|
||||
info = json.load(open(f))
|
||||
targets[info["target"]] = info
|
||||
version = os.environ["GITHUB_REF_NAME"].removeprefix("engine-v")
|
||||
weights = json.load(open("engine/weights.json"))
|
||||
json.dump({"version": version, "targets": targets, "weights": weights},
|
||||
open("artifacts/engine-manifest.json", "w"), indent=1)
|
||||
PY
|
||||
- uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ github.ref_name }}
|
||||
name: Konduktor stem engine ${{ github.ref_name }}
|
||||
prerelease: true
|
||||
make_latest: false
|
||||
fail_on_unmatched_files: true
|
||||
files: |
|
||||
artifacts/*.tar.gz*
|
||||
artifacts/engine-manifest.json
|
||||
body: |
|
||||
The stem engine Konduktor downloads for **Convert to Stems** — not an app release.
|
||||
Konduktor fetches the right file for your computer itself; there is nothing to install by hand.
|
||||
+8
-1
@@ -18,11 +18,14 @@ frontend/dist-ssr/
|
||||
# The collection is personal, large, and irreplaceable — don't commit it.
|
||||
# Remove this if you deliberately want to version a sample .nml.
|
||||
*.nml
|
||||
# Backups Konduktor will create before any write (Phase 3+).
|
||||
# Legacy pre-git backups (superseded by version history; left ignored so any
|
||||
# old .bak files on disk stay out of git).
|
||||
*.nml.bak
|
||||
*.nml.backup
|
||||
*.nml.*.bak
|
||||
backups/
|
||||
# Version-history git repos, if a dev points KONDUKTOR_DATA_DIR inside the repo.
|
||||
history/
|
||||
|
||||
# ---- Editor / OS ----
|
||||
.vscode/
|
||||
@@ -44,3 +47,7 @@ backend/userprefs.json
|
||||
# build_sidecar.sh are source and ARE tracked.
|
||||
backend/build/
|
||||
backend/dist/
|
||||
|
||||
# ---- Stem engine (PyInstaller onedir build) ----
|
||||
engine/build/
|
||||
engine/dist/
|
||||
@@ -158,10 +158,20 @@ The installers land in `frontend\src-tauri\target\release\bundle\` (an `.msi` an
|
||||
an NSIS `-setup.exe`). See [BUILDING-WINDOWS.md](BUILDING-WINDOWS.md) for the full
|
||||
walkthrough and Windows-specific notes.
|
||||
|
||||
> **Note:** builds are currently **unsigned**, so the first launch is flagged by
|
||||
> the OS — on macOS right-click → **Open** to get past Gatekeeper; on Windows
|
||||
> click **More info → Run anyway** past SmartScreen. The macOS `.dmg` is
|
||||
> Apple-Silicon (`aarch64`) only.
|
||||
> **First launch — getting past the OS security prompt.** Builds are
|
||||
> **ad-hoc signed, not notarized** (no paid Apple/Windows developer cert yet), so
|
||||
> the OS flags them the first time. This is expected — the app isn't damaged.
|
||||
>
|
||||
> - **macOS:** right-click the app → **Open** → **Open** (or System Settings →
|
||||
> Privacy & Security → **Open Anyway** after the first blocked attempt). If it
|
||||
> still refuses — common for a `.dmg` downloaded via a browser, which macOS
|
||||
> quarantines — clear the quarantine flag once from Terminal:
|
||||
> ```bash
|
||||
> xattr -cr /Applications/Konduktor.app
|
||||
> ```
|
||||
> - **Windows:** click **More info → Run anyway** past SmartScreen.
|
||||
>
|
||||
> The macOS `.dmg` is Apple-Silicon (`aarch64`) only.
|
||||
|
||||
> **Faster local builds:** `npx tauri build --debug --bundles app` skips the
|
||||
> optimizer and the installer, giving you a runnable app in seconds — handy while
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
"""Benchmark beatgrid detection against grids a DJ platform already analysed.
|
||||
|
||||
NOT part of `run_tests.sh`: it needs real audio, and the answer is a score to
|
||||
compare rather than a pass/fail. Every open is read-only — nothing is saved.
|
||||
|
||||
python bench_grid_detect.py # the local Rekordbox library
|
||||
python bench_grid_detect.py path/to/collection.nml path/to/master.db
|
||||
python bench_grid_detect.py --legacy # score the old librosa beat_track
|
||||
|
||||
The reference is each track's own grid, and only single-marker grids are used:
|
||||
a multi-marker grid is either a real tempo change (which a constant-tempo
|
||||
detector cannot match by design) or a hand edit, and neither is ground truth
|
||||
for "what is this track's tempo".
|
||||
|
||||
Per track it reports:
|
||||
- BPM error, and whether it is an octave error (half/double tempo);
|
||||
- PHASE error at 30 s in and 30 s before the end — the distance between the
|
||||
detected grid's nearest beat and the reference's, in ms. Measuring at two
|
||||
ends is what separates "anchor wrong" (both off by the same amount) from
|
||||
"BPM wrong" (error grows along the track), which one number would conflate.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
os.environ.setdefault("KONDUKTOR_DATA_DIR", tempfile.mkdtemp(prefix="konduktor-bench-"))
|
||||
|
||||
import konduktor.adapters # noqa: E402,F401 — registers the drivers
|
||||
from konduktor.core import registry # noqa: E402
|
||||
|
||||
BPM_OK = 0.02 # a grid this close drifts < 1/50 beat per minute...
|
||||
PHASE_OK_MS = 10.0 # roughly where a DJ starts to hear flamming
|
||||
|
||||
|
||||
def _phase_error_ms(t: float, ref: tuple[float, float], det: tuple[float, float]) -> float:
|
||||
"""Signed distance (ms) from the reference's nearest beat at ``t`` to the
|
||||
detected grid's nearest beat, wrapped to half the reference beat."""
|
||||
r0, rb = ref
|
||||
d0, db = det
|
||||
rp, dp = 60.0 / rb, 60.0 / db
|
||||
ref_beat = r0 + round((t - r0) / rp) * rp
|
||||
det_beat = d0 + round((ref_beat - d0) / dp) * dp
|
||||
e = det_beat - ref_beat
|
||||
e = (e + rp / 2) % rp - rp / 2
|
||||
return e * 1000.0
|
||||
|
||||
|
||||
def _octave(det: float, ref: float) -> str:
|
||||
for k, name in ((2.0, "x2"), (0.5, "/2"), (1.5, "x1.5"), (2 / 3, "/1.5")):
|
||||
if abs(det - ref * k) < 0.5:
|
||||
return name
|
||||
return ""
|
||||
|
||||
|
||||
def legacy_detect(audio_path: str):
|
||||
"""The detector `core/grid_detect.py` replaced (librosa ``beat_track``), kept
|
||||
here so the two can still be compared on the same references."""
|
||||
import librosa
|
||||
import numpy as np
|
||||
from konduktor.core.grid_detect import GridResult
|
||||
|
||||
y, sr = librosa.load(audio_path, sr=22050, mono=True)
|
||||
tempo, beats = librosa.beat.beat_track(y=y, sr=sr, trim=False)
|
||||
return GridResult(float(np.ravel(tempo)[0]), float(librosa.frames_to_time(beats, sr=sr)[0]), len(y) / sr)
|
||||
|
||||
|
||||
def references(paths: list[Path]) -> list[tuple[str, Path, float, float]]:
|
||||
out = []
|
||||
for p in paths:
|
||||
a = registry.open_library(p)
|
||||
try:
|
||||
for t in a.tracks:
|
||||
cues = a.track_cues(t.id)
|
||||
if cues is None or len(cues.grid_markers) != 1:
|
||||
continue
|
||||
audio = a.audio_path(t.id)
|
||||
if audio is None or not audio.exists():
|
||||
continue
|
||||
m = cues.grid_markers[0]
|
||||
out.append((f"{t.artist or ''} - {t.title or audio.stem}".strip(" -"), audio, m.start, m.bpm))
|
||||
finally:
|
||||
close = getattr(a, "close", None)
|
||||
if close:
|
||||
close()
|
||||
# One row per audio file: the same file in two libraries would count twice.
|
||||
seen, uniq = set(), []
|
||||
for r in out:
|
||||
if r[1] not in seen:
|
||||
seen.add(r[1])
|
||||
uniq.append(r)
|
||||
return uniq
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("libraries", nargs="*", type=Path)
|
||||
ap.add_argument("--legacy", action="store_true", help="score the old librosa beat_track detector")
|
||||
args = ap.parse_args()
|
||||
|
||||
libs = args.libraries or [Path.home() / "Library/Pioneer/rekordbox/master.db"]
|
||||
refs = references(libs)
|
||||
if not refs:
|
||||
print("No single-marker reference grids with reachable audio.")
|
||||
return 1
|
||||
|
||||
if args.legacy:
|
||||
detect = legacy_detect
|
||||
else:
|
||||
from konduktor.core.grid_detect import detect_grid as detect
|
||||
|
||||
rows = []
|
||||
for name, audio, r0, rb in refs:
|
||||
t0 = time.perf_counter()
|
||||
try:
|
||||
res = detect(str(audio))
|
||||
except Exception as ex: # a failure is a data point, not a crash
|
||||
print(f" FAIL {name[:48]:48} {ex}")
|
||||
rows.append(None)
|
||||
continue
|
||||
dt = time.perf_counter() - t0
|
||||
bpm, first = res.bpm, res.anchor
|
||||
import soundfile as sf
|
||||
try:
|
||||
dur = sf.info(str(audio)).duration
|
||||
except Exception:
|
||||
dur = res.duration
|
||||
early = _phase_error_ms(min(30.0, dur / 3), (r0, rb), (first, bpm))
|
||||
late = _phase_error_ms(max(dur - 30.0, 2 * dur / 3), (r0, rb), (first, bpm))
|
||||
oct_ = _octave(bpm, rb) if abs(bpm - rb) >= 0.5 else ""
|
||||
ok = abs(bpm - rb) <= BPM_OK and abs(early) <= PHASE_OK_MS and abs(late) <= PHASE_OK_MS
|
||||
lossy = audio.suffix.lower() not in (".wav", ".aif", ".aiff", ".flac")
|
||||
rows.append((abs(bpm - rb), early, late, oct_, ok, dt, lossy))
|
||||
conf = f"{res.drift_ms:5.1f}" if res.drift_ms is not None else " -"
|
||||
print(
|
||||
f" {'ok ' if ok else 'BAD '} {name[:48]:48} ref {rb:7.3f} got {bpm:8.3f} {oct_:5}"
|
||||
f" phase {early:+7.1f} / {late:+7.1f} ms drift {conf} ms {dt:4.1f}s"
|
||||
)
|
||||
|
||||
good = [r for r in rows if r]
|
||||
n = len(rows)
|
||||
same_octave = [r for r in good if not r[3]]
|
||||
print()
|
||||
print(f"tracks {n}")
|
||||
print(f"all correct {sum(r[4] for r in good)}/{n}")
|
||||
print(f"BPM within {BPM_OK} {sum(r[0] <= BPM_OK for r in good)}/{n}")
|
||||
print(f"octave errors {sum(bool(r[3]) for r in good)}/{n}")
|
||||
if same_octave:
|
||||
import statistics as st
|
||||
print(f"median |phase| early {st.median(abs(r[1]) for r in same_octave):.1f} ms")
|
||||
print(f"median |phase| late {st.median(abs(r[2]) for r in same_octave):.1f} ms")
|
||||
print(f"phase within {PHASE_OK_MS:.0f} ms "
|
||||
f"{sum(abs(r[1]) <= PHASE_OK_MS and abs(r[2]) <= PHASE_OK_MS for r in same_octave)}/{n}")
|
||||
print(f"mean time per track {sum(r[5] for r in good) / max(1, len(good)):.2f} s")
|
||||
|
||||
# A platform's MP3/AAC time base can differ from the decoded audio's by a
|
||||
# constant (Rekordbox: ~+26 ms, the decoder delay it does not trim). That
|
||||
# is not detection error, and it would swamp it — so report the constant
|
||||
# per format, and how tightly the tracks sit around it.
|
||||
import statistics as st
|
||||
print()
|
||||
for label, want in (("lossless", False), ("lossy", True)):
|
||||
grp = [r for r in same_octave if r[6] == want and r[0] <= BPM_OK]
|
||||
if len(grp) < 2:
|
||||
continue
|
||||
offs = [(r[1] + r[2]) / 2 for r in grp]
|
||||
med = st.median(offs)
|
||||
spread = [abs(o - med) for o in offs]
|
||||
within = sum(abs(r[1] - med) <= PHASE_OK_MS and abs(r[2] - med) <= PHASE_OK_MS for r in grp)
|
||||
print(f"{label:9} n={len(grp):2} constant offset {med:+6.1f} ms "
|
||||
f"|deviation| median {st.median(spread):4.1f} max {max(spread):5.1f} ms "
|
||||
f"within {PHASE_OK_MS:.0f} ms of it: {within}/{len(grp)}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,133 @@
|
||||
"""Benchmark Auto Hotcues' structure events against Rekordbox's phrase analysis.
|
||||
|
||||
NOT part of `run_tests.sh`: it needs real audio and a Rekordbox library whose
|
||||
tracks were analysed with phrase analysis on (the `PSSI` tag in each `.EXT`).
|
||||
Read-only — nothing is saved.
|
||||
|
||||
python bench_structure.py # the local Rekordbox library
|
||||
python bench_structure.py -v # per-track events, detected vs reference
|
||||
|
||||
The reference is Rekordbox's own analysis, not ground truth, and it is only
|
||||
comparable on "High"-mood tracks, whose labels map onto what a DJ cues:
|
||||
Intro / Up (build) / Down (breakdown) / Chorus (drop) / Outro. "Mid" tracks are
|
||||
labelled Verse / Chorus / Bridge and are reported separately for that reason.
|
||||
Tracks whose detected BPM is a different octave from Rekordbox's are skipped:
|
||||
their bars are not the same bars.
|
||||
|
||||
Events are compared in bars from each side's own first downbeat:
|
||||
- drop_n = start of the n-th Chorus run;
|
||||
- breakdown_n = end of the n-th drop, when another drop follows;
|
||||
- build_n = the Up run right before drop_n (Rekordbox's Up usually spans the
|
||||
whole pre-drop groove, so this one is indicative at best);
|
||||
- outro = start of the Outro.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
os.environ.setdefault("KONDUKTOR_DATA_DIR", tempfile.mkdtemp(prefix="konduktor-bench-"))
|
||||
|
||||
import konduktor.adapters # noqa: E402,F401 — registers the drivers
|
||||
from konduktor.core import grid_detect, registry, structure # noqa: E402
|
||||
|
||||
DROP = {1: 5, 2: 9} # PSSI kind of a Chorus, by mood (1 = High, 2 = Mid)
|
||||
OUTRO = {1: 6, 2: 10}
|
||||
UP = {1: 2}
|
||||
|
||||
|
||||
def references(db: Path) -> list[dict]:
|
||||
from pyrekordbox.anlz import AnlzFile
|
||||
|
||||
a = registry.open_library(db)
|
||||
out = []
|
||||
try:
|
||||
st = a._store
|
||||
for t in a.tracks:
|
||||
path = a.audio_path(t.id)
|
||||
rel = getattr(st.content(t.id), "AnalysisDataPath", None)
|
||||
if not path or not path.exists() or not rel:
|
||||
continue
|
||||
base = st.path.parent / "share" / str(rel).lstrip("/\\")
|
||||
ext = base.with_suffix(".EXT")
|
||||
if not (base.is_file() and ext.is_file()):
|
||||
continue
|
||||
rec = {"path": str(path), "title": t.title or path.stem}
|
||||
for tag in AnlzFile.parse_file(str(base)).tags:
|
||||
if tag.type == "PQTZ" and len(tag.content.entries): # one-shots have none
|
||||
e = tag.content.entries
|
||||
rec["bpm"] = e[0].tempo / 100
|
||||
rec["first_down"] = next(i for i, x in enumerate(e) if x.beat == 1)
|
||||
for tag in AnlzFile.parse_file(str(ext)).tags:
|
||||
if tag.type == "PSSI":
|
||||
rec["mood"] = tag.content.mood
|
||||
rec["phrases"] = [(x.beat, x.kind) for x in tag.content.entries]
|
||||
if "phrases" in rec and "bpm" in rec:
|
||||
out.append(rec)
|
||||
finally:
|
||||
a.close()
|
||||
return out
|
||||
|
||||
|
||||
def truth(rec: dict) -> dict[str, int]:
|
||||
runs: list[tuple[int, int]] = []
|
||||
for beat, kind in rec["phrases"]:
|
||||
bar = round((beat - 1 - rec["first_down"]) / 4)
|
||||
if not runs or runs[-1][1] != kind:
|
||||
runs.append((bar, kind))
|
||||
m, ev = rec["mood"], {}
|
||||
drops = [i for i, (_, k) in enumerate(runs) if k == DROP.get(m)]
|
||||
for n, i in enumerate(drops, start=1):
|
||||
ev[f"drop_{n}"] = runs[i][0]
|
||||
if n < len(drops) and i + 1 < len(runs):
|
||||
ev[f"breakdown_{n}"] = runs[i + 1][0]
|
||||
if m in UP and i > 0 and runs[i - 1][1] == UP[m]:
|
||||
ev[f"build_{n}"] = runs[i - 1][0]
|
||||
outro = [b for b, k in runs if k == OUTRO.get(m)]
|
||||
if outro:
|
||||
ev["outro"] = outro[0]
|
||||
return ev
|
||||
|
||||
|
||||
def main() -> int:
|
||||
verbose = "-v" in sys.argv
|
||||
args = [a for a in sys.argv[1:] if not a.startswith("-")]
|
||||
db = Path(args[0]) if args else Path.home() / "Library/Pioneer/rekordbox/master.db"
|
||||
refs = references(db)
|
||||
if not refs:
|
||||
print("No tracks with Rekordbox phrase analysis and reachable audio.")
|
||||
return 1
|
||||
|
||||
for mood, label in ((1, "High"), (2, "Mid")):
|
||||
stats: dict[str, list[int]] = {}
|
||||
for rec in (r for r in refs if r["mood"] == mood):
|
||||
g = grid_detect.detect_grid(rec["path"])
|
||||
if abs(g.bpm - rec["bpm"]) >= 1:
|
||||
continue # a different octave: not the same bars
|
||||
st = structure.analyse(rec["path"], [(g.anchor, g.bpm)])
|
||||
det = {k: (v - st.bar0) // 4 for k, v in st.events.items()}
|
||||
tru = truth(rec)
|
||||
if verbose:
|
||||
print(f" {rec['title'][:28]:28} ref {tru}\n {'':28} got { {k: det[k] for k in tru if k in det} }")
|
||||
for e, bar in tru.items():
|
||||
key = e if e in ("drop_1", "drop_2", "breakdown_1", "build_1", "build_2", "outro") else e.split("_")[0] + "_n"
|
||||
s = stats.setdefault(key, [0, 0, 0])
|
||||
s[0] += 1
|
||||
if e in det:
|
||||
s[1] += det[e] == bar
|
||||
s[2] += abs(det[e] - bar) <= 4
|
||||
if not stats:
|
||||
continue
|
||||
print(f"== {label}-mood tracks")
|
||||
for k in sorted(stats):
|
||||
n, exact, near = stats[k]
|
||||
print(f" {k:12} n={n:2} exact bar {exact:2} ({exact / n:4.0%}) within 4 bars {near:2} ({near / n:4.0%})")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -11,6 +11,15 @@ PY="${PY:-.venv/bin/python}"
|
||||
"$PY" -m PyInstaller --noconfirm --clean konduktor-sidecar.spec
|
||||
echo "Built: $ROOT/dist/konduktor-sidecar"
|
||||
|
||||
# NOTE: do NOT re-codesign this binary. PyInstaller already ad-hoc signs the
|
||||
# one-file bootloader AND its packed libraries (Python.framework, etc.) with a
|
||||
# matching identity. Re-signing only the outer bootloader (e.g. `codesign -s -`)
|
||||
# desyncs the Team IDs, so at runtime dlopen of the extracted Python framework
|
||||
# fails with "different Team IDs" and the sidecar dies on launch (which makes
|
||||
# the Tauri app panic: "backend sidecar did not report a port"). The app bundle
|
||||
# is ad-hoc signed separately via tauri.conf.json `bundle.macOS.signingIdentity`,
|
||||
# which seals this binary without re-signing it.
|
||||
|
||||
# Stage for Tauri: the sidecar must be named with the host target triple so the
|
||||
# shell plugin can resolve it in both dev and bundle. (rustc must be on PATH.)
|
||||
if command -v rustc >/dev/null 2>&1; then
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
"""DEV ONLY — convert audio files to stem files with an UNFROZEN engine.
|
||||
|
||||
Not shipped, not in run_tests.sh. It exists so real stem files can be made (and
|
||||
checked in Traktor) before the frozen engine and its download exist: the stem
|
||||
writer (`core/stem_file.py`) runs here in the backend venv, and the separation
|
||||
runs in any Python that has torch + demucs, through the engine's own one-shot
|
||||
CLI — the same raw-f32 exchange the batch will use.
|
||||
|
||||
python dev_stems.py --engine-python ~/demucs-venv/bin/python \\
|
||||
--weights ~/.cache/huggingface/hub/models--adefossez--HTDemucs-ft/snapshots/<rev> \\
|
||||
[--out-dir DIR] [--device auto] FILE...
|
||||
|
||||
Each FILE becomes `<name>.stem.m4a` beside it (or in --out-dir); an existing
|
||||
target is skipped, never overwritten.
|
||||
|
||||
With `--collection NML` it also does what the batch will do at its end: park
|
||||
each original (`.<name>.konduktor-parked`, beside it), repoint the collection
|
||||
entry that names it at the stem file (`apply_stem_swaps`), and SAVE — after
|
||||
copying the collection into its `backups/` folder. Traktor must be closed.
|
||||
`--keep-audio-id` keeps Traktor's analysis fingerprint on the swapped entries
|
||||
(the milestone-2 check compares kept vs cleared).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
import numpy as np # noqa: E402
|
||||
|
||||
from konduktor.core import stem_file as sf # noqa: E402
|
||||
|
||||
ENGINE_DIR = Path(__file__).resolve().parents[1] / "engine"
|
||||
|
||||
|
||||
def engine_separator(python: str, weights: str, device: str):
|
||||
def separate(pcm: np.ndarray) -> list[np.ndarray]:
|
||||
with tempfile.TemporaryDirectory(prefix="konduktor-dev-stems-") as d:
|
||||
mix = Path(d) / "mix.f32"
|
||||
np.ascontiguousarray(pcm, dtype=np.float32).tofile(mix)
|
||||
cmd = [python, "-m", "konduktor_engine", "separate", "--input", str(mix),
|
||||
"--samples", str(pcm.shape[1]), "--output-dir", str(Path(d) / "out"),
|
||||
"--weights", weights, "--device", device]
|
||||
proc = subprocess.Popen(cmd, cwd=ENGINE_DIR, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL, text=True)
|
||||
last = None
|
||||
for line in proc.stdout:
|
||||
msg = json.loads(line)
|
||||
if msg["event"] == "progress":
|
||||
print(f"\r separating {msg['fraction'] * 100:5.1f} %", end="", flush=True)
|
||||
last = msg
|
||||
proc.wait()
|
||||
print()
|
||||
if not last or last["event"] != "done":
|
||||
raise sf.StemFileError(f"engine failed: {last}")
|
||||
return [np.fromfile(Path(d) / "out" / f"{name}.f32", dtype=np.float32).reshape(2, -1)
|
||||
for name in sf.DEMUCS_ORDER]
|
||||
return separate
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--engine-python", required=True)
|
||||
ap.add_argument("--weights", required=True)
|
||||
ap.add_argument("--out-dir")
|
||||
ap.add_argument("--device", default="auto")
|
||||
ap.add_argument("--collection")
|
||||
ap.add_argument("--keep-audio-id", action="store_true")
|
||||
ap.add_argument("files", nargs="+")
|
||||
args = ap.parse_args()
|
||||
separate = engine_separator(args.engine_python, args.weights, args.device)
|
||||
adapter = None
|
||||
swaps = []
|
||||
if args.collection:
|
||||
if subprocess.run(["pgrep", "-x", "Traktor"], capture_output=True).returncode == 0:
|
||||
print("Traktor is running — close it first (it rewrites the collection on exit).")
|
||||
return 1
|
||||
from konduktor.adapters.traktor.adapter import TraktorAdapter
|
||||
adapter = TraktorAdapter(Path(args.collection))
|
||||
adapter.store._KEEP_AUDIO_ID_ON_STEM = args.keep_audio_id
|
||||
by_path = {str(adapter.audio_path(t.id)): t.id for t in adapter.tracks}
|
||||
for f in (Path(x).expanduser().absolute() for x in args.files):
|
||||
target = (Path(args.out_dir) if args.out_dir else f.parent) / sf.stem_target_name(f.name)
|
||||
if target.exists():
|
||||
print(f"skip (exists): {target}")
|
||||
continue
|
||||
partial = target.with_name(target.name + ".konduktor-partial")
|
||||
t0 = time.time()
|
||||
print(f"{f.name}")
|
||||
try:
|
||||
written = sf.build(f, partial, separate)
|
||||
except Exception:
|
||||
partial.unlink(missing_ok=True)
|
||||
raise
|
||||
os.replace(partial, target)
|
||||
print(f" -> {target.name} {written.duration:.0f} s, {written.bit_rate // 1000} kbps x5, "
|
||||
f"{written.size / 1e6:.1f} MB, {time.time() - t0:.0f} s")
|
||||
if adapter is not None:
|
||||
from konduktor.core.adapter import StemSwap
|
||||
tid = by_path.get(str(f))
|
||||
if tid is None:
|
||||
print(f" (not in the collection: {f})")
|
||||
continue
|
||||
parked = f.with_name(f".{f.name}.konduktor-parked")
|
||||
os.replace(f, parked)
|
||||
swaps.append(StemSwap(tid, target, "repoint", parked, written.bit_rate,
|
||||
written.duration, written.size))
|
||||
if adapter is not None and swaps:
|
||||
import shutil
|
||||
nml = Path(args.collection)
|
||||
backups = nml.parent / "backups"
|
||||
backups.mkdir(exist_ok=True)
|
||||
shutil.copy2(nml, backups / f"{nml.name}.{time.strftime('%Y%m%d-%H%M%S')}.dev-stems.bak")
|
||||
res = adapter.apply_stem_swaps(swaps)
|
||||
adapter.save()
|
||||
print(f"swapped {len(res.renamed)} entries; clamped: {res.clamped or 'none'}; saved {nml}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1 @@
|
||||
placeholder
|
||||
@@ -0,0 +1 @@
|
||||
placeholder
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,58 @@
|
||||
# OneLibrary fixture drive
|
||||
|
||||
A real OneLibrary USB export, trimmed to the size of a test fixture. This is the
|
||||
drive `test_onelibrary_adapter.py` runs against, so the suite needs no USB stick
|
||||
plugged in and gives the same answer on every machine.
|
||||
|
||||
Produced by rekordbox 7.2.18 exporting a two-track playlist to an exFAT stick.
|
||||
**Nothing in the database was written or edited by Konduktor** — it is the bytes
|
||||
rekordbox itself wrote, which is the whole point of a fixture whose job is to
|
||||
prove we read the real format correctly.
|
||||
|
||||
## What was changed
|
||||
|
||||
Only the analysis files, and only by deleting whole tags:
|
||||
|
||||
| File | Original | Here |
|
||||
|---|---|---|
|
||||
| `ANLZ0000.DAT` | 4,972 B | 2,812 B |
|
||||
| `ANLZ0000.EXT` | 85,602 B | 732 B |
|
||||
|
||||
`PPTH`, `PQTZ`, `PCOB` and `PCO2` — the path, the beatgrid and the two cue lists,
|
||||
i.e. everything the adapter reads — are kept **byte for byte**. The waveform tags
|
||||
(`PWAV`, `PWV2`–`PWV5`) are dropped, which is where ~99% of the `.EXT` went, and
|
||||
the `.2EX` files are omitted entirely.
|
||||
|
||||
The trim is byte-level tag surgery, rewriting only the `PMAI` header's file
|
||||
length: `pyrekordbox` cannot rebuild a file containing cue tags, so re-serialising
|
||||
was not an option.
|
||||
|
||||
The two `.mp3` files are **placeholders**, not audio. The adapter resolves paths
|
||||
and never opens them; carrying 12 MB of demo tracks in the repo to prove that
|
||||
would be silly.
|
||||
|
||||
## What is in it
|
||||
|
||||
- 2 tracks, one of which (`Demo Track 1`) carries a **flexible multi-tempo grid**
|
||||
(128.00 BPM to 60 s, then 90.00 BPM) — the awkward case, deliberately.
|
||||
- 4 hot cues plus a looped memory cue on that track, including one on pad **D**,
|
||||
which is the cue that lives only in the `.EXT` and that a reader looking at the
|
||||
`.DAT` alone would lose.
|
||||
- 1 playlist, `demos`, holding both tracks in order.
|
||||
|
||||
`Demo Track 1`'s title still reads `[KONDUKTOR WROTE THIS]` because the grid and
|
||||
title were written into `master.db` by Konduktor before the export. That is
|
||||
incidental to the fixture, but it does record that the whole chain — Konduktor →
|
||||
`master.db` → rekordbox's OneLibrary export → this file — preserved them.
|
||||
|
||||
## schema.sql
|
||||
|
||||
The complete `CREATE TABLE` set for a OneLibrary database, all 22 tables,
|
||||
extracted from Traktor Pro 4.5's binary, which embeds the DDL it uses to create
|
||||
one. AlphaTheta publishes no specification, so this is the closest thing to one:
|
||||
a second vendor's independent implementation of the same schema. It was verified
|
||||
by building an empty database from it and having `pyrekordbox`'s ORM — a third
|
||||
implementation — open and write to it.
|
||||
|
||||
Not loaded by the tests; kept as documentation, and as the starting point if
|
||||
Konduktor ever needs to create a drive from nothing.
|
||||
@@ -0,0 +1,208 @@
|
||||
CREATE TABLE IF NOT EXISTS "content" (
|
||||
"content_id" integer primary key not null,
|
||||
"title" varchar,
|
||||
"titleForSearch" varchar,
|
||||
"subtitle" varchar,
|
||||
"bpmx100" int,
|
||||
"length" int,
|
||||
"trackNo" int,
|
||||
"discNo" int,
|
||||
"artist_id_artist" int,
|
||||
"artist_id_remixer" int,
|
||||
"artist_id_originalArtist" int,
|
||||
"artist_id_composer" int,
|
||||
"artist_id_lyricist" int,
|
||||
"album_id" int,
|
||||
"genre_id" int,
|
||||
"label_id" int,
|
||||
"key_id" int,
|
||||
"color_id" int,
|
||||
"image_id" int,
|
||||
"djComment" varchar,
|
||||
"rating" int,
|
||||
"releaseYear" int,
|
||||
"releaseDate" varchar,
|
||||
"dateAdded" varchar,
|
||||
"dateCreated" varchar,
|
||||
"path" varchar,
|
||||
"fileName" varchar,
|
||||
"fileSize" int,
|
||||
"fileType" int,
|
||||
"bitrate" int,
|
||||
"bitDepth" int,
|
||||
"samplingRate" int,
|
||||
"isrc" varchar,
|
||||
"djPlayCount" int,
|
||||
"isHotCueAutoLoadOn" int,
|
||||
"isKuvoDeliverStatusOn" int,
|
||||
"kuvoDeliveryComment" varchar,
|
||||
"masterDbId" int not null,
|
||||
"masterContentId" int not null,
|
||||
"analysisDataFilePath" varchar,
|
||||
"analysedBits" int,
|
||||
"contentLink" int,
|
||||
"hasModified" int,
|
||||
"cueUpdateCount" int,
|
||||
"analysisDataUpdateCount" int,
|
||||
"informationUpdateCount" int
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "genre" (
|
||||
"genre_id" integer primary key not null,
|
||||
"name" varchar
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "artist" (
|
||||
"artist_id" integer primary key not null,
|
||||
"name" varchar,
|
||||
"nameForSearch" varchar
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "album" (
|
||||
"album_id" integer primary key not null,
|
||||
"name" varchar not null,
|
||||
"artist_id" int,
|
||||
"image_id" int,
|
||||
"isComplation" int,
|
||||
"nameForSearch" varchar
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "label" (
|
||||
"label_id" integer primary key not null,
|
||||
"name" varchar
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "key" (
|
||||
"key_id" integer primary key not null,
|
||||
"name" varchar
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "color" (
|
||||
"color_id" integer primary key not null,
|
||||
"name" varchar
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "playlist" (
|
||||
"playlist_id" integer primary key not null,
|
||||
"sequenceNo" int,
|
||||
"name" varchar,
|
||||
"image_id" int,
|
||||
"attribute" int,
|
||||
"playlist_id_parent" int
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "playlist_content" (
|
||||
"playlist_id" int not null,
|
||||
"content_id" int not null,
|
||||
"sequenceNo" int not null
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "history" (
|
||||
"history_id" integer primary key not null,
|
||||
"sequenceNo" int,
|
||||
"name" varchar,
|
||||
"attribute" int,
|
||||
"history_id_parent" int
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "history_content" (
|
||||
"history_id" int,
|
||||
"content_id" int,
|
||||
"sequenceNo" int
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "image" (
|
||||
"image_id" integer primary key not null,
|
||||
"path" varchar
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "menuItem" (
|
||||
"menuItem_id" integer primary key not null,
|
||||
"kind" int,
|
||||
"name" varchar
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "category" (
|
||||
"category_id" integer primary key not null,
|
||||
"menuItem_id" int,
|
||||
"sequenceNo" int,
|
||||
"isVisible" int
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "sort" (
|
||||
"sort_id" integer primary key not null,
|
||||
"menuItem_id" int,
|
||||
"sequenceNo" int,
|
||||
"isVisible" int,
|
||||
"isSelectedAsSubColumn" int
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "property" (
|
||||
"deviceName" varchar,
|
||||
"dbVersion" varchar,
|
||||
"numberOfContents" int,
|
||||
"createdDate" varchar,
|
||||
"backGroundColorType" int,
|
||||
"myTagMasterDBID" int
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "hotCueBankList" (
|
||||
"hotCueBankList_id" integer primary key not null,
|
||||
"sequenceNo" int,
|
||||
"name" varchar,
|
||||
"image_id" int,
|
||||
"attribute" int,
|
||||
"hotCueBankList_id_parent" int
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "hotCueBankList_cue" (
|
||||
"hotCueBankList_id" int not null,
|
||||
"cue_id" int not null,
|
||||
"sequenceNo" int not null
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "cue" (
|
||||
"cue_id" integer primary key not null,
|
||||
"content_id" int not null,
|
||||
"kind" int not null,
|
||||
"colorTableIndex" int,
|
||||
"cueComment" varchar,
|
||||
"isActiveLoop" int not null,
|
||||
"beatLoopNumerator" int,
|
||||
"beatLoopDenominator" int,
|
||||
"inUsec" int not null,
|
||||
"outUsec" int,
|
||||
"in150FramePerSec" int not null,
|
||||
"out150FramePerSec" int,
|
||||
"inMpegFrameNumber" int,
|
||||
"outMpegFrameNumber" int,
|
||||
"inMpegAbs" int,
|
||||
"outMpegAbs" int,
|
||||
"inDecodingStartFramePosition" int,
|
||||
"outDecodingStartFramePosition" int,
|
||||
"inFileOffsetInBlock" int,
|
||||
"outFileOffsetInBlock" int,
|
||||
"inNumberOfSampleInBlock" int,
|
||||
"outNumberOfSampleInBlock" int
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "recommendedLike" (
|
||||
"content_id_1" int not null,
|
||||
"content_id_2" int not null,
|
||||
"rating" int,
|
||||
"createdDate" datetime
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "myTag" (
|
||||
"myTag_id" integer primary key not null,
|
||||
"sequenceNo" int,
|
||||
"name" varchar,
|
||||
"attribute" int,
|
||||
"myTag_id_parent" int
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "myTag_content" (
|
||||
"myTag_id" int not null,
|
||||
"content_id" int not null
|
||||
);
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
-- rekordbox's own scaffolding rows for a OneLibrary drive: the browse menu
|
||||
-- items, the categories and sort columns a player offers, and the colour
|
||||
-- palette. Extracted verbatim from fixtures/onelibrary/PIONEER/rekordbox/
|
||||
-- exportLibrary.db (a real rekordbox 7.2.18 export). No user data, no
|
||||
-- machine identity. rekordbox writes these on every export, so a drive without
|
||||
-- them is not a shape any player has been tested against.
|
||||
|
||||
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (1, 128, 'GENRE');
|
||||
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (2, 129, 'ARTIST');
|
||||
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (3, 130, 'ALBUM');
|
||||
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (4, 131, 'TRACK');
|
||||
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (5, 133, 'BPM');
|
||||
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (6, 134, 'RATING');
|
||||
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (7, 135, 'YEAR');
|
||||
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (8, 136, 'REMIXER');
|
||||
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (9, 137, 'LABEL');
|
||||
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (10, 138, 'ORIGINAL ARTIST');
|
||||
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (11, 139, 'KEY');
|
||||
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (12, 141, 'CUE');
|
||||
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (13, 142, 'COLOR');
|
||||
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (14, 146, 'TIME');
|
||||
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (15, 147, 'BITRATE');
|
||||
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (16, 148, 'FILE NAME');
|
||||
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (17, 132, 'PLAYLIST');
|
||||
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (18, 152, 'HOT CUE BANK');
|
||||
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (19, 149, 'HISTORY');
|
||||
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (20, 145, 'SEARCH');
|
||||
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (21, 150, 'COMMENTS');
|
||||
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (22, 140, 'DATE ADDED');
|
||||
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (23, 151, 'DJ PLAY COUNT');
|
||||
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (24, 144, 'FOLDER');
|
||||
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (25, 161, 'DEFAULT');
|
||||
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (26, 162, 'ALPHABET');
|
||||
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (27, 170, 'MATCHING');
|
||||
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (1, 1, 0, 0);
|
||||
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (2, 2, 1, 1);
|
||||
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (3, 3, 2, 1);
|
||||
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (4, 4, 3, 1);
|
||||
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (5, 17, 5, 1);
|
||||
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (6, 5, 0, 0);
|
||||
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (7, 6, 0, 0);
|
||||
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (8, 7, 0, 0);
|
||||
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (9, 8, 0, 0);
|
||||
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (10, 9, 0, 0);
|
||||
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (11, 10, 0, 0);
|
||||
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (12, 11, 4, 1);
|
||||
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (15, 13, 0, 0);
|
||||
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (17, 24, 9, 1);
|
||||
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (18, 20, 7, 1);
|
||||
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (19, 14, 0, 0);
|
||||
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (20, 15, 0, 0);
|
||||
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (21, 16, 0, 0);
|
||||
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (22, 19, 6, 1);
|
||||
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (23, 18, 0, 0);
|
||||
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (26, 27, 8, 1);
|
||||
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (27, 22, 10, 1);
|
||||
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (0, 25, 1, 1, 0);
|
||||
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (1, 26, 2, 1, 0);
|
||||
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (2, 2, 3, 1, 0);
|
||||
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (3, 3, 4, 1, 0);
|
||||
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (4, 5, 5, 1, 0);
|
||||
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (5, 6, 6, 1, 0);
|
||||
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (6, 1, 0, 0, 0);
|
||||
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (7, 21, 0, 0, 0);
|
||||
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (8, 14, 0, 0, 0);
|
||||
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (9, 8, 0, 0, 0);
|
||||
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (10, 9, 0, 0, 0);
|
||||
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (11, 10, 0, 0, 0);
|
||||
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (12, 11, 7, 1, 0);
|
||||
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (13, 15, 0, 0, 0);
|
||||
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (15, 13, 0, 0, 0);
|
||||
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (16, 23, 0, 0, 0);
|
||||
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (17, 22, 0, 0, 0);
|
||||
INSERT INTO "color" ("color_id", "name") VALUES (1, 'Pink');
|
||||
INSERT INTO "color" ("color_id", "name") VALUES (2, 'Red');
|
||||
INSERT INTO "color" ("color_id", "name") VALUES (3, 'Orange');
|
||||
INSERT INTO "color" ("color_id", "name") VALUES (4, 'Yellow');
|
||||
INSERT INTO "color" ("color_id", "name") VALUES (5, 'Green');
|
||||
INSERT INTO "color" ("color_id", "name") VALUES (6, 'Aqua');
|
||||
INSERT INTO "color" ("color_id", "name") VALUES (7, 'Blue');
|
||||
INSERT INTO "color" ("color_id", "name") VALUES (8, 'Purple');
|
||||
@@ -0,0 +1,20 @@
|
||||
# `master.db` schema
|
||||
|
||||
`schema.sql` is the DDL of a real Rekordbox 7 library — 47 tables and 288
|
||||
indexes — used by the Rekordbox **exporter** to create a database from nothing.
|
||||
|
||||
**It contains no user data.** Table and index definitions only, extracted with
|
||||
`SELECT sql FROM sqlite_master`.
|
||||
|
||||
## Why this, and not pyrekordbox's models
|
||||
|
||||
`Base.metadata.create_all()` looked like the obvious way to build the schema, and
|
||||
it is wrong in two ways that matter:
|
||||
|
||||
- it models **37 tables**, not 47;
|
||||
- it marks columns **NOT NULL that Rekordbox leaves nullable**. `agentRegistry
|
||||
.id_1` is the one that caught it: a real library has NULL there, and a database
|
||||
built from the ORM refuses the row Rekordbox itself writes.
|
||||
|
||||
So the DDL is the authority and the models are not. Regenerate with the snippet
|
||||
in the export handoff if a future Rekordbox version changes the schema.
|
||||
@@ -0,0 +1,20 @@
|
||||
# Empty rekordbox device library (`export.pdb`, `exportExt.pdb`)
|
||||
|
||||
The legacy "Device Library" a Pioneer USB stick carries — the one Rekordbox
|
||||
lists as **Device Library** and older players (CDJ-2000NXS2, many XDJs) read —
|
||||
exactly as **Rekordbox 7.2.18 wrote it for an empty stick**: it creates both
|
||||
files the first time it mounts a drive that has none.
|
||||
|
||||
They are the starting point of the "Rekordbox Export" target
|
||||
(`adapters/rekordbox/device_export.py`), for the same reason `seed.sql` exists:
|
||||
the format has fixed tables that are the same on every stick and cannot be
|
||||
derived — the colour list (table 6), the browse columns (16), two menu tables
|
||||
(17, 18) and a history header (19) in `export.pdb`; rekordbox's default MyTag
|
||||
names in `exportExt.pdb`. Every data table (tracks, artists, albums, genres,
|
||||
labels, keys, playlists, artwork) holds only its header page, with a blank page
|
||||
reserved after it for its first rows — the allocation rule the writer follows.
|
||||
|
||||
**No user data**: the only strings are colour names, column names, the default
|
||||
MyTag names, the creation date (`2026-09-27`, rewritten on every export) and the
|
||||
database version `1000`. Pages 13-14 and 33-38 are byte-identical to the same
|
||||
pages of a real rekordbox device export of eight tracks.
|
||||
Executable
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -0,0 +1,62 @@
|
||||
{
|
||||
"note": "Rows from a real rekordbox 7.2.18 device export (export.pdb), for byte-level tests. Only the Loopmasters demo tracks and generic key names; see README.md. The track row's u3/u4 (the exporting computer's rekordbox masterDbId) are zeroed.",
|
||||
"track_row_demo_track_2": "2400200000070c0044ac000000000000f6304e0011a8a6040000000000000000000000000000000001000000000000004001000000000000e02e000000000000000000000100000002000000000000000000100080002900000001000300880089008a008c008e00910092009500980099009a00a500a600a700a800d400df00fd000a010b011c0103030531053107313103074f4e074f4e030317323031382d30352d3235030303592f50494f4e4545522f555342414e4c5a2f503035332f30303031443231462f414e4c5a303030302e44415417323032362d30392d31373d547261636b73206279207777772e6c6f6f706d6173746572732e636f6d1b44656d6f20547261636b2032032344656d6f20547261636b20322e6d7033692f436f6e74656e74732f4c6f6f706d6173746572732f556e6b6e6f776e416c62756d2f44656d6f20547261636b20322e6d7033",
|
||||
"track_row_demo_track_2_fields": {
|
||||
"subtype": 36,
|
||||
"index_shift": 32,
|
||||
"bitmask": 788224,
|
||||
"sample_rate": 44100,
|
||||
"composer_id": 0,
|
||||
"file_size": 5124342,
|
||||
"u2": 78030865,
|
||||
"u3": 0,
|
||||
"u4": 0,
|
||||
"artwork_id": 0,
|
||||
"key_id": 0,
|
||||
"original_artist_id": 0,
|
||||
"label_id": 1,
|
||||
"remixer_id": 0,
|
||||
"bitrate": 320,
|
||||
"track_number": 0,
|
||||
"tempo": 12000,
|
||||
"genre_id": 0,
|
||||
"album_id": 0,
|
||||
"artist_id": 1,
|
||||
"id": 2,
|
||||
"disc_number": 0,
|
||||
"play_count": 0,
|
||||
"year": 0,
|
||||
"sample_depth": 16,
|
||||
"duration": 128,
|
||||
"u5": 41,
|
||||
"color_id": 0,
|
||||
"rating": 0,
|
||||
"u6": 1,
|
||||
"u7": 3,
|
||||
"isrc": "",
|
||||
"texter": "",
|
||||
"unknown_string_2": "1",
|
||||
"unknown_string_3": "1",
|
||||
"unknown_string_4": "11",
|
||||
"message": "",
|
||||
"kuvo_public": "ON",
|
||||
"autoload_hotcues": "ON",
|
||||
"unknown_string_5": "",
|
||||
"unknown_string_6": "",
|
||||
"date_added": "2018-05-25",
|
||||
"release_date": "",
|
||||
"mix_name": "",
|
||||
"unknown_string_7": "",
|
||||
"analyze_path": "/PIONEER/USBANLZ/P053/0001D21F/ANLZ0000.DAT",
|
||||
"analyze_date": "2026-09-17",
|
||||
"comment": "Tracks by www.loopmasters.com",
|
||||
"title": "Demo Track 2",
|
||||
"unknown_string_8": "",
|
||||
"filename": "Demo Track 2.mp3",
|
||||
"file_path": "/Contents/Loopmasters/UnknownAlbum/Demo Track 2.mp3"
|
||||
},
|
||||
"artist_row_loopmasters": "6000000001000000030a194c6f6f706d617374657273000000000000",
|
||||
"playlist_row_demos": "00000000000000000100000001000000000000000d64656d6f730000",
|
||||
"keys_page_index": 12,
|
||||
"keys_page": "000000000c0000000500000034000000140000000000000002400024b80f1800010001000000000001000000010000000941626d020000000200000007456d0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000Line truncated
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
-- master.db schema, extracted from a real Rekordbox 7 library.
|
||||
--
|
||||
-- NOT generated from pyrekordbox's SQLAlchemy models: `create_all()` marks
|
||||
-- columns NOT NULL that Rekordbox itself leaves nullable (agentRegistry.id_1
|
||||
-- is the one that caught this), so a database built from the ORM rejects rows
|
||||
-- Rekordbox writes every day. The DDL is the authority; the models are not.
|
||||
--
|
||||
-- Contains no user data — table and index definitions only.
|
||||
|
||||
CREATE TABLE `agentNotification` (`ID` BIGINT PRIMARY KEY, `graphic_area` TINYINT(1) DEFAULT 0, `text_area` TINYINT(1) DEFAULT 0, `os_notification` TINYINT(1) DEFAULT 0, `start_datetime` DATETIME DEFAULT NULL, `end_datetime` DATETIME DEFAULT NULL, `display_datetime` DATETIME DEFAULT NULL, `interval` INTEGER DEFAULT 0, `category` VARCHAR(255) DEFAULT NULL, `category_color` VARCHAR(255) DEFAULT NULL, `title` TEXT DEFAULT NULL, `description` TEXT DEFAULT NULL, `url` VARCHAR(255) DEFAULT NULL, `image` VARCHAR(255) DEFAULT NULL, `image_path` VARCHAR(255) DEFAULT NULL, `read_status` INTEGER DEFAULT 0, `last_displayed_datetime` DATETIME DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `agentNotificationLog` (`ID` INTEGER PRIMARY KEY AUTOINCREMENT, `gigya_uid` VARCHAR(255) DEFAULT NULL, `event_date` INTEGER DEFAULT NULL, `reported_datetime` DATETIME DEFAULT NULL, `kind` INTEGER DEFAULT NULL, `value` INTEGER DEFAULT NULL, `notification_id` BIGINT DEFAULT NULL, `link` VARCHAR(255) DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `agentRegistry` (`registry_id` VARCHAR(255) PRIMARY KEY, `id_1` VARCHAR(255) DEFAULT NULL, `id_2` VARCHAR(255) DEFAULT NULL, `int_1` BIGINT DEFAULT NULL, `int_2` BIGINT DEFAULT NULL, `str_1` VARCHAR(255) DEFAULT NULL, `str_2` VARCHAR(255) DEFAULT NULL, `date_1` DATETIME DEFAULT NULL, `date_2` DATETIME DEFAULT NULL, `text_1` TEXT DEFAULT NULL, `text_2` TEXT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `cloudAgentRegistry` (`ID` VARCHAR(255) PRIMARY KEY, `int_1` BIGINT DEFAULT NULL, `int_2` BIGINT DEFAULT NULL, `str_1` VARCHAR(255) DEFAULT NULL, `str_2` VARCHAR(255) DEFAULT NULL, `date_1` DATETIME DEFAULT NULL, `date_2` DATETIME DEFAULT NULL, `text_1` TEXT DEFAULT NULL, `text_2` TEXT DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `contentActiveCensor` (`ID` VARCHAR(255) PRIMARY KEY, `ContentID` VARCHAR(255) DEFAULT NULL, `ActiveCensors` TEXT DEFAULT NULL, `rb_activecensor_count` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `contentCue` (`ID` VARCHAR(255) PRIMARY KEY, `ContentID` VARCHAR(255) DEFAULT NULL, `Cues` TEXT DEFAULT NULL, `rb_cue_count` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `contentFile` (`ID` VARCHAR(255) PRIMARY KEY, `ContentID` VARCHAR(255) DEFAULT NULL, `Path` VARCHAR(255) DEFAULT NULL, `Hash` VARCHAR(255) DEFAULT NULL, `Size` INTEGER DEFAULT NULL, `rb_local_path` VARCHAR(255) DEFAULT NULL, `rb_insync_hash` VARCHAR(255) DEFAULT NULL, `rb_insync_local_usn` BIGINT DEFAULT NULL, `rb_file_hash_dirty` INTEGER DEFAULT 0, `rb_local_file_status` INTEGER DEFAULT 0, `rb_in_progress` TINYINT(1) DEFAULT 0, `rb_process_type` INTEGER DEFAULT 0, `rb_temp_path` VARCHAR(255) DEFAULT NULL, `rb_priority` INTEGER DEFAULT 50, `rb_file_size_dirty` INTEGER DEFAULT 0, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdActiveCensor` (`ID` VARCHAR(255) PRIMARY KEY, `ContentID` VARCHAR(255) DEFAULT NULL, `InMsec` INTEGER DEFAULT NULL, `OutMsec` INTEGER DEFAULT NULL, `Info` INTEGER DEFAULT NULL, `ParameterList` TEXT DEFAULT NULL, `ContentUUID` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdAlbum` (`ID` VARCHAR(255) PRIMARY KEY, `Name` VARCHAR(255) DEFAULT NULL, `AlbumArtistID` VARCHAR(255) DEFAULT NULL, `ImagePath` VARCHAR(255) DEFAULT NULL, `Compilation` INTEGER DEFAULT NULL, `SearchStr` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdArtist` (`ID` VARCHAR(255) PRIMARY KEY, `Name` VARCHAR(255) DEFAULT NULL, `SearchStr` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdCategory` (`ID` VARCHAR(255) PRIMARY KEY, `MenuItemID` VARCHAR(255) DEFAULT NULL, `Seq` INTEGER DEFAULT NULL, `Disable` INTEGER DEFAULT NULL, `InfoOrder` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdCloudExportPlaylist` (`ID` VARCHAR(255) PRIMARY KEY, `Seq` INTEGER DEFAULT NULL, `Name` VARCHAR(255) DEFAULT NULL, `ImagePath` VARCHAR(255) DEFAULT NULL, `Attribute` INTEGER DEFAULT NULL, `ParentID` VARCHAR(255) DEFAULT NULL, `SmartList` TEXT DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdCloudExportSongPlaylist` (`ID` VARCHAR(255) PRIMARY KEY, `CloudExportPlaylistID` VARCHAR(255) DEFAULT NULL, `ContentID` VARCHAR(255) DEFAULT NULL, `TrackNo` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdCloudFilterPlaylist` (`ID` VARCHAR(255) PRIMARY KEY, `PlaylistUUID` VARCHAR(255) DEFAULT NULL, `Seq` INTEGER DEFAULT 0, `ParentID` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdCloudProperty` (`ID` VARCHAR(255) PRIMARY KEY, `Reserved1` TEXT DEFAULT NULL, `Reserved2` TEXT DEFAULT NULL, `Reserved3` TEXT DEFAULT NULL, `Reserved4` TEXT DEFAULT NULL, `Reserved5` TEXT DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdColor` (`ID` VARCHAR(255) PRIMARY KEY, `ColorCode` INTEGER DEFAULT NULL, `SortKey` INTEGER DEFAULT NULL, `Commnt` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdContent` (`ID` VARCHAR(255) PRIMARY KEY, `FolderPath` VARCHAR(255) DEFAULT NULL, `FileNameL` VARCHAR(255) DEFAULT NULL, `FileNameS` VARCHAR(255) DEFAULT NULL, `Title` VARCHAR(255) DEFAULT NULL, `ArtistID` VARCHAR(255) DEFAULT NULL, `AlbumID` VARCHAR(255) DEFAULT NULL, `GenreID` VARCHAR(255) DEFAULT NULL, `BPM` INTEGER DEFAULT NULL, `Length` INTEGER DEFAULT NULL, `TrackNo` INTEGER DEFAULT NULL, `BitRate` INTEGER DEFAULT NULL, `BitDepth` INTEGER DEFAULT NULL, `Commnt` TEXT DEFAULT NULL, `FileType` INTEGER DEFAULT NULL, `Rating` INTEGER DEFAULT NULL, `ReleaseYear` INTEGER DEFAULT NULL, `RemixerID` VARCHAR(255) DEFAULT NULL, `LabelID` VARCHAR(255) DEFAULT NULL, `OrgArtistID` VARCHAR(255) DEFAULT NULL, `KeyID` VARCHAR(255) DEFAULT NULL, `StockDate` VARCHAR(255) DEFAULT NULL, `ColorID` VARCHAR(255) DEFAULT NULL, `DJPlayCount` INTEGER DEFAULT NULL, `ImagePath` VARCHAR(255) DEFAULT NULL, `MasterDBID` VARCHAR(255) DEFAULT NULL, `MasterSongID` VARCHAR(255) DEFAULT NULL, `AnalysisDataPath` VARCHAR(255) DEFAULT NULL, `SearchStr` VARCHAR(255) DEFAULT NULL, `FileSize` INTEGER DEFAULT NULL, `DiscNo` INTEGER DEFAULT NULL, `ComposerID` VARCHAR(255) DEFAULT NULL, `Subtitle` VARCHAR(255) DEFAULT NULL, `SampleRate` INTEGER DEFAULT NULL, `DisableQuantize` INTEGER DEFAULT NULL, `Analysed` INTEGER DEFAULT NULL, `ReleaseDate` VARCHAR(255) DEFAULT NULL, `DateCreated` VARCHAR(255) DEFAULT NULL, `ContentLink` INTEGER DEFAULT NULL, `Tag` VARCHAR(255) DEFAULT NULL, `ModifiedByRBM` VARCHAR(255) DEFAULT NULL, `HotCueAutoLoad` VARCHAR(255) DEFAULT NULL, `DeliveryControl` VARCHAR(255) DEFAULT NULL, `DeliveryComment` VARCHAR(255) DEFAULT NULL, `CueUpdated` VARCHAR(255) DEFAULT NULL, `AnalysisUpdated` VARCHAR(255) DEFAULT NULL, `TrackInfoUpdated` VARCHAR(255) DEFAULT NULL, `Lyricist` VARCHAR(255) DEFAULT NULL, `ISRC` VARCHAR(255) DEFAULT NULL, `SamplerTrackInfo` INTEGER DEFAULT NULL, `SamplerPlayOffset` INTEGER DEFAULT NULL, `SamplerGain` FLOAT DEFAULT NULL, `VideoAssociate` VARCHAR(255) DEFAULT NULL, `LyricStatus` INTEGER DEFAULT NULL, `ServiceID` INTEGER DEFAULT NULL, `OrgFolderPath` VARCHAR(255) DEFAULT NULL, `Reserved1` TEXT DEFAULT NULL, `Reserved2` TEXT DEFAULT NULL, `Reserved3` TEXT DEFAULT NULL, `Reserved4` TEXT DEFAULT NULL, `ExtInfo` TEXT DEFAULT NULL, `rb_file_id` VARCHAR(255) DEFAULT NULL, `DeviceID` VARCHAR(255) DEFAULT NULL, `rb_LocalFolderPath` VARCHAR(255) DEFAULT NULL, `SrcID` VARCHAR(255) DEFAULT NULL, `SrcTitle` VARCHAR(255) DEFAULT NULL, `SrcArtistName` VARCHAR(255) DEFAULT NULL, `SrcAlbumName` VARCHAR(255) DEFAULT NULL, `SrcLength` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdCue` (`ID` VARCHAR(255) PRIMARY KEY, `ContentID` VARCHAR(255) DEFAULT NULL, `InMsec` INTEGER DEFAULT NULL, `InFrame` INTEGER DEFAULT NULL, `InMpegFrame` INTEGER DEFAULT NULL, `InMpegAbs` INTEGER DEFAULT NULL, `OutMsec` INTEGER DEFAULT NULL, `OutFrame` INTEGER DEFAULT NULL, `OutMpegFrame` INTEGER DEFAULT NULL, `OutMpegAbs` INTEGER DEFAULT NULL, `Kind` INTEGER DEFAULT NULL, `Color` INTEGER DEFAULT NULL, `ColorTableIndex` INTEGER DEFAULT NULL, `ActiveLoop` INTEGER DEFAULT NULL, `Comment` VARCHAR(255) DEFAULT NULL, `BeatLoopSize` INTEGER DEFAULT NULL, `CueMicrosec` INTEGER DEFAULT NULL, `InPointSeekInfo` VARCHAR(255) DEFAULT NULL, `OutPointSeekInfo` VARCHAR(255) DEFAULT NULL, `ContentUUID` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdDevice` (`ID` VARCHAR(255) PRIMARY KEY, `MasterDBID` VARCHAR(255) DEFAULT NULL, `Name` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdGenre` (`ID` VARCHAR(255) PRIMARY KEY, `Name` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdHistory` (`ID` VARCHAR(255) PRIMARY KEY, `Seq` INTEGER DEFAULT NULL, `Name` VARCHAR(255) DEFAULT NULL, `Attribute` INTEGER DEFAULT NULL, `ParentID` VARCHAR(255) DEFAULT NULL, `DateCreated` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdHotCueBanklist` (`ID` VARCHAR(255) PRIMARY KEY, `Seq` INTEGER DEFAULT NULL, `Name` VARCHAR(255) DEFAULT NULL, `ImagePath` VARCHAR(255) DEFAULT NULL, `Attribute` INTEGER DEFAULT NULL, `ParentID` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdKey` (`ID` VARCHAR(255) PRIMARY KEY, `ScaleName` VARCHAR(255) DEFAULT NULL, `Seq` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdLabel` (`ID` VARCHAR(255) PRIMARY KEY, `Name` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdMenuItems` (`ID` VARCHAR(255) PRIMARY KEY, `Class` INTEGER DEFAULT NULL, `Name` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdMixerParam` (`ID` VARCHAR(255) PRIMARY KEY, `ContentID` VARCHAR(255) DEFAULT NULL, `GainHigh` INTEGER DEFAULT NULL, `GainLow` INTEGER DEFAULT NULL, `PeakHigh` INTEGER DEFAULT NULL, `PeakLow` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdMyTag` (`ID` VARCHAR(255) PRIMARY KEY, `Seq` INTEGER DEFAULT NULL, `Name` VARCHAR(255) DEFAULT NULL, `Attribute` INTEGER DEFAULT NULL, `ParentID` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdPlaylist` (`ID` VARCHAR(255) PRIMARY KEY, `Seq` INTEGER DEFAULT NULL, `Name` VARCHAR(255) DEFAULT NULL, `ImagePath` VARCHAR(255) DEFAULT NULL, `Attribute` INTEGER DEFAULT NULL, `ParentID` VARCHAR(255) DEFAULT NULL, `SmartList` TEXT DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdProperty` (`DBID` VARCHAR(255) PRIMARY KEY, `DBVersion` VARCHAR(255) DEFAULT NULL, `BaseDBDrive` VARCHAR(255) DEFAULT NULL, `CurrentDBDrive` VARCHAR(255) DEFAULT NULL, `DeviceID` VARCHAR(255) DEFAULT NULL, `Reserved1` TEXT DEFAULT NULL, `Reserved2` TEXT DEFAULT NULL, `Reserved3` TEXT DEFAULT NULL, `Reserved4` TEXT DEFAULT NULL, `Reserved5` TEXT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdRecommendLike` (`ID` VARCHAR(255) PRIMARY KEY, `ContentID1` VARCHAR(255) DEFAULT NULL, `ContentID2` VARCHAR(255) DEFAULT NULL, `LikeRate` INTEGER DEFAULT NULL, `DataCreatedH` INTEGER DEFAULT NULL, `DataCreatedL` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdRelatedTracks` (`ID` VARCHAR(255) PRIMARY KEY, `Seq` INTEGER DEFAULT NULL, `Name` VARCHAR(255) DEFAULT NULL, `Attribute` INTEGER DEFAULT NULL, `ParentID` VARCHAR(255) DEFAULT NULL, `Criteria` TEXT DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdSampler` (`ID` VARCHAR(255) PRIMARY KEY, `Seq` INTEGER DEFAULT NULL, `Name` VARCHAR(255) DEFAULT NULL, `Attribute` INTEGER DEFAULT NULL, `ParentID` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdSharedPlaylist` (`ID` VARCHAR(255) PRIMARY KEY, `data_selection` TINYINT DEFAULT 0, `edited_at` DATETIME DEFAULT NULL, `int_1` INTEGER DEFAULT NULL, `int_2` INTEGER DEFAULT NULL, `str_1` VARCHAR(255) DEFAULT NULL, `str_2` VARCHAR(255) DEFAULT NULL, `text_1` TEXT DEFAULT NULL, `text_2` TEXT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdSharedPlaylistUser` (`ID` VARCHAR(255) NOT NULL, `member_type` TINYINT DEFAULT 0, `member_id` VARCHAR(255) NOT NULL, `status` TINYINT DEFAULT 0, `invitation_expires_at` DATETIME DEFAULT NULL, `invited_at` DATETIME DEFAULT NULL, `joined_at` DATETIME DEFAULT NULL, `int_1` INTEGER DEFAULT NULL, `int_2` INTEGER DEFAULT NULL, `str_1` VARCHAR(255) DEFAULT NULL, `str_2` VARCHAR(255) DEFAULT NULL, `text_1` TEXT DEFAULT NULL, `text_2` TEXT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL, PRIMARY KEY (`ID`, `member_id`));
|
||||
CREATE TABLE `djmdSongHistory` (`ID` VARCHAR(255) PRIMARY KEY, `HistoryID` VARCHAR(255) DEFAULT NULL, `ContentID` VARCHAR(255) DEFAULT NULL, `TrackNo` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdSongHotCueBanklist` (`ID` VARCHAR(255) PRIMARY KEY, `HotCueBanklistID` VARCHAR(255) DEFAULT NULL, `ContentID` VARCHAR(255) DEFAULT NULL, `TrackNo` INTEGER DEFAULT NULL, `CueID` VARCHAR(255) DEFAULT NULL, `InMsec` INTEGER DEFAULT NULL, `InFrame` INTEGER DEFAULT NULL, `InMpegFrame` INTEGER DEFAULT NULL, `InMpegAbs` INTEGER DEFAULT NULL, `OutMsec` INTEGER DEFAULT NULL, `OutFrame` INTEGER DEFAULT NULL, `OutMpegFrame` INTEGER DEFAULT NULL, `OutMpegAbs` INTEGER DEFAULT NULL, `Color` INTEGER DEFAULT NULL, `ColorTableIndex` INTEGER DEFAULT NULL, `ActiveLoop` INTEGER DEFAULT NULL, `Comment` VARCHAR(255) DEFAULT NULL, `BeatLoopSize` INTEGER DEFAULT NULL, `CueMicrosec` INTEGER DEFAULT NULL, `InPointSeekInfo` VARCHAR(255) DEFAULT NULL, `OutPointSeekInfo` VARCHAR(255) DEFAULT NULL, `HotCueBanklistUUID` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdSongMyTag` (`ID` VARCHAR(255) PRIMARY KEY, `MyTagID` VARCHAR(255) DEFAULT NULL, `ContentID` VARCHAR(255) DEFAULT NULL, `TrackNo` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdSongPlaylist` (`ID` VARCHAR(255) PRIMARY KEY, `PlaylistID` VARCHAR(255) DEFAULT NULL, `ContentID` VARCHAR(255) DEFAULT NULL, `TrackNo` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdSongRelatedTracks` (`ID` VARCHAR(255) PRIMARY KEY, `RelatedTracksID` VARCHAR(255) DEFAULT NULL, `ContentID` VARCHAR(255) DEFAULT NULL, `TrackNo` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdSongRequestList` (`ID` VARCHAR(255) PRIMARY KEY, `ContentID` VARCHAR(255) DEFAULT NULL, `TrackNo` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdSongSampler` (`ID` VARCHAR(255) PRIMARY KEY, `SamplerID` VARCHAR(255) DEFAULT NULL, `ContentID` VARCHAR(255) DEFAULT NULL, `TrackNo` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdSongTagList` (`ID` VARCHAR(255) PRIMARY KEY, `ContentID` VARCHAR(255) DEFAULT NULL, `TrackNo` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `djmdSort` (`ID` VARCHAR(255) PRIMARY KEY, `MenuItemID` VARCHAR(255) DEFAULT NULL, `Seq` INTEGER DEFAULT NULL, `Disable` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `hotCueBanklistCue` (`ID` VARCHAR(255) PRIMARY KEY, `HotCueBanklistID` VARCHAR(255) DEFAULT NULL, `Cues` TEXT DEFAULT NULL, `rb_cue_count` INTEGER DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `imageFile` (`ID` VARCHAR(255) PRIMARY KEY, `TableName` VARCHAR(255) DEFAULT NULL, `TargetUUID` VARCHAR(255) DEFAULT NULL, `TargetID` VARCHAR(255) DEFAULT NULL, `Path` VARCHAR(255) DEFAULT NULL, `Hash` VARCHAR(255) DEFAULT NULL, `Size` INTEGER DEFAULT NULL, `rb_local_path` VARCHAR(255) DEFAULT NULL, `rb_insync_hash` VARCHAR(255) DEFAULT NULL, `rb_insync_local_usn` BIGINT DEFAULT NULL, `rb_file_hash_dirty` INTEGER DEFAULT 0, `rb_local_file_status` INTEGER DEFAULT 0, `rb_in_progress` TINYINT(1) DEFAULT 0, `rb_process_type` INTEGER DEFAULT 0, `rb_temp_path` VARCHAR(255) DEFAULT NULL, `rb_priority` INTEGER DEFAULT 50, `rb_file_size_dirty` INTEGER DEFAULT 0, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `settingFile` (`ID` VARCHAR(255) PRIMARY KEY, `Path` VARCHAR(255) DEFAULT NULL, `Hash` VARCHAR(255) DEFAULT NULL, `Size` INTEGER DEFAULT NULL, `rb_local_path` VARCHAR(255) DEFAULT NULL, `rb_insync_hash` VARCHAR(255) DEFAULT NULL, `rb_insync_local_usn` BIGINT DEFAULT NULL, `rb_file_hash_dirty` INTEGER DEFAULT 0, `rb_file_size_dirty` INTEGER DEFAULT 0, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE TABLE `uuidIDMap` (`ID` VARCHAR(255) PRIMARY KEY, `TableName` VARCHAR(255) DEFAULT NULL, `TargetUUID` VARCHAR(255) DEFAULT NULL, `CurrentID` VARCHAR(255) DEFAULT NULL, `UUID` VARCHAR(255) DEFAULT NULL, `rb_data_status` INTEGER DEFAULT 0, `rb_local_data_status` INTEGER DEFAULT 0, `rb_local_deleted` TINYINT(1) DEFAULT 0, `rb_local_synced` TINYINT(1) DEFAULT 0, `usn` BIGINT DEFAULT NULL, `rb_local_usn` BIGINT DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
|
||||
CREATE INDEX `agent_notification_log_gigya_uid_event_date_kind_notification_id` ON `agentNotificationLog` (`gigya_uid`, `event_date`, `kind`, `notification_id`);
|
||||
CREATE INDEX `agent_notification_log_reported_datetime_event_date` ON `agentNotificationLog` (`reported_datetime`, `event_date`);
|
||||
CREATE INDEX `agent_notification_start_datetime_end_datetime` ON `agentNotification` (`start_datetime`, `end_datetime`);
|
||||
CREATE INDEX `agent_registry_id_1_id_2` ON `agentRegistry` (`id_1`, `id_2`);
|
||||
CREATE INDEX `cloud_agent_registry__u_u_i_d` ON `cloudAgentRegistry` (`UUID`);
|
||||
CREATE INDEX `cloud_agent_registry_rb_data_status` ON `cloudAgentRegistry` (`rb_data_status`);
|
||||
CREATE INDEX `cloud_agent_registry_rb_local_data_status` ON `cloudAgentRegistry` (`rb_local_data_status`);
|
||||
CREATE INDEX `cloud_agent_registry_rb_local_deleted` ON `cloudAgentRegistry` (`rb_local_deleted`);
|
||||
CREATE INDEX `cloud_agent_registry_rb_local_usn__i_d` ON `cloudAgentRegistry` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `content_active_censor__content_i_d` ON `contentActiveCensor` (`ContentID`);
|
||||
CREATE INDEX `content_active_censor__u_u_i_d` ON `contentActiveCensor` (`UUID`);
|
||||
CREATE INDEX `content_active_censor_rb_data_status` ON `contentActiveCensor` (`rb_data_status`);
|
||||
CREATE INDEX `content_active_censor_rb_local_data_status` ON `contentActiveCensor` (`rb_local_data_status`);
|
||||
CREATE INDEX `content_active_censor_rb_local_deleted` ON `contentActiveCensor` (`rb_local_deleted`);
|
||||
CREATE INDEX `content_active_censor_rb_local_usn__i_d` ON `contentActiveCensor` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `content_cue__content_i_d` ON `contentCue` (`ContentID`);
|
||||
CREATE INDEX `content_cue__u_u_i_d` ON `contentCue` (`UUID`);
|
||||
CREATE INDEX `content_cue_rb_cue_count` ON `contentCue` (`rb_cue_count`);
|
||||
CREATE INDEX `content_cue_rb_data_status` ON `contentCue` (`rb_data_status`);
|
||||
CREATE INDEX `content_cue_rb_local_data_status` ON `contentCue` (`rb_local_data_status`);
|
||||
CREATE INDEX `content_cue_rb_local_deleted` ON `contentCue` (`rb_local_deleted`);
|
||||
CREATE INDEX `content_cue_rb_local_usn__i_d` ON `contentCue` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `content_file__content_i_d` ON `contentFile` (`ContentID`);
|
||||
CREATE INDEX `content_file__u_u_i_d` ON `contentFile` (`UUID`);
|
||||
CREATE INDEX `content_file_rb_data_status` ON `contentFile` (`rb_data_status`);
|
||||
CREATE INDEX `content_file_rb_file_hash_dirty` ON `contentFile` (`rb_file_hash_dirty`);
|
||||
CREATE INDEX `content_file_rb_file_size_dirty` ON `contentFile` (`rb_file_size_dirty`);
|
||||
CREATE INDEX `content_file_rb_local_data_status` ON `contentFile` (`rb_local_data_status`);
|
||||
CREATE INDEX `content_file_rb_local_deleted` ON `contentFile` (`rb_local_deleted`);
|
||||
CREATE INDEX `content_file_rb_local_deleted_rb_in_progress_rb_local_file_status_rb_process_type_rb_priority` ON `contentFile` (`rb_local_deleted`, `rb_in_progress`, `rb_local_file_status`, `rb_process_type`, `rb_priority`);
|
||||
CREATE INDEX `content_file_rb_local_usn__i_d` ON `contentFile` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_active_censor__content_i_d` ON `djmdActiveCensor` (`ContentID`);
|
||||
CREATE INDEX `djmd_active_censor__content_u_u_i_d` ON `djmdActiveCensor` (`ContentUUID`);
|
||||
CREATE INDEX `djmd_active_censor__u_u_i_d` ON `djmdActiveCensor` (`UUID`);
|
||||
CREATE INDEX `djmd_active_censor_rb_data_status` ON `djmdActiveCensor` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_active_censor_rb_local_data_status` ON `djmdActiveCensor` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_active_censor_rb_local_deleted` ON `djmdActiveCensor` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_active_censor_rb_local_usn__i_d` ON `djmdActiveCensor` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_album__album_artist_i_d` ON `djmdAlbum` (`AlbumArtistID`);
|
||||
CREATE INDEX `djmd_album__name` ON `djmdAlbum` (`Name`);
|
||||
CREATE INDEX `djmd_album__u_u_i_d` ON `djmdAlbum` (`UUID`);
|
||||
CREATE INDEX `djmd_album_rb_data_status` ON `djmdAlbum` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_album_rb_local_data_status` ON `djmdAlbum` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_album_rb_local_deleted` ON `djmdAlbum` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_album_rb_local_usn__i_d` ON `djmdAlbum` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_artist__name` ON `djmdArtist` (`Name`);
|
||||
CREATE INDEX `djmd_artist__u_u_i_d` ON `djmdArtist` (`UUID`);
|
||||
CREATE INDEX `djmd_artist_rb_data_status` ON `djmdArtist` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_artist_rb_local_data_status` ON `djmdArtist` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_artist_rb_local_deleted` ON `djmdArtist` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_artist_rb_local_usn__i_d` ON `djmdArtist` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_category__u_u_i_d` ON `djmdCategory` (`UUID`);
|
||||
CREATE INDEX `djmd_category_rb_data_status` ON `djmdCategory` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_category_rb_local_data_status` ON `djmdCategory` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_category_rb_local_deleted` ON `djmdCategory` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_category_rb_local_usn__i_d` ON `djmdCategory` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_cloud_export_playlist__attribute` ON `djmdCloudExportPlaylist` (`Attribute`);
|
||||
CREATE INDEX `djmd_cloud_export_playlist__name` ON `djmdCloudExportPlaylist` (`Name`);
|
||||
CREATE INDEX `djmd_cloud_export_playlist__parent_i_d` ON `djmdCloudExportPlaylist` (`ParentID`);
|
||||
CREATE INDEX `djmd_cloud_export_playlist__seq` ON `djmdCloudExportPlaylist` (`Seq`);
|
||||
CREATE INDEX `djmd_cloud_export_playlist__u_u_i_d` ON `djmdCloudExportPlaylist` (`UUID`);
|
||||
CREATE INDEX `djmd_cloud_export_playlist_rb_data_status` ON `djmdCloudExportPlaylist` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_cloud_export_playlist_rb_local_data_status` ON `djmdCloudExportPlaylist` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_cloud_export_playlist_rb_local_deleted` ON `djmdCloudExportPlaylist` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_cloud_export_playlist_rb_local_usn__i_d` ON `djmdCloudExportPlaylist` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_cloud_export_song_playlist__cloud_export_playlist_i_d__i_d` ON `djmdCloudExportSongPlaylist` (`CloudExportPlaylistID`, `ID`);
|
||||
CREATE INDEX `djmd_cloud_export_song_playlist__content_i_d_rb_local_deleted` ON `djmdCloudExportSongPlaylist` (`ContentID`, `rb_local_deleted`);
|
||||
CREATE INDEX `djmd_cloud_export_song_playlist__u_u_i_d` ON `djmdCloudExportSongPlaylist` (`UUID`);
|
||||
CREATE INDEX `djmd_cloud_export_song_playlist_rb_data_status` ON `djmdCloudExportSongPlaylist` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_cloud_export_song_playlist_rb_local_data_status` ON `djmdCloudExportSongPlaylist` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_cloud_export_song_playlist_rb_local_deleted` ON `djmdCloudExportSongPlaylist` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_cloud_export_song_playlist_rb_local_usn__i_d` ON `djmdCloudExportSongPlaylist` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_cloud_filter_playlist__u_u_i_d` ON `djmdCloudFilterPlaylist` (`UUID`);
|
||||
CREATE INDEX `djmd_cloud_filter_playlist_rb_data_status` ON `djmdCloudFilterPlaylist` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_cloud_filter_playlist_rb_local_data_status` ON `djmdCloudFilterPlaylist` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_cloud_filter_playlist_rb_local_deleted` ON `djmdCloudFilterPlaylist` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_cloud_filter_playlist_rb_local_usn__i_d` ON `djmdCloudFilterPlaylist` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_cloud_property__u_u_i_d` ON `djmdCloudProperty` (`UUID`);
|
||||
CREATE INDEX `djmd_cloud_property_rb_data_status` ON `djmdCloudProperty` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_cloud_property_rb_local_data_status` ON `djmdCloudProperty` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_cloud_property_rb_local_deleted` ON `djmdCloudProperty` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_cloud_property_rb_local_usn__i_d` ON `djmdCloudProperty` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_color__u_u_i_d` ON `djmdColor` (`UUID`);
|
||||
CREATE INDEX `djmd_color_rb_data_status` ON `djmdColor` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_color_rb_local_data_status` ON `djmdColor` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_color_rb_local_deleted` ON `djmdColor` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_color_rb_local_usn__i_d` ON `djmdColor` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_content__album_i_d` ON `djmdContent` (`AlbumID`);
|
||||
CREATE INDEX `djmd_content__artist_i_d` ON `djmdContent` (`ArtistID`);
|
||||
CREATE INDEX `djmd_content__composer_i_d` ON `djmdContent` (`ComposerID`);
|
||||
CREATE INDEX `djmd_content__genre_i_d` ON `djmdContent` (`GenreID`);
|
||||
CREATE INDEX `djmd_content__key_i_d` ON `djmdContent` (`KeyID`);
|
||||
CREATE INDEX `djmd_content__label_i_d` ON `djmdContent` (`LabelID`);
|
||||
CREATE INDEX `djmd_content__master_d_b_i_d__master_song_i_d` ON `djmdContent` (`MasterDBID`, `MasterSongID`);
|
||||
CREATE INDEX `djmd_content__org_artist_i_d` ON `djmdContent` (`OrgArtistID`);
|
||||
CREATE INDEX `djmd_content__remixer_i_d` ON `djmdContent` (`RemixerID`);
|
||||
CREATE INDEX `djmd_content__u_u_i_d` ON `djmdContent` (`UUID`);
|
||||
CREATE INDEX `djmd_content_rb_data_status` ON `djmdContent` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_content_rb_local_data_status` ON `djmdContent` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_content_rb_local_deleted` ON `djmdContent` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_content_rb_local_deleted__bit_depth` ON `djmdContent` (`rb_local_deleted`, `BitDepth`);
|
||||
CREATE INDEX `djmd_content_rb_local_deleted__bit_rate` ON `djmdContent` (`rb_local_deleted`, `BitRate`);
|
||||
CREATE INDEX `djmd_content_rb_local_deleted__file_type` ON `djmdContent` (`rb_local_deleted`, `FileType`);
|
||||
CREATE INDEX `djmd_content_rb_local_deleted__service_i_d` ON `djmdContent` (`rb_local_deleted`, `ServiceID`);
|
||||
CREATE INDEX `djmd_content_rb_local_usn__i_d` ON `djmdContent` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_cue__content_i_d_rb_local_deleted` ON `djmdCue` (`ContentID`, `rb_local_deleted`);
|
||||
CREATE INDEX `djmd_cue__content_u_u_i_d` ON `djmdCue` (`ContentUUID`);
|
||||
CREATE INDEX `djmd_cue__u_u_i_d` ON `djmdCue` (`UUID`);
|
||||
CREATE INDEX `djmd_cue_rb_data_status` ON `djmdCue` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_cue_rb_local_data_status` ON `djmdCue` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_cue_rb_local_deleted` ON `djmdCue` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_cue_rb_local_usn__i_d` ON `djmdCue` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_device__u_u_i_d` ON `djmdDevice` (`UUID`);
|
||||
CREATE INDEX `djmd_device_rb_data_status` ON `djmdDevice` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_device_rb_local_data_status` ON `djmdDevice` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_device_rb_local_deleted` ON `djmdDevice` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_device_rb_local_usn__i_d` ON `djmdDevice` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_genre__name` ON `djmdGenre` (`Name`);
|
||||
CREATE INDEX `djmd_genre__u_u_i_d` ON `djmdGenre` (`UUID`);
|
||||
CREATE INDEX `djmd_genre_rb_data_status` ON `djmdGenre` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_genre_rb_local_data_status` ON `djmdGenre` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_genre_rb_local_deleted` ON `djmdGenre` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_genre_rb_local_usn__i_d` ON `djmdGenre` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_history__name` ON `djmdHistory` (`Name`);
|
||||
CREATE INDEX `djmd_history__parent_i_d` ON `djmdHistory` (`ParentID`);
|
||||
CREATE INDEX `djmd_history__u_u_i_d` ON `djmdHistory` (`UUID`);
|
||||
CREATE INDEX `djmd_history_rb_data_status` ON `djmdHistory` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_history_rb_local_data_status` ON `djmdHistory` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_history_rb_local_deleted` ON `djmdHistory` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_history_rb_local_usn__i_d` ON `djmdHistory` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_hot_cue_banklist__name` ON `djmdHotCueBanklist` (`Name`);
|
||||
CREATE INDEX `djmd_hot_cue_banklist__parent_i_d` ON `djmdHotCueBanklist` (`ParentID`);
|
||||
CREATE INDEX `djmd_hot_cue_banklist__u_u_i_d` ON `djmdHotCueBanklist` (`UUID`);
|
||||
CREATE INDEX `djmd_hot_cue_banklist_rb_data_status` ON `djmdHotCueBanklist` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_hot_cue_banklist_rb_local_data_status` ON `djmdHotCueBanklist` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_hot_cue_banklist_rb_local_deleted` ON `djmdHotCueBanklist` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_hot_cue_banklist_rb_local_usn__i_d` ON `djmdHotCueBanklist` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_key__scale_name` ON `djmdKey` (`ScaleName`);
|
||||
CREATE INDEX `djmd_key__u_u_i_d` ON `djmdKey` (`UUID`);
|
||||
CREATE INDEX `djmd_key_rb_data_status` ON `djmdKey` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_key_rb_local_data_status` ON `djmdKey` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_key_rb_local_deleted` ON `djmdKey` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_key_rb_local_usn__i_d` ON `djmdKey` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_label__name` ON `djmdLabel` (`Name`);
|
||||
CREATE INDEX `djmd_label__u_u_i_d` ON `djmdLabel` (`UUID`);
|
||||
CREATE INDEX `djmd_label_rb_data_status` ON `djmdLabel` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_label_rb_local_data_status` ON `djmdLabel` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_label_rb_local_deleted` ON `djmdLabel` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_label_rb_local_usn__i_d` ON `djmdLabel` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_menu_items__u_u_i_d` ON `djmdMenuItems` (`UUID`);
|
||||
CREATE INDEX `djmd_menu_items_rb_data_status` ON `djmdMenuItems` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_menu_items_rb_local_data_status` ON `djmdMenuItems` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_menu_items_rb_local_deleted` ON `djmdMenuItems` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_menu_items_rb_local_usn__i_d` ON `djmdMenuItems` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_mixer_param__content_i_d_rb_local_deleted` ON `djmdMixerParam` (`ContentID`, `rb_local_deleted`);
|
||||
CREATE INDEX `djmd_mixer_param__u_u_i_d` ON `djmdMixerParam` (`UUID`);
|
||||
CREATE INDEX `djmd_mixer_param_rb_data_status` ON `djmdMixerParam` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_mixer_param_rb_local_data_status` ON `djmdMixerParam` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_mixer_param_rb_local_deleted` ON `djmdMixerParam` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_mixer_param_rb_local_usn__i_d` ON `djmdMixerParam` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_my_tag__parent_i_d` ON `djmdMyTag` (`ParentID`);
|
||||
CREATE INDEX `djmd_my_tag__seq` ON `djmdMyTag` (`Seq`);
|
||||
CREATE INDEX `djmd_my_tag__u_u_i_d` ON `djmdMyTag` (`UUID`);
|
||||
CREATE INDEX `djmd_my_tag_rb_data_status` ON `djmdMyTag` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_my_tag_rb_local_data_status` ON `djmdMyTag` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_my_tag_rb_local_deleted` ON `djmdMyTag` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_my_tag_rb_local_usn__i_d` ON `djmdMyTag` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_playlist__attribute` ON `djmdPlaylist` (`Attribute`);
|
||||
CREATE INDEX `djmd_playlist__name` ON `djmdPlaylist` (`Name`);
|
||||
CREATE INDEX `djmd_playlist__parent_i_d` ON `djmdPlaylist` (`ParentID`);
|
||||
CREATE INDEX `djmd_playlist__seq` ON `djmdPlaylist` (`Seq`);
|
||||
CREATE INDEX `djmd_playlist__u_u_i_d` ON `djmdPlaylist` (`UUID`);
|
||||
CREATE INDEX `djmd_playlist_rb_data_status` ON `djmdPlaylist` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_playlist_rb_local_data_status` ON `djmdPlaylist` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_playlist_rb_local_deleted` ON `djmdPlaylist` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_playlist_rb_local_usn__i_d` ON `djmdPlaylist` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_recommend_like__content_i_d1__content_i_d2` ON `djmdRecommendLike` (`ContentID1`, `ContentID2`);
|
||||
CREATE INDEX `djmd_recommend_like__content_i_d2` ON `djmdRecommendLike` (`ContentID2`);
|
||||
CREATE INDEX `djmd_recommend_like__u_u_i_d` ON `djmdRecommendLike` (`UUID`);
|
||||
CREATE INDEX `djmd_recommend_like_rb_data_status` ON `djmdRecommendLike` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_recommend_like_rb_local_data_status` ON `djmdRecommendLike` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_recommend_like_rb_local_deleted` ON `djmdRecommendLike` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_recommend_like_rb_local_usn__i_d` ON `djmdRecommendLike` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_related_tracks__name` ON `djmdRelatedTracks` (`Name`);
|
||||
CREATE INDEX `djmd_related_tracks__parent_i_d` ON `djmdRelatedTracks` (`ParentID`);
|
||||
CREATE INDEX `djmd_related_tracks__seq` ON `djmdRelatedTracks` (`Seq`);
|
||||
CREATE INDEX `djmd_related_tracks__u_u_i_d` ON `djmdRelatedTracks` (`UUID`);
|
||||
CREATE INDEX `djmd_related_tracks_rb_data_status` ON `djmdRelatedTracks` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_related_tracks_rb_local_data_status` ON `djmdRelatedTracks` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_related_tracks_rb_local_deleted` ON `djmdRelatedTracks` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_related_tracks_rb_local_usn__i_d` ON `djmdRelatedTracks` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_sampler__name` ON `djmdSampler` (`Name`);
|
||||
CREATE INDEX `djmd_sampler__parent_i_d` ON `djmdSampler` (`ParentID`);
|
||||
CREATE INDEX `djmd_sampler__seq` ON `djmdSampler` (`Seq`);
|
||||
CREATE INDEX `djmd_sampler__u_u_i_d` ON `djmdSampler` (`UUID`);
|
||||
CREATE INDEX `djmd_sampler_rb_data_status` ON `djmdSampler` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_sampler_rb_local_data_status` ON `djmdSampler` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_sampler_rb_local_deleted` ON `djmdSampler` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_sampler_rb_local_usn__i_d` ON `djmdSampler` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_song_history__content_i_d_rb_local_deleted` ON `djmdSongHistory` (`ContentID`, `rb_local_deleted`);
|
||||
CREATE INDEX `djmd_song_history__history_i_d` ON `djmdSongHistory` (`HistoryID`);
|
||||
CREATE INDEX `djmd_song_history__u_u_i_d` ON `djmdSongHistory` (`UUID`);
|
||||
CREATE INDEX `djmd_song_history_rb_data_status` ON `djmdSongHistory` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_song_history_rb_local_data_status` ON `djmdSongHistory` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_song_history_rb_local_deleted` ON `djmdSongHistory` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_song_history_rb_local_usn__i_d` ON `djmdSongHistory` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_song_hot_cue_banklist__content_i_d` ON `djmdSongHotCueBanklist` (`ContentID`);
|
||||
CREATE INDEX `djmd_song_hot_cue_banklist__hot_cue_banklist_i_d` ON `djmdSongHotCueBanklist` (`HotCueBanklistID`);
|
||||
CREATE INDEX `djmd_song_hot_cue_banklist__hot_cue_banklist_u_u_i_d` ON `djmdSongHotCueBanklist` (`HotCueBanklistUUID`);
|
||||
CREATE INDEX `djmd_song_hot_cue_banklist__u_u_i_d` ON `djmdSongHotCueBanklist` (`UUID`);
|
||||
CREATE INDEX `djmd_song_hot_cue_banklist_rb_data_status` ON `djmdSongHotCueBanklist` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_song_hot_cue_banklist_rb_local_data_status` ON `djmdSongHotCueBanklist` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_song_hot_cue_banklist_rb_local_deleted` ON `djmdSongHotCueBanklist` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_song_hot_cue_banklist_rb_local_usn__i_d` ON `djmdSongHotCueBanklist` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_song_my_tag__content_i_d_rb_local_deleted` ON `djmdSongMyTag` (`ContentID`, `rb_local_deleted`);
|
||||
CREATE INDEX `djmd_song_my_tag__my_tag_i_d_rb_local_deleted__i_d` ON `djmdSongMyTag` (`MyTagID`, `rb_local_deleted`, `ID`);
|
||||
CREATE INDEX `djmd_song_my_tag__u_u_i_d` ON `djmdSongMyTag` (`UUID`);
|
||||
CREATE INDEX `djmd_song_my_tag_rb_data_status` ON `djmdSongMyTag` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_song_my_tag_rb_local_data_status` ON `djmdSongMyTag` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_song_my_tag_rb_local_deleted` ON `djmdSongMyTag` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_song_my_tag_rb_local_usn__i_d` ON `djmdSongMyTag` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_song_playlist__content_i_d_rb_local_deleted` ON `djmdSongPlaylist` (`ContentID`, `rb_local_deleted`);
|
||||
CREATE INDEX `djmd_song_playlist__playlist_i_d__i_d` ON `djmdSongPlaylist` (`PlaylistID`, `ID`);
|
||||
CREATE INDEX `djmd_song_playlist__u_u_i_d` ON `djmdSongPlaylist` (`UUID`);
|
||||
CREATE INDEX `djmd_song_playlist_rb_data_status` ON `djmdSongPlaylist` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_song_playlist_rb_local_data_status` ON `djmdSongPlaylist` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_song_playlist_rb_local_deleted` ON `djmdSongPlaylist` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_song_playlist_rb_local_usn__i_d` ON `djmdSongPlaylist` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_song_related_tracks__content_i_d` ON `djmdSongRelatedTracks` (`ContentID`);
|
||||
CREATE INDEX `djmd_song_related_tracks__related_tracks_i_d` ON `djmdSongRelatedTracks` (`RelatedTracksID`);
|
||||
CREATE INDEX `djmd_song_related_tracks__u_u_i_d` ON `djmdSongRelatedTracks` (`UUID`);
|
||||
CREATE INDEX `djmd_song_related_tracks_rb_data_status` ON `djmdSongRelatedTracks` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_song_related_tracks_rb_local_data_status` ON `djmdSongRelatedTracks` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_song_related_tracks_rb_local_deleted` ON `djmdSongRelatedTracks` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_song_related_tracks_rb_local_usn__i_d` ON `djmdSongRelatedTracks` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_song_request_list__content_i_d` ON `djmdSongRequestList` (`ContentID`);
|
||||
CREATE INDEX `djmd_song_request_list__u_u_i_d` ON `djmdSongRequestList` (`UUID`);
|
||||
CREATE INDEX `djmd_song_request_list_rb_data_status` ON `djmdSongRequestList` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_song_request_list_rb_local_data_status` ON `djmdSongRequestList` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_song_request_list_rb_local_deleted` ON `djmdSongRequestList` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_song_request_list_rb_local_usn__i_d` ON `djmdSongRequestList` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_song_sampler__content_i_d` ON `djmdSongSampler` (`ContentID`);
|
||||
CREATE INDEX `djmd_song_sampler__sampler_i_d` ON `djmdSongSampler` (`SamplerID`);
|
||||
CREATE INDEX `djmd_song_sampler__u_u_i_d` ON `djmdSongSampler` (`UUID`);
|
||||
CREATE INDEX `djmd_song_sampler_rb_data_status` ON `djmdSongSampler` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_song_sampler_rb_local_data_status` ON `djmdSongSampler` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_song_sampler_rb_local_deleted` ON `djmdSongSampler` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_song_sampler_rb_local_usn__i_d` ON `djmdSongSampler` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_song_tag_list__content_i_d` ON `djmdSongTagList` (`ContentID`);
|
||||
CREATE INDEX `djmd_song_tag_list__u_u_i_d` ON `djmdSongTagList` (`UUID`);
|
||||
CREATE INDEX `djmd_song_tag_list_rb_data_status` ON `djmdSongTagList` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_song_tag_list_rb_local_data_status` ON `djmdSongTagList` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_song_tag_list_rb_local_deleted` ON `djmdSongTagList` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_song_tag_list_rb_local_usn__i_d` ON `djmdSongTagList` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `djmd_sort__u_u_i_d` ON `djmdSort` (`UUID`);
|
||||
CREATE INDEX `djmd_sort_rb_data_status` ON `djmdSort` (`rb_data_status`);
|
||||
CREATE INDEX `djmd_sort_rb_local_data_status` ON `djmdSort` (`rb_local_data_status`);
|
||||
CREATE INDEX `djmd_sort_rb_local_deleted` ON `djmdSort` (`rb_local_deleted`);
|
||||
CREATE INDEX `djmd_sort_rb_local_usn__i_d` ON `djmdSort` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `hot_cue_banklist_cue__hot_cue_banklist_i_d` ON `hotCueBanklistCue` (`HotCueBanklistID`);
|
||||
CREATE INDEX `hot_cue_banklist_cue__u_u_i_d` ON `hotCueBanklistCue` (`UUID`);
|
||||
CREATE INDEX `hot_cue_banklist_cue_rb_cue_count` ON `hotCueBanklistCue` (`rb_cue_count`);
|
||||
CREATE INDEX `hot_cue_banklist_cue_rb_data_status` ON `hotCueBanklistCue` (`rb_data_status`);
|
||||
CREATE INDEX `hot_cue_banklist_cue_rb_local_data_status` ON `hotCueBanklistCue` (`rb_local_data_status`);
|
||||
CREATE INDEX `hot_cue_banklist_cue_rb_local_deleted` ON `hotCueBanklistCue` (`rb_local_deleted`);
|
||||
CREATE INDEX `hot_cue_banklist_cue_rb_local_usn__i_d` ON `hotCueBanklistCue` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `image_file__table_name__target_i_d` ON `imageFile` (`TableName`, `TargetID`);
|
||||
CREATE INDEX `image_file__table_name__target_u_u_i_d__i_d` ON `imageFile` (`TableName`, `TargetUUID`, `ID`);
|
||||
CREATE INDEX `image_file__u_u_i_d` ON `imageFile` (`UUID`);
|
||||
CREATE INDEX `image_file_rb_data_status` ON `imageFile` (`rb_data_status`);
|
||||
CREATE INDEX `image_file_rb_file_hash_dirty` ON `imageFile` (`rb_file_hash_dirty`);
|
||||
CREATE INDEX `image_file_rb_file_size_dirty` ON `imageFile` (`rb_file_size_dirty`);
|
||||
CREATE INDEX `image_file_rb_local_data_status` ON `imageFile` (`rb_local_data_status`);
|
||||
CREATE INDEX `image_file_rb_local_deleted` ON `imageFile` (`rb_local_deleted`);
|
||||
CREATE INDEX `image_file_rb_local_deleted_rb_in_progress_rb_local_file_status_rb_process_type_rb_priority` ON `imageFile` (`rb_local_deleted`, `rb_in_progress`, `rb_local_file_status`, `rb_process_type`, `rb_priority`);
|
||||
CREATE INDEX `image_file_rb_local_usn__i_d` ON `imageFile` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `setting_file__u_u_i_d` ON `settingFile` (`UUID`);
|
||||
CREATE INDEX `setting_file_rb_data_status` ON `settingFile` (`rb_data_status`);
|
||||
CREATE INDEX `setting_file_rb_file_hash_dirty` ON `settingFile` (`rb_file_hash_dirty`);
|
||||
CREATE INDEX `setting_file_rb_file_size_dirty` ON `settingFile` (`rb_file_size_dirty`);
|
||||
CREATE INDEX `setting_file_rb_local_data_status` ON `settingFile` (`rb_local_data_status`);
|
||||
CREATE INDEX `setting_file_rb_local_deleted` ON `settingFile` (`rb_local_deleted`);
|
||||
CREATE INDEX `setting_file_rb_local_usn__i_d` ON `settingFile` (`rb_local_usn`, `ID`);
|
||||
CREATE INDEX `uuid_i_d_map__u_u_i_d` ON `uuidIDMap` (`UUID`);
|
||||
CREATE INDEX `uuid_i_d_map_rb_data_status` ON `uuidIDMap` (`rb_data_status`);
|
||||
CREATE INDEX `uuid_i_d_map_rb_local_data_status` ON `uuidIDMap` (`rb_local_data_status`);
|
||||
CREATE INDEX `uuid_i_d_map_rb_local_deleted` ON `uuidIDMap` (`rb_local_deleted`);
|
||||
CREATE INDEX `uuid_i_d_map_rb_local_usn__i_d` ON `uuidIDMap` (`rb_local_usn`, `ID`);
|
||||
@@ -0,0 +1,88 @@
|
||||
-- Rekordbox's own scaffolding rows, needed before any track can be added:
|
||||
-- `add_content` looks up djmdMenuItems('TRACK') and fails on an empty table.
|
||||
--
|
||||
-- Static UI data only — menu items, colours, categories, sort options.
|
||||
-- djmdDevice and djmdProperty are DELIBERATELY absent: they carry the
|
||||
-- machine's name and UUIDs, so the exporter generates those fresh instead.
|
||||
|
||||
-- djmdMenuItems: 27 rows
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('1', -128, 'GENRE', '1', 0, 0, 0, 0, NULL, 10, '2026-09-17 20:53:21.658 +00:00', '2026-09-17 20:53:21.658 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('2', -127, 'ARTIST', '2', 0, 0, 0, 0, NULL, 11, '2026-09-17 20:53:21.658 +00:00', '2026-09-17 20:53:21.658 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('3', -126, 'ALBUM', '3', 0, 0, 0, 0, NULL, 12, '2026-09-17 20:53:21.658 +00:00', '2026-09-17 20:53:21.658 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('4', -125, 'TRACK', '4', 0, 0, 0, 0, NULL, 13, '2026-09-17 20:53:21.658 +00:00', '2026-09-17 20:53:21.658 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('5', -123, 'BPM', '5', 0, 0, 0, 0, NULL, 14, '2026-09-17 20:53:21.658 +00:00', '2026-09-17 20:53:21.658 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('6', -122, 'RATING', '6', 0, 0, 0, 0, NULL, 15, '2026-09-17 20:53:21.659 +00:00', '2026-09-17 20:53:21.659 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('7', -121, 'YEAR', '7', 0, 0, 0, 0, NULL, 16, '2026-09-17 20:53:21.659 +00:00', '2026-09-17 20:53:21.659 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('8', -120, 'REMIXER', '8', 0, 0, 0, 0, NULL, 17, '2026-09-17 20:53:21.659 +00:00', '2026-09-17 20:53:21.659 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('9', -119, 'LABEL', '9', 0, 0, 0, 0, NULL, 18, '2026-09-17 20:53:21.659 +00:00', '2026-09-17 20:53:21.659 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('10', -118, 'ORIGINAL ARTIST', '10', 0, 0, 0, 0, NULL, 19, '2026-09-17 20:53:21.659 +00:00', '2026-09-17 20:53:21.659 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('11', -117, 'KEY', '11', 0, 0, 0, 0, NULL, 20, '2026-09-17 20:53:21.659 +00:00', '2026-09-17 20:53:21.659 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('12', -115, 'CUE', '12', 0, 0, 0, 0, NULL, 21, '2026-09-17 20:53:21.659 +00:00', '2026-09-17 20:53:21.659 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('13', -114, 'COLOR', '13', 0, 0, 0, 0, NULL, 22, '2026-09-17 20:53:21.659 +00:00', '2026-09-17 20:53:21.659 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('14', -110, 'TIME', '14', 0, 0, 0, 0, NULL, 23, '2026-09-17 20:53:21.660 +00:00', '2026-09-17 20:53:21.660 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('15', -109, 'BITRATE', '15', 0, 0, 0, 0, NULL, 24, '2026-09-17 20:53:21.660 +00:00', '2026-09-17 20:53:21.660 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('16', -108, 'FILE NAME', '16', 0, 0, 0, 0, NULL, 25, '2026-09-17 20:53:21.660 +00:00', '2026-09-17 20:53:21.660 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('17', -124, 'PLAYLIST', '17', 0, 0, 0, 0, NULL, 26, '2026-09-17 20:53:21.660 +00:00', '2026-09-17 20:53:21.660 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('18', -104, 'HOT CUE BANK', '18', 0, 0, 0, 0, NULL, 27, '2026-09-17 20:53:21.660 +00:00', '2026-09-17 20:53:21.660 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('19', -107, 'HISTORY', '19', 0, 0, 0, 0, NULL, 28, '2026-09-17 20:53:21.660 +00:00', '2026-09-17 20:53:21.660 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('20', -111, 'SEARCH', '20', 0, 0, 0, 0, NULL, 29, '2026-09-17 20:53:21.660 +00:00', '2026-09-17 20:53:21.660 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('21', -106, 'COMMENTS', '21', 0, 0, 0, 0, NULL, 30, '2026-09-17 20:53:21.660 +00:00', '2026-09-17 20:53:21.660 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('22', -116, 'DATE ADDED', '22', 0, 0, 0, 0, NULL, 31, '2026-09-17 20:53:21.660 +00:00', '2026-09-17 20:53:21.660 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('23', -105, 'DJ PLAY COUNT', '23', 0, 0, 0, 0, NULL, 32, '2026-09-17 20:53:21.661 +00:00', '2026-09-17 20:53:21.661 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('24', -112, 'FOLDER', '24', 0, 0, 0, 0, NULL, 33, '2026-09-17 20:53:21.661 +00:00', '2026-09-17 20:53:21.661 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('25', -95, 'DEFAULT', '25', 0, 0, 0, 0, NULL, 34, '2026-09-17 20:53:21.661 +00:00', '2026-09-17 20:53:21.661 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('26', -94, 'ALPHABET', '26', 0, 0, 0, 0, NULL, 35, '2026-09-17 20:53:21.661 +00:00', '2026-09-17 20:53:21.661 +00:00');
|
||||
INSERT INTO "djmdMenuItems" ("ID", "Class", "Name", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('27', -86, 'MATCHING', '27', 0, 0, 0, 0, NULL, 36, '2026-09-17 20:53:21.661 +00:00', '2026-09-17 20:53:21.661 +00:00');
|
||||
|
||||
-- djmdColor: 8 rows
|
||||
INSERT INTO "djmdColor" ("ID", "ColorCode", "SortKey", "Commnt", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('1', NULL, 1, 'Pink', '1', 0, 0, 0, 0, NULL, 2, '2026-09-17 20:53:21.657 +00:00', '2026-09-17 20:53:21.657 +00:00');
|
||||
INSERT INTO "djmdColor" ("ID", "ColorCode", "SortKey", "Commnt", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('2', NULL, 2, 'Red', '2', 0, 0, 0, 0, NULL, 3, '2026-09-17 20:53:21.657 +00:00', '2026-09-17 20:53:21.657 +00:00');
|
||||
INSERT INTO "djmdColor" ("ID", "ColorCode", "SortKey", "Commnt", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('3', NULL, 3, 'Orange', '3', 0, 0, 0, 0, NULL, 4, '2026-09-17 20:53:21.657 +00:00', '2026-09-17 20:53:21.657 +00:00');
|
||||
INSERT INTO "djmdColor" ("ID", "ColorCode", "SortKey", "Commnt", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('4', NULL, 4, 'Yellow', '4', 0, 0, 0, 0, NULL, 5, '2026-09-17 20:53:21.657 +00:00', '2026-09-17 20:53:21.657 +00:00');
|
||||
INSERT INTO "djmdColor" ("ID", "ColorCode", "SortKey", "Commnt", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('5', NULL, 5, 'Green', '5', 0, 0, 0, 0, NULL, 6, '2026-09-17 20:53:21.657 +00:00', '2026-09-17 20:53:21.657 +00:00');
|
||||
INSERT INTO "djmdColor" ("ID", "ColorCode", "SortKey", "Commnt", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('6', NULL, 6, 'Aqua', '6', 0, 0, 0, 0, NULL, 7, '2026-09-17 20:53:21.657 +00:00', '2026-09-17 20:53:21.657 +00:00');
|
||||
INSERT INTO "djmdColor" ("ID", "ColorCode", "SortKey", "Commnt", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('7', NULL, 7, 'Blue', '7', 0, 0, 0, 0, NULL, 8, '2026-09-17 20:53:21.658 +00:00', '2026-09-17 20:53:21.658 +00:00');
|
||||
INSERT INTO "djmdColor" ("ID", "ColorCode", "SortKey", "Commnt", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('8', NULL, 8, 'Purple', '8', 0, 0, 0, 0, NULL, 9, '2026-09-17 20:53:21.658 +00:00', '2026-09-17 20:53:21.658 +00:00');
|
||||
|
||||
-- djmdCategory: 22 rows
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('1', '1', 0, 1, 99, '1', 0, 0, 0, 0, NULL, 37, '2026-09-17 20:53:25.758 +00:00', '2026-09-17 20:53:25.758 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('2', '2', 1, 0, 2, '2', 0, 0, 0, 0, NULL, 38, '2026-09-17 20:53:25.769 +00:00', '2026-09-17 20:53:25.769 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('3', '3', 2, 0, 3, '3', 0, 0, 0, 0, NULL, 39, '2026-09-17 20:53:25.774 +00:00', '2026-09-17 20:53:25.774 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('4', '4', 3, 0, 1, '4', 0, 0, 0, 0, NULL, 40, '2026-09-17 20:53:25.780 +00:00', '2026-09-17 20:53:25.780 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('5', '17', 5, 0, 99, '5', 0, 0, 0, 0, NULL, 41, '2026-09-17 20:53:25.786 +00:00', '2026-09-17 20:53:25.786 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('6', '5', 0, 1, 5, '6', 0, 0, 0, 0, NULL, 42, '2026-09-17 20:53:25.793 +00:00', '2026-09-17 20:53:25.793 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('7', '6', 0, 1, 99, '7', 0, 0, 0, 0, NULL, 43, '2026-09-17 20:53:25.799 +00:00', '2026-09-17 20:53:25.799 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('8', '7', 0, 1, 99, '8', 0, 0, 0, 0, NULL, 44, '2026-09-17 20:53:25.804 +00:00', '2026-09-17 20:53:25.804 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('9', '8', 0, 1, 99, '9', 0, 0, 0, 0, NULL, 45, '2026-09-17 20:53:25.811 +00:00', '2026-09-17 20:53:25.811 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('10', '9', 0, 1, 99, '10', 0, 0, 0, 0, NULL, 46, '2026-09-17 20:53:25.817 +00:00', '2026-09-17 20:53:25.817 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('11', '10', 0, 1, 99, '11', 0, 0, 0, 0, NULL, 47, '2026-09-17 20:53:25.823 +00:00', '2026-09-17 20:53:25.823 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('12', '11', 4, 0, 99, '12', 0, 0, 0, 0, NULL, 48, '2026-09-17 20:53:25.829 +00:00', '2026-09-17 20:53:25.829 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('15', '13', 0, 1, 99, '15', 0, 0, 0, 0, NULL, 49, '2026-09-17 20:53:25.836 +00:00', '2026-09-17 20:53:25.836 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('17', '24', 9, 0, 99, '17', 0, 0, 0, 0, NULL, 50, '2026-09-17 20:53:25.842 +00:00', '2026-09-17 20:53:25.842 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('18', '20', 7, 0, 99, '18', 0, 0, 0, 0, NULL, 51, '2026-09-17 20:53:25.848 +00:00', '2026-09-17 20:53:25.848 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('19', '14', 0, 1, 4, '19', 0, 0, 0, 0, NULL, 52, '2026-09-17 20:53:25.854 +00:00', '2026-09-17 20:53:25.854 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('20', '15', 0, 1, 6, '20', 0, 0, 0, 0, NULL, 53, '2026-09-17 20:53:25.860 +00:00', '2026-09-17 20:53:25.860 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('21', '16', 0, 1, 99, '21', 0, 0, 0, 0, NULL, 54, '2026-09-17 20:53:25.865 +00:00', '2026-09-17 20:53:25.865 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('22', '19', 6, 0, 99, '22', 0, 0, 0, 0, NULL, 55, '2026-09-17 20:53:25.870 +00:00', '2026-09-17 20:53:25.870 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('23', '18', 0, 1, 99, '23', 0, 0, 0, 0, NULL, 56, '2026-09-17 20:53:25.875 +00:00', '2026-09-17 20:53:25.875 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('26', '27', 8, 2, 99, '26', 0, 0, 0, 0, NULL, 57, '2026-09-17 20:53:25.881 +00:00', '2026-09-17 20:53:25.881 +00:00');
|
||||
INSERT INTO "djmdCategory" ("ID", "MenuItemID", "Seq", "Disable", "InfoOrder", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('27', '22', 10, 0, 99, '27', 0, 0, 0, 0, NULL, 58, '2026-09-17 20:53:25.886 +00:00', '2026-09-17 20:53:25.886 +00:00');
|
||||
|
||||
-- djmdSort: 17 rows
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('0', '25', 1, 0, '0', 0, 0, 0, 0, NULL, 59, '2026-09-17 20:53:25.893 +00:00', '2026-09-17 20:53:25.893 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('1', '26', 2, 0, '1', 0, 0, 0, 0, NULL, 60, '2026-09-17 20:53:25.900 +00:00', '2026-09-17 20:53:25.900 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('2', '2', 3, 0, '2', 0, 0, 0, 0, NULL, 61, '2026-09-17 20:53:25.907 +00:00', '2026-09-17 20:53:25.907 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('3', '3', 4, 0, '3', 0, 0, 0, 0, NULL, 62, '2026-09-17 20:53:25.913 +00:00', '2026-09-17 20:53:25.913 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('4', '5', 5, 0, '4', 0, 0, 0, 0, NULL, 63, '2026-09-17 20:53:25.920 +00:00', '2026-09-17 20:53:25.920 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('5', '6', 6, 0, '5', 0, 0, 0, 0, NULL, 64, '2026-09-17 20:53:25.925 +00:00', '2026-09-17 20:53:25.925 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('6', '1', 0, 1, '6', 0, 0, 0, 0, NULL, 65, '2026-09-17 20:53:25.931 +00:00', '2026-09-17 20:53:25.931 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('7', '21', 0, 1, '7', 0, 0, 0, 0, NULL, 66, '2026-09-17 20:53:25.937 +00:00', '2026-09-17 20:53:25.937 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('8', '14', 0, 1, '8', 0, 0, 0, 0, NULL, 67, '2026-09-17 20:53:25.943 +00:00', '2026-09-17 20:53:25.943 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('9', '8', 0, 1, '9', 0, 0, 0, 0, NULL, 68, '2026-09-17 20:53:25.950 +00:00', '2026-09-17 20:53:25.950 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('10', '9', 0, 1, '10', 0, 0, 0, 0, NULL, 69, '2026-09-17 20:53:25.957 +00:00', '2026-09-17 20:53:25.957 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('11', '10', 0, 1, '11', 0, 0, 0, 0, NULL, 70, '2026-09-17 20:53:25.963 +00:00', '2026-09-17 20:53:25.963 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('12', '11', 7, 0, '12', 0, 0, 0, 0, NULL, 71, '2026-09-17 20:53:25.971 +00:00', '2026-09-17 20:53:25.971 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('13', '15', 0, 1, '13', 0, 0, 0, 0, NULL, 72, '2026-09-17 20:53:25.978 +00:00', '2026-09-17 20:53:25.978 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('15', '13', 0, 1, '15', 0, 0, 0, 0, NULL, 73, '2026-09-17 20:53:25.985 +00:00', '2026-09-17 20:53:25.985 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('16', '23', 0, 1, '16', 0, 0, 0, 0, NULL, 74, '2026-09-17 20:53:25.992 +00:00', '2026-09-17 20:53:25.992 +00:00');
|
||||
INSERT INTO "djmdSort" ("ID", "MenuItemID", "Seq", "Disable", "UUID", "rb_data_status", "rb_local_data_status", "rb_local_deleted", "rb_local_synced", "usn", "rb_local_usn", "created_at", "updated_at") VALUES ('17', '22', 0, 1, '17', 0, 0, 0, 0, NULL, 75, '2026-09-17 20:53:25.998 +00:00', '2026-09-17 20:53:25.998 +00:00');
|
||||
@@ -8,6 +8,8 @@
|
||||
# - traktor-nml-utils parses/serializes via xsdata, which discovers plugins at
|
||||
# runtime → collect_submodules('xsdata')
|
||||
# - python-multipart is imported as `multipart` by starlette → hidden import
|
||||
# - dulwich (version-history backups) imports git backends dynamically →
|
||||
# collect_submodules('dulwich')
|
||||
from PyInstaller.utils.hooks import collect_submodules, collect_all
|
||||
|
||||
hiddenimports = []
|
||||
@@ -15,11 +17,12 @@ datas = []
|
||||
binaries = []
|
||||
|
||||
# Dynamically-imported subpackages.
|
||||
for pkg in ("uvicorn", "xsdata"):
|
||||
for pkg in ("uvicorn", "xsdata", "dulwich"):
|
||||
hiddenimports += collect_submodules(pkg)
|
||||
|
||||
# Native standard extras — grab modules + shared libs + any data.
|
||||
for pkg in ("uvloop", "httptools", "websockets"):
|
||||
# Native standard extras — grab modules + shared libs + any data. PyAV (`av`)
|
||||
# carries FFmpeg's shared libraries, which the export's waveform analysis needs.
|
||||
for pkg in ("uvloop", "httptools", "websockets", "av"):
|
||||
d, b, h = collect_all(pkg)
|
||||
datas += d
|
||||
binaries += b
|
||||
@@ -33,6 +36,25 @@ hiddenimports += ["multipart", "anyio"]
|
||||
# app version — see konduktor/__init__.py). Path is relative to this spec.
|
||||
datas += [("../frontend/package.json", ".")]
|
||||
|
||||
# The Rekordbox and OneLibrary exporters build their databases from the real
|
||||
# DDL + scaffolding rows under fixtures/, found at `parents[3] / "fixtures"` —
|
||||
# i.e. the bundle root. Without these a packaged app cannot export to either.
|
||||
datas += [
|
||||
("fixtures/rekordbox/schema.sql", "fixtures/rekordbox"),
|
||||
("fixtures/rekordbox/seed.sql", "fixtures/rekordbox"),
|
||||
("fixtures/onelibrary/schema.sql", "fixtures/onelibrary"),
|
||||
("fixtures/onelibrary/seed.sql", "fixtures/onelibrary"),
|
||||
# The "Rekordbox Export" target starts from rekordbox's own empty device library.
|
||||
("fixtures/rekordbox/device/export.pdb", "fixtures/rekordbox/device"),
|
||||
("fixtures/rekordbox/device/exportExt.pdb", "fixtures/rekordbox/device"),
|
||||
]
|
||||
# Which stem engine this build needs, and the pinned weights (read at import by
|
||||
# konduktor/stems/engine_manager.py).
|
||||
datas += [
|
||||
("konduktor/stems/engine.json", "konduktor/stems"),
|
||||
("konduktor/stems/weights.json", "konduktor/stems"),
|
||||
]
|
||||
|
||||
a = Analysis(
|
||||
["sidecar.py"],
|
||||
pathex=[],
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Per-platform adapters. Each owns a native library model and translates the
|
||||
generic commands onto it; nothing outside an adapter package sees a native type.
|
||||
|
||||
Importing this package registers every adapter. Order matters only for the
|
||||
registry's ``can_open()`` probe, and the probes are mutually exclusive: Traktor
|
||||
requires an NML header, Rekordbox an encrypted database with its own schema, and
|
||||
OneLibrary a drive laid out around ``PIONEER/rekordbox/exportLibrary.db``. The
|
||||
two encrypted databases cannot be confused for one another — they use different
|
||||
SQLCipher keys, so each driver's decrypt fails outright on the other's file.
|
||||
"""
|
||||
from . import onelibrary # noqa: F401 — registers the OneLibrary driver
|
||||
from . import rekordbox # noqa: F401 — registers the Rekordbox driver
|
||||
from . import traktor # noqa: F401 — registers the Traktor driver
|
||||
@@ -0,0 +1,16 @@
|
||||
"""The OneLibrary adapter: the cross-vendor USB export format.
|
||||
|
||||
Importing this package registers the platform for READING (a plugged-in drive)
|
||||
and as an export TARGET (writing a fresh drive). Two registries, because opening
|
||||
a library and creating one from nothing are different capabilities.
|
||||
"""
|
||||
from ...core import export as core_export
|
||||
from ...core import registry
|
||||
from .driver import OneLibraryDriver
|
||||
from .export import OneLibraryExporter
|
||||
|
||||
ONELIBRARY = OneLibraryDriver()
|
||||
registry.register(ONELIBRARY)
|
||||
|
||||
ONELIBRARY_EXPORTER = OneLibraryExporter()
|
||||
core_export.register(ONELIBRARY_EXPORTER)
|
||||
@@ -0,0 +1,326 @@
|
||||
"""The OneLibrary adapter: owns the drive's database and the generic projection.
|
||||
|
||||
Mirrors `adapters.rekordbox.adapter`. It holds:
|
||||
|
||||
* a ``OneLibraryStore`` — the retained NATIVE model (the open drive),
|
||||
* a ``TrackIndex`` — the generic READ projection built from it.
|
||||
|
||||
**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.
|
||||
|
||||
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 Unsupported
|
||||
from ...core.capabilities import Capabilities
|
||||
from ...core.model import HotcueChip, PlaylistNode, Track, TrackCues
|
||||
from ...core.pathmap import PathMapping, common_dir_prefix
|
||||
from ...core.query import TrackIndex
|
||||
from . import capabilities as caps
|
||||
from . import projection
|
||||
from .store import OneLibraryStore
|
||||
|
||||
# `playlist.attribute`, from pyrekordbox's own enum. A drive carries no smart
|
||||
# playlists — rekordbox resolves them to static lists on export, because a CDJ
|
||||
# cannot evaluate rules — but the value is handled rather than assumed absent.
|
||||
ATTRIBUTE_PLAYLIST = 0
|
||||
ATTRIBUTE_FOLDER = 1
|
||||
ATTRIBUTE_SMART = 4
|
||||
|
||||
|
||||
class OneLibraryAdapter:
|
||||
platform = "onelibrary"
|
||||
|
||||
def __init__(self, path: Path):
|
||||
self.path = Path(path)
|
||||
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)
|
||||
|
||||
def _drive_path(self, row) -> str | None:
|
||||
resolved = self._store.layout.resolve(getattr(row, "path", None))
|
||||
return str(resolved) if resolved is not None else None
|
||||
|
||||
def close(self) -> None:
|
||||
"""Release the database and its file handle.
|
||||
|
||||
More than housekeeping here: the library is on a removable drive, and a
|
||||
held handle is what stops it ejecting.
|
||||
"""
|
||||
self._store.close()
|
||||
|
||||
def reload(self) -> None:
|
||||
self._store._load()
|
||||
self._rebuild()
|
||||
|
||||
# ---- identity --------------------------------------------------------
|
||||
def capabilities(self) -> Capabilities:
|
||||
return caps.capabilities_for(
|
||||
device_name=self._store.device_name,
|
||||
version=self._store.db_version,
|
||||
)
|
||||
|
||||
# ---- read ------------------------------------------------------------
|
||||
@property
|
||||
def tracks(self) -> list[Track]:
|
||||
return self._index.tracks
|
||||
|
||||
@property
|
||||
def by_key(self) -> dict[str, Track]:
|
||||
return self._index.by_key
|
||||
|
||||
def track(self, track_id: str) -> Track | None:
|
||||
return self._index.get(track_id)
|
||||
|
||||
def query_tracks(self, **kw):
|
||||
return self._index.query_tracks(**kw)
|
||||
|
||||
def facets(self):
|
||||
return self._index.facets()
|
||||
|
||||
def stats(self, playlist_count: int):
|
||||
return self._index.stats(playlist_count)
|
||||
|
||||
def playlist_count(self) -> int:
|
||||
return self._store.count_playlists()
|
||||
|
||||
def track_cues(self, track_id: str) -> TrackCues | None:
|
||||
"""A track's cues and beatgrid — and where the approximate counts get fixed.
|
||||
|
||||
`projection.to_track` cannot afford the track's analysis files at open
|
||||
(~23 ms each for the `.EXT`), so it reports no cues and a guessed marker
|
||||
count. This is the moment the real numbers exist, so the projected track
|
||||
is corrected here rather than being left disagreeing with the deck.
|
||||
"""
|
||||
if self._index.get(track_id) is None:
|
||||
return None
|
||||
cues = self._store.cues(track_id)
|
||||
grid = self._store.anlz_grid(track_id)
|
||||
from . import beatgrid
|
||||
|
||||
markers = beatgrid.markers_from_beats(*grid) if grid is not None else []
|
||||
result = projection.to_track_cues(cues, markers)
|
||||
|
||||
track = self._index.get(track_id)
|
||||
if track is not None:
|
||||
track.grid_marker_count = len(result.grid_markers)
|
||||
track.cue_count = len(result.cues)
|
||||
track.hotcues = sorted(
|
||||
(
|
||||
HotcueChip(slot=c.slot, type=c.type, color=c.color)
|
||||
for c in result.cues
|
||||
if c.role == "hotcue" and c.slot is not None
|
||||
),
|
||||
key=lambda chip: chip.slot,
|
||||
)
|
||||
track.hotcue_count = len(track.hotcues)
|
||||
return result
|
||||
|
||||
# ---- playlists -------------------------------------------------------
|
||||
def playlist_tree(self) -> list[PlaylistNode]:
|
||||
"""The drive's playlist tree: a flat table with `playlist_id_parent` links.
|
||||
|
||||
A root node's parent is 0, not NULL — so "no parent" is a value here
|
||||
rather than an absence, and treating 0 as a real id would orphan every
|
||||
top-level playlist.
|
||||
"""
|
||||
rows = self._store.playlists()
|
||||
nodes: dict[str, PlaylistNode] = {}
|
||||
parents: dict[str, str] = {}
|
||||
|
||||
for r in rows:
|
||||
attribute = int(getattr(r, "attribute", 0) or 0)
|
||||
if attribute == ATTRIBUTE_FOLDER:
|
||||
kind = "folder"
|
||||
elif attribute == ATTRIBUTE_SMART:
|
||||
kind = "smart"
|
||||
else:
|
||||
kind = "playlist"
|
||||
node_id = str(getattr(r, "playlist_id", ""))
|
||||
nodes[node_id] = PlaylistNode(
|
||||
id=node_id,
|
||||
name=getattr(r, "name", "") or "",
|
||||
kind=kind,
|
||||
count=(0 if kind == "folder" else len(self._store.playlist_song_ids(node_id))),
|
||||
children=[],
|
||||
selectable=kind == "playlist",
|
||||
# Read-only: every per-node flag is False, and
|
||||
# `capabilities.writable` tells the UI why, once.
|
||||
can_add_tracks=False,
|
||||
can_reorder=False,
|
||||
can_rename=False,
|
||||
can_delete=False,
|
||||
can_contain_children=kind == "folder",
|
||||
)
|
||||
parent = str(getattr(r, "playlist_id_parent", 0) or 0)
|
||||
parents[node_id] = "root" if parent in ("0", "", "None") else parent
|
||||
|
||||
roots: list[PlaylistNode] = []
|
||||
for node_id, node in nodes.items():
|
||||
parent = nodes.get(parents.get(node_id, "root"))
|
||||
if parent is None:
|
||||
roots.append(node)
|
||||
else:
|
||||
parent.children.append(node)
|
||||
return roots
|
||||
|
||||
def playlist_entries(self, node_id: str) -> list[str] | None:
|
||||
ids = self._store.playlist_song_ids(node_id)
|
||||
return ids if ids or self._is_playlist(node_id) else None
|
||||
|
||||
def playlist_tracks(self, node_id: str) -> list[Track] | None:
|
||||
keys = self.playlist_entries(node_id)
|
||||
if keys is None:
|
||||
return None
|
||||
return [t for k in keys if (t := self._index.get(k)) is not None]
|
||||
|
||||
def _is_playlist(self, node_id: str) -> bool:
|
||||
return any(str(getattr(r, "playlist_id", "")) == str(node_id) for r in self._store.playlists())
|
||||
|
||||
# ---- audio / paths ----------------------------------------------------
|
||||
def audio_path(self, track_id: str):
|
||||
return self._store.audio_path(track_id)
|
||||
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None:
|
||||
"""Ignored: a drive's paths are relative to wherever it is mounted.
|
||||
|
||||
Path remapping exists because a desktop library stores absolute paths
|
||||
that go stale when music moves. A OneLibrary drive stores everything
|
||||
relative to its own root, so it is self-contained by construction and
|
||||
there is nothing for a mapping to fix.
|
||||
"""
|
||||
return None
|
||||
|
||||
def unresolved_path_groups(self) -> list:
|
||||
"""None, ever: a drive's paths are relative to its own mount point."""
|
||||
return []
|
||||
|
||||
def set_session_mappings(self, mappings: list[PathMapping]) -> None:
|
||||
return None
|
||||
|
||||
def path_prefix_suggestions(self) -> dict:
|
||||
paths = self._store.all_audio_paths()
|
||||
primary = common_dir_prefix(paths)
|
||||
return {
|
||||
"primary": primary,
|
||||
"groups": [{"prefix": primary, "count": len(paths)}] if primary else [],
|
||||
}
|
||||
|
||||
def remap_preview(self, mapping: PathMapping) -> dict:
|
||||
paths = [Path(p) for p in self._store.all_audio_paths()]
|
||||
return {"total": len(paths), "matched": 0, "existing": 0, "samples": []}
|
||||
|
||||
def remap_locations(self, mapping: PathMapping) -> dict[str, str]:
|
||||
raise Unsupported(self._readonly_reason("Rewriting stored paths"))
|
||||
|
||||
# ---- save -------------------------------------------------------------
|
||||
@property
|
||||
def dirty(self) -> bool:
|
||||
return False
|
||||
|
||||
def save(self):
|
||||
raise Unsupported(self._readonly_reason("Saving"))
|
||||
|
||||
def snapshot(self) -> bytes:
|
||||
raise Unsupported("OneLibrary drives are not versioned by Konduktor")
|
||||
|
||||
# ---- commands: all refused -------------------------------------------
|
||||
def _readonly_reason(self, what: str) -> str:
|
||||
return f"{what} is not supported yet for OneLibrary drives."
|
||||
|
||||
def _refuse(self, what: str):
|
||||
raise Unsupported(self._readonly_reason(what))
|
||||
|
||||
def add_tracks(self, items: list, *, checkpoint=None) -> list[str]:
|
||||
self._refuse("Adding tracks")
|
||||
|
||||
def remove_tracks(self, track_ids: list[str]) -> int:
|
||||
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._refuse("Editing track metadata")
|
||||
|
||||
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
|
||||
self._refuse("Editing cover art")
|
||||
|
||||
def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
|
||||
return self._store.cover_art(track_id)
|
||||
|
||||
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
|
||||
self._refuse("Creating playlists")
|
||||
|
||||
def create_folder(self, name: str, parent_id: str | None = None) -> str:
|
||||
self._refuse("Creating playlist folders")
|
||||
|
||||
def rename_playlist(self, node_id: str, name: str) -> None:
|
||||
self._refuse("Renaming playlists")
|
||||
|
||||
def delete_playlist(self, node_id: str) -> None:
|
||||
self._refuse("Deleting playlists")
|
||||
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
|
||||
self._refuse("Editing playlists")
|
||||
|
||||
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._refuse("Editing cues")
|
||||
|
||||
def set_cue_color(self, track_id: str, slot: int, color: str | None) -> TrackCues:
|
||||
self._refuse("Editing cues")
|
||||
|
||||
def delete_cue(self, track_id: str, slot: int) -> TrackCues:
|
||||
self._refuse("Deleting cues")
|
||||
|
||||
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues:
|
||||
self._refuse("Placing cues")
|
||||
|
||||
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> TrackCues:
|
||||
self._refuse("Editing the beatgrid")
|
||||
|
||||
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> TrackCues:
|
||||
self._refuse("Editing the beatgrid")
|
||||
|
||||
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> TrackCues:
|
||||
self._refuse("Editing the beatgrid")
|
||||
|
||||
def delete_grid_marker(self, track_id: str, index: int) -> TrackCues:
|
||||
self._refuse("Editing the beatgrid")
|
||||
|
||||
def replace_grid(self, track_id: str, markers: list) -> TrackCues:
|
||||
self._refuse("Editing the beatgrid")
|
||||
|
||||
def set_analysed_grid(self, track_id: str, markers: list) -> TrackCues:
|
||||
self._refuse("Editing the beatgrid")
|
||||
|
||||
def delete_grid(self, track_id: str) -> TrackCues:
|
||||
self._refuse("Deleting the beatgrid")
|
||||
|
||||
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues:
|
||||
raise Unsupported("OneLibrary has no beatgrid lock")
|
||||
@@ -0,0 +1,65 @@
|
||||
"""A OneLibrary beatgrid -> the generic marker list.
|
||||
|
||||
**The beatgrid is not in the database.** `exportLibrary.db` has no grid table at
|
||||
all — `content.bpmx100` is a single display tempo — and the real grid is the
|
||||
`PQTZ` tag of the track's ANLZ `.DAT`, holding EVERY BEAT explicitly. That is the
|
||||
same arrangement, and the same tag, as a desktop Rekordbox library: a drive is
|
||||
exported from one, and rekordbox regenerates the analysis files rather than
|
||||
inventing a new format for them.
|
||||
|
||||
Verified end to end on a track whose flexible grid Konduktor itself had written
|
||||
into `master.db`: exporting it to a OneLibrary drive preserved both tempo
|
||||
segments exactly (128.00 BPM to 60 s, then 90.00 BPM), so multi-tempo grids
|
||||
survive the whole chain and the marker list is the right generic shape.
|
||||
|
||||
The collapse rule is shared with the Rekordbox adapter deliberately rather than
|
||||
copied. Two implementations of "when is this a new marker?" would be free to
|
||||
drift apart by a rounding tolerance, and a drifting grid is a silent corruption
|
||||
rather than a visible bug. If a third AlphaTheta-format adapter ever appears,
|
||||
this and `rekordbox.beatgrid` should be promoted to one shared ANLZ module; the
|
||||
import direction here is the cheapest way to stay honest until then.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from ...core.model import GridMarker
|
||||
from ..rekordbox.beatgrid import BPM_EPSILON, markers_from_beats # noqa: F401
|
||||
|
||||
__all__ = ["BPM_EPSILON", "markers_from_beats", "beats_from_pqtz", "markers_from_anlz"]
|
||||
|
||||
|
||||
def beats_from_pqtz(anlz) -> tuple[list[float], list[float], list[int]] | None:
|
||||
"""Per-beat ``(times_sec, bpms, beat_in_bar)`` from a parsed ANLZ file's `PQTZ` tag.
|
||||
|
||||
Returns None when the file has no `PQTZ` — which is a real state, not an
|
||||
error: rekordbox analyses one-shot samples too, and gives them an analysis
|
||||
file with no beatgrid in it.
|
||||
|
||||
`PQTZ` stores time in milliseconds and tempo in hundredths of a BPM.
|
||||
"""
|
||||
for tag in getattr(anlz, "tags", []):
|
||||
if tag.type != "PQTZ":
|
||||
continue
|
||||
entries = getattr(getattr(tag.struct, "content", None), "entries", None)
|
||||
if not entries:
|
||||
return None
|
||||
times: list[float] = []
|
||||
bpms: list[float] = []
|
||||
beats: list[int] = []
|
||||
for e in entries:
|
||||
try:
|
||||
time, tempo, beat = int(e.time) / 1000.0, int(e.tempo) / 100.0, int(e.beat)
|
||||
except (AttributeError, TypeError, ValueError):
|
||||
continue
|
||||
times.append(time)
|
||||
bpms.append(tempo)
|
||||
beats.append(beat)
|
||||
return (times, bpms, beats) if times else None
|
||||
return None
|
||||
|
||||
|
||||
def markers_from_anlz(anlz) -> list[GridMarker]:
|
||||
"""The generic marker list for a parsed ANLZ file."""
|
||||
grid = beats_from_pqtz(anlz)
|
||||
if grid is None:
|
||||
return []
|
||||
return markers_from_beats(*grid)
|
||||
@@ -0,0 +1,95 @@
|
||||
"""What a OneLibrary drive can persist: nothing, for now.
|
||||
|
||||
`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.
|
||||
|
||||
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 **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.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from ...core.capabilities import (
|
||||
Capabilities,
|
||||
CueCapabilities,
|
||||
GridCapabilities,
|
||||
PlaylistCapabilities,
|
||||
SaveCapabilities,
|
||||
TrackCapabilities,
|
||||
)
|
||||
|
||||
# Pads A-H. Unlike `djmdCue.Kind`, the ANLZ slot number is a dense 1-based index,
|
||||
# so the bank really is 1..8 (see `cues.py`).
|
||||
HOTCUE_SLOTS = 8
|
||||
|
||||
|
||||
def capabilities_for(device_name: str | None = None, version: str | None = None) -> Capabilities:
|
||||
return Capabilities(
|
||||
platform="onelibrary",
|
||||
version=version,
|
||||
# A roadmap gap, not a protective refusal — the UI words the two
|
||||
# differently, which is the whole reason `readonly_cause` exists.
|
||||
writable=False,
|
||||
readonly_cause="platform_incomplete",
|
||||
cues=CueCapabilities(
|
||||
editable=False,
|
||||
hotcue_slots=HOTCUE_SLOTS,
|
||||
slot_labels="letter",
|
||||
# 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=["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, 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
|
||||
editable_fields=[],
|
||||
media_kinds=["audio", "stem"],
|
||||
# `artwork` gates EDITING, and a drive is read-only here. Reading
|
||||
# works: `store.cover_art` follows `content.image_id` -> `image.path`.
|
||||
artwork=False,
|
||||
artwork_note=None,
|
||||
),
|
||||
playlists=PlaylistCapabilities(
|
||||
folders=True, # `playlist.attribute` 1, nested via playlist_id_parent
|
||||
# A drive carries no smart playlists: rekordbox resolves them to
|
||||
# static lists on export, because a CDJ cannot evaluate rules.
|
||||
smart="none",
|
||||
reorder=False,
|
||||
),
|
||||
save=SaveCapabilities(
|
||||
app_name="OneLibrary",
|
||||
library_label=device_name or "exportLibrary.db",
|
||||
# Nothing is written, so nothing can be overwritten by another app.
|
||||
overwrite_risk="none",
|
||||
# A drive is a database plus N analysis files plus the audio itself,
|
||||
# so there is no single blob that IS the library — the same reason
|
||||
# Rekordbox libraries are not versioned.
|
||||
history=False,
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,188 @@
|
||||
"""OneLibrary cues: read from the ANLZ analysis files, not the database.
|
||||
|
||||
**The `cue` table is not where a drive's cues are.** It exists in the schema —
|
||||
and has columns for everything a cue needs — but rekordbox exports an empty one
|
||||
and puts the cues in the track's ANLZ file instead. Measured on a real rekordbox
|
||||
7 export of a track carrying four hot cues and a looped memory cue: the `cue`
|
||||
table held zero rows and every cue was present in the analysis files. The table
|
||||
appears to be for hardware writing edits BACK to the drive, which is a different
|
||||
direction than this adapter reads.
|
||||
|
||||
Two tags carry cues, and they are not equivalent:
|
||||
|
||||
* **`PCOB`** is the original list, and it is SPLIT BY PAD. The `.DAT` holds
|
||||
only hot cues 1-3 — the three pads the earliest CDJs had — and the `.EXT`
|
||||
holds 4 and up. Reading only the `.DAT` silently loses pads D-H.
|
||||
* **`PCO2`** is the extended list in the `.EXT`, and it holds the COMPLETE set
|
||||
in one tag plus three things `PCOB` has nowhere to put: an RGB colour, a
|
||||
comment, and the loop length expressed in BEATS.
|
||||
|
||||
So `PCO2` is preferred and `PCOB` is the fallback for a drive old enough not to
|
||||
have one. Both are merged across files before that choice is made, because "the
|
||||
complete list" must not depend on which file happened to be read.
|
||||
|
||||
**Slot numbering differs from `master.db` and this is the trap.** In the desktop
|
||||
database a hot cue's `djmdCue.Kind` is a sparse bank that SKIPS 4 (`1,2,3,5,…`
|
||||
for pads A-H). In ANLZ, `hot_cue` is a plain dense 1-based index (1=A, 2=B, …),
|
||||
and `0` means the cue is a memory cue rather than a pad. The two were aligned
|
||||
against each other on one track: `Kind` 1/2/3/5 at 40.000 s, 18.773 s, 90.667 s
|
||||
and 120.000 s came out as `hot_cue` 1/2/3/4 at exactly the same times. Carry the
|
||||
Rekordbox adapter's mapping over here unchanged and every cue from pad D onward
|
||||
lands one pad too far along.
|
||||
|
||||
Times are MILLISECONDS here, where the desktop database counts frames at 150 fps.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from ...core.model import CuePoint
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
# `loop_time` when a cue is not a loop. Stored as an unsigned 32-bit -1 rather
|
||||
# than 0, so a plain falsiness test would read it as "a loop ending at zero".
|
||||
NO_LOOP = 0xFFFFFFFF
|
||||
|
||||
# `hot_cue` for a cue that sits in no pad bank, i.e. a memory cue.
|
||||
MEMORY_SLOT = 0
|
||||
|
||||
# PCO2/PCOB entry kinds. The value is the same in both tags; 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:
|
||||
"""PCOB gives an enum, PCO2 an int — one number out of either."""
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
return ENTRY_CUE
|
||||
|
||||
|
||||
def _color(entry) -> str | None:
|
||||
"""A cue's colour as ``#RRGGBB``, when the tag carries one.
|
||||
|
||||
Only `PCO2` stores RGB. A cue with no colour set stores 0,0,0 — which is a
|
||||
real black in principle, but rekordbox uses it as "unset" and shows such a
|
||||
cue in the default colour, so it is reported as no colour rather than as
|
||||
black. Memory cues in the reference export are exactly this case.
|
||||
"""
|
||||
try:
|
||||
r, g, b = int(entry.color_red), int(entry.color_green), int(entry.color_blue)
|
||||
except (AttributeError, TypeError, ValueError):
|
||||
return None
|
||||
if (r, g, b) == (0, 0, 0):
|
||||
return None
|
||||
return f"#{r:02X}{g:02X}{b:02X}"
|
||||
|
||||
|
||||
def _to_cue(entry, *, with_color: bool) -> CuePoint | None:
|
||||
"""One ANLZ cue entry as a generic `CuePoint`, or None if unreadable."""
|
||||
try:
|
||||
hot_cue = int(entry.hot_cue)
|
||||
start_ms = int(entry.time)
|
||||
except (AttributeError, TypeError, ValueError):
|
||||
return None
|
||||
|
||||
loop_ms = getattr(entry, "loop_time", NO_LOOP)
|
||||
try:
|
||||
loop_ms = int(loop_ms)
|
||||
except (TypeError, ValueError):
|
||||
loop_ms = NO_LOOP
|
||||
|
||||
is_loop = _entry_kind(getattr(entry, "type", ENTRY_CUE)) == ENTRY_LOOP
|
||||
length = 0.0
|
||||
if is_loop and loop_ms != NO_LOOP and loop_ms > start_ms:
|
||||
length = (loop_ms - start_ms) / 1000.0
|
||||
|
||||
# hot_cue 0 is the memory list; 1..N are the pads, dense and 1-based, so the
|
||||
# generic 0-based slot is simply one less.
|
||||
role = "memory" if hot_cue == MEMORY_SLOT else "hotcue"
|
||||
slot = None if role == "memory" else hot_cue - 1
|
||||
|
||||
comment = getattr(entry, "comment", None)
|
||||
return CuePoint(
|
||||
name=(str(comment) or None) if comment else None,
|
||||
type="loop" if length > 0 else "cue",
|
||||
role=role,
|
||||
start=start_ms / 1000.0,
|
||||
length=length,
|
||||
slot=slot,
|
||||
color=_color(entry) if with_color else None,
|
||||
# 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,
|
||||
)
|
||||
|
||||
|
||||
def _entries(anlz, tag_type: str) -> list:
|
||||
"""Every entry of every `tag_type` tag in one parsed ANLZ file.
|
||||
|
||||
A file carries the tag twice — once for hot cues and once for memory cues —
|
||||
so both are collected and the entry's own `hot_cue` decides which it is.
|
||||
That is more robust than trusting the container's type field, which is
|
||||
absent on some tags in real files.
|
||||
"""
|
||||
out: list = []
|
||||
for tag in getattr(anlz, "tags", []):
|
||||
if tag.type != tag_type:
|
||||
continue
|
||||
content = getattr(tag.struct, "content", None)
|
||||
out.extend(getattr(content, "entries", None) or [])
|
||||
return out
|
||||
|
||||
|
||||
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.
|
||||
"""
|
||||
files = [f for f in (dat, ext) if f is not None]
|
||||
if not files:
|
||||
return []
|
||||
|
||||
# PCO2 first: it is the complete list and the only one with colour, comment
|
||||
# and beat-denominated loops. It lives only in the .EXT.
|
||||
pco2: list = []
|
||||
for f in files:
|
||||
pco2.extend(_entries(f, "PCO2"))
|
||||
if pco2:
|
||||
cues = [c for e in pco2 if (c := _to_cue(e, with_color=True)) is not None]
|
||||
else:
|
||||
# Fallback: merge PCOB across BOTH files. The .DAT holds pads 1-3 and the
|
||||
# .EXT the rest, so either alone is an incomplete bank.
|
||||
pcob: list = []
|
||||
for f in files:
|
||||
pcob.extend(_entries(f, "PCOB"))
|
||||
cues = [c for e in pcob if (c := _to_cue(e, with_color=False)) is not None]
|
||||
|
||||
return _dedupe(cues)
|
||||
|
||||
|
||||
def _dedupe(cues: list[CuePoint]) -> list[CuePoint]:
|
||||
"""Collapse the same cue appearing in more than one tag or file.
|
||||
|
||||
Identity is (role, slot, start) 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[str, int | None, int]] = set()
|
||||
out: list[CuePoint] = []
|
||||
for c in cues:
|
||||
key = (c.role, c.slot, round(c.start * 1000))
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
out.append(c)
|
||||
out.sort(key=lambda c: (c.start, c.slot if c.slot is not None else -1))
|
||||
return out
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Find OneLibrary drives that are plugged in right now.
|
||||
|
||||
This is the one platform whose libraries have no fixed location: Traktor and
|
||||
Rekordbox each keep theirs at a known per-OS path, but a OneLibrary library is
|
||||
whatever USB stick happens to be mounted. So detection scans mount points rather
|
||||
than probing a list of known paths, and what it finds legitimately changes
|
||||
between two calls a second apart.
|
||||
|
||||
Only the mount ROOTS are scanned, never their contents recursively. A drive can
|
||||
hold tens of thousands of files, the database is at a fixed place within it, and
|
||||
walking a slow USB stick at startup is exactly the kind of thing that makes an
|
||||
app feel broken.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
# Where this OS mounts drives is not adapter knowledge — the file browser needs
|
||||
# the same answer, and two scanners would drift. It grew here because this is
|
||||
# the platform whose libraries ARE drives; it lives in core now.
|
||||
from ...core.places import mount_points as _mount_points
|
||||
from .layout import DriveLayout
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def describe(path: Path) -> dict:
|
||||
"""A candidate record for a drive or database path, shaped for the picker."""
|
||||
path = Path(path)
|
||||
layout = DriveLayout.locate(path)
|
||||
database = layout.database if layout is not None else path
|
||||
exists = False
|
||||
try:
|
||||
exists = database.is_file()
|
||||
except OSError:
|
||||
pass
|
||||
# The drive's name is what a person recognises — "Hardy", not
|
||||
# "exportLibrary.db" — so the mount point supplies the label.
|
||||
root_name = layout.root.name if layout is not None else path.name
|
||||
return {
|
||||
"path": str(database),
|
||||
"label": f"OneLibrary — {root_name}" if root_name else "OneLibrary",
|
||||
"version": None,
|
||||
"modified": (database.stat().st_mtime if exists else None),
|
||||
"exists": exists,
|
||||
}
|
||||
|
||||
|
||||
def detect_libraries() -> list[dict]:
|
||||
"""Every mounted drive that carries a OneLibrary database, newest first."""
|
||||
found: list[dict] = []
|
||||
seen: set[str] = set()
|
||||
for root in _mount_points():
|
||||
layout = DriveLayout.locate(root)
|
||||
if layout is None:
|
||||
continue
|
||||
try:
|
||||
key = str(layout.database.resolve())
|
||||
except OSError:
|
||||
continue
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
found.append(describe(layout.root))
|
||||
found.sort(key=lambda c: c["modified"] or 0.0, reverse=True)
|
||||
return found
|
||||
@@ -0,0 +1,105 @@
|
||||
"""Opening OneLibrary drives: recognition and discovery."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
from . import discovery
|
||||
from .adapter import OneLibraryAdapter
|
||||
from .layout import DriveLayout
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class OneLibraryDriver:
|
||||
platform = "onelibrary"
|
||||
display_name = "OneLibrary"
|
||||
# This platform's libraries live on plugged-in drives rather than at a
|
||||
# fixed path, so `detect()` genuinely changes between calls and the app
|
||||
# offers them as IMPORT SOURCES. Declared rather than inferred from the
|
||||
# platform name, so a future Serato-on-a-stick needs no change upstream.
|
||||
removable = True
|
||||
suffixes = (".db",)
|
||||
library_label = "exportLibrary.db"
|
||||
# What a user PICKS is the mount point, not the database buried three levels
|
||||
# down inside it — `DriveLayout.locate()` accepts either, but only one of
|
||||
# them is a thing anybody browses to. The file browser reads this to offer
|
||||
# folders rather than files.
|
||||
selects = "directory"
|
||||
|
||||
def can_open(self, path: Path) -> bool:
|
||||
"""Recognise a OneLibrary drive, by layout and then by schema.
|
||||
|
||||
Both halves are needed. The layout check alone would accept any file
|
||||
called ``exportLibrary.db``; the schema check alone cannot run on a
|
||||
directory, and a drive is what a user actually picks.
|
||||
|
||||
It must also not collide with the Rekordbox driver, which probes for
|
||||
`master.db`. It cannot: both files are SQLCipher databases with no
|
||||
readable header, but they use DIFFERENT keys, so each driver's decrypt
|
||||
simply fails on the other's file. The table probe then makes it explicit
|
||||
rather than leaving the two relying on a key mismatch.
|
||||
"""
|
||||
layout = DriveLayout.locate(Path(path))
|
||||
if layout is None:
|
||||
return False
|
||||
return self._has_onelibrary_schema(layout.database)
|
||||
|
||||
@staticmethod
|
||||
def _has_onelibrary_schema(path: Path) -> bool:
|
||||
try:
|
||||
import sqlcipher3.dbapi2 as sqlcipher
|
||||
from pyrekordbox.devicelib_plus.database import BLOB
|
||||
from pyrekordbox.utils import deobfuscate
|
||||
except ImportError: # pragma: no cover — dependency missing
|
||||
return False
|
||||
con = None
|
||||
try:
|
||||
con = sqlcipher.connect(str(path))
|
||||
con.execute(f"PRAGMA key='{deobfuscate(BLOB)}'")
|
||||
# `content` is too generic a name to trust on its own, so the probe
|
||||
# asks for a pair only this schema has together.
|
||||
rows = con.execute(
|
||||
"SELECT name FROM sqlite_master WHERE type='table' "
|
||||
"AND name IN ('content','hotCueBankList')"
|
||||
).fetchall()
|
||||
return len(rows) == 2
|
||||
except Exception: # noqa: BLE001 — wrong key or not a database
|
||||
return False
|
||||
finally:
|
||||
if con is not None:
|
||||
try:
|
||||
con.close()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
def open(self, path: Path) -> OneLibraryAdapter:
|
||||
return OneLibraryAdapter(path)
|
||||
|
||||
def detect(self) -> list[dict]:
|
||||
return discovery.detect_libraries()
|
||||
|
||||
def describe(self, path: Path) -> dict:
|
||||
return discovery.describe(path)
|
||||
|
||||
def display_name_for(self, path: Path) -> str:
|
||||
"""What to call this library on screen: the DRIVE's name.
|
||||
|
||||
The filename is not a stable answer here. A OneLibrary library can be
|
||||
opened by its mount point OR by the database three levels inside it —
|
||||
`DriveLayout.locate()` accepts both on purpose — so the same stick would
|
||||
be "Hardy" opened one way and "exportLibrary.db" opened the other.
|
||||
"""
|
||||
layout = DriveLayout.locate(Path(path))
|
||||
return layout.root.name if layout is not None else Path(path).name
|
||||
|
||||
def restore(self, path: Path, data: bytes) -> None:
|
||||
"""Not supported: a drive is a database plus analysis files plus audio.
|
||||
|
||||
`capabilities.save.history` is False for the same reason, so nothing
|
||||
should reach this.
|
||||
"""
|
||||
raise NotImplementedError(
|
||||
"Konduktor does not version OneLibrary drives: the library is a "
|
||||
"database, N analysis files and the audio itself."
|
||||
)
|
||||
@@ -0,0 +1,468 @@
|
||||
"""Writing a OneLibrary USB drive from nothing.
|
||||
|
||||
The export target that matters most for a DJ: a stick CDJ-class hardware reads.
|
||||
|
||||
## What a drive is
|
||||
|
||||
The destination folder IS the drive root. Three things go in it:
|
||||
|
||||
<root>/PIONEER/rekordbox/exportLibrary.db the library (SQLCipher)
|
||||
<root>/PIONEER/USBANLZ/P0xx/xxxxxxxx/ANLZ0000.{DAT,EXT} per-track analysis
|
||||
<root>/… the audio, already copied
|
||||
|
||||
Audio is already on disk when this runs, laid out by the runner mirroring the
|
||||
source tree. Every path the database stores is **drive-relative with a leading
|
||||
slash** — `/House/track.mp3` — which is not a host path, and the reader's
|
||||
`DriveLayout.resolve()` is what joins it back to a mount point.
|
||||
|
||||
## What could not be reused, and why
|
||||
|
||||
`master.db`'s schema comes free from `pyrekordbox`'s ORM. This one has no ORM, so
|
||||
the DDL is the checked-in `fixtures/onelibrary/schema.sql` — 22 tables extracted
|
||||
from a real rekordbox 7 export, which is also what the read tests run against.
|
||||
|
||||
Cues are **not** in the `cue` table: rekordbox exports it empty and puts them in
|
||||
the analysis files. So `anlz_writer` builds those, with ANLZ's own **dense
|
||||
1-based** `hot_cue` numbering — not `master.db`'s sparse bank that skips 4.
|
||||
|
||||
## Deliberately not written
|
||||
|
||||
`PWAV`/`PWV2`-`PWV7` waveform tags, and the `cue` table's eight MPEG seek
|
||||
columns. Both are documented unknowns (see the OneLibrary handoff §7): a CDJ
|
||||
draws its waveform from those tags and seeks VBR MP3s with those columns, and
|
||||
whether their absence is unplayable, ugly or fine has never been measured. A
|
||||
guess here fails in a club rather than at a desk, so they are left out and said
|
||||
so rather than invented.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
|
||||
from ...core.cue_colors import effective_color
|
||||
from ..rekordbox import anlz_writer as W
|
||||
from ..rekordbox import artwork, palette, timebase
|
||||
from ..rekordbox.beatgrid import beats_from_markers
|
||||
from ..rekordbox.projection import render_key
|
||||
from .capabilities import capabilities_for
|
||||
from .layout import DB_SUBPATH
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
SCHEMA = Path(__file__).resolve().parents[3] / "fixtures" / "onelibrary" / "schema.sql"
|
||||
#: rekordbox's scaffolding rows — browse menu items, categories, sort columns,
|
||||
#: the colour palette — copied from a real export. See the file's header.
|
||||
SEED = SCHEMA.with_name("seed.sql")
|
||||
|
||||
#: rekordbox writes this in `property.dbVersion` on a real export.
|
||||
DB_VERSION = "1000"
|
||||
#: Seen on every track of a real export; semantics undocumented, copied as-is.
|
||||
ANALYSED_BITS = 41
|
||||
#: `content.contentLink`, as rekordbox 7 writes it beside `analysedBits` 41 (a
|
||||
#: re-analysed track carried 1902336 beside 105; what the bits mean is unknown).
|
||||
#: NOT optional: measured by blanking it on one track of a rekordbox-written
|
||||
#: stick — that row's song-list preview fell back to plain blue and gained a "?"
|
||||
#: beside CUE, exactly as every row of Konduktor's exports did while it was NULL.
|
||||
#: `masterDbId`/`masterContentId` were cleared the same way and changed nothing.
|
||||
CONTENT_LINK = 788224
|
||||
|
||||
OTHER_PLAYLIST = "Other"
|
||||
|
||||
|
||||
def _drive_relative(path: Path, root: Path) -> str:
|
||||
"""`/House/track.mp3` — drive-relative, WITH the leading slash.
|
||||
|
||||
The slash is not a host root. Joining one of these naively discards the
|
||||
mount point and silently yields a path that looks like an empty drive.
|
||||
"""
|
||||
return "/" + path.relative_to(root).as_posix()
|
||||
|
||||
|
||||
def _anlz_dir(drive_relative: str) -> str:
|
||||
"""`/PIONEER/USBANLZ/P0xx/xxxxxxxx` for a track.
|
||||
|
||||
rekordbox derives these two levels from a hash whose algorithm is not
|
||||
published. It does not need to match: the database stores the resulting path
|
||||
in `content.analysisDataFilePath` and that column is what a player follows.
|
||||
So this derives its own stable value in the same SHAPE, which keeps a drive
|
||||
recognisable to a human without pretending to reproduce rekordbox's scheme.
|
||||
"""
|
||||
digest = hashlib.sha1(drive_relative.encode("utf-8")).hexdigest().upper()
|
||||
return f"/PIONEER/USBANLZ/P0{digest[:2]}/{digest[2:10]}"
|
||||
|
||||
|
||||
class OneLibraryExporter:
|
||||
platform = "onelibrary"
|
||||
menu_order = 10
|
||||
#: Relative to the drive root, which is what the destination folder is.
|
||||
library_filename = str(Path("PIONEER") / DB_SUBPATH)
|
||||
#: A CDJ looks for `PIONEER/` at the root of the stick and nowhere else.
|
||||
drive_root = True
|
||||
|
||||
def capabilities(self):
|
||||
"""What a drive can hold — no device, no path, no library to read.
|
||||
|
||||
`writable` is overridden to True. The adapter's own set says False
|
||||
because Konduktor cannot EDIT a plugged-in drive in place; an export
|
||||
target is a different question, and it is one Konduktor can now answer
|
||||
yes to. Leaving the adapter's answer here would have the UI report that
|
||||
the thing it just wrote cannot be written.
|
||||
"""
|
||||
caps = capabilities_for()
|
||||
# An exported drive CARRIES artwork (`_write_art`); the adapter's False
|
||||
# means "cannot edit a plugged-in drive's art", a different question.
|
||||
return caps.model_copy(update={
|
||||
"writable": True, "readonly_cause": None,
|
||||
"tracks": caps.tracks.model_copy(update={"artwork": True}),
|
||||
})
|
||||
|
||||
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
|
||||
import sqlcipher3.dbapi2 as sqlcipher
|
||||
from pyrekordbox.devicelib_plus.database import BLOB
|
||||
from pyrekordbox.utils import deobfuscate
|
||||
|
||||
root = Path(destination)
|
||||
library = root / "PIONEER" / DB_SUBPATH
|
||||
library.parent.mkdir(parents=True, exist_ok=True)
|
||||
# SQLCipher will not re-key an existing file — and the WAL and shared
|
||||
# memory files beside it must go too. rekordbox leaves both on a stick
|
||||
# it has mounted, and SQLite REPLAYS a leftover WAL into whatever
|
||||
# database it finds, so a fresh library would open with the old one's
|
||||
# pages written over it.
|
||||
for stale in (library, *(library.with_name(library.name + s) for s in ("-wal", "-shm"))):
|
||||
if stale.exists():
|
||||
stale.unlink()
|
||||
|
||||
extra: list[Path] = []
|
||||
con = sqlcipher.connect(str(library))
|
||||
try:
|
||||
# The same universal key every vendor's drive uses — a OneLibrary
|
||||
# stick is readable by any of them, which is the point of it.
|
||||
con.execute(f"PRAGMA key='{deobfuscate(BLOB)}'")
|
||||
con.executescript(SCHEMA.read_text())
|
||||
con.executescript(SEED.read_text(encoding="utf-8"))
|
||||
extra += self._fill(con, payload, root)
|
||||
con.commit()
|
||||
finally:
|
||||
con.close()
|
||||
return WrittenLibrary(library=library, extra=extra)
|
||||
|
||||
# ---- the database --------------------------------------------------------
|
||||
|
||||
def _fill(self, con, payload: ExportPayload, root: Path) -> list[Path]:
|
||||
lookups = {name: {} for name in ("artist", "album", "genre", "label", "key")}
|
||||
# Image ids are handed out in track order, one per track that HAS art —
|
||||
# rekordbox does not share an image between tracks, even identical ones.
|
||||
lookups["image"] = {"next": 0}
|
||||
written: list[Path] = []
|
||||
by_source: dict[str, int] = {}
|
||||
|
||||
total = len(payload.tracks)
|
||||
for n, item in enumerate(payload.tracks, start=1):
|
||||
# Each track is DECODED for its waveform, so this loop is the slow
|
||||
# part of the write — report it, and let a cancel land between tracks.
|
||||
payload.checkpoint(f"Analysing {item.track.title or item.destination.name} ({n}/{total})", step=n, of=total)
|
||||
by_source[item.source_id] = n
|
||||
written += self._write_track(con, n, item, root, lookups)
|
||||
|
||||
self._write_playlists(con, payload, by_source)
|
||||
con.execute(
|
||||
"INSERT INTO property (deviceName, dbVersion, numberOfContents, "
|
||||
"createdDate, backGroundColorType, myTagMasterDBID) VALUES (?,?,?,?,?,?)",
|
||||
(payload.name, DB_VERSION, len(payload.tracks),
|
||||
date.today().isoformat(), 0, 0),
|
||||
)
|
||||
return written
|
||||
|
||||
@staticmethod
|
||||
def _lookup(con, table: str, cache: dict, name: str | None) -> int | None:
|
||||
"""Find-or-create a row in one of the name tables."""
|
||||
if not name:
|
||||
return None
|
||||
if name in cache:
|
||||
return cache[name]
|
||||
column = f"{table}_id"
|
||||
row = con.execute(f"SELECT {column} FROM {table} WHERE name = ?", (name,)).fetchone()
|
||||
if row:
|
||||
cache[name] = row[0]
|
||||
return row[0]
|
||||
cur = con.execute(f"INSERT INTO {table} (name) VALUES (?)", (name,))
|
||||
cache[name] = cur.lastrowid
|
||||
return cur.lastrowid
|
||||
|
||||
def _write_track(self, con, content_id: int, item: ExportTrack,
|
||||
root: Path, lookups: dict) -> list[Path]:
|
||||
track = item.track
|
||||
rel = _drive_relative(item.destination, root)
|
||||
anlz_rel = f"{_anlz_dir(rel)}/ANLZ0000.DAT"
|
||||
|
||||
try:
|
||||
size = item.destination.stat().st_size
|
||||
except OSError:
|
||||
size = 0
|
||||
sample_rate, bit_depth = _audio_format(item.destination)
|
||||
image_id, art_files = self._write_art(con, item, root, lookups["image"])
|
||||
|
||||
con.execute(
|
||||
"INSERT INTO content (content_id, title, titleForSearch, bpmx100, length, "
|
||||
"trackNo, artist_id_artist, album_id, genre_id, label_id, key_id, image_id, "
|
||||
"djComment, rating, releaseDate, dateAdded, path, fileName, fileSize, "
|
||||
"fileType, bitrate, bitDepth, samplingRate, isHotCueAutoLoadOn, "
|
||||
"isKuvoDeliverStatusOn, masterDbId, masterContentId, "
|
||||
"analysisDataFilePath, analysedBits, contentLink, hasModified, cueUpdateCount, "
|
||||
"analysisDataUpdateCount, informationUpdateCount) "
|
||||
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
|
||||
(
|
||||
content_id, track.title, (track.title or "").lower(),
|
||||
int(round((track.bpm or 0) * 100)) or None, track.length,
|
||||
None,
|
||||
self._lookup(con, "artist", lookups["artist"], track.artist),
|
||||
self._lookup(con, "album", lookups["album"], track.album),
|
||||
self._lookup(con, "genre", lookups["genre"], track.genre),
|
||||
self._lookup(con, "label", lookups["label"], track.label),
|
||||
# NOT `track.key` — that is the SOURCE platform's notation, and
|
||||
# writing Traktor's "10m" into a Pioneer library shows "10m"
|
||||
# where the deck expects "Cm". Rendered from the parsed wheel.
|
||||
self._lookup(con, "key", lookups["key"],
|
||||
render_key(track.key_wheel, track.key_mode)),
|
||||
image_id,
|
||||
track.comment, track.rating or 0, track.release_date,
|
||||
date.today().isoformat(), rel, item.destination.name, size,
|
||||
# kbps, as every Pioneer library stores it; the generic model
|
||||
# carries bits per second.
|
||||
_file_type(item.destination), _kbps(track.bitrate),
|
||||
bit_depth, sample_rate, 1, 1, 0, content_id,
|
||||
anlz_rel, ANALYSED_BITS, CONTENT_LINK, 0, 0, 0, 0,
|
||||
),
|
||||
)
|
||||
return art_files + self._write_anlz(item, rel, root / anlz_rel.lstrip("/"))
|
||||
|
||||
# ---- artwork -------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _write_art(con, item: ExportTrack, root: Path, counter: dict) -> tuple[int | None, list[Path]]:
|
||||
"""One track's cover: four JPEGs and an `image` row, as rekordbox 7 writes.
|
||||
|
||||
`PIONEER/Artwork/00001/` holds `a<n>.jpg` / `a<n>_m.jpg` and a byte-
|
||||
identical `b<n>.jpg` / `b<n>_m.jpg` (80 and 240 px); `image.path` names the
|
||||
`b` file and `content.image_id` points at the row. rekordbox's own export
|
||||
writes both letters — the `a` pair presumably for the legacy `export.pdb`
|
||||
readers — so both are written here too.
|
||||
|
||||
Everything goes in folder `00001`. How rekordbox splits a large library
|
||||
across folders is not known (the reference export has 6 images); a single
|
||||
folder is what it demonstrably reads.
|
||||
"""
|
||||
if not item.art:
|
||||
return None, []
|
||||
jpegs = artwork.pioneer_jpegs(item.art[0])
|
||||
if jpegs is None:
|
||||
return None, []
|
||||
counter["next"] += 1
|
||||
n = counter["next"]
|
||||
folder = root / "PIONEER" / "Artwork" / "00001"
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
small, medium = jpegs
|
||||
files = []
|
||||
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 _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,
|
||||
which readers prefer — lives only in the `.EXT`.
|
||||
|
||||
**The `.DAT` must carry `PVBR` and the preview waveforms**, or rekordbox
|
||||
shows neither the grid nor the cues (see `anlz_writer`). The `.EXT` and
|
||||
`.2EX` waveforms only affect drawing: the song-list preview and the
|
||||
deck's scrolling waveform. Tag order is rekordbox's in each file:
|
||||
.DAT PPTH PVBR PQTZ PWAV PWV2 PCOB PCOB
|
||||
.EXT PPTH PWV3 PCOB PCOB PCO2 PCO2 PWV5 PWV4
|
||||
.2EX PPTH PWV7 PWV6 PWVC
|
||||
An undecodable file still gets the `.DAT` (with a flat preview) and the
|
||||
`.EXT` cue lists — its grid and cues must show — but no drawn waveforms.
|
||||
"""
|
||||
# rekordbox's clock runs ~25 ms behind the decoded audio on MP3/AAC (see
|
||||
# `timebase`): beats and cues are computed in the decoded time base and
|
||||
# shifted as they are packed, and the waveform frames are measured with
|
||||
# the same lead so they line up with the beats.
|
||||
off = timebase.offset(item.destination)
|
||||
measured = item.waveform(lead=off)
|
||||
# The DECODED length where there is one: `Track.length` is whole seconds
|
||||
# rounded down, and a grid expanded to it loses the track's last beat.
|
||||
beats = self._beats(item, measured.duration if measured else None)
|
||||
cues = self._cue_dicts(item, beats, off)
|
||||
if measured:
|
||||
previews = W.preview_tags(measured.columns.rms, measured.columns.brightness)
|
||||
ext_waves, two_ex = W.waveform_tags(measured.frames.bands)
|
||||
else:
|
||||
previews, ext_waves, two_ex = W.flat_preview_tags(), [], []
|
||||
|
||||
tags = [W.path_tag(rel), W.vbr_tag(W.mp3_samples(item.destination))]
|
||||
if beats:
|
||||
tags.append(W.beatgrid_tag([(n, bpm, timebase.to_pioneer(t, off))
|
||||
for n, bpm, t in beats]))
|
||||
tags += previews
|
||||
tags += W.cue_tags(cues, extended=False)
|
||||
ext = [W.path_tag(rel), *ext_waves[:1], *W.cue_tags(cues, extended=True), *ext_waves[1:]]
|
||||
written = [W.write_anlz(dat, tags), W.write_anlz(dat.with_suffix(".EXT"), ext)]
|
||||
if two_ex:
|
||||
written.append(W.write_anlz(dat.with_suffix(".2EX"), [W.path_tag(rel), *two_ex]))
|
||||
return written
|
||||
|
||||
@staticmethod
|
||||
def _beats(item: ExportTrack, duration: float | None = None) -> list[tuple[int, float, float]]:
|
||||
"""Every beat, expanded from the generic marker list.
|
||||
|
||||
A Pioneer grid has no tempo markers — it is a flat list of beats — so a
|
||||
flexible multi-tempo grid crosses by expansion here and is collapsed
|
||||
back by `markers_from_beats` on read. Both directions share one
|
||||
definition of where a tempo change starts.
|
||||
"""
|
||||
cues = item.cues
|
||||
if not cues or not cues.grid_markers:
|
||||
return []
|
||||
duration = (duration or float(item.track.length or 0)
|
||||
or (cues.grid_markers[-1].start + 60.0))
|
||||
nums, bpms, times = beats_from_markers(cues.grid_markers, duration)
|
||||
return list(zip(nums, bpms, times))
|
||||
|
||||
@staticmethod
|
||||
def _cue_dicts(item: ExportTrack, beats: list | None = None, off: float = 0.0) -> list[dict]:
|
||||
"""Generic cues in the shape `anlz_writer` packs.
|
||||
|
||||
Slot numbering is ANLZ's own: **dense 1-based**, 0 for a memory cue.
|
||||
The generic model's `slot` is 0-based, so every hot cue is +1. Reuse
|
||||
`master.db`'s sparse bank here and every cue from pad D lands one pad
|
||||
too far along.
|
||||
"""
|
||||
out: list[dict] = []
|
||||
for cue in (item.cues.cues if item.cues else []):
|
||||
is_loop = cue.type == "loop" or cue.length > 0
|
||||
# A hot cue carries what Konduktor SHOWS — stored colour, else the
|
||||
# type's (blue cue, green loop) — as a rekordbox palette CODE, which
|
||||
# is what rekordbox draws from; "unset" draws its own defaults. A
|
||||
# memory cue keeps rekordbox's own "unset".
|
||||
code, rgb = palette.code_for(cue.color if cue.role == "memory" else effective_color(cue))
|
||||
out.append({
|
||||
"hot_cue": 0 if cue.role == "memory" or cue.slot is None else cue.slot + 1,
|
||||
"kind": 2 if is_loop else 1,
|
||||
"time_ms": int(round(timebase.to_pioneer(cue.start, off) * 1000)),
|
||||
"loop_ms": (int(round(timebase.to_pioneer(cue.start + cue.length, off) * 1000))
|
||||
if is_loop else None),
|
||||
"rgb": rgb,
|
||||
"code": code,
|
||||
"beats": _loop_beats(cue.start, cue.length, beats or []) if is_loop else None,
|
||||
})
|
||||
return out
|
||||
|
||||
# ---- playlists -----------------------------------------------------------
|
||||
|
||||
def _write_playlists(self, con, payload: ExportPayload, by_source: dict) -> None:
|
||||
"""One folder named after the export, with the tree preserved under it.
|
||||
|
||||
`playlist` is a flat table with `playlist_id_parent`, so folders and
|
||||
playlists are the same row kind told apart by `attribute` (1 = folder).
|
||||
"""
|
||||
next_id = [0]
|
||||
|
||||
def add(name: str, parent: int | None, *, folder: bool) -> int:
|
||||
next_id[0] += 1
|
||||
con.execute(
|
||||
"INSERT INTO playlist (playlist_id, sequenceNo, name, attribute, "
|
||||
"playlist_id_parent) VALUES (?,?,?,?,?)",
|
||||
(next_id[0], next_id[0], name, 1 if folder else 0, parent),
|
||||
)
|
||||
return next_id[0]
|
||||
|
||||
root = add(payload.name, None, folder=True)
|
||||
folders: dict[tuple[str, ...], int] = {(): root}
|
||||
|
||||
for playlist in payload.playlists:
|
||||
parent = root
|
||||
for depth in range(1, len(playlist.folders) + 1):
|
||||
branch = tuple(playlist.folders[:depth])
|
||||
if branch not in folders:
|
||||
folders[branch] = add(branch[-1], folders[branch[:-1]], folder=True)
|
||||
parent = folders[branch]
|
||||
self._fill_playlist(con, add(playlist.name, parent, folder=False),
|
||||
playlist.track_ids, by_source)
|
||||
|
||||
claimed = {t for p in payload.playlists for t in p.track_ids}
|
||||
loose = [t.source_id for t in payload.tracks if t.source_id not in claimed]
|
||||
if loose:
|
||||
self._fill_playlist(con, add(OTHER_PLAYLIST, root, folder=False),
|
||||
loose, by_source)
|
||||
|
||||
@staticmethod
|
||||
def _fill_playlist(con, playlist_id: int, track_ids: list[str], by_source: dict) -> None:
|
||||
for seq, source_id in enumerate(track_ids, start=1):
|
||||
content_id = by_source.get(source_id)
|
||||
if content_id is not None:
|
||||
con.execute(
|
||||
"INSERT INTO playlist_content (playlist_id, content_id, sequenceNo) "
|
||||
"VALUES (?,?,?)", (playlist_id, content_id, seq)
|
||||
)
|
||||
|
||||
|
||||
#: rekordbox's `fileType` codes, as `pyrekordbox.devicelib_plus.FileType` has them.
|
||||
#: `.stem.m4a` (a Traktor STEM) is an M4A to a Pioneer player.
|
||||
_FILE_TYPES = {".mp3": 1, ".m4a": 4, ".mp4": 4, ".aac": 4, ".flac": 5, ".wav": 11,
|
||||
".aif": 12, ".aiff": 12}
|
||||
|
||||
|
||||
def _file_type(path: Path) -> int:
|
||||
return _FILE_TYPES.get(path.suffix.lower(), 1)
|
||||
|
||||
|
||||
def _kbps(bitrate: int | None) -> int | None:
|
||||
"""Generic bits per second → Pioneer's kbps."""
|
||||
if not bitrate:
|
||||
return None
|
||||
return int(round(bitrate / 1000))
|
||||
|
||||
|
||||
def _audio_format(path: Path) -> tuple[int | None, int | None]:
|
||||
"""(sample rate, bit depth) read from the COPIED file, or Nones.
|
||||
|
||||
Not in the generic model, and not worth adding for one target: the file is
|
||||
right here, and reading its header costs a millisecond.
|
||||
"""
|
||||
try:
|
||||
import mutagen
|
||||
|
||||
info = getattr(mutagen.File(str(path)), "info", None)
|
||||
except Exception: # an unreadable file still exports; these stay empty
|
||||
return None, None
|
||||
rate = getattr(info, "sample_rate", None)
|
||||
depth = getattr(info, "bits_per_sample", None)
|
||||
return (int(rate) if rate else None), (int(depth) if depth else None)
|
||||
|
||||
|
||||
def _loop_beats(start: float, length: float, beats: list[tuple[int, float, float]]) -> int | None:
|
||||
"""A loop's length in whole beats at the tempo governing its start.
|
||||
|
||||
rekordbox stores it (`loop_num`/`loop_den`, e.g. 4/1). A loop that is not a
|
||||
whole number of beats — or a track with no grid — gets none, as rekordbox
|
||||
itself writes for a loop set by hand.
|
||||
"""
|
||||
bpm = next((b for _, b, t in reversed(beats) if t <= start + 1e-3), None)
|
||||
if not bpm or length <= 0:
|
||||
return None
|
||||
count = length * bpm / 60.0
|
||||
whole = round(count)
|
||||
return whole if whole >= 1 and abs(count - whole) < 0.05 else None
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
"""Where things live on a OneLibrary drive.
|
||||
|
||||
A OneLibrary library is a **removable drive**, not a file, and that is the one
|
||||
structural fact that separates this adapter from every other one. Everything the
|
||||
library refers to — the audio, the analysis files, the artwork — is stored
|
||||
DRIVE-RELATIVE (``/Contents/Loopmasters/Demo Track 1.mp3``), because the same
|
||||
stick must resolve on a CDJ, on macOS and on Windows, where it is mounted at
|
||||
three different places. Nothing inside the database is an absolute host path.
|
||||
|
||||
So resolving a stored path means joining it to the mount point, and that is what
|
||||
this module exists to do. It is kept separate from the store because it is also
|
||||
the knowledge a future *export* would need to lay a drive out from nothing.
|
||||
|
||||
Two layout details are measured from a real rekordbox 7 export rather than
|
||||
assumed:
|
||||
|
||||
* the database is at ``PIONEER/rekordbox/exportLibrary.db``, alongside — not
|
||||
instead of — the legacy ``export.pdb``. Both formats coexist on one drive,
|
||||
and newer players prefer OneLibrary when they find it.
|
||||
* analysis files sit under ``PIONEER/USBANLZ/P0<xx>/<8 hex>/ANLZ0000.*``,
|
||||
where the two directory levels are a hash of the track's path. Konduktor
|
||||
never has to compute that hash to READ, because ``content.analysisDataFilePath``
|
||||
stores the resulting path outright — it would only matter for writing.
|
||||
|
||||
``.PIONEER`` is accepted as well as ``PIONEER``. Traktor's own OneLibrary writer
|
||||
looks for both, so a drive written by it may use the dot-prefixed (hidden) form.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
# In preference order: a drive may legitimately carry either spelling, and the
|
||||
# visible one is what rekordbox itself writes.
|
||||
PIONEER_DIRS = ("PIONEER", ".PIONEER")
|
||||
DB_SUBPATH = Path("rekordbox") / "exportLibrary.db"
|
||||
|
||||
# The analysis file the database points at is the `.DAT`; its siblings differ
|
||||
# only by extension. `.EXT` carries the complete cue list and the colour
|
||||
# waveforms, `.2EX` the newer high-resolution ones.
|
||||
ANLZ_EXTENDED = ".EXT"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DriveLayout:
|
||||
"""A located OneLibrary drive: its mount point and its database."""
|
||||
|
||||
root: Path
|
||||
database: Path
|
||||
|
||||
@classmethod
|
||||
def locate(cls, path: Path) -> "DriveLayout | None":
|
||||
"""Find the layout for `path`, or None if it is not a OneLibrary drive.
|
||||
|
||||
Accepts either end of the drive deliberately: the MOUNT POINT, which is
|
||||
what discovery finds and what a user picks in a file browser, or the
|
||||
``exportLibrary.db`` ITSELF, which is what someone reaches by drilling
|
||||
into the folder or by re-opening a remembered path. Both name the same
|
||||
library, and refusing one of them would make the picker and the
|
||||
last-opened shortcut disagree about what a valid library is.
|
||||
"""
|
||||
path = Path(path)
|
||||
try:
|
||||
if path.is_file():
|
||||
# .../PIONEER/rekordbox/exportLibrary.db -> the drive is 3 up.
|
||||
if path.name.lower() != "exportLibrary.db".lower():
|
||||
return None
|
||||
root = path.parent.parent.parent
|
||||
if path.parent.parent.name not in PIONEER_DIRS:
|
||||
return None
|
||||
return cls(root=root, database=path)
|
||||
if path.is_dir():
|
||||
for pioneer in PIONEER_DIRS:
|
||||
db = path / pioneer / DB_SUBPATH
|
||||
if db.is_file():
|
||||
return cls(root=path, database=db)
|
||||
except OSError:
|
||||
return None
|
||||
return None
|
||||
|
||||
def resolve(self, drive_relative: str | None) -> Path | None:
|
||||
"""A stored drive-relative path as a real path on this host.
|
||||
|
||||
Stored paths are POSIX-style and lead with a slash. That leading slash is
|
||||
NOT a host root — treating it as one is the mistake this method exists to
|
||||
prevent, since ``Path('/Volumes/X') / '/Contents/a.mp3'`` silently
|
||||
discards the mount point and yields ``/Contents/a.mp3``.
|
||||
"""
|
||||
if not drive_relative:
|
||||
return None
|
||||
relative = str(drive_relative).replace("\\", "/").lstrip("/")
|
||||
if not relative:
|
||||
return None
|
||||
return self.root / relative
|
||||
|
||||
def extended_anlz(self, dat_path: Path) -> Path:
|
||||
"""The `.EXT` beside a given `.DAT`.
|
||||
|
||||
Cues are read from the `.EXT`, not the `.DAT` the database points at:
|
||||
see `cues.py` for why that distinction is load-bearing rather than a
|
||||
preference.
|
||||
"""
|
||||
return dat_path.with_suffix(ANLZ_EXTENDED)
|
||||
@@ -0,0 +1,120 @@
|
||||
"""OneLibrary rows -> the generic projection.
|
||||
|
||||
The only place a ``devicelib_plus`` ORM object becomes a generic `Track` /
|
||||
`TrackCues`. Everything above this file sees generic types exclusively.
|
||||
|
||||
Field conventions are read off a real rekordbox 7 export rather than guessed:
|
||||
|
||||
* ``bpmx100`` is the tempo in hundredths, and it is a DISPLAY value — the real
|
||||
grid is per-beat in the ANLZ file, and a variable-tempo track stores only its
|
||||
first tempo here.
|
||||
* ``rating`` is 0-5 directly, like `master.db` and unlike Traktor's /51.
|
||||
* ``length`` is whole seconds.
|
||||
* ``path`` is drive-relative with a leading slash; the store resolves it.
|
||||
* dates arrive as `datetime` from the ORM, not as strings.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from ...core.model import GridMarker, Track, TrackCues
|
||||
from ..rekordbox.projection import parse_key
|
||||
|
||||
|
||||
def _name_of(related) -> str | None:
|
||||
"""A joined lookup row's display name, or None when unset."""
|
||||
if related is None:
|
||||
return None
|
||||
value = getattr(related, "name", None)
|
||||
return str(value) if value else None
|
||||
|
||||
|
||||
def _iso_date(value) -> str | None:
|
||||
"""`YYYY-MM-DD` from whatever the column holds.
|
||||
|
||||
The ORM converts the stored strings to `datetime`, so this takes the date
|
||||
part of one — but a drive written by another vendor's software may well
|
||||
store a plain string, and passing that through unchanged is better than
|
||||
losing it.
|
||||
"""
|
||||
if not value:
|
||||
return None
|
||||
date = getattr(value, "date", None)
|
||||
if callable(date):
|
||||
try:
|
||||
return date().isoformat()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
text = str(value).strip()
|
||||
return text.split(" ")[0] if text else None
|
||||
|
||||
|
||||
def _bpm(row) -> float | None:
|
||||
raw = getattr(row, "bpmx100", None)
|
||||
if not raw:
|
||||
return None
|
||||
return round(int(raw) / 100.0, 2)
|
||||
|
||||
|
||||
def to_track(row, drive_path: str | None = None, *, stem: bool = False) -> Track:
|
||||
"""Project one ``Content`` row.
|
||||
|
||||
**The three count fields are approximations here**, and deliberately so. Cues
|
||||
and the beatgrid both live in the track's ANLZ files, and parsing a track's
|
||||
`.EXT` costs ~23 ms — ~23 s for a 1,000-track drive if done at open. So a
|
||||
track that has an analysis file and a tempo is reported as having one grid
|
||||
marker (constant tempo, true for all but a fraction of a percent of tracks)
|
||||
and no cues, and all three are corrected the moment the track's cues are
|
||||
actually read. `adapter.track_cues` is where that happens.
|
||||
|
||||
Reporting zero cues rather than a guess is the honest direction to be wrong
|
||||
in: a count that appears from nowhere on selection reads as the detail
|
||||
arriving, whereas one that shrinks reads as data being lost.
|
||||
"""
|
||||
key_name = _name_of(getattr(row, "key", None))
|
||||
wheel, mode = parse_key(key_name)
|
||||
has_analysis = bool(getattr(row, "analysisDataFilePath", None))
|
||||
bpm = _bpm(row)
|
||||
return Track(
|
||||
id=str(getattr(row, "path", "") or ""),
|
||||
artist=_name_of(getattr(row, "artist", None)),
|
||||
title=getattr(row, "title", None),
|
||||
album=_name_of(getattr(row, "album", None)),
|
||||
genre=_name_of(getattr(row, "genre", None)),
|
||||
label=_name_of(getattr(row, "label", None)),
|
||||
remixer=_name_of(getattr(row, "remixer", None)),
|
||||
# OneLibrary has `composer` and `lyricist`, neither of which is Traktor's
|
||||
# "producer" or "mix", so nothing is mapped onto them approximately.
|
||||
producer=None,
|
||||
mix=None,
|
||||
comment=getattr(row, "djComment", None),
|
||||
bpm=bpm,
|
||||
key=key_name,
|
||||
key_wheel=wheel,
|
||||
key_mode=mode,
|
||||
rating=max(0, min(5, int(getattr(row, "rating", 0) or 0))),
|
||||
playcount=getattr(row, "djPlayCount", None),
|
||||
length=getattr(row, "length", None),
|
||||
# kbps here; the generic model (and the table) carry bits per second.
|
||||
bitrate=(getattr(row, "bitrate", None) or 0) * 1000 or None,
|
||||
import_date=_iso_date(getattr(row, "dateAdded", None)),
|
||||
last_played=None, # the drive records history as playlists, not per track
|
||||
release_date=_iso_date(getattr(row, "releaseDate", None))
|
||||
or (str(getattr(row, "releaseYear", "") or "") or None),
|
||||
filepath=drive_path,
|
||||
cue_count=0,
|
||||
hotcue_count=0,
|
||||
grid_marker_count=1 if (bpm and has_analysis) else 0,
|
||||
grid_locked=False, # OneLibrary has no grid lock
|
||||
# What the FILE is, as the deck plays it — see the Rekordbox projection.
|
||||
media_kind="stem" if stem else "audio",
|
||||
)
|
||||
|
||||
|
||||
def to_track_cues(cues: list, grid_markers: list[GridMarker]) -> TrackCues:
|
||||
"""Project a track's cues and beatgrid.
|
||||
|
||||
`cues` are already generic — see `store.cues` for why that boundary sits
|
||||
where it does — so this is the assembly point rather than a translation.
|
||||
Nothing here is editable: a OneLibrary drive is read-only in Konduktor, and
|
||||
`capabilities.writable` says so at the library level.
|
||||
"""
|
||||
return TrackCues(grid_markers=grid_markers, grid_locked=False, cues=list(cues))
|
||||
@@ -0,0 +1,284 @@
|
||||
"""The retained native model for a OneLibrary drive.
|
||||
|
||||
Owns the open ``exportLibrary.db`` and the drive layout around it, and is the
|
||||
only place a ``pyrekordbox.devicelib_plus`` row or an ANLZ tag is touched.
|
||||
|
||||
The database is SQLCipher-encrypted SQLite, like Rekordbox's ``master.db``, but
|
||||
with a **different and universal key**: every OneLibrary drive from every vendor
|
||||
is encrypted with the same one, which is what makes the format readable across
|
||||
brands at all. `pyrekordbox` carries it, so nothing here needs to know it.
|
||||
|
||||
**Analysis files are parsed lazily, and that is a measurement, not a
|
||||
preference.** The beatgrid and the cues both live in the per-track ANLZ files,
|
||||
and parsing one costs ~2 ms for the `.DAT` but ~23 ms for the `.EXT`, which
|
||||
carries the colour waveforms as well. Reading every track's `.EXT` at open would
|
||||
cost ~23 s on a 1,000-track drive — so it happens on demand and is cached, the
|
||||
same bargain the Rekordbox adapter strikes for its grids. The visible
|
||||
consequence is that cue and marker counts are approximate in the library table
|
||||
until a track's cues are actually read; see `projection.to_track`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
from ...core.adapter import LibraryNotSupported, NotFound
|
||||
from ...core.model import CuePoint
|
||||
from . import beatgrid, cues as cue_reader
|
||||
from ..rekordbox import timebase
|
||||
from .layout import DriveLayout
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class OneLibraryStore:
|
||||
def __init__(self, path: Path):
|
||||
layout = DriveLayout.locate(Path(path))
|
||||
if layout is None:
|
||||
raise LibraryNotSupported(f"No OneLibrary database found at {path}")
|
||||
self.layout = layout
|
||||
self.path = layout.database
|
||||
self._db = None
|
||||
# Parsed ANLZ, keyed by track id. Two caches because the two files cost
|
||||
# an order of magnitude apart: a grid read must not drag in the .EXT.
|
||||
self._dat_cache: dict[str, object | None] = {}
|
||||
self._ext_cache: dict[str, object | None] = {}
|
||||
self._content_cache: list | None = None
|
||||
self._by_id: dict[str, object] | None = None
|
||||
self._load()
|
||||
|
||||
# ---- open / close ----------------------------------------------------
|
||||
def _load(self) -> None:
|
||||
try:
|
||||
from pyrekordbox.devicelib_plus import DeviceLibraryPlus
|
||||
except ImportError as ex: # pragma: no cover — dependency missing
|
||||
raise LibraryNotSupported(
|
||||
"Reading OneLibrary drives needs pyrekordbox with devicelib_plus"
|
||||
) from ex
|
||||
try:
|
||||
self._db = DeviceLibraryPlus(str(self.path))
|
||||
except Exception as ex: # noqa: BLE001 — surfaced as a clean 4xx
|
||||
raise LibraryNotSupported(f"Could not open OneLibrary database: {ex}") from ex
|
||||
self._dat_cache.clear()
|
||||
self._ext_cache.clear()
|
||||
self._content_cache = None
|
||||
self._by_id = None
|
||||
|
||||
def close(self) -> None:
|
||||
"""Release the database AND the underlying file handle.
|
||||
|
||||
Disposing the engine matters more here than anywhere else: the library
|
||||
is on a REMOVABLE drive, and a lingering handle is what makes a stick
|
||||
refuse to eject. `DeviceLibraryPlus.close()` only ends the session, so
|
||||
the engine is disposed explicitly — the same gap the Rekordbox store
|
||||
had to close for `master.db`.
|
||||
"""
|
||||
db, self._db = self._db, None
|
||||
if db is None:
|
||||
return
|
||||
try:
|
||||
db.close()
|
||||
except Exception: # noqa: BLE001 — closing must not raise
|
||||
log.debug("OneLibrary session close failed", exc_info=True)
|
||||
engine = getattr(db, "engine", None)
|
||||
if engine is not None:
|
||||
try:
|
||||
engine.dispose()
|
||||
except Exception: # noqa: BLE001
|
||||
log.debug("OneLibrary engine dispose failed", exc_info=True)
|
||||
|
||||
def _require_db(self):
|
||||
if self._db is None:
|
||||
raise LibraryNotSupported("The OneLibrary database is closed")
|
||||
return self._db
|
||||
|
||||
# ---- identity --------------------------------------------------------
|
||||
@property
|
||||
def device_name(self) -> str | None:
|
||||
"""The drive's own name, which is NOT the volume label.
|
||||
|
||||
Stored in `property.deviceName` and often blank — rekordbox leaves it
|
||||
empty unless the user names the device — so the mount point's name is
|
||||
the fallback a person will actually recognise.
|
||||
"""
|
||||
try:
|
||||
row = self._require_db().get_property().first()
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
name = (getattr(row, "deviceName", "") or "").strip() if row is not None else ""
|
||||
return name or self.layout.root.name or None
|
||||
|
||||
@property
|
||||
def db_version(self) -> str | None:
|
||||
try:
|
||||
row = self._require_db().get_property().first()
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
value = getattr(row, "dbVersion", None) if row is not None else None
|
||||
return str(value) if value else None
|
||||
|
||||
# ---- tracks ----------------------------------------------------------
|
||||
def iter_content(self) -> list:
|
||||
"""Every track row, cached for the life of the open library."""
|
||||
if self._content_cache is None:
|
||||
rows = list(self._require_db().get_content())
|
||||
self._content_cache = rows
|
||||
self._by_id = {self.track_id(r): r for r in rows}
|
||||
return self._content_cache
|
||||
|
||||
@staticmethod
|
||||
def track_id(row) -> str:
|
||||
"""A track's stable id: its DRIVE-RELATIVE path.
|
||||
|
||||
Not `content_id`, which is a row number rekordbox reassigns from 1 every
|
||||
time it rewrites the drive — so it would change under a user who merely
|
||||
re-exported, breaking every playlist reference Konduktor had remembered.
|
||||
The path is stable, unique on the drive, and is also the key a future
|
||||
import would match against a Traktor collection, so it is the honest
|
||||
identity here.
|
||||
"""
|
||||
return str(getattr(row, "path", "") or f"content:{getattr(row, 'content_id', '')}")
|
||||
|
||||
def content(self, track_id: str):
|
||||
self.iter_content()
|
||||
row = (self._by_id or {}).get(str(track_id))
|
||||
if row is None:
|
||||
raise NotFound(f"No track {track_id!r} on this OneLibrary drive")
|
||||
return row
|
||||
|
||||
def audio_path(self, track_id: str) -> Path | None:
|
||||
return self.layout.resolve(getattr(self.content(track_id), "path", None))
|
||||
|
||||
def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
|
||||
"""The track's artwork: `content.image_id` -> `image.path` -> the file.
|
||||
|
||||
The row names the 80 px JPEG (`.../b<n>.jpg`); a `_m` sibling at 240 px
|
||||
sits beside it on every export seen, and is what is served — 80 px is a
|
||||
CDJ browse thumbnail, too small for anything Konduktor draws.
|
||||
"""
|
||||
image_id = getattr(self.content(track_id), "image_id", None)
|
||||
if not image_id:
|
||||
return None
|
||||
from pyrekordbox.devicelib_plus import models
|
||||
|
||||
row = self._require_db().query(models.Image).filter_by(image_id=image_id).one_or_none()
|
||||
small = self.layout.resolve(getattr(row, "path", None)) if row is not None else None
|
||||
if small is None:
|
||||
return None
|
||||
medium = small.with_name(small.stem + "_m" + small.suffix)
|
||||
for path in (medium, small):
|
||||
try:
|
||||
return path.read_bytes(), "image/jpeg"
|
||||
except OSError:
|
||||
continue
|
||||
return None
|
||||
|
||||
def all_audio_paths(self) -> list[str]:
|
||||
out: list[str] = []
|
||||
for row in self.iter_content():
|
||||
resolved = self.layout.resolve(getattr(row, "path", None))
|
||||
if resolved is not None:
|
||||
out.append(str(resolved))
|
||||
return out
|
||||
|
||||
# ---- analysis files --------------------------------------------------
|
||||
def _anlz(self, track_id: str, *, extended: bool):
|
||||
"""The parsed `.DAT` or `.EXT` for a track, or None if unreadable.
|
||||
|
||||
A missing or corrupt analysis file is a normal state on a real drive —
|
||||
an unanalysed track has none — so it is cached as None and never raised.
|
||||
"""
|
||||
cache = self._ext_cache if extended else self._dat_cache
|
||||
key = str(track_id)
|
||||
if key in cache:
|
||||
return cache[key]
|
||||
|
||||
cache[key] = None
|
||||
row = self.content(track_id)
|
||||
dat = self.layout.resolve(getattr(row, "analysisDataFilePath", None))
|
||||
if dat is None:
|
||||
return None
|
||||
target = self.layout.extended_anlz(dat) if extended else dat
|
||||
try:
|
||||
if not target.is_file():
|
||||
return None
|
||||
from pyrekordbox.anlz import AnlzFile
|
||||
|
||||
cache[key] = AnlzFile.parse_file(str(target))
|
||||
except Exception: # noqa: BLE001 — a bad file must not break browsing
|
||||
log.debug("Could not parse ANLZ %s", target, exc_info=True)
|
||||
return None
|
||||
return cache[key]
|
||||
|
||||
def anlz_grid(self, track_id: str) -> tuple[list[float], list[float], list[int]] | None:
|
||||
"""The per-beat ``(times, bpms, beat_in_bar)`` from the track's `PQTZ`
|
||||
tag, in the DECODED time base (see `rekordbox.timebase`).
|
||||
|
||||
`PQTZ` is in the `.DAT`, which is the cheap file — a grid read does not
|
||||
pay for the `.EXT`'s waveforms.
|
||||
"""
|
||||
anlz = self._anlz(track_id, extended=False)
|
||||
if anlz is None:
|
||||
return None
|
||||
grid = beatgrid.beats_from_pqtz(anlz)
|
||||
if grid is None:
|
||||
return None
|
||||
off = timebase.offset(self.audio_path(track_id))
|
||||
times, bpms, beats = grid
|
||||
return [timebase.from_pioneer(t, off) for t in times], bpms, beats
|
||||
|
||||
def cues(self, track_id: str) -> list[CuePoint]:
|
||||
"""The track's cues, already generic.
|
||||
|
||||
Unusually for a store, this returns generic types rather than native
|
||||
rows: the native shape is a pair of parsed tag containers whose entries
|
||||
only mean anything once merged across two files, and handing that to the
|
||||
projection would put ANLZ knowledge on both sides of the boundary.
|
||||
"""
|
||||
cues = cue_reader.cues_from_anlz(
|
||||
self._anlz(track_id, extended=False),
|
||||
self._anlz(track_id, extended=True),
|
||||
)
|
||||
# Positions are stored on rekordbox's clock; the generic model is the
|
||||
# decoded audio's. A loop keeps its length.
|
||||
off = timebase.offset(self.audio_path(track_id))
|
||||
return [c.model_copy(update={"start": timebase.from_pioneer(c.start, off)})
|
||||
for c in cues] if off else cues
|
||||
|
||||
# ---- playlists -------------------------------------------------------
|
||||
def playlists(self) -> list:
|
||||
return list(self._require_db().get_playlist())
|
||||
|
||||
def count_playlists(self) -> int:
|
||||
try:
|
||||
return self._require_db().get_playlist().count()
|
||||
except Exception: # noqa: BLE001
|
||||
return 0
|
||||
|
||||
def playlist_song_ids(self, node_id: str) -> list[str]:
|
||||
"""Track ids in a playlist, in the order the drive stores them.
|
||||
|
||||
`playlist_content` joins on `content_id`, but Konduktor's track id is the
|
||||
path (see `track_id`), so the row numbers are translated here rather than
|
||||
leaking a second notion of identity upward.
|
||||
"""
|
||||
try:
|
||||
pid = int(node_id)
|
||||
except (TypeError, ValueError):
|
||||
return []
|
||||
self.iter_content()
|
||||
by_content_id = {
|
||||
int(getattr(r, "content_id", -1)): self.track_id(r) for r in self.iter_content()
|
||||
}
|
||||
rows = [
|
||||
r
|
||||
for r in self._require_db().get_playlist_content()
|
||||
if int(getattr(r, "playlist_id", -1)) == pid
|
||||
]
|
||||
rows.sort(key=lambda r: int(getattr(r, "sequenceNo", 0) or 0))
|
||||
out: list[str] = []
|
||||
for r in rows:
|
||||
track_id = by_content_id.get(int(getattr(r, "content_id", -1)))
|
||||
if track_id is not None:
|
||||
out.append(track_id)
|
||||
return out
|
||||
@@ -0,0 +1,23 @@
|
||||
"""The Rekordbox adapter: ``master.db`` (SQLCipher) via ``pyrekordbox``.
|
||||
|
||||
Importing this package registers the platform for READING and editing a library
|
||||
in place, and as an export TARGET for writing a fresh one. Two registries,
|
||||
because opening a library and creating one from nothing are different
|
||||
capabilities.
|
||||
"""
|
||||
from ...core import export as core_export
|
||||
from ...core import registry
|
||||
from .driver import RekordboxDriver
|
||||
from .device_export import RekordboxDeviceExporter
|
||||
from .export import RekordboxExporter
|
||||
|
||||
REKORDBOX = RekordboxDriver()
|
||||
registry.register(REKORDBOX)
|
||||
|
||||
REKORDBOX_EXPORTER = RekordboxExporter()
|
||||
core_export.register(REKORDBOX_EXPORTER)
|
||||
|
||||
# The stick's legacy Device Library (`export.pdb`): a separate TARGET with no
|
||||
# reader of its own — Konduktor reads a stick through its OneLibrary database.
|
||||
REKORDBOX_DEVICE_EXPORTER = RekordboxDeviceExporter()
|
||||
core_export.register(REKORDBOX_DEVICE_EXPORTER)
|
||||
@@ -0,0 +1,519 @@
|
||||
"""The Rekordbox adapter: owns the native database and the generic projection.
|
||||
|
||||
Mirrors `adapters.traktor.adapter`. It holds:
|
||||
|
||||
* a ``RekordboxStore`` — the retained NATIVE model (the open ``master.db``),
|
||||
* a ``TrackIndex`` — the generic READ projection built from it.
|
||||
|
||||
**Track metadata and playlists are writable; cues and the beatgrid are not
|
||||
yet.** Those two are separate native stores (two DB tables kept consistent, and
|
||||
the per-track ANLZ analysis files), so they keep refusing until milestone 3 —
|
||||
and `capabilities.cues.editable` / `grid.editable` say so, which is what the UI
|
||||
actually gates on. The raise is the backstop, not the mechanism.
|
||||
|
||||
Writes are refused entirely, and permanently, on a **cloud-synced** library:
|
||||
propagating a bad sync state to the user's other machines is not something
|
||||
version history can undo — especially here, where there is no version history at
|
||||
all. That check lives at the top of every command path so no future command can
|
||||
forget it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from ...core.adapter import InvalidCommand, Unsupported
|
||||
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 .store import RekordboxStore
|
||||
|
||||
|
||||
class RekordboxAdapter:
|
||||
platform = "rekordbox"
|
||||
|
||||
def __init__(self, path: Path):
|
||||
self.path = Path(path)
|
||||
self._store = RekordboxStore(self.path)
|
||||
self._index = TrackIndex()
|
||||
self._cloud_synced = self._store.cloud_synced
|
||||
self._rebuild()
|
||||
|
||||
# ---- projection maintenance -----------------------------------------
|
||||
def _rebuild(self) -> None:
|
||||
kinds = self._store.cue_kinds()
|
||||
self._index.rebuild(
|
||||
[
|
||||
projection.to_track(row, kinds.get(str(row.ID), ()),
|
||||
stem=self._store.is_stem(str(row.ID)))
|
||||
for row in self._store.iter_content()
|
||||
]
|
||||
)
|
||||
|
||||
def _refresh_cues(self, track_id: str) -> TrackCues:
|
||||
"""Re-project a track AND return its fresh cues.
|
||||
|
||||
Every mutating cue/grid command ends here: the contract is that a command
|
||||
returns the refreshed projection, so a route can never serve a stale one.
|
||||
"""
|
||||
self._refresh(track_id)
|
||||
return self.track_cues(track_id) or TrackCues()
|
||||
|
||||
def _refresh(self, track_id: str) -> None:
|
||||
"""Re-project one track after a command, so the UI cannot go stale.
|
||||
|
||||
Every mutating command must end in this — a forgotten refresh is a
|
||||
silently stale projection that no byte- or row-level test would catch.
|
||||
"""
|
||||
kinds = self._store.cue_kinds()
|
||||
row = self._store.content(track_id)
|
||||
self._index.replace(projection.to_track(row, kinds.get(str(row.ID), ()),
|
||||
stem=self._store.is_stem(str(row.ID))))
|
||||
|
||||
def close(self) -> None:
|
||||
"""Release the database connection.
|
||||
|
||||
Rekordbox's library is a live SQLite file, not a document parsed into
|
||||
memory: leaving the connection open keeps a file handle (and possibly a
|
||||
`-wal`) around, so an adapter that is being replaced must be closed.
|
||||
"""
|
||||
self._store.close()
|
||||
|
||||
def reload(self) -> None:
|
||||
"""Re-read the library from disk, DISCARDING unsaved edits (see
|
||||
`RekordboxStore.discard` for why a plain re-open is not enough)."""
|
||||
self._store.discard()
|
||||
self._cloud_synced = self._store.cloud_synced
|
||||
self._rebuild()
|
||||
|
||||
# ---- identity --------------------------------------------------------
|
||||
def capabilities(self) -> Capabilities:
|
||||
return caps.capabilities_for(
|
||||
self.path,
|
||||
cloud_synced=self._cloud_synced,
|
||||
editable_fields=sorted(RekordboxStore.EDITABLE_FIELDS),
|
||||
)
|
||||
|
||||
@property
|
||||
def cloud_synced(self) -> bool:
|
||||
return self._cloud_synced
|
||||
|
||||
# ---- read ------------------------------------------------------------
|
||||
@property
|
||||
def tracks(self) -> list[Track]:
|
||||
return self._index.tracks
|
||||
|
||||
@property
|
||||
def by_key(self) -> dict[str, Track]:
|
||||
return self._index.by_key
|
||||
|
||||
def track(self, track_id: str) -> Track | None:
|
||||
return self._index.get(track_id)
|
||||
|
||||
def query_tracks(self, **kw):
|
||||
return self._index.query_tracks(**kw)
|
||||
|
||||
def facets(self):
|
||||
return self._index.facets()
|
||||
|
||||
def stats(self, playlist_count: int):
|
||||
return self._index.stats(playlist_count)
|
||||
|
||||
def playlist_count(self) -> int:
|
||||
return self._store.count_playlists()
|
||||
|
||||
def track_cues(self, track_id: str) -> TrackCues | None:
|
||||
if self._index.get(track_id) is None:
|
||||
return None
|
||||
cues = projection.to_track_cues(
|
||||
self._store.cues(track_id), self._store.anlz_grid(track_id),
|
||||
self._store.time_offset(track_id),
|
||||
)
|
||||
# The track projection carries an APPROXIMATE grid_marker_count until the
|
||||
# grid is actually read (see projection.to_track). This is that moment —
|
||||
# correct it, so the library table stops showing the guess.
|
||||
track = self._index.get(track_id)
|
||||
if track is not None:
|
||||
track.grid_marker_count = len(cues.grid_markers)
|
||||
return cues
|
||||
|
||||
# ---- playlists -------------------------------------------------------
|
||||
def playlist_tree(self) -> list[PlaylistNode]:
|
||||
"""Rekordbox stores the tree as a flat table with ``ParentID`` links."""
|
||||
from pyrekordbox.masterdb import models as tables
|
||||
|
||||
rows = self._store.playlists()
|
||||
folder = int(tables.PlaylistType.FOLDER)
|
||||
smart = int(tables.PlaylistType.SMART_PLAYLIST)
|
||||
writable = not self._cloud_synced
|
||||
|
||||
nodes: dict[str, PlaylistNode] = {}
|
||||
parents: dict[str, str] = {}
|
||||
for r in rows:
|
||||
attribute = int(r.Attribute or 0)
|
||||
kind = "folder" if attribute == folder else ("smart" if attribute == smart else "playlist")
|
||||
node_id = str(r.ID)
|
||||
nodes[node_id] = PlaylistNode(
|
||||
id=node_id,
|
||||
name=r.Name or "",
|
||||
kind=kind,
|
||||
count=(0 if kind == "folder" else len(self._store.playlist_song_ids(node_id))),
|
||||
children=[],
|
||||
# A smart playlist has no static entry list; a folder has no tracks.
|
||||
selectable=kind == "playlist",
|
||||
# Rekordbox's own working lists are filtered out by the store, so
|
||||
# everything reaching here is the user's and may be edited — as
|
||||
# long as the library itself is writable at all.
|
||||
can_add_tracks=writable and kind == "playlist",
|
||||
can_reorder=writable and kind == "playlist",
|
||||
can_rename=writable,
|
||||
can_delete=writable,
|
||||
can_contain_children=kind == "folder",
|
||||
)
|
||||
parent = str(r.ParentID or "root")
|
||||
parents[node_id] = "root" if parent in ("0", "", "root", "None") else parent
|
||||
|
||||
roots: list[PlaylistNode] = []
|
||||
for node_id, node in nodes.items():
|
||||
parent_id = parents.get(node_id, "root")
|
||||
parent = nodes.get(parent_id)
|
||||
if parent is None:
|
||||
roots.append(node)
|
||||
else:
|
||||
parent.children.append(node)
|
||||
return roots
|
||||
|
||||
def playlist_entries(self, node_id: str) -> list[str] | None:
|
||||
ids = self._store.playlist_song_ids(node_id)
|
||||
return ids if ids or self._is_playlist(node_id) else None
|
||||
|
||||
def playlist_tracks(self, node_id: str) -> list[Track] | None:
|
||||
keys = self.playlist_entries(node_id)
|
||||
if keys is None:
|
||||
return None
|
||||
return [t for k in keys if (t := self._index.get(k)) is not None]
|
||||
|
||||
def _is_playlist(self, node_id: str) -> bool:
|
||||
return any(str(r.ID) == str(node_id) for r in self._store.playlists())
|
||||
|
||||
# ---- audio / paths ----------------------------------------------------
|
||||
def audio_path(self, track_id: str):
|
||||
return self._store.audio_path(track_id)
|
||||
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None:
|
||||
self._store.set_path_mapping(mapping)
|
||||
# The FILE decides a track's media kind, and the mapping moves files.
|
||||
self._rebuild()
|
||||
|
||||
def unresolved_path_groups(self) -> list:
|
||||
"""Not checked yet: the open-time missing-files check is Traktor-only
|
||||
for now. Rekordbox's `FolderPath` is absolute too, so it will qualify."""
|
||||
return []
|
||||
|
||||
def set_session_mappings(self, mappings: list[PathMapping]) -> None:
|
||||
return None
|
||||
|
||||
def path_prefix_suggestions(self) -> dict:
|
||||
paths = self._store.all_audio_paths()
|
||||
primary = common_dir_prefix(paths)
|
||||
return {"primary": primary, "groups": [{"prefix": primary, "count": len(paths)}] if primary else []}
|
||||
|
||||
def remap_preview(self, mapping: PathMapping) -> dict:
|
||||
paths = [Path(p) for p in self._store.all_audio_paths()]
|
||||
matched = [p for p in paths if mapping.matches(p)]
|
||||
samples = []
|
||||
for p in matched[:5]:
|
||||
target = mapping.apply(p)
|
||||
samples.append({"from": str(p), "to": str(target), "exists": target.exists()})
|
||||
existing = sum(1 for p in matched if mapping.apply(p).exists())
|
||||
return {
|
||||
"total": len(paths),
|
||||
"matched": len(matched),
|
||||
"existing": existing,
|
||||
"samples": samples,
|
||||
}
|
||||
|
||||
def remap_locations(self, mapping: PathMapping) -> dict[str, str]:
|
||||
raise Unsupported(self._readonly_reason("Rewriting stored paths"))
|
||||
|
||||
# ---- commands: track metadata ----------------------------------------
|
||||
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None:
|
||||
self._require_writable("Editing track metadata")
|
||||
self._store.set_track_metadata(track_id, fields)
|
||||
self._refresh(track_id)
|
||||
return self._index.get(track_id)
|
||||
|
||||
# ---- commands: playlists ----------------------------------------------
|
||||
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
|
||||
self._require_writable("Creating playlists")
|
||||
return self._store.create_playlist(name, parent_id)
|
||||
|
||||
def create_folder(self, name: str, parent_id: str | None = None) -> str:
|
||||
self._require_writable("Creating playlist folders")
|
||||
return self._store.create_folder(name, parent_id)
|
||||
|
||||
def rename_playlist(self, node_id: str, name: str) -> None:
|
||||
self._require_writable("Renaming playlists")
|
||||
self._store.rename_playlist(node_id, name)
|
||||
|
||||
def delete_playlist(self, node_id: str) -> None:
|
||||
self._require_writable("Deleting playlists")
|
||||
self._store.delete_playlist(node_id)
|
||||
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
|
||||
self._require_writable("Editing playlists")
|
||||
return self._store.set_playlist_entries(node_id, track_ids)
|
||||
|
||||
# ---- commands: cues ---------------------------------------------------
|
||||
def _check_cue_type(self, cue_type: str) -> None:
|
||||
if cue_type not in caps.WRITABLE_CUE_TYPES:
|
||||
raise Unsupported(f"Rekordbox has no cue type {cue_type!r}")
|
||||
|
||||
def set_cue(
|
||||
self,
|
||||
track_id: str,
|
||||
*,
|
||||
slot: int,
|
||||
start_sec: float,
|
||||
cue_type: str,
|
||||
length_sec: float = 0.0,
|
||||
role: str = "hotcue",
|
||||
name: str | None = None,
|
||||
) -> TrackCues:
|
||||
self._require_writable("Editing cues")
|
||||
if role != "hotcue":
|
||||
# Rekordbox is the ONLY platform with memory cues, so under the
|
||||
# two-platform promotion rule they stay preserved-but-uneditable:
|
||||
# they are projected and shown, never written.
|
||||
raise Unsupported(
|
||||
"Memory cues are shown but cannot be edited — only hot cues are writable"
|
||||
)
|
||||
self._check_cue_type(cue_type)
|
||||
self._store.set_cue(
|
||||
track_id, slot=slot, start_sec=start_sec, cue_type=cue_type,
|
||||
length_sec=length_sec, name=name,
|
||||
)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> TrackCues:
|
||||
self._require_writable("Editing cues")
|
||||
self._check_cue_type(cue_type)
|
||||
self._store.set_cue_type(track_id, slot, cue_type)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def set_cue_color(self, track_id: str, slot: int, color: str | None) -> TrackCues:
|
||||
self._require_writable("Editing cues")
|
||||
code = None
|
||||
if color is not None:
|
||||
code = palette.swatch_code(color)
|
||||
if code is None:
|
||||
raise InvalidCommand(
|
||||
f"{color!r} is not one of Rekordbox's hot cue colours"
|
||||
)
|
||||
self._store.set_cue_color(track_id, slot, code)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def delete_cue(self, track_id: str, slot: int) -> TrackCues:
|
||||
self._require_writable("Deleting cues")
|
||||
self._store.delete_cue(track_id, slot)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues:
|
||||
self._require_writable("Placing cues")
|
||||
for cue in cues:
|
||||
self._check_cue_type(getattr(cue, "type", "cue"))
|
||||
self._store.place_cues(track_id, cues, overwrite=overwrite)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
# ---- commands: beatgrid -----------------------------------------------
|
||||
def _markers_from(self, markers: list) -> list:
|
||||
"""Accept either GridMarkers or the (start, bpm) tuples routes send."""
|
||||
out = []
|
||||
for m in markers:
|
||||
if isinstance(m, GridMarker):
|
||||
out.append(m)
|
||||
else:
|
||||
start, bpm = m
|
||||
out.append(GridMarker(start=float(start), bpm=float(bpm)))
|
||||
return out
|
||||
|
||||
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> TrackCues:
|
||||
self._require_writable("Editing the beatgrid")
|
||||
self._store.add_grid_marker(track_id, start_sec, bpm)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> TrackCues:
|
||||
self._require_writable("Editing the beatgrid")
|
||||
self._store.move_grid_marker(track_id, index, start_sec)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> TrackCues:
|
||||
self._require_writable("Editing the beatgrid")
|
||||
self._store.set_grid_marker_bpm(track_id, index, bpm)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def delete_grid_marker(self, track_id: str, index: int) -> TrackCues:
|
||||
self._require_writable("Editing the beatgrid")
|
||||
self._store.delete_grid_marker(track_id, index)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def replace_grid(self, track_id: str, markers: list) -> TrackCues:
|
||||
self._require_writable("Editing the beatgrid")
|
||||
self._store.replace_grid(track_id, self._markers_from(markers))
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def set_analysed_grid(self, track_id: str, markers: list) -> TrackCues:
|
||||
"""Write an analysis result the way Rekordbox's own analyser would.
|
||||
|
||||
Rekordbox pairs nothing with a grid marker — the companion cue is a
|
||||
Traktor convention — so this is just a replace.
|
||||
"""
|
||||
return self.replace_grid(track_id, markers)
|
||||
|
||||
def delete_grid(self, track_id: str) -> TrackCues:
|
||||
self._require_writable("Deleting the beatgrid")
|
||||
self._store.delete_grid(track_id)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
# ---- save -------------------------------------------------------------
|
||||
@property
|
||||
def dirty(self) -> bool:
|
||||
return self._store.dirty
|
||||
|
||||
def save(self):
|
||||
self._require_writable("Saving")
|
||||
return self._store.save()
|
||||
|
||||
def snapshot(self) -> bytes:
|
||||
"""The library's bytes, for version history.
|
||||
|
||||
`master.db` alone is NOT a complete snapshot of a Rekordbox library (the
|
||||
beatgrids live in separate ANLZ files, and restoring the database
|
||||
wholesale would also roll back Rekordbox's own auth and sampler state),
|
||||
which is why `capabilities.save.history` is False. Nothing should be
|
||||
calling this.
|
||||
"""
|
||||
raise Unsupported("Rekordbox libraries are not versioned by Konduktor")
|
||||
|
||||
# ---- commands: all refused in this milestone -------------------------
|
||||
def _readonly_reason(self, what: str) -> str:
|
||||
if self._cloud_synced:
|
||||
return (
|
||||
f"{what} is not possible: this Rekordbox library is synced with "
|
||||
"Rekordbox Cloud, and Konduktor will not write to a cloud-synced "
|
||||
"library."
|
||||
)
|
||||
return f"{what} is not supported yet for Rekordbox libraries."
|
||||
|
||||
def _refuse(self, what: str):
|
||||
raise Unsupported(self._readonly_reason(what))
|
||||
|
||||
def _require_writable(self, what: str) -> None:
|
||||
"""Every write passes through here, so the cloud-sync refusal cannot be
|
||||
forgotten by a command added later."""
|
||||
if self._cloud_synced:
|
||||
raise Unsupported(self._readonly_reason(what))
|
||||
|
||||
def 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 remove_tracks(self, track_ids: list[str]) -> int:
|
||||
# What goes with a track was measured in Rekordbox 7 — see the store.
|
||||
self._require_writable("Removing tracks")
|
||||
n = self._store.remove_tracks(track_ids)
|
||||
if n:
|
||||
self._rebuild()
|
||||
return n
|
||||
|
||||
def apply_stem_swaps(self, swaps, *, add_to_playlist=None):
|
||||
# Rekordbox does not play native-instruments stem files as stems.
|
||||
self._refuse("Converting tracks to stems")
|
||||
|
||||
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
|
||||
self._refuse("Editing cover art")
|
||||
|
||||
def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
|
||||
return self._store.cover_art(track_id)
|
||||
|
||||
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues:
|
||||
# Rekordbox has no per-track grid lock; capabilities.grid.lockable says so.
|
||||
raise Unsupported("Rekordbox has no beatgrid lock")
|
||||
@@ -0,0 +1,421 @@
|
||||
"""Building ANLZ analysis files from nothing.
|
||||
|
||||
Lives here rather than in the OneLibrary adapter because the format is Pioneer's,
|
||||
not one product's: a `master.db` track and a USB drive track carry the same tags.
|
||||
OneLibrary borrows it, the same direction it already borrows `beatgrid`.
|
||||
|
||||
The read path parses these with `pyrekordbox`; writing needs the inverse, and
|
||||
two things stand in the way of simply reusing its `construct` structs.
|
||||
|
||||
**`AnlzTag.content` is a Switch**, so a tag is built by handing it the parsed
|
||||
STRUCTURE rather than bytes. Fine once known, surprising until then.
|
||||
|
||||
**The cue-entry structs cannot be built at all.** `AnlzCuePoint` and
|
||||
`AnlzCuePoint2` each declare `"type"` twice — once as a `Const` magic string
|
||||
(`PCPT`/`PCP2`) and once as the cue's kind. Parsing works because the second
|
||||
silently overwrites the first in the result; BUILDING is impossible, because
|
||||
`construct` reads one value out of the dict for both and no single value can
|
||||
satisfy a string `Const` and an integer field. So cue entries are packed here by
|
||||
hand, to the layout `pyrekordbox`'s own structs document:
|
||||
|
||||
PCP2: 4s magic · I len_header · I len_entry · I hot_cue · B kind · x
|
||||
H 1000 · I time · I loop_time · B color_id · B 1 · 6x
|
||||
H loop_num · H loop_den · I len_comment · {n}s comment(utf-16-be)
|
||||
4B colour · {pad}x
|
||||
|
||||
**`pyrekordbox` accepting the result is NOT enough.** Its parser ignores
|
||||
`len_header` and the constants, so an early version with a 12-byte `PCPT`
|
||||
header round-tripped through Konduktor's own reader perfectly. The cue layout is
|
||||
therefore pinned to a real rekordbox 7 export byte-for-byte
|
||||
(`test_export_pioneer.py`).
|
||||
|
||||
**Which tags a file needs was measured, not assumed** — by stripping tags from a
|
||||
rekordbox-written stick one at a time and loading each track in rekordbox 7:
|
||||
* `.DAT` needs `PVBR` AND the preview waveform (`PWAV`/`PWV2`) before rekordbox
|
||||
shows the grid OR the hot cues. The grid and cue tags alone — rekordbox's
|
||||
own bytes — show nothing. (This, not the cue bytes, was why an early
|
||||
Konduktor export had no grid.)
|
||||
* rekordbox follows the database's analysis-path column; the folder names
|
||||
need not match its own path hash.
|
||||
* `.EXT` extras (`PWV3`-`PWV5`, `PQT2`, `PSSI`) and the whole `.2EX` affect
|
||||
only the drawn waveforms.
|
||||
|
||||
Slot numbering here is ANLZ's own — a **dense 1-based** `hot_cue` where 0 means a
|
||||
memory cue. That is NOT `master.db`'s sparse `Kind` bank, which skips 4.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import struct
|
||||
from pathlib import Path
|
||||
|
||||
from construct import Container, ListContainer
|
||||
from pyrekordbox.anlz import structs
|
||||
|
||||
from ...core.waveform import even_slices
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
NO_LOOP = 0xFFFFFFFF
|
||||
#: `len_entry` rekordbox itself writes for a comment-less PCP2 entry.
|
||||
PCP2_ENTRY_LEN = 88
|
||||
PCPT_ENTRY_LEN = 56
|
||||
|
||||
#: Copied from a rekordbox-written file; zeros here would be a guess.
|
||||
FILE_HEADER_U1, FILE_HEADER_U2, FILE_HEADER_U3 = 1, 0x10000, 0x10000
|
||||
|
||||
|
||||
#: The three fields every tag starts with: magic, len_header, len_tag.
|
||||
_TAG_PREFIX = 12
|
||||
|
||||
|
||||
#: Each tag counts a different number of its leading CONTENT fields as part of
|
||||
#: its header. Read off `pyrekordbox`'s own tag classes rather than guessed.
|
||||
_LEN_HEADER = {"PPTH": 16, "PQTZ": 24, "PCOB": 24, "PCO2": 20,
|
||||
"PVBR": 16, "PWAV": 20, "PWV2": 20,
|
||||
"PWV3": 24, "PWV5": 24, "PWV4": 24, "PWV7": 24, "PWV6": 20, "PWVC": 14}
|
||||
|
||||
|
||||
def _wrap(kind: str, body: bytes) -> bytes:
|
||||
"""An AnlzTag around already-built content bytes.
|
||||
|
||||
Returns BYTES, not a tag object. `AnlzFile.build()` cannot be used on the
|
||||
write side at all: it re-builds every tag from its parsed struct, which puts
|
||||
the cue tags straight back through the unbuildable duplicate-`type` structs.
|
||||
So the whole file is assembled here and `pyrekordbox` is used only to read
|
||||
the result back — which is the direction that has to work anyway.
|
||||
"""
|
||||
return struct.pack(">4sII", kind.encode("ascii"), _LEN_HEADER[kind],
|
||||
_TAG_PREFIX + len(body)) + body
|
||||
|
||||
|
||||
def path_tag(drive_relative: str) -> bytes:
|
||||
"""`PPTH` — the track's own path, as the drive stores it."""
|
||||
raw_len = (len(drive_relative) + 1) * 2
|
||||
body = structs.PPTH.build(Container(len_path=raw_len, path=drive_relative))
|
||||
return _wrap("PPTH", body)
|
||||
|
||||
|
||||
def beatgrid_tag(beats: list[tuple[int, float, float]]) -> bytes:
|
||||
"""`PQTZ` — EVERY beat, as (beat-in-bar 1-4, bpm, seconds).
|
||||
|
||||
The grid is per-beat here, not per-marker: a OneLibrary/Rekordbox grid has
|
||||
no concept of a tempo marker, so the generic marker list is expanded into
|
||||
individual beats on the way out and collapsed back on the way in.
|
||||
"""
|
||||
entries = ListContainer([
|
||||
Container(beat=beat, tempo=int(round(bpm * 100)), time=int(round(sec * 1000)))
|
||||
for beat, bpm, sec in beats
|
||||
])
|
||||
body = structs.PQTZ.build(Container(entry_count=len(entries), entries=entries))
|
||||
return _wrap("PQTZ", body)
|
||||
|
||||
|
||||
# ---- what rekordbox needs before it will show a grid or cues ------------------
|
||||
#
|
||||
# Measured on a rekordbox-written stick by removing tags one at a time: with
|
||||
# only PPTH + PQTZ + PCOB in the `.DAT` — the grid and cue tags byte-for-byte
|
||||
# rekordbox's own — rekordbox shows NO grid and NO hot cues. Adding PVBR alone
|
||||
# is not enough, nor PWAV + PWV2 alone; the full `.DAT` is. So every `.DAT`
|
||||
# carries all three. (The `.EXT` and `.2EX` waveforms only affect drawing.)
|
||||
|
||||
#: PVBR's entry count: 400 seek points plus one trailing value.
|
||||
_PVBR_ENTRIES = 401
|
||||
|
||||
|
||||
def vbr_tag(total_samples: int = 0) -> bytes:
|
||||
"""`PVBR` as rekordbox writes it for a constant-rate file.
|
||||
|
||||
400 zero seek offsets, then the track's length in SAMPLES — for an MP3,
|
||||
frames x 1152 (Demo Track 1: 6601 x 1152 = 7604352). An `.m4a` gets zero
|
||||
there too. A VBR MP3 presumably gets real offsets; none of the reference
|
||||
tracks is VBR, so that is unmeasured, and a zero index is what an `.m4a`
|
||||
carries and rekordbox accepts.
|
||||
"""
|
||||
body = struct.pack(">I", 0) + bytes(4 * (_PVBR_ENTRIES - 1)) + struct.pack(
|
||||
">I", max(0, int(total_samples)))
|
||||
return _wrap("PVBR", body)
|
||||
|
||||
|
||||
def mp3_samples(path: Path) -> int:
|
||||
"""An MP3's length in samples — frames x 1152 — for `PVBR`; 0 otherwise.
|
||||
|
||||
rekordbox writes this value only for MP3s (every `.m4a` carries 0).
|
||||
"""
|
||||
if path.suffix.lower() != ".mp3":
|
||||
return 0
|
||||
try:
|
||||
import mutagen
|
||||
|
||||
info = mutagen.File(str(path)).info
|
||||
return int(round(info.length * info.sample_rate / 1152)) * 1152
|
||||
except Exception: # an unreadable header costs the seek hint, not the export
|
||||
return 0
|
||||
|
||||
|
||||
#: PWAV height = K * sqrt(rms) + B, fitted against rekordbox's own previews of
|
||||
#: eight tracks (mean error 3.4 on the 0-31 scale, correlation 0.8). An absolute
|
||||
#: scale, not normalised per track — a quiet master draws smaller, as in rekordbox.
|
||||
_PWAV_K, _PWAV_B = 37.6, -5.2
|
||||
|
||||
|
||||
def preview_tags(rms, brightness) -> list[bytes]:
|
||||
"""`PWAV` (400 columns) and `PWV2` (100) from per-column RMS and brightness.
|
||||
|
||||
`PWAV`: one byte per column — whiteness (3 bits) << 5 | height (5 bits).
|
||||
`PWV2`: a 4-bit height per group of four `PWAV` columns, scaled so the
|
||||
track's tallest column is 15; that reproduces rekordbox's own to a mean
|
||||
error of 1.7. Whiteness loosely follows brightness in rekordbox's output
|
||||
(it is cosmetic: the colour of the blue-to-white preview).
|
||||
"""
|
||||
import numpy as np
|
||||
|
||||
rms = np.asarray(rms, dtype=float)
|
||||
heights = np.clip(np.round(_PWAV_K * np.sqrt(rms) + _PWAV_B), 0, 31).astype(int)
|
||||
white = np.clip(np.round(2.5 + 10.0 * np.asarray(brightness, dtype=float)), 0, 5).astype(int)
|
||||
pwav = bytes(int((w << 5) | h) for w, h in zip(white, heights))
|
||||
|
||||
tallest = max(int(heights.max()), 1)
|
||||
grouped = heights.reshape(100, 4).max(axis=1)
|
||||
pwv2 = bytes(int(v) for v in np.clip(np.round(grouped * 15 / tallest), 0, 15))
|
||||
return [
|
||||
_wrap("PWAV", struct.pack(">II", len(pwav), 0x10000) + pwav),
|
||||
_wrap("PWV2", struct.pack(">II", len(pwv2), 0x10000) + pwv2),
|
||||
]
|
||||
|
||||
|
||||
# ---- the detail and 3-band waveforms (`.EXT` / `.2EX`) -------------------------
|
||||
#
|
||||
# These only affect DRAWING — rekordbox shows the grid and cues without them — but
|
||||
# without them its song list has no preview and its deck draws a flat blue line,
|
||||
# and it warns the device was "analyzed by an older version". All constants are
|
||||
# fitted against rekordbox 7's own files for 12 local tracks, measured through
|
||||
# `core.waveform` exactly as the exporter measures (per-band mean error ~8 on the
|
||||
# 0-127 scale). rekordbox 7's song list draws `PWV6` — but ONLY for a track
|
||||
# whose `content.contentLink` is set (see the OneLibrary exporter); with it NULL
|
||||
# the row is plain blue whatever the files hold. `PWV4` is written by
|
||||
# distribution matching, not per-column fitting (see `_PWV4_MAPS`).
|
||||
|
||||
#: PWV7 byte per band = top * (energy / its 99.5th percentile) ** gamma.
|
||||
_PWV7 = ((88, 0.6), (92, 0.9), (68, 1.7)) # low, mid, high
|
||||
#: PWV6: the same, over 1200 overview columns (column = mean of its frames).
|
||||
_PWV6 = ((40, 0.5), (34, 0.5), (34, 0.5))
|
||||
#: PWVC: a per-band gain, = C / (the band's 99.5th percentile), floored at 80 —
|
||||
#: rekordbox's own values follow this to about +/-20%. What rekordbox does with
|
||||
#: it is not known; it is reproduced rather than invented.
|
||||
_PWVC_C, _PWVC_FLOOR = (20763.0, 15220.0, 12571.0), 80
|
||||
#: PWV3/PWV5 height (5 bits) from overall energy: 28 * x ** 1.5.
|
||||
_HEIGHT = (28, 1.5)
|
||||
#: PWV5 colour (3 bits each) from each band's SHARE of the frame's energy.
|
||||
_RGB = ((8.47, 0.54), (7.60, 0.47), (13.78, 1.83)) # red<-low, green<-mid, blue<-high
|
||||
_OVERVIEW_COLUMNS = 1200
|
||||
|
||||
#: PWV4 — the 6-byte colour overview. NOT what rekordbox 7's song list draws
|
||||
#: (that is PWV6: removing PWV6 from a rekordbox-written track left its row
|
||||
#: empty, removing PWV4 changed nothing); written because every rekordbox file
|
||||
#: carries it and its RGB mode and older players may read it. Per column: b0 overall level, b1 a
|
||||
#: companion of b0, b2 the height, b3/b4/b5 the low/mid/high (red/green/blue)
|
||||
#: levels. Two measured facts shape it: b4 and b5 are sampled at ONE instant per
|
||||
#: column (their column-to-column correlation is 0.05 and 0.16, against ~0.6 for
|
||||
#: the rest), and rekordbox's per-column bytes are too jumpy to reproduce one by
|
||||
#: one — so each byte is a QUANTILE MAP, (normalised measurement knots, byte
|
||||
#: knots), fitted on 12 tracks so the distribution matches rekordbox's (held-out
|
||||
#: medians within a few levels, the same spiky top end). b2 and b1 follow from
|
||||
#: the others by linear fits on rekordbox's own bytes (mean error 10 and 12).
|
||||
_PWV4_MAPS = {
|
||||
"b0": ((0.0, 0.1027, 0.1843, 0.3094, 0.3971, 0.4832, 0.5759, 0.6569, 0.731, 0.8102, 0.8973, 0.9419, 0.971, 1.1784),
|
||||
(0, 17, 28, 45, 56, 62, 65, 69, 74, 115, 127, 127, 127, 127)),
|
||||
"b3": ((0.0, 0.0135, 0.0473, 0.1407, 0.26, 0.3841, 0.5027, 0.5911, 0.6686, 0.7617, 0.8646, 0.9209, 0.9645, 1.1825),
|
||||
(0, 1, 4, 15, 24.7, 37, 44, 54, 62, 68, 89, 107, 120, 127)),
|
||||
"b4": ((0.0, 0.0305, 0.0654, 0.1307, 0.1855, 0.2325, 0.2819, 0.3342, 0.3977, 0.4809, 0.6036, 0.708, 0.8719, 1.2804),
|
||||
(0, 2, 7, 12, 17, 21, 25, 30, 35, 43, 62, 109, 127, 127)),
|
||||
"b5": ((0.0, 0.0077, 0.0223, 0.0511, 0.09, 0.1298, 0.1809, 0.2427, 0.3167, 0.4143, 0.5749, 0.7209, 0.863, 1.4313),
|
||||
(0, 1, 4, 7, 10, 12, 16, 20, 24, 31, 60, 127, 127, 127)),
|
||||
}
|
||||
|
||||
|
||||
def _pwv4(bands) -> bytes:
|
||||
import numpy as np
|
||||
|
||||
full = np.sqrt((bands ** 2).sum(axis=1))
|
||||
x = np.column_stack([bands, full]) # low, mid, high, full
|
||||
cols = [np.arange(len(x))[s] for s in even_slices(len(x), _OVERVIEW_COLUMNS)]
|
||||
mean = np.array([x[i].mean(axis=0) if len(i) else np.zeros(4) for i in cols])
|
||||
instant = np.array([x[i[len(i) // 2]] if len(i) else np.zeros(4) for i in cols])
|
||||
|
||||
def mapped(values, key):
|
||||
ref = float(np.percentile(values, 99.5)) or 1.0
|
||||
knots_x, knots_y = _PWV4_MAPS[key]
|
||||
return np.clip(np.round(np.interp(values / ref, knots_x, knots_y)), 0, 127).astype(int)
|
||||
|
||||
b0, b3 = mapped(mean[:, 3], "b0"), mapped(mean[:, 0], "b3")
|
||||
b4, b5 = mapped(instant[:, 1], "b4"), mapped(instant[:, 2], "b5")
|
||||
b2 = np.clip(np.round(0.83 * np.maximum(b3, np.maximum(b4, b5)) + 11.6), 0, 127).astype(int)
|
||||
b1 = np.clip(np.round(235.2 - 0.77 * b0), 0, 255).astype(int)
|
||||
return np.column_stack([b0, b1, b2, b3, b4, b5]).astype(np.uint8).tobytes()
|
||||
|
||||
|
||||
def _norm(x, top: float, gamma: float, cap: int):
|
||||
import numpy as np
|
||||
|
||||
ref = float(np.percentile(x, 99.5)) or 1.0
|
||||
return np.clip(np.round(top * np.clip(x / ref, 0, None) ** gamma), 0, cap).astype(int)
|
||||
|
||||
|
||||
def waveform_tags(bands) -> tuple[list[bytes], list[bytes]]:
|
||||
"""(`.EXT` tags, `.2EX` tags) from 150-per-second low/mid/high band energy.
|
||||
|
||||
`.EXT`: `PWV3` (detail, 1 byte: whiteness << 5 | height), `PWV5` (detail
|
||||
colour, 2 bytes: rrr ggg bbb hhhhh 00) and `PWV4` (the RGB-mode colour
|
||||
overview, 1200 x 6 bytes — see `_PWV4_MAPS`). `.2EX`: `PWV7` (3-band detail, one
|
||||
byte per band), `PWV6` (3-band overview, 1200 columns) and `PWVC`. The frames
|
||||
must already be on rekordbox's clock (`waveform.analyse(lead=offset)`).
|
||||
"""
|
||||
import numpy as np
|
||||
|
||||
bands = np.asarray(bands, dtype=float)
|
||||
n = len(bands)
|
||||
full = np.sqrt((bands ** 2).sum(axis=1))
|
||||
share = bands / (bands.sum(axis=1, keepdims=True) + 1e-12)
|
||||
|
||||
height = _norm(full, *_HEIGHT, 31)
|
||||
white = np.clip(np.round(2.5 + 10.0 * share[:, 2]), 0, 7).astype(int)
|
||||
pwv3 = bytes(int((w << 5) | h) for w, h in zip(white, height))
|
||||
rgb = [np.clip(np.round(k * share[:, i] + c), 0, 7).astype(int)
|
||||
for i, (k, c) in enumerate(_RGB)]
|
||||
pwv5 = b"".join(struct.pack(">H", (int(r) << 13) | (int(g) << 10) | (int(b) << 7) | (int(h) << 2))
|
||||
for r, g, b, h in zip(*rgb, height))
|
||||
|
||||
pwv7 = np.stack([_norm(bands[:, i], top, g, 127) for i, (top, g) in enumerate(_PWV7)], axis=1)
|
||||
cols = np.array([bands[s].mean(axis=0) if n else np.zeros(3)
|
||||
for s in even_slices(n, _OVERVIEW_COLUMNS)])
|
||||
pwv6 = np.stack([_norm(cols[:, i], top, g, 127) for i, (top, g) in enumerate(_PWV6)], axis=1)
|
||||
gains = [max(_PWVC_FLOOR, int(round(c / (float(np.percentile(bands[:, i], 99.5)) or 1.0))))
|
||||
for i, c in enumerate(_PWVC_C)]
|
||||
|
||||
ext = [
|
||||
_wrap("PWV3", struct.pack(">III", 1, n, 0x00960000) + pwv3),
|
||||
_wrap("PWV5", struct.pack(">III", 2, n, 0x00960305) + pwv5),
|
||||
_wrap("PWV4", struct.pack(">III", 6, _OVERVIEW_COLUMNS, 0) + _pwv4(bands)),
|
||||
]
|
||||
two_ex = [
|
||||
_wrap("PWV7", struct.pack(">III", 3, n, 0x00960000) + pwv7.astype(np.uint8).tobytes()),
|
||||
_wrap("PWV6", struct.pack(">II", 3, _OVERVIEW_COLUMNS) + pwv6.astype(np.uint8).tobytes()),
|
||||
_wrap("PWVC", struct.pack(">H", 0) + struct.pack(">HHH", *[min(g, 0xFFFF) for g in gains])),
|
||||
]
|
||||
return ext, two_ex
|
||||
|
||||
|
||||
def flat_preview_tags() -> list[bytes]:
|
||||
"""Empty previews, for a file nothing could decode, so the grid and cues can
|
||||
still show. That an all-zero preview satisfies rekordbox is an assumption,
|
||||
by analogy with the all-zero PVBR every `.m4a` carries — not measured."""
|
||||
return preview_tags([0.0] * 400, [0.0] * 400)
|
||||
|
||||
|
||||
def _pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
|
||||
rgb: tuple[int, int, int] | None, beats: int | None, code: int = 0) -> 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.
|
||||
"""
|
||||
comment = b""
|
||||
red, green, blue = rgb or (0, 0, 0)
|
||||
return struct.pack(
|
||||
">4sIIIBxHIIBB6xHHI",
|
||||
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),
|
||||
# The colour is the palette CODE, then RGB: rekordbox draws from the code
|
||||
# (`palette`); a code of 0 draws its default colour whatever the RGB says.
|
||||
) + comment + struct.pack(">4B", code & 0xFF, red, green, blue) + bytes(
|
||||
PCP2_ENTRY_LEN - 48 - len(comment)
|
||||
)
|
||||
|
||||
|
||||
def _pcpt_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None) -> bytes:
|
||||
"""One `PCPT` entry, byte-for-byte as rekordbox 7 writes it.
|
||||
|
||||
`len_header` is **28**, not 12: a reader that trusts it finds the body 16
|
||||
bytes early.
|
||||
Status is 0 on a hot cue and 4 on a memory cue, and rekordbox leaves the
|
||||
linked-list order fields at 0xFFFF rather than linking the entries.
|
||||
"""
|
||||
return struct.pack(
|
||||
">4sIIIIIHHBxHII",
|
||||
b"PCPT", 28, PCPT_ENTRY_LEN, hot_cue,
|
||||
0 if hot_cue else 4,
|
||||
0x10000, 0xFFFF, 0xFFFF, kind, 1000,
|
||||
int(time_ms), NO_LOOP if loop_ms is None else int(loop_ms),
|
||||
) + bytes(16)
|
||||
|
||||
|
||||
def _pcob(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.
|
||||
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:
|
||||
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
|
||||
)
|
||||
return _wrap("PCO2", struct.pack(">IHH", cue_type, len(chosen), 0) + blob)
|
||||
|
||||
|
||||
def cue_tags(cues: list[dict], *, extended: bool) -> list[bytes]:
|
||||
"""The cue tags for one file, in the order and shape rekordbox writes them.
|
||||
|
||||
`.DAT`: `PCOB` hot (pads 1-3), `PCOB` memory (every memory cue).
|
||||
`.EXT`: `PCOB` hot (pads 4 and up), `PCOB` memory (EMPTY), then `PCO2` hot
|
||||
and `PCO2` memory — each the complete list of its kind.
|
||||
|
||||
**Every list is written even when empty.** A rekordbox file always carries
|
||||
all of them, and a file missing one is not a shape rekordbox produces.
|
||||
Hot cues are ordered by pad, HIGHEST first, which is also what it does.
|
||||
"""
|
||||
hot = sorted((c for c in cues if c["hot_cue"]), key=lambda c: -c["hot_cue"])
|
||||
memory = sorted((c for c in cues if not c["hot_cue"]), key=lambda c: c["time_ms"])
|
||||
if not extended:
|
||||
return [_pcob(1, [c for c in hot if c["hot_cue"] <= 3]), _pcob(0, memory)]
|
||||
return [
|
||||
_pcob(1, [c for c in hot if c["hot_cue"] > 3]),
|
||||
_pcob(0, []),
|
||||
_pco2(1, hot),
|
||||
_pco2(0, memory),
|
||||
]
|
||||
|
||||
|
||||
#: `PMAI` + len_header + len_file + four unknowns.
|
||||
_FILE_HEADER_LEN = 28
|
||||
|
||||
|
||||
def anlz_bytes(tags: list[bytes]) -> bytes:
|
||||
"""Assemble an ANLZ file from built tag bytes."""
|
||||
body = b"".join(tags)
|
||||
header = struct.pack(
|
||||
">4sIIIIII", b"PMAI", _FILE_HEADER_LEN, _FILE_HEADER_LEN + len(body),
|
||||
FILE_HEADER_U1, FILE_HEADER_U2, FILE_HEADER_U3, 0,
|
||||
)
|
||||
return header + body
|
||||
|
||||
|
||||
def write_anlz(path: Path, tags: list[bytes]) -> Path:
|
||||
"""Assemble and write an ANLZ file from built tag bytes."""
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(anlz_bytes(tags))
|
||||
return path
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Cover art the way a Pioneer library stores it: two small square JPEGs.
|
||||
|
||||
Measured on a rekordbox 7 USB export rather than assumed:
|
||||
|
||||
* two sizes per image — **80 x 80** (`<n>.jpg`) and **240 x 240** (`<n>_m.jpg`);
|
||||
* **baseline JPEG at quality 85, 4:2:0** — its quantisation table is libjpeg's
|
||||
standard table scaled to exactly 85, with no EXIF and a plain JFIF header;
|
||||
* a non-square cover is **letterboxed onto black**, aspect kept and centred.
|
||||
Motorola's 4112 x 1112 art matches rekordbox's own to a mean of 1.8 levels
|
||||
that way; a centre crop is off by 26, a stretch by 19.5.
|
||||
|
||||
Where the files go and how the database points at them is the target's business
|
||||
(a OneLibrary drive: `PIONEER/Artwork/00001/`, see its exporter).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import logging
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
SMALL, MEDIUM = 80, 240
|
||||
#: A master.db library also keeps a LARGE copy: the cover itself, aspect kept,
|
||||
#: scaled down to fit 800 px (never up) — Motorola's 4112 x 1112 art is stored
|
||||
#: 800 x 216, a 640 or 300 px cover unchanged.
|
||||
LARGE = 800
|
||||
_QUALITY = 85
|
||||
|
||||
|
||||
def _square(image, size: int):
|
||||
from PIL import Image
|
||||
|
||||
fitted = image.copy()
|
||||
fitted.thumbnail((size, size), Image.BICUBIC) # the closest of Pillow's filters
|
||||
canvas = Image.new("RGB", (size, size), (0, 0, 0))
|
||||
canvas.paste(fitted, ((size - fitted.width) // 2, (size - fitted.height) // 2))
|
||||
return canvas
|
||||
|
||||
|
||||
def _jpeg(image) -> bytes:
|
||||
out = io.BytesIO()
|
||||
# subsampling=2 is 4:2:0; progressive/optimize off = the baseline rekordbox writes.
|
||||
image.save(out, format="JPEG", quality=_QUALITY, subsampling=2,
|
||||
progressive=False, optimize=False)
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
def _open(data: bytes):
|
||||
from PIL import Image
|
||||
|
||||
try:
|
||||
with Image.open(io.BytesIO(data)) as src:
|
||||
src.load()
|
||||
return src.convert("RGB") # PNG alpha / palette / CMYK -> RGB
|
||||
except Exception as ex: # noqa: BLE001 — any unreadable image
|
||||
log.warning("could not read cover art (%s); exporting without it", ex)
|
||||
return None
|
||||
|
||||
|
||||
def library_jpegs(data: bytes) -> tuple[bytes, bytes, bytes] | None:
|
||||
"""(large, 240 px, 80 px) for a `master.db` library — `artwork.jpg`,
|
||||
`artwork_m.jpg`, `artwork_s.jpg` — or None when the image cannot be read."""
|
||||
from PIL import Image
|
||||
|
||||
rgb = _open(data)
|
||||
if rgb is None:
|
||||
return None
|
||||
large = rgb.copy()
|
||||
large.thumbnail((LARGE, LARGE), Image.BICUBIC)
|
||||
return _jpeg(large), _jpeg(_square(rgb, MEDIUM)), _jpeg(_square(rgb, SMALL))
|
||||
|
||||
|
||||
def pioneer_jpegs(data: bytes) -> tuple[bytes, bytes] | None:
|
||||
"""(80 px JPEG, 240 px JPEG) from any image the source library holds, or None
|
||||
when it cannot be read — a bad cover costs the artwork, not the export."""
|
||||
try:
|
||||
from PIL import Image
|
||||
|
||||
with Image.open(io.BytesIO(data)) as src:
|
||||
src.load()
|
||||
rgb = src.convert("RGB") # PNG alpha / palette / CMYK -> RGB
|
||||
except Exception as ex: # noqa: BLE001 — any unreadable image
|
||||
log.warning("could not read cover art (%s); exporting without it", ex)
|
||||
return None
|
||||
return _jpeg(_square(rgb, SMALL)), _jpeg(_square(rgb, MEDIUM))
|
||||
@@ -0,0 +1,161 @@
|
||||
"""Rekordbox's beatgrid <-> the generic marker list.
|
||||
|
||||
**Rekordbox does not store markers.** There is no beatgrid table in
|
||||
``master.db`` at all; the grid lives in the track's ANLZ analysis file as a
|
||||
``PQTZ`` tag holding EVERY BEAT explicitly — beat-number-in-bar, BPM and time,
|
||||
one entry per beat (a 4-minute track is ~500 entries).
|
||||
|
||||
Konduktor's generic model is a marker list, so this module is the projection
|
||||
between the two:
|
||||
|
||||
* read — collapse runs of equal BPM into one marker each, so a constant-tempo
|
||||
track becomes a list of length one and a variable-tempo track becomes one
|
||||
marker per tempo change. This is exactly the shape ``core.model.GridMarker``
|
||||
describes.
|
||||
* write — expand a marker list back into a full beat list (milestone 2; the
|
||||
read direction is what a read-only adapter needs).
|
||||
|
||||
BPMs are compared with a tolerance because Rekordbox stores them as hundredths
|
||||
and floating-point division reintroduces noise; two beats within `BPM_EPSILON`
|
||||
are the same tempo and must not produce a spurious marker.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from ...core.model import GridMarker
|
||||
|
||||
BPM_EPSILON = 0.005 # half of the 0.01 BPM Rekordbox can actually represent
|
||||
|
||||
|
||||
def markers_from_beats(
|
||||
times: list[float], bpms: list[float], beats: list[int] | None = None
|
||||
) -> list[GridMarker]:
|
||||
"""Collapse a per-beat grid into the generic marker list.
|
||||
|
||||
`times` are seconds, `bpms` the tempo in force at each beat, `beats` the
|
||||
beat-in-bar (1-4) of each. A marker is emitted for the start of the grid and
|
||||
wherever the tempo changes.
|
||||
|
||||
**The first marker goes on the first DOWNBEAT**, not the first beat. In the
|
||||
generic model the first marker is bar 1 (Traktor's convention), but a
|
||||
Pioneer grid often starts mid-bar: Motorola's opens on beat 3 at 0.026 s,
|
||||
with its first downbeat at 0.986 s. Put the marker on the first beat and
|
||||
every bar lands two beats early — in Traktor after an import, and on the
|
||||
CDJ after an export. The beats before it are not lost: a grid extends back
|
||||
to the start of the track from its first marker, and `beats_from_markers`
|
||||
writes them back numbered as they were.
|
||||
"""
|
||||
if not times or not bpms:
|
||||
return []
|
||||
out: list[GridMarker] = []
|
||||
last_bpm: float | None = None
|
||||
for i, (t, bpm) in enumerate(zip(times, bpms)):
|
||||
if last_bpm is None or abs(bpm - last_bpm) > BPM_EPSILON:
|
||||
out.append(GridMarker(start=float(t), bpm=float(bpm), name=None, companion=None))
|
||||
last_bpm = float(bpm)
|
||||
if beats and out:
|
||||
# The first tempo run ends where the second marker starts (or never).
|
||||
run_end = out[1].start if len(out) > 1 else float("inf")
|
||||
downbeat = next((t for t, b in zip(times, beats) if int(b) == 1 and t < run_end), None)
|
||||
if downbeat is not None:
|
||||
out[0] = out[0].model_copy(update={"start": float(downbeat)})
|
||||
return out
|
||||
|
||||
|
||||
def beats_from_markers(
|
||||
markers: list[GridMarker], duration_sec: float
|
||||
) -> tuple[list[int], list[float], list[float]]:
|
||||
"""Expand a marker list into the per-beat arrays Rekordbox stores.
|
||||
|
||||
Each marker governs until the next one; the last runs to `duration_sec`.
|
||||
Returns ``(beat_in_bar, bpms, times)`` with beat numbers cycling 1-4 from
|
||||
each marker, which is how Rekordbox numbers bars.
|
||||
|
||||
The first marker's tempo also runs BACKWARDS to the start of the track: a
|
||||
grid covers the whole track in Traktor and in rekordbox alike, and a marker
|
||||
placed on the first downbeat (see `markers_from_beats`) has beats before it
|
||||
— numbered 4, 3, … counting back, which reproduces rekordbox's own grid.
|
||||
"""
|
||||
beat_nums: list[int] = []
|
||||
bpms: list[float] = []
|
||||
times: list[float] = []
|
||||
if not markers:
|
||||
return beat_nums, bpms, times
|
||||
ordered = sorted(markers, key=lambda m: m.start)
|
||||
|
||||
first = next((m for m in ordered if m.bpm > 0), None)
|
||||
if first is not None:
|
||||
step = 60.0 / first.bpm
|
||||
lead = int((first.start + 1e-9) // step) # whole beats that fit before it
|
||||
for k in range(lead, 0, -1):
|
||||
beat_nums.append((-k) % 4 + 1)
|
||||
bpms.append(first.bpm)
|
||||
times.append(first.start - k * step)
|
||||
for i, m in enumerate(ordered):
|
||||
if m.bpm <= 0:
|
||||
continue
|
||||
end = ordered[i + 1].start if i + 1 < len(ordered) else duration_sec
|
||||
step = 60.0 / m.bpm
|
||||
t = m.start
|
||||
n = 1
|
||||
# Guard against a zero/negative span producing an endless loop.
|
||||
while t < end - 1e-9 and step > 0:
|
||||
# A beat before the audio starts is skipped but still COUNTED, so the
|
||||
# next one keeps its place in the bar. The generic model can hold one
|
||||
# (a Traktor grid anchored inside an MP3's header frame reads
|
||||
# negative); rekordbox stores no negative times, and clamping it to 0
|
||||
# would invent a beat there.
|
||||
if t >= 0.0:
|
||||
beat_nums.append(n)
|
||||
bpms.append(m.bpm)
|
||||
times.append(t)
|
||||
n = n % 4 + 1
|
||||
t += step
|
||||
return beat_nums, bpms, times
|
||||
|
||||
|
||||
# ---- writing the analysis file ----------------------------------------------
|
||||
#
|
||||
# The grid lives in the ANLZ files, and only `.DAT`'s `PQTZ` tag is written here.
|
||||
# `.EXT` carries a second, "extended" grid (`PQT2`) whose per-beat byte and `u3`
|
||||
# field are NOT decoded — `pyrekordbox` itself calls the field `unkown` — so
|
||||
# rewriting it would mean guessing at bytes in real user data that has no version
|
||||
# history. Leaving it alone is the only safe option until it is decoded.
|
||||
#
|
||||
# `.DAT`/`.EXT` round-trip byte-identically through parse -> build (verified
|
||||
# across a whole library), which is what makes this checkable at all: a rebuild
|
||||
# must differ ONLY inside the tag we touched.
|
||||
|
||||
|
||||
def write_pqtz(path, beat_nums, bpms, times) -> bool:
|
||||
"""Replace the beat grid in an ANLZ `.DAT`, in place. True if written.
|
||||
|
||||
`pyrekordbox`'s own `PQTZAnlzTag.set*()` refuse to change the NUMBER of
|
||||
beats ("only values of existing beats can be set"), and every real grid edit
|
||||
changes it — so the entry list is rebuilt directly and the tag's own
|
||||
`update_len()` recomputes `len_tag`. `check_parse()` then asserts the
|
||||
declared count and the list agree before anything is written.
|
||||
"""
|
||||
import construct
|
||||
from pyrekordbox.anlz import AnlzFile
|
||||
|
||||
anlz = AnlzFile.parse_file(str(path))
|
||||
tag = next((t for t in anlz.tags if t.type == "PQTZ"), None)
|
||||
if tag is None:
|
||||
return False
|
||||
entries = construct.ListContainer()
|
||||
for beat, bpm, t in zip(beat_nums, bpms, times):
|
||||
entries.append(
|
||||
construct.Container(
|
||||
beat=int(beat),
|
||||
tempo=int(round(bpm * 100)), # BPM is stored x100
|
||||
time=int(round(t * 1000)), # seconds -> ms
|
||||
)
|
||||
)
|
||||
tag.struct.content.entries = entries
|
||||
tag.struct.content.entry_count = len(entries)
|
||||
tag.update_len()
|
||||
tag.check_parse()
|
||||
data = anlz.build()
|
||||
with open(path, "wb") as fh:
|
||||
fh.write(data)
|
||||
return True
|
||||
@@ -0,0 +1,109 @@
|
||||
"""What a Rekordbox library can persist.
|
||||
|
||||
**Track metadata and playlists are writable; cues and the beatgrid are not.**
|
||||
The spike verified that Rekordbox accepts writes which maintain its USN columns
|
||||
(see the handoff's Findings), and those two write paths use `pyrekordbox`, which
|
||||
maintains them. Cues and the grid are separate hand-written stores and stay
|
||||
false until milestone 3 — the capability system exists precisely so the UI never
|
||||
offers an edit that will not persist.
|
||||
|
||||
A **cloud-synced** library reports `writable=False` regardless: Konduktor will
|
||||
not write one at all.
|
||||
|
||||
Two facts are already known and encoded, because getting them wrong later would
|
||||
be a silent data bug rather than a missing feature:
|
||||
|
||||
* a saved loop is a cue with an out-point, NOT a separate bank, so
|
||||
``loops="cue_type"`` — the same answer as Traktor, and NOT the
|
||||
``separate_bank`` the original plan assumed;
|
||||
* cue colour is a PALETTE index (``djmdCue.ColorTableIndex``), not free RGB,
|
||||
and the palette is a built-in table — `djmdColor` is the *track* colour
|
||||
palette and is unrelated.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from ...core.capabilities import (
|
||||
Capabilities,
|
||||
CueCapabilities,
|
||||
GridCapabilities,
|
||||
PlaylistCapabilities,
|
||||
SaveCapabilities,
|
||||
TrackCapabilities,
|
||||
)
|
||||
from . import palette
|
||||
from .cue_types import WRITABLE_CUE_TYPES
|
||||
|
||||
# Rekordbox's addressable hot cue bank. The pads are labelled A-H; the stored
|
||||
# slot number is NOT a plain letter index (see cue_types), so the adapter keeps
|
||||
# slots numeric and lets the UI label them.
|
||||
HOTCUE_SLOTS = 8
|
||||
|
||||
|
||||
def capabilities_for(
|
||||
path,
|
||||
version: str | None = None,
|
||||
*,
|
||||
cloud_synced: bool = False,
|
||||
editable_fields: list[str] | None = None,
|
||||
) -> Capabilities:
|
||||
# A cloud-synced library is refused PERMANENTLY, not pending a milestone:
|
||||
# a local edit the server did not issue could propagate a broken sync state
|
||||
# to the user's other machines, which version history cannot undo.
|
||||
return Capabilities(
|
||||
platform="rekordbox",
|
||||
version=version,
|
||||
writable=not cloud_synced,
|
||||
readonly_cause="cloud_synced" if cloud_synced else None,
|
||||
cues=CueCapabilities(
|
||||
# Hot cues are writable: djmdCue rows plus the contentCue JSON
|
||||
# mirror, kept in step. MEMORY cues stay preserved-but-uneditable —
|
||||
# Rekordbox is the only platform that has them, and the two-platform
|
||||
# promotion rule says a one-platform concept does not become an
|
||||
# editing feature.
|
||||
editable=True,
|
||||
hotcue_slots=HOTCUE_SLOTS,
|
||||
slot_labels="letter",
|
||||
# Rekordbox is the only platform with memory cues, so they are
|
||||
# projected and PRESERVED but not editable (two-platform rule).
|
||||
memory_cues=True,
|
||||
max_memory_cues=None, # unlimited
|
||||
# Both cue types write; Rekordbox has no fade/load types.
|
||||
types=WRITABLE_CUE_TYPES,
|
||||
# A hot cue's colour is one of rekordbox's swatches (the 15 that
|
||||
# were measured, see `palette`), offered in rekordbox's own order.
|
||||
color="palette",
|
||||
palette=[palette.hex_for(code) for code in palette.SWATCHES],
|
||||
named=True, # djmdCue.Comment
|
||||
loops="cue_type",
|
||||
),
|
||||
# The grid is written into the track's ANLZ .DAT (PQTZ). Verified:
|
||||
# Rekordbox reads the grid and its BPM readout from there, and leaves a
|
||||
# Konduktor-written file alone. It has no per-track grid lock.
|
||||
grid=GridCapabilities(editable=True, flexible=True, lockable=False),
|
||||
tracks=TrackCapabilities(
|
||||
rating_max=5, # Rekordbox stores 0-5 directly, unlike Traktor's /51
|
||||
# Narrower than Traktor's: `producer` and `mix` have no Rekordbox
|
||||
# column (its Composer is a different field), so they are absent
|
||||
# rather than mapped onto something approximate.
|
||||
editable_fields=sorted(editable_fields or []),
|
||||
# A stem file is held (and played by Rekordbox as its mix);
|
||||
# Konduktor's deck plays its stems.
|
||||
media_kinds=["audio", "stem"],
|
||||
removable=True,
|
||||
addable=True,
|
||||
artwork=False,
|
||||
artwork_note=None,
|
||||
),
|
||||
playlists=PlaylistCapabilities(folders=True, smart="read_only", reorder=True),
|
||||
save=SaveCapabilities(
|
||||
app_name="Rekordbox",
|
||||
library_label="master.db",
|
||||
# Rekordbox holds master.db open while running and cloud-syncs it,
|
||||
# so a concurrent write is riskier than Traktor's overwrite-on-exit.
|
||||
overwrite_risk="while_running",
|
||||
# The artefact set is master.db + N ANLZ files + masterPlaylists6.xml,
|
||||
# and history.py tracks a single blob. Also, restoring master.db
|
||||
# wholesale would roll back Rekordbox's auth token and sampler state.
|
||||
history=False,
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,103 @@
|
||||
"""Rekordbox's ``djmdCue.Kind`` encoding <-> the generic cue vocabulary.
|
||||
|
||||
The only place these integers are given meaning. Verified against a real
|
||||
library (see the handoff's Findings section):
|
||||
|
||||
* ``Kind == 0`` -> a MEMORY cue: no bank slot, and Rekordbox allows any
|
||||
number of them.
|
||||
* ``Kind >= 1`` -> a HOT CUE.
|
||||
|
||||
**``Kind`` is 1-based AND it skips 4.** Konduktor's generic model numbers bank
|
||||
slots from zero — slot 0 is the pad the UI labels "A", which is also how Traktor
|
||||
stores its ``HOTCUE`` attribute. Rekordbox's first pad is ``Kind=1``, and the
|
||||
value ``4`` is reserved: the bank runs 1, 2, 3, 5, 6, 7, 8, 9.
|
||||
|
||||
Measured, not guessed. A loop was written at every ``Kind`` from 1 to 8, ten
|
||||
seconds apart, and read off a real deck:
|
||||
|
||||
Kind 1 2 3 4 5 6 7 8 9
|
||||
pad A B C - D E F G H
|
||||
|
||||
``Kind=4`` appears on no pad at all; Rekordbox shows such a cue as a memory cue.
|
||||
That one gap explains two earlier puzzles: a Rekordbox-authored loop on pad F
|
||||
stored ``Kind=7``, and a Konduktor cue written as ``Kind=4`` vanished from the
|
||||
bank. Getting this wrong silently moves cues to the wrong pad — or loses them
|
||||
from the bank entirely.
|
||||
|
||||
**``Kind`` is treated as an opaque slot id.** Setting cues on pads A and C
|
||||
stored 1 and 3, but the pad in the 6th position stored 7, so the slot -> letter
|
||||
mapping is NOT a plain index and has not been pinned down. Nothing here depends
|
||||
on it: the adapter addresses cues by slot number and the UI labels them, which
|
||||
is what ``capabilities.cues.slot_labels`` is for.
|
||||
|
||||
Loop-ness is NOT carried by ``Kind``. A loop is an ordinary cue row that also
|
||||
has an out-point, so a loop can sit in a hot cue slot or be a memory cue.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
MEMORY_KIND = 0
|
||||
|
||||
# Rekordbox has no fade-in/fade-out/load cues; those are Traktor-only.
|
||||
CUE_TYPES = ["cue", "loop"]
|
||||
|
||||
# What Konduktor will write. Loops were disabled for a while because a loop
|
||||
# written at `Kind=4` disappeared from the bank — which turned out to be the
|
||||
# reserved-Kind gap above, not anything to do with loops. Both types write.
|
||||
WRITABLE_CUE_TYPES = ["cue", "loop"]
|
||||
|
||||
|
||||
# The Kind value that is not a bank slot. Everything at or above it is shifted
|
||||
# by one relative to the pad index.
|
||||
RESERVED_KIND = 4
|
||||
|
||||
|
||||
def role_and_slot(kind: int | None) -> tuple[str, int | None]:
|
||||
"""(role, 0-based slot) for a native ``Kind``.
|
||||
|
||||
A cue at `RESERVED_KIND` occupies no pad, so it is projected as a memory cue
|
||||
— which is how Rekordbox itself displays one.
|
||||
"""
|
||||
if kind is None or kind == MEMORY_KIND or int(kind) == RESERVED_KIND:
|
||||
return "memory", None
|
||||
kind = int(kind)
|
||||
return "hotcue", kind - 1 if kind < RESERVED_KIND else kind - 2
|
||||
|
||||
|
||||
def kind_for(role: str, slot: int | None) -> int:
|
||||
"""The native ``Kind`` for a generic (role, 0-based slot).
|
||||
|
||||
Inverse of `role_and_slot`; skips `RESERVED_KIND`.
|
||||
"""
|
||||
if role == "memory":
|
||||
return MEMORY_KIND
|
||||
if slot is None:
|
||||
raise ValueError("a hot cue needs a slot")
|
||||
slot = int(slot)
|
||||
if slot < 0:
|
||||
raise ValueError(f"a hot cue slot cannot be negative, got {slot}")
|
||||
return slot + 1 if slot < RESERVED_KIND - 1 else slot + 2
|
||||
|
||||
|
||||
def cue_type(out_msec: int | None) -> str:
|
||||
"""A cue with a real out-point is a loop; everything else is a plain cue.
|
||||
|
||||
Rekordbox writes ``OutMsec = -1`` for a non-loop.
|
||||
"""
|
||||
return "loop" if out_msec is not None and out_msec > 0 else "cue"
|
||||
|
||||
|
||||
def beat_loop_size(beats: int) -> int:
|
||||
"""Encode a loop's musical length.
|
||||
|
||||
``BeatLoopSize = (beats << 16) | 1`` — verified against two real loops at
|
||||
different tempos (1 beat @125 BPM = 0x10001, 4 beats @120 BPM = 0x40001),
|
||||
each agreeing with the measured millisecond span.
|
||||
"""
|
||||
return (int(beats) << 16) | 1
|
||||
|
||||
|
||||
def beats_in_loop(beat_loop_size: int | None) -> int | None:
|
||||
"""Decode `beat_loop_size`. None when unset."""
|
||||
if not beat_loop_size:
|
||||
return None
|
||||
return beat_loop_size >> 16
|
||||
@@ -0,0 +1,237 @@
|
||||
"""The "Rekordbox Export" target: a USB stick's legacy Device Library (`export.pdb`).
|
||||
|
||||
What Rekordbox lists as a stick's **Device Library**, and what pre-OneLibrary
|
||||
players (CDJ-2000NXS2, many XDJs) read. Not to be confused with the "Rekordbox
|
||||
Library" target (`export.py`), which writes a COMPUTER library (`master.db`)
|
||||
that Rekordbox never reads from a stick.
|
||||
|
||||
## Shared with the OneLibrary target — deliberately
|
||||
|
||||
Rekordbox's own device export writes `export.pdb` AND `exportLibrary.db`, both
|
||||
pointing at ONE set of audio, analysis files and artwork. This target does the
|
||||
same: the analysis files are written by the OneLibrary exporter's own
|
||||
`_write_anlz`, at the same paths (`PIONEER/USBANLZ/P0xx/xxxxxxxx/`), and the
|
||||
artwork is the `a<n>.jpg` pair the OneLibrary target also writes (rekordbox's
|
||||
`a` files are the ones `export.pdb` names; OneLibrary's `image` table names the
|
||||
byte-identical `b` files). When both targets are ticked, whichever runs second
|
||||
finds the analysis already on the stick — written moments ago by the first, as
|
||||
the runner clears the previous export before copying — and reuses it rather
|
||||
than decoding every track again.
|
||||
|
||||
## The database
|
||||
|
||||
`pdb.PdbWriter` fills rekordbox's own empty device library (a template) with
|
||||
rows; see `pdb.py` for the format and why a template. Values follow a real
|
||||
rekordbox 7 device export:
|
||||
|
||||
* `bitmask` 0xC0700 — the same value as OneLibrary's `content.contentLink`,
|
||||
which is what makes rekordbox draw a track's song-list preview there;
|
||||
* `u2` = the track id + 0x600 (rekordbox: masterContentId + 0x600);
|
||||
* `u3`/`u4` = 0: they are the halves of rekordbox's `masterDbId`, the link to a
|
||||
computer's collection, which a Konduktor export does not claim;
|
||||
* `u5` 0x29 (= `analysedBits` 41), `u6` the file type, `u7` 3;
|
||||
* strings "ON" for kuvo_public / autoload_hotcues; the three unnamed strings
|
||||
rekordbox fills from its phrase analysis are left EMPTY — this exporter
|
||||
writes no phrases, and whether players care is what the device test checks.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
|
||||
from . import artwork, pdb
|
||||
from .projection import render_key
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
PDB_DIR = Path("PIONEER") / "rekordbox"
|
||||
OTHER_PLAYLIST = "Other"
|
||||
BITMASK = 0xC0700
|
||||
ANALYSED = 0x29
|
||||
|
||||
|
||||
class RekordboxDeviceExporter:
|
||||
platform = "rekordbox_export"
|
||||
menu_order = 30
|
||||
display_name = "Rekordbox Export"
|
||||
library_filename = str(PDB_DIR / "export.pdb")
|
||||
#: A player looks for `PIONEER/` at the root of the stick.
|
||||
drive_root = True
|
||||
|
||||
def capabilities(self):
|
||||
"""What a stick's device library can hold — the OneLibrary target's
|
||||
answer, since both describe the same drive and its analysis files."""
|
||||
from ..onelibrary.export import OneLibraryExporter
|
||||
|
||||
return OneLibraryExporter().capabilities()
|
||||
|
||||
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
|
||||
# Imported here, not at module level: the OneLibrary package imports this
|
||||
# package's modules, and a module-level import would be circular.
|
||||
from ..onelibrary.export import (
|
||||
OneLibraryExporter, _anlz_dir, _audio_format, _drive_relative, _file_type, _kbps,
|
||||
)
|
||||
|
||||
root = Path(destination)
|
||||
(root / PDB_DIR).mkdir(parents=True, exist_ok=True)
|
||||
today = date.today().isoformat()
|
||||
drive = OneLibraryExporter()
|
||||
extra: list[Path] = []
|
||||
|
||||
ids = {name: {} for name in ("artist", "album", "genre", "label", "key")}
|
||||
rows = {t: [] for t in (pdb.TRACKS, pdb.ARTISTS, pdb.ALBUMS, pdb.GENRES,
|
||||
pdb.LABELS, pdb.KEYS, pdb.ARTWORK)}
|
||||
builders = {"artist": (pdb.ARTISTS, pdb.artist_row), "album": (pdb.ALBUMS, pdb.album_row),
|
||||
"genre": (pdb.GENRES, pdb.id_string_row), "label": (pdb.LABELS, pdb.id_string_row),
|
||||
"key": (pdb.KEYS, pdb.key_row)}
|
||||
|
||||
def lookup(kind: str, name: str | None) -> int:
|
||||
if not name:
|
||||
return 0
|
||||
table = ids[kind]
|
||||
if name not in table:
|
||||
table[name] = len(table) + 1
|
||||
t, build = builders[kind]
|
||||
rows[t].append(build(table[name], name))
|
||||
return table[name]
|
||||
|
||||
by_source: dict[str, int] = {}
|
||||
art_n = 0
|
||||
total = len(payload.tracks)
|
||||
for n, item in enumerate(payload.tracks, start=1):
|
||||
payload.checkpoint(f"Writing the device library: {item.track.title or item.destination.name} ({n}/{total})", step=n, of=total)
|
||||
track = item.track
|
||||
by_source[item.source_id] = n
|
||||
rel = _drive_relative(item.destination, root)
|
||||
anlz_rel = f"{_anlz_dir(rel)}/ANLZ0000.DAT"
|
||||
dat = root / anlz_rel.lstrip("/")
|
||||
extra += self._analysis(drive, item, rel, dat)
|
||||
|
||||
artwork_id = 0
|
||||
art = self._art(item, root, art_n + 1)
|
||||
if art:
|
||||
art_n += 1
|
||||
artwork_id = art_n
|
||||
extra += art
|
||||
rows[pdb.ARTWORK].append(pdb.id_string_row(art_n, f"/PIONEER/Artwork/00001/a{art_n}.jpg"))
|
||||
|
||||
sample_rate, bit_depth = _audio_format(item.destination)
|
||||
try:
|
||||
size = item.destination.stat().st_size
|
||||
except OSError:
|
||||
size = 0
|
||||
year = int(track.release_date[:4]) if (track.release_date or "")[:4].isdigit() else 0
|
||||
rows[pdb.TRACKS].append(pdb.track_row(
|
||||
{
|
||||
"subtype": 0x24, "bitmask": BITMASK, "sample_rate": sample_rate or 0,
|
||||
"file_size": size, "u2": n + 0x600,
|
||||
"artwork_id": artwork_id,
|
||||
"key_id": lookup("key", render_key(track.key_wheel, track.key_mode)),
|
||||
"label_id": lookup("label", track.label),
|
||||
"bitrate": _kbps(track.bitrate) or 0,
|
||||
"tempo": int(round((track.bpm or 0) * 100)),
|
||||
"genre_id": lookup("genre", track.genre),
|
||||
"album_id": lookup("album", track.album),
|
||||
"artist_id": lookup("artist", track.artist),
|
||||
"id": n, "year": year, "sample_depth": bit_depth or 0,
|
||||
"duration": min(int(track.length or 0), 0xFFFF),
|
||||
"u5": ANALYSED, "rating": max(0, min(5, int(track.rating or 0))),
|
||||
"u6": _file_type(item.destination), "u7": 3,
|
||||
},
|
||||
{
|
||||
"kuvo_public": "ON", "autoload_hotcues": "ON",
|
||||
"date_added": today, "release_date": track.release_date or "",
|
||||
"mix_name": track.mix or "", "analyze_path": anlz_rel,
|
||||
"analyze_date": today, "comment": track.comment or "",
|
||||
"title": track.title or item.destination.stem,
|
||||
"filename": item.destination.name, "file_path": rel,
|
||||
},
|
||||
))
|
||||
|
||||
tree, entries = self._playlists(payload, by_source)
|
||||
writer = pdb.PdbWriter(pdb.template("export.pdb"))
|
||||
for table in (pdb.TRACKS, pdb.GENRES, pdb.ARTISTS, pdb.ALBUMS, pdb.LABELS, pdb.KEYS, pdb.ARTWORK):
|
||||
writer.fill(table, rows[table])
|
||||
writer.fill(pdb.PLAYLIST_TREE, tree)
|
||||
writer.fill(pdb.PLAYLIST_ENTRIES, entries)
|
||||
writer.stamp_history_date(date.today())
|
||||
writer.stamp_track_count(len(rows[pdb.TRACKS]))
|
||||
|
||||
library = root / self.library_filename
|
||||
library.write_bytes(writer.render())
|
||||
ext = root / PDB_DIR / "exportExt.pdb"
|
||||
ext.write_bytes(pdb.template("exportExt.pdb"))
|
||||
return WrittenLibrary(library=library, extra=[ext, *extra])
|
||||
|
||||
# ---- shared drive files ---------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _analysis(drive, item: ExportTrack, rel: str, dat: Path) -> list[Path]:
|
||||
"""This track's analysis files — reused when the OneLibrary target has
|
||||
just written them in this same export, else written the same way."""
|
||||
existing = [dat.with_suffix(s) for s in (".DAT", ".EXT", ".2EX") if dat.with_suffix(s).exists()]
|
||||
if dat.exists() and dat.with_suffix(".EXT").exists():
|
||||
return existing
|
||||
return drive._write_anlz(item, rel, dat)
|
||||
|
||||
@staticmethod
|
||||
def _art(item: ExportTrack, root: Path, n: int) -> list[Path]:
|
||||
"""`a<n>.jpg` / `a<n>_m.jpg` — the pair export.pdb's artwork table names,
|
||||
numbered in track order exactly as the OneLibrary target numbers them."""
|
||||
if not item.art:
|
||||
return []
|
||||
folder = root / "PIONEER" / "Artwork" / "00001"
|
||||
small, medium = folder / f"a{n}.jpg", folder / f"a{n}_m.jpg"
|
||||
if small.exists() and medium.exists():
|
||||
return [small, medium]
|
||||
jpegs = artwork.pioneer_jpegs(item.art[0])
|
||||
if jpegs is None:
|
||||
return []
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
small.write_bytes(jpegs[0])
|
||||
medium.write_bytes(jpegs[1])
|
||||
return [small, medium]
|
||||
|
||||
# ---- playlists ------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _playlists(payload: ExportPayload, by_source: dict) -> tuple[list[bytes], list[bytes]]:
|
||||
"""The tree under one folder named after the export, as the other
|
||||
targets build it. `sort_order` is a node's position among its siblings."""
|
||||
tree: list[bytes] = []
|
||||
entries: list[bytes] = []
|
||||
next_id = [0]
|
||||
siblings: dict[int, int] = {}
|
||||
|
||||
def add(name: str, parent: int, *, folder: bool) -> int:
|
||||
next_id[0] += 1
|
||||
order = siblings.get(parent, 0)
|
||||
siblings[parent] = order + 1
|
||||
tree.append(pdb.playlist_tree_row(next_id[0], parent, order, name, folder=folder))
|
||||
return next_id[0]
|
||||
|
||||
def fill(playlist_id: int, source_ids: list[str]) -> None:
|
||||
index = 0
|
||||
for source_id in source_ids:
|
||||
track_id = by_source.get(source_id)
|
||||
if track_id is not None:
|
||||
index += 1
|
||||
entries.append(pdb.playlist_entry_row(index, track_id, playlist_id))
|
||||
|
||||
root = add(payload.name, 0, folder=True)
|
||||
folders: dict[tuple[str, ...], int] = {(): root}
|
||||
for playlist in payload.playlists:
|
||||
parent = root
|
||||
for depth in range(1, len(playlist.folders) + 1):
|
||||
branch = tuple(playlist.folders[:depth])
|
||||
if branch not in folders:
|
||||
folders[branch] = add(branch[-1], folders[branch[:-1]], folder=True)
|
||||
parent = folders[branch]
|
||||
fill(add(playlist.name, parent, folder=False), playlist.track_ids)
|
||||
claimed = {t for p in payload.playlists for t in p.track_ids}
|
||||
loose = [t.source_id for t in payload.tracks if t.source_id not in claimed]
|
||||
if loose:
|
||||
fill(add(OTHER_PLAYLIST, root, folder=False), loose)
|
||||
return tree, entries
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Locate Rekordbox libraries in their default install locations.
|
||||
|
||||
Rekordbox keeps one library per install, at a fixed per-OS path:
|
||||
|
||||
macOS ~/Library/Pioneer/rekordbox/master.db
|
||||
Windows %APPDATA%/Pioneer/rekordbox/master.db
|
||||
|
||||
``pyrekordbox`` already resolves this (including the v6/v7 split and any
|
||||
non-default location recorded in Rekordbox's own settings), so that is the
|
||||
primary source and the hard-coded paths are the fallback.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
_RELATIVE = Path("Pioneer") / "rekordbox" / "master.db"
|
||||
|
||||
|
||||
def _configured_paths() -> list[Path]:
|
||||
"""Library paths pyrekordbox finds from Rekordbox's own configuration."""
|
||||
out: list[Path] = []
|
||||
try:
|
||||
from pyrekordbox.config import get_config
|
||||
except Exception: # noqa: BLE001 — never let discovery break startup
|
||||
return out
|
||||
for version in ("rekordbox7", "rekordbox6"):
|
||||
try:
|
||||
conf = get_config(version)
|
||||
except Exception: # noqa: BLE001
|
||||
continue
|
||||
if not conf:
|
||||
continue
|
||||
p = conf.get("db_path")
|
||||
if p:
|
||||
out.append(Path(p))
|
||||
return out
|
||||
|
||||
|
||||
def _default_paths() -> list[Path]:
|
||||
home = Path.home()
|
||||
return [
|
||||
home / "Library" / _RELATIVE, # macOS
|
||||
home / "AppData" / "Roaming" / _RELATIVE, # Windows
|
||||
]
|
||||
|
||||
|
||||
def describe(path: Path) -> dict:
|
||||
"""A candidate record for a master.db path, shaped like the picker wants."""
|
||||
path = Path(path)
|
||||
exists = path.is_file()
|
||||
# The version Rekordbox itself is, not a schema version stamped in the file:
|
||||
# master.db carries no version field, so the folder is the best label there is.
|
||||
return {
|
||||
"path": str(path),
|
||||
"label": "Rekordbox",
|
||||
"version": None,
|
||||
"modified": (path.stat().st_mtime if exists else None),
|
||||
"exists": exists,
|
||||
}
|
||||
|
||||
|
||||
def detect_libraries() -> list[dict]:
|
||||
"""Every Rekordbox master.db found in a default location, newest first."""
|
||||
seen: set[str] = set()
|
||||
found: list[dict] = []
|
||||
for p in _configured_paths() + _default_paths():
|
||||
try:
|
||||
if not p.is_file():
|
||||
continue
|
||||
except OSError:
|
||||
continue
|
||||
key = str(p.resolve())
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
found.append(describe(p))
|
||||
found.sort(key=lambda c: c["modified"] or 0.0, reverse=True)
|
||||
return found
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Opening Rekordbox libraries: recognition, discovery and restore."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
from . import discovery
|
||||
from .adapter import RekordboxAdapter
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
_SQLITE_MAGIC = b"SQLite format 3\x00"
|
||||
|
||||
|
||||
class RekordboxDriver:
|
||||
platform = "rekordbox"
|
||||
display_name = "Rekordbox"
|
||||
suffixes = (".db",)
|
||||
library_label = "master.db"
|
||||
selects = "file"
|
||||
|
||||
def can_open(self, path: Path) -> bool:
|
||||
"""Recognise an encrypted Rekordbox database.
|
||||
|
||||
Extension is not enough — plenty of things are called ``.db`` — and a
|
||||
SQLCipher file has no readable header at all (its first page is
|
||||
encrypted, so it does NOT start with the SQLite magic). So the probe
|
||||
decrypts just far enough to look for a table only Rekordbox has. That is
|
||||
one page read, and it is the only way to answer honestly.
|
||||
"""
|
||||
try:
|
||||
if not path.is_file() or path.suffix.lower() != ".db":
|
||||
return False
|
||||
with path.open("rb") as fh:
|
||||
if fh.read(len(_SQLITE_MAGIC)) == _SQLITE_MAGIC:
|
||||
return False # a plain, unencrypted SQLite file
|
||||
except OSError:
|
||||
return False
|
||||
return self._has_rekordbox_schema(path)
|
||||
|
||||
@staticmethod
|
||||
def _has_rekordbox_schema(path: Path) -> bool:
|
||||
try:
|
||||
import sqlcipher3.dbapi2 as sqlcipher
|
||||
from pyrekordbox.masterdb.database import BLOB
|
||||
from pyrekordbox.utils import deobfuscate
|
||||
except ImportError: # pragma: no cover — dependency missing
|
||||
return False
|
||||
con = None
|
||||
try:
|
||||
con = sqlcipher.connect(str(path))
|
||||
con.execute(f"PRAGMA key='{deobfuscate(BLOB)}'")
|
||||
row = con.execute(
|
||||
"SELECT name FROM sqlite_master WHERE type='table' AND name='djmdContent'"
|
||||
).fetchone()
|
||||
return row is not None
|
||||
except Exception: # noqa: BLE001 — wrong key or not a database
|
||||
return False
|
||||
finally:
|
||||
if con is not None:
|
||||
try:
|
||||
con.close()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
def open(self, path: Path) -> RekordboxAdapter:
|
||||
return RekordboxAdapter(path)
|
||||
|
||||
def detect(self) -> list[dict]:
|
||||
return discovery.detect_libraries()
|
||||
|
||||
def describe(self, path: Path) -> dict:
|
||||
return discovery.describe(path)
|
||||
|
||||
def restore(self, path: Path, data: bytes) -> None:
|
||||
"""Not supported: a Rekordbox library is more than one file.
|
||||
|
||||
`master.db` carries neither the beatgrids (ANLZ files) nor the playlist
|
||||
XML, and putting an old database back would also revert Rekordbox's auth
|
||||
token and sampler state. `capabilities.save.history` is False for the
|
||||
same reason, so nothing should reach this.
|
||||
"""
|
||||
raise NotImplementedError(
|
||||
"Konduktor does not version Rekordbox libraries: a restore would need "
|
||||
"the analysis files and would roll back Rekordbox's own app state."
|
||||
)
|
||||
@@ -0,0 +1,416 @@
|
||||
"""Writing a fresh Rekordbox `master.db` from nothing.
|
||||
|
||||
## The shape, and why it is not a hand-built schema
|
||||
|
||||
The handoff expected this to be the hard target — "a from-scratch SQLCipher
|
||||
master.db, lookup-table FKs, USN bookkeeping". Most of that turned out to be
|
||||
available:
|
||||
|
||||
* the **schema** is the checked-in DDL of a real Rekordbox 7 library,
|
||||
`fixtures/rekordbox/schema.sql`. NOT `Base.metadata.create_all()`, which was
|
||||
the plan until it failed: the ORM models 37 tables where the real thing has
|
||||
47, and marks columns NOT NULL that Rekordbox leaves nullable — a database
|
||||
built from the models refuses `agentRegistry` rows Rekordbox writes daily;
|
||||
* the **key** is the same one reading uses, `deobfuscate(BLOB)`, so an
|
||||
exported database is readable by any Rekordbox that reads the user's own;
|
||||
* `add_content`, `create_playlist`, `create_playlist_folder` and
|
||||
`add_to_playlist` already exist and assign the ids, UUIDs and USNs.
|
||||
|
||||
So this fills a new database through the library's own API rather than inventing
|
||||
row shapes — the same "create, then use the ordinary write path" the Traktor
|
||||
exporter uses, for the same reason: a second definition would drift from the one
|
||||
the read path is tested against.
|
||||
|
||||
## What is genuinely written here
|
||||
|
||||
**Cue rows and their JSON mirror.** Rekordbox keeps cues in `djmdCue` AND in a
|
||||
`contentCue.Cues` mirror that must agree; leaving the mirror stale is this
|
||||
platform's version of Traktor's companion-cue desync. Field conventions are the
|
||||
adapter's, not guessed: positions in frames at **150 fps**, `ContentUUID` is the
|
||||
TRACK's UUID, an uncoloured cue is `Color=-1`, a loop is `Color=255` with
|
||||
`BeatLoopSize = (beats << 16) | 1`, and `Kind` is the **sparse** bank
|
||||
`1,2,3,5,6,7,8,9` that skips 4 — taken from `cue_types.kind_for`, not
|
||||
redefined, because two copies of a mapping that subtle would drift.
|
||||
|
||||
**Analysis files.** The grid lives in a per-track ANLZ `PQTZ` tag, not in the
|
||||
database, so each track gets one built by the shared `anlz_writer` and pointed
|
||||
at by `djmdContent.AnalysisDataPath`. Rekordbox derives that path from the
|
||||
track's UUID — `/PIONEER/USBANLZ/<first 3>/<rest>/ANLZ0000.DAT` — which is
|
||||
reproduced here because the column and the file have to agree. That path is
|
||||
rooted at a **`share/` directory beside `master.db`**, not at the library root.
|
||||
|
||||
## The catch worth knowing
|
||||
|
||||
`djmdContent.FolderPath` is an **absolute host path**, unlike Traktor's
|
||||
volume-relative LOCATION and OneLibrary's drive-relative path. A Rekordbox
|
||||
export is therefore NOT portable to another machine by copying the folder: it
|
||||
describes files where they are right now. Swapping it into a Rekordbox install
|
||||
on the same machine works; carrying it to a gig does not.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import uuid as uuidlib
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
|
||||
from ...core.cue_colors import effective_color
|
||||
from . import new_content, palette
|
||||
from . import timebase
|
||||
from .beatgrid import beats_from_markers
|
||||
from .capabilities import capabilities_for
|
||||
from .cue_types import kind_for
|
||||
from .projection import render_key
|
||||
from .store import rekordbox_probe_suppressed
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
#: A real Rekordbox 7 library's DDL. See the fixture's README for why the ORM's
|
||||
#: `create_all()` is not used.
|
||||
_FIXTURES = Path(__file__).resolve().parents[3] / "fixtures" / "rekordbox"
|
||||
SCHEMA = _FIXTURES / "schema.sql"
|
||||
#: Rekordbox's own scaffolding rows — menu items, colours, categories, sort
|
||||
#: options. Not optional: `add_content` looks up djmdMenuItems('TRACK') and
|
||||
#: raises on an empty table. Carries no user data and no machine identity;
|
||||
#: `djmdDevice`/`djmdProperty` are generated per export instead.
|
||||
SEED = _FIXTURES / "seed.sql"
|
||||
|
||||
#: Rekordbox counts cue positions in frames at 150 fps, not milliseconds.
|
||||
FRAMES_PER_SECOND = 150
|
||||
|
||||
#: `djmdContent.ContentLink` — see `new_content`, where its bits are measured.
|
||||
CONTENT_LINK = new_content.CONTENT_LINK
|
||||
|
||||
#: Rekordbox's playlist side file, beside master.db. It lists every playlist
|
||||
#: node with a `Timestamp` matching the row's `updated_at` (ms); a playlist the
|
||||
#: file does not vouch for is not shown. The skeleton is a real Rekordbox 7
|
||||
#: file's, minus its nodes — pyrekordbox adds ours as it creates them.
|
||||
PLAYLISTS_XML = "masterPlaylists6.xml"
|
||||
PLAYLISTS_XML_SKELETON = (
|
||||
'<?xml version="1.0" encoding="UTF-8"?>\n\n'
|
||||
'<MASTER_PLAYLIST Version="3.0.0" AutomaticSync="0">\n'
|
||||
' <PRODUCT Name="rekordbox" Version="7.2.18" Company="Pioneer DJ"/>\n'
|
||||
' <PLAYLISTS>\n </PLAYLISTS>\n'
|
||||
'</MASTER_PLAYLIST>\n'
|
||||
)
|
||||
OTHER_PLAYLIST = "Other"
|
||||
|
||||
|
||||
class RekordboxExporter:
|
||||
platform = "rekordbox"
|
||||
menu_order = 40
|
||||
#: A COMPUTER library (master.db), which Rekordbox never reads from a stick —
|
||||
#: named so, beside "Rekordbox Export" (the stick's Device Library).
|
||||
display_name = "Rekordbox Library"
|
||||
#: Rekordbox opens a master.db only from its own library folder.
|
||||
computer_only = True
|
||||
library_filename = "master.db"
|
||||
drive_root = False
|
||||
|
||||
def capabilities(self):
|
||||
"""What a Rekordbox library can hold, with no library to read.
|
||||
|
||||
`capabilities_for` normally takes the loaded library's version and cloud
|
||||
state; a brand-new one has no version and is definitionally not synced.
|
||||
"""
|
||||
return capabilities_for(
|
||||
None,
|
||||
editable_fields=[
|
||||
"title", "artist", "album", "genre", "label", "remixer",
|
||||
"release_date", "comment", "rating",
|
||||
],
|
||||
)
|
||||
|
||||
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
|
||||
# `masterdb`'s OWN key blob. `devicelib_plus` has a different one — a
|
||||
# OneLibrary drive uses a universal key shared across vendors, and
|
||||
# master.db does not. Mixing them up produces a database Rekordbox
|
||||
# cannot open, and pyrekordbox rejects the wrong one outright.
|
||||
import sqlcipher3.dbapi2 as sqlcipher
|
||||
from pyrekordbox.masterdb import MasterDatabase, models
|
||||
from pyrekordbox.masterdb.database import BLOB
|
||||
from pyrekordbox.utils import deobfuscate
|
||||
|
||||
root = Path(destination)
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
library = root / self.library_filename
|
||||
if library.exists():
|
||||
library.unlink() # SQLCipher will not re-key an existing file
|
||||
|
||||
key = deobfuscate(BLOB)
|
||||
con = sqlcipher.connect(str(library))
|
||||
try:
|
||||
con.execute(f"PRAGMA key='{key}'")
|
||||
con.executescript(SCHEMA.read_text())
|
||||
con.executescript(SEED.read_text())
|
||||
con.commit()
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
# BEFORE the database is opened: pyrekordbox keeps masterPlaylists6.xml
|
||||
# in step with every playlist it creates — but only if the file exists
|
||||
# at open time. Without it Rekordbox opened the library, generated its
|
||||
# own file listing our playlists with Timestamp 0, and showed NONE of
|
||||
# them (measured by swapping an export into a real Rekordbox 7).
|
||||
playlists_xml = root / PLAYLISTS_XML
|
||||
playlists_xml.write_text(PLAYLISTS_XML_SKELETON, encoding="utf-8")
|
||||
|
||||
db = MasterDatabase(path=str(library), key=key)
|
||||
extra: list[Path] = [playlists_xml]
|
||||
ids: dict[str, str] = {}
|
||||
try:
|
||||
self._seed_registry(db, models)
|
||||
self._seed_device(db, payload)
|
||||
rows = {}
|
||||
total = len(payload.tracks)
|
||||
for n, item in enumerate(payload.tracks, start=1):
|
||||
# Each track is decoded for its waveform: the slow part.
|
||||
payload.checkpoint(f"Analysing {item.track.title or item.destination.name} ({n}/{total})", step=n, of=total)
|
||||
content = self._add_track(db, item)
|
||||
rows[item.source_id] = content
|
||||
ids[item.source_id] = str(content.ID)
|
||||
extra += self._write_anlz(item, content, root, db)
|
||||
extra += self._write_art(item, content, root)
|
||||
self._write_playlists(db, payload, rows)
|
||||
# A brand-new file: a running Rekordbox cannot have it open, so its
|
||||
# process-wide veto protects nothing here.
|
||||
with rekordbox_probe_suppressed():
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
self._replay_cues(library, payload, ids)
|
||||
return WrittenLibrary(library=library, extra=extra)
|
||||
|
||||
@staticmethod
|
||||
def _replay_cues(library: Path, payload: ExportPayload, ids: dict) -> None:
|
||||
"""Write the cues through the ORDINARY cue-row code, not by hand.
|
||||
|
||||
Same reason the Traktor exporter replays commands: `set_cue` already
|
||||
owns every convention a cue row needs — the sparse `Kind` bank, frames
|
||||
at 150 fps, the loop encoding, and `_sync_content_cue`, which rebuilds
|
||||
the `contentCue` JSON mirror the rows must agree with. Writing those
|
||||
again here would be a second definition of all of it, untested, and a
|
||||
stale mirror is this platform's version of a desynced companion cue.
|
||||
"""
|
||||
from .adapter import RekordboxAdapter
|
||||
|
||||
adapter = RekordboxAdapter(library)
|
||||
# The store, not the adapter's commands: the adapter refuses memory cues
|
||||
# (editing them in a user's library is off-limits) and takes no colour.
|
||||
# Building a NEW library is neither an edit nor lossy by choice, so the
|
||||
# exporter writes both — through the same `_write_cue` every edit uses.
|
||||
store = adapter._store
|
||||
try:
|
||||
for item in payload.tracks:
|
||||
track_id = ids.get(item.source_id)
|
||||
if track_id is None or not item.cues:
|
||||
continue
|
||||
for cue in item.cues.cues:
|
||||
if cue.role == "memory" or cue.slot is None:
|
||||
# rekordbox's own "unset" for a memory cue with no colour.
|
||||
code, _rgb = palette.code_for(cue.color)
|
||||
store.add_memory_cue(
|
||||
track_id, start_sec=cue.start, cue_type=cue.type,
|
||||
length_sec=cue.length, name=cue.name, color_code=code or None,
|
||||
)
|
||||
continue
|
||||
# What Konduktor SHOWS — stored colour, else the type's (blue
|
||||
# cue, green loop) — as a palette code, which is what
|
||||
# rekordbox draws from. White (a grid companion) has no swatch:
|
||||
# code 0, i.e. uncoloured.
|
||||
code, _rgb = palette.code_for(effective_color(cue))
|
||||
store.set_cue(
|
||||
track_id, slot=cue.slot, start_sec=cue.start, cue_type=cue.type,
|
||||
length_sec=cue.length, name=cue.name, color_code=code or None,
|
||||
)
|
||||
adapter.save()
|
||||
finally:
|
||||
adapter.close()
|
||||
|
||||
# ---- rows -----------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _seed_registry(db, models) -> None:
|
||||
"""`agentRegistry.localUpdateCount` is where Rekordbox's USNs come from.
|
||||
|
||||
A database with no row there has nothing for the library's own
|
||||
bookkeeping to increment, so it is created before anything else.
|
||||
"""
|
||||
existing = db.query(models.AgentRegistry).filter_by(
|
||||
registry_id="localUpdateCount").first()
|
||||
if existing is not None:
|
||||
return
|
||||
# Inserted with raw SQL, NOT the ORM. `AgentRegistry`'s DateTime columns
|
||||
# bind through a processor that calls `.astimezone()` unconditionally,
|
||||
# so a NULL `date_1` — which is exactly what a real Rekordbox library
|
||||
# has — raises on INSERT. Reading such a row works; writing one does
|
||||
# not. Raw SQL sidesteps the processor and stores what Rekordbox stores.
|
||||
now = datetime.now().isoformat(sep=" ", timespec="milliseconds")
|
||||
db.session.execute(
|
||||
text('INSERT INTO "agentRegistry" (registry_id, int_1, created_at, '
|
||||
"updated_at) VALUES (:k, 1, :now, :now)"),
|
||||
{"k": "localUpdateCount", "now": now},
|
||||
)
|
||||
db.flush()
|
||||
|
||||
@staticmethod
|
||||
def _seed_device(db, payload: ExportPayload) -> None:
|
||||
"""This library's own identity — a fresh device and DB id per export.
|
||||
|
||||
Deliberately NOT copied from the fixture: a real `djmdDevice` row holds
|
||||
the machine's NAME and UUIDs, which have no business in a repo or in
|
||||
somebody else's exported library. Rekordbox stamps content rows with
|
||||
`MasterDBID`, so the value has to exist; it just has to be ours.
|
||||
"""
|
||||
now = datetime.now().isoformat(sep=" ", timespec="milliseconds")
|
||||
device_id = str(uuidlib.uuid4())
|
||||
db_id = str(uuidlib.uuid4().int % 2_147_483_647)
|
||||
db.session.execute(
|
||||
text('INSERT INTO "djmdProperty" (DBID, DBVersion, DeviceID, '
|
||||
"created_at, updated_at) VALUES (:db, '6000', :dev, :now, :now)"),
|
||||
{"db": db_id, "dev": device_id, "now": now},
|
||||
)
|
||||
db.session.execute(
|
||||
text('INSERT INTO "djmdDevice" (ID, MasterDBID, Name, UUID, '
|
||||
"rb_local_usn, created_at, updated_at) "
|
||||
"VALUES (:dev, :db, :name, :uuid, 1, :now, :now)"),
|
||||
{"dev": device_id, "db": db_id, "name": payload.name,
|
||||
"uuid": str(uuidlib.uuid4()), "now": now},
|
||||
)
|
||||
db.flush()
|
||||
|
||||
def _add_track(self, db, item: ExportTrack):
|
||||
"""One `djmdContent` row, through pyrekordbox's own helper."""
|
||||
track = item.track
|
||||
content = db.add_content(
|
||||
str(item.destination),
|
||||
Title=track.title,
|
||||
BPM=int(round((track.bpm or 0) * 100)) or None,
|
||||
Length=track.length,
|
||||
Rating=track.rating or 0,
|
||||
Commnt=track.comment,
|
||||
ReleaseDate=track.release_date,
|
||||
)
|
||||
# Lookups are foreign keys; pyrekordbox's add_* RAISES on an existing
|
||||
# name, so every one is find-or-create — the same rule the in-place
|
||||
# adapter follows.
|
||||
content.ArtistID = self._lookup(db, "artist", track.artist)
|
||||
content.AlbumID = self._lookup(db, "album", track.album)
|
||||
content.GenreID = self._lookup(db, "genre", track.genre)
|
||||
content.LabelID = self._lookup(db, "label", track.label)
|
||||
# NOT `track.key`: that is the SOURCE platform's notation, so a Traktor
|
||||
# export would put "10m" where Rekordbox shows "Cm".
|
||||
content.KeyID = self._lookup(db, "key", render_key(track.key_wheel, track.key_mode))
|
||||
content.ContentLink = CONTENT_LINK
|
||||
db.flush()
|
||||
return content
|
||||
|
||||
@staticmethod
|
||||
def _lookup(db, kind: str, name: str | None):
|
||||
return new_content.lookup(db, kind, name)
|
||||
|
||||
# ---- analysis ---------------------------------------------------------------
|
||||
|
||||
def _write_anlz(self, item: ExportTrack, content, root: Path, db) -> list[Path]:
|
||||
"""The ANLZ file carrying this track's grid, and the column pointing at it.
|
||||
|
||||
Rekordbox derives the path from the track's UUID, and the database column
|
||||
and the file on disk have to agree — so the same derivation is used here
|
||||
rather than a path of our own choosing.
|
||||
"""
|
||||
rel = new_content.anlz_rel(str(content.UUID))
|
||||
content.AnalysisDataPath = rel
|
||||
content.Analysed = 105 # what a rekordbox-analysed track carries
|
||||
content.AnalysisUpdated = 1
|
||||
db.flush()
|
||||
|
||||
off = timebase.offset(item.destination)
|
||||
measured = item.waveform(lead=off)
|
||||
beats = None
|
||||
markers = item.cues.grid_markers if item.cues else []
|
||||
if markers:
|
||||
duration = ((measured.duration if measured else 0.0)
|
||||
or float(item.track.length or 0) or (markers[-1].start + 60.0))
|
||||
nums, bpms, times = beats_from_markers(markers, duration)
|
||||
if nums:
|
||||
# Onto rekordbox's clock (~25 ms behind on MP3/AAC — `timebase`).
|
||||
# The cues need no such line: they are replayed through
|
||||
# `set_cue`, which applies the same offset itself.
|
||||
beats = [(n, bpm, timebase.to_pioneer(t, off))
|
||||
for n, bpm, t in zip(nums, bpms, times)]
|
||||
# AnalysisDataPath is rooted at a `share` directory BESIDE master.db,
|
||||
# not at the library root — the read path joins it that way, and writing
|
||||
# it anywhere else produces a track whose grid silently reads as empty.
|
||||
dat = root / "share" / rel.lstrip("/")
|
||||
written = []
|
||||
for suffix, data in new_content.anlz_files(item.destination, measured, beats).items():
|
||||
target = dat.with_suffix(suffix)
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes(data)
|
||||
written.append(target)
|
||||
return written
|
||||
|
||||
# ---- artwork ------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _write_art(item: ExportTrack, content, root: Path) -> list[Path]:
|
||||
"""The cover, as a rekordbox-managed track carries it.
|
||||
|
||||
Three JPEGs under `share/PIONEER/Artwork/<uuid[:3]>/<uuid[3:]>/` — the
|
||||
same UUID split as the analysis folder — named `artwork.jpg` (the cover,
|
||||
fit to 800 px), `artwork_m.jpg` (240) and `artwork_s.jpg` (80), the last
|
||||
two letterboxed square. `djmdContent.ImagePath` names `artwork.jpg`,
|
||||
rooted at `share/` like `AnalysisDataPath`. All measured on a real
|
||||
Rekordbox 7 library.
|
||||
"""
|
||||
files = new_content.artwork_files(item.art[0] if item.art else None)
|
||||
if files is None:
|
||||
return []
|
||||
rel = new_content.artwork_rel(str(content.UUID))
|
||||
folder = root / "share" / rel.lstrip("/")
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
written = []
|
||||
for name, data in files.items():
|
||||
(folder / name).write_bytes(data)
|
||||
written.append(folder / name)
|
||||
content.ImagePath = f"{rel}/artwork.jpg"
|
||||
return written
|
||||
|
||||
# ---- playlists ---------------------------------------------------------------
|
||||
|
||||
def _write_playlists(self, db, payload: ExportPayload, rows: dict) -> None:
|
||||
"""The tree, under one folder named after the export."""
|
||||
root = db.create_playlist_folder(payload.name)
|
||||
db.flush()
|
||||
folders: dict[tuple[str, ...], object] = {(): root}
|
||||
|
||||
for playlist in payload.playlists:
|
||||
parent = root
|
||||
for depth in range(1, len(playlist.folders) + 1):
|
||||
branch = tuple(playlist.folders[:depth])
|
||||
if branch not in folders:
|
||||
folders[branch] = db.create_playlist_folder(
|
||||
branch[-1], parent=folders[branch[:-1]])
|
||||
db.flush()
|
||||
parent = folders[branch]
|
||||
self._fill(db, db.create_playlist(playlist.name, parent=parent),
|
||||
playlist.track_ids, rows)
|
||||
|
||||
claimed = {t for p in payload.playlists for t in p.track_ids}
|
||||
loose = [t.source_id for t in payload.tracks if t.source_id not in claimed]
|
||||
if loose:
|
||||
self._fill(db, db.create_playlist(OTHER_PLAYLIST, parent=root), loose, rows)
|
||||
|
||||
@staticmethod
|
||||
def _fill(db, playlist, track_ids: list[str], rows: dict) -> None:
|
||||
db.flush()
|
||||
for source_id in track_ids:
|
||||
content = rows.get(source_id)
|
||||
if content is not None:
|
||||
db.add_to_playlist(playlist, content)
|
||||
db.flush()
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
"""A NEW track's rows and files in a `master.db` library.
|
||||
|
||||
Shared by the two places a track is created rather than edited: the Rekordbox
|
||||
Library exporter (a `master.db` from nothing) and `RekordboxStore.add_tracks`
|
||||
(a track added to the user's own library). One definition, because a track
|
||||
row, its lookups and its analysis files are the same thing in both, and two
|
||||
copies would drift.
|
||||
|
||||
What a track Rekordbox itself adds looks like was MEASURED (two files dragged
|
||||
into Rekordbox 7.2's collection, 2026-10-01, every row and file diffed): a
|
||||
`djmdContent` row, three ANLZ files plus a `.3EX`, the embedded cover as three
|
||||
JPEGs, one `contentFile` row per file (its `Hash` the file's MD5), and its own
|
||||
analysis results — key, mixer gain, phrases — which nothing here can produce.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid as uuidlib
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from . import anlz_writer as W
|
||||
from . import artwork
|
||||
|
||||
#: `djmdContent.ContentLink` — NOT optional, and a bit field. Measured by giving
|
||||
#: five tracks of a Konduktor-written library different values and loading it
|
||||
#: in Rekordbox 7: with it NULL the song-list preview is plain blue with a "?"
|
||||
#: beside CUE; any value colours the preview; the 0x200000 bit (0x2C060E here,
|
||||
#: 0x0C060E without it) clears the "?"; and 0x3D060E — what the real library's
|
||||
#: MP3/M4A tracks carry, and what Rekordbox writes for a track it analyses
|
||||
#: itself — adds two more bits that draw an extra badge, most likely claiming
|
||||
#: phrase/vocal analysis Konduktor does not write. So the value that claims
|
||||
#: only what is written: 0x2C060E.
|
||||
CONTENT_LINK = 2885134
|
||||
|
||||
|
||||
def anlz_rel(track_uuid: str) -> str:
|
||||
"""`djmdContent.AnalysisDataPath` for a track. Rekordbox derives it from
|
||||
the track's UUID, and the column and the file have to agree."""
|
||||
return f"/PIONEER/USBANLZ/{track_uuid[:3]}/{track_uuid[3:]}/ANLZ0000.DAT"
|
||||
|
||||
|
||||
def artwork_rel(track_uuid: str) -> str:
|
||||
"""The track's artwork FOLDER — the same UUID split as its analysis."""
|
||||
return f"/PIONEER/Artwork/{track_uuid[:3]}/{track_uuid[3:]}"
|
||||
|
||||
|
||||
def anlz_files(audio: Path, measured, beats: list | None) -> dict[str, bytes]:
|
||||
"""The analysis files for a track, by suffix: `.DAT`, `.EXT`, `.2EX`.
|
||||
|
||||
The same files as a rekordbox-analysed track. The `.DAT` needs PVBR and the
|
||||
preview waveforms before rekordbox shows a grid at all (measured on a
|
||||
OneLibrary stick; the same Pioneer file here); the `.EXT`/`.2EX` carry the
|
||||
drawn waveforms. Cue lists are present but EMPTY — master.db keeps cues in
|
||||
djmdCue. `measured` is `waveform.analyse`'s result (None: flat previews).
|
||||
`beats` is `(beat-in-bar, bpm, seconds)` ON REKORDBOX'S CLOCK; None writes
|
||||
no `PQTZ`, and `[]` an empty one for `write_pqtz` to fill later.
|
||||
"""
|
||||
path = str(audio)
|
||||
tags = [W.path_tag(path), W.vbr_tag(W.mp3_samples(audio))]
|
||||
if beats is not None:
|
||||
tags.append(W.beatgrid_tag(beats))
|
||||
if measured:
|
||||
tags += W.preview_tags(measured.columns.rms, measured.columns.brightness)
|
||||
ext_waves, two_ex = W.waveform_tags(measured.frames.bands)
|
||||
else:
|
||||
tags += W.flat_preview_tags()
|
||||
ext_waves, two_ex = [], []
|
||||
tags += W.cue_tags([], extended=False)
|
||||
out = {
|
||||
".DAT": W.anlz_bytes(tags),
|
||||
".EXT": W.anlz_bytes([W.path_tag(path), *ext_waves[:1],
|
||||
*W.cue_tags([], extended=True), *ext_waves[1:]]),
|
||||
}
|
||||
if two_ex:
|
||||
out[".2EX"] = W.anlz_bytes([W.path_tag(path), *two_ex])
|
||||
return out
|
||||
|
||||
|
||||
def artwork_files(art: bytes | None) -> dict[str, bytes] | None:
|
||||
"""The cover as a rekordbox-managed track carries it, by file name.
|
||||
|
||||
`artwork.jpg` (the cover, fit to 800 px), `artwork_m.jpg` (240) and
|
||||
`artwork_s.jpg` (80), the last two letterboxed square; `djmdContent.
|
||||
ImagePath` names `artwork.jpg`. All measured on a real Rekordbox 7 library.
|
||||
None when there is no art or it cannot be read.
|
||||
"""
|
||||
if not art:
|
||||
return None
|
||||
jpegs = artwork.library_jpegs(art)
|
||||
if jpegs is None:
|
||||
return None
|
||||
return dict(zip(("artwork.jpg", "artwork_m.jpg", "artwork_s.jpg"), jpegs))
|
||||
|
||||
|
||||
def lookup(db, kind: str, name: str | None):
|
||||
"""Find-or-create a lookup row, returning its id.
|
||||
|
||||
Lookups are foreign keys; pyrekordbox's `add_*` RAISES on an existing name,
|
||||
so every one is find-or-create — the same rule the in-place adapter follows.
|
||||
`djmdKey` is the odd one out twice over: its name column is `ScaleName`,
|
||||
not `Name`, and pyrekordbox has no `add_key`. So keys are inserted
|
||||
directly, with a `Seq` that keeps them in wheel order in Rekordbox's UI.
|
||||
"""
|
||||
if not name:
|
||||
return None
|
||||
if kind == "key":
|
||||
found = db.get_key(ScaleName=name).first()
|
||||
if found is not None:
|
||||
return found.ID
|
||||
return insert_key(db, name)
|
||||
found = {"artist": db.get_artist, "album": db.get_album,
|
||||
"genre": db.get_genre, "label": db.get_label}[kind](Name=name).first()
|
||||
if found is not None:
|
||||
return found.ID
|
||||
created = {"artist": db.add_artist, "album": db.add_album,
|
||||
"genre": db.add_genre, "label": db.add_label}[kind](name)
|
||||
db.flush()
|
||||
return created.ID
|
||||
|
||||
|
||||
def insert_key(db, name: str) -> str:
|
||||
"""A `djmdKey` row. Raw SQL: the ORM's DateTime binder raises on the NULLs
|
||||
a real row carries."""
|
||||
from pyrekordbox.masterdb import models
|
||||
|
||||
now = datetime.now().isoformat(sep=" ", timespec="milliseconds")
|
||||
seq = (db.query(models.DjmdKey).count() or 0) + 1
|
||||
key_id = str(uuidlib.uuid4().int % 2_147_483_647)
|
||||
db.session.execute(
|
||||
text('INSERT INTO "djmdKey" (ID, ScaleName, Seq, UUID, created_at, '
|
||||
"updated_at) VALUES (:id, :name, :seq, :uuid, :now, :now)"),
|
||||
{"id": key_id, "name": name, "seq": seq,
|
||||
"uuid": str(uuidlib.uuid4()), "now": now},
|
||||
)
|
||||
db.flush()
|
||||
return key_id
|
||||
@@ -0,0 +1,118 @@
|
||||
"""rekordbox's hot-cue colour palette: a generic `#RRGGBB` -> (palette code, RGB).
|
||||
|
||||
**rekordbox draws a hot cue from its palette CODE, not from its RGB bytes.** An
|
||||
export that wrote only RGB (code 0) had every cue drawn in rekordbox's defaults
|
||||
— green cues, orange loops. The code is `PCP2`'s colour byte (offset 44, before
|
||||
the RGB triple) in the ANLZ `.EXT`, and `djmdCue.ColorTableIndex` in `master.db`.
|
||||
|
||||
The table was MEASURED, not recalled: 16 hot cues coloured through rekordbox 7's
|
||||
own palette, one colour per pad, exported to a stick, and read back. Rekordbox
|
||||
writes the palette's exact RGB beside each code.
|
||||
|
||||
* 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
|
||||
all Traktor's white grid-marker companion — gets code 0 with its RGB. rekordbox
|
||||
produces that state itself (the reference fixture's cues are code 0 + RGB);
|
||||
what rekordbox DRAWS for it is not yet verified.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import colorsys
|
||||
|
||||
#: code -> RGB, exactly as rekordbox 7 writes them.
|
||||
PALETTE: dict[int, tuple[int, int, int]] = {
|
||||
0x31: (0xFF, 0x00, 0xA1), # magenta
|
||||
0x38: (0xB3, 0x00, 0xFF), # purple
|
||||
0x3C: (0x4D, 0x00, 0xFF), # violet
|
||||
0x3E: (0x1A, 0x00, 0xFF), # blue-violet
|
||||
0x01: (0x00, 0x00, 0xFF), # blue
|
||||
0x05: (0x00, 0x70, 0xFF), # light blue
|
||||
0x09: (0x00, 0xE0, 0xFF), # cyan
|
||||
0x0E: (0x00, 0xFF, 0xA3), # teal
|
||||
0x16: (0x1A, 0xFF, 0x00), # green
|
||||
0x1A: (0x80, 0xFF, 0x00), # lime
|
||||
0x1E: (0xE6, 0xFF, 0x00), # yellow-lime
|
||||
0x20: (0xFF, 0xE8, 0x00), # yellow
|
||||
0x26: (0xFF, 0x5E, 0x00), # orange
|
||||
0x2A: (0xFF, 0x00, 0x00), # red
|
||||
0x2B: (0xFF, 0x00, 0x17), # red (observed, not a swatch)
|
||||
0x2D: (0xFF, 0x00, 0x45), # pink-red
|
||||
}
|
||||
|
||||
#: Konduktor's TYPE colours (`core.cue_colors`) -> the swatch a DJ would call by
|
||||
#: the same name. Nearest-hue alone sends the mint loop green to TEAL, and a
|
||||
#: Traktor user reads a loop as green; so the type colours are pinned by intent.
|
||||
_BY_INTENT: dict[str, int] = {
|
||||
"#4D94FF": 0x05, # cue -> light blue
|
||||
"#3DDC84": 0x16, # loop -> green
|
||||
"#FF9A3D": 0x26, # fade -> orange
|
||||
"#FFD23D": 0x20, # load -> yellow
|
||||
}
|
||||
|
||||
#: Below this saturation a colour is white/grey, which the palette cannot show.
|
||||
_GREY = 0.2
|
||||
|
||||
|
||||
def _parse(color: str) -> tuple[int, int, int] | None:
|
||||
c = (color or "").strip().lstrip("#")
|
||||
if len(c) != 6:
|
||||
return None
|
||||
try:
|
||||
return int(c[0:2], 16), int(c[2:4], 16), int(c[4:6], 16)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def code_for(color: str | None) -> tuple[int, tuple[int, int, int]]:
|
||||
"""(palette code, RGB to store) for a generic `#RRGGBB`; (0, black) for none.
|
||||
|
||||
An exact palette RGB keeps its code; a type colour maps by intent; a
|
||||
white/grey keeps its RGB with code 0; anything else takes the swatch of the
|
||||
nearest hue, and stores THAT swatch's RGB so code and colour agree.
|
||||
"""
|
||||
rgb = _parse(color) if color else None
|
||||
if rgb is None:
|
||||
return 0, (0, 0, 0)
|
||||
for code, value in PALETTE.items():
|
||||
if value == rgb:
|
||||
return code, value
|
||||
intent = _BY_INTENT.get(f"#{rgb[0]:02X}{rgb[1]:02X}{rgb[2]:02X}")
|
||||
if intent is not None:
|
||||
return intent, PALETTE[intent]
|
||||
h, _l, s = colorsys.rgb_to_hls(*(v / 255 for v in rgb))
|
||||
if s < _GREY or max(rgb) - min(rgb) < 40:
|
||||
return 0, rgb
|
||||
def hue_gap(code: int) -> float:
|
||||
ph = colorsys.rgb_to_hls(*(v / 255 for v in PALETTE[code]))[0]
|
||||
d = abs(ph - h)
|
||||
return min(d, 1 - d)
|
||||
best = min((c for c in PALETTE if c != 0x2B), key=hue_gap)
|
||||
return best, PALETTE[best]
|
||||
|
||||
|
||||
#: The swatches a user can pick, in rekordbox's own order — what
|
||||
#: `capabilities.cues.palette` offers. 15 of rekordbox's 16: the unmeasured
|
||||
#: teal-green is left out rather than offered with a guessed RGB, and 0x2B is
|
||||
#: not a swatch at all (see the module note).
|
||||
SWATCHES: list[int] = [code for code in PALETTE if code != 0x2B]
|
||||
|
||||
|
||||
def hex_for(code: int | None) -> str | None:
|
||||
"""`#RRGGBB` for a stored palette code; None for uncoloured or unknown.
|
||||
|
||||
An unknown code (the unmeasured teal-green) projects as no colour rather
|
||||
than a guessed one; it is still kept on the row, since editing a cue's
|
||||
position, type or name never rewrites its colour.
|
||||
"""
|
||||
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)
|
||||
@@ -0,0 +1,432 @@
|
||||
"""The legacy rekordbox device library: `export.pdb` (DeviceSQL), read and written.
|
||||
|
||||
What Rekordbox lists as a stick's **Device Library** and what pre-OneLibrary
|
||||
players (CDJ-2000NXS2, many XDJs) read. Rekordbox writes it beside the
|
||||
OneLibrary `exportLibrary.db`; both point at the same audio, analysis files and
|
||||
artwork.
|
||||
|
||||
## The format
|
||||
|
||||
There is no public specification. The layout used here is the one Deep
|
||||
Symmetry's crate-digger documents, CONFIRMED byte for byte against a real
|
||||
rekordbox 7 device export of eight tracks (every row of every table decodes, and
|
||||
the page arithmetic below reproduces rekordbox's header fields exactly):
|
||||
|
||||
* the file is 4096-byte pages; page 0 is a header listing 20 tables, each a
|
||||
chain of pages `first -> ... -> last -> empty_candidate` (the candidate is a
|
||||
reserved page, possibly beyond the end of the file);
|
||||
* every table starts with a HEADER page that holds no rows (flags 0x64) but
|
||||
DOES hold an index: the table's first data page, and for tracks, the
|
||||
playlist tree and history an entry per data page (`page << 3 | flag`, 3 =
|
||||
has room). A first Konduktor export left these pointing nowhere and
|
||||
rekordbox 7 called the device library corrupted; rows live in DATA pages
|
||||
(flags 0x34 for tracks and the playlist tree, else 0x24);
|
||||
* a data page is a 0x28-byte header, a heap of rows (each 4-byte aligned) from
|
||||
the top, and a row index growing from the bottom in groups of 16: per group
|
||||
16 u16 heap offsets, a u16 "present" bitmask and a u16 bitmask of the last
|
||||
row written;
|
||||
* strings are DeviceSQL strings: short ASCII `((len+1)<<1)|1` + bytes, long
|
||||
ASCII `0x40` + u16 length + pad, or UTF-16LE `0x90` + u16 length + pad.
|
||||
|
||||
## Writing
|
||||
|
||||
**From a template, not from nothing** (`fixtures/rekordbox/device/`): the empty
|
||||
library rekordbox itself writes for a new stick. It carries the tables that are
|
||||
the same on every stick and cannot be derived (colours, browse columns, menus,
|
||||
the history header), and reserves a blank page after each data table's header
|
||||
page. Filling a table follows rekordbox's own allocation, read off a real
|
||||
export: the first data page is the table's reserved candidate, further pages and
|
||||
the new candidate come from the file header's next-unused counter, and any
|
||||
reserved page left inside the file stays blank.
|
||||
|
||||
Data pages are written the way a rekordbox EXPORT writes them (rows appended
|
||||
one by one): `u5` = 1, `num_rows_large` = rows - 1, and each index group's
|
||||
"last written" mask names its final row.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import struct
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
PAGE = 4096
|
||||
_HEADER = 0x28
|
||||
_GROUP = 0x24 # one row-index group: 16 offsets + present + last-written
|
||||
|
||||
TRACKS, GENRES, ARTISTS, ALBUMS, LABELS, KEYS, COLORS = 0, 1, 2, 3, 4, 5, 6
|
||||
PLAYLIST_TREE, PLAYLIST_ENTRIES, ARTWORK, HISTORY = 7, 8, 13, 19
|
||||
|
||||
#: Data-page flags per table, as rekordbox writes them.
|
||||
_PAGE_FLAGS = {TRACKS: 0x34, PLAYLIST_TREE: 0x34}
|
||||
_DEFAULT_FLAGS = 0x24
|
||||
_HEADER_PAGE = 0x40 # bit set on header / non-data pages
|
||||
|
||||
TEMPLATE_DIR = Path(__file__).resolve().parents[3] / "fixtures" / "rekordbox" / "device"
|
||||
|
||||
|
||||
# ---- strings -------------------------------------------------------------------
|
||||
|
||||
|
||||
def dsql(text: str | None) -> bytes:
|
||||
"""A DeviceSQL string."""
|
||||
text = text or ""
|
||||
try:
|
||||
raw = text.encode("ascii")
|
||||
except UnicodeEncodeError:
|
||||
wide = text.encode("utf-16-le")
|
||||
return struct.pack("<BHB", 0x90, len(wide) + 4, 0) + wide
|
||||
if len(raw) <= 126:
|
||||
return bytes([((len(raw) + 1) << 1) | 1]) + raw
|
||||
return struct.pack("<BHB", 0x40, len(raw) + 4, 0) + raw
|
||||
|
||||
|
||||
def read_dsql(buf: bytes, off: int) -> str:
|
||||
head = buf[off]
|
||||
if head & 1:
|
||||
n = (head >> 1) - 1
|
||||
return buf[off + 1:off + 1 + n].decode("ascii", "replace")
|
||||
n = struct.unpack_from("<H", buf, off + 1)[0]
|
||||
body = buf[off + 4:off + n]
|
||||
return body.decode("utf-16-le" if head == 0x90 else "ascii", "replace")
|
||||
|
||||
|
||||
def _pad4(row: bytes) -> bytes:
|
||||
return row + bytes(-len(row) % 4)
|
||||
|
||||
|
||||
# ---- rows ----------------------------------------------------------------------
|
||||
|
||||
#: The track row's fixed part, in order: 94 bytes.
|
||||
_TRACK_FIELDS = (
|
||||
("subtype", "H"), ("index_shift", "H"), ("bitmask", "I"), ("sample_rate", "I"),
|
||||
("composer_id", "I"), ("file_size", "I"), ("u2", "I"), ("u3", "H"), ("u4", "H"),
|
||||
("artwork_id", "I"), ("key_id", "I"), ("original_artist_id", "I"), ("label_id", "I"),
|
||||
("remixer_id", "I"), ("bitrate", "I"), ("track_number", "I"), ("tempo", "I"),
|
||||
("genre_id", "I"), ("album_id", "I"), ("artist_id", "I"), ("id", "I"),
|
||||
("disc_number", "H"), ("play_count", "H"), ("year", "H"), ("sample_depth", "H"),
|
||||
("duration", "H"), ("u5", "H"), ("color_id", "B"), ("rating", "B"), ("u6", "H"), ("u7", "H"),
|
||||
)
|
||||
_TRACK_FMT = "<" + "".join(f for _, f in _TRACK_FIELDS)
|
||||
_TRACK_FIXED = struct.calcsize(_TRACK_FMT) # 94
|
||||
#: The 21 string slots, in the order their offsets follow the fixed part.
|
||||
TRACK_STRINGS = (
|
||||
"isrc", "texter", "unknown_string_2", "unknown_string_3", "unknown_string_4",
|
||||
"message", "kuvo_public", "autoload_hotcues", "unknown_string_5", "unknown_string_6",
|
||||
"date_added", "release_date", "mix_name", "unknown_string_7", "analyze_path",
|
||||
"analyze_date", "comment", "title", "unknown_string_8", "filename", "file_path",
|
||||
)
|
||||
_INDEX_SHIFT_AT = 2 # tracks, artists and albums carry their slot << 5 here
|
||||
#: Tables whose header page indexes every data page (the rest only point at the
|
||||
#: first). History (19) is already indexed in the template.
|
||||
_INDEXED = (TRACKS, PLAYLIST_TREE)
|
||||
_NONE = 0x1FFF
|
||||
|
||||
|
||||
def track_row(fields: dict, strings: dict) -> bytes:
|
||||
"""A tracks-table row. `fields` fills the fixed part (missing = 0);
|
||||
`strings` the string slots (missing = empty)."""
|
||||
values = [fields.get(name, 0) for name, _ in _TRACK_FIELDS]
|
||||
fixed = struct.pack(_TRACK_FMT, *values)
|
||||
offsets, heap = [], b""
|
||||
base = _TRACK_FIXED + 2 * len(TRACK_STRINGS)
|
||||
for name in TRACK_STRINGS:
|
||||
offsets.append(base + len(heap))
|
||||
heap += dsql(strings.get(name))
|
||||
return _pad4(fixed + struct.pack(f"<{len(offsets)}H", *offsets) + heap)
|
||||
|
||||
|
||||
def id_string_row(row_id: int, text: str) -> bytes:
|
||||
"""Genres, labels and artwork: u32 id + string."""
|
||||
return _pad4(struct.pack("<I", row_id) + dsql(text))
|
||||
|
||||
|
||||
def key_row(row_id: int, name: str) -> bytes:
|
||||
"""Keys store their id twice."""
|
||||
return _pad4(struct.pack("<II", row_id, row_id) + dsql(name))
|
||||
|
||||
|
||||
def artist_row(row_id: int, name: str) -> bytes:
|
||||
"""Subtype 0x60: the name starts at a fixed offset of 10."""
|
||||
return _pad4(struct.pack("<HHIBB", 0x60, 0, row_id, 0x03, 10) + dsql(name))
|
||||
|
||||
|
||||
def album_row(row_id: int, name: str, artist_id: int = 0) -> bytes:
|
||||
"""Subtype 0x80: the name starts at 22. rekordbox's own export leaves the
|
||||
album's artist 0 even when the track has one, so the default follows it."""
|
||||
return _pad4(struct.pack("<HHIIIIBB", 0x80, 0, 0, artist_id, row_id, 0, 0x03, 22) + dsql(name))
|
||||
|
||||
|
||||
def playlist_tree_row(row_id: int, parent_id: int, sort_order: int, name: str, *, folder: bool) -> bytes:
|
||||
return _pad4(struct.pack("<IIIII", parent_id, 0, sort_order, row_id, 1 if folder else 0) + dsql(name))
|
||||
|
||||
|
||||
def playlist_entry_row(entry_index: int, track_id: int, playlist_id: int) -> bytes:
|
||||
return struct.pack("<III", entry_index, track_id, playlist_id)
|
||||
|
||||
|
||||
# ---- pages ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def _index_space(n: int) -> int:
|
||||
"""Bytes the row index occupies at the bottom of a page holding `n` rows."""
|
||||
return ((n + 15) // 16) * _GROUP
|
||||
|
||||
|
||||
def _chunk(rows: list[bytes]) -> list[list[bytes]]:
|
||||
"""Greedy: as many rows per page as fit beside their index."""
|
||||
pages, cur, used = [], [], 0
|
||||
for row in rows:
|
||||
if cur and _HEADER + used + len(row) + _index_space(len(cur) + 1) > PAGE:
|
||||
pages.append(cur)
|
||||
cur, used = [], 0
|
||||
if _HEADER + len(row) + _index_space(1) > PAGE:
|
||||
raise ValueError(f"a {len(row)}-byte row cannot fit in a page")
|
||||
cur.append(row)
|
||||
used += len(row)
|
||||
if cur:
|
||||
pages.append(cur)
|
||||
return pages
|
||||
|
||||
|
||||
def _data_page(index: int, table: int, next_page: int, rows: list[bytes], sequence: int,
|
||||
*, shift_at: int | None, fill: tuple[int, int] | None = None) -> bytes:
|
||||
page = bytearray(PAGE)
|
||||
heap = bytearray()
|
||||
offsets = []
|
||||
for slot, row in enumerate(rows):
|
||||
row = bytearray(row)
|
||||
if shift_at is not None:
|
||||
struct.pack_into("<H", row, shift_at, slot << 5)
|
||||
offsets.append(len(heap))
|
||||
heap += row
|
||||
n = len(rows)
|
||||
groups = (n + 15) // 16
|
||||
page[_HEADER:_HEADER + len(heap)] = heap
|
||||
for g in range(groups):
|
||||
base = PAGE - g * _GROUP
|
||||
k = min(16, n - 16 * g)
|
||||
struct.pack_into("<H", page, base - 4, (1 << k) - 1) # present
|
||||
struct.pack_into("<H", page, base - 2, 1 << (k - 1)) # last written
|
||||
for r in range(k):
|
||||
struct.pack_into("<H", page, base - 6 - 2 * r, offsets[16 * g + r])
|
||||
used = len(heap)
|
||||
free = PAGE - _HEADER - used - (2 * n + 4 * groups)
|
||||
struct.pack_into("<6I", page, 0, 0, index, table, next_page, sequence, 0)
|
||||
page[0x18] = n & 0xFF
|
||||
page[0x19] = ((n >> 8) & 0x1F) | ((n & 0x07) << 5)
|
||||
page[0x1A] = (n >> 3) & 0xFF
|
||||
page[0x1B] = _PAGE_FLAGS.get(table, _DEFAULT_FLAGS)
|
||||
u5, nrl = fill if fill is not None else (1, n - 1)
|
||||
struct.pack_into("<6H", page, 0x1C, free, used, u5, nrl, 0, 0)
|
||||
return bytes(page)
|
||||
|
||||
|
||||
# ---- the writer ----------------------------------------------------------------
|
||||
|
||||
|
||||
class PdbWriter:
|
||||
"""Fills an empty rekordbox device library (the template) with rows."""
|
||||
|
||||
def __init__(self, template: bytes):
|
||||
self.buf = bytearray(template)
|
||||
self.pages: dict[int, bytes] = {}
|
||||
n_tables = struct.unpack_from("<I", self.buf, 8)[0]
|
||||
self.next_unused = struct.unpack_from("<I", self.buf, 12)[0]
|
||||
self.sequence = struct.unpack_from("<I", self.buf, 20)[0]
|
||||
self.tables = {}
|
||||
self.pages_with_room = 0
|
||||
for i in range(n_tables):
|
||||
t, empty, first, last = struct.unpack_from("<4I", self.buf, 28 + 16 * i)
|
||||
self.tables[t] = [i, empty, first, last]
|
||||
|
||||
def _alloc(self) -> int:
|
||||
page = self.next_unused
|
||||
self.next_unused += 1
|
||||
return page
|
||||
|
||||
def fill(self, table: int, rows: list[bytes]) -> None:
|
||||
"""Write `rows` into `table`, which must still be empty (header page only)."""
|
||||
if not rows:
|
||||
return
|
||||
slot, empty, first, last = self.tables[table]
|
||||
if first != last:
|
||||
raise ValueError(f"table {table} already has data pages")
|
||||
chunks = _chunk(rows)
|
||||
indices = [empty] + [self._alloc() for _ in chunks[1:]]
|
||||
candidate = self._alloc()
|
||||
shift_at = _INDEX_SHIFT_AT if table in (TRACKS, ARTISTS, ALBUMS) else None
|
||||
indexed = table in _INDEXED
|
||||
for i, chunk in enumerate(chunks):
|
||||
nxt = indices[i + 1] if i + 1 < len(indices) else candidate
|
||||
last_page = i + 1 == len(chunks)
|
||||
# Indexed tables mark a full page 0x1FFF/0x1FFF and a page with room
|
||||
# rows+1 / 0 — as a real export's tracks and playlist pages do.
|
||||
fill = None
|
||||
if indexed:
|
||||
fill = (len(chunk) + 1, 0) if last_page else (_NONE, _NONE)
|
||||
self.sequence += 1
|
||||
self.pages[indices[i]] = _data_page(indices[i], table, nxt, chunk, self.sequence,
|
||||
shift_at=shift_at, fill=fill)
|
||||
self._index(first, indices, indexed=indexed)
|
||||
self.tables[table] = [slot, candidate, first, indices[-1]]
|
||||
|
||||
def _index(self, header_page: int, data_pages: list[int], *, indexed: bool) -> None:
|
||||
"""Point the table's HEADER page at its data.
|
||||
|
||||
A header page is not empty: past its 0x28-byte header it holds an index —
|
||||
its own number, the FIRST DATA PAGE, 0x03FFFFFF, 0, a u16 entry count,
|
||||
0x1FFF, then entries `page << 3 | flag` padded with 0x1FFFFFF8. Every
|
||||
table with data points at its first data page (left at 0x03FFFFFF,
|
||||
rekordbox calls the library corrupted); the indexed tables (tracks, the
|
||||
playlist tree, history) also list every data page — flag 3 for a page
|
||||
with room, 0 for a full one — and the header's u7 is that count, u5 the
|
||||
number of pages with room and num_rows_large the first of them.
|
||||
"""
|
||||
o = header_page * PAGE
|
||||
struct.pack_into("<I", self.buf, o + _HEADER + 4, data_pages[0])
|
||||
if not indexed:
|
||||
return
|
||||
flags = [3 if i + 1 == len(data_pages) else 0 for i in range(len(data_pages))]
|
||||
struct.pack_into("<HH", self.buf, o + _HEADER + 16, len(data_pages), 0x1FFF)
|
||||
for k, (page, flag) in enumerate(zip(data_pages, flags)):
|
||||
struct.pack_into("<I", self.buf, o + _HEADER + 20 + 4 * k, (page << 3) | flag)
|
||||
room = [k for k, flag in enumerate(flags) if flag == 3]
|
||||
struct.pack_into("<HH", self.buf, o + 0x20, len(room) or _NONE, room[0] if room else _NONE)
|
||||
struct.pack_into("<H", self.buf, o + 0x26, len(data_pages))
|
||||
self.pages_with_room += len(room)
|
||||
|
||||
def stamp_track_count(self, n: int) -> None:
|
||||
"""The history header row counts the library's tracks (and flags that
|
||||
it has any): 8 on a real 8-track export, 0 in the empty template."""
|
||||
_, _, first, last = self.tables[HISTORY]
|
||||
for _header, row in _rows(bytes(self.buf), first, last):
|
||||
if row is not None:
|
||||
self.buf[row + 3] = 1 if n else 0
|
||||
struct.pack_into("<I", self.buf, row + 4, n)
|
||||
break
|
||||
if n:
|
||||
# A library with tracks also INDEXES its history page — entry
|
||||
# `page << 3 | 0`, count 1, u7 1 — which the empty template does not.
|
||||
o = first * PAGE
|
||||
struct.pack_into("<HH", self.buf, o + _HEADER + 16, 1, 0x1FFF)
|
||||
struct.pack_into("<I", self.buf, o + _HEADER + 20, last << 3)
|
||||
struct.pack_into("<H", self.buf, o + 0x26, 1)
|
||||
|
||||
def stamp_history_date(self, when: date) -> None:
|
||||
"""The history header row records the library's creation date."""
|
||||
_, _, first, last = self.tables[HISTORY]
|
||||
o = last * PAGE
|
||||
page = self.buf[o:o + PAGE]
|
||||
m = re.search(rb"\d{4}-\d{2}-\d{2}", page[_HEADER:])
|
||||
if m:
|
||||
at = o + _HEADER + m.start()
|
||||
self.buf[at:at + 10] = when.isoformat().encode("ascii")
|
||||
|
||||
def render(self) -> bytes:
|
||||
for t, (slot, empty, first, last) in self.tables.items():
|
||||
struct.pack_into("<4I", self.buf, 28 + 16 * slot, t, empty, first, last)
|
||||
struct.pack_into("<I", self.buf, 12, self.next_unused)
|
||||
# 1 in the empty template, 4 on a real export whose index lists three
|
||||
# pages with room: 1 + that count fits both. The least certain field here.
|
||||
struct.pack_into("<I", self.buf, 16, 1 + self.pages_with_room)
|
||||
struct.pack_into("<I", self.buf, 20, self.sequence + 1)
|
||||
top = max([len(self.buf) // PAGE - 1, *self.pages])
|
||||
out = bytearray(self.buf) + bytes((top + 1) * PAGE - len(self.buf))
|
||||
for index, page in self.pages.items():
|
||||
out[index * PAGE:(index + 1) * PAGE] = page
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def template(name: str = "export.pdb") -> bytes:
|
||||
return (TEMPLATE_DIR / name).read_bytes()
|
||||
|
||||
|
||||
# ---- the reader ----------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass
|
||||
class Library:
|
||||
"""What a device library holds, decoded — for tests and diagnostics."""
|
||||
|
||||
tracks: list[dict] = field(default_factory=list)
|
||||
genres: dict[int, str] = field(default_factory=dict)
|
||||
artists: dict[int, str] = field(default_factory=dict)
|
||||
albums: dict[int, str] = field(default_factory=dict)
|
||||
labels: dict[int, str] = field(default_factory=dict)
|
||||
keys: dict[int, str] = field(default_factory=dict)
|
||||
artwork: dict[int, str] = field(default_factory=dict)
|
||||
playlists: list[dict] = field(default_factory=list)
|
||||
entries: list[tuple[int, int, int]] = field(default_factory=list)
|
||||
pages: dict[int, list[dict]] = field(default_factory=dict) # table -> page headers
|
||||
|
||||
|
||||
def _rows(buf: bytes, first: int, last: int):
|
||||
"""(page header dict, row offset) for every present row of a table."""
|
||||
p, seen = first, 0
|
||||
while True:
|
||||
o = p * PAGE
|
||||
if o + PAGE > len(buf):
|
||||
return
|
||||
flags = buf[o + 0x1B]
|
||||
n = (buf[o + 0x19] >> 5) | (buf[o + 0x1A] << 3)
|
||||
header = {"index": p, "flags": flags, "rows": n,
|
||||
"next": struct.unpack_from("<I", buf, o + 12)[0],
|
||||
"free": struct.unpack_from("<H", buf, o + 0x1C)[0],
|
||||
"used": struct.unpack_from("<H", buf, o + 0x1E)[0]}
|
||||
yield header, None
|
||||
if not flags & _HEADER_PAGE:
|
||||
for g in range((n + 15) // 16):
|
||||
base = o + PAGE - g * _GROUP
|
||||
present = struct.unpack_from("<H", buf, base - 4)[0]
|
||||
for r in range(16):
|
||||
if present & (1 << r):
|
||||
yield header, o + _HEADER + struct.unpack_from("<H", buf, base - 6 - 2 * r)[0]
|
||||
if p == last or seen > 10000:
|
||||
return
|
||||
p, seen = header["next"], seen + 1
|
||||
|
||||
|
||||
def read(buf: bytes) -> Library:
|
||||
lib = Library()
|
||||
n_tables = struct.unpack_from("<I", buf, 8)[0]
|
||||
for i in range(n_tables):
|
||||
t, _empty, first, last = struct.unpack_from("<4I", buf, 28 + 16 * i)
|
||||
for header, row in _rows(buf, first, last):
|
||||
if row is None:
|
||||
lib.pages.setdefault(t, []).append(header)
|
||||
continue
|
||||
if t == TRACKS:
|
||||
values = dict(zip([n for n, _ in _TRACK_FIELDS], struct.unpack_from(_TRACK_FMT, buf, row)))
|
||||
offs = struct.unpack_from(f"<{len(TRACK_STRINGS)}H", buf, row + _TRACK_FIXED)
|
||||
values.update({name: read_dsql(buf, row + o) for name, o in zip(TRACK_STRINGS, offs)})
|
||||
lib.tracks.append(values)
|
||||
elif t in (GENRES, LABELS, ARTWORK):
|
||||
target = {GENRES: lib.genres, LABELS: lib.labels, ARTWORK: lib.artwork}[t]
|
||||
target[struct.unpack_from("<I", buf, row)[0]] = read_dsql(buf, row + 4)
|
||||
elif t == KEYS:
|
||||
lib.keys[struct.unpack_from("<I", buf, row)[0]] = read_dsql(buf, row + 8)
|
||||
elif t == ARTISTS:
|
||||
sub, _shift, rid, _b, ofs = struct.unpack_from("<HHIBB", buf, row)
|
||||
if sub == 0x64:
|
||||
ofs = struct.unpack_from("<H", buf, row + 10)[0]
|
||||
lib.artists[rid] = read_dsql(buf, row + ofs)
|
||||
elif t == ALBUMS:
|
||||
sub, _shift, _u, artist, rid, _u3, _b, ofs = struct.unpack_from("<HHIIIIBB", buf, row)
|
||||
lib.albums[rid] = read_dsql(buf, row + ofs)
|
||||
elif t == PLAYLIST_TREE:
|
||||
parent, _u, sort, rid, folder = struct.unpack_from("<5I", buf, row)
|
||||
lib.playlists.append({"id": rid, "parent": parent, "sort": sort,
|
||||
"folder": bool(folder), "name": read_dsql(buf, row + 20)})
|
||||
elif t == PLAYLIST_ENTRIES:
|
||||
lib.entries.append(struct.unpack_from("<3I", buf, row))
|
||||
return lib
|
||||
|
||||
|
||||
__all__ = [
|
||||
"ALBUMS", "ARTISTS", "ARTWORK", "GENRES", "KEYS", "LABELS", "Library", "PAGE",
|
||||
"PLAYLIST_ENTRIES", "PLAYLIST_TREE", "PdbWriter", "TRACKS", "TRACK_STRINGS",
|
||||
"album_row", "artist_row", "dsql", "id_string_row", "key_row", "playlist_entry_row",
|
||||
"playlist_tree_row", "read", "read_dsql", "template", "track_row",
|
||||
]
|
||||
@@ -0,0 +1,217 @@
|
||||
"""Rekordbox native rows -> the generic projection.
|
||||
|
||||
The only place a ``pyrekordbox`` ORM object becomes a generic `Track` /
|
||||
`TrackCues`. Everything above this file sees generic types exclusively.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
|
||||
from . import beatgrid, palette, timebase
|
||||
from .cue_types import cue_type, role_and_slot
|
||||
|
||||
# Rekordbox names keys musically ("Abm", "F", "Ebm") rather than in Camelot or
|
||||
# Open Key notation. Parsing that is platform knowledge and belongs here.
|
||||
_KEY_RE = re.compile(r"^([A-G])([#b]?)(m?)$", re.I)
|
||||
|
||||
# Camelot wheel position for each pitch class, per mode.
|
||||
_CAMELOT_MINOR = {
|
||||
"A": 8, "E": 9, "B": 10, "F#": 11, "Gb": 11, "C#": 12, "Db": 12,
|
||||
"G#": 1, "Ab": 1, "D#": 2, "Eb": 2, "A#": 3, "Bb": 3,
|
||||
"F": 4, "C": 5, "G": 6, "D": 7,
|
||||
}
|
||||
_CAMELOT_MAJOR = {
|
||||
"C": 8, "G": 9, "D": 10, "A": 11, "E": 12, "B": 1, "F#": 2, "Gb": 2,
|
||||
"C#": 3, "Db": 3, "G#": 4, "Ab": 4, "D#": 5, "Eb": 5, "A#": 6, "Bb": 6,
|
||||
"F": 7,
|
||||
}
|
||||
|
||||
|
||||
def parse_key(key: str | None) -> tuple[int | None, str | None]:
|
||||
"""(Camelot wheel position 1-12, mode) for a Rekordbox key name."""
|
||||
if not key:
|
||||
return None, None
|
||||
m = _KEY_RE.match(key.strip())
|
||||
if not m:
|
||||
return None, None
|
||||
letter, accidental, minor = m.group(1).upper(), m.group(2), m.group(3)
|
||||
pitch = letter + (accidental.replace("B", "b") if accidental else "")
|
||||
table = _CAMELOT_MINOR if minor else _CAMELOT_MAJOR
|
||||
n = table.get(pitch)
|
||||
return (n, "minor" if minor else "major") if n else (None, None)
|
||||
|
||||
|
||||
# The inverse, for EXPORT. A track arriving from Traktor carries `key` as
|
||||
# Traktor's own display string ("10m") and `key_wheel`/`key_mode` as the parsed
|
||||
# position — so writing the string verbatim into a Pioneer library would show
|
||||
# "10m" where the deck expects "Abm". Rendering from the wheel is the only
|
||||
# correct crossing. Shared with the OneLibrary exporter: same vendor, same
|
||||
# notation, and two tables would drift.
|
||||
_MINOR_NAMES = {v: k for k, v in reversed(list(_CAMELOT_MINOR.items()))}
|
||||
_MAJOR_NAMES = {v: k for k, v in reversed(list(_CAMELOT_MAJOR.items()))}
|
||||
|
||||
|
||||
def render_key(wheel: int | None, mode: str | None) -> str | None:
|
||||
"""A Pioneer-style key name ("Abm", "F") for a Camelot position + mode.
|
||||
|
||||
Returns None when the position is unknown, which is honest: a made-up key is
|
||||
worse than a blank one, and Pioneer software shows blanks without complaint.
|
||||
"""
|
||||
if not wheel or not (1 <= wheel <= 12):
|
||||
return None
|
||||
if mode == "minor":
|
||||
name = _MINOR_NAMES.get(wheel)
|
||||
return f"{name}m" if name else None
|
||||
return _MAJOR_NAMES.get(wheel)
|
||||
|
||||
|
||||
def _iso_date(value) -> str | None:
|
||||
"""Rekordbox already stores ISO-ish 'YYYY-MM-DD'; blanks become None."""
|
||||
if not value:
|
||||
return None
|
||||
s = str(value).strip()
|
||||
return s or None
|
||||
|
||||
|
||||
def _bpm(row) -> float | None:
|
||||
"""``djmdContent.BPM`` is the tempo x100, and 0 means 'not known'.
|
||||
|
||||
It is a display value only — the real grid is in the ANLZ file — and it is
|
||||
genuinely 0 for analysed tracks in real libraries.
|
||||
"""
|
||||
raw = getattr(row, "BPM", None)
|
||||
if not raw:
|
||||
return None
|
||||
return round(raw / 100.0, 2)
|
||||
|
||||
|
||||
def _name_of(related) -> str | None:
|
||||
"""A joined lookup row's display name, or None when unset."""
|
||||
if related is None:
|
||||
return None
|
||||
for attr in ("Name", "ScaleName"):
|
||||
value = getattr(related, attr, None)
|
||||
if value:
|
||||
return str(value)
|
||||
return None
|
||||
|
||||
|
||||
def to_track(row, cue_kinds=(), *, stem: bool = False) -> Track:
|
||||
"""Project one ``DjmdContent`` row.
|
||||
|
||||
`cue_kinds` is this track's ``(Kind, OutMsec, ColorTableIndex)`` from the store's single
|
||||
query — passed in rather than read off the row, which would be a per-track
|
||||
round trip. "Is this a hot cue, and on which pad?" is `role_and_slot`, the
|
||||
same definition `to_track_cues` uses, so the table's count and dots agree
|
||||
with the pads shown in the deck (it also rules out the reserved Kind).
|
||||
|
||||
**`grid_marker_count` is an approximation here**: the real count needs the
|
||||
track's ANLZ file, which is far too slow to read for every track at open
|
||||
(~12 s on a library of 8,500). A track with a BPM is reported as 1 (constant
|
||||
tempo, true for all but a fraction of a percent of real tracks) and the value
|
||||
is corrected the moment the track's grid is actually read.
|
||||
|
||||
BPM — not the presence of an analysis file — is the signal, because Rekordbox
|
||||
analyses one-shot samples too and gives them an ANLZ with no beatgrid at all.
|
||||
On the reference library the two sets agree exactly: all 22 tracks with no
|
||||
BPM are precisely the 22 with no grid.
|
||||
"""
|
||||
chips: list[HotcueChip] = []
|
||||
for kind, out_msec, color_code in cue_kinds:
|
||||
role, slot = role_and_slot(kind)
|
||||
if role == "hotcue" and slot is not None:
|
||||
chips.append(HotcueChip(slot=slot, type=cue_type(out_msec),
|
||||
color=palette.hex_for(color_code)))
|
||||
chips.sort(key=lambda chip: chip.slot)
|
||||
key_name = _name_of(getattr(row, "Key", None))
|
||||
wheel, mode = parse_key(key_name)
|
||||
return Track(
|
||||
id=str(row.ID),
|
||||
artist=_name_of(getattr(row, "Artist", None)),
|
||||
title=getattr(row, "Title", None),
|
||||
album=_name_of(getattr(row, "Album", None)),
|
||||
genre=_name_of(getattr(row, "Genre", None)),
|
||||
label=_name_of(getattr(row, "Label", None)),
|
||||
remixer=_name_of(getattr(row, "Remixer", None)),
|
||||
producer=None, # Rekordbox has Composer, which is not the same field
|
||||
mix=None,
|
||||
comment=getattr(row, "Commnt", None),
|
||||
bpm=_bpm(row),
|
||||
key=key_name,
|
||||
key_wheel=wheel,
|
||||
key_mode=mode,
|
||||
# Rekordbox stores 0-5 stars directly — no /51 conversion, unlike Traktor.
|
||||
rating=max(0, min(5, int(getattr(row, "Rating", 0) or 0))),
|
||||
playcount=getattr(row, "DJPlayCount", None),
|
||||
length=getattr(row, "Length", None),
|
||||
# kbps here; the generic model (and the table) carry bits per second.
|
||||
bitrate=(getattr(row, "BitRate", None) or 0) * 1000 or None,
|
||||
import_date=_iso_date(getattr(row, "StockDate", None)),
|
||||
last_played=None, # not modelled as a date in master.db
|
||||
release_date=_iso_date(getattr(row, "ReleaseDate", None)),
|
||||
filepath=str(getattr(row, "FolderPath", "") or "") or None,
|
||||
cue_count=len(cue_kinds),
|
||||
hotcue_count=len(chips),
|
||||
hotcues=chips,
|
||||
grid_marker_count=1 if (_bpm(row) and getattr(row, "AnalysisDataPath", None)) else 0,
|
||||
grid_locked=False, # Rekordbox has no per-track grid lock
|
||||
# What the FILE is (`store.is_stem`): Rekordbox itself plays a stem
|
||||
# file's mix, but Konduktor's deck plays its stems, and the Type column
|
||||
# must not disagree with the deck.
|
||||
media_kind="stem" if stem else "audio",
|
||||
)
|
||||
|
||||
|
||||
def to_track_cues(cue_rows: list, grid: tuple | None, time_offset: float = 0.0) -> TrackCues:
|
||||
"""Project a track's cues and beatgrid.
|
||||
|
||||
`grid` is the per-beat ``(times, bpms, beats)`` from the ANLZ file, collapsed here
|
||||
into the generic marker list. Rekordbox pairs nothing with a grid marker, so
|
||||
`companion` is always None — that is a Traktor convention.
|
||||
|
||||
`editable` says whether the adapter will accept a command on THIS cue, which
|
||||
is the only thing the UI gates on. Every hot cue is editable, loops included.
|
||||
|
||||
**Memory cues are not**: Rekordbox is the only platform that has them, so
|
||||
under the two-platform promotion rule they are shown and never written. A cue
|
||||
sitting on the reserved `Kind` occupies no pad and is projected the same way,
|
||||
because that is how Rekordbox itself displays one.
|
||||
"""
|
||||
markers: list[GridMarker] = []
|
||||
if grid is not None:
|
||||
markers = beatgrid.markers_from_beats(*grid)
|
||||
|
||||
cues: list[CuePoint] = []
|
||||
for c in cue_rows:
|
||||
role, slot = role_and_slot(getattr(c, "Kind", None))
|
||||
out_msec = getattr(c, "OutMsec", None)
|
||||
in_msec = getattr(c, "InMsec", 0) or 0
|
||||
kind = cue_type(out_msec)
|
||||
length = 0.0
|
||||
if out_msec is not None and out_msec > 0:
|
||||
length = max(0.0, (out_msec - in_msec) / 1000.0)
|
||||
editable = role == "hotcue"
|
||||
cues.append(
|
||||
CuePoint(
|
||||
name=(getattr(c, "Comment", None) or None),
|
||||
type=kind,
|
||||
role=role,
|
||||
# rekordbox's clock -> the decoded audio's (see `timebase`); the
|
||||
# grid arrives already converted by the store.
|
||||
start=timebase.from_pioneer(in_msec / 1000.0, time_offset),
|
||||
length=length,
|
||||
slot=slot,
|
||||
color=_cue_color(c),
|
||||
editable=editable,
|
||||
readonly_reason=None if editable else "platform_managed",
|
||||
grid_marker=None,
|
||||
)
|
||||
)
|
||||
return TrackCues(grid_markers=markers, grid_locked=False, cues=cues)
|
||||
|
||||
|
||||
def _cue_color(row) -> str | None:
|
||||
"""Rekordbox stores a PALETTE CODE (`ColorTableIndex`), not an RGB value;
|
||||
`Color` is -1 on a coloured cue. A loop's uncoloured convention is code 0."""
|
||||
return palette.hex_for(getattr(row, "ColorTableIndex", None))
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,107 @@
|
||||
"""Pioneer's clock vs the decoded audio's — one rule, used at every boundary.
|
||||
|
||||
**rekordbox's time 0 is not always the decoded audio's time 0**, and by how much
|
||||
depends on the FILE, not just its format. rekordbox does not trim the start
|
||||
padding a gapless decoder removes, so every position it stores — beats, cues,
|
||||
loops — sits LATER than the same moment in the decoded audio by exactly that
|
||||
padding:
|
||||
|
||||
* **MP3 with a Xing/Info header**: the header's encoder delay + 529 decoder
|
||||
delay — 1105 samples (~25 ms at 44.1 kHz) for LAME's usual 576. rekordbox
|
||||
SKIPS the header frame (Traktor does not — see `adapters/traktor/timebase.py`),
|
||||
it just does not trim.
|
||||
* **MP3 without a header**: 0. No decoder knows the delay, so none trims it.
|
||||
* **AAC / M4A** (incl. a Traktor `.stem.m4a`): the edit list's priming, which
|
||||
rekordbox ignores — 1024 samples from FFmpeg's encoder, 2112 from Apple's.
|
||||
* **Lossless**: 0.
|
||||
|
||||
Measured 2026-09-30 in rekordbox 7 with kit 4 (see the stem-conversion discussion
|
||||
log): blinded hotcues Konduktor wrote on a synthetic kick landed on it only at
|
||||
these offsets, hot cues placed by hand read back at them to rekordbox's 1 ms
|
||||
resolution, and rekordbox's own grids agree. It replaced a fixed 1105 samples
|
||||
for every lossy file, fitted to a library of MP3s that all had headers and
|
||||
FFmpeg-encoded M4As — right for those, 25 ms wrong on a header-less MP3 and
|
||||
22 ms wrong on Apple-encoded AAC.
|
||||
|
||||
Derived, not measured: an MP3 header whose delay field a decoder does not trust
|
||||
(no LAME/Lavf/Lavc tag, or VBRI) — nothing is trimmed, so 0.
|
||||
|
||||
A file that cannot be READ (offline, or a path that does not resolve) falls back
|
||||
to the old 1105 samples for a lossy suffix: the overwhelmingly common case, and
|
||||
what every position written before this rule assumed.
|
||||
|
||||
The generic model is in the DECODED time base — what Konduktor's deck plays and
|
||||
the grid detector measures. So a Pioneer adapter ADDS the offset on every write
|
||||
and SUBTRACTS it on every read. Get it wrong and nothing fails: every cue and
|
||||
beat is simply early in rekordbox (as the first OneLibrary exports were), or
|
||||
late in Konduktor.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
from ...core import mp3_gapless, mp4_edit
|
||||
|
||||
#: The fallback for a lossy file that cannot be read: MP3's classic codec delay.
|
||||
CODEC_DELAY_SAMPLES = 1105
|
||||
#: Formats that carry a start padding. `.stem.m4a` (a Traktor STEM) is AAC.
|
||||
LOSSY = frozenset({".mp3", ".m4a", ".mp4", ".aac"})
|
||||
_MP4 = frozenset({".m4a", ".mp4"})
|
||||
_DEFAULT_RATE = 44100
|
||||
|
||||
|
||||
@lru_cache(maxsize=4096)
|
||||
def _sample_rate(path: str) -> int:
|
||||
try:
|
||||
import mutagen
|
||||
|
||||
rate = getattr(getattr(mutagen.File(path), "info", None), "sample_rate", None)
|
||||
return int(rate) if rate else _DEFAULT_RATE
|
||||
except Exception: # an unreadable header: assume the overwhelmingly common rate
|
||||
return _DEFAULT_RATE
|
||||
|
||||
|
||||
def _measured(p: Path) -> float | None:
|
||||
"""The per-file offset, or None when the file cannot be read."""
|
||||
suffix = p.suffix.lower()
|
||||
if suffix == ".mp3":
|
||||
start = mp3_gapless.read(p)
|
||||
if start is None:
|
||||
return None
|
||||
return start.trimmed / start.sample_rate if start.header_frame else 0.0
|
||||
if suffix in _MP4:
|
||||
return mp4_edit.priming_seconds(p)
|
||||
return None # raw ADTS .aac: nothing to read, keep the fallback
|
||||
|
||||
|
||||
def offset(path: Path | str | None) -> float:
|
||||
"""Seconds to ADD to a decoded-audio time to get rekordbox's; 0 if lossless.
|
||||
|
||||
A missing path (a track whose audio cannot be located) gets 0: there is no
|
||||
file to say which format it is, and guessing lossy would move a lossless
|
||||
track's cues. A path to a lossy file that cannot be read gets the fallback.
|
||||
"""
|
||||
if not path:
|
||||
return 0.0
|
||||
p = Path(path)
|
||||
if p.suffix.lower() not in LOSSY:
|
||||
return 0.0
|
||||
measured = _measured(p)
|
||||
if measured is not None:
|
||||
return measured
|
||||
return CODEC_DELAY_SAMPLES / _sample_rate(str(p))
|
||||
|
||||
|
||||
def to_pioneer(seconds: float, off: float) -> float:
|
||||
"""A decoded-audio time -> rekordbox's, never before its own time 0: the
|
||||
generic model can hold a position before the decoded audio starts (a
|
||||
Traktor grid anchored inside an MP3's header frame), which no Pioneer field
|
||||
can store."""
|
||||
return max(0.0, seconds + off)
|
||||
|
||||
|
||||
def from_pioneer(seconds: float, off: float) -> float:
|
||||
"""Back to the decoded time base, never before the start of the track: a
|
||||
rekordbox position inside the codec delay is the track's first sample."""
|
||||
return max(0.0, seconds - off)
|
||||
@@ -0,0 +1,17 @@
|
||||
"""The Traktor adapter: NML v20 (Traktor Pro 4) via ``traktor-nml-utils``.
|
||||
|
||||
Importing this package registers the platform, so ``core.registry`` can find it
|
||||
without knowing it exists — and registers it as an export TARGET, which is a
|
||||
separate registry because opening a library and creating one from nothing are
|
||||
different capabilities: Rekordbox has the first and not the second.
|
||||
"""
|
||||
from ...core import export as core_export
|
||||
from ...core import registry
|
||||
from .driver import TraktorDriver
|
||||
from .export import TraktorExporter
|
||||
|
||||
TRAKTOR = TraktorDriver()
|
||||
registry.register(TRAKTOR)
|
||||
|
||||
TRAKTOR_EXPORTER = TraktorExporter()
|
||||
core_export.register(TRAKTOR_EXPORTER)
|
||||
@@ -0,0 +1,426 @@
|
||||
"""The Traktor adapter: owns the native NML model and the generic projection.
|
||||
|
||||
This is the object the app talks to. It holds:
|
||||
|
||||
* a ``TraktorStore`` — the retained NATIVE model, which is the write target.
|
||||
Commands are replayed onto it; it is never regenerated from the projection.
|
||||
* a ``TrackIndex`` — the generic READ projection, rebuilt from the store.
|
||||
|
||||
Only one parse happens per open, and the projection is refreshed from the same
|
||||
object graph the commands mutate — so the two cannot drift.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
from ...core.adapter import InvalidCommand, NotFound, Unsupported
|
||||
from ...core.capabilities import Capabilities
|
||||
from ...core.model import PlaylistNode, Track, TrackCues
|
||||
from ...core.pathmap import PathMapping
|
||||
from ...core.query import TrackIndex
|
||||
from ...core.relocate import PathGroup
|
||||
from . import capabilities as caps
|
||||
from . import projection
|
||||
from .cue_types import CUE_TYPE_TO_NATIVE
|
||||
from .store import PlaylistError, TraktorStore
|
||||
|
||||
|
||||
|
||||
|
||||
class TraktorAdapter:
|
||||
platform = "traktor"
|
||||
|
||||
def __init__(self, path: Path):
|
||||
self.path = Path(path)
|
||||
self._store = TraktorStore(self.path)
|
||||
self._index = TrackIndex()
|
||||
self._rebuild()
|
||||
|
||||
# ---- projection maintenance ----------------------------------------
|
||||
def _rebuild(self) -> None:
|
||||
"""Re-project every track. Needed after a save or a path remap, where
|
||||
track ids themselves change and a per-track patch is impossible."""
|
||||
self._index.rebuild([projection.to_track(e) for e in self._store.iter_entries()])
|
||||
|
||||
def _refresh(self, track_id: str) -> TrackCues:
|
||||
"""Re-project one track after a command, and return its fresh cues."""
|
||||
entry = self._store.model_entry(track_id)
|
||||
if entry is None:
|
||||
return TrackCues()
|
||||
self._index.replace(projection.to_track(entry))
|
||||
return projection.to_track_cues(entry, self._store.time_offset_ms(entry))
|
||||
|
||||
# ---- read ------------------------------------------------------------
|
||||
@property
|
||||
def tracks(self) -> list[Track]:
|
||||
return self._index.tracks
|
||||
|
||||
@property
|
||||
def by_key(self) -> dict[str, Track]:
|
||||
return self._index.by_key
|
||||
|
||||
def track(self, track_id: str) -> Track | None:
|
||||
return self._index.get(track_id)
|
||||
|
||||
def query_tracks(self, **kw):
|
||||
return self._index.query_tracks(**kw)
|
||||
|
||||
def facets(self):
|
||||
return self._index.facets()
|
||||
|
||||
def stats(self, playlist_count: int):
|
||||
return self._index.stats(playlist_count)
|
||||
|
||||
def track_cues(self, track_id: str) -> TrackCues | None:
|
||||
entry = self._store.model_entry(track_id)
|
||||
if entry is None:
|
||||
return None
|
||||
return projection.to_track_cues(entry, self._store.time_offset_ms(entry))
|
||||
|
||||
# ---- transitional shims --------------------------------------------
|
||||
# main.py still drives the store directly and calls replace_track after each
|
||||
# command; both go away when the routes move onto the protocol (step 7).
|
||||
@property
|
||||
def store(self) -> TraktorStore:
|
||||
return self._store
|
||||
|
||||
def entries_for(self, track_ids: list[str]) -> list[tuple[str, str]]:
|
||||
return self._store.entries_for(track_ids)
|
||||
|
||||
def replace_track(self, track_id: str, entry=None) -> None:
|
||||
self._refresh(track_id)
|
||||
|
||||
def reload(self) -> None:
|
||||
self._store._load()
|
||||
self._rebuild()
|
||||
|
||||
def playlist_count(self) -> int:
|
||||
return self._store.count_playlists()
|
||||
|
||||
def capabilities(self) -> Capabilities:
|
||||
return caps.capabilities_for(self.path, sorted(TraktorStore.EDITABLE_FIELDS))
|
||||
|
||||
# ---- playlists -------------------------------------------------------
|
||||
def playlist_tree(self) -> list[PlaylistNode]:
|
||||
return self._store.tree()
|
||||
|
||||
def playlist_entries(self, node_id: str) -> list[str] | None:
|
||||
return self._store.entry_keys(node_id)
|
||||
|
||||
def playlist_tracks(self, node_id: str) -> list[Track] | None:
|
||||
keys = self._store.entry_keys(node_id)
|
||||
if keys is None:
|
||||
return None
|
||||
return [t for k in keys if (t := self._index.get(k)) is not None]
|
||||
|
||||
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
|
||||
with _translate():
|
||||
return self._store.create_playlist(name, parent_id)
|
||||
|
||||
def create_folder(self, name: str, parent_id: str | None = None) -> str:
|
||||
with _translate():
|
||||
return self._store.create_folder(name, parent_id)
|
||||
|
||||
def rename_playlist(self, node_id: str, name: str) -> None:
|
||||
with _translate():
|
||||
self._store.rename_playlist(node_id, name)
|
||||
|
||||
def delete_playlist(self, node_id: str) -> None:
|
||||
with _translate():
|
||||
self._store.delete_playlist(node_id)
|
||||
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
|
||||
"""Replace a playlist's contents. The adapter resolves each id to its
|
||||
native entry kind, so callers never see Traktor's STEM/TRACK split."""
|
||||
entries = self._store.entries_for(track_ids)
|
||||
with _translate():
|
||||
self._store.set_entries(node_id, entries)
|
||||
return len(entries)
|
||||
|
||||
# ---- metadata / art --------------------------------------------------
|
||||
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None:
|
||||
with _translate():
|
||||
self._store.set_track_metadata(track_id, fields)
|
||||
self._refresh(track_id)
|
||||
return self._index.get(track_id)
|
||||
|
||||
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
|
||||
with _translate():
|
||||
self._store.set_track_art(track_id, data, mime)
|
||||
|
||||
def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
|
||||
return self._store.cover_art(track_id)
|
||||
|
||||
# ---- removing tracks ---------------------------------------------------
|
||||
def remove_tracks(self, track_ids: list[str]) -> int:
|
||||
with _translate():
|
||||
n = self._store.remove_entries(track_ids)
|
||||
if n:
|
||||
# Rebuilt rather than patched: an entry sharing a removed key went
|
||||
# too, and the index would otherwise still hold its projection.
|
||||
self._rebuild()
|
||||
return n
|
||||
|
||||
# ---- stem conversion --------------------------------------------------
|
||||
def apply_stem_swaps(self, swaps: list, *, add_to_playlist: str | None = None):
|
||||
with _translate():
|
||||
result = self._store.apply_stem_swaps(swaps, add_to_playlist=add_to_playlist)
|
||||
# One rebuild for the whole batch: ids changed (repoint) or appeared
|
||||
# (add), and `TrackIndex` has no per-id remove.
|
||||
self._rebuild()
|
||||
return result
|
||||
|
||||
# ---- adding tracks ----------------------------------------------------
|
||||
def add_tracks(self, items: list, *, checkpoint=None) -> 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 —
|
||||
the only genuinely new code — and then the track's cues and grid are
|
||||
written by **replaying the ordinary commands** onto it. So an imported
|
||||
track's beatgrid goes in through the same `replace_grid` that the deck's
|
||||
Reset button uses, and inherits its companion-cue handling, its TEMPO
|
||||
mirroring and its tests, rather than growing a second implementation
|
||||
that would drift.
|
||||
|
||||
Lossiness follows the settled rule — degrade to the nearest equivalent,
|
||||
drop only where none exists:
|
||||
|
||||
* **Memory cues become hot cues in spare slots.** Traktor has no
|
||||
memory cues, and every Traktor cue occupies a slot. Filling the
|
||||
leftovers preserves the positions a DJ actually marked; when the
|
||||
bank is full the rest are dropped, because there is nowhere left.
|
||||
* **Cue colour is dropped.** Traktor derives a cue's colour from its
|
||||
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:
|
||||
audio = Path(item.audio_path)
|
||||
if not audio.is_file():
|
||||
raise InvalidCommand(f"No audio file at {audio}")
|
||||
with _translate():
|
||||
track_id = self._store.add_entry(item.track, audio)
|
||||
# Into the projection BEFORE the cues are replayed: those go through
|
||||
# the ordinary commands, and those look the track up by id.
|
||||
entry = self._store.model_entry(track_id)
|
||||
self._index.add(projection.to_track(entry))
|
||||
added.append(track_id)
|
||||
if item.cues is not None:
|
||||
self._apply_imported_cues(track_id, item.cues)
|
||||
self._refresh(track_id)
|
||||
return added
|
||||
|
||||
def _apply_imported_cues(self, track_id: str, cues) -> None:
|
||||
"""Replay a generic TrackCues onto a freshly added entry."""
|
||||
markers = [(m.start, m.bpm) for m in (cues.grid_markers or [])]
|
||||
if markers:
|
||||
# `replace_grid`, NOT `set_analysed_grid`. The latter also places
|
||||
# Traktor's beat-1 companion cue, and that is wrong twice over here:
|
||||
# it invents a cue the source never had (companions are a Traktor
|
||||
# convention, and the project's rule is to follow them but never
|
||||
# invent one outside Auto Grid), and it occupies pad A — which
|
||||
# silently displaced the imported track's own pad A cue.
|
||||
self.replace_grid(track_id, markers)
|
||||
|
||||
slots = self.capabilities().cues.hotcue_slots
|
||||
taken = {c.slot for c in self.track_cues(track_id).cues if c.slot is not None}
|
||||
hotcues = [c for c in (cues.cues or []) if c.role == "hotcue" and c.slot is not None]
|
||||
|
||||
# Hot cues keep the pad they were on wherever that pad is free, because
|
||||
# muscle memory is most of what a hot cue layout IS.
|
||||
displaced: list = []
|
||||
for cue in sorted(hotcues, key=lambda c: c.slot):
|
||||
if cue.slot in taken or not (0 <= cue.slot < slots):
|
||||
displaced.append(cue)
|
||||
continue
|
||||
self._place_imported_cue(track_id, cue.slot, cue)
|
||||
taken.add(cue.slot)
|
||||
|
||||
# Everything without a pad of its own competes for what is left: memory
|
||||
# cues, which Traktor has no equivalent for, and any hot cue whose pad
|
||||
# was already occupied. Earliest first, so that when the bank runs out
|
||||
# it is the late cues that are lost rather than an arbitrary set — and
|
||||
# a displaced hot cue is moved rather than dropped, because losing one
|
||||
# silently is much worse than having it turn up on the wrong pad.
|
||||
leftovers = displaced + [c for c in (cues.cues or []) if c.role != "hotcue"]
|
||||
spare = (s for s in range(slots) if s not in taken)
|
||||
for cue in sorted(leftovers, key=lambda c: c.start):
|
||||
slot = next(spare, None)
|
||||
if slot is None:
|
||||
break # bank full: the rest are dropped, per the lossiness rule
|
||||
self._place_imported_cue(track_id, slot, cue)
|
||||
|
||||
def _place_imported_cue(self, track_id: str, slot: int, cue) -> None:
|
||||
cue_type = "loop" if getattr(cue, "length", 0) else "cue"
|
||||
if cue_type not in CUE_TYPE_TO_NATIVE:
|
||||
return
|
||||
self.set_cue(
|
||||
track_id,
|
||||
slot=slot,
|
||||
start_sec=cue.start,
|
||||
cue_type=cue_type,
|
||||
length_sec=getattr(cue, "length", 0.0) or 0.0,
|
||||
name=getattr(cue, "name", None),
|
||||
)
|
||||
|
||||
# ---- cues -------------------------------------------------------------
|
||||
def _native_cue_type(self, cue_type: str) -> int:
|
||||
native = CUE_TYPE_TO_NATIVE.get(cue_type)
|
||||
if native is None:
|
||||
raise Unsupported(f"Traktor has no cue type {cue_type!r}")
|
||||
return native
|
||||
|
||||
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:
|
||||
if role != "hotcue":
|
||||
# Memory cues are a Rekordbox concept; every Traktor cue holds a slot.
|
||||
raise Unsupported("Traktor cues always occupy a hotcue slot")
|
||||
with _translate():
|
||||
self._store.set_hotcue(
|
||||
track_id, slot, start_sec, self._native_cue_type(cue_type), length_sec, name
|
||||
)
|
||||
return self._refresh(track_id)
|
||||
|
||||
def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> TrackCues:
|
||||
with _translate():
|
||||
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)
|
||||
return self._refresh(track_id)
|
||||
|
||||
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues:
|
||||
native = [
|
||||
SimpleNamespace(
|
||||
slot=c.slot,
|
||||
start=c.start,
|
||||
name=c.name,
|
||||
type=self._native_cue_type(getattr(c, "type", "cue")),
|
||||
length=getattr(c, "length", 0.0),
|
||||
)
|
||||
for c in cues
|
||||
]
|
||||
with _translate():
|
||||
self._store.place_hotcues(track_id, native, overwrite=overwrite)
|
||||
return self._refresh(track_id)
|
||||
|
||||
# ---- beatgrid ---------------------------------------------------------
|
||||
def add_grid_marker(self, track_id, start_sec, bpm=None) -> TrackCues:
|
||||
with _translate():
|
||||
self._store.add_grid_marker(track_id, start_sec, bpm)
|
||||
return self._refresh(track_id)
|
||||
|
||||
def move_grid_marker(self, track_id, index, start_sec) -> TrackCues:
|
||||
with _translate():
|
||||
self._store.move_grid_marker(track_id, index, start_sec)
|
||||
return self._refresh(track_id)
|
||||
|
||||
def set_grid_marker_bpm(self, track_id, index, bpm) -> TrackCues:
|
||||
with _translate():
|
||||
self._store.set_grid_marker_bpm(track_id, index, bpm)
|
||||
return self._refresh(track_id)
|
||||
|
||||
def delete_grid_marker(self, track_id, index) -> TrackCues:
|
||||
with _translate():
|
||||
self._store.delete_grid_marker(track_id, index)
|
||||
return self._refresh(track_id)
|
||||
|
||||
def replace_grid(self, track_id, markers: list[tuple[float, float]]) -> TrackCues:
|
||||
"""Set exactly these markers and nothing else (the deck's Reset)."""
|
||||
with _translate():
|
||||
self._store.replace_grid(track_id, markers)
|
||||
return self._refresh(track_id)
|
||||
|
||||
def set_analysed_grid(self, track_id, markers: list[tuple[float, float]]) -> TrackCues:
|
||||
"""Write an analysis result the way this platform's own analyser would.
|
||||
|
||||
Traktor pairs its first grid marker with a white beat-1 cue, so a grid it
|
||||
wrote looks different from one merely assigned. Keeping that as a
|
||||
separate intent is what lets the companion convention stay inside this
|
||||
adapter instead of leaking into the generic vocabulary.
|
||||
"""
|
||||
with _translate():
|
||||
self._store.replace_grid(track_id, markers)
|
||||
self._store.place_grid_companion(track_id, 0, prefer_slot=0)
|
||||
return self._refresh(track_id)
|
||||
|
||||
def delete_grid(self, track_id) -> TrackCues:
|
||||
with _translate():
|
||||
self._store.delete_grid(track_id)
|
||||
return self._refresh(track_id)
|
||||
|
||||
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues:
|
||||
with _translate():
|
||||
self._store.set_lock(track_id, locked)
|
||||
return self._refresh(track_id)
|
||||
|
||||
# ---- audio / paths ----------------------------------------------------
|
||||
def audio_path(self, track_id: str):
|
||||
return self._store.audio_path(track_id)
|
||||
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None:
|
||||
self._store.set_path_mapping(mapping)
|
||||
|
||||
def set_session_mappings(self, mappings: list[PathMapping]) -> None:
|
||||
self._store.set_session_mappings(mappings)
|
||||
|
||||
def unresolved_path_groups(self) -> list[PathGroup]:
|
||||
return self._store.unresolved_path_groups()
|
||||
|
||||
def path_prefix_suggestions(self) -> dict:
|
||||
return self._store.path_prefix_suggestions()
|
||||
|
||||
def remap_preview(self, mapping: PathMapping) -> dict:
|
||||
return self._store.remap_preview(mapping)
|
||||
|
||||
def remap_locations(self, mapping: PathMapping) -> dict[str, str]:
|
||||
with _translate():
|
||||
moved = self._store.remap_locations(mapping)
|
||||
# A remap rewrites LOCATIONs, so track ids themselves change — there is
|
||||
# no per-track patch that could express this.
|
||||
self._rebuild()
|
||||
return moved
|
||||
|
||||
# ---- save --------------------------------------------------------------
|
||||
@property
|
||||
def dirty(self) -> bool:
|
||||
return self._store.dirty
|
||||
|
||||
def save(self):
|
||||
outcome = self._store.save()
|
||||
self._rebuild() # save() re-parses, so every object identity changed
|
||||
return outcome
|
||||
|
||||
def snapshot(self) -> bytes:
|
||||
return self._store._render()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _translate():
|
||||
"""Map the store's native error onto the generic one the HTTP layer maps."""
|
||||
try:
|
||||
yield
|
||||
except PlaylistError as ex:
|
||||
msg = str(ex)
|
||||
if "not found" in msg.lower():
|
||||
raise NotFound(msg) from ex
|
||||
raise InvalidCommand(msg) from ex
|
||||
@@ -0,0 +1,117 @@
|
||||
"""The beatgrid model: an ORDERED LIST of grid markers.
|
||||
|
||||
A Traktor beatgrid is not "a BPM and an anchor" — it is a list of `CUE_V2
|
||||
TYPE="4"` markers, each carrying its own `<GRID BPM>` child. Marker *i*'s tempo
|
||||
governs from its position until marker *i+1*. Traktor has stored grids this way
|
||||
since 3.4 (flexible beatgrids); a constant-tempo track is simply a list of
|
||||
length one, which is why this model is right for every track rather than a
|
||||
special case for flexible ones.
|
||||
|
||||
`<TEMPO BPM>` mirrors the FIRST marker by START.
|
||||
|
||||
Verified against the 8485-entry reference collection:
|
||||
* markers per entry: {1: 7966, 0: 517, 2: 2}
|
||||
* TEMPO.bpm == markers[0].grid.bpm in 7968/7968 entries with both
|
||||
* CUE_V2 is ascending by START in 8485/8485 entries
|
||||
* 53 entries have a TEMPO but no marker -> deleting a grid must KEEP TEMPO
|
||||
|
||||
Two rules that are easy to get wrong:
|
||||
|
||||
1. **Marker NAME is not a discriminator.** In the reference collection TYPE=4
|
||||
markers are named "AutoGrid" x7888, "n.n." x64, "Beat Marker" x14 and
|
||||
"Unnamed" x4. Identify a marker by having a `<GRID>` child, and order the
|
||||
list by START — never by name, never by document order.
|
||||
|
||||
2. **Companion cues are conventional, not structural.** Traktor usually writes a
|
||||
white TYPE=0 cue alongside each grid marker, at the same position, occupying
|
||||
a real hotcue slot. 7910 of 7970 markers have one; 60 do not, and one track
|
||||
has a companion on its first marker but not its second. So we follow them
|
||||
where they exist, keep them in sync, and NEVER invent one.
|
||||
|
||||
This module is pure and imports nothing else from the package, so it can be the
|
||||
single shared definition used by the store, the API projection and the read
|
||||
model — which previously each had their own and disagreed about BPM.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from traktor_nml_utils.models.collection import CueV2Type, Entrytype
|
||||
|
||||
# How close a cue must sit to a marker to be considered its companion. Traktor
|
||||
# writes them at the identical START; 71 markers in the reference collection are
|
||||
# a fraction of a millisecond off, which this absorbs.
|
||||
COMPANION_EPS_MS = 1.0
|
||||
|
||||
# Companions are always white. This test is LOAD-BEARING: 49 uncoloured cues and
|
||||
# 18 LOOPS also sit within 1 ms of a marker in the reference collection. Drop the
|
||||
# colour check and the marker commands would start dragging and deleting the
|
||||
# user's own loops.
|
||||
COMPANION_COLOR = "#FFFFFF"
|
||||
|
||||
|
||||
def grid_markers(entry: Entrytype) -> list[CueV2Type]:
|
||||
"""Every grid marker on `entry`, ordered by START.
|
||||
|
||||
Sorting is not cosmetic: the first marker by START is the one `<TEMPO BPM>`
|
||||
mirrors, and marker indices are the identity used by the edit commands.
|
||||
"""
|
||||
markers = [c for c in (entry.cue_v2 or []) if getattr(c, "grid", None) is not None]
|
||||
markers.sort(key=lambda c: c.start or 0.0)
|
||||
return markers
|
||||
|
||||
|
||||
def first_marker(entry: Entrytype) -> CueV2Type | None:
|
||||
"""The marker `<TEMPO BPM>` mirrors, or None when the track has no grid."""
|
||||
markers = grid_markers(entry)
|
||||
return markers[0] if markers else None
|
||||
|
||||
|
||||
def effective_bpm(entry: Entrytype) -> float | None:
|
||||
"""The tempo the grid actually starts at.
|
||||
|
||||
Prefers the first marker's `<GRID BPM>` and falls back to `<TEMPO BPM>` so
|
||||
the 53 gridless-but-tempo'd entries still report a BPM. Routing both the
|
||||
library table and the prep deck through this makes them structurally
|
||||
incapable of disagreeing.
|
||||
"""
|
||||
marker = first_marker(entry)
|
||||
if marker is not None and marker.grid is not None and marker.grid.bpm:
|
||||
return marker.grid.bpm
|
||||
return entry.tempo.bpm if entry.tempo else None
|
||||
|
||||
|
||||
def companions(entry: Entrytype) -> dict[int, CueV2Type]:
|
||||
"""Map marker index -> the companion cue paired with it, where one exists.
|
||||
|
||||
Greedy nearest-unclaimed matching, so two markers close together can never
|
||||
both claim the same cue.
|
||||
"""
|
||||
markers = grid_markers(entry)
|
||||
if not markers:
|
||||
return {}
|
||||
pool = [
|
||||
c
|
||||
for c in (entry.cue_v2 or [])
|
||||
if getattr(c, "grid", None) is None
|
||||
and c.type == 0
|
||||
and c.color == COMPANION_COLOR
|
||||
and c.hotcue is not None
|
||||
and c.hotcue >= 0
|
||||
]
|
||||
out: dict[int, CueV2Type] = {}
|
||||
claimed: set[int] = set()
|
||||
for i, m in enumerate(markers):
|
||||
m_start = m.start or 0.0
|
||||
best = min(
|
||||
(c for c in pool if id(c) not in claimed),
|
||||
key=lambda c: abs((c.start or 0.0) - m_start),
|
||||
default=None,
|
||||
)
|
||||
if best is not None and abs((best.start or 0.0) - m_start) <= COMPANION_EPS_MS:
|
||||
out[i] = best
|
||||
claimed.add(id(best))
|
||||
return out
|
||||
|
||||
|
||||
def is_companion(entry: Entrytype, cue: CueV2Type) -> bool:
|
||||
"""True when `cue` is some grid marker's companion on this entry."""
|
||||
return any(c is cue for c in companions(entry).values())
|
||||
@@ -0,0 +1,85 @@
|
||||
"""What Traktor can persist.
|
||||
|
||||
Derived from the NML version where one is declared, which is the accurate way to
|
||||
report capabilities rather than assuming a floor that denies users features their
|
||||
install actually has. NML v19 (Traktor 3) and v20 (Traktor 4) are equivalent for
|
||||
everything Konduktor edits; flexible beatgrids arrived in Traktor 3.4, which is
|
||||
older than any NML version we can open, so the flag is unconditional.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from ...core.capabilities import (
|
||||
Capabilities,
|
||||
CueCapabilities,
|
||||
GridCapabilities,
|
||||
PlaylistCapabilities,
|
||||
SaveCapabilities,
|
||||
TrackCapabilities,
|
||||
)
|
||||
|
||||
_VERSION_RE = re.compile(rb'<NML\s+VERSION="(\d+)"')
|
||||
|
||||
# Traktor's cue vocabulary, in generic terms. The integer encoding lives in
|
||||
# projection.py / store.py and never leaves this package.
|
||||
CUE_TYPES = ["cue", "fade_in", "fade_out", "load", "loop"]
|
||||
|
||||
|
||||
def nml_version(path: Path) -> str | None:
|
||||
"""The NML VERSION attribute, read from the file head without parsing it."""
|
||||
try:
|
||||
with path.open("rb") as fh:
|
||||
m = _VERSION_RE.search(fh.read(4096))
|
||||
return m.group(1).decode() if m else None
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
|
||||
return Capabilities(
|
||||
platform="traktor",
|
||||
version=nml_version(path),
|
||||
writable=True,
|
||||
cues=CueCapabilities(
|
||||
editable=True,
|
||||
hotcue_slots=8,
|
||||
slot_labels="number",
|
||||
# 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",
|
||||
named=True,
|
||||
# A saved loop is a cue TYPE in Traktor, not a separate bank.
|
||||
loops="cue_type",
|
||||
),
|
||||
grid=GridCapabilities(editable=True, flexible=True, lockable=True),
|
||||
tracks=TrackCapabilities(
|
||||
rating_max=5,
|
||||
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.
|
||||
audio_formats=[".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a", ".mp4", ".ogg"],
|
||||
artwork=True,
|
||||
artwork_note=(
|
||||
"Traktor caches its own cover thumbnail, so a replaced image may "
|
||||
"need a manual Import Cover Art to show up."
|
||||
),
|
||||
),
|
||||
playlists=PlaylistCapabilities(folders=True, smart="read_only", reorder=True),
|
||||
save=SaveCapabilities(
|
||||
app_name="Traktor",
|
||||
library_label="collection.nml",
|
||||
# Traktor rewrites collection.nml when it quits, so an edit made
|
||||
# while it is running is lost on exit.
|
||||
overwrite_risk="on_exit",
|
||||
history=True,
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Traktor's CUE_V2 TYPE encoding <-> the generic cue vocabulary.
|
||||
|
||||
The only place these integers are given meaning. Type 4 is a grid marker, not a
|
||||
cue, so it has no generic name — grid markers are projected as beatgrid markers
|
||||
and never appear in a track's cue list.
|
||||
|
||||
Lives in its own module so the projection and the adapter can both use it
|
||||
without importing each other.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
CUE_TYPE_TO_NATIVE = {"cue": 0, "fade_in": 1, "fade_out": 2, "load": 3, "loop": 5}
|
||||
NATIVE_TO_CUE_TYPE = {v: k for k, v in CUE_TYPE_TO_NATIVE.items()}
|
||||
File renamed without changes.
@@ -0,0 +1,41 @@
|
||||
"""Opening Traktor libraries: recognition, discovery and restore."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from . import discovery
|
||||
from .adapter import TraktorAdapter
|
||||
|
||||
|
||||
class TraktorDriver:
|
||||
platform = "traktor"
|
||||
display_name = "Traktor"
|
||||
suffixes = (".nml",)
|
||||
library_label = "collection.nml"
|
||||
selects = "file"
|
||||
|
||||
def can_open(self, path: Path) -> bool:
|
||||
"""Recognise an NML without parsing 14 MB of it."""
|
||||
if not path.is_file() or path.suffix.lower() != ".nml":
|
||||
return False
|
||||
try:
|
||||
with path.open("rb") as fh:
|
||||
head = fh.read(4096)
|
||||
except OSError:
|
||||
return False
|
||||
return b"<NML" in head and b"VERSION=" in head
|
||||
|
||||
def open(self, path: Path) -> TraktorAdapter:
|
||||
return TraktorAdapter(path)
|
||||
|
||||
def detect(self) -> list[dict]:
|
||||
return discovery.detect_collections()
|
||||
|
||||
def describe(self, path: Path) -> dict:
|
||||
return discovery.describe(path)
|
||||
|
||||
def restore(self, path: Path, data: bytes) -> None:
|
||||
"""Write a history snapshot back over the library, atomically."""
|
||||
tmp = path.with_suffix(path.suffix + ".tmp")
|
||||
tmp.write_bytes(data)
|
||||
tmp.replace(path)
|
||||
@@ -0,0 +1,147 @@
|
||||
"""Writing a fresh Traktor `collection.nml` from nothing.
|
||||
|
||||
## How it works, and why it is not a second writer
|
||||
|
||||
The obvious shape — build an `Nml` object graph by hand and render it — would
|
||||
mean a SECOND definition of "generic Track plus cues plus grid becomes a Traktor
|
||||
ENTRY", living beside `TraktorStore.add_entry` and the cue/grid commands. Two
|
||||
definitions drift, and the new one would inherit none of `test_save_fidelity`'s
|
||||
coverage, none of `replace_grid`'s companion-cue handling, and none of the
|
||||
lossiness rules the import feature already settled.
|
||||
|
||||
So instead: **write an empty but valid collection, open it, and replay the
|
||||
ordinary commands onto it.** The skeleton below is the smallest NML Traktor
|
||||
accepts, verified against a real Traktor Pro 4 file.
|
||||
|
||||
That is a deliberate amendment to the original design note, which said an
|
||||
exporter should not "create then replay commands". Its stated reason was that
|
||||
doing so would make "an empty new file" and "the user's real library" share code
|
||||
paths, when the safety of the architecture rests on the write target always
|
||||
being a retained native model parsed from a real file. Here that invariant holds
|
||||
literally: the write target IS parsed from a real file — a skeleton Konduktor
|
||||
wrote a moment earlier — and the import feature has already proved the approach
|
||||
end to end in Traktor 4.5. The exporter still owns everything genuinely new: the
|
||||
skeleton, the playlist tree, and the `$ROOT` wrapper.
|
||||
|
||||
## The skeleton
|
||||
|
||||
Read off Ben's own collection rather than assumed. Note there is **no
|
||||
`<MUSICFOLDERS>` element at all**, so it is not required, and `<PLAYLISTS>` must
|
||||
wrap a `$ROOT` FOLDER node — playlists cannot sit at the top level.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
from ...core.adapter import NewTrack
|
||||
from ...core.export import ExportPayload, WrittenLibrary
|
||||
from .adapter import TraktorAdapter
|
||||
from .capabilities import capabilities_for
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
#: The smallest collection Traktor Pro 4 accepts. `PROGRAM` names the writer;
|
||||
#: Traktor itself writes "Traktor Pro 4" here and does not appear to care, but
|
||||
#: claiming to BE Traktor would be dishonest in a file a user may inspect.
|
||||
SKELETON = (
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>\n'
|
||||
'<NML VERSION="20"><HEAD COMPANY="www.native-instruments.com" '
|
||||
'PROGRAM="Konduktor"></HEAD>\n'
|
||||
'<COLLECTION ENTRIES="0"></COLLECTION>\n'
|
||||
'<SETS ENTRIES="0"></SETS>\n'
|
||||
'<PLAYLISTS><NODE TYPE="FOLDER" NAME="$ROOT"><SUBNODES COUNT="0">'
|
||||
"</SUBNODES>\n</NODE>\n</PLAYLISTS>\n"
|
||||
'<INDEXING><SORTING_INFO PATH="$COLLECTION"></SORTING_INFO>\n'
|
||||
"</INDEXING>\n</NML>\n"
|
||||
)
|
||||
|
||||
#: Loose tracks — added individually rather than through a playlist — would
|
||||
#: otherwise be reachable only by search in the exported library.
|
||||
OTHER_PLAYLIST = "Other"
|
||||
|
||||
|
||||
class TraktorExporter:
|
||||
platform = "traktor"
|
||||
menu_order = 20
|
||||
library_filename = "collection.nml"
|
||||
drive_root = False
|
||||
|
||||
def capabilities(self):
|
||||
"""What a Traktor library can hold — answered with no library to read.
|
||||
|
||||
`editable_fields` is the full safe set: an exported collection is
|
||||
brand new, so nothing about it is read-only.
|
||||
"""
|
||||
return capabilities_for(
|
||||
Path(self.library_filename),
|
||||
[
|
||||
"title", "artist", "album", "genre", "label", "remixer",
|
||||
"producer", "mix", "release_date", "comment", "comment2", "rating",
|
||||
],
|
||||
)
|
||||
|
||||
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
|
||||
destination = Path(destination)
|
||||
destination.mkdir(parents=True, exist_ok=True)
|
||||
library = destination / self.library_filename
|
||||
library.write_text(SKELETON, encoding="utf-8")
|
||||
|
||||
adapter = TraktorAdapter(library)
|
||||
|
||||
# The tracks, with their cues and grids, through the ordinary command
|
||||
# path — so an exported beatgrid is written by the same `replace_grid`
|
||||
# the deck's Reset uses.
|
||||
new_ids = adapter.add_tracks(
|
||||
[NewTrack(track=t.track, audio_path=t.destination, cues=t.cues)
|
||||
for t in payload.tracks]
|
||||
)
|
||||
# Source id -> the id it got here. Both are Traktor primary keys derived
|
||||
# from a LOCATION, and the location changed, so they are never equal.
|
||||
moved = {t.source_id: new_id for t, new_id in zip(payload.tracks, new_ids)}
|
||||
|
||||
self._write_playlists(adapter, payload, moved)
|
||||
adapter.save()
|
||||
# One file; nothing else to report.
|
||||
return WrittenLibrary(library=library)
|
||||
|
||||
def _write_playlists(self, adapter, payload: ExportPayload, moved: dict) -> None:
|
||||
"""Recreate the tree under one folder named after the export.
|
||||
|
||||
Nested under the export's own name for the same reason import nests a
|
||||
drive's playlists under the drive's name: a collection swapped onto
|
||||
another machine should say where its playlists came from.
|
||||
"""
|
||||
root = adapter.create_folder(payload.name)
|
||||
folders: dict[tuple[str, ...], str] = {(): root}
|
||||
|
||||
for playlist in payload.playlists:
|
||||
parent = self._folder_for(adapter, folders, tuple(playlist.folders), root)
|
||||
node_id = adapter.create_playlist(playlist.name, parent)
|
||||
entries = [moved[t] for t in playlist.track_ids if t in moved]
|
||||
if entries:
|
||||
adapter.set_playlist_entries(node_id, entries)
|
||||
|
||||
loose = self._loose(payload, moved)
|
||||
if loose:
|
||||
node_id = adapter.create_playlist(OTHER_PLAYLIST, root)
|
||||
adapter.set_playlist_entries(node_id, loose)
|
||||
|
||||
@staticmethod
|
||||
def _folder_for(adapter, folders: dict, path: tuple[str, ...], root: str) -> str:
|
||||
"""Create (once) the folder chain a playlist sits under, and return it."""
|
||||
for depth in range(1, len(path) + 1):
|
||||
branch = path[:depth]
|
||||
if branch not in folders:
|
||||
folders[branch] = adapter.create_folder(branch[-1], folders[branch[:-1]])
|
||||
return folders.get(path, root)
|
||||
|
||||
@staticmethod
|
||||
def _loose(payload: ExportPayload, moved: dict) -> list[str]:
|
||||
"""Tracks no exported playlist accounts for, in payload order."""
|
||||
in_playlists = {t for p in payload.playlists for t in p.track_ids}
|
||||
return [
|
||||
moved[t.source_id]
|
||||
for t in payload.tracks
|
||||
if t.source_id not in in_playlists and t.source_id in moved
|
||||
]
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Traktor LOCATION <-> OS path conversion.
|
||||
|
||||
A Traktor ``<LOCATION>`` is a ``(VOLUME, DIR, FILE)`` triple using ``/:`` as its
|
||||
directory separator, with the boot volume spelled ``Macintosh HD``. These two
|
||||
functions are exact inverses of each other and are the only place that
|
||||
convention is encoded — keep them together, and keep them out of ``core``.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
_WIN_DRIVE = re.compile(r"^([A-Za-z]:)[\\/](.*)$")
|
||||
_MAC_VOLUME = re.compile(r"^/Volumes/([^/]+)/(.*)$")
|
||||
|
||||
|
||||
def resolve_path(volume: str | None, dir_: str | None, file: str | None) -> Path:
|
||||
"""Map a Traktor LOCATION to an OS path.
|
||||
|
||||
Paths are trusted (per project decision): boot volume 'Macintosh HD' -> '/',
|
||||
a Windows drive like 'X:' stays a drive path, other volumes -> /Volumes/<v>.
|
||||
"""
|
||||
d = (dir_ or "").replace("/:", "/")
|
||||
name = file or ""
|
||||
vol = volume or ""
|
||||
if vol.endswith(":"): # Windows drive letter, e.g. "X:"
|
||||
return Path(vol + d + name)
|
||||
if vol and vol != "Macintosh HD": # other mounted volume (macOS/*nix)
|
||||
return Path("/Volumes") / vol / (d.lstrip("/") + name)
|
||||
return Path(d + name) # boot volume
|
||||
|
||||
|
||||
def _traktor_dir(posix_body: str) -> str:
|
||||
"""Convert a POSIX directory body (leading+trailing '/', e.g. '/Music/')
|
||||
to Traktor's '/:'-segmented form ('/:Music/:')."""
|
||||
return posix_body.replace("/", "/:")
|
||||
|
||||
|
||||
def os_path_to_location(os_path: Path) -> tuple[str, str, str]:
|
||||
"""Inverse of ``file_tags.resolve_path``: build a Traktor
|
||||
``(volume, dir, file)`` from an OS path, for the platform implied by the
|
||||
path's shape. Round-trips with ``resolve_path``.
|
||||
|
||||
Used by write-back only; the produced LOCATION is valid for the OS whose
|
||||
path shape it matches (Windows drive, macOS ``/Volumes`` mount, or a POSIX
|
||||
boot path -> ``Macintosh HD``).
|
||||
"""
|
||||
# Derive the filename from the string (not Path.name) so a Windows-style
|
||||
# path is handled even when this runs on a POSIX host, and vice-versa.
|
||||
s = str(os_path)
|
||||
|
||||
m = _WIN_DRIVE.match(s)
|
||||
if m:
|
||||
volume = m.group(1) # e.g. "E:"
|
||||
body = m.group(2).replace("\\", "/") # "Music/x.mp3"
|
||||
name = body.rsplit("/", 1)[-1]
|
||||
dir_body = "/" + body[: len(body) - len(name)] # "/Music/"
|
||||
return volume, _traktor_dir(dir_body), name
|
||||
|
||||
m = _MAC_VOLUME.match(s)
|
||||
if m:
|
||||
volume = m.group(1) # mounted volume name
|
||||
body = m.group(2) # "Music/x.mp3"
|
||||
name = body.rsplit("/", 1)[-1]
|
||||
dir_body = "/" + body[: len(body) - len(name)] # "/Music/"
|
||||
return volume, _traktor_dir(dir_body), name
|
||||
|
||||
# POSIX boot volume, e.g. "/Users/you/Music/x.mp3".
|
||||
name = s.rsplit("/", 1)[-1]
|
||||
dir_body = s[: len(s) - len(name)] # "/Users/you/Music/"
|
||||
return "Macintosh HD", _traktor_dir(dir_body), name
|
||||
@@ -0,0 +1,210 @@
|
||||
"""Traktor native model -> the generic projection.
|
||||
|
||||
The only place an NML dataclass is turned into a generic `Track`/`TrackCues`.
|
||||
Everything above this file sees generic types exclusively.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
|
||||
from . import beatgrid, timebase
|
||||
from .cue_types import NATIVE_TO_CUE_TYPE
|
||||
|
||||
# Traktor displays keys in Open Key ("10m" / "8d") or Camelot ("8A" / "8B"),
|
||||
# depending on a user preference — so the library can contain either. Parsing
|
||||
# notation is platform knowledge and belongs here, not in the UI.
|
||||
_OPEN_KEY = re.compile(r"^(\d{1,2})\s*([md])$", re.I)
|
||||
_CAMELOT = re.compile(r"^(\d{1,2})\s*([ab])$", re.I)
|
||||
_DATE = re.compile(r"^(\d{4})/(\d{1,2})/(\d{1,2})$")
|
||||
# "YYYY", "YYYY-MM" or "YYYY-MM-DD", optionally followed by a time (a
|
||||
# timestamp's date part is the date).
|
||||
_ISO_DATE = re.compile(r"^(\d{4})(?:-(\d{1,2})(?:-(\d{1,2}))?)?(?:[T ].*)?$")
|
||||
|
||||
|
||||
def parse_key(key: str | None) -> tuple[int | None, str | None]:
|
||||
"""(Camelot wheel position 1-12, mode) for a Traktor display key.
|
||||
|
||||
Open Key numbers the wheel seven semitones round from Camelot, so
|
||||
Open Key 1 == Camelot 8 (both are C major / A minor).
|
||||
"""
|
||||
if not key:
|
||||
return None, None
|
||||
k = key.strip()
|
||||
if m := _CAMELOT.match(k):
|
||||
n = int(m.group(1))
|
||||
if 1 <= n <= 12:
|
||||
return n, "minor" if m.group(2).lower() == "a" else "major"
|
||||
if m := _OPEN_KEY.match(k):
|
||||
n = int(m.group(1))
|
||||
if 1 <= n <= 12:
|
||||
return ((n + 6) % 12) + 1, "minor" if m.group(2).lower() == "m" else "major"
|
||||
return None, None
|
||||
|
||||
|
||||
def iso_date(value: str | None) -> str | None:
|
||||
"""Traktor writes dates as "YYYY/M/D"; the model carries ISO-8601."""
|
||||
if not value:
|
||||
return None
|
||||
m = _DATE.match(value.strip())
|
||||
if not m:
|
||||
return value
|
||||
y, mo, d = m.groups()
|
||||
return f"{y}-{int(mo):02d}-{int(d):02d}"
|
||||
|
||||
|
||||
def traktor_date(value: str | None) -> str | None:
|
||||
"""The inverse of `iso_date`: an ISO-8601 date as Traktor writes it.
|
||||
|
||||
Traktor's form is unpadded "YYYY/M/D" — every one of the 16,000-odd dates
|
||||
in the real collection. A year alone becomes "YYYY/1/1", as Traktor itself
|
||||
records a year-only release date (2,094 of 2,122 there). Anything that is
|
||||
neither ISO nor already Traktor's form passes through unchanged, as
|
||||
`iso_date` does in the other direction: losing a date is worse than
|
||||
carrying one Traktor may not parse.
|
||||
"""
|
||||
if not value:
|
||||
return None
|
||||
s = value.strip()
|
||||
if m := _DATE.match(s):
|
||||
y, mo, d = m.groups()
|
||||
return f"{y}/{int(mo)}/{int(d)}"
|
||||
if m := _ISO_DATE.match(s):
|
||||
y, mo, d = m.groups()
|
||||
return f"{y}/{int(mo or 1)}/{int(d or 1)}"
|
||||
return value
|
||||
|
||||
|
||||
def primary_key(location) -> str:
|
||||
"""Reconstruct the Traktor primary key used by playlist entries."""
|
||||
vol = location.volume or ""
|
||||
d = location.dir or ""
|
||||
f = location.file or ""
|
||||
return f"{vol}{d}{f}"
|
||||
|
||||
|
||||
def _display_path(location) -> str:
|
||||
"""Human-readable OS-ish path from Traktor's '/:'-separated dir."""
|
||||
d = (location.dir or "").replace("/:", "/")
|
||||
f = location.file or ""
|
||||
return f"{d}{f}"
|
||||
|
||||
|
||||
def _rating_stars(ranking) -> int:
|
||||
if not ranking:
|
||||
return 0
|
||||
return max(0, min(5, round(ranking / 51)))
|
||||
|
||||
|
||||
def to_track(e) -> Track:
|
||||
info = e.info
|
||||
loc = e.location
|
||||
# "Is this a cue?" must mean the same here as in `to_track_cues`, which
|
||||
# skips grid markers — a marker is projected as a beatgrid marker, not a
|
||||
# cue. Counting the raw CUE_V2 list instead made the library table report
|
||||
# every track as having one more cue than the deck showed, and made the
|
||||
# "has cues: no" filter match nothing, since a gridded track always had at
|
||||
# least one. The same class of bug as the Rekordbox hotcue miscount: one
|
||||
# question, two answers.
|
||||
markers = beatgrid.grid_markers(e)
|
||||
cues = [c for c in (e.cue_v2 or []) if getattr(c, "grid", None) is None]
|
||||
# The same "is this in the bank" test as `to_track_cues`' slot, so the
|
||||
# table's dots and the deck's pads cannot disagree.
|
||||
chips = sorted(
|
||||
(
|
||||
HotcueChip(
|
||||
slot=c.hotcue,
|
||||
type=NATIVE_TO_CUE_TYPE.get(c.type, "cue"),
|
||||
color=c.color or None,
|
||||
)
|
||||
for c in cues
|
||||
if c.hotcue is not None and c.hotcue >= 0
|
||||
),
|
||||
key=lambda chip: chip.slot,
|
||||
)
|
||||
wheel, mode = parse_key(info.key if info else None)
|
||||
return Track(
|
||||
id=primary_key(loc) if loc else (e.title or ""),
|
||||
artist=e.artist,
|
||||
title=e.title,
|
||||
album=e.album.title if e.album else None,
|
||||
genre=info.genre if info else None,
|
||||
label=info.label if info else None,
|
||||
remixer=info.remixer if info else None,
|
||||
producer=info.producer if info else None,
|
||||
mix=info.mix if info else None,
|
||||
comment=info.comment if info else None,
|
||||
# Traktor's "Comment 2" is stored in INFO@RATING (stars are RANKING).
|
||||
comment2=info.rating if info else None,
|
||||
bpm=beatgrid.effective_bpm(e),
|
||||
key=info.key if info else None,
|
||||
key_wheel=wheel,
|
||||
key_mode=mode,
|
||||
rating=_rating_stars(info.ranking if info else None),
|
||||
playcount=info.playcount if info else None,
|
||||
length=info.playtime if info else None,
|
||||
bitrate=info.bitrate if info else None,
|
||||
import_date=iso_date(info.import_date if info else None),
|
||||
last_played=iso_date(info.last_played if info else None),
|
||||
release_date=iso_date(info.release_date if info else None),
|
||||
filepath=_display_path(loc) if loc else None,
|
||||
cue_count=len(cues),
|
||||
hotcue_count=len(chips),
|
||||
hotcues=chips,
|
||||
grid_marker_count=len(markers),
|
||||
grid_locked=bool(e.lock),
|
||||
media_kind="stem" if getattr(e, "stems", None) is not None else "audio",
|
||||
)
|
||||
|
||||
|
||||
def to_track_cues(entry, offset_ms: float = 0.0) -> TrackCues:
|
||||
"""Project an ENTRY's beatgrid + cues.
|
||||
|
||||
`offset_ms` is how far the entry's positions sit behind the decoded audio
|
||||
(`TraktorStore.time_offset_ms`, see `timebase`); positions come out in the
|
||||
decoded time base, unclamped.
|
||||
|
||||
The beatgrid is the FULL ordered marker list — a constant grid is a list of
|
||||
length one. Grid markers themselves are not cues; their companion cues are,
|
||||
because they occupy real hotcue slots. Each is tagged with the marker it sits
|
||||
on, but is an ordinary, editable hotcue: Traktor 4 keeps a beatgrid without
|
||||
one, so nothing depends on it staying put.
|
||||
"""
|
||||
markers = beatgrid.grid_markers(entry)
|
||||
comps = beatgrid.companions(entry)
|
||||
marker_of = {id(c): i for i, c in comps.items()}
|
||||
grid_markers = [
|
||||
GridMarker(
|
||||
start=timebase.from_traktor_ms(m.start or 0.0, offset_ms), # START is ms
|
||||
bpm=m.grid.bpm if m.grid and m.grid.bpm else 0.0,
|
||||
name=m.name,
|
||||
companion=comps[i].hotcue if i in comps else None,
|
||||
)
|
||||
for i, m in enumerate(markers)
|
||||
]
|
||||
cues = []
|
||||
for c in entry.cue_v2 or []:
|
||||
if getattr(c, "grid", None) is not None:
|
||||
continue # a grid marker is projected as a beatgrid marker, not a cue
|
||||
marker = marker_of.get(id(c))
|
||||
slot = c.hotcue if c.hotcue is not None and c.hotcue >= 0 else None
|
||||
cues.append(
|
||||
CuePoint(
|
||||
name=c.name,
|
||||
# An unknown TYPE is projected as a plain cue rather than dropped:
|
||||
# preserving a cue we cannot name beats hiding it from the user.
|
||||
type=NATIVE_TO_CUE_TYPE.get(c.type, "cue"),
|
||||
# Every Traktor cue lives in the hotcue bank.
|
||||
role="hotcue",
|
||||
start=timebase.from_traktor_ms(c.start or 0.0, offset_ms),
|
||||
length=(c.len or 0.0) / 1000.0,
|
||||
slot=slot,
|
||||
color=c.color,
|
||||
editable=True,
|
||||
readonly_reason=None,
|
||||
grid_marker=marker,
|
||||
)
|
||||
)
|
||||
return TrackCues(
|
||||
grid_markers=grid_markers, grid_locked=bool(entry.lock), cues=cues
|
||||
)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,74 @@
|
||||
"""Traktor's clock vs the decoded audio's — one rule, used at every boundary.
|
||||
|
||||
**On an MP3 with a gapless header, Traktor's time 0 is NOT the decoded audio's
|
||||
time 0.** Traktor decodes MP3 naively: it ignores the LAME gapless fields and
|
||||
decodes the Xing/Info header frame as if it were audio. A gapless decoder skips
|
||||
that frame and trims the encoder's start padding. So every position Traktor
|
||||
stores — grid markers, cues, loops — sits
|
||||
|
||||
samples_per_frame + encoder_delay + 529 (= 2257 for LAME's usual 576)
|
||||
|
||||
samples LATER than the same moment in the decoded audio: ~51.2 ms at 44.1 kHz,
|
||||
~47.0 ms at 48 kHz. The rule is in SAMPLES. An MP3 WITHOUT a header is decoded
|
||||
the same way by both sides (nothing to skip, nothing to trim), so its offset is
|
||||
0 — as is every other format: WAV, AIFF, FLAC and AAC (Traktor honours the MP4
|
||||
edit list) line up to the sample.
|
||||
|
||||
Measured 2026-09-30 in Traktor 4.5 ("kit 4", see the stem-conversion discussion
|
||||
log): hotcues Konduktor wrote on a synthetic kick, blinded, landed on it only
|
||||
at this offset, and hotcues placed by hand in Traktor read back at it (+2255 at
|
||||
44.1 kHz, +2242 at 48 kHz, header-less −6, WAV −4, AAC −13). Traktor's AutoGrid
|
||||
agrees, and `bench_grid_detect.py` shows it on every Traktor-analysed MP3.
|
||||
Derived, not measured: a header frame whose delay field a gapless decoder does
|
||||
not trust (no LAME/Lavf/Lavc tag, or a VBRI tag) — the decoder then skips the
|
||||
frame but trims nothing, so the offset is one frame.
|
||||
|
||||
The generic model is in the DECODED time base — what Konduktor's deck plays and
|
||||
the grid detector measures. So the Traktor store ADDS the offset on every write
|
||||
and the projection SUBTRACTS it on every read. A read is NOT clamped at 0: a
|
||||
Traktor grid anchor can sit inside the header frame (a beat before the decoded
|
||||
audio starts), and clamping it would move the grid on its next write-back.
|
||||
Get it wrong and nothing fails: every MP3 cue and beat is simply ~51 ms early in
|
||||
Traktor, or late in Konduktor — which is what every release before this did.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from ...core import mp3_gapless
|
||||
|
||||
|
||||
def offset_samples(path: Path | str | None, suffix: str | None = None) -> tuple[int, int]:
|
||||
"""(samples Traktor runs behind the decoded audio, sample rate).
|
||||
|
||||
(0, 0) for anything that is not an MP3 with a header frame — including a
|
||||
file that cannot be read: with no header to go by, 0 is the answer that
|
||||
cannot move a cue, since a position read at 0 is written back at 0.
|
||||
|
||||
`suffix` overrides the format the name implies — for a file whose bytes are
|
||||
a track's but whose name is not, like a converted track's original parked
|
||||
as `.<name>.konduktor-parked` until Save.
|
||||
"""
|
||||
if not path or (suffix or Path(path).suffix).lower() != ".mp3":
|
||||
return 0, 0
|
||||
start = mp3_gapless.read(path)
|
||||
if start is None or not start.header_frame:
|
||||
return 0, 0
|
||||
return start.samples_per_frame + start.trimmed, start.sample_rate
|
||||
|
||||
|
||||
def offset_ms(path: Path | str | None, suffix: str | None = None) -> float:
|
||||
"""Milliseconds to ADD to a decoded-audio time to get Traktor's."""
|
||||
samples, rate = offset_samples(path, suffix)
|
||||
return samples * 1000.0 / rate if samples else 0.0
|
||||
|
||||
|
||||
def to_traktor_ms(seconds: float, off_ms: float) -> float:
|
||||
"""A decoded-audio time in seconds -> a Traktor START in ms (never < 0:
|
||||
Traktor cannot store a position before its own time 0)."""
|
||||
return max(0.0, seconds * 1000.0 + off_ms)
|
||||
|
||||
|
||||
def from_traktor_ms(start_ms: float, off_ms: float) -> float:
|
||||
"""A Traktor START in ms -> decoded-audio seconds. Deliberately unclamped."""
|
||||
return (start_ms - off_ms) / 1000.0
|
||||
@@ -0,0 +1,223 @@
|
||||
"""The loaded library, and the version-history bookkeeping around saving it.
|
||||
|
||||
Exactly one library is open **for editing** at a time: that keeps every edit and
|
||||
every save unambiguous about what it targets, and it is why the adapter can own
|
||||
its own projection without anyone asking which library a command meant.
|
||||
|
||||
A **source** may be open alongside it, and only alongside it. A source is a
|
||||
library being read FROM — a plugged-in OneLibrary stick whose tracks are about to
|
||||
be imported — and it is deliberately not symmetrical with the loaded library:
|
||||
|
||||
* it is **never written**, so no command can be ambiguous about its target;
|
||||
* it is **never saved**, so version history has nothing to disambiguate;
|
||||
* it is **never the fallback** when nothing is loaded — a source with no
|
||||
destination is a browser, not a library, and the routes say so.
|
||||
|
||||
That asymmetry is what keeps "exactly one library is open" true in the sense that
|
||||
mattered: there is still exactly one thing a command can mean.
|
||||
|
||||
Version history lives here rather than in the adapter. An adapter's job is to
|
||||
write its own format faithfully; knowing that Konduktor keeps a git-backed
|
||||
history of each library is app-level knowledge, and an adapter reaching up for it
|
||||
would invert the dependency. So the adapter returns the bytes it wrote and a
|
||||
human summary, and this module versions them.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from . import __version__, adapters, history, library_id, prefs # noqa: F401 — registers adapters
|
||||
from .core import registry
|
||||
from .core.adapter import LibraryAdapter
|
||||
from .core.pathmap import PathMapping
|
||||
from .relocation import RelocationCheck
|
||||
|
||||
|
||||
class AppState:
|
||||
"""Holds the currently-loaded library (selectable at runtime)."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.path: Path | None = None
|
||||
self.adapter: LibraryAdapter | None = None
|
||||
# This library's stable identity, which survives it being moved. What
|
||||
# export sets are keyed by; see `library_id.py` for why a path is not
|
||||
# good enough for curated user work.
|
||||
self.library_id: str | None = None
|
||||
# The library being read FROM, if any. Read-only by contract; see the
|
||||
# module docstring for why it is not symmetrical with `adapter`.
|
||||
self.source_path: Path | None = None
|
||||
self.source: LibraryAdapter | None = None
|
||||
# This open's missing-files check (see `relocation.py`). A new one per
|
||||
# open, which is what makes the dialog ask again on a reopen.
|
||||
self.relocation: RelocationCheck | None = None
|
||||
# Serialises the operations that REPLACE or COMMIT the whole library —
|
||||
# open, save, discard (and a stem batch's swap step). A save landing in
|
||||
# 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:
|
||||
return self.adapter is not None
|
||||
|
||||
@property
|
||||
def source_loaded(self) -> bool:
|
||||
return self.source is not None
|
||||
|
||||
# ---- the source library ---------------------------------------------
|
||||
def open_source(self, path: Path) -> None:
|
||||
"""Open a library to read from, alongside the loaded one.
|
||||
|
||||
Refuses a source that is not read-only. Nothing downstream sends it a
|
||||
command, but "this is only ever read" is the assumption the whole slot
|
||||
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)
|
||||
if adapter.capabilities().writable:
|
||||
if hasattr(adapter, "close"):
|
||||
try:
|
||||
adapter.close()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
raise ValueError(
|
||||
f"{path} is a writable library; only read-only sources "
|
||||
"(such as a OneLibrary drive) can be opened as a source"
|
||||
)
|
||||
self.close_source()
|
||||
self.source_path, self.source = path, adapter
|
||||
|
||||
def close_source(self) -> None:
|
||||
"""Release the source. Load-bearing: a source lives on a REMOVABLE drive,
|
||||
and a held file handle is what stops a stick ejecting."""
|
||||
previous, self.source = self.source, None
|
||||
self.source_path = None
|
||||
if previous is not None and hasattr(previous, "close"):
|
||||
try:
|
||||
previous.close()
|
||||
except Exception: # noqa: BLE001 — a failed close must not block
|
||||
pass
|
||||
|
||||
def open(self, path: Path) -> None:
|
||||
with self.mutation:
|
||||
self._open(path)
|
||||
|
||||
def _open(self, path: Path) -> None:
|
||||
# The registry picks the adapter by probing the file, not by extension —
|
||||
# a Rekordbox library is a .db and a Serato one is a directory. Raises on
|
||||
# an unrecognised or unparseable file; only commit once it has parsed.
|
||||
# One parse: the adapter builds its read projection from the same object
|
||||
# graph the commands mutate.
|
||||
adapter = registry.open_library(path)
|
||||
# Release the previous library first. A file-backed platform (Rekordbox
|
||||
# holds master.db open) would otherwise leak a handle — and a lingering
|
||||
# write-ahead log beside a file another process replaces is how a SQLite
|
||||
# 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()
|
||||
except Exception: # noqa: BLE001 — a failed close must not block the open
|
||||
pass
|
||||
# Apply this library's saved OS-path remapping (per-machine, keyed by the
|
||||
# library's local path) so runtime translation is live on open.
|
||||
saved = prefs.get_path_mapping(str(path))
|
||||
if saved:
|
||||
adapter.set_path_mapping(PathMapping.make(saved["from"], saved["to"]))
|
||||
self.path, self.adapter = path, 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
|
||||
# get a path-derived id instead, which `is_durable()` reports honestly.
|
||||
driver = next(
|
||||
(d for d in registry.drivers() if d.platform == caps.platform), None
|
||||
)
|
||||
self.library_id = library_id.for_path(
|
||||
path,
|
||||
platform=caps.platform,
|
||||
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)
|
||||
|
||||
def save(self):
|
||||
"""Write the library, then record the saved bytes in version history.
|
||||
|
||||
Returns ``(outcome, commit_sha | None)``. Every path that saves must come
|
||||
through here — a save that skips it leaves a gap in the history the user
|
||||
cannot restore from.
|
||||
"""
|
||||
assert self.adapter is not None and self.path is not None
|
||||
with self.mutation:
|
||||
return self._save()
|
||||
|
||||
def _save(self):
|
||||
outcome = self.adapter.save()
|
||||
# Not every platform is versioned. A library that is more than one file
|
||||
# has no single blob that IS the library, and it says so through its
|
||||
# capabilities rather than this module knowing which platforms those are.
|
||||
versioned = self.adapter.capabilities().save.history
|
||||
commit = None
|
||||
if versioned and outcome.snapshot is not None:
|
||||
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:
|
||||
"""Drop every unsaved edit: the library re-reads itself from disk.
|
||||
|
||||
Through the adapter's own `reload`, NOT `open` — reopening would start a
|
||||
new missing-files check and forget this session's relocation answers,
|
||||
which are not edits and survive a reload (the store keeps them).
|
||||
"""
|
||||
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()
|
||||
|
||||
|
||||
STATE = AppState()
|
||||
|
||||
# Optional auto-load for dev/tests.
|
||||
_env_nml = os.environ.get("KONDUKTOR_NML")
|
||||
if _env_nml and Path(_env_nml).exists():
|
||||
try:
|
||||
STATE.open(Path(_env_nml))
|
||||
except Exception: # noqa: BLE001 — bad env path shouldn't crash startup
|
||||
pass
|
||||
@@ -1,201 +0,0 @@
|
||||
"""Auto Hotcues — structural boundary detection for DJ cue placement.
|
||||
|
||||
Detection uses the McFee & Ellis (2014) Laplacian structural segmentation as
|
||||
implemented on top of librosa: beat-synchronous CQT features → a
|
||||
sequence-augmented recurrence Laplacian → spectral clustering of beats into
|
||||
section *types* → boundaries at type changes. This is repetition/homogeneity
|
||||
aware (unlike a raw energy-novelty curve), so boundaries land on real musical
|
||||
transitions. Validated on real house tracks: clean, phrase-scale boundaries in
|
||||
~1.5s each; pure-Python (~150MB), no torch/native build; runs on Python 3.14.
|
||||
|
||||
The module is split so the DSP (`detect_boundaries`, needs the audio) is
|
||||
separate from the placement logic (`select_hotcues`, pure arithmetic on the
|
||||
beatgrid) — the latter is unit-testable without audio.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
|
||||
# Traktor's hotcue bank. Parameterised (not hardcoded at call sites) so it can
|
||||
# grow if a future Traktor allows more than 8 triggerable hotcues.
|
||||
MAX_HOTCUES = 8
|
||||
|
||||
_SR = 22050
|
||||
_N_EIGENVECTORS = 6 # section-type clusters for the Laplacian embedding
|
||||
|
||||
|
||||
def detect_boundaries(audio_path: str, sr: int = _SR) -> tuple[list[tuple[float, float]], float]:
|
||||
"""Detect structural boundaries in a track.
|
||||
|
||||
Returns ``(boundaries, duration)`` where ``boundaries`` is a list of
|
||||
``(time_sec, energy)`` pairs — one per detected section start — and
|
||||
``energy`` is that section's mean RMS normalised to 0..1 across the track
|
||||
(used downstream for positional naming). Sorted by time.
|
||||
"""
|
||||
import librosa
|
||||
from scipy.ndimage import median_filter
|
||||
from scipy.sparse.csgraph import laplacian as csgraph_laplacian
|
||||
from scipy.linalg import eigh
|
||||
import sklearn.cluster
|
||||
|
||||
y, sr = librosa.load(audio_path, sr=sr, mono=True)
|
||||
duration = len(y) / sr
|
||||
if duration < 1.0:
|
||||
return [], duration
|
||||
|
||||
# Beat-synchronous CQT — the harmonic/timbre backbone of the method.
|
||||
cqt = librosa.amplitude_to_db(np.abs(librosa.cqt(y=y, sr=sr)), ref=np.max)
|
||||
_, beats = librosa.beat.beat_track(y=y, sr=sr, trim=False)
|
||||
if len(beats) < 4:
|
||||
return [], duration
|
||||
csync = librosa.util.sync(cqt, beats, aggregate=np.median)
|
||||
beat_times = librosa.frames_to_time(beats, sr=sr)
|
||||
|
||||
# Sequence-augmented recurrence Laplacian (McFee & Ellis 2014):
|
||||
# a repetition graph (which beats sound alike) blended with a local path
|
||||
# graph (consecutive-beat timbral continuity).
|
||||
rec = librosa.segment.recurrence_matrix(csync, width=3, mode="affinity", sym=True)
|
||||
rec = median_filter(rec, size=(1, 7))
|
||||
mfcc = librosa.feature.mfcc(y=y, sr=sr)
|
||||
msync = librosa.util.sync(mfcc, beats)
|
||||
path_dist = np.sum(np.diff(msync, axis=1) ** 2, axis=0)
|
||||
path_sim = np.exp(-path_dist / (np.median(path_dist) + 1e-9))
|
||||
path = np.diag(path_sim, 1) + np.diag(path_sim, -1)
|
||||
deg_path, deg_rec = path.sum(1), rec.sum(1)
|
||||
denom = np.sum((deg_path + deg_rec) ** 2) + 1e-9
|
||||
mu = deg_path.dot(deg_path + deg_rec) / denom
|
||||
graph = mu * rec + (1 - mu) * path
|
||||
|
||||
# Symmetric-normalised Laplacian → eigenvectors → k-means over beats.
|
||||
lap = csgraph_laplacian(graph, normed=True)
|
||||
_, evecs = eigh(lap)
|
||||
evecs = median_filter(evecs, size=(9, 1))
|
||||
k = min(_N_EIGENVECTORS, evecs.shape[1])
|
||||
x = librosa.util.normalize(evecs[:, :k], norm=2, axis=1)
|
||||
ids = sklearn.cluster.KMeans(n_clusters=k, n_init=10, random_state=0).fit_predict(x)
|
||||
|
||||
# Boundaries = beats where the section-type label changes (plus the start).
|
||||
bound_beats = [0] + [i for i in range(1, len(ids)) if ids[i] != ids[i - 1]]
|
||||
|
||||
# Per-section mean RMS (energy) for positional naming, normalised 0..1.
|
||||
rms = librosa.feature.rms(y=y)[0]
|
||||
rms_t = librosa.times_like(rms, sr=sr)
|
||||
rms_max = float(rms.max()) or 1.0
|
||||
out: list[tuple[float, float]] = []
|
||||
for j, bi in enumerate(bound_beats):
|
||||
t = float(beat_times[min(bi, len(beat_times) - 1)])
|
||||
t_next = (
|
||||
float(beat_times[min(bound_beats[j + 1], len(beat_times) - 1)])
|
||||
if j + 1 < len(bound_beats)
|
||||
else duration
|
||||
)
|
||||
seg = rms[(rms_t >= t) & (rms_t < max(t_next, t + 1e-3))]
|
||||
energy = float(seg.mean() / rms_max) if len(seg) else 0.0
|
||||
out.append((t, energy))
|
||||
return out, duration
|
||||
|
||||
|
||||
def detect_grid(audio_path: str, sr: int = _SR) -> tuple[float, float]:
|
||||
"""Detect a track's tempo and the time of its first beat.
|
||||
|
||||
Returns ``(bpm, first_beat_sec)`` for building a Traktor beatgrid (BPM +
|
||||
anchor). Uses librosa beat tracking. Half/double-tempo octave errors are
|
||||
left for the user to fix with the ×2 / ÷2 controls (per product decision).
|
||||
"""
|
||||
import librosa
|
||||
|
||||
y, sr = librosa.load(audio_path, sr=sr, mono=True)
|
||||
tempo, beats = librosa.beat.beat_track(y=y, sr=sr, trim=False)
|
||||
bpm = float(np.ravel(tempo)[0])
|
||||
if bpm <= 0 or len(beats) == 0:
|
||||
raise ValueError("Could not detect a tempo/beat")
|
||||
first_beat = float(librosa.frames_to_time(beats, sr=sr)[0])
|
||||
return bpm, first_beat
|
||||
|
||||
|
||||
def select_hotcues(
|
||||
boundaries: list[tuple[float, float]],
|
||||
*,
|
||||
bpm: float,
|
||||
anchor: float,
|
||||
duration: float,
|
||||
free_slots: list[int],
|
||||
existing_times: list[float],
|
||||
max_cues: int = MAX_HOTCUES,
|
||||
phrase_bars: int = 16,
|
||||
) -> list[dict]:
|
||||
"""Turn raw boundaries into hotcue specs, phrase-snapped to the beatgrid.
|
||||
|
||||
Snaps each boundary to the nearest ``phrase_bars``-bar grid point (which
|
||||
also merges near-duplicates), drops any coinciding with an existing hotcue,
|
||||
caps to the free slots (down-sampling evenly if there are too many), and
|
||||
assigns positional names. Returns dicts with slot/start/name/type/length.
|
||||
"""
|
||||
if not boundaries or not free_slots or bpm <= 0:
|
||||
return []
|
||||
|
||||
beat = 60.0 / bpm
|
||||
phrase = phrase_bars * 4 * beat # seconds per phrase
|
||||
|
||||
# Snap to phrase grid; dedupe (keep the strongest energy seen at each point).
|
||||
snapped: dict[float, float] = {}
|
||||
for t, energy in boundaries:
|
||||
p = anchor + round((t - anchor) / phrase) * phrase
|
||||
p = max(0.0, min(p, duration - beat))
|
||||
snapped[p] = max(snapped.get(p, 0.0), energy)
|
||||
|
||||
# Drop points that collide with an existing (hand-placed) hotcue.
|
||||
def near_existing(t: float) -> bool:
|
||||
return any(abs(t - e) < beat for e in existing_times)
|
||||
|
||||
points = sorted((t, e) for t, e in snapped.items() if not near_existing(t))
|
||||
if not points:
|
||||
return []
|
||||
|
||||
# If more candidates than free slots, down-sample evenly across the track
|
||||
# (keeps intro..outro coverage rather than just the first N).
|
||||
n = min(len(free_slots), max_cues)
|
||||
if len(points) > n:
|
||||
idx = np.linspace(0, len(points) - 1, n).round().astype(int)
|
||||
points = [points[i] for i in sorted(set(idx))]
|
||||
|
||||
names = _name_positionally([t for t, _ in points], [e for _, e in points], duration)
|
||||
slots = sorted(free_slots)[: len(points)]
|
||||
return [
|
||||
{"slot": slot, "start": round(t, 3), "name": name, "type": 0, "length": 0.0}
|
||||
for slot, (t, _), name in zip(slots, points, names)
|
||||
]
|
||||
|
||||
|
||||
def _name_positionally(times: list[float], energies: list[float], duration: float) -> list[str]:
|
||||
"""Positional-hint names from track position + energy trend (not true
|
||||
structural classification — the names are hints; value is the position)."""
|
||||
if not times:
|
||||
return []
|
||||
med = float(np.median(energies))
|
||||
raw: list[str] = []
|
||||
n = len(times)
|
||||
for i, (t, e) in enumerate(zip(times, energies)):
|
||||
frac = t / duration if duration else 0.0
|
||||
prev = energies[i - 1] if i > 0 else e
|
||||
if i == 0 or frac < 0.08:
|
||||
name = "Intro"
|
||||
elif i == n - 1 or frac > 0.85:
|
||||
name = "Outro"
|
||||
elif e - prev > 0.12 and e >= med:
|
||||
name = "Drop"
|
||||
elif prev - e > 0.12:
|
||||
name = "Break"
|
||||
elif e > prev:
|
||||
name = "Build"
|
||||
else:
|
||||
name = "Mid"
|
||||
raw.append(name)
|
||||
# De-duplicate repeated labels with ordinals (Drop, Drop 2, ...).
|
||||
counts: dict[str, int] = {}
|
||||
out: list[str] = []
|
||||
for name in raw:
|
||||
counts[name] = counts.get(name, 0) + 1
|
||||
out.append(name if counts[name] == 1 else f"{name} {counts[name]}")
|
||||
return out
|
||||
@@ -1,316 +0,0 @@
|
||||
"""Loads a Traktor collection and serves query-friendly views of it.
|
||||
|
||||
Phase 1 is read-only. The service parses the .nml once into memory, builds a
|
||||
flat list of Track objects, a primary-key index (so playlist entries can be
|
||||
joined to full track metadata), and the playlist tree.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from traktor_nml_utils import TraktorCollection
|
||||
|
||||
from .schemas import (
|
||||
Facets,
|
||||
GenreCount,
|
||||
PlaylistNode,
|
||||
Stats,
|
||||
Track,
|
||||
TrackPage,
|
||||
)
|
||||
|
||||
|
||||
def _primary_key(location) -> str:
|
||||
"""Reconstruct the Traktor primary key used by playlist entries."""
|
||||
vol = location.volume or ""
|
||||
d = location.dir or ""
|
||||
f = location.file or ""
|
||||
return f"{vol}{d}{f}"
|
||||
|
||||
|
||||
def _display_path(location) -> str:
|
||||
"""Human-readable OS-ish path from Traktor's '/:'-separated dir."""
|
||||
d = (location.dir or "").replace("/:", "/")
|
||||
f = location.file or ""
|
||||
return f"{d}{f}"
|
||||
|
||||
|
||||
def _rating_stars(ranking) -> int:
|
||||
if not ranking:
|
||||
return 0
|
||||
return max(0, min(5, round(ranking / 51)))
|
||||
|
||||
|
||||
class CollectionService:
|
||||
def __init__(self, nml_path: Path):
|
||||
self.nml_path = Path(nml_path)
|
||||
self._lock = threading.Lock()
|
||||
self.tracks: list[Track] = []
|
||||
self.by_key: dict[str, Track] = {}
|
||||
self.stem_keys: set[str] = set()
|
||||
self._playlist_entries: dict[str, list[str]] = {} # id -> ordered primary keys
|
||||
self._tree: list[PlaylistNode] = []
|
||||
self._playlist_count = 0
|
||||
self.load()
|
||||
|
||||
# ---- loading -------------------------------------------------------
|
||||
def load(self) -> None:
|
||||
with self._lock:
|
||||
collection = TraktorCollection(path=self.nml_path)
|
||||
self.tracks = [self._to_track(e) for e in collection.nml.collection.entry]
|
||||
self.by_key = {t.id: t for t in self.tracks}
|
||||
# Tracks with stems use PRIMARYKEY TYPE="STEM" in playlists (verified
|
||||
# 945/945 against the real collection); all others use "TRACK".
|
||||
self.stem_keys = {
|
||||
_primary_key(e.location)
|
||||
for e in collection.nml.collection.entry
|
||||
if e.location and getattr(e, "stems", None) is not None
|
||||
}
|
||||
self._playlist_entries = {}
|
||||
self._playlist_count = 0
|
||||
counter = {"n": 0}
|
||||
root = collection.nml.playlists.node if collection.nml.playlists else None
|
||||
self._tree = self._build_tree(root, counter) if root else []
|
||||
|
||||
def _to_track(self, e) -> Track:
|
||||
info = e.info
|
||||
loc = e.location
|
||||
cues = e.cue_v2 or []
|
||||
hotcues = sum(
|
||||
1 for c in cues if c.hotcue is not None and c.hotcue >= 0
|
||||
)
|
||||
has_grid = any(getattr(c, "grid", None) is not None for c in cues)
|
||||
return Track(
|
||||
id=_primary_key(loc) if loc else (e.title or ""),
|
||||
artist=e.artist,
|
||||
title=e.title,
|
||||
album=e.album.title if e.album else None,
|
||||
genre=info.genre if info else None,
|
||||
label=info.label if info else None,
|
||||
remixer=info.remixer if info else None,
|
||||
producer=info.producer if info else None,
|
||||
mix=info.mix if info else None,
|
||||
comment=info.comment if info else None,
|
||||
bpm=e.tempo.bpm if e.tempo else None,
|
||||
key=info.key if info else None,
|
||||
rating=_rating_stars(info.ranking if info else None),
|
||||
playcount=info.playcount if info else None,
|
||||
length=info.playtime if info else None,
|
||||
bitrate=info.bitrate if info else None,
|
||||
import_date=info.import_date if info else None,
|
||||
last_played=info.last_played if info else None,
|
||||
release_date=info.release_date if info else None,
|
||||
filepath=_display_path(loc) if loc else None,
|
||||
cue_count=len(cues),
|
||||
hotcue_count=hotcues,
|
||||
has_grid=has_grid,
|
||||
is_stem=getattr(e, "stems", None) is not None,
|
||||
)
|
||||
|
||||
def _build_tree(self, node, counter, is_root=True) -> list[PlaylistNode]:
|
||||
"""Return the children of the $ROOT folder as the top-level tree."""
|
||||
if node is None:
|
||||
return []
|
||||
# Root ($ROOT) is a wrapper folder; expose its children as top level.
|
||||
if is_root and node.subnodes:
|
||||
out = []
|
||||
for child in node.subnodes.node:
|
||||
out.append(self._node_to_model(child, counter))
|
||||
return out
|
||||
return [self._node_to_model(node, counter)]
|
||||
|
||||
def _node_to_model(self, node, counter) -> PlaylistNode:
|
||||
ntype = node.type or "FOLDER"
|
||||
if ntype == "PLAYLIST" or (node.playlist is not None):
|
||||
nid = f"pl-{counter['n']}"
|
||||
counter["n"] += 1
|
||||
self._playlist_count += 1
|
||||
keys = []
|
||||
if node.playlist and node.playlist.entry:
|
||||
for en in node.playlist.entry:
|
||||
if en.primarykey and en.primarykey.key:
|
||||
keys.append(en.primarykey.key)
|
||||
self._playlist_entries[nid] = keys
|
||||
return PlaylistNode(
|
||||
id=nid,
|
||||
name=node.name or "(unnamed)",
|
||||
type="PLAYLIST",
|
||||
uuid=node.playlist.uuid if node.playlist else None,
|
||||
count=len(keys),
|
||||
)
|
||||
if ntype == "SMARTLIST" or getattr(node, "smartlist", None) is not None:
|
||||
# Smart playlists are dynamic (rule-based); no static entry list.
|
||||
nid = f"sl-{counter['n']}"
|
||||
counter["n"] += 1
|
||||
return PlaylistNode(id=nid, name=node.name or "(smart)", type="SMARTLIST")
|
||||
# FOLDER
|
||||
nid = f"fld-{counter['n']}"
|
||||
counter["n"] += 1
|
||||
children = []
|
||||
if node.subnodes:
|
||||
for child in node.subnodes.node:
|
||||
children.append(self._node_to_model(child, counter))
|
||||
return PlaylistNode(
|
||||
id=nid, name=node.name or "(folder)", type="FOLDER", children=children
|
||||
)
|
||||
|
||||
# ---- queries -------------------------------------------------------
|
||||
_SORT_KEYS = {
|
||||
"artist": lambda t: (t.artist or "").lower(),
|
||||
"title": lambda t: (t.title or "").lower(),
|
||||
"album": lambda t: (t.album or "").lower(),
|
||||
"genre": lambda t: (t.genre or "").lower(),
|
||||
"key": lambda t: (t.key or ""),
|
||||
"bpm": lambda t: (t.bpm if t.bpm is not None else -1),
|
||||
"rating": lambda t: t.rating,
|
||||
"playcount": lambda t: (t.playcount or 0),
|
||||
"import_date": lambda t: (t.import_date or ""),
|
||||
"length": lambda t: (t.length or 0),
|
||||
}
|
||||
|
||||
def query_tracks(
|
||||
self,
|
||||
q: str | None = None,
|
||||
genre: str | None = None,
|
||||
key: str | None = None,
|
||||
bpm_min: float | None = None,
|
||||
bpm_max: float | None = None,
|
||||
rating_min: int | None = None,
|
||||
has_cues: bool | None = None,
|
||||
sort: str = "artist",
|
||||
order: str = "asc",
|
||||
limit: int = 100,
|
||||
offset: int = 0,
|
||||
) -> TrackPage:
|
||||
items = self.tracks
|
||||
if q:
|
||||
ql = q.lower()
|
||||
items = [
|
||||
t
|
||||
for t in items
|
||||
if (t.artist and ql in t.artist.lower())
|
||||
or (t.title and ql in t.title.lower())
|
||||
or (t.album and ql in t.album.lower())
|
||||
]
|
||||
if genre:
|
||||
items = [t for t in items if t.genre == genre]
|
||||
if key:
|
||||
items = [t for t in items if t.key == key]
|
||||
if bpm_min is not None:
|
||||
items = [t for t in items if t.bpm is not None and t.bpm >= bpm_min]
|
||||
if bpm_max is not None:
|
||||
items = [t for t in items if t.bpm is not None and t.bpm <= bpm_max]
|
||||
if rating_min is not None:
|
||||
items = [t for t in items if t.rating >= rating_min]
|
||||
if has_cues is not None:
|
||||
items = [t for t in items if (t.cue_count > 0) == has_cues]
|
||||
|
||||
keyfn = self._SORT_KEYS.get(sort, self._SORT_KEYS["artist"])
|
||||
items = sorted(items, key=keyfn, reverse=(order == "desc"))
|
||||
|
||||
total = len(items)
|
||||
page = items[offset : offset + limit]
|
||||
return TrackPage(total=total, offset=offset, limit=limit, items=page)
|
||||
|
||||
def facets(self) -> Facets:
|
||||
genres: dict[str, int] = {}
|
||||
keys: dict[str, int] = {}
|
||||
bpms = []
|
||||
for t in self.tracks:
|
||||
if t.genre:
|
||||
genres[t.genre] = genres.get(t.genre, 0) + 1
|
||||
if t.key:
|
||||
keys[t.key] = keys.get(t.key, 0) + 1
|
||||
if t.bpm is not None:
|
||||
bpms.append(t.bpm)
|
||||
return Facets(
|
||||
genres=[
|
||||
GenreCount(name=k, count=v)
|
||||
for k, v in sorted(genres.items(), key=lambda x: -x[1])
|
||||
],
|
||||
keys=[
|
||||
GenreCount(name=k, count=v)
|
||||
for k, v in sorted(keys.items(), key=lambda x: -x[1])
|
||||
],
|
||||
bpm_min=min(bpms) if bpms else None,
|
||||
bpm_max=max(bpms) if bpms else None,
|
||||
total_tracks=len(self.tracks),
|
||||
)
|
||||
|
||||
def replace_track(self, track_id: str, entry) -> None:
|
||||
"""Refresh the read projection for one track from its (edited) model
|
||||
entry, mutating the existing Track object in place so both `tracks` and
|
||||
`by_key` reflect it. Bridges the store (edit model) and this read model
|
||||
until they're consolidated."""
|
||||
old = self.by_key.get(track_id)
|
||||
if old is None:
|
||||
return
|
||||
new = self._to_track(entry)
|
||||
for field in type(new).model_fields:
|
||||
setattr(old, field, getattr(new, field))
|
||||
|
||||
def entries_for(self, track_ids: list[str]) -> list[tuple[str, str]]:
|
||||
"""Map track ids to (key, PRIMARYKEY-type) pairs for playlist writing.
|
||||
Unknown ids are skipped (can't reference a track not in the collection)."""
|
||||
out = []
|
||||
for tid in track_ids:
|
||||
if tid in self.by_key:
|
||||
out.append((tid, "STEM" if tid in self.stem_keys else "TRACK"))
|
||||
return out
|
||||
|
||||
def stats(self, playlist_count: int | None = None) -> Stats:
|
||||
rating_breakdown = {i: 0 for i in range(6)}
|
||||
genres: dict[str, int] = {}
|
||||
bpm_buckets: dict[str, int] = {}
|
||||
rated = missing_key = missing_genre = missing_bpm = no_cues = 0
|
||||
for t in self.tracks:
|
||||
rating_breakdown[t.rating] += 1
|
||||
if t.rating > 0:
|
||||
rated += 1
|
||||
if not t.key:
|
||||
missing_key += 1
|
||||
if not t.genre:
|
||||
missing_genre += 1
|
||||
else:
|
||||
genres[t.genre] = genres.get(t.genre, 0) + 1
|
||||
if t.bpm is None:
|
||||
missing_bpm += 1
|
||||
else:
|
||||
lo = int(t.bpm // 10 * 10)
|
||||
bucket = f"{lo}-{lo + 10}"
|
||||
bpm_buckets[bucket] = bpm_buckets.get(bucket, 0) + 1
|
||||
if t.cue_count == 0:
|
||||
no_cues += 1
|
||||
total = len(self.tracks)
|
||||
histogram = [
|
||||
{"bucket": b, "count": c}
|
||||
for b, c in sorted(bpm_buckets.items(), key=lambda x: int(x[0].split("-")[0]))
|
||||
]
|
||||
top = sorted(genres.items(), key=lambda x: -x[1])[:10]
|
||||
return Stats(
|
||||
total_tracks=total,
|
||||
total_playlists=self._playlist_count if playlist_count is None else playlist_count,
|
||||
rated=rated,
|
||||
unrated=total - rated,
|
||||
missing_key=missing_key,
|
||||
missing_genre=missing_genre,
|
||||
missing_bpm=missing_bpm,
|
||||
no_cues=no_cues,
|
||||
rating_breakdown=rating_breakdown,
|
||||
bpm_histogram=histogram,
|
||||
top_genres=[GenreCount(name=k, count=v) for k, v in top],
|
||||
)
|
||||
|
||||
def playlist_tree(self) -> list[PlaylistNode]:
|
||||
return self._tree
|
||||
|
||||
def playlist_tracks(self, playlist_id: str) -> list[Track] | None:
|
||||
if playlist_id not in self._playlist_entries:
|
||||
return None
|
||||
out = []
|
||||
for k in self._playlist_entries[playlist_id]:
|
||||
t = self.by_key.get(k)
|
||||
if t is not None:
|
||||
out.append(t)
|
||||
return out
|
||||
@@ -0,0 +1,7 @@
|
||||
"""Platform-independent core: the generic model, the query/projection layer and
|
||||
the format-agnostic helpers.
|
||||
|
||||
Nothing in here may import ``traktor_nml_utils`` or ``konduktor.adapters`` —
|
||||
``test_layering.py`` enforces that. This package is what a Rekordbox or Serato
|
||||
adapter will be written against.
|
||||
"""
|
||||
@@ -0,0 +1,284 @@
|
||||
"""The adapter contract: what the app needs from a DJ library, generically.
|
||||
|
||||
Konduktor's save model is **projection + command replay**. The generic model is
|
||||
a READ PROJECTION; edits are commands an adapter replays onto its RETAINED
|
||||
NATIVE MODEL, which stays the write target. The generic model is never
|
||||
serialized back over a library — that is what preserves byte-exact saves, and
|
||||
it is also the only model that works for formats you cannot regenerate at all
|
||||
(a Rekordbox SQLite row, a Serato tag inside an audio file).
|
||||
|
||||
Two rules keep this honest:
|
||||
|
||||
* **No native type appears in any signature here.** If a concept cannot be
|
||||
expressed generically it does not belong on the protocol.
|
||||
* **Every mutating command returns its refreshed projection.** That makes the
|
||||
refresh an adapter-internal invariant rather than something each route has
|
||||
to remember; a forgotten refresh is a silently stale UI that no byte-level
|
||||
test would catch.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Protocol, runtime_checkable
|
||||
|
||||
from .capabilities import Capabilities
|
||||
from .model import Facets, PlaylistNode, Stats, Track, TrackCues, TrackPage
|
||||
from .pathmap import PathMapping
|
||||
from .relocate import PathGroup
|
||||
|
||||
|
||||
@dataclass
|
||||
class SaveOutcome:
|
||||
"""What a save produced, in terms every platform can answer.
|
||||
|
||||
Promoted here once a second adapter needed it (the two-platform rule). The
|
||||
fields are deliberately optional because platforms differ in kind, not just
|
||||
in detail:
|
||||
|
||||
* `snapshot` is the exact bytes written, for the version-history commit —
|
||||
and it is None on a platform Konduktor does not version. A Rekordbox
|
||||
library is `master.db` plus ~200 analysis files plus a playlist XML, so
|
||||
there is no single blob that *is* the library, and restoring the database
|
||||
alone would roll back the app's own auth and sampler state.
|
||||
* `tag_results` reports embedded audio-file tag writes, which only a
|
||||
platform that does them will populate.
|
||||
"""
|
||||
|
||||
summary: str # human-readable edit summary, for the version-history message
|
||||
snapshot: bytes | None = None
|
||||
tag_results: list = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class NewTrack:
|
||||
"""A track to ADD to a library, described generically.
|
||||
|
||||
Import is the first operation that puts a track into a library that never
|
||||
had one, so it needs a way to say "here is a track" without naming a
|
||||
platform. That is all this is: the generic projection of a track, plus the
|
||||
audio file it should point at.
|
||||
|
||||
* `track` carries the metadata. **Its `id` is ignored** — an id belongs to
|
||||
the library that holds the track, and this one comes from somewhere
|
||||
else. The receiving adapter assigns its own and returns it.
|
||||
* `cues` is optional because a track can be imported without prep, and
|
||||
because a platform may hold the track but not (yet) its cues.
|
||||
* `audio_path` is a path on THIS machine that must already exist. Copying
|
||||
the audio is the caller's job, deliberately: an adapter's business is
|
||||
the library, and a file copy that failed halfway is not something a
|
||||
library write should be discovering.
|
||||
"""
|
||||
|
||||
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)
|
||||
class StemSwap:
|
||||
"""Put a converted stem file into the library in place of — or beside — a track.
|
||||
|
||||
The conversion itself (separation, encoding, file moves) is not the
|
||||
adapter's business; this is only the library side, and it arrives once the
|
||||
file is finished and verified.
|
||||
|
||||
* `mode` "repoint": the track's entry now names the stem file and keeps
|
||||
its playlists, prep and history — its id changes with its location.
|
||||
"add": a NEW entry for the stem file, copying the track's prep and
|
||||
metadata; the original entry stays.
|
||||
* `original_audio` is where the original's audio bytes are RIGHT NOW. In
|
||||
Replace mode that is its parked name, not its old one — a platform whose
|
||||
clock depends on the file (an MP3's header) must read it there, and
|
||||
must not look at the old path, which no longer holds it.
|
||||
* `bit_rate` (bps per stream), `duration` (seconds) and `size` (bytes)
|
||||
describe the stem file, for the library's own fields.
|
||||
"""
|
||||
|
||||
track_id: str
|
||||
stem_path: Path
|
||||
mode: str # "repoint" | "add"
|
||||
original_audio: Path | None
|
||||
bit_rate: int
|
||||
duration: float
|
||||
size: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class StemSwapResult:
|
||||
#: Old track id -> the id of the entry that now names the stem file.
|
||||
renamed: dict[str, str] = field(default_factory=dict)
|
||||
#: New id -> hotcue slots whose position fell before the stem file's start
|
||||
#: and were moved to 0 (a platform time-base shift can push one there).
|
||||
clamped: dict[str, list[int]] = field(default_factory=dict)
|
||||
|
||||
|
||||
class AdapterError(Exception):
|
||||
"""Base for every failure an adapter reports to the HTTP layer."""
|
||||
|
||||
|
||||
class LibraryNotSupported(AdapterError):
|
||||
"""No driver can open this path, or it failed to parse."""
|
||||
|
||||
|
||||
class NotFound(AdapterError):
|
||||
"""Unknown track, playlist or marker index."""
|
||||
|
||||
|
||||
class InvalidCommand(AdapterError):
|
||||
"""Well-formed request the library cannot accept (bad slot, BPM <= 0, ...)."""
|
||||
|
||||
|
||||
class Unsupported(AdapterError):
|
||||
"""The platform cannot represent this edit at all."""
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class LibraryAdapter(Protocol):
|
||||
"""One open library. Stateful; exactly one is loaded at a time."""
|
||||
|
||||
platform: str
|
||||
path: Path
|
||||
|
||||
# ---- identity -------------------------------------------------------
|
||||
def capabilities(self) -> Capabilities: ...
|
||||
def reload(self) -> None: ...
|
||||
|
||||
# ---- read projection -------------------------------------------------
|
||||
@property
|
||||
def tracks(self) -> list[Track]: ...
|
||||
def track(self, track_id: str) -> Track | None: ...
|
||||
def query_tracks(self, **kw) -> TrackPage: ...
|
||||
def facets(self) -> Facets: ...
|
||||
def stats(self, playlist_count: int) -> Stats: ...
|
||||
def playlist_tree(self) -> list[PlaylistNode]: ...
|
||||
def playlist_entries(self, node_id: str) -> list[str] | None: ...
|
||||
def playlist_tracks(self, node_id: str) -> list[Track] | None: ...
|
||||
def track_cues(self, track_id: str) -> TrackCues | None: ...
|
||||
|
||||
# ---- commands: playlists --------------------------------------------
|
||||
def create_playlist(self, name: str, parent_id: str | None = None) -> str: ...
|
||||
# Folders are a separate verb rather than a flag on create_playlist: a
|
||||
# platform can support one and not the other, and `capabilities.playlists
|
||||
# .folders` is what the UI gates on.
|
||||
def create_folder(self, name: str, parent_id: str | None = None) -> str: ...
|
||||
def rename_playlist(self, node_id: str, name: str) -> None: ...
|
||||
def delete_playlist(self, node_id: str) -> None: ...
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: ...
|
||||
|
||||
# ---- commands: adding tracks ----------------------------------------
|
||||
# The ONLY command that creates a track rather than editing one, and the
|
||||
# one place the "retained native model" rule is stretched: everywhere else
|
||||
# the write target was parsed from a real file, which is what makes the
|
||||
# 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]: ...
|
||||
|
||||
# Remove tracks from the library — and so from every playlist, since an
|
||||
# entry naming a track the library no longer has is a dangling reference.
|
||||
# Never touches audio files. Returns how many were removed; gated on
|
||||
# `capabilities().tracks.removable`.
|
||||
def remove_tracks(self, track_ids: list[str]) -> int: ...
|
||||
|
||||
# Swap converted stem files into the library (see `StemSwap`), all at once:
|
||||
# every swap is validated before any is applied, so a clash leaves the
|
||||
# library untouched. Gated on `capabilities().tracks.stem_convertible`.
|
||||
# `add_to_playlist` receives the entries "add" mode creates, in order.
|
||||
def apply_stem_swaps(self, swaps: list["StemSwap"], *,
|
||||
add_to_playlist: str | None = None) -> "StemSwapResult": ...
|
||||
|
||||
# ---- commands: track metadata / art ---------------------------------
|
||||
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None: ...
|
||||
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None: ...
|
||||
def cover_art(self, track_id: str) -> tuple[bytes, str] | None: ...
|
||||
|
||||
# ---- commands: cues --------------------------------------------------
|
||||
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: ...
|
||||
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: ...
|
||||
|
||||
# ---- commands: beatgrid ---------------------------------------------
|
||||
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> TrackCues: ...
|
||||
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> TrackCues: ...
|
||||
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> TrackCues: ...
|
||||
def delete_grid_marker(self, track_id: str, index: int) -> TrackCues: ...
|
||||
def replace_grid(self, track_id: str, markers: list[tuple[float, float]]) -> TrackCues: ...
|
||||
def set_analysed_grid(self, track_id: str, markers: list[tuple[float, float]]) -> TrackCues: ...
|
||||
def delete_grid(self, track_id: str) -> TrackCues: ...
|
||||
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues: ...
|
||||
|
||||
# ---- audio / paths ---------------------------------------------------
|
||||
def audio_path(self, track_id: str) -> Path | None: ...
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None: ...
|
||||
# The open-time missing-files check (`core/relocate.py`): the stored volumes
|
||||
# in which NO track resolves, and the mappings the user confirmed for them —
|
||||
# session-only, applied beneath the saved mapping. An adapter that does not
|
||||
# take part returns no groups, so its library is never checked.
|
||||
def unresolved_path_groups(self) -> list[PathGroup]: ...
|
||||
def set_session_mappings(self, mappings: list[PathMapping]) -> None: ...
|
||||
def path_prefix_suggestions(self) -> dict: ...
|
||||
def remap_preview(self, mapping: PathMapping) -> dict: ...
|
||||
# {old track id: new track id}; ids may change because a Traktor id IS its path.
|
||||
def remap_locations(self, mapping: PathMapping) -> dict[str, str]: ...
|
||||
|
||||
# ---- save -------------------------------------------------------------
|
||||
@property
|
||||
def dirty(self) -> bool: ...
|
||||
def save(self): ...
|
||||
def snapshot(self) -> bytes: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class LibraryDriver(Protocol):
|
||||
"""Opens libraries of one platform. Stateless; one instance per platform."""
|
||||
|
||||
platform: str
|
||||
display_name: str
|
||||
suffixes: tuple[str, ...]
|
||||
# True when this platform's libraries live on plugged-in media rather than at
|
||||
# a fixed path — so `detect()` genuinely changes between calls, and the app
|
||||
# can offer them as import SOURCES. Optional, and False for a platform that
|
||||
# does not set it, because most keep one library in a known place.
|
||||
removable: bool
|
||||
# Whether a user picks a FILE or a DIRECTORY for this platform. Both exist:
|
||||
# Traktor's library is `collection.nml`, OneLibrary's is the drive, and
|
||||
# Serato's will be a `_Serato_` folder. The file browser and the open route
|
||||
# both read this rather than assuming everything is a file. Defaults to
|
||||
# "file" for a driver that does not set it.
|
||||
selects: str
|
||||
|
||||
def can_open(self, path: Path) -> bool: ...
|
||||
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
|
||||
# library that is a drive. Omitted means "the path's own name".
|
||||
def display_name_for(self, path: Path) -> str: ...
|
||||
def detect(self) -> list: ...
|
||||
def describe(self, path: Path) -> object: ...
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Waveform analysis kept on the export's own drive, so a re-export decodes only
|
||||
what changed.
|
||||
|
||||
Decoding is the slow part of a Pioneer export (~1.5 s a track, where copying a
|
||||
track to a stick is well under a second), so skipping unchanged copies alone
|
||||
would leave most of a re-export's time in place. What is cached is the
|
||||
MEASUREMENT (`waveform.Analysis`), not any platform's tags: every Pioneer target
|
||||
turns the same measurement into its own files, and the Rekordbox Library target
|
||||
names its analysis folders after a fresh UUID each time, so reusing old ANLZ
|
||||
files by path could never have worked there.
|
||||
|
||||
## Where, and keyed by what
|
||||
|
||||
It lives on the destination (`.konduktor-cache/`), beside the manifest, for the
|
||||
manifest's reason: it describes that drive, and should travel, be cloned or be
|
||||
wiped with it. An entry is keyed by the SOURCE file's path, size and mtime —
|
||||
the same facts the runner uses to decide a copy is unchanged — so an edited
|
||||
track is re-measured exactly when it is re-copied, and the same stick plugged
|
||||
into another computer (other source paths) simply misses and re-decodes.
|
||||
|
||||
`waveform.ANALYSIS_VERSION` is part of every key: change what `analyse()`
|
||||
measures without bumping it and every re-export serves the old measurement.
|
||||
|
||||
Best-effort in both directions: an unreadable entry is a miss, and a failed
|
||||
store is logged, never fatal — the cache can cost time, never an export.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
from . import waveform
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
#: The folder, relative to the export's destination.
|
||||
CACHE_DIR = ".konduktor-cache"
|
||||
|
||||
|
||||
def fingerprint(source: Path | str, size: int, mtime_ns: int) -> str:
|
||||
"""The identity of one version of one source file."""
|
||||
text = f"{waveform.ANALYSIS_VERSION}|{source}|{size}|{mtime_ns}"
|
||||
return hashlib.sha1(text.encode("utf-8")).hexdigest()[:24]
|
||||
|
||||
|
||||
class AnalysisCache:
|
||||
def __init__(self, folder: Path):
|
||||
self.folder = Path(folder)
|
||||
|
||||
def _path(self, key: str, lead: float, n_columns: int) -> Path:
|
||||
# One source can be measured with different leads (a target's clock
|
||||
# offset), so each variant is its own entry under the same key prefix.
|
||||
return self.folder / f"{key}-{int(round(lead * 1_000_000))}-{n_columns}.npz"
|
||||
|
||||
def analyse(self, audio: Path, key: str, *, lead: float = 0.0,
|
||||
n_columns: int = 400) -> waveform.Analysis | None:
|
||||
"""`waveform.analyse(audio, …)`, served from the cache when it can be."""
|
||||
path = self._path(key, lead, n_columns)
|
||||
hit, value = self._load(path, n_columns)
|
||||
if hit:
|
||||
return value
|
||||
value = waveform.analyse(audio, n_columns=n_columns, lead=lead)
|
||||
self._store(path, value)
|
||||
return value
|
||||
|
||||
def prune(self, keep: set[str]) -> None:
|
||||
"""Drop every entry whose key is not in `keep`."""
|
||||
try:
|
||||
for entry in self.folder.iterdir():
|
||||
if entry.name.split("-", 1)[0] not in keep:
|
||||
entry.unlink()
|
||||
self.folder.rmdir() # only succeeds when nothing is left
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def clear(self) -> None:
|
||||
self.prune(set())
|
||||
|
||||
# ---- storage -----------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _load(path: Path, n_columns: int) -> tuple[bool, waveform.Analysis | None]:
|
||||
try:
|
||||
with np.load(path, allow_pickle=False) as data:
|
||||
if bool(data["undecodable"]):
|
||||
# Remembered too: a file nothing can decode would otherwise
|
||||
# be retried, slowly, on every export.
|
||||
return True, None
|
||||
rms = data["rms"]
|
||||
if len(rms) != n_columns:
|
||||
return False, None
|
||||
return True, waveform.Analysis(
|
||||
columns=waveform.Columns(
|
||||
rms=rms, brightness=data["brightness"],
|
||||
duration=float(data["duration"]),
|
||||
),
|
||||
frames=waveform.Frames(bands=data["bands"], duration=float(data["duration"])),
|
||||
)
|
||||
except FileNotFoundError:
|
||||
return False, None
|
||||
except Exception as ex: # noqa: BLE001 — a damaged entry is a miss
|
||||
log.debug("ignoring unreadable analysis cache entry %s: %s", path, ex)
|
||||
return False, None
|
||||
|
||||
@staticmethod
|
||||
def _store(path: Path, value: waveform.Analysis | None) -> None:
|
||||
try:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
partial = path.with_name(path.name + ".partial")
|
||||
with partial.open("wb") as out:
|
||||
if value is None:
|
||||
np.savez_compressed(out, undecodable=np.array(True))
|
||||
else:
|
||||
# Full precision: a cached export must write the same bytes
|
||||
# a fresh one would.
|
||||
np.savez_compressed(
|
||||
out, undecodable=np.array(False),
|
||||
rms=value.columns.rms, brightness=value.columns.brightness,
|
||||
bands=value.frames.bands, duration=np.array(value.columns.duration),
|
||||
)
|
||||
os.replace(partial, path)
|
||||
except OSError as ex:
|
||||
log.warning("could not cache the analysis of %s: %s", path.name, ex)
|
||||
@@ -1,6 +1,6 @@
|
||||
"""Write track metadata into audio files' embedded tags (best-effort).
|
||||
|
||||
Konduktor's source of truth is the `.nml`; this module additionally syncs the
|
||||
Konduktor's source of truth is the library file; this module additionally syncs the
|
||||
safe metadata fields into the audio file itself so the data travels with the
|
||||
file (portability to other apps). It is best-effort: if the file isn't present
|
||||
(e.g. the drive isn't mounted) or the format doesn't support a field, it reports
|
||||
@@ -14,7 +14,12 @@ from __future__ import annotations
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
# The safe, editable metadata we sync to files (mirrors PlaylistStore.EDITABLE_FIELDS).
|
||||
# Whose POPM frame we claim when writing an ID3 rating. The frame is per-owner,
|
||||
# so writing under the DJ app's own email is what makes the rating visible there.
|
||||
# The *51 scaling below is the POPM convention itself, not a platform quirk.
|
||||
DEFAULT_POPM_EMAIL = "no@email"
|
||||
|
||||
# The safe, editable metadata we sync to files (the adapter's editable field set).
|
||||
# rating is 0–5 stars.
|
||||
TagMeta = dict # keys: title, artist, album, genre, label, remixer, producer,
|
||||
# comment, mix, release_date, rating
|
||||
@@ -27,22 +32,6 @@ class TagResult:
|
||||
detail: str = ""
|
||||
|
||||
|
||||
def resolve_path(volume: str | None, dir_: str | None, file: str | None) -> Path:
|
||||
"""Map a Traktor LOCATION to an OS path.
|
||||
|
||||
Paths are trusted (per project decision): boot volume 'Macintosh HD' -> '/',
|
||||
a Windows drive like 'X:' stays a drive path, other volumes -> /Volumes/<v>.
|
||||
"""
|
||||
d = (dir_ or "").replace("/:", "/")
|
||||
name = file or ""
|
||||
vol = volume or ""
|
||||
if vol.endswith(":"): # Windows drive letter, e.g. "X:"
|
||||
return Path(vol + d + name)
|
||||
if vol and vol != "Macintosh HD": # other mounted volume (macOS/*nix)
|
||||
return Path("/Volumes") / vol / (d.lstrip("/") + name)
|
||||
return Path(d + name) # boot volume
|
||||
|
||||
|
||||
def read_cover(path: Path) -> tuple[bytes, str] | None:
|
||||
"""Return (image_bytes, mime) of the file's embedded front cover, or None."""
|
||||
if not path.exists():
|
||||
@@ -148,15 +137,17 @@ def _clean(v) -> str | None:
|
||||
return s or None
|
||||
|
||||
|
||||
def write_tags(path: Path, meta: TagMeta) -> TagResult:
|
||||
def write_tags(
|
||||
path: Path, meta: TagMeta, *, popm_email: str = DEFAULT_POPM_EMAIL
|
||||
) -> TagResult:
|
||||
if not path.exists():
|
||||
return TagResult(False, "file-not-found", str(path))
|
||||
ext = path.suffix.lower()
|
||||
try:
|
||||
if ext == ".mp3":
|
||||
_write_id3(path, meta, id3_only=False)
|
||||
_write_id3(path, meta, id3_only=False, popm_email=popm_email)
|
||||
elif ext in (".aif", ".aiff"):
|
||||
_write_aiff(path, meta)
|
||||
_write_aiff(path, meta, popm_email=popm_email)
|
||||
elif ext in (".m4a", ".mp4") or path.name.lower().endswith(".stem.m4a"):
|
||||
_write_mp4(path, meta)
|
||||
elif ext == ".flac":
|
||||
@@ -170,7 +161,7 @@ def write_tags(path: Path, meta: TagMeta) -> TagResult:
|
||||
|
||||
|
||||
# ---- ID3 (mp3 / aiff) --------------------------------------------------
|
||||
def _apply_id3(id3, meta: TagMeta) -> None:
|
||||
def _apply_id3(id3, meta: TagMeta, popm_email: str = DEFAULT_POPM_EMAIL) -> None:
|
||||
from mutagen.id3 import (
|
||||
COMM,
|
||||
POPM,
|
||||
@@ -217,31 +208,33 @@ def _apply_id3(id3, meta: TagMeta) -> None:
|
||||
if stars > 0:
|
||||
id3.add(
|
||||
POPM(
|
||||
email="traktor@native-instruments.de",
|
||||
email=popm_email,
|
||||
rating=max(0, min(5, stars)) * 51,
|
||||
count=0,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _write_id3(path: Path, meta: TagMeta, id3_only: bool) -> None:
|
||||
def _write_id3(
|
||||
path: Path, meta: TagMeta, id3_only: bool, popm_email: str = DEFAULT_POPM_EMAIL
|
||||
) -> None:
|
||||
from mutagen.id3 import ID3, ID3NoHeaderError
|
||||
|
||||
try:
|
||||
id3 = ID3(path)
|
||||
except ID3NoHeaderError:
|
||||
id3 = ID3()
|
||||
_apply_id3(id3, meta)
|
||||
_apply_id3(id3, meta, popm_email)
|
||||
id3.save(path)
|
||||
|
||||
|
||||
def _write_aiff(path: Path, meta: TagMeta) -> None:
|
||||
def _write_aiff(path: Path, meta: TagMeta, popm_email: str = DEFAULT_POPM_EMAIL) -> None:
|
||||
from mutagen.aiff import AIFF
|
||||
|
||||
audio = AIFF(path)
|
||||
if audio.tags is None:
|
||||
audio.add_tags()
|
||||
_apply_id3(audio.tags, meta)
|
||||
_apply_id3(audio.tags, meta, popm_email)
|
||||
audio.save()
|
||||
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
"""Auto Hotcues: resolve a slot template against a track's structure.
|
||||
|
||||
The user binds each hotcue slot to an EVENT ("first drop", "start of the second
|
||||
breakdown", …) plus an offset in beats ("16 beats before the first drop"). The
|
||||
events come from `core/structure.py`; this module is the pure part — which
|
||||
slots get a cue, where, called what, and why a slot got nothing — so it is
|
||||
testable without audio.
|
||||
|
||||
Offsets are counted along the grid's own beats, not in seconds, so a -16 on a
|
||||
flexible grid lands 16 BEATS earlier even across a tempo change.
|
||||
|
||||
Each slot reports an outcome rather than silently dropping, because a template
|
||||
names specific events and "no second drop in this track" is an answer the user
|
||||
needs, not a cue that quietly failed to appear.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .structure import EVENTS, Structure
|
||||
|
||||
LABELS: dict[str, str] = {
|
||||
"first_beat": "First Beat",
|
||||
"intro_end": "Intro End",
|
||||
"build_1": "Build 1",
|
||||
"drop_1": "Drop 1",
|
||||
"breakdown_1": "Breakdown 1",
|
||||
"build_2": "Build 2",
|
||||
"drop_2": "Drop 2",
|
||||
"breakdown_2": "Breakdown 2",
|
||||
"build_3": "Build 3",
|
||||
"drop_3": "Drop 3",
|
||||
"breakdown_3": "Breakdown 3",
|
||||
"outro": "Outro",
|
||||
"last_beat": "Last Beat",
|
||||
}
|
||||
assert set(LABELS) == set(EVENTS)
|
||||
|
||||
# Outcomes a slot can report.
|
||||
PLACED = "placed"
|
||||
NOT_FOUND = "not_found" # the track has no such event (e.g. no third drop)
|
||||
OUT_OF_RANGE = "out_of_range" # the offset moves it before the start / past the end
|
||||
OCCUPIED = "occupied" # the slot holds a cue and overwrite was not asked for
|
||||
PROTECTED = "protected" # the slot holds a cue the adapter will not replace
|
||||
DUPLICATE = "duplicate" # another cue (kept, or new in a lower slot) is on this beat
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SlotRequest:
|
||||
slot: int
|
||||
event: str
|
||||
offset_beats: int = 0
|
||||
overwrite: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExistingCue:
|
||||
"""A hotcue already in the bank, before this run."""
|
||||
|
||||
editable: bool
|
||||
start: float # seconds
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SlotOutcome:
|
||||
slot: int
|
||||
event: str
|
||||
status: str
|
||||
start: float | None = None
|
||||
name: str | None = None
|
||||
duplicate_of: int | None = None # the slot that got this beat, for DUPLICATE
|
||||
|
||||
|
||||
def cue_name(event: str, offset_beats: int) -> str:
|
||||
"""The label a placed cue carries, e.g. ``Drop 1`` or ``Drop 1 -16``."""
|
||||
label = LABELS[event]
|
||||
return f"{label} {offset_beats:+d}" if offset_beats else label
|
||||
|
||||
|
||||
def _beat_of(structure: Structure, t: float) -> int | None:
|
||||
"""The grid beat a cue at ``t`` sits on, or None if it is between beats.
|
||||
|
||||
A quarter-beat tolerance: a hand-placed cue is rarely sample-exact on the
|
||||
grid, and one a DJ put on the half-beat on purpose is a different beat.
|
||||
"""
|
||||
b = structure.beats
|
||||
i = int(np.clip(np.searchsorted(b, t), 1, len(b) - 1))
|
||||
i = i if abs(b[i] - t) < abs(b[i - 1] - t) else i - 1
|
||||
step = b[min(i + 1, len(b) - 1)] - b[max(i - 1, 0)]
|
||||
step = step / 2 if step > 0 else 0.5
|
||||
return i if abs(b[i] - t) <= step / 4 else None
|
||||
|
||||
|
||||
def plan(
|
||||
structure: Structure,
|
||||
requests: list[SlotRequest],
|
||||
existing: dict[int, ExistingCue],
|
||||
) -> list[SlotOutcome]:
|
||||
"""Decide every requested slot.
|
||||
|
||||
``existing`` is the bank before this run. A non-editable cue (a Traktor grid
|
||||
marker's companion) is never replaced, even when overwrite is ticked,
|
||||
because the adapter would refuse it anyway.
|
||||
|
||||
**One cue per beat.** A slot whose position is on a beat that already has a
|
||||
cue — one this run is placing in a LOWER slot, or one that was in the bank
|
||||
before and stays there (the grid cue, a hand-placed cue) — is skipped as a
|
||||
duplicate of that slot: a second pad on the same beat is a wasted pad. New
|
||||
cues are decided in slot order, so "lower wins" holds whatever order the
|
||||
request lists them in.
|
||||
|
||||
A cue being REPLACED frees its beat only if its replacement is actually
|
||||
placed; a replacement that is itself skipped leaves the old cue — and its
|
||||
claim on the beat — where they were. That is circular (whether slot 3's old
|
||||
cue survives decides slot 5, and slot 5 may be what slot 3 collides with),
|
||||
so the plan is recomputed until the set of surviving cues stops changing;
|
||||
each pass can only add survivors, so it ends within one pass per slot.
|
||||
"""
|
||||
requested = {r.slot: r for r in requests}
|
||||
# Old cues whose replacement was not placed, found by the previous pass.
|
||||
surviving_overwritten: set[int] = set()
|
||||
while True:
|
||||
claims: dict[int, int] = {} # beat index -> slot of the cue on it
|
||||
for slot, cue in sorted(existing.items()):
|
||||
replaced = slot in requested and requested[slot].overwrite and cue.editable
|
||||
if replaced and slot not in surviving_overwritten:
|
||||
continue
|
||||
beat = _beat_of(structure, cue.start)
|
||||
if beat is not None:
|
||||
claims.setdefault(beat, slot)
|
||||
out = _decide(structure, requests, existing, claims)
|
||||
now = {
|
||||
o.slot for o in out
|
||||
if o.slot in existing and requested[o.slot].overwrite
|
||||
and existing[o.slot].editable and o.status != PLACED
|
||||
}
|
||||
if now <= surviving_overwritten:
|
||||
return out
|
||||
surviving_overwritten |= now
|
||||
|
||||
|
||||
def _decide(structure, requests, existing, claims) -> list[SlotOutcome]:
|
||||
out: list[SlotOutcome] = []
|
||||
taken = dict(claims)
|
||||
for r in sorted(requests, key=lambda r: r.slot):
|
||||
cue = existing.get(r.slot)
|
||||
if cue is not None and not cue.editable:
|
||||
out.append(SlotOutcome(r.slot, r.event, PROTECTED))
|
||||
continue
|
||||
if cue is not None and not r.overwrite:
|
||||
out.append(SlotOutcome(r.slot, r.event, OCCUPIED))
|
||||
continue
|
||||
beat = structure.events.get(r.event)
|
||||
if beat is None:
|
||||
out.append(SlotOutcome(r.slot, r.event, NOT_FOUND))
|
||||
continue
|
||||
index = beat + r.offset_beats
|
||||
t = structure.beat_time(index)
|
||||
if t < 0 or t >= structure.duration:
|
||||
out.append(SlotOutcome(r.slot, r.event, OUT_OF_RANGE))
|
||||
continue
|
||||
if index in taken:
|
||||
out.append(SlotOutcome(r.slot, r.event, DUPLICATE, duplicate_of=taken[index]))
|
||||
continue
|
||||
taken[index] = r.slot
|
||||
out.append(SlotOutcome(r.slot, r.event, PLACED, round(t, 4), cue_name(r.event, r.offset_beats)))
|
||||
return out
|
||||
@@ -0,0 +1,117 @@
|
||||
"""What a loaded library can actually do.
|
||||
|
||||
Capabilities are ``f(platform, version)``: the UI reads them and disables or
|
||||
hides the controls the loaded platform cannot persist, so a user is never
|
||||
offered an edit that will silently vanish on save. No component branches on the
|
||||
platform name — that is the whole point.
|
||||
|
||||
With a single adapter most of these are constants, and several keys exist purely
|
||||
so the second adapter has somewhere to answer. That is deliberate: the shape is
|
||||
cheap now and expensive to retrofit once components depend on it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
# Why a library cannot be edited. A FACT, not a sentence — the UI composes the
|
||||
# wording (lib/platformCopy.ts), and the two causes need very different ones:
|
||||
# "Konduktor cannot write this platform YET" is a roadmap gap the user should
|
||||
# expect to close, whereas "this library is synced with Rekordbox Cloud" is a
|
||||
# permanent refusal protecting their other machines.
|
||||
# `not_in_library` is a folder of loose files being browsed: nothing there is a
|
||||
# library to write to, and the way to edit one is to add it to the collection.
|
||||
ReadonlyCause = Literal["platform_incomplete", "cloud_synced", "not_in_library"]
|
||||
|
||||
CueType = Literal["cue", "fade_in", "fade_out", "load", "loop"]
|
||||
CueRole = Literal["hotcue", "memory"]
|
||||
MediaKind = Literal["audio", "stem", "video"]
|
||||
PlaylistKind = Literal["folder", "playlist", "smart"]
|
||||
|
||||
|
||||
class CueCapabilities(BaseModel):
|
||||
# Whether cues can be CREATED/CHANGED. Symmetric with GridCapabilities —
|
||||
# a platform can be writable overall while its cue store is not yet
|
||||
# implemented, which is exactly the Rekordbox milestone-2 state.
|
||||
editable: bool = False
|
||||
hotcue_slots: int = 8 # size of the addressable bank; 0 = no bank
|
||||
slot_labels: Literal["number", "letter"] = "number"
|
||||
# Memory cues are Rekordbox-only today, so they are modelled and PRESERVED
|
||||
# but not editable anywhere yet (the two-platform promotion rule).
|
||||
memory_cues: bool = False
|
||||
max_memory_cues: int | None = None
|
||||
types: list[CueType] = ["cue"]
|
||||
color: Literal["none", "free", "palette"] = "none"
|
||||
palette: list[str] = []
|
||||
named: bool = False
|
||||
# Where a saved loop lives: a cue type (Traktor) or its own bank (Serato).
|
||||
loops: Literal["none", "cue_type", "separate_bank"] = "none"
|
||||
loop_slots: int | None = None
|
||||
|
||||
|
||||
class GridCapabilities(BaseModel):
|
||||
editable: bool = False
|
||||
flexible: bool = False # multi-marker (variable-tempo) grids can be written
|
||||
lockable: bool = False # a per-track grid/analysis lock exists
|
||||
|
||||
|
||||
class TrackCapabilities(BaseModel):
|
||||
rating_max: int = 5
|
||||
editable_fields: list[str] = []
|
||||
media_kinds: list[MediaKind] = ["audio"]
|
||||
# Tracks can be removed from the library (and so from its playlists). The
|
||||
# audio file is never touched either way.
|
||||
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
|
||||
# Tracks can be converted to native-instruments STEM files, which this
|
||||
# platform plays as stems (`apply_stem_swaps`).
|
||||
stem_convertible: bool = False
|
||||
# The audio files this library can hold, as lower-case suffixes. What a
|
||||
# browsed folder offers to add — a file the library would refuse, or that
|
||||
# the DJ app cannot play, is not worth listing as addable.
|
||||
audio_formats: list[str] = [".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a"]
|
||||
artwork: bool = False
|
||||
artwork_note: str | None = None
|
||||
|
||||
|
||||
class PlaylistCapabilities(BaseModel):
|
||||
folders: bool = False
|
||||
smart: Literal["none", "read_only"] = "none"
|
||||
reorder: bool = False
|
||||
|
||||
|
||||
class SaveCapabilities(BaseModel):
|
||||
"""Structured facts, never finished sentences.
|
||||
|
||||
The warning a user needs before saving is genuinely per-platform, so the
|
||||
adapter supplies the facts and the UI composes the wording — which keeps the
|
||||
copy (and any future translation) in the UI without making it vague.
|
||||
"""
|
||||
|
||||
app_name: str
|
||||
library_label: str
|
||||
overwrite_risk: Literal["none", "on_exit", "while_running"] = "none"
|
||||
history: bool = True
|
||||
|
||||
|
||||
class Capabilities(BaseModel):
|
||||
platform: str
|
||||
version: str | None = None
|
||||
# Whether ANY edit can be persisted to this library.
|
||||
#
|
||||
# This is deliberately NOT the same as every individual capability being
|
||||
# false. "The platform has no such feature" and "this library cannot be
|
||||
# written at all" look identical to a UI that only sees the per-feature
|
||||
# flags, and the second one needs saying out loud — silently inert controls
|
||||
# read as a bug. When this is false the per-feature flags are still reported
|
||||
# honestly, so the UI can show what the platform *would* support.
|
||||
writable: bool = True
|
||||
readonly_cause: ReadonlyCause | None = None
|
||||
cues: CueCapabilities = CueCapabilities()
|
||||
grid: GridCapabilities = GridCapabilities()
|
||||
tracks: TrackCapabilities = TrackCapabilities()
|
||||
playlists: PlaylistCapabilities = PlaylistCapabilities()
|
||||
save: SaveCapabilities
|
||||
@@ -0,0 +1,33 @@
|
||||
"""The colour a cue is SHOWN in — the one backend definition.
|
||||
|
||||
A stored colour wins; otherwise the cue's type decides. That is Traktor's own
|
||||
convention (it stores a colour only on a grid marker's white companion cue and
|
||||
draws every other cue from its type) and it is exactly what Konduktor's deck and
|
||||
table draw. **Keep in lockstep with `TYPE_COLORS` in `frontend/src/lib/cues.ts`.**
|
||||
|
||||
Why the backend needs it: an export to a platform that stores a colour per cue
|
||||
(rekordbox) must write what the user SEES. Writing "no colour" hands the choice
|
||||
to the target, which draws its own defaults — rekordbox showed green cues and
|
||||
orange loops where Konduktor and Traktor show blue and green.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .model import CuePoint
|
||||
|
||||
TYPE_COLORS = {
|
||||
"cue": "#4D94FF", # blue
|
||||
"fade_in": "#FF9A3D", # orange
|
||||
"fade_out": "#FF9A3D", # orange
|
||||
"load": "#FFD23D", # yellow
|
||||
"loop": "#3DDC84", # green
|
||||
}
|
||||
MEMORY_COLOR = "#9AA1B2" # grey
|
||||
|
||||
|
||||
def effective_color(cue: CuePoint) -> str:
|
||||
"""`#RRGGBB` — the stored colour, or the type's."""
|
||||
if cue.color:
|
||||
return cue.color.upper()
|
||||
if cue.role == "memory":
|
||||
return MEMORY_COLOR
|
||||
return TYPE_COLORS.get(cue.type, MEMORY_COLOR)
|
||||
@@ -0,0 +1,221 @@
|
||||
"""What changed this session, at field resolution.
|
||||
|
||||
Three things need to know about an edit, and they need different views of it:
|
||||
|
||||
* the file-tag sync wants *which metadata fields* of which track changed, so it
|
||||
writes only those and leaves everything else in the file alone;
|
||||
* the version history wants a human sentence;
|
||||
* a future undo wants the value a field held before.
|
||||
|
||||
The journal records one `Change` per command and derives all three. Recording it
|
||||
at field resolution has to happen from the start: reconstructed afterwards by
|
||||
diffing, an edit that set a field back to its original value is indistinguishable
|
||||
from one that never happened — which is exactly the case where rewriting the
|
||||
field would lose the platform's own formatting of it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Change:
|
||||
scope: str # "track" | "cue" | "grid" | "lock" | "playlist" | "library"
|
||||
op: str # "set" | "add" | "delete" | "modify" | "create" | "rename" | ...
|
||||
target: str | None = None # track id, or a playlist's name
|
||||
detail: str | None = None # field name, "slot:3", "marker:1", "art", ...
|
||||
before: Any = None
|
||||
after: Any = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class EditJournal:
|
||||
changes: list[Change] = field(default_factory=list)
|
||||
|
||||
# ---- recording --------------------------------------------------------
|
||||
def record(
|
||||
self,
|
||||
scope: str,
|
||||
op: str,
|
||||
target: str | None = None,
|
||||
detail: str | None = None,
|
||||
before: Any = None,
|
||||
after: Any = None,
|
||||
) -> None:
|
||||
self.changes.append(Change(scope, op, target, detail, before, after))
|
||||
|
||||
def clear(self) -> None:
|
||||
self.changes.clear()
|
||||
|
||||
@property
|
||||
def dirty(self) -> bool:
|
||||
return bool(self.changes)
|
||||
|
||||
# ---- views ------------------------------------------------------------
|
||||
def fields_for(self, track_id: str) -> set[str]:
|
||||
"""Metadata field names edited on this track (drives the file-tag sync)."""
|
||||
return {
|
||||
c.detail
|
||||
for c in self.changes
|
||||
if c.scope == "track" and c.op == "set" and c.target == track_id and c.detail
|
||||
}
|
||||
|
||||
def edited_tracks(self) -> set[str]:
|
||||
"""Tracks whose metadata or artwork changed.
|
||||
|
||||
Excludes tracks that were ADDED. They are not edits: nothing about them
|
||||
changed, they simply did not exist before. Counting them here would both
|
||||
mislabel the version-history message and drag them through the file-tag
|
||||
sync, which has nothing to write for a track whose fields were never
|
||||
touched. Excludes tracks REMOVED from the library for the same reason:
|
||||
"edited 40 tracks" would describe a deletion as an edit.
|
||||
"""
|
||||
removed = self.removed_tracks()
|
||||
return {
|
||||
c.target
|
||||
for c in self.changes
|
||||
if c.scope == "track" and c.target and c.op not in ("add", "remove")
|
||||
and c.target not in removed
|
||||
}
|
||||
|
||||
def removed_tracks(self) -> set[str]:
|
||||
"""Tracks taken out of the library this session."""
|
||||
return {
|
||||
c.target for c in self.changes if c.scope == "track" and c.op == "remove" and c.target
|
||||
}
|
||||
|
||||
def added_tracks(self) -> set[str]:
|
||||
"""Tracks put into the library that it did not previously hold."""
|
||||
return {
|
||||
c.target for c in self.changes if c.scope == "track" and c.op == "add" and c.target
|
||||
}
|
||||
|
||||
def retarget(self, old_id: str, new_id: str) -> None:
|
||||
"""Follow a track whose id changed (a path remap rewrites LOCATIONs, and
|
||||
the id is derived from the location). Without this, edits made earlier in
|
||||
the session would silently stop syncing to the file."""
|
||||
self.retarget_many({old_id: new_id})
|
||||
|
||||
def retarget_many(self, renames: dict[str, str]) -> None:
|
||||
"""`retarget` for a whole remap AT ONCE. One at a time would be wrong
|
||||
for a chain — A moving to B's old path while B moves on to C would
|
||||
carry A's edits to C along with B's."""
|
||||
renames = {o: n for o, n in renames.items() if o != n}
|
||||
if not renames:
|
||||
return
|
||||
for i, c in enumerate(self.changes):
|
||||
if c.target in renames and c.scope in ("track", "cue", "grid", "lock"):
|
||||
self.changes[i] = Change(c.scope, c.op, renames[c.target], c.detail, c.before, c.after)
|
||||
|
||||
# ---- the version-history message --------------------------------------
|
||||
def summary(self, extra_tracks: set[str] | None = None) -> str:
|
||||
"""A one-line, human-readable summary of this session's edits, used as the
|
||||
version-history commit message (e.g. "Edited 3 tracks; renamed playlist
|
||||
'House'; added 6 hotcues; edited beatgrid on 2 tracks").
|
||||
|
||||
Prep edits are collapsed to meaningful aggregates rather than raw op
|
||||
counts: hotcues report their NET change (created − removed), and beatgrid/
|
||||
lock edits report how many distinct tracks were affected — so tweaking one
|
||||
grid ten times reads as "1 track", not "10 edits".
|
||||
"""
|
||||
parts: list[str] = []
|
||||
|
||||
def tracks(n: int) -> str:
|
||||
return f"{n} track{'' if n == 1 else 's'}"
|
||||
|
||||
# --- tracks added to the library (import) ---
|
||||
# First, because it is the largest-grained thing that can have happened:
|
||||
# "added 52 tracks" is the headline, and the cue/grid counts that follow
|
||||
# are mostly describing those same tracks' imported prep.
|
||||
n_added = len(self.added_tracks())
|
||||
if n_added:
|
||||
parts.append(f"added {tracks(n_added)}")
|
||||
n_removed = len(self.removed_tracks())
|
||||
if n_removed:
|
||||
parts.append(f"removed {tracks(n_removed)} from the collection")
|
||||
n_stems = len({c.target for c in self.changes if c.scope == "stem" and c.target})
|
||||
if n_stems:
|
||||
parts.append(f"converted {tracks(n_stems)} to stems")
|
||||
|
||||
# --- track metadata + cover art (already counted per-track) ---
|
||||
n_meta = len(self.edited_tracks() | (extra_tracks or set()))
|
||||
if n_meta:
|
||||
parts.append(f"edited {tracks(n_meta)}")
|
||||
|
||||
# --- playlists (name-bearing) ---
|
||||
pl_names: dict[str, list[str]] = {}
|
||||
for c in self.changes:
|
||||
if c.scope == "playlist" and c.target:
|
||||
pl_names.setdefault(c.op, []).append(c.target)
|
||||
# A folder is its own op so the message does not call it a playlist —
|
||||
# "created playlists 'Hardy', 'demos'" reads as two playlists when one is
|
||||
# the folder the other went into.
|
||||
for op, verb, noun in (
|
||||
("create", "created", "playlist"),
|
||||
("create-folder", "created", "folder"),
|
||||
("rename", "renamed", "playlist"),
|
||||
("delete", "deleted", "playlist"),
|
||||
("entries", "reordered", "playlist"),
|
||||
):
|
||||
names = pl_names.get(op, [])
|
||||
if not names:
|
||||
continue
|
||||
if len(names) <= 2:
|
||||
joined = ", ".join(f"'{n}'" for n in names)
|
||||
parts.append(f"{verb} {noun}{'' if len(names) == 1 else 's'} {joined}")
|
||||
else:
|
||||
parts.append(f"{verb} {len(names)} {noun}s")
|
||||
|
||||
# --- hotcues: net change in count, scoped by how many tracks were touched ---
|
||||
hc_add = hc_del = 0
|
||||
hc_tracks: set[str] = set()
|
||||
grid_edit: set[str] = set()
|
||||
grid_del: set[str] = set()
|
||||
lock_on: set[str] = set()
|
||||
lock_off: set[str] = set()
|
||||
for c in self.changes:
|
||||
if c.scope == "cue":
|
||||
if c.target:
|
||||
hc_tracks.add(c.target)
|
||||
if c.op == "add":
|
||||
hc_add += 1
|
||||
elif c.op == "delete":
|
||||
hc_del += 1
|
||||
elif c.scope == "grid":
|
||||
# "delete" is the ONLY deletion op. Everything else — including
|
||||
# ops added later — counts as an edit, because mis-labelling an
|
||||
# edit as a deletion in the history summary is the damaging direction.
|
||||
(grid_del if c.op == "delete" else grid_edit).add(c.target or "")
|
||||
elif c.scope == "lock":
|
||||
(lock_on if c.op == "on" else lock_off).add(c.target or "")
|
||||
|
||||
if hc_tracks:
|
||||
net = hc_add - hc_del
|
||||
scope = f" across {tracks(len(hc_tracks))}" if len(hc_tracks) > 1 else ""
|
||||
if net > 0:
|
||||
parts.append(f"added {net} hotcue{'' if net == 1 else 's'}{scope}")
|
||||
elif net < 0:
|
||||
parts.append(f"removed {-net} hotcue{'' if -net == 1 else 's'}{scope}")
|
||||
else: # net zero but there was activity (moves / retypes / add-then-delete)
|
||||
parts.append(f"adjusted hotcues{scope}")
|
||||
|
||||
# --- beatgrids & lock: per-track counts ---
|
||||
if grid_edit:
|
||||
parts.append(f"edited beatgrid on {tracks(len(grid_edit))}")
|
||||
if grid_del:
|
||||
parts.append(f"deleted beatgrid on {tracks(len(grid_del))}")
|
||||
if lock_on:
|
||||
parts.append(f"locked {tracks(len(lock_on))}")
|
||||
if lock_off:
|
||||
parts.append(f"unlocked {tracks(len(lock_off))}")
|
||||
|
||||
# --- path remap ---
|
||||
for c in self.changes:
|
||||
if c.scope == "library" and c.op == "remap" and c.after:
|
||||
parts.append(f"remapped {c.after} file paths")
|
||||
|
||||
if not parts:
|
||||
return "Saved changes"
|
||||
summary = "; ".join(parts)
|
||||
return summary[0].upper() + summary[1:]
|
||||
@@ -0,0 +1,189 @@
|
||||
"""Writing a BRAND NEW library for another platform.
|
||||
|
||||
The contract an exporter is written against, and the payload it consumes. Both
|
||||
are strictly generic: an exporter is handed `Track`s, `TrackCues` and playlist
|
||||
names, never a native type from whatever library the user happens to have open.
|
||||
That is what makes "the source is whatever is loaded" free — a Rekordbox
|
||||
collection exports to Traktor with no exporter knowing Rekordbox exists.
|
||||
|
||||
## Why this is not `LibraryDriver`
|
||||
|
||||
A driver OPENS a library that already exists; an exporter CREATES one where
|
||||
nothing does. Keeping them apart keeps the edit path — the one carrying the
|
||||
byte-fidelity guarantees — out of reach of a lossy-by-design export.
|
||||
|
||||
An exporter also declares **static** capabilities. It has no instance and no
|
||||
path, because the library it describes does not exist yet, which is exactly the
|
||||
question "what can the target represent?" needs answering before any of it is
|
||||
written.
|
||||
|
||||
## Who does what
|
||||
|
||||
`core` plans and copies; the exporter only writes the library file. Layout,
|
||||
collision and dedup rules are platform-independent and must not drift between
|
||||
targets — and the exporter could not write a Traktor `<LOCATION>` before the
|
||||
destination path is known anyway, so every `ExportTrack` arrives carrying its
|
||||
FINAL audio path.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Callable, Protocol, runtime_checkable
|
||||
|
||||
from .capabilities import Capabilities
|
||||
from .model import Track, TrackCues
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .analysis_cache import AnalysisCache
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExportTrack:
|
||||
"""One track, with its prep, and where its audio now lives."""
|
||||
|
||||
track: Track
|
||||
#: Where the copy ALREADY IS. The exporter never copies; by the time it runs
|
||||
#: the file is on disk, because a half-copied file is not something a library
|
||||
#: write should be discovering.
|
||||
destination: Path
|
||||
cues: TrackCues | None = None
|
||||
#: The cover as the SOURCE library serves it — `(bytes, mime)` from
|
||||
#: `LibraryAdapter.cover_art` — or None. Carried rather than re-read from the
|
||||
#: copied file, because a library's art is not always embedded in the audio
|
||||
#: (rekordbox keeps its own copy under `share/`).
|
||||
art: tuple[bytes, str] | None = None
|
||||
#: The source file's identity (`analysis_cache.fingerprint`), and the cache
|
||||
#: on the destination drive — both set by the runner, so a re-export does
|
||||
#: not decode an unchanged track again. Either may be None.
|
||||
fingerprint: str | None = None
|
||||
analysis_cache: "AnalysisCache | None" = field(default=None, repr=False)
|
||||
|
||||
def waveform(self, *, lead: float = 0.0):
|
||||
"""`waveform.analyse()` of the copied audio — the call every exporter that
|
||||
measures audio makes, so all of them share the cache."""
|
||||
from . import waveform
|
||||
|
||||
if self.analysis_cache is not None and self.fingerprint:
|
||||
return self.analysis_cache.analyse(self.destination, self.fingerprint, lead=lead)
|
||||
return waveform.analyse(self.destination, lead=lead)
|
||||
|
||||
@property
|
||||
def source_id(self) -> str:
|
||||
"""Its id in the SOURCE library, for joining playlists to tracks."""
|
||||
return self.track.id
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExportPlaylist:
|
||||
"""A playlist to recreate in the exported library.
|
||||
|
||||
`folders` is the path of folder names to nest it under, outermost first, so
|
||||
a target that supports folders can preserve the user's tree and one that
|
||||
cannot may flatten the same information into a name.
|
||||
"""
|
||||
|
||||
name: str
|
||||
track_ids: list[str] = field(default_factory=list) # SOURCE ids
|
||||
folders: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExportPayload:
|
||||
"""Everything an exporter needs, and nothing platform-specific."""
|
||||
|
||||
tracks: list[ExportTrack] = field(default_factory=list)
|
||||
playlists: list[ExportPlaylist] = field(default_factory=list)
|
||||
#: The export's name, used for the folder its playlists are nested under.
|
||||
name: str = "Export"
|
||||
#: Called by a writer before each slow step (e.g. decoding a track for its
|
||||
#: waveform) with a message for the status bar, and — for a per-track loop —
|
||||
#: `step` of `of`, which drives the progress bar. RAISES when the user has
|
||||
#: cancelled — so a writer that analyses audio stays cancellable. The runner
|
||||
#: sets it; a writer may call it freely and never needs to check for None.
|
||||
checkpoint: Callable[..., None] = field(
|
||||
default=lambda message, step=None, of=None: None, repr=False)
|
||||
|
||||
|
||||
@dataclass
|
||||
class WrittenLibrary:
|
||||
"""What an exporter put on disk.
|
||||
|
||||
A list rather than one path because a library is not always one file: a
|
||||
Traktor export is a single `collection.nml`, but Rekordbox and OneLibrary
|
||||
each write a database PLUS a per-track analysis file. The runner records all
|
||||
of them in its manifest, and a re-export clears exactly that list — so an
|
||||
exporter that under-reports leaves orphans behind that the next export
|
||||
cannot clean up.
|
||||
"""
|
||||
|
||||
#: The library file itself, for the manifest and for telling the user.
|
||||
library: Path
|
||||
#: Everything else written, e.g. analysis files. Excludes `library`.
|
||||
extra: list[Path] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def all_paths(self) -> list[Path]:
|
||||
return [self.library, *self.extra]
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class LibraryExporter(Protocol):
|
||||
"""Writes one platform's library, from nothing. Stateless."""
|
||||
|
||||
platform: str
|
||||
#: What the written library file is called, e.g. "collection.nml".
|
||||
library_filename: str
|
||||
#: Where the target sits in the export dialog's list, lowest first. Optional
|
||||
#: (unset sorts last): a stick's formats lead, a computer library trails.
|
||||
#: The name the export dialog shows. Optional: a target named after its
|
||||
#: platform omits it and the driver's `display_name` is used. Needed where
|
||||
#: one platform has two targets ("Rekordbox Library" / "Rekordbox Export").
|
||||
#: The library is only found when the destination is a DRIVE'S ROOT — a
|
||||
#: player looks for it there and nowhere else. Several targets can share one
|
||||
#: destination, so this is a warning the UI raises, not a refusal: the other
|
||||
#: targets in the same export are still perfectly valid in any folder.
|
||||
drive_root: bool = False
|
||||
|
||||
def capabilities(self) -> Capabilities:
|
||||
"""What this target can represent — STATIC, with no library to read."""
|
||||
...
|
||||
|
||||
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
|
||||
"""Write a complete library into `destination`; report what it wrote.
|
||||
|
||||
The destination exists and already holds the copied audio. Raises rather
|
||||
than writing something partial: a library file is the last thing an
|
||||
export produces, so its absence is what marks an export unfinished.
|
||||
|
||||
Everything written must be reported, not just the library — the runner's
|
||||
manifest is what lets a re-export clear its own output and nothing else.
|
||||
"""
|
||||
...
|
||||
|
||||
|
||||
_EXPORTERS: list[LibraryExporter] = []
|
||||
|
||||
|
||||
def register(exporter: LibraryExporter) -> None:
|
||||
"""Register a target. Called once per adapter package, at import."""
|
||||
if not any(e.platform == exporter.platform for e in _EXPORTERS):
|
||||
_EXPORTERS.append(exporter)
|
||||
|
||||
|
||||
def exporters() -> list[LibraryExporter]:
|
||||
return list(_EXPORTERS)
|
||||
|
||||
|
||||
def for_platform(platform: str) -> LibraryExporter | None:
|
||||
"""The exporter for a platform, or None when it cannot be a target.
|
||||
|
||||
Deliberately narrower than `registry.driver_for`: reading a library and
|
||||
creating one from nothing are different capabilities, and a platform can
|
||||
have the first without the second.
|
||||
"""
|
||||
return next((e for e in _EXPORTERS if e.platform == platform), None)
|
||||
|
||||
|
||||
def targets() -> set[str]:
|
||||
return {e.platform for e in _EXPORTERS}
|
||||
@@ -0,0 +1,202 @@
|
||||
"""A folder of loose audio files, read as if it were a (read-only) library.
|
||||
|
||||
The sidebar's Files trees browse any drive, and selecting a folder shows the
|
||||
audio in it in the ordinary track table and deck. Projecting the folder into the
|
||||
generic `Track` model is what makes that cheap: the table, the deck, the
|
||||
read-only gating and the importer all already speak it, so none of them needs to
|
||||
learn what a folder is.
|
||||
|
||||
Deliberately NOT a registered driver. `can_open()` on "any directory" would make
|
||||
every folder a library to the picker, and the collection picker offering
|
||||
`~/Downloads` as a library is exactly the confusion the registry exists to avoid.
|
||||
This is opened by the folder routes and nothing else.
|
||||
|
||||
Three rules:
|
||||
|
||||
* **This folder only.** Subfolders are not scanned — the tree is how you get to
|
||||
them — so a click on a drive root never walks the whole drive.
|
||||
* **A track id is the file's absolute path.** It is the one identity a loose
|
||||
file has, and it is what the audio route checks a request against.
|
||||
* **Tags are read once per folder state.** Reading tags opens every file, which
|
||||
on a slow stick is the whole cost; the result is cached until the folder's
|
||||
own mtime changes (a file added, removed or renamed).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
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__)
|
||||
|
||||
|
||||
def _first(tags, key: str) -> str | None:
|
||||
try:
|
||||
values = tags.get(key)
|
||||
except (KeyError, ValueError):
|
||||
return None
|
||||
if not values:
|
||||
return None
|
||||
value = str(values[0]).strip()
|
||||
return value or None
|
||||
|
||||
|
||||
def _bpm(tags) -> float | None:
|
||||
raw = _first(tags, "bpm")
|
||||
if raw is None:
|
||||
return None
|
||||
try:
|
||||
bpm = float(raw)
|
||||
except ValueError:
|
||||
return None
|
||||
return bpm if 20 <= bpm <= 400 else 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")
|
||||
try:
|
||||
import mutagen
|
||||
|
||||
audio = mutagen.File(path, easy=True)
|
||||
except Exception: # noqa: BLE001 — a corrupt file must not hide the folder
|
||||
log.debug("could not read tags from %s", path, exc_info=True)
|
||||
return track
|
||||
if audio is None:
|
||||
return track
|
||||
tags = audio.tags or {}
|
||||
track.title = _first(tags, "title") or path.stem
|
||||
track.artist = _first(tags, "artist")
|
||||
track.album = _first(tags, "album")
|
||||
track.genre = _first(tags, "genre")
|
||||
track.label = _first(tags, "organization")
|
||||
track.bpm = _bpm(tags)
|
||||
info = getattr(audio, "info", None)
|
||||
if info is not None:
|
||||
length = getattr(info, "length", None)
|
||||
track.length = int(round(length)) if length else None
|
||||
bitrate = getattr(info, "bitrate", None)
|
||||
track.bitrate = int(bitrate) if bitrate else None
|
||||
# Key is left out on purpose: tagged keys arrive in every notation there is
|
||||
# ("Am", "8A", "1m", "A minor"), and passing one through to a library would
|
||||
# write a string its own analysis never would.
|
||||
return track
|
||||
|
||||
|
||||
def audio_files(folder: Path, formats: list[str]) -> list[Path]:
|
||||
"""The visible audio files directly inside `folder`, sorted by name."""
|
||||
wanted = {f.lower() for f in formats}
|
||||
out: list[Path] = []
|
||||
try:
|
||||
with os.scandir(folder) as it:
|
||||
for entry in it:
|
||||
try:
|
||||
if not entry.is_file() or is_hidden(entry):
|
||||
continue
|
||||
except OSError:
|
||||
continue
|
||||
if Path(entry.name).suffix.lower() in wanted:
|
||||
out.append(Path(entry.path))
|
||||
except OSError:
|
||||
return []
|
||||
return sorted(out, key=lambda p: p.name.lower())
|
||||
|
||||
|
||||
def capabilities_for(folder: Path) -> Capabilities:
|
||||
return Capabilities(
|
||||
platform="folder",
|
||||
writable=False,
|
||||
readonly_cause="not_in_library",
|
||||
tracks=TrackCapabilities(editable_fields=[], artwork=False, media_kinds=["audio", "stem"]),
|
||||
save=SaveCapabilities(
|
||||
app_name="Files",
|
||||
library_label=folder.name or str(folder),
|
||||
overwrite_risk="none",
|
||||
history=False,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class FolderSource:
|
||||
"""The read half of the adapter protocol, over one folder's audio files.
|
||||
|
||||
Only what the table, the deck and the importer ask a source for. There are
|
||||
no commands at all: nothing here can be written, so nothing here pretends
|
||||
it could.
|
||||
"""
|
||||
|
||||
def __init__(self, folder: Path, tracks: list[Track]):
|
||||
self.path = folder
|
||||
self._tracks = tracks
|
||||
self._by_id = {t.id: t for t in tracks}
|
||||
|
||||
@property
|
||||
def tracks(self) -> list[Track]:
|
||||
return self._tracks
|
||||
|
||||
def track(self, track_id: str) -> Track | None:
|
||||
return self._by_id.get(track_id)
|
||||
|
||||
def track_cues(self, track_id: str) -> TrackCues | None:
|
||||
return TrackCues(cues=[], grid_markers=[]) if track_id in self._by_id else None
|
||||
|
||||
def audio_path(self, track_id: str) -> Path | None:
|
||||
return Path(track_id) if track_id in self._by_id else None
|
||||
|
||||
def playlist_tree(self) -> list[PlaylistNode]:
|
||||
return []
|
||||
|
||||
def playlist_tracks(self, node_id: str) -> list[Track] | None:
|
||||
return None
|
||||
|
||||
def capabilities(self) -> Capabilities:
|
||||
return capabilities_for(self.path)
|
||||
|
||||
|
||||
class FolderScanner:
|
||||
"""Scans folders on request, caching each until its contents change.
|
||||
|
||||
Also the gatekeeper for streaming: `source_for_file` answers only for a file
|
||||
found by a scan, so the audio route cannot be used to read an arbitrary path
|
||||
off the disk — only audio the user has browsed to.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._lock = threading.Lock()
|
||||
self._cache: dict[str, tuple[float, tuple[str, ...], FolderSource]] = {}
|
||||
|
||||
def scan(self, folder: Path, formats: list[str]) -> FolderSource:
|
||||
folder = Path(folder)
|
||||
try:
|
||||
mtime = folder.stat().st_mtime
|
||||
except OSError:
|
||||
mtime = -1.0
|
||||
key = str(folder)
|
||||
fmts = tuple(sorted(f.lower() for f in formats))
|
||||
with self._lock:
|
||||
hit = self._cache.get(key)
|
||||
if hit is not None and hit[0] == mtime and hit[1] == fmts:
|
||||
return hit[2]
|
||||
source = FolderSource(folder, [read_track(p) for p in audio_files(folder, formats)])
|
||||
with self._lock:
|
||||
self._cache[key] = (mtime, fmts, source)
|
||||
return source
|
||||
|
||||
def source_for_file(self, track_id: str) -> FolderSource | None:
|
||||
folder = str(Path(track_id).parent)
|
||||
with self._lock:
|
||||
hit = self._cache.get(folder)
|
||||
if hit is None or hit[2].track(track_id) is None:
|
||||
return None
|
||||
return hit[2]
|
||||
|
||||
def clear(self) -> None:
|
||||
with self._lock:
|
||||
self._cache.clear()
|
||||
@@ -0,0 +1,387 @@
|
||||
"""Beatgrid detection: one constant tempo + anchor, fitted to the whole track.
|
||||
|
||||
Why not a beat tracker. The previous detector was ``librosa.beat.beat_track``,
|
||||
and it could not be right: its tempo comes from an autocorrelation over
|
||||
~23 ms frames, so it can only return ``60 / (k * 23 ms)`` — between 115 and
|
||||
140 BPM the ONLY values it can produce are 117.45, 123.05, 129.20 and 136.00.
|
||||
A 125 BPM track came back as 123.05 and drifted ~2 beats per minute, and its
|
||||
first beat carried the onset curve's own ~23 ms lag. Against 29 grids
|
||||
Rekordbox analysed (``bench_grid_detect.py``) it got 1 BPM and 0 grids right.
|
||||
|
||||
Dance music makes a much stronger assumption available, the one Traktor's and
|
||||
Rekordbox's analysers make: the tempo is CONSTANT. So instead of tracking
|
||||
beats, this fits one pulse train to every onset in the track:
|
||||
|
||||
1. **Onset curves at 1 kHz from zero-phase band filters** (``sosfiltfilt``
|
||||
adds no group delay): a kick band, a mid band and the full signal.
|
||||
2. **Tempo from the whole track's spectrum.** A pulse train at ``f`` Hz has
|
||||
energy at ``f, 2f, 3f …``; the onset spectrum's magnitude summed over those
|
||||
harmonics peaks at the tempo, as finely as ``1 / track length`` allows,
|
||||
then parabolic refinement goes further.
|
||||
3. **Octave by comb score**: a comb at half the tempo hits every kick too, so
|
||||
the FASTEST candidate scoring nearly as well as the best wins, inside
|
||||
``bpm_range``. Halftime genres stay genuinely ambiguous — ×2 / ÷2 exist.
|
||||
4. **Phase from attacks that are followed by low end.** Timing comes from a
|
||||
1–8 kHz attack band, whose onset is sharp (a kick's low end swells for ~25 ms after
|
||||
its attack, so the kick band alone lands late). Which attack is the beat is
|
||||
decided by whether low end follows it: that rejects the off-beat hat (no low
|
||||
end) and the syncopated bassline (no attack), each of which won a benchmark
|
||||
track when judged by one band alone.
|
||||
5. **Round BPMs are snapped** only if the round tempo keeps every section of
|
||||
the track on the beat — a direct test, rather than a score ratio.
|
||||
|
||||
Positions are in the DECODED audio's time base — the one Konduktor's deck
|
||||
plays (libsndfile and macOS CoreAudio agree to the sample on MP3). A platform
|
||||
may disagree for lossy files: Rekordbox's grids sit a constant ~25 ms later on
|
||||
every MP3/AAC in the benchmark (the decoder delay it does not trim) and at 0 on
|
||||
WAV. That is a platform time-base difference, not a detection error, and it is
|
||||
deliberately not corrected here.
|
||||
|
||||
``drift_ms`` reports how far the fitted grid strays from the beat in its
|
||||
worst section — the number that says a slowly wandering tempo is not being
|
||||
described by one marker. A sudden tempo change is out of its reach (that is
|
||||
flexible-grid detection, not built).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
|
||||
_SR = 22050 # plenty for a kick; halves decode + filter cost vs 44.1k
|
||||
_FR = 1000 # onset-curve frame rate (Hz) — 1 ms timing resolution
|
||||
_TEMPO_FR = 250 # the tempo spectrum only needs content up to ~15 Hz
|
||||
_HARMONICS = 8 # pulse-train harmonics summed for the tempo score
|
||||
|
||||
# The band an attack's timing is read from. A kick's beater click reaches well
|
||||
# above 1 kHz; a bass note's leakage does not, which is what stops a
|
||||
# syncopated bassline (whose low end is as loud as the kick's) from posing as
|
||||
# one. The hat lives here too, but has no low end to follow it.
|
||||
_ATTACK_LO_HZ = 1000.0
|
||||
_ATTACK_HI_HZ = 8000.0
|
||||
# How long after an attack a kick's low end is looked for (ms).
|
||||
_KICK_FOLLOW_MS = 45
|
||||
# Measured, not derived: on WAV loops that start exactly on the beat, the
|
||||
# mid-band onset peak lands this far before the true attack (the centred
|
||||
# smoothing's leading edge). Added back so the grid sits ON the transient.
|
||||
_ONSET_BIAS_S = 0.002
|
||||
|
||||
# The detected range. Anything outside is folded in by octaves, which is where
|
||||
# half/double-tempo answers come from — and what ×2 / ÷2 are for.
|
||||
DEFAULT_BPM_RANGE = (70.0, 180.0)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class GridResult:
|
||||
bpm: float
|
||||
anchor: float # seconds: the first beat at or after the music starts
|
||||
duration: float # seconds
|
||||
# Worst distance between the grid and the beat over any ~30 s section with
|
||||
# a clear beat. A few ms on a produced track; tens of ms means the tempo
|
||||
# wanders (a live drummer, a vinyl rip). A sudden tempo CHANGE is not seen.
|
||||
drift_ms: float | None = None
|
||||
|
||||
|
||||
# ---- onset curves -------------------------------------------------------------
|
||||
def _band_env(
|
||||
y: np.ndarray, sr: int, lo: float | None, hi: float | None, smooth_ms: int = 11
|
||||
) -> np.ndarray:
|
||||
"""Log-energy envelope of one band at ``_FR`` Hz, zero-phase throughout."""
|
||||
from scipy.signal import butter, sosfiltfilt
|
||||
|
||||
if lo and hi:
|
||||
sos = butter(4, [lo, hi], btype="bandpass", fs=sr, output="sos")
|
||||
elif hi:
|
||||
sos = butter(4, hi, btype="lowpass", fs=sr, output="sos")
|
||||
elif lo:
|
||||
sos = butter(4, lo, btype="highpass", fs=sr, output="sos")
|
||||
else:
|
||||
sos = None
|
||||
x = sosfiltfilt(sos, y) if sos is not None else y
|
||||
hop = sr / _FR
|
||||
n = int(len(x) / hop)
|
||||
# Block energy on a fractional hop, so frame i is centred on time i / _FR.
|
||||
edges = np.round(np.arange(n + 1) * hop).astype(np.int64)
|
||||
c = np.concatenate(([0.0], np.cumsum(x.astype(np.float64) ** 2)))
|
||||
e = (c[edges[1:]] - c[edges[:-1]]) / np.maximum(1, np.diff(edges))
|
||||
# A centred smooth removes a band's carrier ripple (a 50 Hz kick needs
|
||||
# ~10 ms) without moving anything in time.
|
||||
if smooth_ms > 1:
|
||||
e = np.convolve(e, np.ones(smooth_ms) / smooth_ms, mode="same")
|
||||
return np.log1p(e / (np.percentile(e, 90) + 1e-12) * 100.0)
|
||||
|
||||
|
||||
def _onset(env: np.ndarray) -> np.ndarray:
|
||||
"""Positive slope of a log envelope, centred so a peak sits ON the attack."""
|
||||
d = np.zeros_like(env)
|
||||
d[1:-1] = (env[2:] - env[:-2]) / 2
|
||||
d = np.maximum(d, 0.0)
|
||||
# Remove a slowly varying floor so long crescendos don't read as onsets.
|
||||
from scipy.ndimage import uniform_filter1d
|
||||
d = np.maximum(d - uniform_filter1d(d, size=_FR // 4), 0.0)
|
||||
return d / (d.max() + 1e-12)
|
||||
|
||||
|
||||
# ---- tempo --------------------------------------------------------------------
|
||||
def _decimate(o: np.ndarray, factor: int) -> np.ndarray:
|
||||
n = len(o) // factor
|
||||
return o[: n * factor].reshape(n, factor).sum(axis=1)
|
||||
|
||||
|
||||
def _dft(o: np.ndarray, fr: float, freqs: np.ndarray) -> np.ndarray:
|
||||
"""|DFT| of ``o`` at arbitrary frequencies (Hz), chunked to bound memory."""
|
||||
t = np.arange(len(o)) / fr
|
||||
out = np.empty(len(freqs))
|
||||
step = max(1, 4_000_000 // max(1, len(o)))
|
||||
for i in range(0, len(freqs), step):
|
||||
f = freqs[i : i + step, None]
|
||||
out[i : i + step] = np.abs(np.exp(-2j * np.pi * f * t) @ o)
|
||||
return out
|
||||
|
||||
|
||||
def _harmonic_score(o: np.ndarray, fr: float, bpms: np.ndarray, n_harm: int = _HARMONICS) -> np.ndarray:
|
||||
f0 = bpms / 60.0
|
||||
return sum(_dft(o, fr, f0 * k) for k in range(1, n_harm + 1))
|
||||
|
||||
|
||||
def _coarse_candidates(o_t: np.ndarray, lo: float, hi: float) -> list[float]:
|
||||
"""Local maxima of the harmonic tempo score over [lo/2, hi*2] BPM."""
|
||||
n = 1 << int(np.ceil(np.log2(len(o_t) * 8)))
|
||||
spec = np.abs(np.fft.rfft(o_t - o_t.mean(), n))
|
||||
df = _TEMPO_FR / n
|
||||
bpms = np.arange(lo / 2, hi * 2, 0.05)
|
||||
score = np.zeros_like(bpms)
|
||||
for k in range(1, _HARMONICS + 1):
|
||||
idx = np.round(bpms / 60.0 * k / df).astype(np.int64)
|
||||
idx = idx[idx < len(spec)]
|
||||
score[: len(idx)] += spec[idx]
|
||||
from scipy.signal import find_peaks
|
||||
peaks, _ = find_peaks(score, distance=int(1.0 / 0.05))
|
||||
peaks = peaks[np.argsort(score[peaks])[::-1][:8]]
|
||||
return [float(bpms[p]) for p in peaks]
|
||||
|
||||
|
||||
def _refine(o_t: np.ndarray, bpm: float, width: float, step: float) -> tuple[float, float]:
|
||||
grid = np.arange(bpm - width, bpm + width + step / 2, step)
|
||||
s = _harmonic_score(o_t, _TEMPO_FR, grid)
|
||||
i = int(np.argmax(s))
|
||||
# Parabolic interpolation between the three samples around the max.
|
||||
if 0 < i < len(s) - 1:
|
||||
a, b, c = s[i - 1], s[i], s[i + 1]
|
||||
den = a - 2 * b + c
|
||||
off = 0.5 * (a - c) / den if den != 0 else 0.0
|
||||
return float(grid[i] + off * step), float(b)
|
||||
return float(grid[i]), float(s[i])
|
||||
|
||||
|
||||
def _fold(o: np.ndarray, period_s: float, smooth_ms: int = 11, start: int = 0) -> np.ndarray:
|
||||
"""Onset curve folded onto one period: mean strength at each phase (1 ms bins).
|
||||
|
||||
``start`` is the frame ``o`` begins at, so a slice of the track folds onto
|
||||
the same phase axis as the whole of it.
|
||||
"""
|
||||
bins = max(8, int(round(period_s * _FR)))
|
||||
t = (np.arange(len(o)) + start) / _FR
|
||||
ph = ((t / period_s) % 1.0 * bins).astype(np.int64) % bins
|
||||
h = np.bincount(ph, weights=o, minlength=bins)
|
||||
cnt = np.bincount(ph, minlength=bins)
|
||||
h = h / np.maximum(cnt, 1)
|
||||
# Circular triangle smoothing, centred, so one jittery frame cannot win.
|
||||
w = np.bartlett(smooth_ms + 2)[1:-1]
|
||||
w /= w.sum()
|
||||
kern = np.roll(np.pad(w, (0, bins - len(w))), -(len(w) // 2))
|
||||
return np.real(np.fft.ifft(np.fft.fft(h) * np.fft.fft(kern)))
|
||||
|
||||
|
||||
def _comb(o: np.ndarray, bpm: float) -> float:
|
||||
"""Peak of the folded onset curve: the mean onset strength ON the beat."""
|
||||
return float(_fold(o, 60.0 / bpm).max())
|
||||
|
||||
|
||||
def _in_range(bpm: float, lo: float, hi: float) -> float:
|
||||
while bpm < lo:
|
||||
bpm *= 2
|
||||
while bpm >= hi:
|
||||
bpm /= 2
|
||||
return bpm
|
||||
|
||||
|
||||
# ---- entry point --------------------------------------------------------------
|
||||
def detect_grid(
|
||||
audio_path: str,
|
||||
bpm_range: tuple[float, float] = DEFAULT_BPM_RANGE,
|
||||
*,
|
||||
y: np.ndarray | None = None,
|
||||
sr: int = _SR,
|
||||
) -> GridResult:
|
||||
"""Detect a track's constant tempo and first beat.
|
||||
|
||||
``y``/``sr`` let a caller (or a test) pass decoded mono audio directly.
|
||||
Raises ``ValueError`` when there is no pulse to fit (silence, a one-shot).
|
||||
"""
|
||||
if y is None:
|
||||
import librosa
|
||||
y, sr = librosa.load(audio_path, sr=sr, mono=True)
|
||||
y = np.asarray(y, dtype=np.float32)
|
||||
duration = len(y) / sr
|
||||
if duration < 1.5:
|
||||
raise ValueError("Track is too short to detect a tempo")
|
||||
|
||||
lo, hi = bpm_range
|
||||
low = _onset(_band_env(y, sr, 30.0, 150.0))
|
||||
mid = _onset(_band_env(y, sr, 150.0, 4000.0, smooth_ms=3))
|
||||
attack = _onset(_band_env(y, sr, _ATTACK_LO_HZ, _ATTACK_HI_HZ, smooth_ms=3))
|
||||
full = _onset(_band_env(y, sr, None, None, smooth_ms=3))
|
||||
o_tempo = low + mid + 0.5 * full
|
||||
if not np.isfinite(o_tempo).all() or o_tempo.max() <= 0:
|
||||
raise ValueError("No onsets found")
|
||||
|
||||
o_t = _decimate(o_tempo, _FR // _TEMPO_FR)
|
||||
cands = _coarse_candidates(o_t, lo, hi)
|
||||
if not cands:
|
||||
raise ValueError("Could not detect a tempo")
|
||||
|
||||
# Refine every coarse candidate, fold each into the range, and score it
|
||||
# with the comb (onset strength on the beat, best phase).
|
||||
refined: dict[float, tuple[float, float]] = {}
|
||||
for c in cands:
|
||||
b, _ = _refine(o_t, c, 0.1, 0.01)
|
||||
b = _in_range(b, lo, hi)
|
||||
key = round(b, 1)
|
||||
if key not in refined:
|
||||
refined[key] = (b, _comb(o_tempo, b))
|
||||
best = max(s for _, s in refined.values())
|
||||
# Octave rule: prefer the FASTEST tempo that explains the onsets nearly as
|
||||
# well as the best — a slower comb hits a subset of the same beats.
|
||||
viable = [(b, s) for b, s in refined.values() if s >= 0.9 * best]
|
||||
bpm = max(viable)[0]
|
||||
|
||||
# Final refinement at full precision around the chosen tempo.
|
||||
bpm, _ = _refine(o_t, bpm, 0.02, 0.001)
|
||||
phase = _phase(low, attack, 60.0 / bpm)
|
||||
drift = _drift(attack, bpm, phase)
|
||||
bpm, phase, drift = _snap_round(low, attack, bpm, phase, drift, duration)
|
||||
|
||||
period = 60.0 / bpm
|
||||
return GridResult(
|
||||
bpm=round(bpm, 4),
|
||||
anchor=round(_first_beat(low + attack, phase, period), 4),
|
||||
duration=duration,
|
||||
drift_ms=round(drift * 1000.0, 1),
|
||||
)
|
||||
|
||||
|
||||
def _peaks(f: np.ndarray, k: int, min_sep: int) -> list[int]:
|
||||
"""The ``k`` highest local maxima of a circular curve, ``min_sep`` apart."""
|
||||
n = len(f)
|
||||
is_max = (f >= np.roll(f, 1)) & (f >= np.roll(f, -1))
|
||||
out: list[int] = []
|
||||
for i in np.flatnonzero(is_max)[np.argsort(f[is_max])[::-1]]:
|
||||
if all(min(abs(i - j), n - abs(i - j)) >= min_sep for j in out):
|
||||
out.append(int(i))
|
||||
if len(out) == k:
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
def _phase(low: np.ndarray, attack: np.ndarray, period: float) -> float:
|
||||
"""Seconds into the beat period at which the beat lands.
|
||||
|
||||
Timing comes from the attack band, whose onset is sharp; the kick band's
|
||||
is not — a kick's low end swells for tens of ms after its attack. But the
|
||||
loudest attack is not always the beat (an off-beat hat), and the loudest
|
||||
low-band onset is not always the kick (a bassline note between beats). So
|
||||
each sharp attack is scored by whether LOW END FOLLOWS it: a kick has both,
|
||||
a hat has no low end, a bass note has no attack.
|
||||
"""
|
||||
fine = _fold(attack, period, smooth_ms=3)
|
||||
low_f = _fold(low, period)
|
||||
n = len(fine)
|
||||
floor = 0.1 * low_f.max() # a track with no kick still picks its best attack
|
||||
|
||||
def score(c: int) -> float:
|
||||
follow = max(low_f[(c + d) % n] for d in range(-5, _KICK_FOLLOW_MS + 1))
|
||||
return float(fine[c] * (floor + follow))
|
||||
|
||||
best = max(_peaks(fine, 6, 20), key=score)
|
||||
return (best / n * period + _ONSET_BIAS_S) % period
|
||||
|
||||
|
||||
def _segment_offsets(attack: np.ndarray, period: float, phase: float) -> list[float]:
|
||||
"""Where the beat lands in each ~30 s section, relative to ``phase`` (s).
|
||||
|
||||
Only sections with a clear attack within 40 ms of the grid count. That
|
||||
makes this a measure of SLOW drift — a fit a few hundredths of a BPM out,
|
||||
which is what the round-BPM snap must judge. It cannot see a tempo change
|
||||
(a section whose beat is far off the grid looks the same as a kickless
|
||||
breakdown with hats over it, and on real music treating those as drift
|
||||
reported 100–250 ms on tracks whose grid was right end to end). Detecting
|
||||
tempo changes is flexible-grid detection, and a different job.
|
||||
"""
|
||||
n = len(attack)
|
||||
seg = min(30 * _FR, n // 4)
|
||||
if seg < 6 * _FR:
|
||||
return []
|
||||
out = []
|
||||
for s0 in range(0, n - seg + 1, seg):
|
||||
f = _fold(attack[s0 : s0 + seg], period, smooth_ms=3, start=s0)
|
||||
bins = len(f)
|
||||
c = int(round(phase / period * bins)) % bins
|
||||
i = max(((c + d) % bins for d in range(-40, 41)), key=lambda j: f[j])
|
||||
if f[i] < 2.0 * np.median(f):
|
||||
continue
|
||||
d = (i - c + bins / 2) % bins - bins / 2
|
||||
out.append(d / bins * period)
|
||||
return out
|
||||
|
||||
|
||||
def _drift(attack: np.ndarray, bpm: float, phase: float) -> float:
|
||||
"""Distance (s) between the grid and the beat in the worst section but one.
|
||||
|
||||
One section is allowed to disagree: an intro whose nearest attack is not
|
||||
the kick shows up as a single ~30 ms outlier on otherwise flat tracks, and
|
||||
blocked two round-BPM snaps on the benchmark. Real drift cannot hide behind
|
||||
that — it grows with distance from the anchor, so it is at both ends.
|
||||
"""
|
||||
offs = sorted((abs(o) for o in _segment_offsets(attack, 60.0 / bpm, phase)), reverse=True)
|
||||
if len(offs) >= 4:
|
||||
offs = offs[1:]
|
||||
return offs[0] if offs else 0.0
|
||||
|
||||
|
||||
def _snap_round(low, attack, bpm: float, phase: float, drift: float, duration: float):
|
||||
"""Snap to a round (or half) BPM if it keeps the whole track on the beat.
|
||||
|
||||
The test is the thing that matters, not a score ratio: at the round tempo,
|
||||
does every section of the track stay within a few ms of its onsets? A real
|
||||
124.01 BPM track snapped to 124 would drift ~30 ms over six minutes and
|
||||
fails; a 124.0 track whose fit came out at 124.012 passes.
|
||||
|
||||
How far to look scales with 1/duration, because so does the fit's
|
||||
precision: the window is the tempo error that would move the LAST beat by
|
||||
10 ms, floored at 0.05 BPM. A four-bar loop gets a wide one; a track that
|
||||
is long enough to have a precise fit relies on the drift test instead.
|
||||
"""
|
||||
tol = max(0.05, 0.01 * bpm / max(duration, 1.0))
|
||||
for r in (float(round(bpm)), round(bpm * 2) / 2):
|
||||
if abs(bpm - r) < tol:
|
||||
ph = _phase(low, attack, 60.0 / r)
|
||||
dr = _drift(attack, r, ph)
|
||||
if dr <= max(drift, 0.004) + 0.003:
|
||||
return r, ph, dr
|
||||
return bpm, phase, drift
|
||||
|
||||
|
||||
def _first_beat(o: np.ndarray, phase: float, period: float) -> float:
|
||||
"""The first grid beat at which the music has started.
|
||||
|
||||
A grid anchored in the silence before a track is still correct, but a DJ
|
||||
reads the first marker as "the track starts here", as Traktor draws it.
|
||||
"""
|
||||
pos = o[o > 0]
|
||||
thr = 0.15 * np.percentile(pos, 99) if len(pos) else 0.0
|
||||
hits = np.flatnonzero(o > thr)
|
||||
start = hits[0] / _FR if len(hits) else 0.0
|
||||
# The beat nearest the music's first onset, never before the track starts.
|
||||
n = round((start - phase) / period)
|
||||
return max(phase + n * period, phase % period)
|
||||
@@ -0,0 +1,289 @@
|
||||
"""The generic model — Konduktor's platform-independent read projection.
|
||||
|
||||
Every adapter projects its native library into these types, and the HTTP layer
|
||||
serves them directly. Nothing here may reference a platform's own encodings: a
|
||||
value that only makes sense for one format belongs in that adapter, not here.
|
||||
|
||||
`AutoHotcue` is the one command-input type that lives alongside them, because it
|
||||
is the shape a batch cue placement takes in generic terms.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from .capabilities import CueRole, CueType, MediaKind, PlaylistKind
|
||||
|
||||
|
||||
class HotcueChip(BaseModel):
|
||||
"""One occupied hotcue slot, as the library table previews it.
|
||||
|
||||
Deliberately far smaller than a `CuePoint`: it rides on every `Track` in the
|
||||
whole-library fetch, and a row only needs enough to draw a coloured dot.
|
||||
"""
|
||||
|
||||
slot: int
|
||||
type: CueType = "cue"
|
||||
color: str | None = None # "#RRGGBB" as the platform stored it
|
||||
|
||||
|
||||
class Track(BaseModel):
|
||||
"""A single track in the library, as the app sees it."""
|
||||
|
||||
id: str # the adapter's stable track key; opaque above the adapter
|
||||
artist: str | None = None
|
||||
title: str | None = None
|
||||
album: str | None = None
|
||||
genre: str | None = None
|
||||
label: str | None = None
|
||||
remixer: str | None = None
|
||||
producer: str | None = None
|
||||
mix: str | None = None
|
||||
comment: str | None = None
|
||||
# A second free-text comment. Traktor's "Comment 2", which it keeps only in
|
||||
# the collection (`INFO@RATING` — not the star rating, that is RANKING) and
|
||||
# never writes into the audio file.
|
||||
comment2: str | None = None
|
||||
bpm: float | None = None
|
||||
# The platform's own display string, shown verbatim ("10m", "8A", "Am").
|
||||
key: str | None = None
|
||||
# Camelot wheel position 1-12 + mode, parsed BY THE ADAPTER — notation is
|
||||
# platform knowledge. None when the key is absent or unparseable.
|
||||
key_wheel: int | None = None
|
||||
key_mode: Literal["major", "minor"] | None = None
|
||||
rating: int = 0 # 0-5 stars (derived from RANKING/51)
|
||||
playcount: int | None = None
|
||||
length: int | None = None # seconds
|
||||
bitrate: int | None = None # bits per second (Pioneer libraries store kbps)
|
||||
# ISO-8601 "YYYY-MM-DD", normalised by the adapter.
|
||||
import_date: str | None = None
|
||||
last_played: str | None = None
|
||||
release_date: str | None = None
|
||||
filepath: str | None = None # human-readable OS path
|
||||
cue_count: int = 0
|
||||
hotcue_count: int = 0
|
||||
# The occupied hotcue slots, ordered by slot. Where cues are parsed lazily
|
||||
# (OneLibrary) this is empty until `track_cues()` corrects it, exactly like
|
||||
# `hotcue_count` — the two must always agree.
|
||||
hotcues: list[HotcueChip] = Field(default_factory=list)
|
||||
# 0 = no beatgrid, 1 = constant tempo, >1 = a flexible (multi-tempo) grid.
|
||||
grid_marker_count: int = 0
|
||||
grid_locked: bool = False
|
||||
media_kind: MediaKind = "audio"
|
||||
|
||||
|
||||
class TrackPage(BaseModel):
|
||||
total: int # total matching the filter (before pagination)
|
||||
offset: int
|
||||
limit: int
|
||||
items: list[Track]
|
||||
|
||||
|
||||
class GenreCount(BaseModel):
|
||||
name: str
|
||||
count: int
|
||||
|
||||
|
||||
class Facets(BaseModel):
|
||||
"""Distinct values available for building filter UI."""
|
||||
|
||||
genres: list[GenreCount]
|
||||
keys: list[GenreCount]
|
||||
bpm_min: float | None
|
||||
bpm_max: float | None
|
||||
total_tracks: int
|
||||
|
||||
|
||||
class Stats(BaseModel):
|
||||
total_tracks: int
|
||||
total_playlists: int
|
||||
rated: int
|
||||
unrated: int
|
||||
missing_key: int
|
||||
missing_genre: int
|
||||
missing_bpm: int
|
||||
no_cues: int
|
||||
rating_breakdown: dict[int, int] # stars -> count
|
||||
bpm_histogram: list[dict] # [{bucket: "120-130", count: n}]
|
||||
top_genres: list[GenreCount]
|
||||
|
||||
|
||||
class PlaylistNode(BaseModel):
|
||||
"""A node in the playlist tree.
|
||||
|
||||
`id` is OPAQUE: the adapter mints it and decodes it, and the UI never
|
||||
constructs, parses or prefixes one. `kind` is for choosing an icon — every
|
||||
behavioural question is answered by the flags, so the UI never has to infer
|
||||
what a node can do from what it is called.
|
||||
"""
|
||||
|
||||
id: str
|
||||
name: str
|
||||
kind: PlaylistKind = "playlist"
|
||||
count: int = 0 # track count (for playlists)
|
||||
children: list["PlaylistNode"] = []
|
||||
|
||||
selectable: bool = False # has a static, listable entry set
|
||||
can_add_tracks: bool = False
|
||||
can_reorder: bool = False
|
||||
can_rename: bool = False
|
||||
can_delete: bool = False
|
||||
can_contain_children: bool = False # a valid parent for a new playlist
|
||||
|
||||
|
||||
PlaylistNode.model_rebuild()
|
||||
|
||||
|
||||
# ---- write request bodies ----
|
||||
|
||||
|
||||
class CuePoint(BaseModel):
|
||||
name: str | None = None
|
||||
type: CueType = "cue"
|
||||
# "memory" cues have no bank slot. Only Rekordbox has them, so they are
|
||||
# modelled and preserved but not yet editable anywhere.
|
||||
role: CueRole = "hotcue"
|
||||
start: float # seconds
|
||||
length: float # seconds (>0 for loops)
|
||||
slot: int | None = None # bank slot; None for a cue not in a bank
|
||||
color: str | None = None # "#RRGGBB" as the platform stored it
|
||||
# False when the adapter refuses commands on this cue — the UI gates on THIS
|
||||
# rather than on any platform-specific reason.
|
||||
editable: bool = True
|
||||
readonly_reason: Literal["platform_managed"] | None = None
|
||||
# Index of the grid marker this cue mirrors, where the platform pairs them.
|
||||
# A display hint only; None on platforms that do not.
|
||||
grid_marker: int | None = None
|
||||
|
||||
|
||||
class GridMarker(BaseModel):
|
||||
"""One beatgrid marker. Its position in the list IS its index/identity."""
|
||||
|
||||
start: float # seconds
|
||||
bpm: float # governs from this marker until the next one
|
||||
name: str | None = None # Traktor's label — display only, NOT a discriminator
|
||||
companion: int | None = None # hotcue slot of the paired white cue, if any
|
||||
|
||||
|
||||
class TrackCues(BaseModel):
|
||||
# THE beatgrid, ordered by start. Empty = no grid; one marker = constant
|
||||
# tempo. There is deliberately no scalar bpm/anchor here: a single "the BPM"
|
||||
# is what made flexible grids render and edit wrongly.
|
||||
grid_markers: list[GridMarker] = []
|
||||
grid_locked: bool = False
|
||||
cues: list[CuePoint] = [] # cue/loop markers (grid markers themselves excluded)
|
||||
|
||||
|
||||
class AutoHotcue(BaseModel):
|
||||
"""One cue in a batch placement (Auto Hotcues)."""
|
||||
|
||||
slot: int
|
||||
start: float # seconds
|
||||
name: str | None = None # positional label (e.g. "Drop")
|
||||
type: CueType = "cue"
|
||||
length: float = 0.0 # seconds (>0 for a loop cue)
|
||||
|
||||
|
||||
class LibraryInfo(BaseModel):
|
||||
"""Identity of the loaded library, for display and for composing copy."""
|
||||
|
||||
platform: str
|
||||
name: str # the DJ app's name, e.g. "Traktor"
|
||||
library_label: str # what the user thinks of the artefact as, e.g. "collection.nml"
|
||||
path: str
|
||||
display_name: str # short label for the status bar
|
||||
version: str | None = None
|
||||
|
||||
|
||||
class PlatformOption(BaseModel):
|
||||
"""A platform the picker can offer before any library is open.
|
||||
|
||||
Facts only, never finished sentences: `lib/platformCopy.ts` composes the
|
||||
wording. The distinction that matters is `removable` — a platform with no
|
||||
library found is "not installed" for Traktor and "nothing plugged in" for
|
||||
OneLibrary, and only the driver knows which of those is true.
|
||||
"""
|
||||
|
||||
platform: str
|
||||
name: str
|
||||
library_label: str
|
||||
selects: Literal["file", "directory"] = "file"
|
||||
installed: bool = False
|
||||
#: How many libraries this platform has right now; `installed` is `found > 0`.
|
||||
found: int = 0
|
||||
#: The library lives on a plugged-in drive, so `found` changes between calls.
|
||||
removable: bool = False
|
||||
#: As an export TARGET: its library is only found at a drive's root.
|
||||
drive_root: bool = False
|
||||
#: As an export TARGET: its library is only ever read on a computer, never
|
||||
#: from a drive — so it does nothing beside a stick format.
|
||||
computer_only: bool = False
|
||||
|
||||
|
||||
class RemapSample(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
from_: str = Field(alias="from")
|
||||
to: str
|
||||
exists: bool
|
||||
|
||||
|
||||
class RemapPreview(BaseModel):
|
||||
total: int # tracks with a resolvable location
|
||||
matched: int # how many match the `from` prefix
|
||||
existing: int # of matched, how many exist at the `to` target
|
||||
samples: list[RemapSample] = []
|
||||
# Target paths more than one track would land on. Non-zero means the remap
|
||||
# would be refused: two entries sharing a path corrupt the library.
|
||||
collisions: int = 0
|
||||
collision_samples: list[str] = []
|
||||
|
||||
|
||||
class PrefixGroup(BaseModel):
|
||||
prefix: str # common directory prefix of a group of tracks
|
||||
count: int # tracks sharing it
|
||||
|
||||
|
||||
class PrefixSuggestions(BaseModel):
|
||||
primary: str # best guess for the `from` prefix (largest group)
|
||||
groups: list[PrefixGroup] = [] # alternatives, ranked by count
|
||||
|
||||
|
||||
class RelocationCandidate(BaseModel):
|
||||
"""One place a volume's tracks were found, as a mapping the user can pick."""
|
||||
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
from_: str = Field(alias="from")
|
||||
to: str
|
||||
found: int # of the volume's tracks, how many exist under this mapping
|
||||
|
||||
|
||||
class RelocationVolume(BaseModel):
|
||||
"""A stored volume in which NO track resolves, and where its tracks are now.
|
||||
|
||||
`ambiguous` means more than one candidate resolves most of the volume (a
|
||||
drive and its backup clone): the user chooses, nothing is preselected.
|
||||
"""
|
||||
|
||||
label: str # how the library names the place, e.g. Traktor's "X:"
|
||||
root: str # the stored OS-path prefix
|
||||
total: int
|
||||
status: Literal["found", "ambiguous", "not_found"]
|
||||
candidates: list[RelocationCandidate] = []
|
||||
|
||||
|
||||
class Relocation(BaseModel):
|
||||
"""The open-time missing-files check, pending until the user answers it.
|
||||
|
||||
`scanning` while the search is still running; afterwards `volumes` is empty
|
||||
when there is nothing to ask — every volume resolves, the platform does not
|
||||
take part, or the user has already answered for this open.
|
||||
"""
|
||||
|
||||
scanning: bool = False
|
||||
volumes: list[RelocationVolume] = []
|
||||
|
||||
|
||||
class RelocationApplied(BaseModel):
|
||||
mappings: int
|
||||
tracks: int # how many tracks the applied mappings resolve
|
||||
@@ -0,0 +1,127 @@
|
||||
"""What an MP3's first frame says about where its audio starts.
|
||||
|
||||
A gapless MP3 opens with a HEADER FRAME — a valid MPEG frame whose payload is a
|
||||
`Xing` (VBR) or `Info` (CBR) tag instead of audio — often followed by a LAME
|
||||
extension recording the encoder delay. A gapless decoder (FFmpeg, libsndfile's
|
||||
mpg123, CoreAudio) skips that frame and trims `encoder delay + 529` samples of
|
||||
start padding; a naive one decodes the frame as silence and trims nothing. Where
|
||||
a platform's clock sits relative to Konduktor's decoded time base therefore
|
||||
depends on these facts, per file — which is why they are read here, once, rather
|
||||
than assumed per format.
|
||||
|
||||
Format knowledge, not platform knowledge: this reads bytes and says what is
|
||||
there. What a platform DOES with them lives in that platform's `timebase`.
|
||||
|
||||
Two things are easy to get wrong, and both were got wrong once:
|
||||
* the first frame comes AFTER the ID3v2 tag, which can be megabytes of cover
|
||||
art — a check that only looks at the start of the file sees no header;
|
||||
* the tag sits at a fixed offset after the side information, whose size
|
||||
depends on the MPEG version and channel mode.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
#: The mp3 decoder delay a gapless decoder trims on top of the encoder's.
|
||||
DECODER_DELAY = 529
|
||||
#: Encoder strings whose LAME-style delay field FFmpeg (and mpg123) honour.
|
||||
_TRUSTED_ENCODERS = (b"LAME", b"Lavf", b"Lavc")
|
||||
#: How far past the ID3 tag to look for the first frame (junk, padding).
|
||||
_SCAN = 64 * 1024
|
||||
|
||||
_RATES = {3: (44100, 48000, 32000), 2: (22050, 24000, 16000), 0: (11025, 12000, 8000)}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Mp3Start:
|
||||
sample_rate: int
|
||||
#: Samples in one frame: 1152 for MPEG-1 Layer III, 576 for MPEG-2/2.5.
|
||||
samples_per_frame: int
|
||||
#: The first frame is a Xing/Info/VBRI tag, not audio.
|
||||
header_frame: bool
|
||||
#: Encoder delay from a LAME-style tag a gapless decoder trusts, else None.
|
||||
encoder_delay: int | None
|
||||
|
||||
@property
|
||||
def trimmed(self) -> int:
|
||||
"""Samples of start padding a gapless decoder removes (0 without a
|
||||
trusted delay field: it has nothing to trim by)."""
|
||||
return 0 if self.encoder_delay is None else self.encoder_delay + DECODER_DELAY
|
||||
|
||||
|
||||
def _id3_end(head: bytes) -> int:
|
||||
if head[:3] != b"ID3" or len(head) < 10:
|
||||
return 0
|
||||
size = ((head[6] & 127) << 21) | ((head[7] & 127) << 14) | ((head[8] & 127) << 7) | (head[9] & 127)
|
||||
footer = 10 if head[5] & 0x10 else 0
|
||||
return 10 + size + footer
|
||||
|
||||
|
||||
def _frame_header(b: bytes, i: int):
|
||||
"""(version bits, sample rate, mono) if a Layer III frame header starts at i."""
|
||||
if i + 4 > len(b) or b[i] != 0xFF or (b[i + 1] & 0xE0) != 0xE0:
|
||||
return None
|
||||
version = (b[i + 1] >> 3) & 3
|
||||
layer = (b[i + 1] >> 1) & 3
|
||||
bitrate = b[i + 2] >> 4
|
||||
rate = (b[i + 2] >> 2) & 3
|
||||
if version == 1 or layer != 1 or bitrate in (0, 15) or rate == 3:
|
||||
return None
|
||||
return version, _RATES[version][rate], (b[i + 3] >> 6) == 3
|
||||
|
||||
|
||||
def parse(data: bytes, audio_start: int = 0) -> Mp3Start | None:
|
||||
"""Read the first frame of `data`, whose audio starts at `audio_start`
|
||||
(after any ID3v2 tag). None if no Layer III frame is found."""
|
||||
for i in range(audio_start, min(len(data) - 4, audio_start + _SCAN)):
|
||||
hdr = _frame_header(data, i)
|
||||
if hdr is None:
|
||||
continue
|
||||
version, rate, mono = hdr
|
||||
mpeg1 = version == 3
|
||||
spf = 1152 if mpeg1 else 576
|
||||
side = (17 if mono else 32) if mpeg1 else (9 if mono else 17)
|
||||
x = i + 4 + side
|
||||
tag = data[x:x + 4]
|
||||
if tag in (b"Xing", b"Info"):
|
||||
flags = int.from_bytes(data[x + 4:x + 8], "big")
|
||||
lame = x + 8 + (4 if flags & 1 else 0) + (4 if flags & 2 else 0) \
|
||||
+ (100 if flags & 4 else 0) + (4 if flags & 8 else 0)
|
||||
delay = None
|
||||
if data[lame:lame + 4] in _TRUSTED_ENCODERS and len(data) >= lame + 24:
|
||||
d = data[lame + 21:lame + 24]
|
||||
delay = (d[0] << 4) | (d[1] >> 4)
|
||||
return Mp3Start(rate, spf, True, delay)
|
||||
if data[i + 36:i + 40] == b"VBRI": # Fraunhofer's tag, always at 32 + 4
|
||||
return Mp3Start(rate, spf, True, None)
|
||||
return Mp3Start(rate, spf, False, None)
|
||||
return None
|
||||
|
||||
|
||||
@lru_cache(maxsize=16384)
|
||||
def _read_cached(path: str, size: int, mtime_ns: int) -> Mp3Start | None:
|
||||
with open(path, "rb") as f:
|
||||
head = f.read(10)
|
||||
start = _id3_end(head)
|
||||
f.seek(start)
|
||||
# Enough for the first frame and a scan past junk before it.
|
||||
return parse(f.read(_SCAN + 2048), 0)
|
||||
|
||||
|
||||
def read(path: Path | str | None) -> Mp3Start | None:
|
||||
"""`parse` a file on disk; None when it is missing, unreadable or no MP3.
|
||||
|
||||
Cached per (path, size, mtime), so a file that appears later — a drive
|
||||
plugged in mid-session — or is replaced is read afresh, and a missing one is
|
||||
never remembered as headerless.
|
||||
"""
|
||||
if not path:
|
||||
return None
|
||||
try:
|
||||
st = os.stat(path)
|
||||
return _read_cached(str(path), st.st_size, st.st_mtime_ns)
|
||||
except OSError:
|
||||
return None
|
||||
@@ -0,0 +1,106 @@
|
||||
"""The priming an MP4/M4A's edit list tells a decoder to skip.
|
||||
|
||||
An AAC encoder emits `priming` samples of lead-in before the audio proper —
|
||||
1024 from FFmpeg's `aac`, 2112 from Apple's — and records it as the
|
||||
`media_time` of the audio track's edit list (`moov/trak/edts/elst`). A decoder
|
||||
that honours the edit list (FFmpeg, CoreAudio, Traktor) starts the audio after
|
||||
it; one that ignores it (rekordbox) plays the priming as audio. What a platform
|
||||
does with it lives in that platform's `timebase`; this only reads the box.
|
||||
|
||||
Only box headers are read and `mdat` is seeked past, so `moov` at the END of a
|
||||
file (FFmpeg's default, and every commercial stem file) costs a few reads.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import struct
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
_CONTAINERS = {b"moov", b"trak", b"mdia", b"edts"}
|
||||
|
||||
|
||||
def _boxes(f, start: int, end: int):
|
||||
"""(type, payload offset, payload end) for each box in [start, end)."""
|
||||
pos = start
|
||||
while pos + 8 <= end:
|
||||
f.seek(pos)
|
||||
head = f.read(8)
|
||||
if len(head) < 8:
|
||||
return
|
||||
size, kind = struct.unpack(">I4s", head)
|
||||
body = pos + 8
|
||||
if size == 1:
|
||||
size = struct.unpack(">Q", f.read(8))[0]
|
||||
body = pos + 16
|
||||
elif size == 0:
|
||||
size = end - pos
|
||||
if size < 8:
|
||||
return
|
||||
yield kind, body, min(pos + size, end)
|
||||
pos += size
|
||||
|
||||
|
||||
def _audio_track_priming(f, trak_start: int, trak_end: int) -> tuple[int, int] | None:
|
||||
"""(media_time, media timescale) of one trak if it is audio, else None."""
|
||||
handler = timescale = None
|
||||
media_time = 0 # no edit list: nothing to skip
|
||||
for kind, body, end in _boxes(f, trak_start, trak_end):
|
||||
if kind == b"mdia":
|
||||
for k2, b2, e2 in _boxes(f, body, end):
|
||||
f.seek(b2)
|
||||
if k2 == b"hdlr":
|
||||
handler = f.read(12)[8:12]
|
||||
elif k2 == b"mdhd":
|
||||
version = f.read(1)[0]
|
||||
f.seek(b2 + (20 if version == 1 else 12))
|
||||
timescale = struct.unpack(">I", f.read(4))[0]
|
||||
elif kind == b"edts":
|
||||
for k2, b2, e2 in _boxes(f, body, end):
|
||||
if k2 != b"elst":
|
||||
continue
|
||||
f.seek(b2)
|
||||
version = f.read(1)[0]
|
||||
f.read(3)
|
||||
count = struct.unpack(">I", f.read(4))[0]
|
||||
for _ in range(count):
|
||||
if version == 1:
|
||||
_dur, mt = struct.unpack(">Qq", f.read(16))
|
||||
else:
|
||||
_dur, mt = struct.unpack(">Ii", f.read(8))
|
||||
f.read(4) # media rate
|
||||
if mt >= 0: # -1 is an EMPTY edit (a delay), not a skip
|
||||
media_time = mt
|
||||
break
|
||||
if handler != b"soun" or not timescale:
|
||||
return None
|
||||
return media_time, timescale
|
||||
|
||||
|
||||
@lru_cache(maxsize=16384)
|
||||
def _read_cached(path: str, size: int, mtime_ns: int) -> float | None:
|
||||
with open(path, "rb") as f:
|
||||
for kind, body, end in _boxes(f, 0, size):
|
||||
if kind != b"moov":
|
||||
continue
|
||||
for k2, b2, e2 in _boxes(f, body, end):
|
||||
if k2 == b"trak":
|
||||
found = _audio_track_priming(f, b2, e2)
|
||||
if found is not None: # the FIRST audio track: a stem's master
|
||||
media_time, timescale = found
|
||||
return media_time / timescale
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def priming_seconds(path: Path | str | None) -> float | None:
|
||||
"""Seconds of priming the first audio track's edit list skips (0.0 when it
|
||||
has no edit list); None when the file is missing or not a readable MP4.
|
||||
Cached per (path, size, mtime), like `mp3_gapless.read`."""
|
||||
if not path:
|
||||
return None
|
||||
try:
|
||||
st = os.stat(path)
|
||||
return _read_cached(str(path), st.st_size, st.st_mtime_ns)
|
||||
except (OSError, struct.error, IndexError):
|
||||
return None
|
||||
@@ -13,12 +13,9 @@ step this composes with.
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
_WIN_DRIVE = re.compile(r"^([A-Za-z]:)[\\/](.*)$")
|
||||
_MAC_VOLUME = re.compile(r"^/Volumes/([^/]+)/(.*)$")
|
||||
|
||||
|
||||
def _norm(prefix: str | None) -> str:
|
||||
@@ -84,44 +81,3 @@ def common_dir_prefix(paths: list[str]) -> str:
|
||||
else:
|
||||
break
|
||||
return "/".join(common)
|
||||
|
||||
|
||||
def _traktor_dir(posix_body: str) -> str:
|
||||
"""Convert a POSIX directory body (leading+trailing '/', e.g. '/Music/')
|
||||
to Traktor's '/:'-segmented form ('/:Music/:')."""
|
||||
return posix_body.replace("/", "/:")
|
||||
|
||||
|
||||
def os_path_to_location(os_path: Path) -> tuple[str, str, str]:
|
||||
"""Inverse of ``file_tags.resolve_path``: build a Traktor
|
||||
``(volume, dir, file)`` from an OS path, for the platform implied by the
|
||||
path's shape. Round-trips with ``resolve_path``.
|
||||
|
||||
Used by write-back only; the produced LOCATION is valid for the OS whose
|
||||
path shape it matches (Windows drive, macOS ``/Volumes`` mount, or a POSIX
|
||||
boot path -> ``Macintosh HD``).
|
||||
"""
|
||||
# Derive the filename from the string (not Path.name) so a Windows-style
|
||||
# path is handled even when this runs on a POSIX host, and vice-versa.
|
||||
s = str(os_path)
|
||||
|
||||
m = _WIN_DRIVE.match(s)
|
||||
if m:
|
||||
volume = m.group(1) # e.g. "E:"
|
||||
body = m.group(2).replace("\\", "/") # "Music/x.mp3"
|
||||
name = body.rsplit("/", 1)[-1]
|
||||
dir_body = "/" + body[: len(body) - len(name)] # "/Music/"
|
||||
return volume, _traktor_dir(dir_body), name
|
||||
|
||||
m = _MAC_VOLUME.match(s)
|
||||
if m:
|
||||
volume = m.group(1) # mounted volume name
|
||||
body = m.group(2) # "Music/x.mp3"
|
||||
name = body.rsplit("/", 1)[-1]
|
||||
dir_body = "/" + body[: len(body) - len(name)] # "/Music/"
|
||||
return volume, _traktor_dir(dir_body), name
|
||||
|
||||
# POSIX boot volume, e.g. "/Users/you/Music/x.mp3".
|
||||
name = s.rsplit("/", 1)[-1]
|
||||
dir_body = s[: len(s) - len(name)] # "/Users/you/Music/"
|
||||
return "Macintosh HD", _traktor_dir(dir_body), name
|
||||
@@ -0,0 +1,306 @@
|
||||
"""Where a person keeps things on this computer.
|
||||
|
||||
Two jobs, both of them "ask the OS rather than assume":
|
||||
|
||||
* **Mounted volumes.** Where a drive appears is per-OS and nothing else in the
|
||||
app can work it out. This lives here rather than in the OneLibrary adapter —
|
||||
which is where it grew, because that is the platform whose libraries ARE
|
||||
drives — because "where does this OS mount things" is not adapter knowledge.
|
||||
The file browser needs the same answer, and two scanners would drift.
|
||||
|
||||
* **The user's own folders.** `platformdirs` answers these, and hardcoding
|
||||
them would be wrong on every OS in a different way: `~/Videos` is `Movies`
|
||||
on macOS, Linux's are XDG user-dirs which are user-configurable AND
|
||||
localised, and Windows Known Folders are routinely **relocated by OneDrive**
|
||||
so Documents and Desktop are often not under the home directory at all.
|
||||
|
||||
A place that does not exist is never returned. A file browser offering a Music
|
||||
folder that is not there reads as breakage, whereas its absence reads as an
|
||||
accurate description of the machine.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import string
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import platformdirs
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
#: Entries an OS writes into a volume or folder BY ITSELF — on mount, on
|
||||
#: indexing, or when Finder/Explorer merely browses it. They say nothing about
|
||||
#: whether a person keeps things there, so "is this folder empty?" must not
|
||||
#: count them: a freshly formatted stick mounted once on a Mac is not empty to
|
||||
#: `iterdir()`, and treating it as occupied made its root unexportable.
|
||||
#: Compared case-insensitively — Windows' names are, and FAT/exFAT sticks are.
|
||||
OS_HOUSEKEEPING = frozenset(
|
||||
name.lower()
|
||||
for name in (
|
||||
# macOS
|
||||
".Spotlight-V100", ".fseventsd", ".Trashes", ".TemporaryItems",
|
||||
".DocumentRevisions-V100", ".DS_Store", ".apdisk",
|
||||
".com.apple.timemachine.donotpresent",
|
||||
# Windows
|
||||
"System Volume Information", "$RECYCLE.BIN", "desktop.ini", "Thumbs.db",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def is_os_housekeeping(name: str) -> bool:
|
||||
"""Whether a directory entry is the OS's bookkeeping rather than the user's.
|
||||
|
||||
`._*` are AppleDouble files: macOS writes one beside every file it touches
|
||||
on a volume that cannot hold extended attributes (FAT, exFAT).
|
||||
"""
|
||||
return name.lower() in OS_HOUSEKEEPING or name.startswith("._")
|
||||
|
||||
|
||||
def mount_points() -> list[Path]:
|
||||
"""Every mounted volume's root directory, for this OS.
|
||||
|
||||
Only the ROOTS: a drive can hold tens of thousands of files, and walking a
|
||||
slow USB stick to answer "what is plugged in" is exactly the kind of thing
|
||||
that makes an app feel broken.
|
||||
"""
|
||||
bases: list[Path] = []
|
||||
if sys.platform == "darwin":
|
||||
bases.append(Path("/Volumes"))
|
||||
elif sys.platform.startswith("linux"):
|
||||
bases.extend([Path("/media"), Path("/mnt"), Path("/run/media")])
|
||||
user = os.environ.get("USER")
|
||||
if user:
|
||||
bases.append(Path("/media") / user)
|
||||
bases.append(Path("/run/media") / user)
|
||||
|
||||
roots: list[Path] = []
|
||||
for base in bases:
|
||||
try:
|
||||
if not base.is_dir():
|
||||
continue
|
||||
roots.extend(p for p in base.iterdir() if p.is_dir())
|
||||
except OSError:
|
||||
continue
|
||||
|
||||
if sys.platform == "win32":
|
||||
# No mount-point directory to list: check the drive letters directly.
|
||||
for letter in string.ascii_uppercase:
|
||||
drive = Path(f"{letter}:\\")
|
||||
try:
|
||||
if drive.is_dir():
|
||||
roots.append(drive)
|
||||
except OSError:
|
||||
continue
|
||||
return roots
|
||||
|
||||
|
||||
def _boot_device() -> int | None:
|
||||
try:
|
||||
return Path("/").stat().st_dev
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def is_boot_volume(path: Path) -> bool:
|
||||
"""Whether `path` is the volume the OS itself booted from.
|
||||
|
||||
macOS lists the startup disk in `/Volumes` alongside real removable media,
|
||||
so a "Drives" list that does not filter it leads with a path back to where
|
||||
the user already is. Compared by DEVICE id rather than by name, because
|
||||
`Macintosh HD` is only the default name and is freely renamed.
|
||||
"""
|
||||
boot = _boot_device()
|
||||
if boot is None:
|
||||
return False
|
||||
try:
|
||||
return path.stat().st_dev == boot
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def is_drive_root(path: Path) -> bool:
|
||||
"""Whether `path` is the root of a mounted drive — `/Volumes/STICK`, `E:\\`.
|
||||
|
||||
What a OneLibrary export needs, since a CDJ looks for `PIONEER/` there and
|
||||
nowhere else. A folder that does not exist yet is not one.
|
||||
"""
|
||||
try:
|
||||
return os.path.ismount(Path(path).expanduser())
|
||||
except (OSError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def volumes(*, include_boot: bool = False) -> list[Path]:
|
||||
"""Mounted volumes, newest-mounted order not guaranteed. Sorted by name."""
|
||||
found = [v for v in mount_points() if include_boot or not is_boot_volume(v)]
|
||||
return sorted(set(found), key=lambda p: p.name.lower())
|
||||
|
||||
|
||||
# The user's own folders, in the order a file browser should show them. Music
|
||||
# sits high because this is a DJ app: it is the likeliest destination by far.
|
||||
_USER_DIRS: tuple[tuple[str, str, str], ...] = (
|
||||
("home", "Home", ""),
|
||||
("music", "Music", "user_music_dir"),
|
||||
("desktop", "Desktop", "user_desktop_dir"),
|
||||
("documents", "Documents", "user_documents_dir"),
|
||||
("downloads", "Downloads", "user_downloads_dir"),
|
||||
)
|
||||
|
||||
|
||||
def user_places() -> list[dict]:
|
||||
"""The user's own folders that actually exist on this machine."""
|
||||
out: list[dict] = []
|
||||
seen: set[str] = set()
|
||||
for kind, name, getter in _USER_DIRS:
|
||||
try:
|
||||
path = Path.home() if not getter else Path(getattr(platformdirs, getter)())
|
||||
if not path.is_dir():
|
||||
continue
|
||||
key = str(path)
|
||||
# Windows can resolve two Known Folders to one place; listing it
|
||||
# twice under different names would just look like a bug.
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
out.append({"kind": kind, "name": name, "path": key})
|
||||
except (OSError, AttributeError):
|
||||
continue
|
||||
return out
|
||||
|
||||
|
||||
def volume_places() -> list[dict]:
|
||||
"""Mounted drives, named as the user sees them."""
|
||||
out: list[dict] = []
|
||||
for vol in volumes():
|
||||
try:
|
||||
out.append({"kind": "volume", "name": vol.name or str(vol), "path": str(vol)})
|
||||
except OSError:
|
||||
continue
|
||||
return out
|
||||
|
||||
|
||||
# ---- local vs external drives -------------------------------------------------
|
||||
#
|
||||
# Only the boot disk is identifiable everywhere. Whether ANOTHER volume is an
|
||||
# internal SSD or a USB stick needs the OS's own answer, and where that answer is
|
||||
# not available (or not trustworthy — Windows reports most USB SSDs as "fixed")
|
||||
# a volume is filed as EXTERNAL. Guessing "local" wrongly would present a stick
|
||||
# that is about to be unplugged as a permanent home for referenced tracks.
|
||||
|
||||
# Keyed by (path, st_dev): a volume's answer does not change while it is mounted,
|
||||
# and `diskutil` is a subprocess — too slow to run for every drive on every poll.
|
||||
_mac_info_cache: dict[tuple[str, int], dict] = {}
|
||||
|
||||
|
||||
def _mac_info(path: Path) -> dict:
|
||||
import plistlib
|
||||
import subprocess
|
||||
|
||||
try:
|
||||
key = (str(path), path.stat().st_dev)
|
||||
except OSError:
|
||||
return {}
|
||||
if key not in _mac_info_cache:
|
||||
try:
|
||||
out = subprocess.run(
|
||||
["diskutil", "info", "-plist", str(path)],
|
||||
capture_output=True, timeout=5, check=True,
|
||||
).stdout
|
||||
_mac_info_cache[key] = plistlib.loads(out)
|
||||
except (OSError, subprocess.SubprocessError, plistlib.InvalidFileException, ValueError):
|
||||
_mac_info_cache[key] = {}
|
||||
return _mac_info_cache[key]
|
||||
|
||||
|
||||
def is_internal(path: Path) -> bool:
|
||||
"""Whether a non-boot volume is a drive built into this computer."""
|
||||
if sys.platform != "darwin":
|
||||
return False
|
||||
info = _mac_info(path)
|
||||
return (
|
||||
bool(info.get("Internal"))
|
||||
and not info.get("Ejectable")
|
||||
and not info.get("RemovableMediaOrExternalDevice")
|
||||
and not info.get("RemovableMedia")
|
||||
)
|
||||
|
||||
|
||||
def _is_disk_image(path: Path) -> bool:
|
||||
"""A mounted .dmg (an installer, usually) — a mount, but not a drive."""
|
||||
return sys.platform == "darwin" and _mac_info(path).get("BusProtocol") == "Disk Image"
|
||||
|
||||
|
||||
def drives() -> list[dict]:
|
||||
"""Every drive, split into `local` (boot + internal) and `external`.
|
||||
|
||||
The boot disk's path is the filesystem root, not its `/Volumes` alias: on
|
||||
macOS `/Volumes/Macintosh HD` is a link back to `/`, and browsing through it
|
||||
would show every path twice over.
|
||||
"""
|
||||
out: list[dict] = []
|
||||
boot_seen = False
|
||||
for vol in sorted(set(mount_points()), key=lambda p: p.name.lower()):
|
||||
try:
|
||||
if is_boot_volume(vol):
|
||||
if boot_seen:
|
||||
continue
|
||||
boot_seen = True
|
||||
root = Path(vol.anchor) if sys.platform == "win32" else Path("/")
|
||||
out.append({"name": vol.name or str(vol), "path": str(root), "kind": "local"})
|
||||
continue
|
||||
if _is_disk_image(vol):
|
||||
continue
|
||||
kind = "local" if is_internal(vol) else "external"
|
||||
out.append({"name": vol.name or str(vol), "path": str(vol), "kind": kind})
|
||||
except OSError:
|
||||
continue
|
||||
if not boot_seen and sys.platform != "win32":
|
||||
# Linux mounts nothing for the root filesystem under /media.
|
||||
out.insert(0, {"name": "Computer", "path": "/", "kind": "local"})
|
||||
return out
|
||||
|
||||
|
||||
# ---- what a folder listing should show ----------------------------------------
|
||||
|
||||
_UF_HIDDEN = 0x8000 # macOS/BSD `chflags hidden`: /usr, /bin, /Volumes, …
|
||||
_WIN_HIDDEN = 0x2 | 0x4 # FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM
|
||||
|
||||
|
||||
def is_hidden(entry: os.DirEntry | Path) -> bool:
|
||||
"""Whether a file browser should leave this entry out.
|
||||
|
||||
macOS hides its system folders by FLAG, not by name, so a list of names to
|
||||
skip would be both incomplete and wrong on a renamed volume. The flag is what
|
||||
Finder itself reads.
|
||||
"""
|
||||
name = entry.name
|
||||
if name.startswith(".") or is_os_housekeeping(name):
|
||||
return True
|
||||
try:
|
||||
st = entry.stat(follow_symlinks=False) if isinstance(entry, os.DirEntry) else entry.lstat()
|
||||
except OSError:
|
||||
return True
|
||||
if getattr(st, "st_flags", 0) & _UF_HIDDEN:
|
||||
return True
|
||||
if getattr(st, "st_file_attributes", 0) & _WIN_HIDDEN:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def subfolders(path: Path) -> list[Path]:
|
||||
"""The visible folders directly inside `path`, sorted as Finder would."""
|
||||
out: list[Path] = []
|
||||
try:
|
||||
with os.scandir(path) as it:
|
||||
for entry in it:
|
||||
try:
|
||||
if entry.is_dir(follow_symlinks=True) and not is_hidden(entry):
|
||||
out.append(Path(entry.path))
|
||||
except OSError:
|
||||
continue
|
||||
except OSError:
|
||||
return []
|
||||
return sorted(out, key=lambda p: p.name.lower())
|
||||
@@ -0,0 +1,195 @@
|
||||
"""Query, facet and statistics layer over the generic model.
|
||||
|
||||
This is deliberately platform-independent: it reads nothing but `Track`
|
||||
attributes. Keeping it in `core` rather than per-adapter is what stops "sort by
|
||||
artist" quietly meaning different things on different platforms behind one UI —
|
||||
if a filter needs something the projection cannot express, the fix is to add the
|
||||
field to the projection, where every adapter must then answer for it.
|
||||
|
||||
An adapter owns its `TrackIndex` instance and refreshes it after each command.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
|
||||
from .model import Facets, GenreCount, Stats, Track, TrackPage
|
||||
|
||||
|
||||
class TrackIndex:
|
||||
"""An ordered list of projected tracks plus a primary-key index."""
|
||||
|
||||
def __init__(self, tracks: list[Track] | None = None):
|
||||
self._lock = threading.Lock()
|
||||
self.tracks: list[Track] = []
|
||||
self.by_key: dict[str, Track] = {}
|
||||
if tracks is not None:
|
||||
self.rebuild(tracks)
|
||||
|
||||
def rebuild(self, tracks: list[Track]) -> None:
|
||||
"""Replace the whole projection — after a save or a path remap, where
|
||||
track ids themselves may have changed."""
|
||||
with self._lock:
|
||||
self.tracks = tracks
|
||||
self.by_key = {t.id: t for t in tracks}
|
||||
|
||||
def all(self) -> list[Track]:
|
||||
return self.tracks
|
||||
|
||||
def get(self, track_id: str) -> Track | None:
|
||||
return self.by_key.get(track_id)
|
||||
|
||||
def add(self, track: Track) -> None:
|
||||
"""Put a track the projection has never seen into it.
|
||||
|
||||
`replace` deliberately ignores an unknown id — it exists to refresh, and
|
||||
silently inventing a track would hide a bug. Adding is a different
|
||||
intent and needs saying out loud, which is why importing a track needs
|
||||
this rather than being able to reuse `replace`.
|
||||
|
||||
An id that is already present is refreshed instead of duplicated:
|
||||
`by_key` could not represent two, so appending would desynchronise it
|
||||
from `tracks`.
|
||||
"""
|
||||
with self._lock:
|
||||
if track.id in self.by_key:
|
||||
self.replace(track)
|
||||
return
|
||||
self.tracks.append(track)
|
||||
self.by_key[track.id] = track
|
||||
|
||||
def replace(self, track: Track) -> None:
|
||||
"""Refresh one track's projection in place.
|
||||
|
||||
Mutating the existing object rather than replacing it keeps `tracks`,
|
||||
`by_key` and any list a caller is already holding consistent.
|
||||
"""
|
||||
old = self.by_key.get(track.id)
|
||||
if old is None:
|
||||
return
|
||||
for field in type(track).model_fields:
|
||||
setattr(old, field, getattr(track, field))
|
||||
|
||||
_SORT_KEYS = {
|
||||
"artist": lambda t: (t.artist or "").lower(),
|
||||
"title": lambda t: (t.title or "").lower(),
|
||||
"album": lambda t: (t.album or "").lower(),
|
||||
"genre": lambda t: (t.genre or "").lower(),
|
||||
"key": lambda t: (t.key or ""),
|
||||
"bpm": lambda t: (t.bpm if t.bpm is not None else -1),
|
||||
"rating": lambda t: t.rating,
|
||||
"playcount": lambda t: (t.playcount or 0),
|
||||
"import_date": lambda t: (t.import_date or ""),
|
||||
"length": lambda t: (t.length or 0),
|
||||
}
|
||||
|
||||
def query_tracks(
|
||||
self,
|
||||
q: str | None = None,
|
||||
genre: str | None = None,
|
||||
key: str | None = None,
|
||||
bpm_min: float | None = None,
|
||||
bpm_max: float | None = None,
|
||||
rating_min: int | None = None,
|
||||
has_cues: bool | None = None,
|
||||
sort: str = "artist",
|
||||
order: str = "asc",
|
||||
limit: int = 100,
|
||||
offset: int = 0,
|
||||
) -> TrackPage:
|
||||
items = self.tracks
|
||||
if q:
|
||||
ql = q.lower()
|
||||
items = [
|
||||
t
|
||||
for t in items
|
||||
if (t.artist and ql in t.artist.lower())
|
||||
or (t.title and ql in t.title.lower())
|
||||
or (t.album and ql in t.album.lower())
|
||||
]
|
||||
if genre:
|
||||
items = [t for t in items if t.genre == genre]
|
||||
if key:
|
||||
items = [t for t in items if t.key == key]
|
||||
if bpm_min is not None:
|
||||
items = [t for t in items if t.bpm is not None and t.bpm >= bpm_min]
|
||||
if bpm_max is not None:
|
||||
items = [t for t in items if t.bpm is not None and t.bpm <= bpm_max]
|
||||
if rating_min is not None:
|
||||
items = [t for t in items if t.rating >= rating_min]
|
||||
if has_cues is not None:
|
||||
items = [t for t in items if (t.cue_count > 0) == has_cues]
|
||||
|
||||
keyfn = self._SORT_KEYS.get(sort, self._SORT_KEYS["artist"])
|
||||
items = sorted(items, key=keyfn, reverse=(order == "desc"))
|
||||
|
||||
total = len(items)
|
||||
page = items[offset : offset + limit]
|
||||
return TrackPage(total=total, offset=offset, limit=limit, items=page)
|
||||
|
||||
def facets(self) -> Facets:
|
||||
genres: dict[str, int] = {}
|
||||
keys: dict[str, int] = {}
|
||||
bpms = []
|
||||
for t in self.tracks:
|
||||
if t.genre:
|
||||
genres[t.genre] = genres.get(t.genre, 0) + 1
|
||||
if t.key:
|
||||
keys[t.key] = keys.get(t.key, 0) + 1
|
||||
if t.bpm is not None:
|
||||
bpms.append(t.bpm)
|
||||
return Facets(
|
||||
genres=[
|
||||
GenreCount(name=k, count=v)
|
||||
for k, v in sorted(genres.items(), key=lambda x: -x[1])
|
||||
],
|
||||
keys=[
|
||||
GenreCount(name=k, count=v)
|
||||
for k, v in sorted(keys.items(), key=lambda x: -x[1])
|
||||
],
|
||||
bpm_min=min(bpms) if bpms else None,
|
||||
bpm_max=max(bpms) if bpms else None,
|
||||
total_tracks=len(self.tracks),
|
||||
)
|
||||
|
||||
def stats(self, playlist_count: int) -> Stats:
|
||||
rating_breakdown = {i: 0 for i in range(6)}
|
||||
genres: dict[str, int] = {}
|
||||
bpm_buckets: dict[str, int] = {}
|
||||
rated = missing_key = missing_genre = missing_bpm = no_cues = 0
|
||||
for t in self.tracks:
|
||||
rating_breakdown[t.rating] += 1
|
||||
if t.rating > 0:
|
||||
rated += 1
|
||||
if not t.key:
|
||||
missing_key += 1
|
||||
if not t.genre:
|
||||
missing_genre += 1
|
||||
else:
|
||||
genres[t.genre] = genres.get(t.genre, 0) + 1
|
||||
if t.bpm is None:
|
||||
missing_bpm += 1
|
||||
else:
|
||||
lo = int(t.bpm // 10 * 10)
|
||||
bucket = f"{lo}-{lo + 10}"
|
||||
bpm_buckets[bucket] = bpm_buckets.get(bucket, 0) + 1
|
||||
if t.cue_count == 0:
|
||||
no_cues += 1
|
||||
total = len(self.tracks)
|
||||
histogram = [
|
||||
{"bucket": b, "count": c}
|
||||
for b, c in sorted(bpm_buckets.items(), key=lambda x: int(x[0].split("-")[0]))
|
||||
]
|
||||
top = sorted(genres.items(), key=lambda x: -x[1])[:10]
|
||||
return Stats(
|
||||
total_tracks=total,
|
||||
total_playlists=playlist_count,
|
||||
rated=rated,
|
||||
unrated=total - rated,
|
||||
missing_key=missing_key,
|
||||
missing_genre=missing_genre,
|
||||
missing_bpm=missing_bpm,
|
||||
no_cues=no_cues,
|
||||
rating_breakdown=rating_breakdown,
|
||||
bpm_histogram=histogram,
|
||||
top_genres=[GenreCount(name=k, count=v) for k, v in top],
|
||||
)
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Which adapter can open a given path.
|
||||
|
||||
Selection is a ``can_open()`` probe, not an extension match. That matters as soon
|
||||
as a second platform exists: Rekordbox's library is a SQLite file called
|
||||
``master.db`` and Serato's is a ``_Serato_`` *directory*, so neither can be
|
||||
recognised by suffix alone, and a probe lets an adapter be as specific as it
|
||||
needs to be (Traktor's reads 4 KB and looks for the NML header).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from .adapter import LibraryDriver, LibraryNotSupported
|
||||
|
||||
_DRIVERS: list[LibraryDriver] = []
|
||||
|
||||
|
||||
def register(driver: LibraryDriver) -> None:
|
||||
"""Register a platform. Called once per adapter package, at import."""
|
||||
if not any(d.platform == driver.platform for d in _DRIVERS):
|
||||
_DRIVERS.append(driver)
|
||||
|
||||
|
||||
def drivers() -> list[LibraryDriver]:
|
||||
return list(_DRIVERS)
|
||||
|
||||
|
||||
def driver_by_platform(platform: str) -> LibraryDriver:
|
||||
"""The driver for a platform name, e.g. ``"traktor"``."""
|
||||
for d in _DRIVERS:
|
||||
if d.platform == platform:
|
||||
return d
|
||||
raise LibraryNotSupported(f"No adapter registered for platform {platform!r}")
|
||||
|
||||
|
||||
def driver_for(path: Path) -> LibraryDriver:
|
||||
"""The first registered driver that recognises `path`."""
|
||||
for d in _DRIVERS:
|
||||
try:
|
||||
if d.can_open(path):
|
||||
return d
|
||||
except OSError:
|
||||
continue
|
||||
raise LibraryNotSupported(f"No DJ library Konduktor recognises at {path}")
|
||||
|
||||
|
||||
def open_library(path: Path):
|
||||
return driver_for(path).open(path)
|
||||
|
||||
|
||||
def describe(path: Path) -> dict:
|
||||
"""Describe a library path using whichever adapter recognises it.
|
||||
|
||||
Used for the picker's "last opened" shortcut, which must still render when
|
||||
the file has since been moved or deleted — so an unrecognised path gets a
|
||||
plain description with ``exists`` false rather than an error.
|
||||
"""
|
||||
try:
|
||||
return driver_for(path).describe(path)
|
||||
except (LibraryNotSupported, OSError):
|
||||
pass
|
||||
try:
|
||||
exists = path.is_file()
|
||||
except OSError:
|
||||
exists = False
|
||||
return {
|
||||
"path": str(path),
|
||||
"label": path.name,
|
||||
"version": None,
|
||||
"modified": None,
|
||||
"exists": exists,
|
||||
}
|
||||
|
||||
|
||||
def detect_for(platform: str) -> list:
|
||||
"""Every library one platform has right now, best first.
|
||||
|
||||
The picker asks which platform FIRST, so detection is scoped to the answer.
|
||||
Unscoped detection (``detect_all``) concatenates drivers in registration
|
||||
order, which made "the best candidate" mean "whatever the first-registered
|
||||
driver found" — with a removable drive registered first, a plugged-in stick
|
||||
could be offered as the user's collection.
|
||||
"""
|
||||
try:
|
||||
return driver_by_platform(platform).detect()
|
||||
except (LibraryNotSupported, OSError):
|
||||
return []
|
||||
|
||||
|
||||
def detect_all() -> list:
|
||||
"""Every library found in the platforms' default install locations."""
|
||||
out: list = []
|
||||
for d in _DRIVERS:
|
||||
try:
|
||||
out.extend(d.detect())
|
||||
except OSError:
|
||||
continue
|
||||
return out
|
||||
|
||||
|
||||
def browsable_suffixes(platform: str | None = None) -> tuple[str, ...]:
|
||||
"""File extensions the in-app browser should show, for one platform or all.
|
||||
|
||||
A platform that selects a DIRECTORY contributes nothing, even though it has
|
||||
suffixes: its libraries are not the thing a user picks, so listing them
|
||||
would offer a file the browser's Open cannot act on.
|
||||
"""
|
||||
try:
|
||||
targets = [driver_by_platform(platform)] if platform else _DRIVERS
|
||||
except LibraryNotSupported:
|
||||
targets = []
|
||||
seen: list[str] = []
|
||||
for d in targets:
|
||||
if getattr(d, "selects", "file") != "file":
|
||||
continue
|
||||
for suffix in d.suffixes:
|
||||
if suffix not in seen:
|
||||
seen.append(suffix)
|
||||
return tuple(seen)
|
||||
@@ -0,0 +1,187 @@
|
||||
"""Finding where a library's audio went: the search behind auto path remapping.
|
||||
|
||||
A library stores absolute paths, and they go stale in ways a DJ does not think
|
||||
of as "moving" anything: the collection on an SSD was built on Windows where the
|
||||
drive was `X:`, and on a Mac the same drive is `/Volumes/MiniSSD`. Every track
|
||||
then reads as missing, though nothing moved. That is what this module fixes,
|
||||
and ALL it fixes — a prefix changed, the layout underneath did not. A user who
|
||||
reorganised their folders needs a relocate-by-filename feature, which this is
|
||||
not.
|
||||
|
||||
The search is by SAMPLING, never by walking a drive: a drive can hold hundreds
|
||||
of thousands of files, and a stat of a path that is not there costs next to
|
||||
nothing. For each group of tracks that share a stored root, a sample of tracks
|
||||
is tried against each candidate root (the mounted drives, the home folder),
|
||||
dropping leading folders one at a time, and the roots that resolve them are
|
||||
counted. The winner is then verified against the WHOLE group, because a count
|
||||
the user is asked to confirm should be the real one.
|
||||
|
||||
Which groups to search is the adapter's business, not this module's: only the
|
||||
adapter knows how its stored paths resolve, including through a mapping the
|
||||
user already saved. It hands over the groups in which NO track resolves — the
|
||||
threshold is "none", so a volume missing a few deleted files never prompts.
|
||||
|
||||
Two candidates that both resolve most of a group (a drive and its backup clone)
|
||||
are reported as AMBIGUOUS rather than ranked: which one the user meant is not a
|
||||
question sample counts can answer, and a wrong guess would silently play and
|
||||
tag files on the wrong drive.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from .pathmap import PathMapping
|
||||
|
||||
#: Tracks sampled per group. Enough that a drive holding a partial copy loses
|
||||
#: clearly to one holding all of it; few enough that a group costs milliseconds.
|
||||
SAMPLE = 50
|
||||
|
||||
#: How many leading folders may be dropped from a stored path. Covers
|
||||
#: `/Users/<name>/Music/<library>`-deep moves with room to spare.
|
||||
MAX_DROP = 8
|
||||
|
||||
#: A runner-up resolving at least this share of the winner's tracks makes the
|
||||
#: group ambiguous.
|
||||
AMBIGUOUS_SHARE = 0.5
|
||||
|
||||
_SEP = re.compile(r"[\\/]")
|
||||
|
||||
|
||||
@dataclass
|
||||
class PathGroup:
|
||||
"""Tracks whose stored paths share a root the library names as one place.
|
||||
|
||||
`root` is the OS-path prefix every path starts with (`X:`, `/Volumes/SSD`,
|
||||
`/`); `label` is how the library itself names that place, for the UI.
|
||||
`paths` are the STORED paths — before any mapping.
|
||||
"""
|
||||
|
||||
label: str
|
||||
root: str
|
||||
paths: list[str]
|
||||
|
||||
|
||||
@dataclass
|
||||
class Candidate:
|
||||
"""A mapping that resolves some of a group, with how many it resolves."""
|
||||
|
||||
mapping: PathMapping
|
||||
found: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class Proposal:
|
||||
"""What the search concluded about one group."""
|
||||
|
||||
label: str
|
||||
root: str
|
||||
total: int
|
||||
#: Best first. Empty when nothing was found.
|
||||
candidates: list[Candidate] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def status(self) -> str:
|
||||
if not self.candidates:
|
||||
return "not_found"
|
||||
if len(self.candidates) > 1:
|
||||
return "ambiguous"
|
||||
return "found"
|
||||
|
||||
|
||||
def _split(path: str, root: str) -> tuple[list[str], str] | None:
|
||||
"""A stored path's folders below `root`, and its filename."""
|
||||
if not path.startswith(root):
|
||||
return None
|
||||
segs = [s for s in _SEP.split(path[len(root):]) if s]
|
||||
if not segs:
|
||||
return None
|
||||
return segs[:-1], segs[-1]
|
||||
|
||||
|
||||
def _from_prefix(root: str, path: str, dropped: list[str]) -> str:
|
||||
"""The stored prefix a mapping must replace: `root` plus the dropped folders,
|
||||
spelled with the separator the stored path uses, so it matches it."""
|
||||
if not dropped:
|
||||
return root
|
||||
rest = path[len(root):]
|
||||
sep = "\\" if "\\" in rest and "/" not in rest else "/"
|
||||
return root.rstrip("/\\") + sep + sep.join(dropped)
|
||||
|
||||
|
||||
def _sample(paths: list[str], n: int) -> list[str]:
|
||||
"""`n` paths spread evenly over the group, so one album is not the sample."""
|
||||
if len(paths) <= n:
|
||||
return list(paths)
|
||||
step = len(paths) / n
|
||||
return [paths[int(i * step)] for i in range(n)]
|
||||
|
||||
|
||||
def _hits(path: str, root: str, roots: list[Path]) -> set[tuple[str, str]]:
|
||||
"""Every (from, to) mapping that resolves this one stored path, at the
|
||||
SHALLOWEST drop that resolves it at all — dropping more folders only makes a
|
||||
match likelier to be a coincidence."""
|
||||
split = _split(path, root)
|
||||
if split is None:
|
||||
return set()
|
||||
dirs, name = split
|
||||
# A bare filesystem root cannot be a mapping's `from` (it would match every
|
||||
# path), so a group rooted at `/` starts by dropping one folder. And at
|
||||
# least one folder must survive the drop: a filename alone at a drive's
|
||||
# root is far too weak to call a match.
|
||||
first = 1 if not root.strip("/\\") else 0
|
||||
last = min(MAX_DROP, max(len(dirs) - 1, 0))
|
||||
for drop in range(first, last + 1):
|
||||
found = set()
|
||||
for base in roots:
|
||||
try:
|
||||
if base.joinpath(*dirs[drop:], name).exists():
|
||||
found.add((_from_prefix(root, path, dirs[:drop]), str(base)))
|
||||
except OSError:
|
||||
continue
|
||||
if found:
|
||||
return found
|
||||
return set()
|
||||
|
||||
|
||||
def _resolves(mapping: PathMapping, paths: list[str]) -> int:
|
||||
n = 0
|
||||
for p in paths:
|
||||
target = mapping.apply(Path(p))
|
||||
try:
|
||||
if str(target) != p and target.exists():
|
||||
n += 1
|
||||
except OSError:
|
||||
continue
|
||||
return n
|
||||
|
||||
|
||||
def search(groups: list[PathGroup], roots: list[Path]) -> list[Proposal]:
|
||||
"""Where each group's tracks are now, if anywhere among `roots`."""
|
||||
roots = list(dict.fromkeys(Path(r) for r in roots))
|
||||
out: list[Proposal] = []
|
||||
for group in groups:
|
||||
sample = _sample(group.paths, SAMPLE)
|
||||
votes: dict[tuple[str, str], int] = {}
|
||||
for p in sample:
|
||||
for hit in _hits(p, group.root, roots):
|
||||
votes[hit] = votes.get(hit, 0) + 1
|
||||
# One sampled track is a coincidence (a common filename in a common
|
||||
# folder name); a group too small to sample three is taken on one.
|
||||
floor = min(3, len(sample))
|
||||
ranked = sorted(
|
||||
(h for h, n in votes.items() if n >= floor), key=lambda h: -votes[h]
|
||||
)[:3]
|
||||
candidates = []
|
||||
for from_, to in ranked:
|
||||
mapping = PathMapping.make(from_, to)
|
||||
found = _resolves(mapping, group.paths)
|
||||
if found:
|
||||
candidates.append(Candidate(mapping, found))
|
||||
candidates.sort(key=lambda c: -c.found)
|
||||
if candidates:
|
||||
best = candidates[0].found
|
||||
candidates = [c for c in candidates if c.found >= best * AMBIGUOUS_SHARE]
|
||||
out.append(Proposal(group.label, group.root, len(group.paths), candidates))
|
||||
return out
|
||||
@@ -0,0 +1,447 @@
|
||||
"""Write a native-instruments STEM file (`.stem.m4a`) from a source track.
|
||||
|
||||
The file layout is measured, not guessed, and matches the user's commercial
|
||||
stem files (see the stem-conversion discussion log): an `ipod` MP4 with FIVE
|
||||
AAC-LC stereo 44.1 kHz streams — stream 0 the full mix and 1-4 drums / bass /
|
||||
synths / vox — streams 1-4 not enabled (`disposition` 0, so a player that knows
|
||||
nothing of stems plays the mix), and a `moov/udta/stem` box holding JSON that
|
||||
names and colours the stems. Traktor 4.5 loads such a file as stems and honours
|
||||
the MP4 edit list, so a stem file's time base is the decoded audio's own.
|
||||
|
||||
Platform-independent on purpose: the separation itself is a callback
|
||||
(`separate`) so this module never imports torch — the stem ENGINE supplies it
|
||||
in production, and the tests use a fake one. Konduktor's backend owns decode,
|
||||
encode, mux, tags and verification, where they are testable on any machine.
|
||||
|
||||
Things that were measured and are easy to get wrong:
|
||||
* **Mono sources are duplicated by hand.** FFmpeg's resampler upmixes mono to
|
||||
stereo at -3 dB (0.5 -> 0.354), which would make a converted mono track
|
||||
quieter than its source.
|
||||
* **Resampling does not move time**: a 48 kHz impulse at 1.000 s lands on
|
||||
sample 44100 exactly. Tested, because a shift here would move every cue.
|
||||
* **Both encoders are sample-exact on timing** (`aac` primes 1024 samples,
|
||||
Apple's `aac_at` 2112, both recorded in the edit list), but each decodes a
|
||||
little LONGER than the input — the last frame's padding (up to one frame for
|
||||
`aac`, ~2 for `aac_at`). So the length check allows 0..2048 extra samples,
|
||||
and the duration reported to the collection is the SOURCE's.
|
||||
* **Two JSON serialisations, one object.** The file's `stem` box is written
|
||||
the way the commercial files write it (Python's default `json.dumps`: key
|
||||
order kept, `4.0`, 17-digit floats) and Traktor's `<STEMS>` element the way
|
||||
Traktor writes it (sorted keys, `4`, 16 digits — the one value on all 3,678
|
||||
stem entries of the real collection). Neither can be derived from the other
|
||||
byte for byte — Traktor's 16 digits do not even round-trip the same double —
|
||||
so both are literals, and a test proves they hold the same float32 values
|
||||
(the precision NI stores them at: 0.02f, 0.14f, 0.05f).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import fractions
|
||||
import json
|
||||
import struct
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import numpy as np
|
||||
|
||||
from . import mp4_edit, tag_copy
|
||||
|
||||
SR = 44100
|
||||
FRAME = 1024 # AAC-LC frame size, for both encoders
|
||||
#: The stem slots, in file order after the mix. Demucs names its outputs
|
||||
#: drums / bass / other / vocals; "other" is what NI calls Synths.
|
||||
STEM_NAMES = ("Drums", "Bass", "Synths", "Vox")
|
||||
DEMUCS_ORDER = ("drums", "bass", "other", "vocals")
|
||||
|
||||
#: The `moov/udta/stem` box payload, byte for byte as the commercial files have it.
|
||||
STEM_BOX_JSON = (
|
||||
b'{"mastering_dsp": {"compressor": {"ratio": 4.0, "output_gain": 0.0, "enabled": false, '
|
||||
b'"threshold": 0.0, "attack": 0.019999999552965164, "input_gain": 0.0, "release": '
|
||||
b'0.14000000059604645, "hp_cutoff": 50, "dry_wet": 50}, "limiter": {"release": '
|
||||
b'0.05000000074505806, "threshold": 0.0, "ceiling": 0.0, "enabled": false}}, "version": 1, '
|
||||
b'"stems": [{"color": "#FD4A4A", "name": "Drums"}, {"color": "#FFFF00", "name": "Bass"}, '
|
||||
b'{"color": "#00E8E8", "name": "Synths"}, {"color": "#AD65FF", "name": "Vox"}]}'
|
||||
)
|
||||
#: Traktor's `<ENTRY><STEMS STEMS="…">` value for the same object, as Traktor writes it.
|
||||
NML_STEMS_JSON = (
|
||||
'{"mastering_dsp":{"compressor":{"attack":0.01999999955296516,"dry_wet":50,"enabled":false,'
|
||||
'"hp_cutoff":50,"input_gain":0,"output_gain":0,"ratio":4,"release":0.1400000005960464,'
|
||||
'"threshold":0},"limiter":{"ceiling":0,"enabled":false,"release":0.05000000074505806,'
|
||||
'"threshold":0}},"stems":[{"color":"#FD4A4A","name":"Drums"},{"color":"#FFFF00","name":"Bass"},'
|
||||
'{"color":"#00E8E8","name":"Synths"},{"color":"#AD65FF","name":"Vox"}],"version":1}'
|
||||
)
|
||||
|
||||
#: Codecs whose source counts as lossless for the bitrate rule.
|
||||
_LOSSLESS = ("flac", "alac", "wavpack", "tta", "ape", "truehd", "mlp")
|
||||
#: Output bitrate: sources below 256 kbps get 256 (AAC below that is audible on a
|
||||
#: soloed stem), everything else — and every lossless source — 320.
|
||||
_FLOOR, _TOP = 256_000, 320_000
|
||||
#: Decoded length may exceed the source by the encoders' final-frame padding.
|
||||
_LENGTH_SLACK = 2 * FRAME
|
||||
|
||||
|
||||
class StemFileError(Exception):
|
||||
"""The file could not be written, or failed verification. User-facing."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Source:
|
||||
"""A decoded source: stereo float32 at 44.1 kHz, plus what the bitrate rule
|
||||
and the collection need to know about the original."""
|
||||
|
||||
pcm: np.ndarray # shape (2, n), float32 — NOT clamped (masters exceed 0 dBFS)
|
||||
codec: str
|
||||
bit_rate: int | None # bps, as the container/stream reports it
|
||||
|
||||
@property
|
||||
def samples(self) -> int:
|
||||
return int(self.pcm.shape[1])
|
||||
|
||||
@property
|
||||
def lossless(self) -> bool:
|
||||
return self.codec.startswith("pcm_") or self.codec in _LOSSLESS
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Written:
|
||||
"""What a finished stem file is, for the collection entry that points at it."""
|
||||
|
||||
path: Path
|
||||
bit_rate: int # bps per stream, as encoded
|
||||
duration: float # seconds, the SOURCE's (see the module notes)
|
||||
size: int # bytes
|
||||
tags: dict
|
||||
|
||||
|
||||
def default_encoder() -> str:
|
||||
"""Apple's AudioToolbox encoder on macOS (the better AAC encoder there),
|
||||
FFmpeg's own elsewhere. Both are timing-exact in Traktor (kit 1)."""
|
||||
import av
|
||||
|
||||
return "aac_at" if sys.platform == "darwin" and "aac_at" in av.codecs_available else "aac"
|
||||
|
||||
|
||||
def choose_bitrate(source: Source) -> int:
|
||||
if source.lossless or not source.bit_rate:
|
||||
return _TOP
|
||||
return _FLOOR if source.bit_rate < _FLOOR else _TOP
|
||||
|
||||
|
||||
def decode(path: Path | str) -> Source:
|
||||
"""Decode the first audio stream to stereo float32 at 44.1 kHz."""
|
||||
import av
|
||||
|
||||
with av.open(str(path), metadata_errors="ignore") as container:
|
||||
stream = container.streams.audio[0]
|
||||
codec = stream.codec_context.name
|
||||
bit_rate = stream.bit_rate or container.bit_rate or None
|
||||
channels = stream.codec_context.channels
|
||||
# Mono stays mono through the resampler and is duplicated below (see the
|
||||
# module notes); anything wider is downmixed by it.
|
||||
layout = "mono" if channels == 1 else "stereo"
|
||||
resampler = av.AudioResampler(format="fltp", layout=layout, rate=SR)
|
||||
chunks = [f.to_ndarray() for frame in container.decode(stream) for f in resampler.resample(frame)]
|
||||
chunks += [f.to_ndarray() for f in resampler.resample(None)]
|
||||
if not chunks:
|
||||
raise StemFileError("The file has no audio to convert")
|
||||
pcm = np.concatenate(chunks, axis=1).astype(np.float32, copy=False)
|
||||
if pcm.shape[0] == 1:
|
||||
pcm = np.repeat(pcm, 2, axis=0)
|
||||
return Source(pcm=np.ascontiguousarray(pcm), codec=codec, bit_rate=bit_rate)
|
||||
|
||||
|
||||
def _encode(fp, tracks: list[np.ndarray], *, bit_rate: int, encoder: str,
|
||||
checkpoint: Callable[[], None] | None) -> None:
|
||||
"""Mux five AAC streams IN LOCKSTEP — one frame of each in turn — so the
|
||||
muxer never buffers a whole stream (which it would if they came one after
|
||||
another)."""
|
||||
import av
|
||||
|
||||
n = tracks[0].shape[1]
|
||||
tb = fractions.Fraction(1, SR)
|
||||
container = av.open(fp, "w", format="ipod")
|
||||
try:
|
||||
streams = []
|
||||
for k in range(len(tracks)):
|
||||
s = container.add_stream(encoder, rate=SR, layout="stereo")
|
||||
s.bit_rate = bit_rate
|
||||
if k:
|
||||
s.disposition = 0 # present, not enabled: a plain player plays the mix
|
||||
streams.append(s)
|
||||
for i, offset in enumerate(range(0, n, FRAME)):
|
||||
if checkpoint is not None and i % 512 == 0:
|
||||
checkpoint()
|
||||
for s, x in zip(streams, tracks):
|
||||
frame = av.AudioFrame.from_ndarray(
|
||||
np.ascontiguousarray(x[:, offset:offset + FRAME], dtype=np.float32),
|
||||
format="fltp", layout="stereo",
|
||||
)
|
||||
frame.sample_rate, frame.pts, frame.time_base = SR, offset, tb
|
||||
for packet in s.encode(frame):
|
||||
container.mux(packet)
|
||||
for s in streams:
|
||||
for packet in s.encode(None):
|
||||
container.mux(packet)
|
||||
finally:
|
||||
container.close()
|
||||
|
||||
|
||||
def _find(f, start: int, end: int, kind: bytes):
|
||||
for k, body, box_end in mp4_edit._boxes(f, start, end):
|
||||
if k == kind:
|
||||
return body - 8, body, box_end # header offset, payload, end
|
||||
return None
|
||||
|
||||
|
||||
def add_stem_box(path: Path | str) -> None:
|
||||
"""Append the `stem` box to `moov/udta` in place.
|
||||
|
||||
Only valid when `moov` is the file's LAST box, which it is for what `_encode`
|
||||
writes (FFmpeg's default): then growing it moves no media data, so no chunk
|
||||
offset changes and only the sizes of `moov` and `udta` need patching. The
|
||||
box header is always 32-bit here (`moov` is far below 4 GiB).
|
||||
"""
|
||||
path = Path(path)
|
||||
size = path.stat().st_size
|
||||
box = struct.pack(">I4s", 8 + len(STEM_BOX_JSON), b"stem") + STEM_BOX_JSON
|
||||
with open(path, "r+b") as f:
|
||||
moov = _find(f, 0, size, b"moov")
|
||||
if moov is None or moov[2] != size:
|
||||
raise StemFileError("Unexpected MP4 layout: the index is not at the end of the file")
|
||||
moov_at, moov_body, _ = moov
|
||||
f.seek(moov_at)
|
||||
data = bytearray(f.read(size - moov_at))
|
||||
udta = _find(f, moov_body, size, b"udta")
|
||||
if udta is not None:
|
||||
u_at, _u_body, u_end = (x - moov_at for x in udta)
|
||||
data[u_end:u_end] = box
|
||||
struct.pack_into(">I", data, u_at, u_end - u_at + len(box))
|
||||
grow = len(box)
|
||||
else:
|
||||
wrapped = struct.pack(">I4s", 8 + len(box), b"udta") + box
|
||||
data += wrapped
|
||||
grow = len(wrapped)
|
||||
struct.pack_into(">I", data, 0, struct.unpack_from(">I", data, 0)[0] + grow)
|
||||
f.seek(moov_at)
|
||||
f.write(data)
|
||||
|
||||
|
||||
def read_stem_box(path: Path | str) -> bytes | None:
|
||||
"""The `moov/udta/stem` payload, or None."""
|
||||
path = Path(path)
|
||||
size = path.stat().st_size
|
||||
with open(path, "rb") as f:
|
||||
moov = _find(f, 0, size, b"moov")
|
||||
if moov is None:
|
||||
return None
|
||||
udta = _find(f, moov[1], moov[2], b"udta")
|
||||
if udta is None:
|
||||
return None
|
||||
stem = _find(f, udta[1], udta[2], b"stem")
|
||||
if stem is None:
|
||||
return None
|
||||
f.seek(stem[1])
|
||||
return f.read(stem[2] - stem[1])
|
||||
|
||||
|
||||
def _aligned(decoded: np.ndarray, source: np.ndarray, window: int = 10 * SR, search: int = 64) -> int:
|
||||
"""Lag (samples) of `decoded` against `source` in the loudest `window`,
|
||||
searched within +-`search`. 0 means the file starts where the source does."""
|
||||
mono_s = source.mean(axis=0)
|
||||
mono_d = decoded.mean(axis=0)
|
||||
n = min(len(mono_s), len(mono_d))
|
||||
if n <= 2 * search:
|
||||
return 0
|
||||
block = SR
|
||||
energy = [float(np.square(mono_s[i:i + block]).sum()) for i in range(0, max(1, n - window), block)]
|
||||
start = int(np.argmax(energy)) * block if energy else 0
|
||||
stop = min(n - search, start + window)
|
||||
start = max(search, start)
|
||||
ref = mono_s[start:stop]
|
||||
best, best_lag = -np.inf, 0
|
||||
for lag in range(-search, search + 1):
|
||||
seg = mono_d[start + lag:stop + lag]
|
||||
if len(seg) != len(ref):
|
||||
continue
|
||||
score = float(np.dot(ref, seg))
|
||||
if score > best:
|
||||
best, best_lag = score, lag
|
||||
return best_lag
|
||||
|
||||
|
||||
def verify(path: Path | str, source: Source) -> None:
|
||||
"""Refuse a file that is not the stem file it should be: five stereo
|
||||
44.1 kHz streams, only the first enabled, the stem box intact (mutagen
|
||||
rewrote the tags after it), the mix the right length and — by
|
||||
cross-correlation over its loudest ten seconds — not shifted by a sample."""
|
||||
import av
|
||||
|
||||
with av.open(str(path)) as container:
|
||||
streams = container.streams.audio
|
||||
if len(streams) != 5:
|
||||
raise StemFileError(f"Expected 5 audio streams, found {len(streams)}")
|
||||
for s in streams:
|
||||
if s.codec_context.channels != 2 or s.codec_context.sample_rate != SR:
|
||||
raise StemFileError("A stream is not stereo 44.1 kHz")
|
||||
if int(streams[0].disposition) == 0 or any(int(s.disposition) for s in streams[1:]):
|
||||
raise StemFileError("Only the mix stream may be enabled")
|
||||
chunks = [f.to_ndarray() for f in container.decode(streams[0])]
|
||||
mix = np.concatenate(chunks, axis=1) if chunks else np.zeros((2, 0), np.float32)
|
||||
extra = mix.shape[1] - source.samples
|
||||
if not 0 <= extra <= _LENGTH_SLACK:
|
||||
raise StemFileError(f"The mix is {extra:+d} samples off the source's length")
|
||||
if read_stem_box(path) != STEM_BOX_JSON:
|
||||
raise StemFileError("The stem description box is missing or damaged")
|
||||
lag = _aligned(mix, source.pcm)
|
||||
if abs(lag) > 1:
|
||||
raise StemFileError(f"The mix is shifted {lag:+d} samples against the source")
|
||||
|
||||
|
||||
Separate = Callable[[np.ndarray], list[np.ndarray]]
|
||||
|
||||
|
||||
def build(source_path: Path | str, target: Path | str, separate: Separate, *,
|
||||
encoder: str | None = None, checkpoint: Callable[[], None] | None = None) -> Written:
|
||||
"""Convert `source_path` into a stem file at `target`.
|
||||
|
||||
`separate(pcm)` gets the stereo 44.1 kHz mix and must return the four stems
|
||||
in `DEMUCS_ORDER`, each the mix's shape. `target` may be any name — the batch
|
||||
writes a `*.konduktor-partial` and renames it once the batch commits — since
|
||||
nothing here infers a format from the suffix. `checkpoint()` is called between
|
||||
phases and during the encode, and may raise to cancel.
|
||||
"""
|
||||
target = Path(target)
|
||||
tick = checkpoint or (lambda: None)
|
||||
source = decode(source_path)
|
||||
tick()
|
||||
stems = separate(source.pcm)
|
||||
tick()
|
||||
if len(stems) != 4 or any(s.shape != source.pcm.shape for s in stems):
|
||||
raise StemFileError("The separation did not return four stems of the mix's length")
|
||||
bit_rate = choose_bitrate(source)
|
||||
with open(target, "wb") as fp:
|
||||
_encode(fp, [source.pcm, *stems], bit_rate=bit_rate,
|
||||
encoder=encoder or default_encoder(), checkpoint=checkpoint)
|
||||
add_stem_box(target)
|
||||
tags = tag_copy.copy_tags(source_path, target)
|
||||
verify(target, source)
|
||||
return Written(path=target, bit_rate=bit_rate, duration=source.samples / SR,
|
||||
size=target.stat().st_size, tags=tags)
|
||||
|
||||
|
||||
def stem_target_name(source_name: str) -> str:
|
||||
"""`Track.mp3` -> `Track.stem.m4a` (Traktor needs the `.stem.m4a` suffix)."""
|
||||
stem = source_name.rsplit(".", 1)[0] if "." in source_name else source_name
|
||||
return f"{stem}.stem.m4a"
|
||||
|
||||
|
||||
def is_stem_file(path: Path | str) -> bool:
|
||||
"""Whether a FILE is already a stem container — decided by its contents, not
|
||||
by `<STEMS>` in the collection (105 plain MP3s there carry one)."""
|
||||
path = Path(path)
|
||||
if path.suffix.lower() not in (".m4a", ".mp4"):
|
||||
return False
|
||||
try:
|
||||
return read_stem_box(path) is not None
|
||||
except OSError:
|
||||
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",
|
||||
]
|
||||
@@ -0,0 +1,302 @@
|
||||
"""Track structure on a KNOWN beatgrid: sections, and the events a DJ cues.
|
||||
|
||||
This is what Auto Hotcues resolves its slots against ("first drop", "start of
|
||||
the second breakdown", …). It replaced a librosa Laplacian segmentation that
|
||||
ran its own beat tracker and ignored the track's grid; against Rekordbox's
|
||||
phrase analysis its cues scored WORSE than placing one every 16 bars.
|
||||
|
||||
Why it is built the way it is — each choice was measured against the phrase
|
||||
analysis Rekordbox stores for 20 local tracks (PSSI; see the Auto Hotcues
|
||||
section of CLAUDE.md for the numbers):
|
||||
|
||||
- **Everything is per BAR, on the track's own grid.** Bar 1 is the grid's first
|
||||
marker (Traktor's convention: a marker is beat 1). Detecting the bar start
|
||||
from audio was tried and never beat that rule — DJ tracks start on a
|
||||
downbeat — so a wrong bar 1 is fixed by moving the marker, not second-guessed.
|
||||
- **The features are the ones a DJ hears**: is the kick in, is the bass in,
|
||||
how loud and bright is it — plus timbre (MFCC), for changes that keep the
|
||||
level (a lead swapping out). Timbre-only novelty scored below this: the
|
||||
sections that get cued are defined by energy, not by chord changes.
|
||||
- **Sections are an optimal segmentation, and the boundary price depends on
|
||||
where it falls**: cheap on a multiple of 8 bars, dearer on 4, very dear
|
||||
anywhere else. That is the phrase bias, built into the objective rather than
|
||||
applied as a snap afterwards — a snap can only move a boundary, never decide
|
||||
that an off-phrase change was not worth a boundary at all.
|
||||
- **A drop is a high section that follows a low one** — not merely a loud one.
|
||||
A house intro is often as loud as its drop (the full groove, for mixing), and
|
||||
what makes the drop is the breakdown before it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
import numpy as np
|
||||
|
||||
_SR = 22050
|
||||
_FR = 100 # envelope frame rate for per-bar levels (Hz)
|
||||
|
||||
# Boundary cost multipliers by bar position (x the variance of ~4 bars).
|
||||
_LAMBDA_8 = 0.2
|
||||
_LAMBDA_4 = 1.0
|
||||
_LAMBDA_OTHER = 12.0
|
||||
_MIN_SECTION = 4 # bars
|
||||
_HIGH_DB = 4.0 # a section within this of the track's loud parts is "high"
|
||||
_TIMBRE_WEIGHT = 1.0
|
||||
_OUTRO_BARS = 16 # the outro is looked for this far before the music ends
|
||||
_BUILD_MAX = 16 # a longer low stretch is not all build: take its last 8 bars
|
||||
|
||||
# The events a slot can be bound to, in the order the dialog lists them.
|
||||
EVENTS: tuple[str, ...] = (
|
||||
"first_beat", "intro_end",
|
||||
"build_1", "drop_1", "breakdown_1",
|
||||
"build_2", "drop_2", "breakdown_2",
|
||||
"build_3", "drop_3", "breakdown_3",
|
||||
"outro", "last_beat",
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Section:
|
||||
start: int # bar index (0 = the grid's first marker)
|
||||
end: int # exclusive
|
||||
high: bool
|
||||
|
||||
|
||||
@dataclass
|
||||
class Structure:
|
||||
beats: np.ndarray # every grid beat time (s), including before the first marker
|
||||
bar0: int # index into `beats` of bar 1's downbeat
|
||||
n_bars: int
|
||||
duration: float
|
||||
sections: list[Section] = field(default_factory=list)
|
||||
events: dict[str, int] = field(default_factory=dict) # event -> BEAT index
|
||||
|
||||
def beat_of_bar(self, bar: int) -> int:
|
||||
return self.bar0 + 4 * bar
|
||||
|
||||
def beat_time(self, index: int) -> float:
|
||||
"""Time of beat ``index``, extrapolated past either end at the local tempo."""
|
||||
b = self.beats
|
||||
if 0 <= index < len(b):
|
||||
return float(b[index])
|
||||
if index < 0:
|
||||
step = b[1] - b[0] if len(b) > 1 else 0.5
|
||||
return float(b[0] + index * step)
|
||||
step = b[-1] - b[-2] if len(b) > 1 else 0.5
|
||||
return float(b[-1] + (index - len(b) + 1) * step)
|
||||
|
||||
|
||||
# ---- the grid -----------------------------------------------------------------
|
||||
def grid_beats(markers: list[tuple[float, float]], duration: float) -> tuple[np.ndarray, int]:
|
||||
"""Every beat of a (possibly flexible) grid, and the index of the first marker.
|
||||
|
||||
Each marker's tempo governs until the next marker, as the deck draws it;
|
||||
beats before the first marker are extrapolated back to the track start.
|
||||
"""
|
||||
markers = sorted(markers)
|
||||
start0, bpm0 = markers[0]
|
||||
step0 = 60.0 / bpm0
|
||||
before = np.arange(start0 - step0, -1e-9, -step0)[::-1]
|
||||
beats = list(before)
|
||||
bar0 = len(beats)
|
||||
for i, (start, bpm) in enumerate(markers):
|
||||
end = markers[i + 1][0] if i + 1 < len(markers) else duration
|
||||
beats.extend(np.arange(start, end - 1e-6, 60.0 / bpm))
|
||||
return np.asarray(beats, dtype=np.float64), bar0
|
||||
|
||||
|
||||
# ---- per-bar features ----------------------------------------------------------
|
||||
def _power_env(y: np.ndarray, lo: float | None, hi: float | None) -> np.ndarray:
|
||||
from scipy.signal import butter, sosfiltfilt
|
||||
|
||||
if lo and hi:
|
||||
sos = butter(4, [lo, hi], btype="bandpass", fs=_SR, output="sos")
|
||||
elif hi:
|
||||
sos = butter(4, hi, btype="lowpass", fs=_SR, output="sos")
|
||||
else:
|
||||
sos = butter(4, lo, btype="highpass", fs=_SR, output="sos")
|
||||
x = sosfiltfilt(sos, y) ** 2
|
||||
h = _SR // _FR
|
||||
n = len(x) // h
|
||||
return x[: n * h].reshape(n, h).mean(axis=1)
|
||||
|
||||
|
||||
def _db(x):
|
||||
return 10.0 * np.log10(np.asarray(x) + 1e-10)
|
||||
|
||||
|
||||
def _bar_features(y: np.ndarray, beats: np.ndarray, bar0: int, n_bars: int):
|
||||
"""``(D, T)``: per-bar [kick, bass, mid, high, loud] and mean MFCC.
|
||||
|
||||
Levels are dB BELOW the track's own 90th percentile, so every track is on
|
||||
the same scale whatever its mastering; kick is 0..~1 of the track's usual.
|
||||
"""
|
||||
import librosa
|
||||
|
||||
from . import grid_detect
|
||||
|
||||
bass = _power_env(y, 30.0, 120.0)
|
||||
mid = _power_env(y, 200.0, 2000.0)
|
||||
high = _power_env(y, 5000.0, None)
|
||||
full = _power_env(y, 20.0, 10000.0)
|
||||
# The kick is read as the grid detector reads it: the sharp low-band onset,
|
||||
# peaked within ±15 ms of each beat. Comparing on-beat to off-beat ENERGY
|
||||
# does not work: a house bassline lives on the off-beat.
|
||||
kick_on = grid_detect._onset(grid_detect._band_env(y, _SR, 30.0, 150.0))
|
||||
S = np.abs(librosa.stft(y, n_fft=2048, hop_length=512))
|
||||
mel = librosa.power_to_db(librosa.feature.melspectrogram(S=S**2, sr=_SR, n_mels=40))
|
||||
mfcc = librosa.feature.mfcc(S=mel, n_mfcc=13)
|
||||
mfcc_t = librosa.frames_to_time(np.arange(mfcc.shape[1]), sr=_SR, hop_length=512)
|
||||
|
||||
rows, timbre = [], []
|
||||
for b in range(n_bars):
|
||||
i = bar0 + 4 * b
|
||||
t0, t1 = beats[i], beats[i + 4]
|
||||
ks = []
|
||||
for k in range(4):
|
||||
c = int(round(beats[i + k] * 1000))
|
||||
seg = kick_on[max(0, c - 15) : c + 16]
|
||||
ks.append(float(seg.max()) if len(seg) else 0.0)
|
||||
a, z = int(t0 * _FR), max(int(t1 * _FR), int(t0 * _FR) + 1)
|
||||
rows.append([
|
||||
float(np.median(ks)),
|
||||
_db(bass[a:z].mean()), _db(mid[a:z].mean()), _db(high[a:z].mean()), _db(full[a:z].mean()),
|
||||
])
|
||||
ia, iz = np.searchsorted(mfcc_t, t0), np.searchsorted(mfcc_t, t1)
|
||||
timbre.append(mfcc[:, ia : max(iz, ia + 1)].mean(axis=1))
|
||||
D = np.asarray(rows)
|
||||
D[:, 0] /= np.percentile(D[:, 0], 90) + 1e-9
|
||||
D[:, 1:] -= np.percentile(D[:, 1:], 90, axis=0)
|
||||
D[:, 1:] = np.maximum(D[:, 1:], -30.0) # silence is only "very quiet"
|
||||
return D, np.asarray(timbre), _db(full)
|
||||
|
||||
|
||||
# ---- segmentation ---------------------------------------------------------------
|
||||
def _segment(F: np.ndarray, penalty: np.ndarray) -> list[int]:
|
||||
"""Section start bars minimising squared deviation from each section's mean
|
||||
plus a price per boundary (exact dynamic programme; n is ~100–250 bars)."""
|
||||
n = len(F)
|
||||
cs = np.vstack([np.zeros(F.shape[1]), np.cumsum(F, axis=0)])
|
||||
cs2 = np.r_[0.0, np.cumsum((F**2).sum(axis=1))]
|
||||
|
||||
def cost(i: int, j: int) -> float:
|
||||
s = cs[j] - cs[i]
|
||||
return float(cs2[j] - cs2[i] - (s @ s) / (j - i))
|
||||
|
||||
best = np.full(n + 1, np.inf)
|
||||
best[0] = 0.0
|
||||
arg = np.zeros(n + 1, dtype=np.int64)
|
||||
for j in range(1, n + 1):
|
||||
for i in range(0, j):
|
||||
# every section is at least _MIN_SECTION long, except a short tail
|
||||
if j - i < _MIN_SECTION and j != n:
|
||||
continue
|
||||
if 0 < i < _MIN_SECTION:
|
||||
continue
|
||||
v = best[i] + cost(i, j) + (penalty[i] if i else 0.0)
|
||||
if v < best[j]:
|
||||
best[j], arg[j] = v, i
|
||||
starts, j = [], n
|
||||
while j > 0:
|
||||
starts.append(int(arg[j]))
|
||||
j = int(arg[j])
|
||||
return sorted(set(starts))
|
||||
|
||||
|
||||
def _sections(D: np.ndarray, T: np.ndarray) -> list[Section]:
|
||||
Z = np.column_stack([D[:, 0] * 10, D[:, 1] / 3, D[:, 4] / 3, D[:, 3] / 6, D[:, 2] / 6])
|
||||
Tz = (T - T.mean(axis=0)) / (T.std(axis=0) + 1e-9) * _TIMBRE_WEIGHT
|
||||
F = np.column_stack([Z, Tz])
|
||||
n = len(F)
|
||||
idx = np.arange(n)
|
||||
scale = float(F.var(axis=0).sum()) * 4.0
|
||||
penalty = scale * np.where(idx % 8 == 0, _LAMBDA_8, np.where(idx % 4 == 0, _LAMBDA_4, _LAMBDA_OTHER))
|
||||
starts = _segment(F, penalty)
|
||||
out = []
|
||||
for k, s in enumerate(starts):
|
||||
e = starts[k + 1] if k + 1 < len(starts) else n
|
||||
d = D[s:e].mean(axis=0)
|
||||
# High = near the track's loud parts on BOTH bass and loudness. The kick
|
||||
# is deliberately not required: drum & bass has no kick on every beat.
|
||||
out.append(Section(s, e, bool(d[1] > -_HIGH_DB and d[4] > -_HIGH_DB)))
|
||||
return out
|
||||
|
||||
|
||||
# ---- events ----------------------------------------------------------------------
|
||||
def _events(secs: list[Section], music_end_bar: int) -> dict[str, int]:
|
||||
"""Event -> BAR. Drops are high sections entered from a low one."""
|
||||
ev: dict[str, int] = {}
|
||||
drops: list[int] = []
|
||||
seen_low = False
|
||||
for i, s in enumerate(secs):
|
||||
if s.high:
|
||||
if seen_low and (i == 0 or not secs[i - 1].high):
|
||||
drops.append(i)
|
||||
else:
|
||||
seen_low = True
|
||||
|
||||
def run_end(i: int) -> int:
|
||||
while i + 1 < len(secs) and secs[i + 1].high:
|
||||
i += 1
|
||||
return i
|
||||
|
||||
for n, di in enumerate(drops, start=1):
|
||||
ev[f"drop_{n}"] = secs[di].start
|
||||
prev = secs[di - 1]
|
||||
ev[f"build_{n}"] = prev.start if prev.end - prev.start <= _BUILD_MAX else secs[di].start - 8
|
||||
# A breakdown is the end of a drop that ANOTHER drop follows; the end of
|
||||
# the last one is the outro's business.
|
||||
if n < len(drops):
|
||||
ev[f"breakdown_{n}"] = secs[run_end(di) + 1].start
|
||||
|
||||
if len(secs) > 1:
|
||||
ev["intro_end"] = secs[1].start
|
||||
after = drops[-1] if drops else 0
|
||||
cands = [s.start for s in secs[after + 1 :]] or [s.start for s in secs[1:]]
|
||||
if cands:
|
||||
ev["outro"] = min(cands, key=lambda b: abs(b - (music_end_bar - _OUTRO_BARS)))
|
||||
return ev
|
||||
|
||||
|
||||
# ---- entry point ---------------------------------------------------------------
|
||||
def analyse(
|
||||
audio_path: str,
|
||||
markers: list[tuple[float, float]],
|
||||
*,
|
||||
y: np.ndarray | None = None,
|
||||
) -> Structure:
|
||||
"""Sections and cue events for a track, on its own beatgrid.
|
||||
|
||||
``markers`` is the grid as ``[(start_sec, bpm), …]``. Raises ``ValueError``
|
||||
when there is no grid or too little music to have a structure.
|
||||
"""
|
||||
if not markers:
|
||||
raise ValueError("Set a beatgrid first")
|
||||
if y is None:
|
||||
import librosa
|
||||
y, _ = librosa.load(audio_path, sr=_SR, mono=True)
|
||||
y = np.asarray(y, dtype=np.float32)
|
||||
duration = len(y) / _SR
|
||||
beats, bar0 = grid_beats(markers, duration)
|
||||
n_bars = max(0, (len(beats) - bar0 - 1) // 4)
|
||||
if n_bars < 2 * _MIN_SECTION:
|
||||
raise ValueError("Track is too short to find a structure")
|
||||
|
||||
D, T, full_db = _bar_features(y, beats, bar0, n_bars)
|
||||
st = Structure(beats=beats, bar0=bar0, n_bars=n_bars, duration=duration)
|
||||
st.sections = _sections(D, T)
|
||||
|
||||
# Where the music starts and ends: the first/last beat within 30 dB of the
|
||||
# track's loud parts, so a silent lead-in or tail is not cued.
|
||||
loud = full_db >= np.percentile(full_db, 90) - 30.0
|
||||
frames = np.flatnonzero(loud)
|
||||
t_first = frames[0] / _FR if len(frames) else 0.0
|
||||
t_last = frames[-1] / _FR if len(frames) else duration
|
||||
first_beat = int(np.searchsorted(beats, t_first - 0.05))
|
||||
last_beat = max(first_beat, int(np.searchsorted(beats, t_last, side="right")) - 1)
|
||||
music_end_bar = min(n_bars, max(0, (last_beat - bar0) // 4))
|
||||
|
||||
st.events = {k: st.beat_of_bar(b) for k, b in _events(st.sections, music_end_bar).items()}
|
||||
st.events["first_beat"] = first_beat
|
||||
st.events["last_beat"] = last_beat
|
||||
return st
|
||||
@@ -0,0 +1,218 @@
|
||||
"""Copy a track's file tags into the MP4 a stem conversion writes.
|
||||
|
||||
A converted `.stem.m4a` replaces its source file — in Replace mode the source is
|
||||
deleted on Save — so every tag the source carried must survive the move, not just
|
||||
the handful Konduktor edits (`audio_tags.write_tags`). The collection keeps its
|
||||
own copy of the metadata either way; this is about the FILE, which is what
|
||||
travels: another DJ app, a stick, a re-import.
|
||||
|
||||
One canonical field list, read from whichever tag format the source uses (ID3 on
|
||||
MP3/AIFF/WAV, Vorbis comments on FLAC/Ogg, MP4 atoms on M4A) and written as the
|
||||
MP4 atoms the user's own commercial stem files use — `tmpo` for BPM and the
|
||||
iTunes freeform `initialkey` for the key — plus the freeform names
|
||||
`audio_tags._write_mp4` already writes (LABEL / REMIXER / PRODUCER / MIX), so a
|
||||
later tag edit updates the same atom. Cover art is read by `audio_tags.read_cover`.
|
||||
|
||||
Deliberately NOT copied: the rating (the collection owns it, and players store
|
||||
it under incompatible schemes), ReplayGain / loudness (it describes the SOURCE
|
||||
encode), and app-private blobs (Traktor's own `NITR`/PRIV data: Traktor rewrites
|
||||
its analysis for the new file).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from . import audio_tags
|
||||
|
||||
#: canonical field -> MP4 atom. `None` = an iTunes freeform atom named below.
|
||||
_MP4_ATOMS = {
|
||||
"title": "\xa9nam",
|
||||
"artist": "\xa9ART",
|
||||
"album": "\xa9alb",
|
||||
"albumartist": "aART",
|
||||
"genre": "\xa9gen",
|
||||
"comment": "\xa9cmt",
|
||||
"date": "\xa9day",
|
||||
"composer": "\xa9wrt",
|
||||
"grouping": "\xa9grp",
|
||||
"copyright": "cprt",
|
||||
"lyrics": "\xa9lyr",
|
||||
}
|
||||
_FREEFORM = {
|
||||
"key": "initialkey",
|
||||
"label": "LABEL",
|
||||
"remixer": "REMIXER",
|
||||
"producer": "PRODUCER",
|
||||
"mix": "MIX",
|
||||
"isrc": "ISRC",
|
||||
}
|
||||
#: Structured MP4 atoms: track/disc number pairs, BPM, compilation flag.
|
||||
_STRUCTURED = ("tracknumber", "discnumber", "bpm", "compilation")
|
||||
|
||||
# ---- reading ---------------------------------------------------------------
|
||||
_ID3_TEXT = {
|
||||
"TIT2": "title", "TPE1": "artist", "TALB": "album", "TPE2": "albumartist",
|
||||
"TCON": "genre", "TDRC": "date", "TCOM": "composer", "GRP1": "grouping",
|
||||
"TIT1": "grouping", "TCOP": "copyright", "TKEY": "key", "TPUB": "label",
|
||||
"TPE4": "remixer", "TIT3": "mix", "TSRC": "isrc", "TRCK": "tracknumber",
|
||||
"TPOS": "discnumber", "TBPM": "bpm", "TCMP": "compilation",
|
||||
}
|
||||
_VORBIS = {
|
||||
"title": "title", "artist": "artist", "album": "album", "albumartist": "albumartist",
|
||||
"genre": "genre", "comment": "comment", "description": "comment", "date": "date",
|
||||
"composer": "composer", "grouping": "grouping", "copyright": "copyright",
|
||||
"lyrics": "lyrics", "unsyncedlyrics": "lyrics", "initialkey": "key", "key": "key",
|
||||
"label": "label", "organization": "label", "publisher": "label", "remixer": "remixer",
|
||||
"producer": "producer", "mixname": "mix", "isrc": "isrc", "tracknumber": "tracknumber",
|
||||
"discnumber": "discnumber", "bpm": "bpm", "compilation": "compilation",
|
||||
}
|
||||
|
||||
|
||||
def _first(values) -> str | None:
|
||||
for v in values or []:
|
||||
s = str(v).strip()
|
||||
if s:
|
||||
return s
|
||||
return None
|
||||
|
||||
|
||||
def _read_id3(tags) -> dict[str, str]:
|
||||
out: dict[str, str] = {}
|
||||
for frame_id, field in _ID3_TEXT.items():
|
||||
frame = tags.get(frame_id)
|
||||
if frame is not None and field not in out:
|
||||
val = _first(getattr(frame, "text", []))
|
||||
if val:
|
||||
out[field] = val
|
||||
for frame in tags.getall("TXXX"):
|
||||
if frame.desc.upper() == "PRODUCER" and "producer" not in out:
|
||||
out["producer"] = _first(frame.text) or ""
|
||||
comm = [f for f in tags.getall("COMM") if _first(f.text)]
|
||||
if comm: # the untitled comment first: that is the one players show
|
||||
comm.sort(key=lambda f: f.desc != "")
|
||||
out["comment"] = _first(comm[0].text)
|
||||
uslt = tags.getall("USLT")
|
||||
if uslt and getattr(uslt[0], "text", ""):
|
||||
out["lyrics"] = str(uslt[0].text)
|
||||
return {k: v for k, v in out.items() if v}
|
||||
|
||||
|
||||
def _read_vorbis(tags) -> dict[str, str]:
|
||||
out: dict[str, str] = {}
|
||||
for key, values in tags.items():
|
||||
field = _VORBIS.get(key.lower())
|
||||
if field and field not in out:
|
||||
val = _first(values)
|
||||
if val:
|
||||
out[field] = val
|
||||
lower = {k.lower(): v for k, v in tags.items()}
|
||||
for field, total in (("tracknumber", "tracktotal"), ("discnumber", "disctotal")):
|
||||
if field in out and "/" not in out[field] and _first(lower.get(total)):
|
||||
out[field] = f"{out[field]}/{_first(lower[total])}"
|
||||
return out
|
||||
|
||||
|
||||
def _read_mp4(tags) -> dict[str, str]:
|
||||
out: dict[str, str] = {}
|
||||
for field, atom in _MP4_ATOMS.items():
|
||||
val = _first(tags.get(atom))
|
||||
if val:
|
||||
out[field] = val
|
||||
for field, name in _FREEFORM.items():
|
||||
raw = tags.get(f"----:com.apple.iTunes:{name}")
|
||||
if raw:
|
||||
val = bytes(raw[0]).decode("utf-8", "replace").strip()
|
||||
if val:
|
||||
out[field] = val
|
||||
for field, atom in (("tracknumber", "trkn"), ("discnumber", "disk")):
|
||||
pair = (tags.get(atom) or [None])[0]
|
||||
if pair and pair[0]:
|
||||
out[field] = f"{pair[0]}/{pair[1]}" if pair[1] else str(pair[0])
|
||||
if tags.get("tmpo"):
|
||||
out["bpm"] = str(tags["tmpo"][0])
|
||||
if tags.get("cpil"):
|
||||
out["compilation"] = "1" if tags["cpil"] else "0"
|
||||
return out
|
||||
|
||||
|
||||
def read_tags(path: Path | str) -> dict[str, str]:
|
||||
"""The canonical fields a file carries, whatever its tag format; `{}` for a
|
||||
file with none or one mutagen cannot read."""
|
||||
import mutagen
|
||||
from mutagen.id3 import ID3
|
||||
from mutagen.mp4 import MP4Tags
|
||||
|
||||
try:
|
||||
audio = mutagen.File(str(path))
|
||||
except Exception: # noqa: BLE001 — an unreadable tag is no tags, not a failure
|
||||
return {}
|
||||
tags = getattr(audio, "tags", None)
|
||||
if tags is None:
|
||||
return {}
|
||||
if isinstance(tags, ID3):
|
||||
return _read_id3(tags)
|
||||
if isinstance(tags, MP4Tags):
|
||||
return _read_mp4(tags)
|
||||
if hasattr(tags, "items"): # Vorbis comments (FLAC, Ogg, Opus)
|
||||
return _read_vorbis(tags)
|
||||
return {}
|
||||
|
||||
|
||||
# ---- writing ---------------------------------------------------------------
|
||||
def _number_pair(value: str) -> tuple[int, int] | None:
|
||||
head, _, tail = value.partition("/")
|
||||
try:
|
||||
return int(head), int(tail) if tail.strip() else 0
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def write_mp4_tags(path: Path | str, fields: dict[str, str],
|
||||
cover: tuple[bytes, str] | None = None) -> None:
|
||||
"""Write canonical `fields` (and a cover) into an MP4 file, replacing nothing
|
||||
it does not name. Values that cannot be represented (a BPM that is not a
|
||||
number) are skipped rather than written wrong.
|
||||
|
||||
Opened as `MP4` explicitly, never by suffix: a conversion writes into a
|
||||
`*.konduktor-partial` file, which `audio_tags.write_cover` would refuse as
|
||||
an unsupported format — silently losing the art."""
|
||||
from mutagen.mp4 import MP4, MP4Cover, MP4FreeForm
|
||||
|
||||
audio = MP4(str(path))
|
||||
if audio.tags is None:
|
||||
audio.add_tags()
|
||||
t = audio.tags
|
||||
for field, atom in _MP4_ATOMS.items():
|
||||
if fields.get(field):
|
||||
t[atom] = [fields[field]]
|
||||
for field, name in _FREEFORM.items():
|
||||
if fields.get(field):
|
||||
t[f"----:com.apple.iTunes:{name}"] = [MP4FreeForm(fields[field].encode("utf-8"))]
|
||||
for field, atom in (("tracknumber", "trkn"), ("discnumber", "disk")):
|
||||
pair = _number_pair(fields.get(field, "")) if fields.get(field) else None
|
||||
if pair:
|
||||
t[atom] = [pair]
|
||||
if fields.get("bpm"):
|
||||
try:
|
||||
bpm = round(float(fields["bpm"]))
|
||||
if 0 < bpm < 65536:
|
||||
t["tmpo"] = [bpm]
|
||||
except ValueError:
|
||||
pass
|
||||
if fields.get("compilation"):
|
||||
t["cpil"] = fields["compilation"].strip() not in ("", "0", "false", "False")
|
||||
if cover is not None:
|
||||
data, mime = cover
|
||||
fmt = MP4Cover.FORMAT_PNG if mime == "image/png" else MP4Cover.FORMAT_JPEG
|
||||
t["covr"] = [MP4Cover(data, imageformat=fmt)]
|
||||
audio.save()
|
||||
|
||||
|
||||
def copy_tags(source: Path | str, target: Path | str) -> dict[str, str]:
|
||||
"""Copy every canonical tag and the cover art from `source` into the MP4
|
||||
`target`. Returns the fields copied (for reporting and tests)."""
|
||||
fields = read_tags(source)
|
||||
cover = audio_tags.read_cover(Path(source))
|
||||
if fields or cover is not None:
|
||||
write_mp4_tags(target, fields, cover)
|
||||
return fields
|
||||
@@ -0,0 +1,198 @@
|
||||
"""What a track's waveform is made of — measured once, drawn by whoever needs it.
|
||||
|
||||
Platform-independent on purpose: this decodes and measures, and stops there. How
|
||||
a measurement becomes pixels — Pioneer's 5-bit heights, 3-band bytes, colour
|
||||
bits — is the target's business (`adapters/rekordbox/anlz_writer.py`).
|
||||
|
||||
Two resolutions, from ONE decode:
|
||||
|
||||
* `columns` — `n` equal slices of the whole track (loudness + brightness), for
|
||||
an overview such as Pioneer's blue `PWAV` preview;
|
||||
* `frames` — 150 per second, each split into low / mid / high band energy,
|
||||
for a detail waveform and a 3-band overview (Pioneer's `PWV3`-`PWV7`).
|
||||
|
||||
The bands cross over at 200 Hz and 2.5 kHz: fitted against rekordbox's own 3-band
|
||||
waveforms for ten local tracks (correlation 0.89 / 0.80 / 0.77 per band). Energy
|
||||
is left unscaled — each target normalises it its own way.
|
||||
|
||||
Decoding goes through PyAV (FFmpeg, bundled in its wheel) and falls back to
|
||||
`librosa`, like grid detection: libsndfile for most formats
|
||||
and, for AAC (every Traktor `.stem.m4a`), `audioread`'s CoreAudio backend on macOS.
|
||||
Where nothing can decode a file, `analyse()` returns None and the caller decides
|
||||
what a missing waveform means.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
#: BUMP THIS whenever `analyse()`'s output changes (a constant below, the
|
||||
#: decoder, the maths). Exports cache these measurements on the stick
|
||||
#: (`analysis_cache`), keyed by this number — so an unbumped change keeps
|
||||
#: serving the old measurement to every re-export.
|
||||
ANALYSIS_VERSION = 1
|
||||
|
||||
#: Plenty for a waveform, and half the decode cost of 44.1 kHz. The high band
|
||||
#: runs to 11 kHz, which is where most of its visible energy is anyway.
|
||||
SR = 22050
|
||||
#: Detail resolution. Pioneer's detail tags are 150 entries per second.
|
||||
FPS = 150
|
||||
N_FFT = 1024
|
||||
#: Band crossovers, Hz.
|
||||
LOW_MAX, MID_MAX = 200.0, 2500.0
|
||||
#: "Bright" (for `columns`) = share of spectral energy above this.
|
||||
_BRIGHT_HZ = 2500.0
|
||||
|
||||
|
||||
@dataclass
|
||||
class Columns:
|
||||
"""`n` equal slices of a track, start to end."""
|
||||
|
||||
#: RMS amplitude of each slice, on the decoded signal's 0-1 full scale.
|
||||
rms: np.ndarray
|
||||
#: Share of each slice's spectral energy above ~2.5 kHz, 0-1.
|
||||
brightness: np.ndarray
|
||||
#: Decoded length in seconds.
|
||||
duration: float
|
||||
|
||||
|
||||
@dataclass
|
||||
class Frames:
|
||||
"""150-per-second band energies, low / mid / high, shape (n, 3).
|
||||
|
||||
Frame i covers `[i/150, (i+1)/150)` seconds on the clock the caller asked
|
||||
for — see `analyse(lead=…)`.
|
||||
"""
|
||||
|
||||
bands: np.ndarray
|
||||
#: Decoded length in seconds (of the audio, not counting any lead).
|
||||
duration: float
|
||||
|
||||
|
||||
@dataclass
|
||||
class Analysis:
|
||||
columns: Columns
|
||||
frames: Frames
|
||||
|
||||
@property
|
||||
def duration(self) -> float:
|
||||
return self.columns.duration
|
||||
|
||||
|
||||
def _decode_pyav(path: Path) -> np.ndarray:
|
||||
"""Mono float32 at `SR`, via PyAV — FFmpeg's decoders, bundled in its wheel.
|
||||
|
||||
The reason it is first: it decodes AAC (every Traktor `.stem.m4a`) on EVERY
|
||||
OS, where librosa needs CoreAudio (macOS only) or a system ffmpeg. Measured
|
||||
to start on exactly the same sample as librosa's decode for MP3 and AAC, so
|
||||
switching decoders moves nothing against the beats.
|
||||
"""
|
||||
import av
|
||||
|
||||
with av.open(str(path)) as container:
|
||||
stream = container.streams.audio[0]
|
||||
resampler = av.AudioResampler(format="flt", layout="mono", rate=SR)
|
||||
chunks = []
|
||||
for frame in container.decode(stream):
|
||||
for out in resampler.resample(frame):
|
||||
chunks.append(out.to_ndarray().reshape(-1))
|
||||
for out in resampler.resample(None): # flush
|
||||
chunks.append(out.to_ndarray().reshape(-1))
|
||||
return np.concatenate(chunks) if chunks else np.zeros(0, dtype=np.float32)
|
||||
|
||||
|
||||
def even_slices(n: int, k: int) -> list[slice]:
|
||||
"""`k` slices of `range(n)`, each starting where its share of the whole
|
||||
begins — so column `i` holds exactly the audio at `i/k` of the track.
|
||||
|
||||
NOT `np.array_split`: that gives the FIRST `n % k` chunks one extra element,
|
||||
which pushes every early column's content later than its position — up to
|
||||
~1.8 s by column 420 of a 1200-column overview (24,420 frames), shrinking
|
||||
back to 0 at the end. Rekordbox drew such an overview a bar ahead of the
|
||||
playhead mid-track, and closer to right near the end.
|
||||
"""
|
||||
edges = np.round(np.linspace(0, n, k + 1)).astype(int)
|
||||
return [slice(int(a), int(max(b, a + 1)) if n else 0) for a, b in zip(edges[:-1], edges[1:])]
|
||||
|
||||
|
||||
def _decode(path: Path) -> np.ndarray | None:
|
||||
try:
|
||||
return _decode_pyav(path)
|
||||
except Exception as ex: # PyAV missing, or a file FFmpeg cannot open
|
||||
log.debug("PyAV could not decode %s (%s); trying librosa", path, ex)
|
||||
try:
|
||||
import librosa
|
||||
|
||||
y, _ = librosa.load(str(path), sr=SR, mono=True)
|
||||
return y
|
||||
except Exception as ex: # any decoder failure: no waveform, not a failed export
|
||||
log.warning("could not decode %s for a waveform: %s", path, ex)
|
||||
return None
|
||||
|
||||
|
||||
def _columns(y: np.ndarray, n: int) -> Columns:
|
||||
import librosa
|
||||
|
||||
rms = np.array([float(np.sqrt(np.mean(y[s] * y[s]))) for s in even_slices(len(y), n)])
|
||||
spec = np.abs(librosa.stft(y, n_fft=N_FFT, hop_length=N_FFT)) ** 2
|
||||
freqs = librosa.fft_frequencies(sr=SR, n_fft=N_FFT)
|
||||
share = spec[freqs > _BRIGHT_HZ].sum(0) / (spec.sum(0) + 1e-12)
|
||||
brightness = np.array([float(c.mean()) if len(c) else 0.0
|
||||
for c in (share[s] for s in even_slices(len(share), n))])
|
||||
return Columns(rms=rms, brightness=brightness, duration=len(y) / SR)
|
||||
|
||||
|
||||
def _frames(y: np.ndarray, lead: float) -> Frames:
|
||||
"""Band energies at 150/s, with the frame grid starting `lead` s BEFORE the
|
||||
audio — how a target whose clock runs behind the decoded audio (rekordbox on
|
||||
MP3/AAC) gets frames that line up with its own positions."""
|
||||
import librosa
|
||||
|
||||
duration = len(y) / SR
|
||||
pad = int(round(max(0.0, lead) * SR))
|
||||
padded = np.concatenate([np.zeros(pad, dtype=y.dtype), y]) if pad else y
|
||||
n = int(np.ceil((len(padded) / SR) * FPS))
|
||||
hop = SR / FPS # 147 samples at 22050 Hz
|
||||
spec = np.abs(librosa.stft(padded, n_fft=N_FFT, hop_length=int(round(hop)),
|
||||
center=True)) ** 2
|
||||
f = librosa.fft_frequencies(sr=SR, n_fft=N_FFT)
|
||||
bands = np.stack([
|
||||
np.sqrt(spec[f < LOW_MAX].sum(0)),
|
||||
np.sqrt(spec[(f >= LOW_MAX) & (f < MID_MAX)].sum(0)),
|
||||
np.sqrt(spec[f >= MID_MAX].sum(0)),
|
||||
], axis=1)[:n]
|
||||
if len(bands) < n:
|
||||
bands = np.vstack([bands, np.zeros((n - len(bands), 3))])
|
||||
return Frames(bands=bands, duration=duration)
|
||||
|
||||
|
||||
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`."""
|
||||
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))
|
||||
|
||||
|
||||
def columns(path: Path, n: int) -> Columns | None:
|
||||
"""Just the overview columns — for a caller that needs no detail."""
|
||||
y = _decode(path)
|
||||
if y is None or len(y) < n:
|
||||
return None
|
||||
return _columns(y, n)
|
||||
@@ -0,0 +1,699 @@
|
||||
"""Running an export: plan it, copy the audio, write the library.
|
||||
|
||||
App-level, like `importer.py`, and for the same reason — it coordinates a source
|
||||
library, a destination folder and an exporter, and none of those should know
|
||||
about the others.
|
||||
|
||||
**`core` plans and copies; the exporter only writes the library file.** Layout,
|
||||
collision and dedup rules are platform-independent and must not drift between
|
||||
targets, and the exporter cannot write a Traktor `<LOCATION>` before the
|
||||
destination path is known anyway.
|
||||
|
||||
## Ordering is the safety property
|
||||
|
||||
Audio is copied FIRST and the library written LAST, so a cancel during the long
|
||||
part leaves no library file — its absence is what marks an export unfinished —
|
||||
and everything copied is removed on the way out. The rollback tracks files
|
||||
BEFORE each write, not after: cleaning up only COMPLETED copies leaves the
|
||||
in-flight one behind, which is a bug the import feature had and was fixed there.
|
||||
|
||||
## Konduktor only deletes what Konduktor wrote
|
||||
|
||||
A re-export clears its previous export first, which combined with "the user picks
|
||||
the destination" is a folder-deletion hazard: point an export at `~/Documents`
|
||||
and a confirm dialog is the only thing between a click and real loss. So every
|
||||
export writes a **manifest** of what it put there, and a destination that is
|
||||
non-empty without one is REFUSED rather than confirmed. Clearing then removes
|
||||
exactly the manifest's files — anything the user added themselves survives.
|
||||
|
||||
## A re-export copies only what changed
|
||||
|
||||
The manifest also records, per copied file, the SOURCE's path, size and mtime
|
||||
and the COPY's size and mtime as read back. A re-export keeps a previous copy
|
||||
when all four still match — the same quick check rsync makes, and no
|
||||
checksums: hashing the copy means reading it back over USB, which costs about
|
||||
what copying it again does. A tag edit rewrites the source file, so its mtime
|
||||
moves and the file is copied again. Copies are matched by SOURCE path, not by
|
||||
where they sit, because adding a track from another folder moves the shared
|
||||
root below and with it every destination path; a kept copy whose path changed
|
||||
is renamed, not copied. No record, or an unreadable one, means copy everything.
|
||||
|
||||
The ORDER keeps the safety properties: the previous export's libraries and
|
||||
every file not kept go first, then the kept copies are moved, then what
|
||||
changed is copied (under a temporary name, renamed into place), and the
|
||||
libraries are written last. A cancel removes what THIS run wrote and rewrites
|
||||
the manifest around what it kept — deleting the manifest with kept files still
|
||||
there would leave a folder the next export refuses as not ours.
|
||||
|
||||
Decoding every track for its Pioneer waveforms is the other slow part, so the
|
||||
measurements are cached on the drive too (`core/analysis_cache.py`), keyed by
|
||||
the same source facts.
|
||||
|
||||
## Several targets, one copy of the audio
|
||||
|
||||
An export can target several platforms at once. The audio is copied ONCE and
|
||||
every target's library is written over the same files, one after another. If
|
||||
any of them fails, EVERYTHING is undone — the audio and the libraries already
|
||||
written — because "the libraries' absence marks an export unfinished" only
|
||||
holds if a half-finished multi-target export also leaves none behind.
|
||||
|
||||
## Mirror layout, under `Contents/`
|
||||
|
||||
Audio is laid out mirroring the source tree, relative to the deepest folder all
|
||||
the tracks share (`common_dir_prefix`), inside a `Contents/` folder — the name
|
||||
rekordbox itself uses on a stick. Mirroring absolute paths would put the user's
|
||||
home directory on the stick; mirroring relative to the common root keeps the
|
||||
structure recognisable and makes filename collisions impossible, since two
|
||||
distinct source paths cannot share a relative path. `Contents/` is what keeps
|
||||
the AUDIO from colliding with the LIBRARIES: without it, a music folder with a
|
||||
top-level `PIONEER/` or `share/`, or a file called `master.db`, would land on
|
||||
top of one.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from . import exports
|
||||
from .core import registry
|
||||
from .core.analysis_cache import CACHE_DIR, AnalysisCache, fingerprint
|
||||
from .core.export import ExportPayload, ExportPlaylist, ExportTrack, for_platform
|
||||
from .core.pathmap import common_dir_prefix
|
||||
from .core.places import is_drive_root, is_os_housekeeping
|
||||
from .importer import SPACE_HEADROOM, copy_file, free_bytes
|
||||
from .jobs import JobHandle
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
MANIFEST_NAME = ".konduktor-export.json"
|
||||
#: Every exported audio file lives under this folder, never at the root.
|
||||
AUDIO_DIR = "Contents"
|
||||
#: Where kept copies wait while being moved, and the suffix a copy is written
|
||||
#: under until it is complete. Both are listed in the manifest while in use.
|
||||
MOVING_DIR = ".konduktor-moving"
|
||||
PARTIAL_SUFFIX = ".konduktor-partial"
|
||||
|
||||
#: Why an export cannot run. The UI words these; they are facts, not sentences.
|
||||
BLOCKED_OCCUPIED = "destination_not_empty"
|
||||
BLOCKED_EMPTY = "nothing_to_export"
|
||||
BLOCKED_NO_TARGET = "unsupported_target"
|
||||
|
||||
|
||||
@dataclass
|
||||
class PlannedTrack:
|
||||
track_id: str
|
||||
title: str
|
||||
source_path: Path | None
|
||||
destination: Path | None
|
||||
size: int = 0
|
||||
missing: bool = False
|
||||
#: The source's mtime when planned, recorded in the manifest with `size`.
|
||||
mtime_ns: int = 0
|
||||
#: Where the previous export's copy of this very file sits, when it can be
|
||||
#: kept instead of copied again — possibly a different path from
|
||||
#: `destination`, in which case it is moved. None means copy.
|
||||
reuse: Path | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExportPlan:
|
||||
tracks: list[PlannedTrack] = field(default_factory=list)
|
||||
playlists: list[ExportPlaylist] = field(default_factory=list)
|
||||
destination: Path | None = None
|
||||
#: One of the BLOCKED_* facts, or None when the export can run.
|
||||
blocked: str | None = None
|
||||
#: Whether the destination already holds a Konduktor export to replace.
|
||||
replacing: bool = False
|
||||
#: Targets whose library is only found at a drive's root, when the
|
||||
#: destination is not one. A warning, not a block: the other targets are
|
||||
#: fine anywhere, and the user may be staging a stick's contents on purpose.
|
||||
not_drive_root: list[str] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def exportable(self) -> list[PlannedTrack]:
|
||||
return [t for t in self.tracks if not t.missing]
|
||||
|
||||
@property
|
||||
def total_bytes(self) -> int:
|
||||
"""What will actually be COPIED — a kept file costs neither time nor
|
||||
space, since the previous export's other files are removed first."""
|
||||
return sum(t.size for t in self.exportable if t.reuse is None)
|
||||
|
||||
@property
|
||||
def unchanged(self) -> int:
|
||||
return sum(1 for t in self.exportable if t.reuse is not None)
|
||||
|
||||
def as_dict(self, free: int | None = None) -> dict:
|
||||
return {
|
||||
"tracks": len(self.tracks),
|
||||
"exportable": len(self.exportable),
|
||||
"unchanged": self.unchanged,
|
||||
"missing": [t.title for t in self.tracks if t.missing],
|
||||
"playlists": [p.name for p in self.playlists],
|
||||
"total_bytes": self.total_bytes,
|
||||
"destination": str(self.destination) if self.destination else None,
|
||||
"free_bytes": free,
|
||||
"enough_space": (
|
||||
None if free is None else free >= self.total_bytes + SPACE_HEADROOM
|
||||
),
|
||||
"blocked": self.blocked,
|
||||
"replacing": self.replacing,
|
||||
"not_drive_root": list(self.not_drive_root),
|
||||
}
|
||||
|
||||
|
||||
# ---- the destination ---------------------------------------------------------
|
||||
|
||||
|
||||
def manifest_path(destination: Path) -> Path:
|
||||
return Path(destination) / MANIFEST_NAME
|
||||
|
||||
|
||||
def is_ours(destination: Path) -> bool:
|
||||
"""Whether this folder holds an export Konduktor wrote."""
|
||||
try:
|
||||
return manifest_path(destination).is_file()
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def destination_blocked(destination: Path) -> str | None:
|
||||
"""Why this folder cannot be exported into, or None.
|
||||
|
||||
A folder that does not exist yet, or is empty, or carries our manifest, is
|
||||
fine. Anything else is REFUSED — not confirmed — because an export clears
|
||||
its destination and Konduktor must never delete what it did not write.
|
||||
"Empty" ignores what the OS writes by itself (`.Spotlight-V100`, `.Trashes`,
|
||||
…), or a stick's root would be refused the moment it was first mounted.
|
||||
"""
|
||||
destination = Path(destination)
|
||||
try:
|
||||
if not destination.exists():
|
||||
return None
|
||||
if not destination.is_dir():
|
||||
return BLOCKED_OCCUPIED
|
||||
if is_ours(destination):
|
||||
return None
|
||||
occupied = any(not is_os_housekeeping(p.name) for p in destination.iterdir())
|
||||
return BLOCKED_OCCUPIED if occupied else None
|
||||
except OSError:
|
||||
return BLOCKED_OCCUPIED
|
||||
|
||||
|
||||
def _clear(destination: Path, keep: set[Path] = frozenset()) -> None:
|
||||
"""Remove the previous export, and only it — except the audio in `keep`,
|
||||
which this export reuses.
|
||||
|
||||
Driven by the manifest rather than by wiping the folder: the manifest lists
|
||||
everything the last export wrote, so anything the user put there themselves
|
||||
survives. Empty directories are pruned afterwards so a re-export does not
|
||||
inherit the last one's folder skeleton.
|
||||
"""
|
||||
data = _read_manifest(destination)
|
||||
for name in data.get("files", []):
|
||||
path = destination / name
|
||||
if path in keep:
|
||||
continue
|
||||
try:
|
||||
path.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
# `library` is the single-target manifest an older export left behind.
|
||||
libraries = list(data.get("libraries") or []) + [data.get("library")]
|
||||
for name in (*libraries, MANIFEST_NAME):
|
||||
if name:
|
||||
try:
|
||||
(destination / name).unlink()
|
||||
except OSError:
|
||||
pass
|
||||
_prune_empty(destination)
|
||||
|
||||
|
||||
def _prune_empty(root: Path) -> None:
|
||||
try:
|
||||
for folder in sorted(
|
||||
(p for p in root.rglob("*") if p.is_dir()),
|
||||
key=lambda p: len(p.parts),
|
||||
reverse=True,
|
||||
):
|
||||
try:
|
||||
folder.rmdir()
|
||||
except OSError:
|
||||
pass # not empty — the user's own files live here
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _read_manifest(destination: Path) -> dict:
|
||||
from . import paths
|
||||
|
||||
data = paths.read_json(manifest_path(destination), {})
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def _write_manifest(destination: Path, *, libraries: list[str], files: list[str],
|
||||
audio: dict[str, dict], name: str) -> None:
|
||||
from . import paths
|
||||
|
||||
paths.write_json(
|
||||
manifest_path(destination),
|
||||
{
|
||||
"note": "Written by Konduktor. It lists what this export put here, "
|
||||
"so re-exporting can replace exactly those files.",
|
||||
"export": name,
|
||||
"written": time.time(),
|
||||
"libraries": libraries,
|
||||
"files": files,
|
||||
"audio": audio,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _record(planned: PlannedTrack, copy: Path) -> dict:
|
||||
"""What the manifest remembers about one copied file.
|
||||
|
||||
The SOURCE's size and mtime as planned — if it changed during the copy, the
|
||||
next export sees a mismatch and copies again, which is the safe direction —
|
||||
and the COPY's as read back now, never assumed equal to the source's: a
|
||||
FAT32 stick keeps mtimes to 2 s, so `copystat` does not round-trip there.
|
||||
"""
|
||||
st = copy.stat()
|
||||
return {
|
||||
"source": str(planned.source_path),
|
||||
"size": planned.size,
|
||||
"mtime_ns": planned.mtime_ns,
|
||||
"copy_size": st.st_size,
|
||||
"copy_mtime_ns": st.st_mtime_ns,
|
||||
}
|
||||
|
||||
|
||||
def _previous_copies(destination: Path) -> dict[str, tuple[Path, dict]]:
|
||||
"""The last export's copies, by SOURCE path — not by where they sit, since
|
||||
adding a track from another folder moves the shared root and with it every
|
||||
destination path. No record (none yet, an older manifest, an unreadable
|
||||
one) means nothing is reused: never guess from the files on disk."""
|
||||
if not is_ours(destination):
|
||||
return {}
|
||||
audio = _read_manifest(destination).get("audio")
|
||||
out: dict[str, tuple[Path, dict]] = {}
|
||||
if isinstance(audio, dict):
|
||||
for rel, record in audio.items():
|
||||
if isinstance(record, dict) and isinstance(record.get("source"), str):
|
||||
out[record["source"]] = (destination / rel, record)
|
||||
return out
|
||||
|
||||
|
||||
def _reusable(planned: PlannedTrack, previous: dict[str, tuple[Path, dict]]) -> Path | None:
|
||||
"""The previous copy of this file, if neither it nor its source changed."""
|
||||
found = previous.get(str(planned.source_path))
|
||||
if found is None:
|
||||
return None
|
||||
copy, record = found
|
||||
if (record.get("size"), record.get("mtime_ns")) != (planned.size, planned.mtime_ns):
|
||||
return None
|
||||
try:
|
||||
st = copy.stat()
|
||||
except OSError:
|
||||
return None
|
||||
# The copy is checked too: a file edited or replaced ON the stick is not
|
||||
# the one this export would have written.
|
||||
if (st.st_size, st.st_mtime_ns) != (record.get("copy_size"), record.get("copy_mtime_ns")):
|
||||
return None
|
||||
return copy
|
||||
|
||||
|
||||
# ---- planning ----------------------------------------------------------------
|
||||
|
||||
|
||||
def plan(adapter, export_set) -> ExportPlan:
|
||||
"""Resolve the set and work out where every file lands. Reads only."""
|
||||
destination = Path(export_set.destination).expanduser()
|
||||
built = ExportPlan(destination=destination)
|
||||
|
||||
exporters = [for_platform(t) for t in export_set.targets]
|
||||
if not exporters or None in exporters:
|
||||
built.blocked = BLOCKED_NO_TARGET
|
||||
return built
|
||||
|
||||
resolved = exports.resolve(adapter, export_set)
|
||||
tracks = [t for t in (adapter.track(i) for i in resolved.track_ids) if t is not None]
|
||||
|
||||
# The source is the adapter's `audio_path`, never `Track.filepath`: that is
|
||||
# a DISPLAY path, which on Traktor omits the volume and ignores the active
|
||||
# path mapping — so every track off the boot volume (or on a remapped
|
||||
# Windows drive) read as missing and the export was "empty".
|
||||
sources = {t.id: adapter.audio_path(t.id) for t in tracks}
|
||||
|
||||
# Mirror relative to the deepest shared folder, so the export carries the
|
||||
# user's structure without carrying their home directory.
|
||||
present = [str(p) for p in sources.values() if p]
|
||||
root = common_dir_prefix(present) if present else ""
|
||||
|
||||
previous = _previous_copies(destination)
|
||||
claimed: set[Path] = set()
|
||||
for track in tracks:
|
||||
source = sources[track.id]
|
||||
exists = False
|
||||
size = mtime_ns = 0
|
||||
try:
|
||||
exists = bool(source and source.is_file())
|
||||
if exists:
|
||||
st = source.stat()
|
||||
size, mtime_ns = st.st_size, st.st_mtime_ns
|
||||
except OSError:
|
||||
exists = False
|
||||
planned = PlannedTrack(
|
||||
track_id=track.id,
|
||||
title=track.title or (source.name if source else track.id),
|
||||
source_path=source,
|
||||
destination=(destination / AUDIO_DIR / _relative(source, root)) if exists else None,
|
||||
size=size,
|
||||
mtime_ns=mtime_ns,
|
||||
missing=not exists,
|
||||
)
|
||||
if exists:
|
||||
reuse = _reusable(planned, previous)
|
||||
# One kept copy can serve one planned file: two entries sharing a
|
||||
# source would otherwise both try to move it.
|
||||
if reuse is not None and reuse not in claimed:
|
||||
planned.reuse = reuse
|
||||
claimed.add(reuse)
|
||||
built.tracks.append(planned)
|
||||
|
||||
names = {p.id: p for p in resolved.playlists}
|
||||
folders = _folder_paths(adapter)
|
||||
for playlist in resolved.playlists:
|
||||
if playlist.missing or not playlist.track_ids:
|
||||
continue
|
||||
built.playlists.append(
|
||||
ExportPlaylist(
|
||||
name=names[playlist.id].name,
|
||||
track_ids=list(playlist.track_ids),
|
||||
folders=folders.get(playlist.id, []),
|
||||
)
|
||||
)
|
||||
|
||||
if not built.exportable:
|
||||
built.blocked = BLOCKED_EMPTY
|
||||
else:
|
||||
built.blocked = destination_blocked(destination)
|
||||
built.replacing = is_ours(destination)
|
||||
if not is_drive_root(destination):
|
||||
built.not_drive_root = [e.platform for e in exporters if e.drive_root]
|
||||
return built
|
||||
|
||||
|
||||
def _relative(source: Path, root: str) -> Path:
|
||||
"""Where `source` sits under the export root, mirroring its own folders."""
|
||||
text = str(source).replace("\\", "/")
|
||||
if root and text.startswith(root + "/"):
|
||||
return Path(text[len(root) + 1:])
|
||||
# No shared root (tracks on different volumes): keep the full path minus its
|
||||
# leading separator, which is ugly but never collides.
|
||||
return Path(text.lstrip("/"))
|
||||
|
||||
|
||||
def _folder_paths(adapter) -> dict[str, list[str]]:
|
||||
"""Each playlist's folder chain, outermost first."""
|
||||
out: dict[str, list[str]] = {}
|
||||
|
||||
def walk(nodes, path: list[str]) -> None:
|
||||
for node in nodes or []:
|
||||
if node.kind == "folder":
|
||||
walk(getattr(node, "children", None), path + [node.name])
|
||||
else:
|
||||
out[node.id] = path
|
||||
walk(getattr(node, "children", None), path)
|
||||
|
||||
walk(adapter.playlist_tree(), [])
|
||||
return out
|
||||
|
||||
|
||||
# ---- running -----------------------------------------------------------------
|
||||
|
||||
|
||||
def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict:
|
||||
"""Copy what changed, then write every target's library over the audio.
|
||||
|
||||
Rolls back EVERYTHING this run wrote on cancel or on any failure —
|
||||
including the libraries of targets that had already been written when a
|
||||
later one failed. What it KEPT from the previous export stays, and the
|
||||
manifest is rewritten to say so: deleting the manifest with kept files
|
||||
still there would leave a folder the next export refuses as not ours.
|
||||
"""
|
||||
exporters = [for_platform(t) for t in export_set.targets]
|
||||
if not exporters or None in exporters:
|
||||
raise ValueError(f"Konduktor cannot export to {', '.join(export_set.targets)}")
|
||||
if built.blocked:
|
||||
raise ValueError(f"This export cannot run: {built.blocked}")
|
||||
|
||||
destination = Path(built.destination)
|
||||
items = built.exportable
|
||||
handle.progress(done=0, total=built.total_bytes, unit="bytes", message="Preparing…")
|
||||
cache = AnalysisCache(destination / CACHE_DIR)
|
||||
|
||||
# Registered BEFORE each write, so a cancel mid-file removes the partial one
|
||||
# too. Cleaning up only completed copies leaves debris the retry then
|
||||
# suffixes around — a bug the import feature had.
|
||||
created: list[Path] = []
|
||||
# The previous export's copies this one keeps, by where they are NOW — so a
|
||||
# rollback during the moves still records each at its real location.
|
||||
kept: dict[Path, dict] = {}
|
||||
# What was on disk before the libraries were written. An exporter that
|
||||
# raises midway has written files it never got to REPORT (a OneLibrary
|
||||
# drive's analysis files, say), so rollback also removes anything that
|
||||
# appeared after this snapshot. Safe because the destination is known to
|
||||
# hold only our files and the user's, and the user's predate it.
|
||||
before: set[Path] | None = None
|
||||
done = 0
|
||||
try:
|
||||
destination.mkdir(parents=True, exist_ok=True)
|
||||
if is_ours(destination):
|
||||
handle.progress(message="Replacing the previous export…")
|
||||
old = _read_manifest(destination).get("audio") or {}
|
||||
for planned in items:
|
||||
if planned.reuse is not None:
|
||||
record = old.get(_rel(planned.reuse, destination))
|
||||
if record is None:
|
||||
# The manifest changed since the plan: copy after all.
|
||||
planned.reuse = None
|
||||
else:
|
||||
kept[planned.reuse] = record
|
||||
_clear(destination, keep=set(kept))
|
||||
else:
|
||||
for planned in items:
|
||||
planned.reuse = None
|
||||
reused = [t for t in items if t.reuse is not None]
|
||||
handle.progress(total=built.total_bytes)
|
||||
# Written before anything moves or is copied, listing every path this
|
||||
# run may leave behind, so even a crash (not a cancel — nothing gets to
|
||||
# clean up after a crash) leaves a folder the next export can clear.
|
||||
_write_manifest(
|
||||
destination, libraries=[], name=export_set.name,
|
||||
files=sorted({_rel(p, destination) for p in (*kept, *(t.destination for t in items))}
|
||||
| {_rel(_partial(t.destination), destination) for t in items}
|
||||
| {_rel(_staging(destination, i), destination) for i in range(len(reused))}),
|
||||
audio={_rel(p, destination): r for p, r in kept.items()},
|
||||
)
|
||||
if reused:
|
||||
handle.progress(message=f"Keeping {len(reused)} unchanged track{'' if len(reused) == 1 else 's'}…")
|
||||
_move_kept(destination, reused, kept)
|
||||
|
||||
payload_tracks: list[ExportTrack] = []
|
||||
for planned in items:
|
||||
handle.raise_if_cancelled()
|
||||
target = Path(planned.destination)
|
||||
if planned.reuse is None:
|
||||
handle.progress(message=f"Copying {planned.title}")
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
# Copied beside the target and renamed into place, so a cancel
|
||||
# can never leave a half-written file under a real track's name.
|
||||
partial = _partial(target)
|
||||
created += [partial, target]
|
||||
|
||||
def advance(n: int) -> None:
|
||||
nonlocal done
|
||||
done += n
|
||||
handle.progress(done=done)
|
||||
|
||||
copy_file(planned.source_path, partial, handle, advance)
|
||||
os.replace(partial, target)
|
||||
payload_tracks.append(
|
||||
ExportTrack(
|
||||
track=adapter.track(planned.track_id),
|
||||
destination=target,
|
||||
cues=adapter.track_cues(planned.track_id),
|
||||
art=_cover(adapter, planned.track_id),
|
||||
fingerprint=_fingerprint(planned),
|
||||
analysis_cache=cache,
|
||||
)
|
||||
)
|
||||
|
||||
def checkpoint(message: str, step: int | None = None, of: int | None = None) -> None:
|
||||
handle.raise_if_cancelled()
|
||||
if step is not None and of:
|
||||
# The bar follows the library being written, in tracks: after
|
||||
# the copy, the slow part is decoding — and a re-export may
|
||||
# have copied nothing at all.
|
||||
handle.progress(done=step - 1, total=of, unit="tracks", message=message)
|
||||
else:
|
||||
handle.progress(message=message)
|
||||
|
||||
payload = ExportPayload(
|
||||
name=export_set.name,
|
||||
tracks=payload_tracks,
|
||||
playlists=built.playlists,
|
||||
checkpoint=checkpoint,
|
||||
)
|
||||
before = _files(destination)
|
||||
libraries: list[tuple[str, Path]] = []
|
||||
for exporter in exporters:
|
||||
handle.raise_if_cancelled()
|
||||
# Indeterminate until the writer reports its tracks.
|
||||
handle.progress(done=0, total=0, unit="tracks",
|
||||
message=f"Writing the {_display_name(exporter.platform)} library…")
|
||||
written = exporter.write(payload, destination)
|
||||
# Everything the exporter reported, not just the library: a target
|
||||
# can write a database PLUS a per-track analysis file, and anything
|
||||
# left out here is an orphan the next re-export cannot clear.
|
||||
created.extend(written.all_paths)
|
||||
libraries.append((exporter.platform, written.library))
|
||||
|
||||
library_paths = {path for _, path in libraries}
|
||||
audio_paths = {Path(t.destination) for t in items}
|
||||
_write_manifest(
|
||||
destination,
|
||||
libraries=[_rel(p, destination) for _, p in libraries],
|
||||
files=sorted(
|
||||
{_rel(p, destination) for p in (*created, *audio_paths)
|
||||
if p not in library_paths and p.exists()}
|
||||
),
|
||||
audio={_rel(Path(t.destination), destination): _record(t, Path(t.destination))
|
||||
for t in items},
|
||||
name=export_set.name,
|
||||
)
|
||||
# Only what this export's tracks need; an unticked Pioneer target
|
||||
# keeps its entries, since they are keyed by source, not by target.
|
||||
cache.prune({_fingerprint(t) for t in items})
|
||||
return {
|
||||
"tracks": len(payload_tracks),
|
||||
"unchanged": len(reused),
|
||||
"playlists": len(built.playlists),
|
||||
"skipped": len(built.tracks) - len(items),
|
||||
"destination": str(destination),
|
||||
"libraries": [
|
||||
{"platform": platform, "library": _rel(path, destination)}
|
||||
for platform, path in libraries
|
||||
],
|
||||
}
|
||||
except BaseException:
|
||||
# Cancelled or failed: leave no library file and no half-written copies.
|
||||
# Matches import, deliberately — two features whose cancel means
|
||||
# different things is worse than either behaviour on its own.
|
||||
leftovers = (_files(destination) - before) if before is not None else set()
|
||||
for path in (*created, *leftovers):
|
||||
if CACHE_DIR in path.relative_to(destination).parts:
|
||||
continue # measurements of the SOURCE: still true, and ours
|
||||
try:
|
||||
path.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
if kept:
|
||||
# The previous export's files this one kept are still here, so the
|
||||
# folder must still say it is ours — with no library, which is what
|
||||
# marks an export unfinished.
|
||||
_write_manifest(
|
||||
destination, libraries=[], name=export_set.name,
|
||||
files=sorted(_rel(p, destination) for p in kept),
|
||||
audio={_rel(p, destination): r for p, r in kept.items()},
|
||||
)
|
||||
else:
|
||||
# Nothing kept: the folder goes back to having no export in it at
|
||||
# all, cache included, as a first export's cancel always has.
|
||||
cache.clear()
|
||||
try:
|
||||
manifest_path(destination).unlink()
|
||||
except OSError:
|
||||
pass
|
||||
_prune_empty(destination)
|
||||
raise
|
||||
|
||||
|
||||
def _move_kept(destination: Path, reused: list[PlannedTrack], kept: dict[Path, dict]) -> None:
|
||||
"""Rename each kept copy to where this export puts it — instant on one drive.
|
||||
|
||||
In two steps, through a staging folder, because one kept file's new path
|
||||
can be another's old one (the shared root moved), and a direct rename
|
||||
would overwrite a copy that has not moved out of the way yet. `kept` is
|
||||
updated after every rename, so a failure part-way still knows where each
|
||||
file really is.
|
||||
"""
|
||||
moving = [t for t in reused if t.reuse != Path(t.destination)]
|
||||
staged: list[tuple[Path, PlannedTrack]] = []
|
||||
for i, planned in enumerate(moving):
|
||||
stage = _staging(destination, i)
|
||||
stage.parent.mkdir(parents=True, exist_ok=True)
|
||||
os.replace(planned.reuse, stage)
|
||||
kept[stage] = kept.pop(planned.reuse)
|
||||
staged.append((stage, planned))
|
||||
for stage, planned in staged:
|
||||
target = Path(planned.destination)
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
os.replace(stage, target)
|
||||
kept[target] = kept.pop(stage)
|
||||
if staged:
|
||||
_prune_empty(destination)
|
||||
|
||||
|
||||
def _staging(destination: Path, i: int) -> Path:
|
||||
return destination / MOVING_DIR / str(i)
|
||||
|
||||
|
||||
def _partial(target: Path) -> Path:
|
||||
return target.with_name(target.name + PARTIAL_SUFFIX)
|
||||
|
||||
|
||||
def _rel(path: Path, destination: Path) -> str:
|
||||
return str(Path(path).relative_to(destination))
|
||||
|
||||
|
||||
def _fingerprint(planned: PlannedTrack) -> str:
|
||||
return fingerprint(planned.source_path, planned.size, planned.mtime_ns)
|
||||
|
||||
|
||||
def _cover(adapter, track_id: str):
|
||||
"""The source's cover art, or None. A missing or unreadable cover costs the
|
||||
artwork on the stick, never the export."""
|
||||
try:
|
||||
return adapter.cover_art(track_id)
|
||||
except Exception as ex: # noqa: BLE001
|
||||
log.warning("no cover art for %s: %s", track_id, ex)
|
||||
return None
|
||||
|
||||
|
||||
def _files(root: Path) -> set[Path]:
|
||||
try:
|
||||
return {p for p in root.rglob("*") if p.is_file()}
|
||||
except OSError:
|
||||
return set()
|
||||
|
||||
|
||||
def _display_name(platform: str) -> str:
|
||||
try:
|
||||
return registry.driver_by_platform(platform).display_name
|
||||
except registry.LibraryNotSupported:
|
||||
return platform
|
||||
|
||||
|
||||
def space_for(built: ExportPlan) -> int | None:
|
||||
return free_bytes(Path(built.destination)) if built.destination else None
|
||||
|
||||
|
||||
__all__ = [
|
||||
"AUDIO_DIR", "BLOCKED_EMPTY", "BLOCKED_NO_TARGET", "BLOCKED_OCCUPIED", "ExportPlan",
|
||||
"MANIFEST_NAME", "PlannedTrack", "destination_blocked", "is_ours", "plan",
|
||||
"run", "space_for",
|
||||
]
|
||||
@@ -0,0 +1,354 @@
|
||||
"""Export sets: a named, persisted slice of the library, bound to a destination.
|
||||
|
||||
An export set is what the user curates before exporting — a name, one or more
|
||||
target platforms, a destination folder, and the tracks and playlists to include.
|
||||
|
||||
**Several targets share one destination and one copy of the audio.** Each
|
||||
target's library references the same files, and none of their layouts collide
|
||||
(`collection.nml`; `PIONEER/…`; `master.db` + `share/…`), so a stick carrying
|
||||
both a Traktor collection and a OneLibrary library costs one copy, not two. It is
|
||||
**Konduktor's own data**, never written into the user's library: a Traktor
|
||||
collection has nowhere to put this, and putting it there would mean a concept
|
||||
only Konduktor understands living in a file Traktor rewrites.
|
||||
|
||||
Three things shape the design:
|
||||
|
||||
**References are LIVE.** A set stores playlist *ids*, not the tracks that were in
|
||||
them when you dragged one in. They are resolved at export time, so adding a track
|
||||
to a playlist next week means the next export picks it up. The consequence is
|
||||
that the contents of a set can never be cached — `resolve()` asks the adapter
|
||||
every time, and the UI's count changes underneath the user by design.
|
||||
|
||||
**A playlist is removable only as a whole.** A live reference and per-track
|
||||
removal are in tension: honouring both needs an exclusion list, i.e. hidden state
|
||||
that silently decides what a future export contains. Loose tracks are removable
|
||||
individually; for a subset of a playlist, add the tracks instead of the playlist.
|
||||
|
||||
**Keyed by library id, not path.** These are curated work. Keying them on the
|
||||
library's OS path — as everything else in the app still does — would orphan every
|
||||
set the moment the user moves their collection. See `library_id.py`.
|
||||
|
||||
Storage is one JSON file per library under the app-data dir, written atomically
|
||||
via `paths.write_json`. Deliberately NOT `prefs.py`, whose best-effort "any I/O
|
||||
error degrades to no prefs" is right for a window size and wrong for this.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from . import paths
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExportSet:
|
||||
"""One curated export. `destination` is bound at creation, not at run time.
|
||||
|
||||
Bound early because it is not merely convenient: a Traktor `<LOCATION>` is a
|
||||
volume name plus a volume-relative path, both derived from where the export
|
||||
lands, so the library file cannot be written until the destination is known.
|
||||
"""
|
||||
|
||||
id: str
|
||||
name: str
|
||||
#: Platform ids of the export TARGETS, e.g. ["traktor", "onelibrary"]. Never
|
||||
#: empty; ordered as the user ticked them, which is the order they are written.
|
||||
targets: list[str] = field(default_factory=lambda: ["traktor"])
|
||||
destination: str = "" # OS path of the folder the export is written into
|
||||
playlist_ids: list[str] = field(default_factory=list)
|
||||
track_ids: list[str] = field(default_factory=list) # loose tracks only
|
||||
created: float = 0.0
|
||||
modified: float = 0.0
|
||||
|
||||
def as_dict(self) -> dict:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ResolvedPlaylist:
|
||||
"""A referenced playlist, as it stands right now."""
|
||||
|
||||
id: str
|
||||
name: str
|
||||
missing: bool # the playlist has since been deleted
|
||||
track_ids: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ResolvedSet:
|
||||
"""What an export set contains at this instant.
|
||||
|
||||
Never stored. The references are live, so a cached answer would be a lie the
|
||||
moment the user edits a playlist.
|
||||
"""
|
||||
|
||||
playlists: list[ResolvedPlaylist] = field(default_factory=list)
|
||||
loose_track_ids: list[str] = field(default_factory=list)
|
||||
# Ids in the set that the library no longer has. Surfaced rather than
|
||||
# silently dropped: a gig stick quietly missing four tracks is the worst
|
||||
# failure this feature has.
|
||||
dangling_track_ids: list[str] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def track_ids(self) -> list[str]:
|
||||
"""Every track this export would carry, DEDUPED, in a stable order.
|
||||
|
||||
A track referenced both loosely and through a playlist is one track and
|
||||
one file copy. Playlists come first so the order follows the tree the
|
||||
user sees.
|
||||
"""
|
||||
seen: set[str] = set()
|
||||
out: list[str] = []
|
||||
for playlist in self.playlists:
|
||||
for track_id in playlist.track_ids:
|
||||
if track_id not in seen:
|
||||
seen.add(track_id)
|
||||
out.append(track_id)
|
||||
for track_id in self.loose_track_ids:
|
||||
if track_id not in seen:
|
||||
seen.add(track_id)
|
||||
out.append(track_id)
|
||||
return out
|
||||
|
||||
|
||||
# ---- storage -----------------------------------------------------------------
|
||||
|
||||
|
||||
def _store_path(library_id: str) -> Path:
|
||||
return paths.app_data_dir() / "exports" / f"{library_id}.json"
|
||||
|
||||
|
||||
def _load(library_id: str) -> dict[str, ExportSet]:
|
||||
data = paths.read_json(_store_path(library_id), {})
|
||||
raw = data.get("sets") if isinstance(data, dict) else None
|
||||
out: dict[str, ExportSet] = {}
|
||||
if isinstance(raw, dict):
|
||||
for set_id, values in raw.items():
|
||||
if not isinstance(values, dict):
|
||||
continue
|
||||
try:
|
||||
out[set_id] = ExportSet(
|
||||
id=set_id,
|
||||
name=values.get("name") or "Untitled",
|
||||
targets=_targets(values),
|
||||
destination=values.get("destination") or "",
|
||||
playlist_ids=list(values.get("playlist_ids") or []),
|
||||
track_ids=list(values.get("track_ids") or []),
|
||||
created=float(values.get("created") or 0.0),
|
||||
modified=float(values.get("modified") or 0.0),
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
log.warning("skipping unreadable export set %s", set_id)
|
||||
return out
|
||||
|
||||
|
||||
def _targets(values: dict) -> list[str]:
|
||||
"""The set's targets, reading the single `target` sets were saved with first."""
|
||||
raw = values.get("targets")
|
||||
if isinstance(raw, list):
|
||||
found = [t for t in raw if isinstance(t, str) and t]
|
||||
if found:
|
||||
return found
|
||||
return [values.get("target") or "traktor"]
|
||||
|
||||
|
||||
def _save(library_id: str, sets: dict[str, ExportSet]) -> None:
|
||||
paths.write_json(
|
||||
_store_path(library_id),
|
||||
{"library_id": library_id, "sets": {k: v.as_dict() for k, v in sets.items()}},
|
||||
)
|
||||
|
||||
|
||||
# ---- reading -----------------------------------------------------------------
|
||||
|
||||
|
||||
def all_sets(library_id: str) -> list[ExportSet]:
|
||||
"""Every export set for one library, oldest first so the list is stable."""
|
||||
return sorted(_load(library_id).values(), key=lambda s: (s.created, s.name.lower()))
|
||||
|
||||
|
||||
def get(library_id: str, set_id: str) -> ExportSet | None:
|
||||
return _load(library_id).get(set_id)
|
||||
|
||||
|
||||
def destination_conflict(library_id: str, destination: str, *, ignore: str | None = None) -> str | None:
|
||||
"""The name of another set already pointing at `destination`, if any.
|
||||
|
||||
An export CLEARS its destination before writing, so two sets sharing one
|
||||
folder means the second silently wipes the first's output. Caught when the
|
||||
destination is chosen rather than at run time, where it would already be too
|
||||
late to be a warning.
|
||||
"""
|
||||
target = _normalise(destination)
|
||||
if not target:
|
||||
return None
|
||||
for existing in _load(library_id).values():
|
||||
if existing.id != ignore and _normalise(existing.destination) == target:
|
||||
return existing.name
|
||||
return None
|
||||
|
||||
|
||||
def _normalise(destination: str) -> str:
|
||||
try:
|
||||
return str(Path(destination).expanduser().resolve())
|
||||
except (OSError, ValueError):
|
||||
return destination.strip()
|
||||
|
||||
|
||||
# ---- writing -----------------------------------------------------------------
|
||||
|
||||
|
||||
def create(library_id: str, *, name: str, targets: list[str], destination: str) -> ExportSet:
|
||||
sets = _load(library_id)
|
||||
now = time.time()
|
||||
created = ExportSet(
|
||||
id=uuid.uuid4().hex,
|
||||
name=name.strip() or "Untitled",
|
||||
targets=list(dict.fromkeys(targets)),
|
||||
destination=destination,
|
||||
created=now,
|
||||
modified=now,
|
||||
)
|
||||
sets[created.id] = created
|
||||
_save(library_id, sets)
|
||||
return created
|
||||
|
||||
|
||||
def update(library_id: str, set_id: str, **fields) -> ExportSet | None:
|
||||
"""Rename, retarget or relocate a set. Unknown fields are ignored."""
|
||||
sets = _load(library_id)
|
||||
found = sets.get(set_id)
|
||||
if found is None:
|
||||
return None
|
||||
for key in ("name", "destination"):
|
||||
if key in fields and fields[key] is not None:
|
||||
setattr(found, key, fields[key])
|
||||
if fields.get("targets"):
|
||||
found.targets = list(dict.fromkeys(fields["targets"]))
|
||||
found.modified = time.time()
|
||||
_save(library_id, sets)
|
||||
return found
|
||||
|
||||
|
||||
def delete(library_id: str, set_id: str) -> bool:
|
||||
"""Forget a set. Deliberately does NOT touch its destination folder."""
|
||||
sets = _load(library_id)
|
||||
if sets.pop(set_id, None) is None:
|
||||
return False
|
||||
_save(library_id, sets)
|
||||
return True
|
||||
|
||||
|
||||
def add(library_id: str, set_id: str, *, track_ids=None, playlist_ids=None) -> ExportSet | None:
|
||||
"""Add tracks and/or playlists, preserving order and ignoring duplicates."""
|
||||
sets = _load(library_id)
|
||||
found = sets.get(set_id)
|
||||
if found is None:
|
||||
return None
|
||||
for incoming, existing in (
|
||||
(track_ids or [], found.track_ids),
|
||||
(playlist_ids or [], found.playlist_ids),
|
||||
):
|
||||
have = set(existing)
|
||||
for item in incoming:
|
||||
if item not in have:
|
||||
have.add(item)
|
||||
existing.append(item)
|
||||
found.modified = time.time()
|
||||
_save(library_id, sets)
|
||||
return found
|
||||
|
||||
|
||||
def remove(library_id: str, set_id: str, *, track_ids=None, playlist_ids=None) -> ExportSet | None:
|
||||
"""Remove loose tracks and/or whole playlists.
|
||||
|
||||
There is no "remove a track from a referenced playlist": see the module
|
||||
docstring. A track id passed here is dropped from the LOOSE list only, so
|
||||
removing one that a referenced playlist also supplies is a no-op — which is
|
||||
honest, because the playlist still puts it in the export.
|
||||
"""
|
||||
sets = _load(library_id)
|
||||
found = sets.get(set_id)
|
||||
if found is None:
|
||||
return None
|
||||
if track_ids:
|
||||
drop = set(track_ids)
|
||||
found.track_ids = [t for t in found.track_ids if t not in drop]
|
||||
if playlist_ids:
|
||||
drop = set(playlist_ids)
|
||||
found.playlist_ids = [p for p in found.playlist_ids if p not in drop]
|
||||
found.modified = time.time()
|
||||
_save(library_id, sets)
|
||||
return found
|
||||
|
||||
|
||||
def retarget(library_id: str, mapping: dict[str, str]) -> None:
|
||||
"""Follow track ids that changed, e.g. after an OS-path remap.
|
||||
|
||||
A Traktor track id IS its path, so a remap renames every id in the library.
|
||||
Without this a set's references would dangle silently — and silently is the
|
||||
problem, since the set would still look fine and export fewer tracks.
|
||||
"""
|
||||
if not mapping:
|
||||
return
|
||||
sets = _load(library_id)
|
||||
touched = False
|
||||
for found in sets.values():
|
||||
renamed = [mapping.get(t, t) for t in found.track_ids]
|
||||
if renamed != found.track_ids:
|
||||
found.track_ids = renamed
|
||||
found.modified = time.time()
|
||||
touched = True
|
||||
if touched:
|
||||
_save(library_id, sets)
|
||||
|
||||
|
||||
# ---- resolution --------------------------------------------------------------
|
||||
|
||||
|
||||
def resolve(adapter, export_set: ExportSet) -> ResolvedSet:
|
||||
"""What this set contains RIGHT NOW, against the loaded library.
|
||||
|
||||
Computed on every call and never stored, because the references are live —
|
||||
the whole point is that a playlist edited after curation is picked up.
|
||||
"""
|
||||
resolved = ResolvedSet()
|
||||
names = _playlist_names(adapter)
|
||||
|
||||
for playlist_id in export_set.playlist_ids:
|
||||
entries = adapter.playlist_entries(playlist_id)
|
||||
resolved.playlists.append(
|
||||
ResolvedPlaylist(
|
||||
id=playlist_id,
|
||||
name=names.get(playlist_id, playlist_id),
|
||||
# A playlist deleted since curation. Shown, not dropped: the set
|
||||
# is the user's record of intent and losing it silently is worse
|
||||
# than showing something broken.
|
||||
missing=entries is None,
|
||||
track_ids=list(entries or []),
|
||||
)
|
||||
)
|
||||
|
||||
for track_id in export_set.track_ids:
|
||||
if adapter.track(track_id) is None:
|
||||
resolved.dangling_track_ids.append(track_id)
|
||||
else:
|
||||
resolved.loose_track_ids.append(track_id)
|
||||
return resolved
|
||||
|
||||
|
||||
def _playlist_names(adapter) -> dict[str, str]:
|
||||
out: dict[str, str] = {}
|
||||
|
||||
def walk(nodes) -> None:
|
||||
for node in nodes or []:
|
||||
out[node.id] = node.name
|
||||
walk(getattr(node, "children", None))
|
||||
|
||||
walk(adapter.playlist_tree())
|
||||
return out
|
||||
@@ -0,0 +1,205 @@
|
||||
"""Per-collection version history backed by a purely-local git repo (dulwich).
|
||||
|
||||
Replaces the old ``.bak`` copy-on-save. Every Konduktor write to a collection is
|
||||
committed to a small git repo — one per collection — living in the app-data dir
|
||||
(NOT next to the user's collection). Git's delta packing makes near-identical
|
||||
NMLs almost free, so we keep full history forever; a manual "delete all history"
|
||||
is the only pruning.
|
||||
|
||||
Design rules:
|
||||
* ALL git interaction is confined to this module.
|
||||
* EVERY public function is best-effort: it swallows its own errors (returning a
|
||||
safe empty/None value) so a history failure can never break a save or an open.
|
||||
* The tracked file is named after the library itself; the
|
||||
repo is keyed by a hash of the collection's absolute OS path (mirrors prefs'
|
||||
path-based keying). Collection identity is therefore the OS path — moving the
|
||||
collection starts a fresh history (same fragility prefs already accepts).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import shutil
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from dulwich import porcelain
|
||||
from dulwich.repo import Repo
|
||||
|
||||
from . import paths
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
_LEGACY_TRACKED_NAME = "collection.nml"
|
||||
|
||||
|
||||
def _tracked_name(library_path: Path) -> str:
|
||||
"""The file name used inside the repo.
|
||||
|
||||
Was hard-coded to ``collection.nml``. Using the library's own name lets a
|
||||
non-Traktor library be versioned the same way; reads fall back to the legacy
|
||||
name so histories recorded before this change stay readable.
|
||||
"""
|
||||
return Path(library_path).name
|
||||
_AUTHOR = b"Konduktor <konduktor@localhost>"
|
||||
|
||||
|
||||
@dataclass
|
||||
class HistoryEntry:
|
||||
id: str # full commit sha (hex)
|
||||
timestamp: str # ISO 8601, UTC
|
||||
summary: str # first line of the commit message
|
||||
|
||||
|
||||
# ---- repo location -----------------------------------------------------------
|
||||
|
||||
def _key(nml_path: Path) -> str:
|
||||
return hashlib.sha256(str(Path(nml_path).resolve()).encode()).hexdigest()[:16]
|
||||
|
||||
|
||||
def _repo_dir(nml_path: Path) -> Path:
|
||||
return paths.app_data_dir() / "history" / _key(nml_path)
|
||||
|
||||
|
||||
def _tracked_file(repo_dir: Path, nml_path: Path) -> Path:
|
||||
return repo_dir / _tracked_name(nml_path)
|
||||
|
||||
|
||||
def _write_meta(repo_dir: Path, nml_path: Path) -> None:
|
||||
"""A tiny sidecar recording which collection this repo belongs to (for
|
||||
debugging / a friendly display name). Best-effort."""
|
||||
try:
|
||||
meta = {"path": str(Path(nml_path).resolve()), "name": Path(nml_path).parent.name}
|
||||
(repo_dir / ".meta.json").write_text(json.dumps(meta, indent=2))
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _open_or_init(nml_path: Path) -> Path:
|
||||
"""Ensure the collection's repo exists; return its directory."""
|
||||
repo_dir = _repo_dir(nml_path)
|
||||
if not (repo_dir / ".git").exists():
|
||||
repo_dir.mkdir(parents=True, exist_ok=True)
|
||||
porcelain.init(str(repo_dir))
|
||||
_write_meta(repo_dir, nml_path)
|
||||
return repo_dir
|
||||
|
||||
|
||||
def _tree_blob(tree, nml_path: Path):
|
||||
"""Find the tracked blob in a commit's tree.
|
||||
|
||||
Tries the library's own name first, then the legacy fixed name, then — if the
|
||||
repo holds exactly one file — that one, so a history written under any past
|
||||
naming rule stays readable.
|
||||
"""
|
||||
for name in (_tracked_name(nml_path), _LEGACY_TRACKED_NAME):
|
||||
try:
|
||||
return tree[name.encode()]
|
||||
except KeyError:
|
||||
continue
|
||||
items = list(tree.items())
|
||||
if len(items) == 1:
|
||||
return items[0].mode, items[0].sha
|
||||
raise KeyError(f"no tracked file in history for {nml_path}")
|
||||
|
||||
|
||||
def _head_blob(repo: Repo, nml_path: Path) -> bytes | None:
|
||||
"""The tracked file's bytes at HEAD, or None if the repo has no commits."""
|
||||
try:
|
||||
head = repo.head()
|
||||
except KeyError:
|
||||
return None
|
||||
commit = repo[head]
|
||||
tree = repo[commit.tree]
|
||||
try:
|
||||
_mode, blob_sha = _tree_blob(tree, nml_path)
|
||||
except KeyError:
|
||||
return None
|
||||
return repo[blob_sha].data
|
||||
|
||||
|
||||
# ---- public API --------------------------------------------------------------
|
||||
|
||||
def commit(nml_path: Path, data: bytes, message: str, app_version: str) -> str | None:
|
||||
"""Commit ``data`` as the collection's newest version. Deduped: if ``data``
|
||||
is byte-identical to HEAD, no commit is made and None is returned. Returns
|
||||
the new commit sha (hex) on success, None on dedup or any failure."""
|
||||
try:
|
||||
repo_dir = _open_or_init(nml_path)
|
||||
with Repo(str(repo_dir)) as repo:
|
||||
if _head_blob(repo, nml_path) == data:
|
||||
return None # nothing changed since last version
|
||||
path = _tracked_file(repo_dir, nml_path)
|
||||
path.write_bytes(data)
|
||||
porcelain.add(str(repo_dir), paths=[str(path)])
|
||||
msg = f"{message}\n\nApp-Version: {app_version}".encode()
|
||||
sha = porcelain.commit(str(repo_dir), message=msg, author=_AUTHOR, committer=_AUTHOR)
|
||||
return sha.decode() if isinstance(sha, bytes) else str(sha)
|
||||
except Exception: # best-effort — history must never break a save
|
||||
log.exception("history.commit failed for %s", nml_path)
|
||||
return None
|
||||
|
||||
|
||||
def ensure_baseline(nml_path: Path) -> None:
|
||||
"""Commit the current on-disk collection as an "as I found it" baseline.
|
||||
Deduped, so re-opening an unchanged collection is a no-op. Best-effort."""
|
||||
try:
|
||||
data = Path(nml_path).read_bytes()
|
||||
except OSError:
|
||||
return
|
||||
commit(nml_path, data, "Baseline — opened collection", _app_version())
|
||||
|
||||
|
||||
def list_history(nml_path: Path) -> list[HistoryEntry]:
|
||||
"""All versions, newest first. Empty list if no history / on any failure."""
|
||||
repo_dir = _repo_dir(nml_path)
|
||||
if not (repo_dir / ".git").exists():
|
||||
return []
|
||||
try:
|
||||
entries: list[HistoryEntry] = []
|
||||
with Repo(str(repo_dir)) as repo:
|
||||
try:
|
||||
repo.head()
|
||||
except KeyError:
|
||||
return []
|
||||
for e in repo.get_walker():
|
||||
c = e.commit
|
||||
ts = datetime.fromtimestamp(c.commit_time, tz=timezone.utc).isoformat()
|
||||
summary = c.message.decode("utf-8", "replace").splitlines()[0] if c.message else ""
|
||||
entries.append(HistoryEntry(id=c.id.decode(), timestamp=ts, summary=summary))
|
||||
return entries
|
||||
except Exception:
|
||||
log.exception("history.list_history failed for %s", nml_path)
|
||||
return []
|
||||
|
||||
|
||||
def read_version(nml_path: Path, commit_id: str) -> bytes | None:
|
||||
"""The tracked collection bytes at a specific commit, or None on failure."""
|
||||
repo_dir = _repo_dir(nml_path)
|
||||
if not (repo_dir / ".git").exists():
|
||||
return None
|
||||
try:
|
||||
with Repo(str(repo_dir)) as repo:
|
||||
c = repo[commit_id.encode()]
|
||||
tree = repo[c.tree]
|
||||
_mode, blob_sha = _tree_blob(tree, nml_path)
|
||||
return repo[blob_sha].data
|
||||
except Exception:
|
||||
log.exception("history.read_version failed for %s @ %s", nml_path, commit_id)
|
||||
return None
|
||||
|
||||
|
||||
def clear_history(nml_path: Path) -> None:
|
||||
"""Delete ALL version history for a collection (removes its repo). Best-effort."""
|
||||
try:
|
||||
shutil.rmtree(_repo_dir(nml_path), ignore_errors=True)
|
||||
except Exception:
|
||||
log.exception("history.clear_history failed for %s", nml_path)
|
||||
|
||||
|
||||
def _app_version() -> str:
|
||||
from . import __version__
|
||||
|
||||
return __version__
|
||||
@@ -0,0 +1,438 @@
|
||||
"""Importing tracks from a source library into the loaded one.
|
||||
|
||||
App-level, not adapter-level, and deliberately so: this coordinates TWO
|
||||
libraries, and neither adapter should know the other exists. The source is asked
|
||||
for generic tracks and cues; the destination is handed generic `NewTrack`s. The
|
||||
only thing this module adds is everything in between — the audio copy, the
|
||||
pre-scan, and the playlist reconstruction.
|
||||
|
||||
**The copy is this module's job, not the adapter's.** `NewTrack.audio_path` must
|
||||
already exist when it reaches the destination, because a file copy that failed
|
||||
halfway is not something a library write should be discovering.
|
||||
|
||||
Scope, chosen deliberately: **everything is added as a new entry**. Nothing is
|
||||
matched against tracks the destination already holds by metadata, so there is no
|
||||
merge policy and no cross-platform identity problem. Re-importing the same stick
|
||||
duplicates, and a preview warns about that rather than preventing it.
|
||||
|
||||
The one match that IS made is by **file**: a source file the destination already
|
||||
points at is never added again. Copying never hits that (it writes a fresh
|
||||
path), but **referencing in place** does — the folder browser can add
|
||||
`~/Music/x.mp3` to a collection that already holds it — and on Traktor two
|
||||
entries for one path share a primary key, which is a corrupt collection rather
|
||||
than a duplicate track. Such a file maps to the EXISTING track instead, so a
|
||||
playlist or export it was headed for still gets it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from .core.adapter import NewTrack
|
||||
from .jobs import JobHandle
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
# Copy in chunks so a cancel lands within a few milliseconds rather than at the
|
||||
# end of a 50 MB file, and so progress can move within one big track.
|
||||
COPY_CHUNK = 1024 * 1024
|
||||
|
||||
# Leave the destination some room rather than filling it exactly. A disk with
|
||||
# zero bytes free is a broken machine, not a successful import.
|
||||
SPACE_HEADROOM = 64 * 1024 * 1024
|
||||
|
||||
|
||||
@dataclass
|
||||
class PlannedTrack:
|
||||
track_id: str # the id in the SOURCE library
|
||||
title: str
|
||||
source_path: Path | None
|
||||
size: int = 0
|
||||
missing: bool = False
|
||||
# True when the destination already holds a track with this filename. Only a
|
||||
# warning: the user chose "add everything as new entries".
|
||||
duplicate: bool = False
|
||||
# The destination's own id for this exact file, when it already holds it.
|
||||
# Not added again; it stands in for the new id wherever one is needed.
|
||||
existing_id: str | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class ImportPlan:
|
||||
tracks: list[PlannedTrack] = field(default_factory=list)
|
||||
playlists: list[tuple[str, str]] = field(default_factory=list) # (id, name)
|
||||
destination: Path | None = None
|
||||
|
||||
@property
|
||||
def importable(self) -> list[PlannedTrack]:
|
||||
return [t for t in self.tracks if not t.missing and t.existing_id is None]
|
||||
|
||||
@property
|
||||
def existing(self) -> list[PlannedTrack]:
|
||||
return [t for t in self.tracks if t.existing_id is not None]
|
||||
|
||||
@property
|
||||
def total_bytes(self) -> int:
|
||||
return sum(t.size for t in self.importable)
|
||||
|
||||
def as_dict(self, free_bytes: int | None = None) -> dict:
|
||||
return {
|
||||
"tracks": len(self.tracks),
|
||||
"importable": len(self.importable),
|
||||
"missing": [t.title for t in self.tracks if t.missing],
|
||||
"duplicates": [t.title for t in self.tracks if t.duplicate],
|
||||
"existing": [t.title for t in self.existing],
|
||||
"playlists": [name for _, name in self.playlists],
|
||||
"total_bytes": self.total_bytes,
|
||||
"destination": str(self.destination) if self.destination else None,
|
||||
"free_bytes": free_bytes,
|
||||
"enough_space": (
|
||||
None if free_bytes is None
|
||||
else free_bytes >= self.total_bytes + SPACE_HEADROOM
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _existing_filenames(dest) -> set[str]:
|
||||
out: set[str] = set()
|
||||
for track in dest.tracks:
|
||||
path = getattr(track, "filepath", None)
|
||||
if path:
|
||||
out.add(Path(path).name.lower())
|
||||
return out
|
||||
|
||||
|
||||
def _key(path: Path) -> str:
|
||||
return os.path.normcase(os.path.normpath(str(path)))
|
||||
|
||||
|
||||
def _existing_files(dest) -> dict[str, str]:
|
||||
"""Every audio file the destination points at → its track id.
|
||||
|
||||
Resolved through the adapter's own `audio_path`, which is the only answer
|
||||
that includes the volume and the active path mapping; the projected
|
||||
`filepath` is a display string and is not good enough to match on.
|
||||
"""
|
||||
out: dict[str, str] = {}
|
||||
for track in dest.tracks:
|
||||
try:
|
||||
path = dest.audio_path(track.id)
|
||||
except Exception: # noqa: BLE001
|
||||
path = None
|
||||
if path is not None:
|
||||
out.setdefault(_key(path), track.id)
|
||||
return out
|
||||
|
||||
|
||||
def plan(source, dest, destination: Path | None, *, track_ids=None, playlist_ids=None) -> ImportPlan:
|
||||
"""Work out what an import would do, WITHOUT doing any of it.
|
||||
|
||||
Computed fresh every time and never stored. Playlist membership on the source
|
||||
can change between planning and importing (a stick can be re-exported), and a
|
||||
stale preview is worse than no preview.
|
||||
|
||||
Playlist selection AUTO-INCLUDES the tracks in those playlists, and the whole
|
||||
set is deduplicated, so a track in three chosen playlists is copied once.
|
||||
"""
|
||||
plan = ImportPlan(destination=destination)
|
||||
wanted: list[str] = []
|
||||
seen: set[str] = set()
|
||||
|
||||
def want(track_id: str) -> None:
|
||||
if track_id not in seen:
|
||||
seen.add(track_id)
|
||||
wanted.append(track_id)
|
||||
|
||||
for node_id in playlist_ids or []:
|
||||
node_tracks = source.playlist_tracks(node_id) or []
|
||||
for t in node_tracks:
|
||||
want(t.id)
|
||||
name = _playlist_name(source, node_id)
|
||||
if name:
|
||||
plan.playlists.append((node_id, name))
|
||||
|
||||
for track_id in track_ids or []:
|
||||
want(track_id)
|
||||
|
||||
# Neither given: the whole drive.
|
||||
if not (track_ids or playlist_ids):
|
||||
for t in source.tracks:
|
||||
want(t.id)
|
||||
for node_id, name in _all_playlists(source):
|
||||
plan.playlists.append((node_id, name))
|
||||
|
||||
existing = _existing_filenames(dest)
|
||||
held = _existing_files(dest)
|
||||
for track_id in wanted:
|
||||
track = source.track(track_id)
|
||||
if track is None:
|
||||
continue
|
||||
raw = getattr(track, "filepath", None)
|
||||
path = Path(raw) if raw else None
|
||||
planned = PlannedTrack(
|
||||
track_id=track_id,
|
||||
title=track.title or (path.name if path else track_id),
|
||||
source_path=path,
|
||||
)
|
||||
try:
|
||||
if path is not None and path.is_file():
|
||||
planned.size = path.stat().st_size
|
||||
planned.existing_id = held.get(_key(path))
|
||||
planned.duplicate = planned.existing_id is None and path.name.lower() in existing
|
||||
else:
|
||||
planned.missing = True
|
||||
except OSError:
|
||||
planned.missing = True
|
||||
plan.tracks.append(planned)
|
||||
return plan
|
||||
|
||||
|
||||
def _playlist_name(source, node_id: str) -> str | None:
|
||||
for nid, name in _all_playlists(source):
|
||||
if nid == node_id:
|
||||
return name
|
||||
return None
|
||||
|
||||
|
||||
def _all_playlists(source) -> list[tuple[str, str]]:
|
||||
"""Every selectable playlist on the source, flattened.
|
||||
|
||||
Folders are dropped rather than recreated. The destination gets ONE folder,
|
||||
named after the drive, and nesting a stick's folder tree inside it would bury
|
||||
the playlists a user is trying to find.
|
||||
"""
|
||||
out: list[tuple[str, str]] = []
|
||||
|
||||
def walk(nodes):
|
||||
for n in nodes:
|
||||
if n.kind == "playlist":
|
||||
out.append((n.id, n.name))
|
||||
walk(n.children or [])
|
||||
|
||||
walk(source.playlist_tree())
|
||||
return out
|
||||
|
||||
|
||||
def free_bytes(path: Path) -> int | None:
|
||||
try:
|
||||
target = path if path.exists() else path.parent
|
||||
return shutil.disk_usage(target).free
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def _unique_target(folder: Path, name: str, taken: set[str]) -> Path:
|
||||
"""A free filename in `folder`, suffixing on collision.
|
||||
|
||||
`taken` covers names claimed earlier in THIS run, which the filesystem cannot
|
||||
answer for — two sticks can both hold `Track.mp3`, and the first copy has not
|
||||
necessarily been written yet when the second is planned.
|
||||
|
||||
Known consequence of suffixing by processing order (accepted in the export
|
||||
design): re-importing may assign a different suffix to the same track.
|
||||
"""
|
||||
stem, dot, ext = name.rpartition(".")
|
||||
if not dot:
|
||||
stem, ext = name, ""
|
||||
candidate = name
|
||||
n = 1
|
||||
while candidate.lower() in taken or (folder / candidate).exists():
|
||||
n += 1
|
||||
candidate = f"{stem}-{n}{'.' + ext if ext else ''}"
|
||||
taken.add(candidate.lower())
|
||||
return folder / candidate
|
||||
|
||||
|
||||
def copy_file(src: Path, dst: Path, handle: JobHandle, on_bytes) -> None:
|
||||
"""Copy a file, checking for cancellation between chunks.
|
||||
|
||||
Public because export copies audio the same way and for the same reason: a
|
||||
second chunked-copy loop would be a second place for the cancel check to be
|
||||
forgotten, and a forgotten cancel check is invisible until someone tries to
|
||||
stop a multi-gigabyte copy.
|
||||
"""
|
||||
with src.open("rb") as fin, dst.open("wb") as fout:
|
||||
while True:
|
||||
handle.raise_if_cancelled()
|
||||
chunk = fin.read(COPY_CHUNK)
|
||||
if not chunk:
|
||||
break
|
||||
fout.write(chunk)
|
||||
on_bytes(len(chunk))
|
||||
shutil.copystat(src, dst, follow_symlinks=True)
|
||||
|
||||
|
||||
def run(
|
||||
source,
|
||||
dest,
|
||||
plan: ImportPlan,
|
||||
handle: JobHandle,
|
||||
*,
|
||||
folder_name: str | None = None,
|
||||
reference: bool = False,
|
||||
into_playlist: str | None = None,
|
||||
) -> dict:
|
||||
"""Perform the import. Returns a summary dict for the job result.
|
||||
|
||||
Ordering is the safety property. Audio is copied FIRST and the library is
|
||||
written LAST, so a cancel or a failure during the long part leaves the
|
||||
collection untouched and the copied files are removed on the way out. Once
|
||||
copying is done the library write is fast and is allowed to finish.
|
||||
|
||||
This is a COMMITTED action — it saves at the end — rather than an in-memory
|
||||
edit the Save button flushes. A multi-gigabyte copy is not a pending tweak,
|
||||
and audio on disk with unsaved entries pointing at it is the worst of both.
|
||||
|
||||
`reference` adds each file WHERE IT IS instead of copying it, so there is no
|
||||
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.
|
||||
"""
|
||||
destination = plan.destination
|
||||
if not reference:
|
||||
assert destination is not None
|
||||
destination.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
importable = plan.importable
|
||||
total = plan.total_bytes or len(importable)
|
||||
handle.progress(done=0, total=total, message="Copying audio…")
|
||||
|
||||
copied: list[tuple[PlannedTrack, Path]] = []
|
||||
# Every path this run has opened for writing, including the one being written
|
||||
# when a cancel lands. `copied` holds only COMPLETED copies, so cleaning up
|
||||
# from it leaves the half-written file behind — which then makes the next
|
||||
# attempt suffix around a file that is not really there.
|
||||
created: list[Path] = []
|
||||
taken: set[str] = set()
|
||||
moved = 0
|
||||
|
||||
def bump(n: int) -> None:
|
||||
nonlocal moved
|
||||
moved += n
|
||||
handle.progress(done=moved)
|
||||
|
||||
try:
|
||||
for planned in importable:
|
||||
handle.raise_if_cancelled()
|
||||
assert planned.source_path is not None
|
||||
if reference:
|
||||
copied.append((planned, planned.source_path))
|
||||
continue
|
||||
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))
|
||||
|
||||
handle.raise_if_cancelled()
|
||||
handle.progress(message="Adding tracks to the library…")
|
||||
|
||||
items: list[NewTrack] = []
|
||||
for planned, target in copied:
|
||||
track = source.track(planned.track_id)
|
||||
if track is None:
|
||||
continue
|
||||
cues = None
|
||||
try:
|
||||
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))
|
||||
|
||||
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)
|
||||
by_source = {
|
||||
planned.track_id: new_id
|
||||
for (planned, _), new_id in zip(copied, new_ids)
|
||||
}
|
||||
by_source.update({t.track_id: t.existing_id for t in plan.existing})
|
||||
# Every planned track's id in the destination, in plan order.
|
||||
all_ids = [by_source[t.track_id] for t in plan.tracks if t.track_id in by_source]
|
||||
|
||||
if into_playlist is not None:
|
||||
handle.progress(message="Adding to the playlist…")
|
||||
current = dest.playlist_entries(into_playlist) or []
|
||||
have = set(current)
|
||||
dest.set_playlist_entries(
|
||||
into_playlist, current + [i for i in all_ids if i not in have]
|
||||
)
|
||||
|
||||
playlists_made = _rebuild_playlists(
|
||||
source, dest, plan, by_source, folder_name, handle
|
||||
)
|
||||
|
||||
handle.progress(message="Saving…")
|
||||
outcome, _commit = _save(dest)
|
||||
return {
|
||||
"tracks": len(new_ids),
|
||||
"track_ids": all_ids,
|
||||
"already_held": len(plan.existing),
|
||||
"playlists": playlists_made,
|
||||
"skipped_missing": len([t for t in plan.tracks if t.missing]),
|
||||
"destination": str(destination) if destination else None,
|
||||
"summary": getattr(outcome, "summary", ""),
|
||||
}
|
||||
except BaseException:
|
||||
# A cancelled or failed import must not leave orphaned audio behind: the
|
||||
# library was never written, so those files reference nothing.
|
||||
for target in created:
|
||||
try:
|
||||
target.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
log.debug("could not clean up %s", target, exc_info=True)
|
||||
raise
|
||||
|
||||
|
||||
def _save(dest):
|
||||
"""Save through AppState so the version-history commit is not skipped."""
|
||||
from .app_state import STATE
|
||||
|
||||
if STATE.adapter is dest:
|
||||
return STATE.save()
|
||||
return dest.save(), None
|
||||
|
||||
|
||||
def _rebuild_playlists(source, dest, plan, by_source, folder_name, handle) -> int:
|
||||
"""Recreate the source's playlists in the destination.
|
||||
|
||||
They go into ONE folder named after the drive, so a re-import is easy to find
|
||||
and easy to delete, and the collection's root does not accumulate. A platform
|
||||
that cannot make folders puts them at the root instead — the capability says
|
||||
which, rather than this guessing.
|
||||
"""
|
||||
if not plan.playlists:
|
||||
return 0
|
||||
parent = None
|
||||
if folder_name and dest.capabilities().playlists.folders:
|
||||
try:
|
||||
parent = dest.create_folder(folder_name)
|
||||
except Exception: # noqa: BLE001 — a missing folder is not worth failing over
|
||||
log.debug("could not create folder %r", folder_name, exc_info=True)
|
||||
|
||||
made = 0
|
||||
for node_id, name in plan.playlists:
|
||||
handle.progress(message=f"Recreating playlist {name}")
|
||||
source_tracks = source.playlist_tracks(node_id) or []
|
||||
ids = [by_source[t.id] for t in source_tracks if t.id in by_source]
|
||||
if not ids:
|
||||
continue
|
||||
new_id = dest.create_playlist(name, parent)
|
||||
dest.set_playlist_entries(new_id, ids)
|
||||
made += 1
|
||||
return made
|
||||
Loaded 100 of 285 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user