From 3f51444e2a7485d183cedc9dba34eb6979f6a7cb Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Thu, 17 Sep 2026 15:13:53 +0200 Subject: [PATCH 01/64] Documented multiplatform changes --- ...scuss-multi-platform-library-2026-09-17.md | 635 ++++++++++++++++++ 1 file changed, 635 insertions(+) create mode 100644 .claude/discussions/discuss-multi-platform-library-2026-09-17.md diff --git a/.claude/discussions/discuss-multi-platform-library-2026-09-17.md b/.claude/discussions/discuss-multi-platform-library-2026-09-17.md new file mode 100644 index 0000000..c719780 --- /dev/null +++ b/.claude/discussions/discuss-multi-platform-library-2026-09-17.md @@ -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 `` +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 `` +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 ``. +`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. From dd97f27ac782a9be7fd58561adcadebb1aa597ac Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Thu, 17 Sep 2026 15:14:07 +0200 Subject: [PATCH 02/64] Added support for flexible beatgrids --- CLAUDE.md | 62 +++- backend/konduktor/auto_hotcues.py | 55 +++- backend/konduktor/beatgrid.py | 117 ++++++++ backend/konduktor/collection_service.py | 9 +- backend/konduktor/main.py | 122 +++++--- backend/konduktor/playlist_store.py | 342 +++++++++++++++++++---- backend/konduktor/schemas.py | 39 ++- backend/test_save_fidelity.py | 258 ++++++++++++++--- frontend/package-lock.json | 304 +++++++++++++++++++- frontend/package.json | 6 +- frontend/src/api.ts | 46 ++- frontend/src/components/GridControls.tsx | 193 +++++++++++-- frontend/src/components/HotcueBar.tsx | 27 +- frontend/src/components/LoopControls.tsx | 5 +- frontend/src/components/MainWaveform.tsx | 14 +- frontend/src/components/PrepStrip.tsx | 319 +++++++++++++-------- frontend/src/lib/beatgrid.test.ts | 191 +++++++++++++ frontend/src/lib/beatgrid.ts | 304 ++++++++++++++++++++ frontend/src/lib/cues.ts | 97 +++++-- frontend/src/lib/trackColumns.tsx | 12 +- 20 files changed, 2176 insertions(+), 346 deletions(-) create mode 100644 backend/konduktor/beatgrid.py create mode 100644 frontend/src/lib/beatgrid.test.ts create mode 100644 frontend/src/lib/beatgrid.ts diff --git a/CLAUDE.md b/CLAUDE.md index 743f934..d3931c6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -78,11 +78,14 @@ Two independent apps that talk over HTTP: — its zoom is owned by `PrepStrip` so it survives track switches and persists, `OverviewWaveform` whole-track), `LoopControls`, `HotcueBar`, `GridControls` (BPM readout/editor, fine ±0.01 / coarse ±0.25 BPM nudge, /2·×2, tap tempo, - grid-phase nudge, set beat 1, lock, delete grid). + marker nudge, add/delete marker, lock, delete grid (confirmed) — all on the + marker **governing the playhead**, since a beatgrid is a marker list and + there is no separate marker selection; see "Beatgrid" below). Prep libs live in `src/lib/`: `playbackEngine.ts` (Web Audio, seamless loops), `scratchEngine.ts` (drag-to-scratch), `waveform.ts` (frequency-colored - analysis + paint), `cues.ts` (draw cues/loop/beatgrid/cue-point). See "Prep - engine" below. + analysis + paint), `beatgrid.ts` (the marker-list beat math — every + beat/bar/snap/jump calculation goes through it), `cues.ts` (draw + cues/loop/beatgrid/cue-point). See "Prep engine" below. - `lib/trackColumns.tsx` — single source of truth for the library table's columns (defs, default widths/visibility/order, the Columns-menu list, the inline `InlineEdit` cell, and the `TableMeta.onEditField` augmentation). @@ -110,6 +113,7 @@ uvicorn konduktor.main:app --reload --port 8000 cd frontend npm run dev # dev server (proxies /api -> :8000) npm run build # tsc -b && vite build — run this to typecheck +npm run test # vitest — unit tests for src/lib/beatgrid.ts ``` **Tests:** `cd backend && ./run_tests.sh` (runs against a temp copy of the real @@ -118,7 +122,10 @@ serialization path.** It enforces: - `test_save_fidelity.py` — a no-op save is byte-identical (A); a playlist edit changes only that playlist's block (B); a **track-metadata edit changes only that ``** (C); a **hotcue create is localized + round-trips** with - START stored in ms (D); a **beatgrid/BPM edit is localized + round-trips** (E). + START stored in ms (D); a **grid-marker edit is localized + round-trips** (E); + **flexible (multi-marker) grids** add/move/delete reversibly, `delete_grid` + leaves no companion debris (I); **companion cues are protected** from hotcue + commands (J); and real flexible grids in the collection project correctly (K). The guard that catches serialization regressions like the lxml reformatting bug. - `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays Traktor-valid, backup-first, COLLECTION byte-identical, original untouched. @@ -149,6 +156,23 @@ frontend at `http://localhost:5173`. (`PRIMARYKEY.KEY`) join to collection tracks. `Track.id` uses this. - **Rating** = `RANKING / 51`, giving 0–5 stars (`_rating_stars`). - **Key** is Traktor's display key string, e.g. `"10m"` (Open Key notation). +- **Beatgrid = an ORDERED LIST of markers**, never a single BPM + anchor. + Traktor stores each as a `CUE_V2 TYPE="4"` with its own `` child + (flexible beatgrids, 3.4+); `` mirrors the **first marker by + START**. A constant-tempo track is simply a list of length one, so this is the + model for every track. Two rules verified against the real 8485-entry + collection — get these wrong and you corrupt grids: + - **Marker NAME is not a discriminator** (`AutoGrid` ×7888, `n.n.` ×64, + `Beat Marker` ×14, `Unnamed` ×4). Identify by the `` child, order by + `START` — never by name or document order. + - **Companion cues are conventional, not structural.** Traktor usually pairs a + marker with a white (`COLOR="#FFFFFF"`) `TYPE="0"` cue at the same position, + which occupies a **real hotcue slot** — but 60 of 7970 markers have none. + Konduktor follows them, keeps them in sync, and **never invents one** (except + `place_grid_companion`, used only by Auto Grid). The `#FFFFFF` test is + load-bearing: 49 uncoloured cues and 18 *loops* also sit within 1 ms of a + marker and must not be dragged or deleted. `backend/konduktor/beatgrid.py` + is the single shared definition of all of this. - **Playlist tree**: recurse `nml.playlists.node.subnodes.node`. A node's `.type` is `FOLDER`, `PLAYLIST`, or `SMARTLIST`. Smart playlists are rule-based and have no static entry list. `PlaylistNode.id` is the playlist's stable `UUID`; @@ -204,6 +228,9 @@ that number and nothing else — everything derives from it: beatgrid display + editing, cue/hotcue create/jump/delete, loops; keyboard shortcuts (Space = play/pause, 1–8 = hotcues, Shift+1–8 = delete). See "Prep engine". - ✅ Track prep Tier 2 — cue-point fine editing / audio export polish +- ✅ Flexible beatgrids — the grid is a marker list end to end (marker-level + commands, piecewise beat math, playhead-derived marker editing). Step 1 of the + multi-platform plan in `.claude/discussions/`. - ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging ## Write path (playlists + track metadata + prep) @@ -232,10 +259,15 @@ diff — no COLLECTION splicing needed. `set_hotcue(track_id, slot, start_sec, type, length_sec)` creates/replaces a `CUE_V2` (types 0 cue, 1 fade-in, 2 fade-out, 3 load, 5 loop; START/LEN stored in **ms**; a loop hotcue carries LEN); `set_hotcue_type` changes just the type; - `delete_hotcue` removes a slot. `set_grid(track_id, bpm?, anchor_sec?)` edits - the TEMPO + the grid marker (`CUE_V2` type 4 with a `` child); - `delete_grid` drops it; `set_lock(track_id, locked)` toggles the `LOCK` attr. - Invariants D/E prove hotcue + grid edits are localized and round-trip. + `delete_hotcue` removes a slot. Hotcue commands **refuse a slot held by a grid + marker's companion cue** (see "Beatgrid"). Beatgrid commands are marker-level: + `add_grid_marker` (inherits the governing tempo when no BPM is given), + `move_grid_marker` (clamped between its neighbours, drags the companion), + `set_grid_marker_bpm` (also serves ×2 / ÷2, which retempo the governing marker + like every other tempo control), `delete_grid_marker`, `replace_grid` (Auto + Grid and the deck's Reset), `delete_grid` (markers **and** companions; keeps + `TEMPO`), `place_grid_companion`. `set_lock(track_id, locked)` toggles `LOCK`. + Invariants D/E/I/J prove hotcue + grid edits are localized and round-trip. - **Embedded file tags + cover art**: on save, for each edited track, `_sync_file_tags()` writes the changed fields (and staged cover art) into the audio file via `file_tags` (mutagen; ID3/MP4/FLAC/AIFF, WAV skipped) — @@ -252,7 +284,9 @@ diff — no COLLECTION splicing needed. `POST .../add` (append); `PATCH /api/tracks` (metadata); `GET/PUT /api/tracks/art` (cover art); `GET /api/tracks/audio` (Range-aware stream for playback/analysis); `GET /api/tracks/cues`, `POST/PATCH/DELETE /api/tracks/hotcue`, - `PATCH/DELETE /api/tracks/grid`, `PATCH /api/tracks/lock` (prep); `POST /api/save`. + `POST/PATCH/DELETE /api/tracks/grid/marker`, + `PUT /api/tracks/grid` (replace), `DELETE /api/tracks/grid`, + `PATCH /api/tracks/lock` (prep); `POST /api/save`. - Tests: `backend/run_tests.sh` → `test_save_fidelity.py` + `test_phase3.py` (both run against a temp copy). Run before touching the save/serialization path. @@ -278,8 +312,14 @@ The prep strip plays every track through the **Web Audio API** (a plain by blending three palette targets (bass→orange, mids→violet, highs→cyan — no green, matching Traktor's Spectrum). Height = amplitude. - `cues.ts` — canvas drawers for cue markers (type-colored), the active loop - band, the beatgrid (white beats/brighter downbeats), and the floating CUE - point (gold). The main waveform's playhead is red; both waveforms share these. + band, the beatgrid (per-segment white beats/brighter downbeats, plus marker + lines — gold for the one governing the playhead, accent otherwise, with the + active segment tinted), and the floating CUE point (gold). The main waveform's + playhead is red; both waveforms share these. +- `beatgrid.ts` — the `BeatGrid` model (`buildBeatGrid` → `BeatGrid | null`). + Unit-tested (`npm run test`, vitest); `beatgrid.test.ts` pins the property that + a **single-marker grid is algebraically identical to the old single-BPM math**, + which is what protects the 99.98% of tracks with a constant tempo. - Prep edits go straight to the prep endpoints above; after each edit the endpoint refreshes the read model (`service.replace_track()`) so cue/grid counts update live, and the frontend invalidates the relevant queries. diff --git a/backend/konduktor/auto_hotcues.py b/backend/konduktor/auto_hotcues.py index 55b5e45..46e0f5d 100644 --- a/backend/konduktor/auto_hotcues.py +++ b/backend/konduktor/auto_hotcues.py @@ -114,11 +114,41 @@ def detect_grid(audio_path: str, sr: int = _SR) -> tuple[float, float]: return bpm, first_beat +def _segment_for(t: float, markers: list[tuple[float, float]]) -> tuple[float, float]: + """The ``(start, bpm)`` of the beatgrid segment containing ``t``. + + Times before the first marker use the first segment, extrapolated backwards + — the same convention the deck draws with. + """ + seg = markers[0] + for m in markers: + if m[0] <= t: + seg = m + else: + break + return seg + + +def snap_to_phrase( + t: float, markers: list[tuple[float, float]], phrase_bars: int = 16 +) -> float: + """Snap ``t`` to the nearest phrase boundary OF ITS OWN SEGMENT. + + Snapping is deliberately segment-local rather than a running phrase count + across the whole track: a flexible grid exists precisely because the tempo + drifted, so carrying a phrase count across a marker seam would propagate the + very error the marker was placed to correct. With a single marker this is + exactly the old ``anchor + round((t - anchor) / phrase) * phrase``. + """ + anchor, bpm = _segment_for(t, markers) + phrase = phrase_bars * 4 * (60.0 / bpm) + return anchor + round((t - anchor) / phrase) * phrase + + def select_hotcues( boundaries: list[tuple[float, float]], *, - bpm: float, - anchor: float, + markers: list[tuple[float, float]], duration: float, free_slots: list[int], existing_times: list[float], @@ -127,21 +157,26 @@ def select_hotcues( ) -> 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. + ``markers`` is the beatgrid as ``[(start_sec, bpm), ...]`` ordered by start — + a constant-tempo track is simply a one-element list. + + Snaps each boundary to the nearest ``phrase_bars``-bar grid point of its own + tempo segment (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: + if not boundaries or not free_slots or not markers or markers[0][1] <= 0: return [] - beat = 60.0 / bpm - phrase = phrase_bars * 4 * beat # seconds per phrase + # Tolerance for "same place as an existing cue" and the end clamp. Marker + # BPMs differ by well under 1% in practice, so the first is representative. + beat = 60.0 / markers[0][1] # 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 = snap_to_phrase(t, markers, phrase_bars) p = max(0.0, min(p, duration - beat)) snapped[p] = max(snapped.get(p, 0.0), energy) diff --git a/backend/konduktor/beatgrid.py b/backend/konduktor/beatgrid.py new file mode 100644 index 0000000..070a2df --- /dev/null +++ b/backend/konduktor/beatgrid.py @@ -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 `` 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. + +`` 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 `` 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 `` + 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 `` 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 `` and falls back to `` 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()) diff --git a/backend/konduktor/collection_service.py b/backend/konduktor/collection_service.py index fbd545a..1491a89 100644 --- a/backend/konduktor/collection_service.py +++ b/backend/konduktor/collection_service.py @@ -11,6 +11,8 @@ from pathlib import Path from traktor_nml_utils import TraktorCollection +from . import beatgrid + from .schemas import ( Facets, GenreCount, @@ -80,7 +82,7 @@ class CollectionService: 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) + markers = beatgrid.grid_markers(e) return Track( id=_primary_key(loc) if loc else (e.title or ""), artist=e.artist, @@ -92,7 +94,7 @@ class CollectionService: 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, + bpm=beatgrid.effective_bpm(e), key=info.key if info else None, rating=_rating_stars(info.ranking if info else None), playcount=info.playcount if info else None, @@ -104,7 +106,8 @@ class CollectionService: filepath=_display_path(loc) if loc else None, cue_count=len(cues), hotcue_count=hotcues, - has_grid=has_grid, + has_grid=bool(markers), + grid_markers=len(markers), is_stem=getattr(e, "stems", None) is not None, ) diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index fbd3063..2e928b6 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -13,7 +13,7 @@ from fastapi import FastAPI, File, Form, HTTPException, Query, Response, UploadF from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse -from . import __version__ +from . import __version__, beatgrid from . import auto_hotcues as ah from . import history, prefs from .collection_service import CollectionService @@ -35,7 +35,10 @@ from .schemas import ( FileTagOutcome, FsEntry, FsListing, - GridEdit, + AddGridMarker, + GridMarker, + GridMarkerEdit, + ReplaceGrid, HistoryEntry, OpenCollection, PathMappingInfo, @@ -452,30 +455,40 @@ def track_audio(track_id: str) -> FileResponse: def _build_track_cues(entry) -> TrackCues: - grid_anchor: float | None = None - grid_bpm: float | None = None - cues: list[CuePoint] = [] - for c in entry.cue_v2 or []: - grid = getattr(c, "grid", None) - start_sec = (c.start or 0.0) / 1000.0 # Traktor stores cue START in ms - if grid is not None: - if grid_anchor is None: - grid_anchor = start_sec - grid_bpm = grid.bpm - continue # grid markers are represented by the beatgrid, not as cues - cues.append( - CuePoint( - name=c.name, - type=c.type if c.type is not None else 0, - start=start_sec, - length=(c.len or 0.0) / 1000.0, - hotcue=c.hotcue if c.hotcue is not None else -1, - color=c.color, - ) + """Project an ENTRY's beatgrid + cues. + + 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, and each is tagged with the marker it + belongs to so the UI can show it as beatgrid-owned rather than editable. + """ + markers = beatgrid.grid_markers(entry) + comps = beatgrid.companions(entry) + marker_of = {id(c): i for i, c in comps.items()} + grid_markers = [ + GridMarker( + start=(m.start or 0.0) / 1000.0, # Traktor stores START in 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, ) - bpm = grid_bpm if grid_bpm is not None else (entry.tempo.bpm if entry.tempo else None) + for i, m in enumerate(markers) + ] + cues = [ + CuePoint( + name=c.name, + type=c.type if c.type is not None else 0, + start=(c.start or 0.0) / 1000.0, + length=(c.len or 0.0) / 1000.0, + hotcue=c.hotcue if c.hotcue is not None else -1, + color=c.color, + grid_marker=marker_of.get(id(c)), + ) + for c in (entry.cue_v2 or []) + if getattr(c, "grid", None) is None + ] return TrackCues( - bpm=bpm, grid_anchor=grid_anchor, locked=bool(entry.lock), cues=cues + grid_markers=grid_markers, locked=bool(entry.lock), cues=cues ) @@ -525,7 +538,7 @@ def auto_hotcues(body: AutoHotcuesRequest) -> TrackCues: if entry is None: raise HTTPException(404, "Track not found") cues = _build_track_cues(entry) - if not cues.bpm or cues.bpm <= 0 or cues.grid_anchor is None: + if not cues.grid_markers: raise HTTPException(400, "Set a beatgrid before using Auto Hotcues") path = store.audio_path(body.track_id) if path is None or not path.exists(): @@ -541,8 +554,7 @@ def auto_hotcues(body: AutoHotcuesRequest) -> TrackCues: existing_times = [c.start for c in cues.cues if c.hotcue is not None and c.hotcue >= 0] specs = ah.select_hotcues( boundaries, - bpm=cues.bpm, - anchor=cues.grid_anchor, + markers=[(m.start, m.bpm) for m in cues.grid_markers], duration=duration, free_slots=free, existing_times=existing_times, @@ -573,8 +585,10 @@ def auto_grid(body: AutoGridRequest) -> TrackCues: except Exception as ex: # analysis is best-effort; never 500 the UI raise HTTPException(400, f"Analysis failed: {ex}") try: - store.set_grid(body.track_id, bpm=bpm, anchor_sec=first_beat) - store.set_hotcue(body.track_id, 0, first_beat, 0) # hotcue 1 = slot 0 + store.replace_grid(body.track_id, [(first_beat, bpm)]) + # Traktor pairs its own grid markers with a white beat-1 cue; mirror + # that, but never over an existing hotcue (the old code clobbered slot 0). + store.place_grid_companion(body.track_id, 0, prefer_slot=0) except PlaylistError as ex: raise HTTPException(400, str(ex)) return _sync_cue_edit(body.track_id) @@ -600,11 +614,51 @@ def delete_hotcue(track_id: str, slot: int) -> TrackCues: return _sync_cue_edit(track_id) -@app.patch("/api/tracks/grid", response_model=TrackCues) -def edit_grid(body: GridEdit) -> TrackCues: - """Set the beatgrid BPM and/or move the grid marker (beat 1).""" +@app.post("/api/tracks/grid/marker", response_model=TrackCues) +def add_grid_marker(body: AddGridMarker) -> TrackCues: + """Add a beatgrid marker. Omitting `bpm` inherits the governing tempo.""" try: - require_store().set_grid(body.track_id, body.bpm, body.anchor) + require_store().add_grid_marker(body.track_id, body.start, body.bpm) + except PlaylistError as ex: + raise HTTPException(400, str(ex)) + return _sync_cue_edit(body.track_id) + + +@app.patch("/api/tracks/grid/marker", response_model=TrackCues) +def edit_grid_marker(body: GridMarkerEdit) -> TrackCues: + """Retempo and/or move one grid marker. + + BPM is applied before the move: a tempo change can never reorder markers, so + `index` is still valid for the move afterwards. + """ + store = require_store() + try: + if body.bpm is not None: + store.set_grid_marker_bpm(body.track_id, body.index, body.bpm) + if body.start is not None: + store.move_grid_marker(body.track_id, body.index, body.start) + except PlaylistError as ex: + raise HTTPException(400, str(ex)) + return _sync_cue_edit(body.track_id) + + +@app.delete("/api/tracks/grid/marker", response_model=TrackCues) +def remove_grid_marker(track_id: str, index: int) -> TrackCues: + """Delete one grid marker (and its companion cue).""" + try: + require_store().delete_grid_marker(track_id, index) + except PlaylistError as ex: + raise HTTPException(400, str(ex)) + return _sync_cue_edit(track_id) + + +@app.put("/api/tracks/grid", response_model=TrackCues) +def replace_grid(body: ReplaceGrid) -> TrackCues: + """Replace the whole beatgrid (the deck's Reset). `markers: []` clears it.""" + try: + require_store().replace_grid( + body.track_id, [(m.start, m.bpm) for m in body.markers] + ) except PlaylistError as ex: raise HTTPException(400, str(ex)) return _sync_cue_edit(body.track_id) @@ -612,7 +666,7 @@ def edit_grid(body: GridEdit) -> TrackCues: @app.delete("/api/tracks/grid", response_model=TrackCues) def remove_grid(track_id: str) -> TrackCues: - """Delete the track's grid marker(s).""" + """Delete every grid marker and its companion cue. is kept.""" try: require_store().delete_grid(track_id) except PlaylistError as ex: diff --git a/backend/konduktor/playlist_store.py b/backend/konduktor/playlist_store.py index 761607b..4cc755f 100644 --- a/backend/konduktor/playlist_store.py +++ b/backend/konduktor/playlist_store.py @@ -42,7 +42,7 @@ from traktor_nml_utils.models.collection import ( ) from xsdata.formats.dataclass.serializers import XmlSerializer -from . import __version__, history +from . import __version__, beatgrid, history from .path_mapping import PathMapping from .schemas import PlaylistNode @@ -295,6 +295,21 @@ class PlaylistStore: raise PlaylistError(f"Track not found: {track_id}") return entry + @staticmethod + def _reject_if_companion(entry: Entrytype, slot: int) -> None: + """Refuse to touch a slot held by a grid marker's companion cue. + + Traktor pairs most grid markers with a white cue in a real hotcue slot. + Overwriting, retyping or deleting one desyncs it from its marker, so the + beatgrid commands own these slots — move or delete the marker instead. + """ + cue = next((c for c in (entry.cue_v2 or []) if c.hotcue == slot), None) + if cue is not None and beatgrid.is_companion(entry, cue): + raise PlaylistError( + f"Hotcue {slot + 1} belongs to a beatgrid marker — " + "move or delete the marker instead" + ) + def set_hotcue( self, track_id: str, @@ -314,6 +329,7 @@ class PlaylistStore: raise PlaylistError(f"Unsupported cue type: {cue_type}") with self._lock: entry = self._entry_or_raise(track_id) + self._reject_if_companion(entry, slot) start_ms = max(0.0, start_sec * 1000.0) # Traktor stores START/LEN in ms len_ms = max(0.0, length_sec * 1000.0) existing = next( @@ -356,8 +372,13 @@ class PlaylistStore: occupied = { c.hotcue for c in (entry.cue_v2 or []) if c.hotcue is not None and c.hotcue >= 0 } + # Companion slots belong to the beatgrid — never fill them, even + # with overwrite=True (occupied alone only guards them while False). + protected = { + c.hotcue for c in beatgrid.companions(entry).values() if c.hotcue is not None + } for spec in specs: - if not overwrite and spec.slot in occupied: + if spec.slot in protected or (not overwrite and spec.slot in occupied): continue self.set_hotcue( track_id, @@ -374,6 +395,7 @@ class PlaylistStore: raise PlaylistError(f"Unsupported cue type: {cue_type}") with self._lock: entry = self._entry_or_raise(track_id) + self._reject_if_companion(entry, slot) cue = next((c for c in (entry.cue_v2 or []) if c.hotcue == slot), None) if cue is None: raise PlaylistError(f"Hotcue {slot} is not set") @@ -384,6 +406,7 @@ class PlaylistStore: def delete_hotcue(self, track_id: str, slot: int) -> None: with self._lock: entry = self._entry_or_raise(track_id) + self._reject_if_companion(entry, slot) before = entry.cue_v2 or [] entry.cue_v2 = [c for c in before if c.hotcue != slot] if len(entry.cue_v2) != len(before): # only count an actual removal @@ -391,61 +414,279 @@ class PlaylistStore: self.dirty = True # ---- beatgrid ----------------------------------------------------- + # A beatgrid is an ORDERED LIST of markers (see beatgrid.py); a constant + # grid is a list of length one. Markers are addressed by their index in that + # start-ordered list. CUE_V2 has no id attribute and save() reparses the + # whole file, so any synthetic id would have to be rebuilt by position + # anyway — the index IS the identity. + _MARKER_MIN_GAP_MS = 1.0 + @staticmethod def _grid_marker(entry: Entrytype) -> CueV2Type | None: - return next( - (c for c in (entry.cue_v2 or []) if getattr(c, "grid", None) is not None), None - ) + """The first grid marker BY START — the one mirrors.""" + return beatgrid.first_marker(entry) - def set_grid( - self, track_id: str, bpm: float | None = None, anchor_sec: float | None = None - ) -> None: - """Set the beatgrid tempo (TEMPO + grid marker BPM) and/or move the grid - marker (beat 1). Creates a grid marker if the track has none.""" + @staticmethod + def _sync_tempo(entry: Entrytype) -> None: + """Mirror from the first marker (7968/7968 in the reference + collection). Called last by every grid mutator, so a move that changes + which marker is first re-mirrors for free. + + With no markers left, TEMPO is LEFT ALONE: Traktor keeps the analysed + BPM on gridless tracks (53 such entries exist in the reference file). + """ + marker = beatgrid.first_marker(entry) + if marker is None or marker.grid is None or not marker.grid.bpm: + return + if entry.tempo is None: + entry.tempo = Tempotype(bpm=marker.grid.bpm, bpm_quality=100.0) + else: + entry.tempo.bpm = marker.grid.bpm + + @staticmethod + def _sort_cues(entry: Entrytype) -> None: + """Keep CUE_V2 ascending by START — true for 8485/8485 reference + entries, so an inserted marker must not become the one exception. + Stable, so a marker stays ahead of a companion at an identical START. + """ + if entry.cue_v2: + entry.cue_v2.sort(key=lambda c: c.start or 0.0) + + def _markers_or_raise( + self, entry: Entrytype, index: int + ) -> tuple[list[CueV2Type], CueV2Type]: + markers = beatgrid.grid_markers(entry) + if not markers: + raise PlaylistError("Track has no beatgrid") + if not 0 <= index < len(markers): + raise PlaylistError( + f"Grid marker {index} out of range (track has {len(markers)})" + ) + return markers, markers[index] + + def _drop_grid(self, entry: Entrytype) -> None: + """Remove every marker AND every companion. No _note — callers do that.""" + doomed = {id(m) for m in beatgrid.grid_markers(entry)} + doomed |= {id(c) for c in beatgrid.companions(entry).values()} + entry.cue_v2 = [c for c in (entry.cue_v2 or []) if id(c) not in doomed] + + def add_grid_marker( + self, + track_id: str, + start_sec: float, + bpm: float | None = None, + name: str | None = None, + ) -> int: + """Add a beatgrid marker at `start_sec`; returns its index. + + With `bpm` unset the marker INHERITS the tempo of the section it lands + in, so splitting a section is musically a no-op until it's retempoed. + Creates no companion cue — Traktor tolerates markers without one, and + inventing them would silently consume the user's hotcue slots. + """ + if bpm is not None and bpm <= 0: + raise PlaylistError(f"BPM must be positive: {bpm}") with self._lock: entry = self._entry_or_raise(track_id) - marker = self._grid_marker(entry) - if bpm is not None: - if bpm <= 0: - raise PlaylistError(f"BPM must be positive: {bpm}") - if entry.tempo is None: - entry.tempo = Tempotype(bpm=bpm, bpm_quality=100.0) - else: - entry.tempo.bpm = bpm - if marker is not None and marker.grid is not None: - marker.grid.bpm = bpm - if anchor_sec is not None: - start_ms = max(0.0, anchor_sec * 1000.0) - if marker is not None: - marker.start = start_ms - else: - grid_bpm = bpm if bpm is not None else (entry.tempo.bpm if entry.tempo else None) - if grid_bpm is None: - raise PlaylistError("No BPM available to create a beatgrid") - if entry.cue_v2 is None: - entry.cue_v2 = [] - entry.cue_v2.append( - CueV2Type( - name="AutoGrid", - displ_order=0, - type=4, - start=start_ms, - len=0.0, - repeats=-1, - hotcue=-1, - color=None, - grid=GridType(bpm=grid_bpm), - ) - ) - self._note("grid", "edit", track_id) + start_ms = max(0.0, start_sec * 1000.0) + markers = beatgrid.grid_markers(entry) + for m in markers: + if abs((m.start or 0.0) - start_ms) < self._MARKER_MIN_GAP_MS: + raise PlaylistError("A grid marker already exists at that position") + if bpm is None: + bpm = self._bpm_governing(entry, start_ms) + if bpm is None: + raise PlaylistError("No BPM available to create a beatgrid") + if entry.cue_v2 is None: + entry.cue_v2 = [] + entry.cue_v2.append( + CueV2Type( + name=name or ("AutoGrid" if not markers else "n.n."), + displ_order=0, + type=4, + start=start_ms, + len=0.0, + repeats=-1, + hotcue=-1, + color=None, + grid=GridType(bpm=bpm), + ) + ) + self._sort_cues(entry) + self._sync_tempo(entry) + self._note("grid", "marker-add", track_id) + self.dirty = True + return next( + i + for i, m in enumerate(beatgrid.grid_markers(entry)) + if abs((m.start or 0.0) - start_ms) < 1e-9 + ) + + @staticmethod + def _bpm_governing(entry: Entrytype, start_ms: float) -> float | None: + """The tempo in force at `start_ms`: the last marker at or before it, + else the first marker (extrapolated backwards), else .""" + markers = beatgrid.grid_markers(entry) + if not markers: + return entry.tempo.bpm if entry.tempo else None + governing = markers[0] + for m in markers: + if (m.start or 0.0) <= start_ms: + governing = m + else: + break + return governing.grid.bpm if governing.grid else None + + def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> None: + """Move marker `index`, DRAGGING ITS COMPANION with it. + + The new position is CLAMPED between the neighbouring markers rather than + allowed to reorder them, so an index can never go stale mid-edit. Phase + nudges are +/-1 and +/-10 ms, so this is no practical constraint; + restructuring a grid is add-then-delete. + """ + with self._lock: + entry = self._entry_or_raise(track_id) + markers, marker = self._markers_or_raise(entry, index) + start_ms = max(0.0, start_sec * 1000.0) + if index > 0: + lo = (markers[index - 1].start or 0.0) + self._MARKER_MIN_GAP_MS + start_ms = max(start_ms, lo) + if index < len(markers) - 1: + hi = (markers[index + 1].start or 0.0) - self._MARKER_MIN_GAP_MS + start_ms = min(start_ms, hi) + companion = beatgrid.companions(entry).get(index) + marker.start = start_ms + if companion is not None: + # Copy the float — never recompute from seconds. A 1-ULP drift + # here would change the rendered bytes and break byte-reverts. + companion.start = marker.start + self._sync_tempo(entry) + self._note("grid", "marker-move", track_id) self.dirty = True - def delete_grid(self, track_id: str) -> None: + def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> None: + """Set marker `index`'s tempo (governs until the next marker).""" + if bpm <= 0: + raise PlaylistError(f"BPM must be positive: {bpm}") with self._lock: entry = self._entry_or_raise(track_id) - entry.cue_v2 = [ - c for c in (entry.cue_v2 or []) if getattr(c, "grid", None) is None - ] + _, marker = self._markers_or_raise(entry, index) + if marker.grid is None: + marker.grid = GridType(bpm=bpm) + else: + marker.grid.bpm = bpm + self._sync_tempo(entry) + self._note("grid", "marker-bpm", track_id) + self.dirty = True + + def delete_grid_marker(self, track_id: str, index: int) -> None: + """Remove marker `index` and its companion (freeing that hotcue slot).""" + with self._lock: + entry = self._entry_or_raise(track_id) + markers, marker = self._markers_or_raise(entry, index) + companion = beatgrid.companions(entry).get(index) + doomed = {id(marker)} | ({id(companion)} if companion is not None else set()) + entry.cue_v2 = [c for c in (entry.cue_v2 or []) if id(c) not in doomed] + self._sync_tempo(entry) + # Removing the last marker IS deleting the grid — report it as one. + self._note( + "grid", "delete" if len(markers) == 1 else "marker-delete", track_id + ) + self.dirty = True + + def replace_grid( + self, track_id: str, markers: list[tuple[float, float]] + ) -> None: + """Throw the grid away and rebuild it from `markers` [(start_sec, bpm)]. + + Serves both Auto Grid (a single marker) and the deck's Reset (restore + the list as loaded) as one atomic, single-event command. Companions of + the old grid go with it; none are created. + """ + for start_sec, bpm in markers: + if bpm <= 0: + raise PlaylistError(f"BPM must be positive: {bpm}") + with self._lock: + entry = self._entry_or_raise(track_id) + self._drop_grid(entry) + if entry.cue_v2 is None: + entry.cue_v2 = [] + for i, (start_sec, bpm) in enumerate( + sorted(markers, key=lambda m: m[0]) + ): + entry.cue_v2.append( + CueV2Type( + name="AutoGrid" if i == 0 else "n.n.", + displ_order=0, + type=4, + start=max(0.0, start_sec * 1000.0), + len=0.0, + repeats=-1, + hotcue=-1, + color=None, + grid=GridType(bpm=bpm), + ) + ) + self._sort_cues(entry) + self._sync_tempo(entry) + self._note("grid", "replace", track_id) + self.dirty = True + + def place_grid_companion( + self, track_id: str, index: int, *, prefer_slot: int = 0 + ) -> int | None: + """Give marker `index` the white beat-1 hotcue Traktor writes beside its + own markers: `prefer_slot` when free, else the lowest free slot. + + Returns the slot used, or None when the bank is full or the marker + already has a companion. NEVER overwrites. This is the ONLY place + Konduktor creates a companion — grid edits never do — because it is a + deliberate, user-invoked feature (Auto Grid), not a side effect. + """ + with self._lock: + entry = self._entry_or_raise(track_id) + _, marker = self._markers_or_raise(entry, index) + if index in beatgrid.companions(entry): + return None + used = { + c.hotcue + for c in (entry.cue_v2 or []) + if c.hotcue is not None and c.hotcue >= 0 + } + slot = next( + (s for s in [prefer_slot, *range(8)] if 0 <= s <= 7 and s not in used), + None, + ) + if slot is None: + return None + entry.cue_v2.append( + CueV2Type( + name=marker.name or "AutoGrid", + displ_order=0, + type=0, + start=marker.start, # copy the float, not start_sec * 1000 + len=0.0, + repeats=-1, + hotcue=slot, + color=beatgrid.COMPANION_COLOR, + grid=None, + ) + ) + self._sort_cues(entry) + self._note("grid", "marker-add", track_id) + self.dirty = True + return slot + + def delete_grid(self, track_id: str) -> None: + """Remove EVERY grid marker AND EVERY companion; is kept. + + Dropping companions is the debris fix: the old code stripped markers + only, leaving orphan white cues squatting in hotcue slots. + """ + with self._lock: + entry = self._entry_or_raise(track_id) + self._drop_grid(entry) self._note("grid", "delete", track_id) self.dirty = True @@ -698,7 +939,10 @@ class PlaylistStore: elif detail == "delete": hc_del += 1 elif cat == "grid": - (grid_edit if detail == "edit" else grid_del).add(tid or "") + # "delete" is the ONLY deletion detail. Everything else — including + # details 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 detail == "delete" else grid_edit).add(tid or "") elif cat == "lock": (lock_on if detail == "on" else lock_off).add(tid or "") diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index 067115f..19c7158 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -30,6 +30,7 @@ class Track(BaseModel): cue_count: int = 0 hotcue_count: int = 0 has_grid: bool = False + grid_markers: int = 0 # >1 = a flexible (multi-tempo) beatgrid is_stem: bool = False # a Stem file ( child) vs a normal audio track @@ -132,19 +133,45 @@ class CuePoint(BaseModel): length: float # seconds (>0 for loops) hotcue: int # -1 if not assigned to a hotcue slot color: str | None = None # "#RRGGBB" if set + # Index of the grid marker this cue is the companion of, if any. Such a cue + # holds a real hotcue slot but belongs to the beatgrid and is not editable. + 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): - bpm: float | None = None # beatgrid BPM (from the grid marker; falls back to tempo) - grid_anchor: float | None = None # seconds — first grid marker (beat 1 of the grid) + # 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] = [] locked: bool = False # Traktor LOCK flag - cues: list[CuePoint] = [] # cue/loop markers (grid markers excluded) + cues: list[CuePoint] = [] # cue/loop markers (grid markers themselves excluded) -class GridEdit(BaseModel): +class AddGridMarker(BaseModel): track_id: str - bpm: float | None = None # set the beatgrid tempo - anchor: float | None = None # set the grid marker (beat 1) position, in seconds + start: float # seconds + bpm: float | None = None # unset = inherit the tempo governing that position + + +class GridMarkerEdit(BaseModel): + track_id: str + index: int # into the start-ordered marker list + start: float | None = None # move it (clamped between its neighbours) + bpm: float | None = None # retempo the section it opens + + +class ReplaceGrid(BaseModel): + track_id: str + markers: list[GridMarker] = [] # [] is equivalent to deleting the grid class SetLock(BaseModel): diff --git a/backend/test_save_fidelity.py b/backend/test_save_fidelity.py index 4e88c3f..c5863a5 100644 --- a/backend/test_save_fidelity.py +++ b/backend/test_save_fidelity.py @@ -31,7 +31,7 @@ os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-fidelity-a REAL = Path(__file__).resolve().parents[1] / "collection.nml" from konduktor.collection_service import CollectionService # noqa: E402 -from konduktor.playlist_store import PlaylistStore # noqa: E402 +from konduktor.playlist_store import PlaylistError, PlaylistStore # noqa: E402 failed = False @@ -232,24 +232,42 @@ with tempfile.TemporaryDirectory() as d: check("create+delete round-trips to the original bytes", work.read_bytes() == original) # ---- Invariant E: a beatgrid edit is fully localized ------------------- -print("== E. grid/bpm edit touches only that track's ENTRY ==") +print("== E. grid marker edit touches only that track's ENTRY ==") +from konduktor import beatgrid as bg # noqa: E402 + with tempfile.TemporaryDirectory() as d: work = Path(d) / "collection.nml" shutil.copy2(REAL, work) original = work.read_bytes() store = PlaylistStore(work) - # first entry that has both a tempo and a grid marker - entry = next( - e - for e in store._nml.collection.entry - if e.tempo and store._grid_marker(e) is not None - ) - loc = entry.location - track_id = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}" - orig_bpm = entry.tempo.bpm - store.set_grid(track_id, bpm=orig_bpm / 2, anchor_sec=1.5) + def _key(e): + loc = e.location + return f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}" if loc else "" + + # An entry with a tempo and exactly ONE marker whose companion (if any) sits + # at an EXACTLY equal START. That predicate is load-bearing: a companion a + # fraction of a ms off would be normalised to exact by the first move, so the + # byte-revert below would fail through no fault of the code. + def _clean_single(e): + ms = bg.grid_markers(e) + if not (e.tempo and len(ms) == 1): + return False + comp = bg.companions(e).get(0) + return comp is None or comp.start == ms[0].start + + entry = next(e for e in store._nml.collection.entry if _clean_single(e)) + loc = entry.location + track_id = _key(entry) + orig_bpm = entry.tempo.bpm + orig_anchor_ms = bg.grid_markers(entry)[0].start + comp_slot = ( + bg.companions(entry)[0].hotcue if 0 in bg.companions(entry) else None + ) + + store.set_grid_marker_bpm(track_id, 0, orig_bpm / 2) + store.move_grid_marker(track_id, 0, 1.5) store.save() edited = work.read_bytes() @@ -272,30 +290,28 @@ with tempfile.TemporaryDirectory() as d: from traktor_nml_utils import TraktorCollection reparsed = TraktorCollection(path=work) - e0 = next( - e - for e in reparsed.nml.collection.entry - if e.location - and f"{e.location.volume or ''}{e.location.dir or ''}{e.location.file or ''}" == track_id - ) + e0 = next(e for e in reparsed.nml.collection.entry if e.location and _key(e) == track_id) + markers = bg.grid_markers(e0) m = store._grid_marker(e0) check("tempo BPM halved + persisted", abs(e0.tempo.bpm - orig_bpm / 2) < 1e-3) check("grid marker BPM matches tempo", m is not None and abs(m.grid.bpm - orig_bpm / 2) < 1e-3) check("grid anchor moved to 1.5s (1500 ms)", m is not None and abs(m.start - 1500.0) < 1) + # A move must reposition the grid, never fork it into a flexible one. + check("still exactly one grid marker", len(markers) == 1, str(len(markers))) + # _grid_marker is the first marker BY START, not by document order. + check("_grid_marker == first marker by start", m is markers[0]) + if comp_slot is not None: + comp = bg.companions(e0).get(0) + check("companion dragged along with its marker", + comp is not None and abs(comp.start - 1500.0) < 1, str(comp.start if comp else None)) + check("companion kept its hotcue slot", comp is not None and comp.hotcue == comp_slot) - # Reverting BPM + anchor to the original values round-trips to the file. - orig_anchor_ms = store._grid_marker( - next( - e - for e in TraktorCollection(path=REAL).nml.collection.entry - if e.location - and f"{e.location.volume or ''}{e.location.dir or ''}{e.location.file or ''}" == track_id - ) - ).start + # Reverting BPM + position round-trips to the original bytes. store2 = PlaylistStore(work) - store2.set_grid(track_id, bpm=orig_bpm, anchor_sec=orig_anchor_ms / 1000.0) + store2.set_grid_marker_bpm(track_id, 0, orig_bpm) + store2.move_grid_marker(track_id, 0, orig_anchor_ms / 1000.0) store2.save() - check("revert BPM + anchor round-trips to original bytes", work.read_bytes() == original) + check("revert BPM + position round-trips to original bytes", work.read_bytes() == original) # ---- Invariant F: batch place_hotcues (Auto Hotcues) ------------------- print("== F. place_hotcues fills empty slots only, names round-trip, localized ==") @@ -365,12 +381,13 @@ with tempfile.TemporaryDirectory() as d: print("== G. select_hotcues: phrase-snap, empty-slots, names, existing-cue avoidance ==") from konduktor import auto_hotcues as ah # noqa: E402 -# 128 BPM => beat 0.46875s, 16-bar phrase = 30.0s exactly; anchor 0.0. +# 128 BPM => beat 0.46875s, 16-bar phrase = 30.0s exactly; marker at 0.0. BPM, ANCHOR, DUR = 128.0, 0.0, 300.0 +GRID = [(ANCHOR, BPM)] # a constant grid is a one-marker list # Raw boundaries near (but not exactly on) phrase multiples + a fragmented pair. raw = [(0.3, 0.2), (29.4, 0.5), (30.6, 0.55), (61.0, 0.9), (150.0, 0.3), (270.2, 0.25)] specs = ah.select_hotcues( - raw, bpm=BPM, anchor=ANCHOR, duration=DUR, + raw, markers=GRID, duration=DUR, free_slots=[2, 3, 4, 5, 6, 7], existing_times=[], max_cues=8, ) starts = [s["start"] for s in specs] @@ -383,13 +400,27 @@ check("names are unique (ordinal de-dupe)", len({s["name"] for s in specs}) == l # A hotcue already sitting on the 60s phrase must not get a duplicate. specs2 = ah.select_hotcues( - raw, bpm=BPM, anchor=ANCHOR, duration=DUR, + raw, markers=GRID, duration=DUR, free_slots=[0, 1, 2, 3, 4, 5, 6, 7], existing_times=[60.0], max_cues=8, ) check("boundary colliding with an existing hotcue is dropped", 60.0 not in [s["start"] for s in specs2], str([s["start"] for s in specs2])) # No free slots => nothing placed. -check("no free slots => empty result", ah.select_hotcues(raw, bpm=BPM, anchor=ANCHOR, duration=DUR, free_slots=[], existing_times=[], max_cues=8) == []) +check("no free slots => empty result", ah.select_hotcues(raw, markers=GRID, duration=DUR, free_slots=[], existing_times=[], max_cues=8) == []) + +# Flexible grid: each segment snaps to ITS OWN phrase length. Segment 2 starts +# at 120s at 120 BPM => 16-bar phrase = 32.0s, so points there land on 120+k*32. +FLEX = [(0.0, 128.0), (120.0, 120.0)] +flex_specs = ah.select_hotcues( + [(29.4, 0.5), (61.0, 0.9), (152.5, 0.4), (215.0, 0.3)], + markers=FLEX, duration=DUR, free_slots=[0, 1, 2, 3, 4, 5, 6, 7], + existing_times=[], max_cues=8, +) +flex_starts = [s_["start"] for s_ in flex_specs] +check("flexible grid: pre-seam points snap to the 30s phrase", + all(abs(round(t / 30.0) * 30.0 - t) < 0.01 for t in flex_starts if t < 120.0), str(flex_starts)) +check("flexible grid: post-seam points snap to that segment's 32s phrase", + all(abs(120.0 + round((t - 120.0) / 32.0) * 32.0 - t) < 0.01 for t in flex_starts if t >= 120.0), str(flex_starts)) # ---- Invariant H: path write-back is localized + round-trips ----------- print("== H. remap_locations rewrites LOCATIONs (+ playlist keys), localized, round-trips ==") @@ -517,5 +548,166 @@ with tempfile.TemporaryDirectory() as d: check("H2: new playlist PRIMARYKEY present", new_key in all_pl_keys) +# ---- Invariant I: flexible (multi-marker) beatgrids round-trip --------- +print("== I. flexible beatgrid: add/move/delete markers, localized + reversible ==") +with tempfile.TemporaryDirectory() as d: + work = Path(d) / "collection.nml" + shutil.copy2(REAL, work) + original = work.read_bytes() + + def _key(e): + loc = e.location + return f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}" if loc else "" + + def entry_span(data: bytes, file_name: str): + marker = f'FILE="{file_name}"'.encode() + i = data.find(marker) + st = data.rfind(b"", i) + len(b"") + return st, en + + # Synthesize the flexible grid rather than relying on the handful of real + # ones: those are the user's own data and could change at any time. + store = PlaylistStore(work) + entry = next( + e for e in store._nml.collection.entry + if e.tempo and len(bg.grid_markers(e)) == 1 + and (bg.companions(e).get(0) is None or bg.companions(e)[0].start == bg.grid_markers(e)[0].start) + ) + loc = entry.location + track_id = _key(entry) + _m0 = bg.grid_markers(entry)[0] + m0_start, m0_bpm = _m0.start, _m0.grid.bpm + orig_tempo = entry.tempo.bpm + + store.add_grid_marker(track_id, (m0_start + 60_000.0) / 1000.0, bpm=m0_bpm * 0.99) + store.save() + two = work.read_bytes() + + reparsed = TraktorCollection(path=work) + e1 = next(e for e in reparsed.nml.collection.entry if e.location and _key(e) == track_id) + ms = bg.grid_markers(e1) + check("I: second marker added", len(ms) == 2, str(len(ms))) + check("I: markers ascending by START", ms[0].start < ms[1].start) + check("I: second marker kept its own BPM", abs(ms[1].grid.bpm - m0_bpm * 0.99) < 1e-3) + check("I: TEMPO still mirrors the FIRST marker", abs(e1.tempo.bpm - orig_tempo) < 1e-6, + f"{e1.tempo.bpm} vs {orig_tempo}") + check("I: CUE_V2 still ascending by START", + all((c.start or 0) <= (ms_ .start or 0) for c, ms_ in zip(e1.cue_v2, e1.cue_v2[1:]))) + check("I: new GRID BPM rendered at 6 decimals", + f''.encode() in two) + os_, oe = entry_span(original, loc.file) + es_, ee = entry_span(two, loc.file) + check("I: adding a marker is confined to that ENTRY", + original[:os_] + b"@@" + original[oe:] == two[:es_] + b"@@" + two[ee:]) + + # Removing it must return the file to its original bytes exactly. + store2 = PlaylistStore(work) + store2.delete_grid_marker(track_id, 1) + store2.save() + check("I: deleting the added marker round-trips to original bytes", + work.read_bytes() == original) + + # Moves clamp between neighbours rather than reordering the list. + store3 = PlaylistStore(work) + store3.add_grid_marker(track_id, (m0_start + 60_000.0) / 1000.0, bpm=m0_bpm * 0.99) + store3.move_grid_marker(track_id, 0, (m0_start + 120_000.0) / 1000.0) + e3 = store3.model_entry(track_id) + ms3 = bg.grid_markers(e3) + check("I: move clamps below the next marker", ms3[0].start < ms3[1].start) + check("I: move never changes the marker count", len(ms3) == 2) + + # delete_grid takes the companions with it and keeps TEMPO. + store3.delete_grid(track_id) + e3 = store3.model_entry(track_id) + whites = [c for c in (e3.cue_v2 or []) if c.color == "#FFFFFF" and getattr(c, "grid", None) is None] + check("I: delete_grid removes every marker", len(bg.grid_markers(e3)) == 0) + check("I: delete_grid leaves no companion debris", not whites, str(len(whites))) + check("I: delete_grid keeps TEMPO", e3.tempo is not None and e3.tempo.bpm == orig_tempo) + + +# ---- Invariant J: companion cues are protected from hotcue edits ------- +print("== J. grid companion cues cannot be clobbered by hotcue commands ==") +with tempfile.TemporaryDirectory() as d: + work = Path(d) / "collection.nml" + shutil.copy2(REAL, work) + original = work.read_bytes() + + store = PlaylistStore(work) + entry = next( + e for e in store._nml.collection.entry if bg.companions(e).get(0) is not None + ) + track_id = f"{entry.location.volume or ''}{entry.location.dir or ''}{entry.location.file or ''}" + slot = bg.companions(entry)[0].hotcue + + for label, fn in [ + ("set_hotcue", lambda: store.set_hotcue(track_id, slot, 5.0, 0)), + ("set_hotcue_type", lambda: store.set_hotcue_type(track_id, slot, 1)), + ("delete_hotcue", lambda: store.delete_hotcue(track_id, slot)), + ]: + try: + fn() + check(f"J: {label} refuses a companion slot", False, "no error raised") + except PlaylistError: + check(f"J: {label} refuses a companion slot", True) + + check("J: refusals leave the store clean", store.dirty is False) + store.save() + check("J: save after refusals is byte-identical", work.read_bytes() == original) + + # The guard must be narrow: a free slot in the same track still works. + used = {c.hotcue for c in (entry.cue_v2 or []) if c.hotcue is not None and c.hotcue >= 0} + free = next(s_ for s_ in range(8) if s_ not in used) + store.set_hotcue(track_id, free, 12.0, 0) + check("J: a non-companion slot is still editable", store.dirty is True) + + # Auto Hotcues must skip companion slots even when told to overwrite. + store2 = PlaylistStore(work) + spec = type("S", (), {"slot": slot, "start": 42.0, "name": "X", "type": 0, "length": 0.0})() + store2.place_hotcues(track_id, [spec], overwrite=True) + e2 = store2.model_entry(track_id) + comp = bg.companions(e2).get(0) + check("J: place_hotcues(overwrite) skips a companion slot", + comp is not None and abs(comp.start - 42_000.0) > 1) + + # Deleting the grid releases the slot it was holding. + store2.delete_grid(track_id) + e2 = store2.model_entry(track_id) + check("J: delete_grid frees the companion's hotcue slot", + not any(c.hotcue == slot for c in (e2.cue_v2 or []))) + + +# ---- Invariant K: real flexible grids project correctly (read-only) ---- +print("== K. genuine Traktor flexible grids read correctly ==") +_real = TraktorCollection(path=REAL).nml.collection.entry +_flex = [e for e in _real if len(bg.grid_markers(e)) > 1] +if not _flex: + print(" [SKIP] no flexible-grid entries in the reference collection") +else: + import konduktor.main as _m + + ok_order = ok_tempo = ok_proj = ok_comp = True + for e in _flex: + ms = bg.grid_markers(e) + ok_order &= all(ms[i].start < ms[i + 1].start for i in range(len(ms) - 1)) + if e.tempo and e.tempo.bpm: + ok_tempo &= abs(e.tempo.bpm - ms[0].grid.bpm) < 1e-6 + tc = _m._build_track_cues(e) + ok_proj &= len(tc.grid_markers) == len(ms) and all( + abs(g.bpm - m.grid.bpm) < 1e-9 and abs(g.start - (m.start or 0) / 1000.0) < 1e-9 + for g, m in zip(tc.grid_markers, ms) + ) + # A marker with no companion must project None, not raise. + comps = bg.companions(e) + ok_comp &= all( + (tc.grid_markers[i].companion is None) == (i not in comps) for i in range(len(ms)) + ) + print(f" ({len(_flex)} flexible entr{'y' if len(_flex) == 1 else 'ies'} checked)") + check("K: markers strictly ascending by START", ok_order) + check("K: TEMPO mirrors the first marker", ok_tempo) + check("K: every marker projects with its own BPM + position", ok_proj) + check("K: a marker without a companion projects None", ok_comp) + + print("\nRESULT:", "FAILED" if failed else "ALL PASSED") sys.exit(1 if failed else 0) diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 0ea190b..33f0aff 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "frontend", - "version": "0.1.1", + "version": "0.1.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "frontend", - "version": "0.1.1", + "version": "0.1.2", "dependencies": { "@dnd-kit/core": "^6.3.1", "@dnd-kit/modifiers": "^9.0.0", @@ -32,7 +32,8 @@ "postcss": "^8.5.16", "tailwindcss": "^4.3.2", "typescript": "~6.0.2", - "vite": "^8.1.1" + "vite": "^8.1.1", + "vitest": "^5.0.1" } }, "node_modules/@alloc/quick-lru": { @@ -182,9 +183,9 @@ } }, "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.5.5", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", - "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", "dev": true, "license": "MIT" }, @@ -1488,6 +1489,31 @@ "tslib": "^2.4.0" } }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/node": { "version": "24.13.2", "resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.2.tgz", @@ -1544,6 +1570,64 @@ } } }, + "node_modules/@vitest/mocker": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.0.1.tgz", + "integrity": "sha512-6K1DoBNAPGvuOcSsGA4D6x+5zEEff/KmOOP3uetT2TrGpVfI+HRHRnJJfKi5ib/g1vx8IYHQD8s0pbJz8WQI7Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.31", + "@vitest/spy": "5.0.1", + "estree-walker": "^3.0.3", + "magic-string": "^1.2.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/mocker/node_modules/magic-string": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.1.tgz", + "integrity": "sha512-8lyCu36ErXR0J9uaGKlKQoiLZKmtI63YGLE8G2o9jyRPdr4X47LusSOwgOJOzcVtp81fTAAjxR7BwKz682Jhow==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/@vitest/spy": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.0.1.tgz", + "integrity": "sha512-rbto/mF/SGERxEgYOek7Xm6B9b+y+mVoo+f4b2LymYO8zM1b7uB5nHuhVMTP2hxdzgxvGiZYGxGIaMvL5y180Q==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, "node_modules/autoprefixer": { "version": "10.5.2", "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.5.2.tgz", @@ -1649,6 +1733,16 @@ ], "license": "CC-BY-4.0" }, + "node_modules/chai": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", + "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/csstype": { "version": "3.2.3", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", @@ -1687,6 +1781,13 @@ "node": ">=10.13.0" } }, + "node_modules/es-module-lexer": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT" + }, "node_modules/escalade": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", @@ -1697,6 +1798,26 @@ "node": ">=6" } }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/fdir": { "version": "6.5.0", "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", @@ -2073,6 +2194,20 @@ "node": ">=18" } }, + "node_modules/obug": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/obug/-/obug-2.2.1.tgz", + "integrity": "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, "node_modules/oxlint": { "version": "1.72.0", "resolved": "https://registry.npmjs.org/oxlint/-/oxlint-1.72.0.tgz", @@ -2130,9 +2265,9 @@ "license": "ISC" }, "node_modules/picomatch": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz", - "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==", + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", "dev": true, "license": "MIT", "engines": { @@ -2239,6 +2374,13 @@ "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==", "license": "MIT" }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, "node_modules/source-map-js": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", @@ -2249,6 +2391,20 @@ "node": ">=0.10.0" } }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/std-env": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.2.0.tgz", + "integrity": "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==", + "dev": true, + "license": "MIT" + }, "node_modules/tailwindcss": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.2.tgz", @@ -2270,6 +2426,26 @@ "url": "https://opencollective.com/webpack" } }, + "node_modules/tinybench": { + "version": "6.1.4", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.1.4.tgz", + "integrity": "sha512-9APumHG7r4yOk4X4WlkmE71aZcv1gvin1czO3OQ1U9iJcFA5Ja/ygyb0vPOVHTthFozUYs8CLoLUlM8grb2lTQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/tinyexec": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.0.tgz", + "integrity": "sha512-QKAl9m8gWWGHV8jZcPeym6j+XULi6tOf1mT83WYJ4Lk2ytW/uwAWkrP0uFsdoYMdueVJ0qs26wZ+23xeB4ibNQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/tinyglobby": { "version": "0.2.17", "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", @@ -2422,6 +2598,116 @@ "optional": true } } + }, + "node_modules/vitest": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.0.1.tgz", + "integrity": "sha512-iA95lQbKEkvrtTkdAgnWbXfbipWiiWe/hDl2P5tMi6WFwD76G0NxXAGp/M9EOcYupeGJRr6wppMc7CoA41TQjg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/mocker": "5.0.1", + "chai": "^6.2.2", + "es-module-lexer": "^2.3.2", + "expect-type": "^1.4.0", + "magic-string": "^1.2.3", + "obug": "^2.1.4", + "picomatch": "^4.0.7", + "std-env": "^4.2.0", + "tinybench": "6.1.4", + "tinyexec": "1.3.0", + "tinyglobby": "^0.2.17", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^22.12.0 || ^24.0.0 || >=26.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "5.0.1", + "@vitest/browser-preview": "5.0.1", + "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", + "@vitest/coverage-istanbul": "5.0.1", + "@vitest/coverage-v8": "5.0.1", + "@vitest/ui": "5.0.1", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/vitest/node_modules/magic-string": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.1.tgz", + "integrity": "sha512-8lyCu36ErXR0J9uaGKlKQoiLZKmtI63YGLE8G2o9jyRPdr4X47LusSOwgOJOzcVtp81fTAAjxR7BwKz682Jhow==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } } } } diff --git a/frontend/package.json b/frontend/package.json index 4163b5c..d867ac5 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -7,7 +7,8 @@ "dev": "vite", "build": "tsc -b && vite build", "lint": "oxlint", - "preview": "vite preview" + "preview": "vite preview", + "test": "vitest run" }, "dependencies": { "@dnd-kit/core": "^6.3.1", @@ -34,6 +35,7 @@ "postcss": "^8.5.16", "tailwindcss": "^4.3.2", "typescript": "~6.0.2", - "vite": "^8.1.1" + "vite": "^8.1.1", + "vitest": "^5.0.1" } } diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 0f65470..3639b3d 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -24,6 +24,7 @@ export interface Track { cue_count: number hotcue_count: number has_grid: boolean + grid_markers: number // >1 = a flexible (multi-tempo) beatgrid is_stem: boolean } @@ -105,11 +106,31 @@ export interface CuePoint { length: number // seconds (>0 for loops) hotcue: number // -1 if not a hotcue color: string | null // "#RRGGBB" + /** + * Index of the grid marker this cue is the companion of, if any. Traktor + * pairs most grid markers with a white cue that occupies a real hotcue slot; + * it belongs to the beatgrid, so it is shown read-only and the backend + * refuses hotcue edits on it. + */ + grid_marker: number | null +} + +/** One beatgrid marker. Its position in the list IS its index/identity. */ +export interface GridMarker { + start: number // seconds + bpm: number // governs from this marker until the next one + name: string | null // Traktor's label — display only, NOT a discriminator + companion: number | null // hotcue slot of the paired white cue, if any } export interface TrackCues { - bpm: number | null - grid_anchor: number | null // seconds + /** + * The beatgrid, ordered by start. Empty = no grid, one marker = constant + * tempo, more = a flexible (multi-tempo) grid. There is deliberately no + * scalar bpm/anchor: assuming a single tempo is what made flexible grids + * render and edit wrongly. + */ + grid_markers: GridMarker[] locked: boolean cues: CuePoint[] } @@ -336,8 +357,25 @@ export const api = { 'DELETE', `/api/tracks/hotcue?track_id=${encodeURIComponent(trackId)}&slot=${slot}`, ), - setGrid: (trackId: string, patch: { bpm?: number; anchor?: number }) => - send('PATCH', '/api/tracks/grid', { track_id: trackId, ...patch }), + /** Retempo and/or move one marker. `index` is its position in grid_markers; + * a move is clamped between its neighbours rather than reordering them. */ + setGridMarker: (trackId: string, index: number, patch: { bpm?: number; start?: number }) => + send('PATCH', '/api/tracks/grid/marker', { + track_id: trackId, + index, + ...patch, + }), + /** Add a marker. Omitting `bpm` inherits the tempo governing that position. */ + addGridMarker: (trackId: string, start: number, bpm?: number) => + send('POST', '/api/tracks/grid/marker', { track_id: trackId, start, bpm }), + deleteGridMarker: (trackId: string, index: number) => + send( + 'DELETE', + `/api/tracks/grid/marker?track_id=${encodeURIComponent(trackId)}&index=${index}`, + ), + /** Replace the whole grid (the deck's Reset). `[]` clears it. */ + replaceGridMarkers: (trackId: string, markers: GridMarker[]) => + send('PUT', '/api/tracks/grid', { track_id: trackId, markers }), deleteGrid: (trackId: string) => send('DELETE', `/api/tracks/grid?track_id=${encodeURIComponent(trackId)}`), setLock: (trackId: string, locked: boolean) => diff --git a/frontend/src/components/GridControls.tsx b/frontend/src/components/GridControls.tsx index 58f33a2..084cc54 100644 --- a/frontend/src/components/GridControls.tsx +++ b/frontend/src/components/GridControls.tsx @@ -1,23 +1,52 @@ -import { useRef, useState } from 'react' +import { memo, useRef, useState } from 'react' interface Props { + /** Tempo of the marker governing the playhead — what the tempo controls act + * on. Null when the track has no grid. */ bpm: number | null + /** Index of that marker; -1 when there is no grid. */ + markerIndex: number + /** 0 = no grid, 1 = constant tempo, >1 = a flexible (multi-tempo) grid. */ + markerCount: number + /** Position (s) of the governing marker; null when there is no grid. */ + markerStart: number | null + /** The playhead is sitting on the governing marker. */ + atMarker: boolean + /** The playhead precedes the first marker (whose tempo extrapolates back). */ + beforeFirst: boolean locked: boolean - hasGrid: boolean + /** A snapshot of the grid as loaded exists to restore. */ + canReset: boolean onSetBpm: (bpm: number) => void onNudgeBpm: (delta: number) => void + /** Octave fix for the governing marker (halve / double its BPM). */ onHalve: () => void onDouble: () => void - onNudge: (deltaMs: number) => void - onSetHere: () => void + /** Move the governing marker by ±ms. */ + onNudgeMarker: (deltaMs: number) => void + /** Add a marker at the playhead (creates the grid when there is none). */ + onAddMarker: () => void + /** Delete the governing marker (offered only while standing on it). */ + onDeleteMarker: () => void + /** Seek to the adjacent marker — under playhead-derived selection this is + * how the user changes which marker they are editing. */ + onPrevMarker: () => void + onNextMarker: () => void onReset: () => void onToggleLock: () => void onDeleteGrid: () => void - /** Detect BPM + first beat and build the grid (sets hotcue 1 + anchor). */ + /** Detect BPM + first beat and rebuild the grid as a single marker. */ onAnalyze: () => void analyzing: boolean } +/** m:ss.mmm — marker positions need millisecond precision to be useful. */ +function markerTime(t: number): string { + const m = Math.floor(t / 60) + const s = t - m * 60 + return `${m}:${s < 10 ? '0' : ''}${s.toFixed(3)}` +} + const BTN = 'flex flex-1 items-center justify-center rounded border border-line bg-ink-850 py-1 text-xs ' + 'font-semibold text-text transition-colors hover:border-accent disabled:opacity-30 ' + @@ -26,25 +55,39 @@ const BTN = /** * Beatgrid / tempo panel (Traktor grid-control equivalent): editable BPM, BPM * nudge (fine ±0.01 / coarse ±0.25), half/double, tap tempo, grid-phase nudge - * (±1/±10 ms), set beat 1 at the playhead, reset to the loaded values, lock, - * and delete grid. + * (±1/±10 ms), add/delete markers, reset to the loaded grid, lock, delete grid. + * + * A beatgrid is a list of tempo markers, and the one being edited is derived + * from the playhead rather than selected separately — so the tempo controls + * always act on the marker governing what you are hearing. Memoised because the + * playhead updates every frame and most of those frames change nothing here. */ -export function GridControls({ +export const GridControls = memo(function GridControls({ bpm, + markerIndex, + markerCount, + markerStart, + atMarker, + beforeFirst, locked, - hasGrid, + canReset, onSetBpm, onNudgeBpm, onHalve, onDouble, - onNudge, - onSetHere, + onNudgeMarker, + onAddMarker, + onDeleteMarker, + onPrevMarker, + onNextMarker, onReset, onToggleLock, onDeleteGrid, onAnalyze, analyzing, }: Props) { + const hasGrid = markerCount > 0 + const flexible = markerCount > 1 const [editing, setEditing] = useState(false) const [val, setVal] = useState('') const tapsRef = useRef([]) @@ -96,7 +139,39 @@ export function GridControls({ {bpm != null ? bpm.toFixed(2) : '––'} )} -
BPM
+ {!hasGrid ? ( +
+ No grid +
+ ) : !flexible ? ( +
BPM
+ ) : ( + // Flexible grid: show which marker is in charge and let the user step + // between them (which seeks — there is no separate selection). +
+ + + {beforeFirst ? '↤ ' : '⊞ '} + {markerIndex + 1}/{markerCount} + {markerStart != null ? ` · ${markerTime(markerStart)}` : ''} + + +
+ )} {/* BPM nudge — coarse ±0.25 (outer) / fine ±0.01 (inner) */} @@ -140,16 +215,31 @@ export function GridControls({ {/* halve / double / tap / reset */}
- - -
@@ -159,19 +249,49 @@ export function GridControls({ Grid - - - - - @@ -190,9 +310,36 @@ export function GridControls({ > {locked ? '🔒 Locked' : '🔓 Lock'} + {/* Only a marker you are standing on can be deleted, so one that is + scrolled off-screen can never go by accident. Deleting the last + marker is "delete grid", not a second button doing the same thing. */} + ) })} diff --git a/frontend/src/components/LoopControls.tsx b/frontend/src/components/LoopControls.tsx index 0768f82..a461f74 100644 --- a/frontend/src/components/LoopControls.tsx +++ b/frontend/src/components/LoopControls.tsx @@ -1,5 +1,5 @@ interface Props { - bpm: number | null // beat-loops need a grid; buttons disable without one + hasGrid: boolean // beat-loops need a beatgrid; buttons disable without one active: boolean // a loop is currently engaged activeBeats: number | null // size of the active loop (null for a manual loop) canToggle: boolean // a loop region exists to enable/disable @@ -23,7 +23,7 @@ const IDLE = 'bg-ink-900 text-text hover:bg-ink-800' const OFF = 'disabled:opacity-30 disabled:hover:bg-ink-900' export function LoopControls({ - bpm, + hasGrid, active, activeBeats, canToggle, @@ -34,7 +34,6 @@ export function LoopControls({ onLoopOut, onToggleActive, }: Props) { - const hasGrid = !!bpm && bpm > 0 return (
diff --git a/frontend/src/components/MainWaveform.tsx b/frontend/src/components/MainWaveform.tsx index 1d57ea8..b86036b 100644 --- a/frontend/src/components/MainWaveform.tsx +++ b/frontend/src/components/MainWaveform.tsx @@ -1,5 +1,6 @@ import { useEffect, useRef } from 'react' import type { CuePoint } from '../api' +import type { BeatGrid } from '../lib/beatgrid' import { drawBeatgrid, drawCuePoint, drawCues, drawLoop } from '../lib/cues' import { paintWave, type WaveColumn } from '../lib/waveform' @@ -9,8 +10,9 @@ interface Props { duration: number cues: CuePoint[] cuePoint: number | null - bpm: number | null - gridAnchor: number | null + grid: BeatGrid | null + /** Marker governing the playhead — drawn gold, its segment tinted. */ + activeMarker: number loop: { start: number; end: number } | null /** Seconds across the view — the zoom level, owned by the parent so it survives track switches and persists to prefs. */ @@ -40,8 +42,8 @@ export function MainWaveform({ duration, cues, cuePoint, - bpm, - gridAnchor, + grid, + activeMarker, loop, secPerView, onZoomChange, @@ -84,8 +86,8 @@ export function MainWaveform({ if (loop) { drawLoop(ctx, timeToX(loop.start), timeToX(loop.end), h, dpr) } - if (bpm && gridAnchor != null) { - drawBeatgrid(ctx, bpm, gridAnchor, startSec, endSec, w, h, dpr) + if (grid) { + drawBeatgrid(ctx, grid, startSec, endSec, w, h, dpr, activeMarker) } if (cues.length) { drawCues(ctx, cues, w, h, dpr, timeToX, true) diff --git a/frontend/src/components/PrepStrip.tsx b/frontend/src/components/PrepStrip.tsx index 86bb285..3b5a7bb 100644 --- a/frontend/src/components/PrepStrip.tsx +++ b/frontend/src/components/PrepStrip.tsx @@ -1,6 +1,7 @@ -import { useEffect, useRef, useState } from 'react' +import { useEffect, useMemo, useRef, useState } from 'react' import { useQuery, useQueryClient } from '@tanstack/react-query' -import { api, type Track, type TrackCues } from '../api' +import { api, type GridMarker, type Track, type TrackCues } from '../api' +import { buildBeatGrid, GRID_EPS } from '../lib/beatgrid' import { analyzeWaveform, type WaveColumn } from '../lib/waveform' import { ScratchEngine } from '../lib/scratchEngine' import { PlaybackEngine } from '../lib/playbackEngine' @@ -54,6 +55,9 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) const [cols, setCols] = useState(null) const [waveStatus, setWaveStatus] = useState<'loading' | 'ready' | 'error'>('loading') const [cueData, setCueData] = useState(null) + // The beatgrid, rebuilt whenever the cue data is replaced (every edit returns + // a fresh TrackCues, so this stays in step automatically). Null = no grid. + const grid = useMemo(() => buildBeatGrid(cueData?.grid_markers), [cueData?.grid_markers]) const [snap, setSnap] = useState(true) const [selectedSlot, setSelectedSlot] = useState(null) const [cuePoint, setCuePoint] = useState(0) // floating "CUE" point (frontend-only) @@ -65,7 +69,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) const [loopActive, setLoopActive] = useState(false) const [activeBeats, setActiveBeats] = useState(null) const loopInRef = useRef(null) // armed manual loop-in point - const originalGridRef = useRef<{ bpm: number | null; anchor: number | null } | null>(null) + const originalGridRef = useRef(null) const audioCtxRef = useRef(null) // playback const scratchCtxRef = useRef(null) // scratch (kept separate!) @@ -244,8 +248,10 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) .then((d) => { if (cancelled) return setCueData(d) - // Remember the loaded grid values for "Reset". - originalGridRef.current = { bpm: d.bpm, anchor: d.grid_anchor } + // Remember the grid as loaded, for "Reset". Flexible-grid editing is + // multi-step and destructive, so restoring exactly what Traktor had is + // the safety net. Set only here (keyed on trackId), never by an edit. + originalGridRef.current = d.grid_markers }) .catch(() => { if (!cancelled) setCueData(null) @@ -397,13 +403,14 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) // active loop. seek() clamps to [0, duration], preserves play/pause state. const beatJump = (dir: -1 | 1) => { const eng = playbackRef.current - const bpm = cueData?.bpm ?? null - if (!eng || !bpm || bpm <= 0) return + if (!eng || !grid) return if (loopActive) { eng.setLoopEnabled(false) setLoopActive(false) } - eng.seek(eng.getPosition() + dir * jumpBeats * (60 / bpm)) + // Phase is preserved in BEAT space, so a jump crossing a tempo change lands + // on the musically right beat rather than a fixed number of seconds away. + eng.seek(grid.advanceBeats(eng.getPosition(), dir * jumpBeats)) setCurrent(eng.getPosition()) } @@ -475,13 +482,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) // ---- loops ------------------------------------------------------------ // Snap a time to the nearest beat when Snap is on (needs a beatgrid). - const snapTime = (t: number) => { - const bpm = cueData?.bpm ?? null - const anchor = cueData?.grid_anchor ?? null - if (!snap || !bpm || bpm <= 0 || anchor == null) return Math.max(0, t) - const beat = 60 / bpm - return Math.max(0, anchor + Math.round((t - anchor) / beat) * beat) - } + const snapTime = (t: number) => (snap && grid ? grid.snapToBeat(t) : Math.max(0, t)) const engagLoop = (start: number, end: number, beats: number | null) => { const eng = playbackRef.current @@ -496,8 +497,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) const setBeatLoop = (beats: number) => { const eng = playbackRef.current - const bpm = cueData?.bpm ?? null - if (!eng || !eng.ready || !bpm || bpm <= 0) return + if (!eng || !eng.ready || !grid) return // Pressing the size of the loop that's already playing disables it. if (loopActive && activeBeats === beats) { eng.setLoopEnabled(false) @@ -508,7 +508,9 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) // Resizing an active loop keeps its start locked; only a fresh loop starts // at the current playhead. const start = loopActive && loopRegion ? loopRegion.start : snapTime(eng.getPosition()) - engagLoop(start, start + beats * (60 / bpm), beats) + // Measured from the loop's own start, so a loop spanning a tempo change + // still covers the right number of beats. + engagLoop(start, grid.advanceBeats(start, beats), beats) } const loopIn = () => { @@ -534,6 +536,19 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) setCurrent(eng.getPosition()) } + // A beat loop's end is stored in seconds, so editing the tempo of a marker + // inside it would silently detune it. Re-derive the end whenever the grid + // changes, keeping the loop the beat length the user actually asked for. + useEffect(() => { + if (!grid || !loopActive || !loopRegion || activeBeats == null) return + const end = grid.advanceBeats(loopRegion.start, activeBeats) + if (Math.abs(end - loopRegion.end) < 1e-4) return + playbackRef.current?.setLoop(loopRegion.start, end, true) + setLoopRegion({ start: loopRegion.start, end }) + // Only the grid should trigger this; loop state changes set the end already. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [grid]) + // ---- hotcues ---------------------------------------------------------- const hotcueAt = (slot: number) => cueData?.cues.find((c) => c.hotcue === slot) ?? null @@ -546,10 +561,11 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) // Map a loop length (seconds) back to a preset beat count for the size // highlight, snapping to the nearest preset when it's close (float tolerance). - const beatsForLength = (length: number): number | null => { - const bpm = cueData?.bpm ?? null - if (!bpm || bpm <= 0) return null - const beats = length / (60 / bpm) + // Needs the start as well as the length: under a marker list a duration + // alone no longer identifies a beat count. + const beatsForLoop = (start: number, length: number): number | null => { + if (!grid) return null + const beats = grid.beatsBetween(start, start + length) let best: number | null = null let bestDiff = Infinity for (const s of LOOP_SIZES) { @@ -570,6 +586,12 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) const onSlotPress = async (slot: number) => { if (!track) return const cue = hotcueAt(slot) + // A grid marker's companion cue holds this slot. It belongs to the beatgrid, + // so pressing it only seeks — never create, retype, select or preview. + if (cue?.grid_marker != null) { + seekManual(cue.start) + return + } if (!cue) { try { // Setting a hotcue while a loop is active stores it as a loop hotcue. @@ -593,7 +615,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) // A loop hotcue jumps to its start AND re-engages a loop of its length. if (cue.type === LOOP_TYPE && cue.length > 0) { seek(cue.start) - engagLoop(cue.start, cue.start + cue.length, beatsForLength(cue.length)) + engagLoop(cue.start, cue.start + cue.length, beatsForLoop(cue.start, cue.length)) } else { seek(cue.start) } @@ -607,7 +629,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) // Auto Hotcues: the backend analyses the track's audio (librosa structural // segmentation), snaps boundaries to the beatgrid, and fills empty slots only. // Requires a beatgrid (button disabled otherwise). - const canAutoCue = !!(cueData?.bpm && cueData.bpm > 0 && cueData.grid_anchor != null) + const canAutoCue = grid != null const runAutoHotcues = async () => { if (!track || !canAutoCue || autoBusy) return const hotcueCount = (c: TrackCues | null) => @@ -654,7 +676,9 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) } const deleteHotcueSlot = async (slot: number) => { - if (!track || !hotcueAt(slot)) return // nothing to remove in an empty slot + const existing = hotcueAt(slot) + if (!track || !existing) return // nothing to remove in an empty slot + if (existing.grid_marker != null) return // beatgrid-owned: delete the marker instead try { applyCueEdit(await api.deleteHotcue(track.id, slot)) if (selectedSlot === slot) setSelectedSlot(null) @@ -663,105 +687,72 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) } } - // ---- keyboard shortcuts ---------------------------------------------- - // Space → play/pause; 1–8 → the matching hotcue slot; Shift+1–8 → delete it. - // Digits are read from e.code (layout-/Shift-independent) and a ref holds the - // latest handlers so the listener attaches once and never goes stale. - const shortcutsRef = useRef({ - toggle, - onSlotPress, - onSlotRelease, - deleteHotcueSlot, - onCuePress, - onCueRelease, - beatJump, - }) - shortcutsRef.current = { - toggle, - onSlotPress, - onSlotRelease, - deleteHotcueSlot, - onCuePress, - onCueRelease, - beatJump, - } - useEffect(() => { - const onKey = (e: KeyboardEvent) => { - // Ignore while typing in a field or with a non-Shift modifier held. - const t = e.target as HTMLElement | null - if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return - if (e.metaKey || e.ctrlKey || e.altKey) return - if (e.repeat) return // held key auto-repeats — treat as one press+hold - if (e.code === 'Space') { - e.preventDefault() - shortcutsRef.current.toggle() - return - } - if (e.code === 'KeyC') { - e.preventDefault() - shortcutsRef.current.onCuePress() - return - } - if (e.code === 'ArrowLeft') { - e.preventDefault() - shortcutsRef.current.beatJump(-1) - return - } - if (e.code === 'ArrowRight') { - e.preventDefault() - shortcutsRef.current.beatJump(1) - return - } - const digit = e.code.match(/^(?:Digit|Numpad)([1-8])$/) - if (digit) { - e.preventDefault() - const slot = Number(digit[1]) - 1 - if (e.shiftKey) void shortcutsRef.current.deleteHotcueSlot(slot) - else void shortcutsRef.current.onSlotPress(slot) - } - } - // keyup ends a held hotcue's momentary preview (release). - const onKeyRelease = (e: KeyboardEvent) => { - if (e.code === 'KeyC') shortcutsRef.current.onCueRelease() - const digit = e.code.match(/^(?:Digit|Numpad)([1-8])$/) - if (digit) shortcutsRef.current.onSlotRelease(Number(digit[1]) - 1) - } - window.addEventListener('keydown', onKey) - window.addEventListener('keyup', onKeyRelease) - return () => { - window.removeEventListener('keydown', onKey) - window.removeEventListener('keyup', onKeyRelease) - } - }, []) - // ---- beatgrid --------------------------------------------------------- - const gridBpm = cueData?.bpm ?? null - const gridAnchor = cueData?.grid_anchor ?? null - // Beat jump needs a tempo to size beats; disabled on ungridded tracks. - const canBeatJump = ready && gridBpm != null && gridBpm > 0 + // Which marker the grid controls act on is derived from the playhead — there + // is no separate selection state to keep in sync. + const activeMarkerIndex = grid ? grid.markerIndexAt(current) : -1 + const activeMarker = activeMarkerIndex >= 0 ? grid!.markers[activeMarkerIndex] : null + // ~4px of the current zoom, so "on the marker" stays usable at 2s and 64s/view. + const markerHitSec = Math.max(0.01, secPerView / 250) + const atMarker = !!grid && grid.isOnMarker(current, markerHitSec) + const beforeFirstMarker = !!grid && current < grid.markers[0].start - GRID_EPS + // Beat jump needs a grid to size beats; disabled on ungridded tracks. + const canBeatJump = ready && grid != null - const editGrid = async (patch: { bpm?: number; anchor?: number }) => { - if (!track) return + const playheadNow = () => playbackRef.current?.getPosition() ?? current + + const editMarker = async (index: number, patch: { bpm?: number; start?: number }) => { + if (!track || index < 0) return try { - applyCueEdit(await api.setGrid(track.id, patch)) + applyCueEdit(await api.setGridMarker(track.id, index, patch)) } catch (e) { onError?.((e as Error).message) } } - const setBpm = (bpm: number) => editGrid({ bpm }) - const nudgeBpm = (delta: number) => - gridBpm && editGrid({ bpm: Math.round((gridBpm + delta) * 1000) / 1000 }) - const halveBpm = () => gridBpm && editGrid({ bpm: gridBpm / 2 }) - const doubleBpm = () => gridBpm && editGrid({ bpm: gridBpm * 2 }) + const setBpm = (bpm: number) => + editMarker(activeMarkerIndex, { bpm: Math.round(bpm * 1000) / 1000 }) + const nudgeBpm = (delta: number) => activeMarker && setBpm(activeMarker.bpm + delta) + // /2 and x2 retempo the governing marker only, like every other tempo control + // in this panel — a section can be octave-wrong on its own. + const halveBpm = () => activeMarker && setBpm(activeMarker.bpm / 2) + const doubleBpm = () => activeMarker && setBpm(activeMarker.bpm * 2) const nudgeGrid = (deltaMs: number) => { - if (gridAnchor == null) return - editGrid({ anchor: Math.max(0, gridAnchor + deltaMs / 1000) }) + if (!activeMarker) return + editMarker(activeMarkerIndex, { start: Math.max(0, activeMarker.start + deltaMs / 1000) }) } - const setGridHere = () => editGrid({ anchor: playbackRef.current?.getPosition() ?? current }) - const resetGrid = () => { + // Adds a marker at the playhead — and creates the grid when there is none. + // Uses the raw playhead, not snapTime: a marker defines where beats are. + const addMarkerHere = async () => { + if (!track) return + try { + applyCueEdit(await api.addGridMarker(track.id, playheadNow())) + } catch (e) { + onError?.((e as Error).message) + } + } + const deleteMarkerHere = async () => { + if (!track || activeMarkerIndex < 0) return + try { + applyCueEdit(await api.deleteGridMarker(track.id, activeMarkerIndex)) + } catch (e) { + onError?.((e as Error).message) + } + } + // Seeking between markers IS how the user changes which marker is active. + const seekToMarker = (index: number) => { + if (!grid || index < 0 || index >= grid.count) return + seekManual(grid.markers[index].start) + } + const prevMarker = () => seekToMarker(grid ? grid.prevMarkerIndex(current, markerHitSec) : -1) + const nextMarker = () => seekToMarker(grid ? grid.nextMarkerIndex(current, markerHitSec) : -1) + const resetGrid = async () => { const o = originalGridRef.current - if (!o) return - editGrid({ bpm: o.bpm ?? undefined, anchor: o.anchor ?? undefined }) + if (!track || !o) return + try { + applyCueEdit(await api.replaceGridMarkers(track.id, o)) + } catch (e) { + onError?.((e as Error).message) + } } const toggleLock = async () => { if (!track) return @@ -793,6 +784,84 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) } } + // ---- keyboard shortcuts ---------------------------------------------- + // Space → play/pause; 1–8 → the matching hotcue slot; Shift+1–8 → delete it. + // ←/→ → beat jump; Shift+←/→ → step between grid markers. + // Digits are read from e.code (layout-/Shift-independent) and a ref holds the + // latest handlers so the listener attaches once and never goes stale. + const shortcutsRef = useRef({ + toggle, + onSlotPress, + onSlotRelease, + deleteHotcueSlot, + onCuePress, + onCueRelease, + beatJump, + prevMarker, + nextMarker, + }) + shortcutsRef.current = { + toggle, + onSlotPress, + onSlotRelease, + deleteHotcueSlot, + onCuePress, + onCueRelease, + beatJump, + prevMarker, + nextMarker, + } + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + // Ignore while typing in a field or with a non-Shift modifier held. + const t = e.target as HTMLElement | null + if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return + if (e.metaKey || e.ctrlKey || e.altKey) return + if (e.repeat) return // held key auto-repeats — treat as one press+hold + if (e.code === 'Space') { + e.preventDefault() + shortcutsRef.current.toggle() + return + } + if (e.code === 'KeyC') { + e.preventDefault() + shortcutsRef.current.onCuePress() + return + } + if (e.code === 'ArrowLeft') { + e.preventDefault() + if (e.shiftKey) shortcutsRef.current.prevMarker() + else shortcutsRef.current.beatJump(-1) + return + } + if (e.code === 'ArrowRight') { + e.preventDefault() + if (e.shiftKey) shortcutsRef.current.nextMarker() + else shortcutsRef.current.beatJump(1) + return + } + const digit = e.code.match(/^(?:Digit|Numpad)([1-8])$/) + if (digit) { + e.preventDefault() + const slot = Number(digit[1]) - 1 + if (e.shiftKey) void shortcutsRef.current.deleteHotcueSlot(slot) + else void shortcutsRef.current.onSlotPress(slot) + } + } + // keyup ends a held hotcue's momentary preview (release). + const onKeyRelease = (e: KeyboardEvent) => { + if (e.code === 'KeyC') shortcutsRef.current.onCueRelease() + const digit = e.code.match(/^(?:Digit|Numpad)([1-8])$/) + if (digit) shortcutsRef.current.onSlotRelease(Number(digit[1]) - 1) + } + window.addEventListener('keydown', onKey) + window.addEventListener('keyup', onKeyRelease) + return () => { + window.removeEventListener('keydown', onKey) + window.removeEventListener('keyup', onKeyRelease) + } + }, []) + const selectedCue = selectedSlot != null ? hotcueAt(selectedSlot) : null const showWaves = track && cols && waveStatus === 'ready' const activeLoop = loopActive && loopRegion ? loopRegion : null @@ -818,15 +887,23 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) {track && ( { + const g = buildBeatGrid(markers) + if (!g) throw new Error('expected a grid') + return g +} + +// 120 BPM => 0.5 s per beat, which keeps the expected values exact in binary. +const CONST = [{ start: 1, bpm: 120 }] +// A tempo change at 10 s: 120 BPM (0.5 s/beat) then 60 BPM (1 s/beat). +const FLEX = [ + { start: 1, bpm: 120 }, + { start: 10, bpm: 60 }, +] + +describe('buildBeatGrid', () => { + it('returns null when there is no grid', () => { + expect(buildBeatGrid(undefined)).toBeNull() + expect(buildBeatGrid(null)).toBeNull() + expect(buildBeatGrid([])).toBeNull() + }) + + it('drops unusable markers and returns null if none survive', () => { + expect(buildBeatGrid([{ start: 0, bpm: 0 }])).toBeNull() + expect(buildBeatGrid([{ start: 0, bpm: NaN }])).toBeNull() + expect(buildBeatGrid([{ start: Infinity, bpm: 120 }])).toBeNull() + }) + + it('sorts unsorted input and clamps negative starts', () => { + const g = grid([ + { start: 10, bpm: 60 }, + { start: -5, bpm: 120 }, + ]) + expect(g.markers.map((m) => m.start)).toEqual([0, 10]) + }) + + it('collapses markers at the same instant', () => { + const g = grid([ + { start: 5, bpm: 120 }, + { start: 5, bpm: 140 }, + ]) + expect(g.count).toBe(1) + expect(g.markers[0].bpm).toBe(140) + }) + + it('clamps absurd BPMs so beat duration is always finite and non-zero', () => { + const g = grid([{ start: 0, bpm: 100000 }]) + expect(Number.isFinite(g.beatDurationAt(0))).toBe(true) + expect(g.beatDurationAt(0)).toBeGreaterThan(0) + }) +}) + +describe('single marker behaves exactly as the old single-BPM math', () => { + // This is the acceptance property for the whole marker-list model: 99.98% of + // tracks have one marker and must be completely unaffected by it. + const g = grid(CONST) + const anchor = CONST[0].start + const beat = 60 / CONST[0].bpm + const oldSnap = (t: number) => Math.max(0, anchor + Math.round((t - anchor) / beat) * beat) + + it('matches the old snapTime across the track', () => { + for (let t = 0; t < 120; t += 0.137) { + expect(g.snapToBeat(t)).toBeCloseTo(oldSnap(t), 9) + } + }) + + it('matches the old beat-jump arithmetic', () => { + for (const n of [1, 4, 8, 32, -1, -4]) { + expect(g.advanceBeats(20, n)).toBeCloseTo(20 + n * beat, 9) + } + }) + + it('extrapolates backwards before the first marker, as before', () => { + expect(g.beatIndexAt(anchor - beat)).toBeCloseTo(-1, 9) + expect(g.markerIndexAt(0)).toBe(0) + }) + + it('clamps snapping at zero', () => { + expect(g.snapToBeat(-99)).toBeGreaterThanOrEqual(0) + }) +}) + +describe('beat space is invertible', () => { + for (const [label, markers] of [ + ['constant', CONST], + ['flexible', FLEX], + ] as const) { + it(`timeOfBeat inverts beatIndexAt (${label})`, () => { + const g = grid([...markers]) + for (let t = 0; t < 40; t += 0.233) { + expect(g.timeOfBeat(g.beatIndexAt(t))).toBeCloseTo(t, 9) + } + }) + + it(`advanceBeats is reversible (${label})`, () => { + const g = grid([...markers]) + for (const n of [1, 4, 16, -3]) { + for (const t of [2, 9.5, 10, 12.25, 30]) { + expect(g.advanceBeats(g.advanceBeats(t, n), -n)).toBeCloseTo(t, 9) + } + } + }) + + it(`beatsBetween inverts advanceBeats (${label})`, () => { + const g = grid([...markers]) + expect(g.beatsBetween(3, g.advanceBeats(3, 8))).toBeCloseTo(8, 9) + }) + } +}) + +describe('flexible grid', () => { + const g = grid(FLEX) + + it('reports the governing tempo per position', () => { + expect(g.bpmAt(5)).toBe(120) + expect(g.bpmAt(15)).toBe(60) + // Exactly on a marker selects THAT marker, so the readout cannot flicker. + expect(g.bpmAt(10)).toBe(60) + // Before the first marker, marker 0 extrapolates backwards. + expect(g.bpmAt(0)).toBe(120) + }) + + it('counts whole beats in a bounded segment', () => { + // 1s -> 10s at 0.5 s/beat = 18 beats, so the second segment starts at 18. + expect(g.segments[0].beatCount).toBe(18) + expect(g.segments[1].baseIndex).toBe(18) + expect(g.segments[1].beatCount).toBe(Infinity) + }) + + it('advances across a tempo change in beat space, not seconds', () => { + // Two beats before the seam, then four beats forward: two at 0.5 s to reach + // the marker, then two at 1 s past it. + expect(g.advanceBeats(9, 4)).toBeCloseTo(12, 9) + }) + + it('keeps no beat closer than half a beat to the next marker', () => { + // The Math.round beat-count rule is what guarantees snapping stays + // unambiguous when a marker does not land on an exact beat. + const off = grid([ + { start: 0, bpm: 120 }, + { start: 10.2, bpm: 60 }, + ]) + const seg = off.segments[0] + const lastBeat = seg.start + (seg.beatCount - 1) * seg.beatDur + expect(off.markers[1].start - lastBeat).toBeGreaterThan(seg.beatDur * 0.5) + }) + + it('restarts bar phase at each marker', () => { + // Each marker is a downbeat of its own segment. + expect(g.nearestBeat(1).beatInBar).toBe(0) + expect(g.nearestBeat(10).beatInBar).toBe(0) + // ...and phase counts up from there within the segment. + expect(g.nearestBeat(12).beatInBar).toBe(2 % BEATS_PER_BAR) + }) + + it('snaps to a real beat near a marker boundary', () => { + const snapped = g.snapToBeat(10.1) + expect(Math.abs(g.beatIndexAt(snapped) - Math.round(g.beatIndexAt(snapped)))).toBeLessThan(1e-9) + }) +}) + +describe('marker lookup helpers', () => { + const g = grid(FLEX) + + it('finds neighbouring markers for playhead navigation', () => { + expect(g.nextMarkerIndex(5, 0.01)).toBe(1) + expect(g.nextMarkerIndex(50, 0.01)).toBe(-1) + expect(g.prevMarkerIndex(5, 0.01)).toBe(0) + expect(g.prevMarkerIndex(0, 0.01)).toBe(-1) + }) + + it('detects standing on a marker within tolerance', () => { + expect(g.isOnMarker(10.005, 0.01)).toBe(true) + expect(g.isOnMarker(10.5, 0.01)).toBe(false) + }) + + it('returns only the segments overlapping a window', () => { + expect(g.segmentsIn(0, 5).map((s) => s.index)).toEqual([0]) + expect(g.segmentsIn(20, 30).map((s) => s.index)).toEqual([1]) + expect(g.segmentsIn(5, 20).map((s) => s.index)).toEqual([0, 1]) + }) + + it('lists markers inside a window', () => { + expect(g.markersIn(0, 5)).toEqual([0]) + expect(g.markersIn(0, 20)).toEqual([0, 1]) + expect(g.markersIn(20, 30)).toEqual([]) + }) +}) diff --git a/frontend/src/lib/beatgrid.ts b/frontend/src/lib/beatgrid.ts new file mode 100644 index 0000000..395f292 --- /dev/null +++ b/frontend/src/lib/beatgrid.ts @@ -0,0 +1,304 @@ +/** + * The beatgrid as an ordered list of tempo markers. + * + * Traktor stores a beatgrid as a list of markers, each carrying its own BPM; + * marker `i`'s tempo governs from its position until marker `i+1`. A + * constant-tempo track is simply a list of length one, so this model covers + * every track rather than being a special case for flexible grids. + * + * The consequence that matters: **beat duration is position-dependent**, so + * `60 / bpm` is wrong the moment a track has more than one marker. Everything + * that needs beats — drawing, cue snapping, beat jump, beat loops, loop-size + * labelling — goes through this module instead. + * + * Two distinct notions of "beat", deliberately kept apart: + * + * - **Beat index** is global and continuous across markers. Beat jump needs a + * single monotonic beat space, or "forward 4 beats" across a tempo change is + * undefined. + * - **Bar phase** restarts at each marker: a marker is beat 0 *and* a downbeat + * of its own segment. With continuous bar numbering, nudging an early + * marker's BPM would renumber every downbeat after it, so the bar lines + * would slide around as you turn the fine nudge — which would make the very + * workflow this exists for unusable. It also matches Traktor, which pairs + * each marker with its own beat-1 cue, and the format cannot express "this + * marker is beat 3 of a bar". + * + * With a single marker every operation here reduces algebraically to the + * previous single-BPM arithmetic, which is the acceptance property for the + * whole model (see beatgrid.test.ts). + */ + +/** One beatgrid marker: this tempo governs from `start` until the next. */ +export interface GridMarker { + start: number // seconds + bpm: number +} + +export const BEATS_PER_BAR = 4 + +/** Positions closer than this are treated as the same instant. Marker times + * arrive as `START / 1000` of a 6-decimal millisecond value, so they carry + * ~1e-9 of noise. */ +export const GRID_EPS = 1e-6 + +// Guards against a corrupt or hand-edited value producing a zero/absurd beat +// duration and an unbounded draw loop. +const MIN_BPM = 1 +const MAX_BPM = 999 + +/** A constant-tempo span, from one marker up to the next. */ +export interface GridSegment { + /** Index of the marker that opens this segment. */ + index: number + marker: GridMarker + /** = marker.start. Segment 0 still extrapolates backwards to -Infinity. */ + start: number + /** The next marker's start, or Infinity for the final segment. */ + end: number + /** Seconds per beat: 60 / marker.bpm. */ + beatDur: number + /** Beats belonging to this segment; Infinity for the final one. */ + beatCount: number + /** Global beat index of this segment's first beat. */ + baseIndex: number +} + +/** One beat line. */ +export interface Beat { + /** Global index: 0 at markers[0], negative before it, +1 per beat. */ + index: number + time: number + /** Index of the marker governing it. */ + marker: number + /** 0..3 within its marker's segment; 0 = downbeat. Restarts at each marker. */ + beatInBar: number +} + +export class BeatGrid { + readonly markers: readonly GridMarker[] + readonly segments: readonly GridSegment[] + + /** Private: a grid can only be built through `buildBeatGrid`, which is where + * the invariants (sorted, deduped, positive finite BPM) are established. */ + private constructor(markers: readonly GridMarker[]) { + this.markers = markers + const segs: GridSegment[] = [] + let baseIndex = 0 + for (let i = 0; i < markers.length; i++) { + const marker = markers[i] + const end = i + 1 < markers.length ? markers[i + 1].start : Infinity + const beatDur = 60 / marker.bpm + // Math.round, not ceil: this makes the gap between a segment's last beat + // and the next marker 0.5-1.5 beats, so a marker that does not land on an + // exact beat absorbs the error into one stretched interval instead of + // producing a beat a few milliseconds before the marker. No two beats can + // ever be near-duplicates, which is what keeps snapping unambiguous. + const beatCount = + end === Infinity ? Infinity : Math.max(1, Math.round((end - marker.start) / beatDur)) + segs.push({ index: i, marker, start: marker.start, end, beatDur, beatCount, baseIndex }) + baseIndex += beatCount + } + this.segments = segs + } + + /** Internal: `markers` must already be sorted, deduped and valid. Use + * `buildBeatGrid` instead. */ + static fromNormalized(markers: readonly GridMarker[]): BeatGrid { + return new BeatGrid(markers) + } + + get count(): number { + return this.markers.length + } + + /** True for a single-marker grid — the constant-tempo case. */ + get isConstant(): boolean { + return this.markers.length === 1 + } + + get bpmRange(): readonly [number, number] { + let lo = Infinity + let hi = -Infinity + for (const m of this.markers) { + if (m.bpm < lo) lo = m.bpm + if (m.bpm > hi) hi = m.bpm + } + return [lo, hi] + } + + // --- which marker is in charge ------------------------------------------ + + /** + * Index of the last marker at or before `t`. Returns 0 when `t` precedes the + * first marker, because marker 0's tempo extrapolates backwards — and 0 is + * also the right marker to edit while standing in that region. + * + * A time exactly on a marker selects THAT marker, not the previous one, so + * the BPM readout does not flicker as the playhead crosses. + */ + markerIndexAt(t: number): number { + let lo = 0 + let hi = this.markers.length - 1 + let found = 0 + while (lo <= hi) { + const mid = (lo + hi) >> 1 + if (this.markers[mid].start <= t + GRID_EPS) { + found = mid + lo = mid + 1 + } else { + hi = mid - 1 + } + } + return found + } + + markerAt(t: number): GridMarker { + return this.markers[this.markerIndexAt(t)] + } + + bpmAt(t: number): number { + return this.markerAt(t).bpm + } + + beatDurationAt(t: number): number { + return 60 / this.bpmAt(t) + } + + isOnMarker(t: number, tol: number): boolean { + return this.markers.some((m) => Math.abs(m.start - t) <= tol) + } + + /** Index of the nearest marker strictly before `t`, or -1. */ + prevMarkerIndex(t: number, tol: number): number { + for (let i = this.markers.length - 1; i >= 0; i--) { + if (this.markers[i].start < t - tol) return i + } + return -1 + } + + /** Index of the nearest marker strictly after `t`, or -1. */ + nextMarkerIndex(t: number, tol: number): number { + for (let i = 0; i < this.markers.length; i++) { + if (this.markers[i].start > t + tol) return i + } + return -1 + } + + // --- beat space ---------------------------------------------------------- + + /** + * Global, real-valued, strictly increasing beat position. Integral exactly on + * beats. Piecewise-linear with breakpoints at the markers, so `timeOfBeat` is + * its exact inverse and round-trips are safe. + */ + beatIndexAt(t: number): number { + const seg = this.segments[this.markerIndexAt(t)] + return seg.baseIndex + (t - seg.start) / seg.beatDur + } + + /** Exact inverse of `beatIndexAt`; accepts fractional and negative `n`. */ + timeOfBeat(n: number): number { + // Find the segment owning beat n. Segment 0 owns everything below it, the + // final segment owns everything above (both have unbounded beat ranges). + let seg = this.segments[0] + for (const s of this.segments) { + if (n >= s.baseIndex) seg = s + else break + } + return seg.start + (n - seg.baseIndex) * seg.beatDur + } + + /** Nearest beat time, clamped to >= 0 (matches the old snapTime). */ + snapToBeat(t: number): number { + return Math.max(0, this.timeOfBeat(Math.round(this.beatIndexAt(t)))) + } + + /** Full descriptor of the nearest beat. */ + nearestBeat(t: number): Beat { + const index = Math.round(this.beatIndexAt(t)) + const time = this.timeOfBeat(index) + const marker = this.markerIndexAt(time) + const seg = this.segments[marker] + const withinSegment = index - seg.baseIndex + return { + index, + time, + marker, + beatInBar: ((withinSegment % BEATS_PER_BAR) + BEATS_PER_BAR) % BEATS_PER_BAR, + } + } + + /** + * Move `t` by `n` beats. Phase is preserved in BEAT space, not seconds, so a + * jump crossing a tempo change lands on the musically correct beat rather + * than a fixed number of seconds away. + */ + advanceBeats(t: number, n: number): number { + return this.timeOfBeat(this.beatIndexAt(t) + n) + } + + /** Signed, fractional beats from `from` to `to`. Inverse of advanceBeats. */ + beatsBetween(from: number, to: number): number { + return this.beatIndexAt(to) - this.beatIndexAt(from) + } + + // --- drawing ------------------------------------------------------------- + + /** Segments overlapping [from, to], in order. A slice of the prebuilt array, + * so this allocates nothing per frame. */ + segmentsIn(from: number, to: number): readonly GridSegment[] { + let first = 0 + let last = this.segments.length - 1 + for (let i = 0; i < this.segments.length; i++) { + if (this.segments[i].end <= from) first = i + 1 + if (this.segments[i].start > to) { + last = i - 1 + break + } + } + if (first > last) return [] + return this.segments.slice(first, last + 1) + } + + /** Marker indices whose position lies within [from, to]. */ + markersIn(from: number, to: number): number[] { + const out: number[] = [] + for (let i = 0; i < this.markers.length; i++) { + const s = this.markers[i].start + if (s >= from && s <= to) out.push(i) + } + return out + } +} + +/** + * Build a grid from the API's marker list, or `null` when the track has none. + * + * Tolerant by design: accepts `undefined` (so a frontend running against an + * older backend degrades to "no grid" rather than throwing), unsorted input, + * duplicate positions, negative starts, and non-finite or out-of-range BPMs. + */ +export function buildBeatGrid(markers?: readonly GridMarker[] | null): BeatGrid | null { + if (!markers || markers.length === 0) return null + const clean: GridMarker[] = [] + for (const m of markers) { + if (!m || !Number.isFinite(m.bpm) || !Number.isFinite(m.start)) continue + if (m.bpm <= 0) continue + clean.push({ + start: Math.max(0, m.start), + bpm: Math.min(MAX_BPM, Math.max(MIN_BPM, m.bpm)), + }) + } + if (clean.length === 0) return null + clean.sort((a, b) => a.start - b.start) + // Collapse markers at the same instant — two segments cannot share a start, + // or `end - start` would be 0 and the beat count would divide by zero. + const deduped: GridMarker[] = [] + for (const m of clean) { + const prev = deduped[deduped.length - 1] + if (prev && Math.abs(prev.start - m.start) <= GRID_EPS) deduped[deduped.length - 1] = m + else deduped.push(m) + } + return BeatGrid.fromNormalized(deduped) +} diff --git a/frontend/src/lib/cues.ts b/frontend/src/lib/cues.ts index 5ba78cd..9e4f932 100644 --- a/frontend/src/lib/cues.ts +++ b/frontend/src/lib/cues.ts @@ -1,7 +1,10 @@ import type { CuePoint } from '../api' +import { BEATS_PER_BAR, type BeatGrid } from './beatgrid' // Marker colour by Traktor cue type. Type is authoritative here (the NML's // stored per-cue colour is intentionally ignored) so each type reads consistently. +// There is deliberately no entry for type 4 (grid): grid markers are not cues — +// they arrive as TrackCues.grid_markers and are drawn by drawBeatgrid. const TYPE_COLORS: Record = { 0: '#3b82f6', // cue — blue 1: '#ff8c2f', // fade-in — orange @@ -50,6 +53,10 @@ export function drawCues( const flagH = Math.round(14 * dpr) const half = Math.floor(lineW / 2) for (const cue of cues) { + // Grid markers and their companion cues belong to the beatgrid and are + // drawn by drawBeatgrid; painting them here too would stack a grey line and + // a numbered flag on top of every marker. + if (cue.type === 4 || cue.grid_marker != null) continue const color = cueColor(cue) const x = Math.round(timeToX(cue.start)) @@ -129,43 +136,91 @@ export function drawLoop( ctx.fillRect(endX - edge, 0, edge, h) } +/** Grid marker line colours. Markers are structural, so they are never culled + * by the density check the way ordinary beat lines are. */ +export const GRID_MARKER_COLOR = '#4f8cff' // accent — an inactive marker +export const GRID_MARKER_ACTIVE_COLOR = '#ffb020' // gold — governs the playhead + /** - * Draw the beatgrid: beat lines extrapolated from the grid anchor at 60/bpm - * spacing, across the visible window [startSec, endSec]. Downbeats (every 4th - * beat from the anchor) are brighter; regular beats are hidden when too dense. + * Draw the beatgrid across the visible window [startSec, endSec]. + * + * The grid is a list of tempo segments, so beats are drawn per segment at that + * segment's own spacing, and downbeats restart at every marker. Marker lines go + * on top; the segment governing the playhead is tinted and its marker drawn in + * gold, so it is visible which marker the grid controls are acting on. */ export function drawBeatgrid( ctx: CanvasRenderingContext2D, - bpm: number, - gridAnchor: number, + grid: BeatGrid, startSec: number, endSec: number, w: number, h: number, dpr: number, + activeMarker: number, ): void { - if (bpm <= 0 || endSec <= startSec) return - const beat = 60 / bpm + if (endSec <= startSec) return const span = endSec - startSec - const beatPx = (beat / span) * w - const showBeats = beatPx >= 6 * dpr + const toX = (t: number) => Math.round(((t - startSec) / span) * w) const outline = Math.max(1, Math.round(dpr)) const beatW = Math.max(1, Math.round(dpr)) const barW = Math.max(2, Math.round(2 * dpr)) - let k = Math.ceil((startSec - gridAnchor) / beat) - for (;;) { - const bt = gridAnchor + k * beat - if (bt > endSec) break - const downbeat = ((k % 4) + 4) % 4 === 0 - k++ - if (bt < startSec) continue - if (!downbeat && !showBeats) continue - const x = Math.round(((bt - startSec) / span) * w) - const lw = downbeat ? barW : beatW - // Dark outline so the line reads on any waveform colour, then a bright line. + + // 1. Tint the active segment. Only meaningful on a flexible grid — on a + // constant one it would just wash the whole canvas for no information. + if (grid.count > 1) { + const seg = grid.segments[activeMarker] + if (seg && seg.start < endSec && seg.end > startSec) { + const x1 = toX(Math.max(seg.start, startSec)) + const x2 = toX(Math.min(seg.end, endSec)) + ctx.fillStyle = 'rgba(255,176,32,0.07)' + ctx.fillRect(x1, 0, Math.max(1, x2 - x1), h) + } + } + + // 2. Beat lines, per segment at its own spacing. Density culling is therefore + // per-segment too: a fast segment can cull while its slower neighbour does not. + for (const seg of grid.segmentsIn(startSec, endSec)) { + const beatPx = (seg.beatDur / span) * w + if (beatPx * BEATS_PER_BAR < 3 * dpr) continue // even bars are sub-pixel + const showBeats = beatPx >= 6 * dpr + let jFrom = Math.ceil((startSec - seg.start) / seg.beatDur) + // Only segment 0 extrapolates backwards; later segments start at their marker. + if (seg.index > 0) jFrom = Math.max(0, jFrom) + const jLimit = Math.floor((Math.min(endSec, seg.end) - seg.start) / seg.beatDur) + const jTo = Math.min(seg.beatCount - 1, jLimit) + for (let j = jFrom; j <= jTo; j++) { + const downbeat = ((j % BEATS_PER_BAR) + BEATS_PER_BAR) % BEATS_PER_BAR === 0 + if (!downbeat && !showBeats) continue + const bt = seg.start + j * seg.beatDur + if (bt < startSec || bt > endSec) continue + const x = toX(bt) + const lw = downbeat ? barW : beatW + // Dark outline so the line reads on any waveform colour, then a bright line. + ctx.fillStyle = 'rgba(0,0,0,0.6)' + ctx.fillRect(x - Math.floor(lw / 2) - outline, 0, lw + outline * 2, h) + ctx.fillStyle = downbeat ? 'rgba(255,255,255,0.95)' : 'rgba(255,255,255,0.65)' + ctx.fillRect(x - Math.floor(lw / 2), 0, lw, h) + } + } + + // 3. Marker lines on top, with a tab at the bottom edge (the top is already + // occupied by drawCues' hotcue flags). + for (const i of grid.markersIn(startSec, endSec)) { + const active = i === activeMarker + const color = active ? GRID_MARKER_ACTIVE_COLOR : GRID_MARKER_COLOR + const lw = Math.max(2, Math.round((active ? 3 : 2) * dpr)) + const x = toX(grid.markers[i].start) ctx.fillStyle = 'rgba(0,0,0,0.6)' ctx.fillRect(x - Math.floor(lw / 2) - outline, 0, lw + outline * 2, h) - ctx.fillStyle = downbeat ? 'rgba(255,255,255,0.95)' : 'rgba(255,255,255,0.65)' + ctx.fillStyle = color ctx.fillRect(x - Math.floor(lw / 2), 0, lw, h) + const tab = Math.round(7 * dpr) + ctx.beginPath() + ctx.moveTo(x, h - tab) + ctx.lineTo(x + tab, h) + ctx.lineTo(x - tab, h) + ctx.closePath() + ctx.fill() } } diff --git a/frontend/src/lib/trackColumns.tsx b/frontend/src/lib/trackColumns.tsx index 89a5fce..d3cfd8a 100644 --- a/frontend/src/lib/trackColumns.tsx +++ b/frontend/src/lib/trackColumns.tsx @@ -211,11 +211,19 @@ export const TRACK_COLUMNS: ColumnDef[] = [ size: 72, cell: (c) => { const n = c.getValue() - const grid = c.row.original.has_grid + const markers = c.row.original.grid_markers + // Gold marks a flexible (multi-tempo) grid, mint an ordinary constant one. return ( 0 ? 'text-text' : 'text-faint'}>{n} - {grid && ⊞} + {c.row.original.has_grid && ( + 1 ? 'text-[10px] text-gold' : 'text-[10px] text-mint'} + title={markers > 1 ? `Flexible beatgrid (${markers} markers)` : 'Beatgrid analyzed'} + > + ⊞ + + )} ) }, From 08c9b8121da1efff1c60d90fb46682adb9227dbb Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Thu, 17 Sep 2026 17:15:41 +0200 Subject: [PATCH 03/64] Refactored library system to support different libraries (adapters) --- backend/konduktor/adapters/__init__.py | 3 + .../konduktor/adapters/traktor/__init__.py | 1 + backend/konduktor/adapters/traktor/adapter.py | 283 +++++ .../konduktor/adapters/traktor/beatgrid.py | 117 ++ .../adapters/traktor/capabilities.py | 75 ++ .../konduktor/adapters/traktor/discovery.py | 62 + .../konduktor/adapters/traktor/locations.py | 71 ++ .../konduktor/adapters/traktor/projection.py | 105 ++ backend/konduktor/adapters/traktor/store.py | 992 ++++++++++++++++ backend/konduktor/auto_hotcues.py | 239 +--- backend/konduktor/beatgrid.py | 120 +- backend/konduktor/collection_service.py | 319 ------ backend/konduktor/core/__init__.py | 7 + backend/konduktor/core/adapter.py | 133 +++ backend/konduktor/core/audio_tags.py | 314 +++++ backend/konduktor/core/auto_hotcues.py | 236 ++++ backend/konduktor/core/capabilities.py | 81 ++ backend/konduktor/core/edit_journal.py | 170 +++ backend/konduktor/core/model.py | 157 +++ backend/konduktor/core/pathmap.py | 83 ++ backend/konduktor/core/query.py | 176 +++ backend/konduktor/discovery.py | 65 +- backend/konduktor/file_tags.py | 334 +----- backend/konduktor/main.py | 86 +- backend/konduktor/path_mapping.py | 133 +-- backend/konduktor/playlist_store.py | 1020 +---------------- backend/konduktor/schemas.py | 161 +-- backend/run_tests.sh | 2 +- backend/test_layering.py | 50 + backend/test_save_fidelity.py | 4 +- backend/test_traktor_adapter.py | 191 +++ 31 files changed, 3405 insertions(+), 2385 deletions(-) create mode 100644 backend/konduktor/adapters/__init__.py create mode 100644 backend/konduktor/adapters/traktor/__init__.py create mode 100644 backend/konduktor/adapters/traktor/adapter.py create mode 100644 backend/konduktor/adapters/traktor/beatgrid.py create mode 100644 backend/konduktor/adapters/traktor/capabilities.py create mode 100644 backend/konduktor/adapters/traktor/discovery.py create mode 100644 backend/konduktor/adapters/traktor/locations.py create mode 100644 backend/konduktor/adapters/traktor/projection.py create mode 100644 backend/konduktor/adapters/traktor/store.py delete mode 100644 backend/konduktor/collection_service.py create mode 100644 backend/konduktor/core/__init__.py create mode 100644 backend/konduktor/core/adapter.py create mode 100644 backend/konduktor/core/audio_tags.py create mode 100644 backend/konduktor/core/auto_hotcues.py create mode 100644 backend/konduktor/core/capabilities.py create mode 100644 backend/konduktor/core/edit_journal.py create mode 100644 backend/konduktor/core/model.py create mode 100644 backend/konduktor/core/pathmap.py create mode 100644 backend/konduktor/core/query.py create mode 100644 backend/test_layering.py create mode 100644 backend/test_traktor_adapter.py diff --git a/backend/konduktor/adapters/__init__.py b/backend/konduktor/adapters/__init__.py new file mode 100644 index 0000000..8c7d8a9 --- /dev/null +++ b/backend/konduktor/adapters/__init__.py @@ -0,0 +1,3 @@ +"""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. +""" diff --git a/backend/konduktor/adapters/traktor/__init__.py b/backend/konduktor/adapters/traktor/__init__.py new file mode 100644 index 0000000..1fb1975 --- /dev/null +++ b/backend/konduktor/adapters/traktor/__init__.py @@ -0,0 +1 @@ +"""The Traktor adapter: NML v20 (Traktor Pro 4) via ``traktor-nml-utils``.""" diff --git a/backend/konduktor/adapters/traktor/adapter.py b/backend/konduktor/adapters/traktor/adapter.py new file mode 100644 index 0000000..004751e --- /dev/null +++ b/backend/konduktor/adapters/traktor/adapter.py @@ -0,0 +1,283 @@ +"""The Traktor adapter: owns the native NML model and the generic projection. + +This is the object the app talks to. It holds: + + * a ``PlaylistStore`` — 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 ...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 . import capabilities as caps +from . import projection +from .store import PlaylistError, PlaylistStore + +# Generic cue vocabulary -> Traktor's CUE_V2 TYPE encoding. This table is the +# only place the integers exist outside the store; type 4 is a grid marker and +# is never a cue, so it has no generic name. +CUE_TYPE_TO_NATIVE = {"cue": 0, "fade_in": 1, "fade_out": 2, "load": 3, "loop": 5} + + +class TraktorAdapter: + platform = "traktor" + + def __init__(self, path: Path): + self.path = Path(path) + self._store = PlaylistStore(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) + + # ---- 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) + return projection.to_track_cues(entry) if entry is not None else None + + # ---- 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) -> PlaylistStore: + 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 capabilities(self) -> Capabilities: + return caps.capabilities_for(self.path, sorted(PlaylistStore.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 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) + + # ---- 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 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: + with _translate(): + self._store.place_hotcues(track_id, cues, 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 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) -> int: + with _translate(): + n = 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 n + + # ---- 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 diff --git a/backend/konduktor/adapters/traktor/beatgrid.py b/backend/konduktor/adapters/traktor/beatgrid.py new file mode 100644 index 0000000..070a2df --- /dev/null +++ b/backend/konduktor/adapters/traktor/beatgrid.py @@ -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 `` 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. + +`` 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 `` 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 `` + 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 `` 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 `` and falls back to `` 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()) diff --git a/backend/konduktor/adapters/traktor/capabilities.py b/backend/konduktor/adapters/traktor/capabilities.py new file mode 100644 index 0000000..f684c49 --- /dev/null +++ b/backend/konduktor/adapters/traktor/capabilities.py @@ -0,0 +1,75 @@ +"""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' 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), + cues=CueCapabilities( + hotcue_slots=8, + slot_labels="number", + # Traktor has no memory cues — every cue occupies a bank slot. + memory_cues=False, + types=CUE_TYPES, + color="free", + 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"], + 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, + ), + ) diff --git a/backend/konduktor/adapters/traktor/discovery.py b/backend/konduktor/adapters/traktor/discovery.py new file mode 100644 index 0000000..9c53270 --- /dev/null +++ b/backend/konduktor/adapters/traktor/discovery.py @@ -0,0 +1,62 @@ +"""Locate Traktor collections in their default install locations. + +Traktor stores each version's data under a versioned folder: + ~/Documents/Native Instruments/Traktor /collection.nml +This is the same relative path on macOS and Windows (both under the user's +Documents folder), so a single glob covers both. +""" +from __future__ import annotations + +import re +from pathlib import Path + +_VERSION_RE = re.compile(r"(\d+(?:\.\d+)*)") + + +def _traktor_root() -> Path: + return Path.home() / "Documents" / "Native Instruments" + + +def _version_key(version: str | None) -> tuple[int, ...]: + """Sortable tuple for a dotted version string; missing/odd → lowest.""" + if not version: + return (0,) + try: + return tuple(int(p) for p in version.split(".")) + except ValueError: + return (0,) + + +def describe(path: Path) -> dict: + """Build a candidate record for a collection.nml path. The label/version + come from the parent folder name (e.g. 'Traktor 4.5.0').""" + parent = path.parent.name + m = _VERSION_RE.search(parent) + exists = path.is_file() + return { + "path": str(path), + "label": parent or path.name, + "version": m.group(1) if m else None, + "modified": (path.stat().st_mtime if exists else None), + "exists": exists, + } + + +def detect_collections() -> list[dict]: + """All Traktor collection.nml files found in default locations, newest + Traktor version first (then most-recently-modified).""" + root = _traktor_root() + found: list[dict] = [] + if not root.is_dir(): + return found + for d in sorted(root.iterdir()): + if not d.is_dir() or not d.name.lower().startswith("traktor"): + continue + nml = d / "collection.nml" + if nml.is_file(): + found.append(describe(nml)) + found.sort( + key=lambda c: (_version_key(c["version"]), c["modified"] or 0.0), + reverse=True, + ) + return found diff --git a/backend/konduktor/adapters/traktor/locations.py b/backend/konduktor/adapters/traktor/locations.py new file mode 100644 index 0000000..e250f46 --- /dev/null +++ b/backend/konduktor/adapters/traktor/locations.py @@ -0,0 +1,71 @@ +"""Traktor LOCATION <-> OS path conversion. + +A Traktor ```` 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/. + """ + 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 diff --git a/backend/konduktor/adapters/traktor/projection.py b/backend/konduktor/adapters/traktor/projection.py new file mode 100644 index 0000000..c79e435 --- /dev/null +++ b/backend/konduktor/adapters/traktor/projection.py @@ -0,0 +1,105 @@ +"""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 + +from ...core.model import CuePoint, GridMarker, Track, TrackCues +from . import beatgrid + + +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 + cues = e.cue_v2 or [] + hotcues = sum( + 1 for c in cues if c.hotcue is not None and c.hotcue >= 0 + ) + markers = beatgrid.grid_markers(e) + 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=beatgrid.effective_bpm(e), + 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=bool(markers), + grid_markers=len(markers), + is_stem=getattr(e, "stems", None) is not None, + ) + + +def to_track_cues(entry) -> TrackCues: + """Project an ENTRY's beatgrid + cues. + + 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, and each is tagged with the marker it + belongs to so the UI can show it as beatgrid-owned rather than editable. + """ + markers = beatgrid.grid_markers(entry) + comps = beatgrid.companions(entry) + marker_of = {id(c): i for i, c in comps.items()} + grid_markers = [ + GridMarker( + start=(m.start or 0.0) / 1000.0, # Traktor stores START in 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 = [ + CuePoint( + name=c.name, + type=c.type if c.type is not None else 0, + start=(c.start or 0.0) / 1000.0, + length=(c.len or 0.0) / 1000.0, + hotcue=c.hotcue if c.hotcue is not None else -1, + color=c.color, + grid_marker=marker_of.get(id(c)), + ) + for c in (entry.cue_v2 or []) + if getattr(c, "grid", None) is None + ] + return TrackCues( + grid_markers=grid_markers, locked=bool(entry.lock), cues=cues + ) diff --git a/backend/konduktor/adapters/traktor/store.py b/backend/konduktor/adapters/traktor/store.py new file mode 100644 index 0000000..09a804d --- /dev/null +++ b/backend/konduktor/adapters/traktor/store.py @@ -0,0 +1,992 @@ +"""Editable playlist store backed by the traktor-nml-utils dataclass model. + +Design goals: + * minimal diff — unedited playlists must serialize byte-for-byte as Traktor + wrote them (the xsdata serializer used by the library reproduces Traktor's + exact formatting; lxml does not), + * surgical — only the objects actually edited differ in the output; the rest + of the ~14 MB file renders byte-identically, + * safe — every save is committed to the collection's version history (see + ``history.py``); the commit is additive and never alters the saved bytes. + +We edit the parsed dataclass model in memory and, on save, render the WHOLE +model through the library's own pipeline — proven byte-identical for unedited +content, so no splicing is needed. + +Playlists are identified by their stable UUID; folders by a synthetic path id +(``fld:/``). Smart playlists are read-only. +""" +from __future__ import annotations + +import threading +import uuid as uuidlib +from dataclasses import dataclass +from pathlib import Path + +from traktor_nml_utils import ( + TraktorCollection, + format_traktor_layout, + restore_traktor_float_format, +) +from traktor_nml_utils.models.collection import ( + Albumtype, + CueV2Type, + Entrytype, + GridType, + Infotype, + Nodetype, + Playlisttype, + Primarykeytype, + Subnodestype, + Tempotype, +) +from xsdata.formats.dataclass.serializers import XmlSerializer + +from ... import __version__, history +from ...core.edit_journal import EditJournal +from ...core.pathmap import common_dir_prefix +from ...core.pathmap import PathMapping +from ...schemas import PlaylistNode +from . import beatgrid +from .locations import os_path_to_location, resolve_path + +# Traktor's POPM frame owner: an ID3 rating is per-owner, so writing under +# this email is what makes the stars show up in Traktor itself. +TRAKTOR_POPM_EMAIL = "traktor@native-instruments.de" + + +class PlaylistError(Exception): + pass + + +@dataclass +class FileTagResult: + track_id: str + file: str + ok: bool + status: str # "written" | "file-not-found" | "unsupported-format" | "error" + detail: str = "" + + +@dataclass +class SaveOutcome: + commit: str | None # sha of the version-history commit (None if deduped/failed) + tag_results: list[FileTagResult] + + +class PlaylistStore: + def __init__(self, nml_path: Path): + self.nml_path = Path(nml_path) + self._lock = threading.RLock() + self.dirty = False + # Active OS-path prefix remapping (empty = identity). Survives _load(). + self._path_mapping = PathMapping() + self._load() + + # ---- load ---------------------------------------------------------- + def _load(self) -> None: + self._collection = TraktorCollection(path=self.nml_path) + self._nml = self._collection.nml + # Index collection entries by their Traktor primary key (volume+dir+file) + # so track-metadata edits can find their ENTRY in O(1). + self._entry_by_key: dict[str, Entrytype] = {} + for e in self._nml.collection.entry: + loc = e.location + if loc: + key = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}" + self._entry_by_key[key] = e + # Every edit this session, at field resolution: drives the file-tag sync, + # the version-history message, and (later) undo. + self._journal = EditJournal() + # track_id -> (image_bytes, mime) of staged replacement cover art + self._track_art: dict[str, tuple[bytes, str]] = {} + self.dirty = False + + def _note( + self, + category: str, + detail: str | None = None, + track_id: str | None = None, + target: str | None = None, + ) -> None: + """Record one command in the edit journal. + + `category` names the scope and `detail` the operation; playlists carry + their name as the target instead of a track id, and a remap carries its + count. `target` optionally names the field/slot/marker touched. + """ + if category.startswith("playlist-"): + self._journal.record("playlist", category.split("-", 1)[1], detail) + elif category == "remap": + self._journal.record("library", "remap", after=detail) + elif category == "hotcue": + self._journal.record("cue", detail or "modify", track_id, target) + else: + self._journal.record(category, detail or "edit", track_id, target) + + def _root(self) -> Nodetype: + node = self._nml.playlists.node if self._nml.playlists else None + if node is None: + raise PlaylistError("PLAYLISTS has no root NODE") + return node + + @staticmethod + def _children(node: Nodetype) -> list[Nodetype]: + return list(node.subnodes.node) if node.subnodes else [] + + # ---- tree walking -------------------------------------------------- + def tree(self) -> list[PlaylistNode]: + with self._lock: + return [self._to_model(c, []) for c in self._children(self._root())] + + def _to_model(self, node: Nodetype, parent_path: list[str]) -> PlaylistNode: + ntype = node.type or "FOLDER" + name = node.name or "(unnamed)" + if ntype == "PLAYLIST" or node.playlist is not None: + pl = node.playlist + keys = self._entry_keys_of(pl) if pl is not None else [] + return PlaylistNode( + id=pl.uuid if pl and pl.uuid else name, + name=name, + type="PLAYLIST", + uuid=pl.uuid if pl else None, + count=len(keys), + ) + if ntype == "SMARTLIST" or node.smartplaylist is not None: + return PlaylistNode( + id="sl:" + "/".join(parent_path + [name]), name=name, type="SMARTLIST" + ) + path = parent_path + [name] + return PlaylistNode( + id="fld:" + "/".join(path), + name=name, + type="FOLDER", + children=[self._to_model(c, path) for c in self._children(node)], + ) + + @staticmethod + def _entry_keys_of(pl: Playlisttype) -> list[str]: + return [ + e.primarykey.key + for e in (pl.entry or []) + if e.primarykey and e.primarykey.key + ] + + # ---- lookups ------------------------------------------------------- + def _iter_nodes(self, node: Nodetype): + yield node + for c in self._children(node): + yield from self._iter_nodes(c) + + def _find_playlist_node(self, playlist_uuid: str) -> Nodetype | None: + for n in self._iter_nodes(self._root()): + if n.playlist is not None and n.playlist.uuid == playlist_uuid: + return n + return None + + def _find_parent_of(self, target: Nodetype) -> Nodetype | None: + for n in self._iter_nodes(self._root()): + if n.subnodes and target in n.subnodes.node: + return n + return None + + def _find_folder(self, folder_id: str | None) -> Nodetype: + root = self._root() + if folder_id in (None, "", "fld:"): + return root + if not folder_id.startswith("fld:"): + raise PlaylistError(f"Not a folder id: {folder_id}") + cur = root + for name in folder_id[len("fld:") :].split("/"): + match = next( + ( + c + for c in self._children(cur) + if (c.type or "FOLDER") == "FOLDER" and c.name == name + ), + None, + ) + if match is None: + raise PlaylistError(f"Folder not found: {folder_id}") + cur = match + return cur + + def entry_keys(self, playlist_uuid: str) -> list[str] | None: + with self._lock: + node = self._find_playlist_node(playlist_uuid) + return None if node is None else self._entry_keys_of(node.playlist) + + # ---- edits --------------------------------------------------------- + def create_playlist(self, name: str, parent_id: str | None = None) -> str: + with self._lock: + folder = self._find_folder(parent_id) + if folder.subnodes is None: + folder.subnodes = Subnodestype(node=[], count=0) + new_uuid = uuidlib.uuid4().hex + node = Nodetype( + type="PLAYLIST", + name=name, + playlist=Playlisttype(entry=[], entries=0, type="LIST", uuid=new_uuid), + ) + folder.subnodes.node.append(node) + folder.subnodes.count = len(folder.subnodes.node) + self._note("playlist-create", name) + self.dirty = True + return new_uuid + + def rename_playlist(self, playlist_uuid: str, name: str) -> None: + with self._lock: + node = self._find_playlist_node(playlist_uuid) + if node is None: + raise PlaylistError(f"Playlist not found: {playlist_uuid}") + node.name = name + self._note("playlist-rename", name) + self.dirty = True + + def delete_playlist(self, playlist_uuid: str) -> None: + with self._lock: + node = self._find_playlist_node(playlist_uuid) + if node is None: + raise PlaylistError(f"Playlist not found: {playlist_uuid}") + parent = self._find_parent_of(node) + if parent is None: + raise PlaylistError("Cannot delete a top-level node") + parent.subnodes.node.remove(node) + parent.subnodes.count = len(parent.subnodes.node) + self._note("playlist-delete", node.name) + self.dirty = True + + def set_entries(self, playlist_uuid: str, entries: list[tuple[str, str]]) -> None: + with self._lock: + node = self._find_playlist_node(playlist_uuid) + if node is None: + raise PlaylistError(f"Playlist not found: {playlist_uuid}") + pl = node.playlist + pl.entry = [ + Entrytype(primarykey=Primarykeytype(type=ptype or "TRACK", key=key)) + for key, ptype in entries + ] + pl.entries = len(pl.entry) + self._note("playlist-entries", node.name) + self.dirty = True + + # ---- track metadata editing --------------------------------------- + # Safe, free-text-ish fields only. Deliberately NOT editable here: file path + # (it's the primary key), bpm/key (audio/grid territory), and read-only info + # like bitrate/playcount. + _INFO_FIELDS = {"genre", "label", "remixer", "producer", "comment", "mix", "release_date"} + EDITABLE_FIELDS = {"title", "artist", "album", "rating"} | _INFO_FIELDS + + def set_track_metadata(self, track_id: str, fields: dict) -> None: + with self._lock: + entry = self._entry_by_key.get(track_id) + if entry is None: + raise PlaylistError(f"Track not found: {track_id}") + if entry.info is None: + entry.info = Infotype() + for k, v in fields.items(): + if k in ("title", "artist"): + setattr(entry, k, v or None) + elif k == "album": + if entry.album is None: + entry.album = Albumtype() + entry.album.title = v or None + elif k in self._INFO_FIELDS: + setattr(entry.info, k, v or None) + elif k == "rating": + stars = max(0, min(5, int(v))) if v is not None else 0 + # Traktor RANKING = stars * 51; unrated has no RANKING attr. + entry.info.ranking = stars * 51 or None + else: + continue # unknown / read-only fields are ignored + self._journal.record("track", "set", track_id, k) + self.dirty = True + + def iter_entries(self): + """Every collection ENTRY in document order. + + Document order, not ``_entry_by_key.values()``: two entries can share a + primary key, and the dict would silently drop one of them. + """ + with self._lock: + return list(self._nml.collection.entry) + + def stem_keys(self) -> set[str]: + """Track ids whose ENTRY has a child. + + Playlist entries for these use ``PRIMARYKEY TYPE="STEM"`` (verified + 945/945 against the real collection); everything else uses ``TRACK``. + """ + with self._lock: + return { + f"{e.location.volume or ''}{e.location.dir or ''}{e.location.file or ''}" + for e in self._nml.collection.entry + if e.location and getattr(e, "stems", None) is not None + } + + def entries_for(self, track_ids: list[str]) -> list[tuple[str, str]]: + """Pair each known track id with its PRIMARYKEY TYPE, dropping unknowns.""" + stems = self.stem_keys() + with self._lock: + known = self._entry_by_key + return [ + (tid, "STEM" if tid in stems else "TRACK") + for tid in track_ids + if tid in known + ] + + def model_entry(self, track_id: str) -> Entrytype | None: + with self._lock: + return self._entry_by_key.get(track_id) + + # ---- hotcues ------------------------------------------------------ + # Creatable/editable types: 0 cue, 1 fade-in, 2 fade-out, 3 load, 5 loop. + # A loop (type 5) carries a length; the point types don't. Grid markers + # (type 4, redefine the beatgrid) are excluded. Cues are NML-only. + POINT_CUE_TYPES = {0, 1, 2, 3} # types the dropdown can switch between + CREATABLE_TYPES = {0, 1, 2, 3, 5} + + def _entry_or_raise(self, track_id: str) -> Entrytype: + entry = self._entry_by_key.get(track_id) + if entry is None: + raise PlaylistError(f"Track not found: {track_id}") + return entry + + @staticmethod + def _reject_if_companion(entry: Entrytype, slot: int) -> None: + """Refuse to touch a slot held by a grid marker's companion cue. + + Traktor pairs most grid markers with a white cue in a real hotcue slot. + Overwriting, retyping or deleting one desyncs it from its marker, so the + beatgrid commands own these slots — move or delete the marker instead. + """ + cue = next((c for c in (entry.cue_v2 or []) if c.hotcue == slot), None) + if cue is not None and beatgrid.is_companion(entry, cue): + raise PlaylistError( + f"Hotcue {slot + 1} belongs to a beatgrid marker — " + "move or delete the marker instead" + ) + + def set_hotcue( + self, + track_id: str, + slot: int, + start_sec: float, + cue_type: int, + length_sec: float = 0.0, + name: str | None = None, + ) -> None: + """Create (or reposition + retype) the hotcue in `slot` at `start_sec`. + + `length_sec` > 0 makes it a loop (used with cue_type 5). `name` sets the + cue label on create; when unset it falls back to Traktor's "n.n.".""" + if not 0 <= slot <= 7: + raise PlaylistError(f"Invalid hotcue slot: {slot}") + if cue_type not in self.CREATABLE_TYPES: + raise PlaylistError(f"Unsupported cue type: {cue_type}") + with self._lock: + entry = self._entry_or_raise(track_id) + self._reject_if_companion(entry, slot) + start_ms = max(0.0, start_sec * 1000.0) # Traktor stores START/LEN in ms + len_ms = max(0.0, length_sec * 1000.0) + existing = next( + (c for c in (entry.cue_v2 or []) if c.hotcue == slot), None + ) + if existing is not None: + existing.start = start_ms + existing.type = cue_type + existing.len = len_ms + else: + if entry.cue_v2 is None: + entry.cue_v2 = [] + entry.cue_v2.append( + CueV2Type( + name=name or "n.n.", # Traktor's default name for a manual cue + displ_order=0, + type=cue_type, + start=start_ms, + len=len_ms, + repeats=-1, + hotcue=slot, + color=None, + grid=None, + ) + ) + # "add" only when it's a genuinely new hotcue; repositioning/retyping + # an existing slot is a "modify" (keeps the net add/remove count honest). + self._note( + "hotcue", "modify" if existing is not None else "add", track_id, f"slot:{slot}" + ) + self.dirty = True + + def place_hotcues( + self, track_id: str, specs: list, *, overwrite: bool = False + ) -> None: + """Batch-create hotcues from `specs` (each has .slot/.start/.name and + optional .type/.length). With `overwrite` False (the default), slots that + already hold a hotcue are skipped so hand-placed cues are never clobbered. + Used by Auto Hotcues.""" + with self._lock: + entry = self._entry_or_raise(track_id) + occupied = { + c.hotcue for c in (entry.cue_v2 or []) if c.hotcue is not None and c.hotcue >= 0 + } + # Companion slots belong to the beatgrid — never fill them, even + # with overwrite=True (occupied alone only guards them while False). + protected = { + c.hotcue for c in beatgrid.companions(entry).values() if c.hotcue is not None + } + for spec in specs: + if spec.slot in protected or (not overwrite and spec.slot in occupied): + continue + self.set_hotcue( + track_id, + spec.slot, + spec.start, + getattr(spec, "type", 0), + getattr(spec, "length", 0.0), + name=getattr(spec, "name", None), + ) + + def set_hotcue_type(self, track_id: str, slot: int, cue_type: int) -> None: + """Change the type of the existing hotcue in `slot` (keeps its position).""" + if cue_type not in self.POINT_CUE_TYPES: + raise PlaylistError(f"Unsupported cue type: {cue_type}") + with self._lock: + entry = self._entry_or_raise(track_id) + self._reject_if_companion(entry, slot) + cue = next((c for c in (entry.cue_v2 or []) if c.hotcue == slot), None) + if cue is None: + raise PlaylistError(f"Hotcue {slot} is not set") + cue.type = cue_type + self._note("hotcue", "modify", track_id, f"slot:{slot}") + self.dirty = True + + def delete_hotcue(self, track_id: str, slot: int) -> None: + with self._lock: + entry = self._entry_or_raise(track_id) + self._reject_if_companion(entry, slot) + before = entry.cue_v2 or [] + entry.cue_v2 = [c for c in before if c.hotcue != slot] + if len(entry.cue_v2) != len(before): # only count an actual removal + self._note("hotcue", "delete", track_id, f"slot:{slot}") + self.dirty = True + + # ---- beatgrid ----------------------------------------------------- + # A beatgrid is an ORDERED LIST of markers (see beatgrid.py); a constant + # grid is a list of length one. Markers are addressed by their index in that + # start-ordered list. CUE_V2 has no id attribute and save() reparses the + # whole file, so any synthetic id would have to be rebuilt by position + # anyway — the index IS the identity. + _MARKER_MIN_GAP_MS = 1.0 + + @staticmethod + def _grid_marker(entry: Entrytype) -> CueV2Type | None: + """The first grid marker BY START — the one mirrors.""" + return beatgrid.first_marker(entry) + + @staticmethod + def _sync_tempo(entry: Entrytype) -> None: + """Mirror from the first marker (7968/7968 in the reference + collection). Called last by every grid mutator, so a move that changes + which marker is first re-mirrors for free. + + With no markers left, TEMPO is LEFT ALONE: Traktor keeps the analysed + BPM on gridless tracks (53 such entries exist in the reference file). + """ + marker = beatgrid.first_marker(entry) + if marker is None or marker.grid is None or not marker.grid.bpm: + return + if entry.tempo is None: + entry.tempo = Tempotype(bpm=marker.grid.bpm, bpm_quality=100.0) + else: + entry.tempo.bpm = marker.grid.bpm + + @staticmethod + def _sort_cues(entry: Entrytype) -> None: + """Keep CUE_V2 ascending by START — true for 8485/8485 reference + entries, so an inserted marker must not become the one exception. + Stable, so a marker stays ahead of a companion at an identical START. + """ + if entry.cue_v2: + entry.cue_v2.sort(key=lambda c: c.start or 0.0) + + def _markers_or_raise( + self, entry: Entrytype, index: int + ) -> tuple[list[CueV2Type], CueV2Type]: + markers = beatgrid.grid_markers(entry) + if not markers: + raise PlaylistError("Track has no beatgrid") + if not 0 <= index < len(markers): + raise PlaylistError( + f"Grid marker {index} out of range (track has {len(markers)})" + ) + return markers, markers[index] + + def _drop_grid(self, entry: Entrytype) -> None: + """Remove every marker AND every companion. No _note — callers do that.""" + doomed = {id(m) for m in beatgrid.grid_markers(entry)} + doomed |= {id(c) for c in beatgrid.companions(entry).values()} + entry.cue_v2 = [c for c in (entry.cue_v2 or []) if id(c) not in doomed] + + def add_grid_marker( + self, + track_id: str, + start_sec: float, + bpm: float | None = None, + name: str | None = None, + ) -> int: + """Add a beatgrid marker at `start_sec`; returns its index. + + With `bpm` unset the marker INHERITS the tempo of the section it lands + in, so splitting a section is musically a no-op until it's retempoed. + Creates no companion cue — Traktor tolerates markers without one, and + inventing them would silently consume the user's hotcue slots. + """ + if bpm is not None and bpm <= 0: + raise PlaylistError(f"BPM must be positive: {bpm}") + with self._lock: + entry = self._entry_or_raise(track_id) + start_ms = max(0.0, start_sec * 1000.0) + markers = beatgrid.grid_markers(entry) + for m in markers: + if abs((m.start or 0.0) - start_ms) < self._MARKER_MIN_GAP_MS: + raise PlaylistError("A grid marker already exists at that position") + if bpm is None: + bpm = self._bpm_governing(entry, start_ms) + if bpm is None: + raise PlaylistError("No BPM available to create a beatgrid") + if entry.cue_v2 is None: + entry.cue_v2 = [] + entry.cue_v2.append( + CueV2Type( + name=name or ("AutoGrid" if not markers else "n.n."), + displ_order=0, + type=4, + start=start_ms, + len=0.0, + repeats=-1, + hotcue=-1, + color=None, + grid=GridType(bpm=bpm), + ) + ) + self._sort_cues(entry) + self._sync_tempo(entry) + self._note("grid", "marker-add", track_id) + self.dirty = True + return next( + i + for i, m in enumerate(beatgrid.grid_markers(entry)) + if abs((m.start or 0.0) - start_ms) < 1e-9 + ) + + @staticmethod + def _bpm_governing(entry: Entrytype, start_ms: float) -> float | None: + """The tempo in force at `start_ms`: the last marker at or before it, + else the first marker (extrapolated backwards), else .""" + markers = beatgrid.grid_markers(entry) + if not markers: + return entry.tempo.bpm if entry.tempo else None + governing = markers[0] + for m in markers: + if (m.start or 0.0) <= start_ms: + governing = m + else: + break + return governing.grid.bpm if governing.grid else None + + def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> None: + """Move marker `index`, DRAGGING ITS COMPANION with it. + + The new position is CLAMPED between the neighbouring markers rather than + allowed to reorder them, so an index can never go stale mid-edit. Phase + nudges are +/-1 and +/-10 ms, so this is no practical constraint; + restructuring a grid is add-then-delete. + """ + with self._lock: + entry = self._entry_or_raise(track_id) + markers, marker = self._markers_or_raise(entry, index) + start_ms = max(0.0, start_sec * 1000.0) + if index > 0: + lo = (markers[index - 1].start or 0.0) + self._MARKER_MIN_GAP_MS + start_ms = max(start_ms, lo) + if index < len(markers) - 1: + hi = (markers[index + 1].start or 0.0) - self._MARKER_MIN_GAP_MS + start_ms = min(start_ms, hi) + companion = beatgrid.companions(entry).get(index) + marker.start = start_ms + if companion is not None: + # Copy the float — never recompute from seconds. A 1-ULP drift + # here would change the rendered bytes and break byte-reverts. + companion.start = marker.start + self._sync_tempo(entry) + self._note("grid", "marker-move", track_id, f"marker:{index}") + self.dirty = True + + def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> None: + """Set marker `index`'s tempo (governs until the next marker).""" + if bpm <= 0: + raise PlaylistError(f"BPM must be positive: {bpm}") + with self._lock: + entry = self._entry_or_raise(track_id) + _, marker = self._markers_or_raise(entry, index) + if marker.grid is None: + marker.grid = GridType(bpm=bpm) + else: + marker.grid.bpm = bpm + self._sync_tempo(entry) + self._note("grid", "marker-bpm", track_id, f"marker:{index}") + self.dirty = True + + def delete_grid_marker(self, track_id: str, index: int) -> None: + """Remove marker `index` and its companion (freeing that hotcue slot).""" + with self._lock: + entry = self._entry_or_raise(track_id) + markers, marker = self._markers_or_raise(entry, index) + companion = beatgrid.companions(entry).get(index) + doomed = {id(marker)} | ({id(companion)} if companion is not None else set()) + entry.cue_v2 = [c for c in (entry.cue_v2 or []) if id(c) not in doomed] + self._sync_tempo(entry) + # Removing the last marker IS deleting the grid — report it as one. + self._note( + "grid", + "delete" if len(markers) == 1 else "marker-delete", + track_id, + f"marker:{index}", + ) + self.dirty = True + + def replace_grid( + self, track_id: str, markers: list[tuple[float, float]] + ) -> None: + """Throw the grid away and rebuild it from `markers` [(start_sec, bpm)]. + + Serves both Auto Grid (a single marker) and the deck's Reset (restore + the list as loaded) as one atomic, single-event command. Companions of + the old grid go with it; none are created. + """ + for start_sec, bpm in markers: + if bpm <= 0: + raise PlaylistError(f"BPM must be positive: {bpm}") + with self._lock: + entry = self._entry_or_raise(track_id) + self._drop_grid(entry) + if entry.cue_v2 is None: + entry.cue_v2 = [] + for i, (start_sec, bpm) in enumerate( + sorted(markers, key=lambda m: m[0]) + ): + entry.cue_v2.append( + CueV2Type( + name="AutoGrid" if i == 0 else "n.n.", + displ_order=0, + type=4, + start=max(0.0, start_sec * 1000.0), + len=0.0, + repeats=-1, + hotcue=-1, + color=None, + grid=GridType(bpm=bpm), + ) + ) + self._sort_cues(entry) + self._sync_tempo(entry) + self._note("grid", "replace", track_id) + self.dirty = True + + def place_grid_companion( + self, track_id: str, index: int, *, prefer_slot: int = 0 + ) -> int | None: + """Give marker `index` the white beat-1 hotcue Traktor writes beside its + own markers: `prefer_slot` when free, else the lowest free slot. + + Returns the slot used, or None when the bank is full or the marker + already has a companion. NEVER overwrites. This is the ONLY place + Konduktor creates a companion — grid edits never do — because it is a + deliberate, user-invoked feature (Auto Grid), not a side effect. + """ + with self._lock: + entry = self._entry_or_raise(track_id) + _, marker = self._markers_or_raise(entry, index) + if index in beatgrid.companions(entry): + return None + used = { + c.hotcue + for c in (entry.cue_v2 or []) + if c.hotcue is not None and c.hotcue >= 0 + } + slot = next( + (s for s in [prefer_slot, *range(8)] if 0 <= s <= 7 and s not in used), + None, + ) + if slot is None: + return None + entry.cue_v2.append( + CueV2Type( + name=marker.name or "AutoGrid", + displ_order=0, + type=0, + start=marker.start, # copy the float, not start_sec * 1000 + len=0.0, + repeats=-1, + hotcue=slot, + color=beatgrid.COMPANION_COLOR, + grid=None, + ) + ) + self._sort_cues(entry) + self._note("grid", "marker-add", track_id) + self.dirty = True + return slot + + def delete_grid(self, track_id: str) -> None: + """Remove EVERY grid marker AND EVERY companion; is kept. + + Dropping companions is the debris fix: the old code stripped markers + only, leaving orphan white cues squatting in hotcue slots. + """ + with self._lock: + entry = self._entry_or_raise(track_id) + self._drop_grid(entry) + self._note("grid", "delete", track_id) + self.dirty = True + + def set_lock(self, track_id: str, locked: bool) -> None: + with self._lock: + entry = self._entry_or_raise(track_id) + entry.lock = 1 if locked else None + self._note("lock", "on" if locked else "off", track_id) + self.dirty = True + + # ---- cover art ----------------------------------------------------- + def set_track_art(self, track_id: str, data: bytes, mime: str) -> None: + with self._lock: + if track_id not in self._entry_by_key: + raise PlaylistError(f"Track not found: {track_id}") + self._track_art[track_id] = (data, mime) + self.dirty = True + + def set_path_mapping(self, mapping: PathMapping) -> None: + """Set the active OS-path prefix remapping (applied at resolve time).""" + with self._lock: + self._path_mapping = mapping + + def _resolve(self, loc) -> "Path | None": + """Resolve a LOCATION to an OS path, applying the active path mapping. + + The single FS chokepoint: LOCATION -> `resolve_path` -> prefix remap. + Falls back to the un-remapped path when the remapped target doesn't + exist, so a misconfigured mapping never makes a present file unreachable. + """ + + if loc is None: + return None + base = resolve_path(loc.volume, loc.dir, loc.file) + if self._path_mapping.empty: + return base + remapped = self._path_mapping.apply(base) + if remapped == base: + return base + return remapped if remapped.exists() else base + + def cover_art(self, track_id: str) -> tuple[bytes, str] | None: + """Staged replacement if present, else the file's current embedded art.""" + from ...core import audio_tags as file_tags + + with self._lock: + if track_id in self._track_art: + return self._track_art[track_id] + entry = self._entry_by_key.get(track_id) + if entry is None or entry.location is None: + return None + path = self._resolve(entry.location) + return file_tags.read_cover(path) if path else None + + def audio_path(self, track_id: str) -> "Path | None": + """Resolve a track's audio file to an OS path (for playback streaming).""" + with self._lock: + entry = self._entry_by_key.get(track_id) + if entry is None or entry.location is None: + return None + return self._resolve(entry.location) + + def path_prefix_suggestions(self) -> dict: + """Auto-suggest ``from`` prefixes by resolving every track's LOCATION and + finding the common directory prefix per volume. Returns a ``primary`` + (the largest group's prefix) plus per-group prefixes ranked by track + count, so the editor can prefill and offer alternatives.""" + from collections import defaultdict + + + with self._lock: + groups: dict[str, list[str]] = defaultdict(list) + for e in self._nml.collection.entry: + loc = e.location + if not loc: + continue + groups[loc.volume or ""].append( + str(resolve_path(loc.volume, loc.dir, loc.file)) + ) + ranked = sorted( + ( + {"prefix": common_dir_prefix(paths), "count": len(paths)} + for paths in groups.values() + ), + key=lambda g: g["count"], + reverse=True, + ) + ranked = [g for g in ranked if g["prefix"]] + return {"primary": ranked[0]["prefix"] if ranked else "", "groups": ranked[:5]} + + def remap_preview(self, mapping: PathMapping) -> dict: + """How a mapping would affect the collection, without changing anything: + total tracks, how many match ``from``, and how many exist at ``to`` + (plus a few samples). Powers the mapping editor's validation line.""" + + with self._lock: + total = matched = existing = 0 + samples: list[dict] = [] + for e in self._nml.collection.entry: + loc = e.location + if not loc: + continue + total += 1 + base = resolve_path(loc.volume, loc.dir, loc.file) + if mapping.matches(base): + matched += 1 + target = mapping.apply(base) + ok = target.exists() + if ok: + existing += 1 + if len(samples) < 5: + samples.append({"from": str(base), "to": str(target), "exists": ok}) + return {"total": total, "matched": matched, "existing": existing, "samples": samples} + + def remap_locations(self, mapping: PathMapping) -> int: + """Permanently rewrite matching track LOCATIONs to the mapping's ``to`` + prefix — a deliberate library move (write-back). + + Because ``track_id`` IS the LOCATION key (``volume+dir+file``), every + playlist ``PRIMARYKEY`` that referenced a moved track is rewritten too, + so playlists keep pointing at their tracks. Non-matching entries are + untouched. Returns the number of tracks rewritten; the caller saves. + """ + + if mapping.empty: + return 0 + with self._lock: + key_remap: dict[str, str] = {} + for e in self._nml.collection.entry: + loc = e.location + if not loc: + continue + base = resolve_path(loc.volume, loc.dir, loc.file) + if not mapping.matches(base): + continue + target = mapping.apply(base) + volume, dir_, file = os_path_to_location(target) + old_key = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}" + new_key = f"{volume or ''}{dir_ or ''}{file or ''}" + if old_key == new_key: + continue # no-op (e.g. from == to); leave byte-identical + loc.volume, loc.dir, loc.file = volume, dir_, file + key_remap[old_key] = new_key + if not key_remap: + return 0 + # Rewrite playlist entry primary keys that referenced moved tracks. + for node in self._iter_nodes(self._root()): + pl = node.playlist + if pl is None or not pl.entry: + continue + for entry in pl.entry: + pk = entry.primarykey + if pk and pk.key in key_remap: + pk.key = key_remap[pk.key] + # Track ids derive from the LOCATION, so a remap renames them. Carry + # this session's journal entries across or their file-tag sync is lost. + for old_key, new_key in key_remap.items(): + self._journal.retarget(old_key, new_key) + self._note("remap", str(len(key_remap))) + self.dirty = True + return len(key_remap) + + def _entry_field_value(self, entry: Entrytype, field: str): + """Read a single editable field's current value from the model, in the + shape file_tags expects (rating as 0–5 stars).""" + if field == "title": + return entry.title + if field == "artist": + return entry.artist + if field == "album": + return entry.album.title if entry.album else None + if field == "rating": + r = entry.info.ranking if entry.info else None + return round(r / 51) if r else 0 + return getattr(entry.info, field, None) if entry.info else None + + def count_playlists(self) -> int: + with self._lock: + return sum(1 for n in self._iter_nodes(self._root()) if n.playlist is not None) + + # ---- persistence --------------------------------------------------- + def save(self) -> "SaveOutcome": + with self._lock: + new_data = self._render() + tmp = self.nml_path.with_suffix(self.nml_path.suffix + ".tmp") + tmp.write_bytes(new_data) + tmp.replace(self.nml_path) + # Best-effort: sync the edited fields into each edited track's file. + tag_results = self._sync_file_tags() + # Version history: commit the saved bytes (additive — never touches the + # file we just wrote). Summary is computed before _load() clears state. + commit = history.commit(self.nml_path, new_data, self._edit_summary(), __version__) + self._load() # clears dirty + the edit journal + staged art + return SaveOutcome(commit=commit, tag_results=tag_results) + + def _edit_summary(self) -> str: + """Delegates to the journal; kept as a method because save() and the + tests reach for it by this name.""" + return self._journal.summary(extra_tracks=set(self._track_art)) + + def _sync_file_tags(self) -> list["FileTagResult"]: + from ...core import audio_tags as file_tags + + results: list[FileTagResult] = [] + # Union of tracks with edited fields and/or replaced art. + for track_id in self._journal.edited_tracks() | self._track_art.keys(): + entry = self._entry_by_key.get(track_id) + if entry is None or entry.location is None: + continue + path = self._resolve(entry.location) + if path is None: + continue + # Report BOTH writes: a failed tag write must not be masked by a + # successful art write on the same track. + written = [] + if fields := self._journal.fields_for(track_id): + meta = {f: self._entry_field_value(entry, f) for f in fields} + written.append(file_tags.write_tags(path, meta, popm_email=TRAKTOR_POPM_EMAIL)) + if track_id in self._track_art: + data, mime = self._track_art[track_id] + written.append(file_tags.write_cover(path, data, mime)) + for r in written: + results.append( + FileTagResult( + track_id=track_id, file=str(path), ok=r.ok, status=r.status, detail=r.detail + ) + ) + return results + + def _render(self) -> bytes: + """Render the whole model exactly as the library's save() does. + + The two post-processing steps restore Traktor's precise layout (expanded + empty tags, 6-decimal floats, newlines), so a no-op render reproduces the + file byte-for-byte and only the objects we actually edited (playlists + AND/OR track entries) diff. Verified by backend/test_save_fidelity.py. + """ + s = XmlSerializer().render(self._nml) + s = restore_traktor_float_format(s, self._nml) + s = format_traktor_layout(s) + return s.encode("utf-8") diff --git a/backend/konduktor/auto_hotcues.py b/backend/konduktor/auto_hotcues.py index 46e0f5d..cf23e33 100644 --- a/backend/konduktor/auto_hotcues.py +++ b/backend/konduktor/auto_hotcues.py @@ -1,236 +1,11 @@ -"""Auto Hotcues — structural boundary detection for DJ cue placement. +"""Compatibility shim — this module moved to ``konduktor.core.auto_hotcues``. -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. +Kept so the existing test suite keeps importing the old path unchanged while the +adapter refactor lands; removed in the final cleanup step. Replacing the entry in +``sys.modules`` makes this module *be* the new one, so private names resolve too. """ +import sys -from __future__ import annotations +from .core import auto_hotcues as _moved -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 _segment_for(t: float, markers: list[tuple[float, float]]) -> tuple[float, float]: - """The ``(start, bpm)`` of the beatgrid segment containing ``t``. - - Times before the first marker use the first segment, extrapolated backwards - — the same convention the deck draws with. - """ - seg = markers[0] - for m in markers: - if m[0] <= t: - seg = m - else: - break - return seg - - -def snap_to_phrase( - t: float, markers: list[tuple[float, float]], phrase_bars: int = 16 -) -> float: - """Snap ``t`` to the nearest phrase boundary OF ITS OWN SEGMENT. - - Snapping is deliberately segment-local rather than a running phrase count - across the whole track: a flexible grid exists precisely because the tempo - drifted, so carrying a phrase count across a marker seam would propagate the - very error the marker was placed to correct. With a single marker this is - exactly the old ``anchor + round((t - anchor) / phrase) * phrase``. - """ - anchor, bpm = _segment_for(t, markers) - phrase = phrase_bars * 4 * (60.0 / bpm) - return anchor + round((t - anchor) / phrase) * phrase - - -def select_hotcues( - boundaries: list[tuple[float, float]], - *, - markers: list[tuple[float, 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. - - ``markers`` is the beatgrid as ``[(start_sec, bpm), ...]`` ordered by start — - a constant-tempo track is simply a one-element list. - - Snaps each boundary to the nearest ``phrase_bars``-bar grid point of its own - tempo segment (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 not markers or markers[0][1] <= 0: - return [] - - # Tolerance for "same place as an existing cue" and the end clamp. Marker - # BPMs differ by well under 1% in practice, so the first is representative. - beat = 60.0 / markers[0][1] - - # Snap to phrase grid; dedupe (keep the strongest energy seen at each point). - snapped: dict[float, float] = {} - for t, energy in boundaries: - p = snap_to_phrase(t, markers, phrase_bars) - 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 +sys.modules[__name__] = _moved diff --git a/backend/konduktor/beatgrid.py b/backend/konduktor/beatgrid.py index 070a2df..3d53c56 100644 --- a/backend/konduktor/beatgrid.py +++ b/backend/konduktor/beatgrid.py @@ -1,117 +1,11 @@ -"""The beatgrid model: an ORDERED LIST of grid markers. +"""Compatibility shim — this module moved to ``konduktor.adapters.traktor.beatgrid``. -A Traktor beatgrid is not "a BPM and an anchor" — it is a list of `CUE_V2 -TYPE="4"` markers, each carrying its own `` 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. - -`` 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 `` 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. +Kept so the existing test suite keeps importing the old path unchanged while the +adapter refactor lands; removed in the final cleanup step. Replacing the entry in +``sys.modules`` makes this module *be* the new one, so private names resolve too. """ -from __future__ import annotations +import sys -from traktor_nml_utils.models.collection import CueV2Type, Entrytype +from .adapters.traktor import beatgrid as _moved -# 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 `` - 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 `` 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 `` and falls back to `` 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()) +sys.modules[__name__] = _moved diff --git a/backend/konduktor/collection_service.py b/backend/konduktor/collection_service.py deleted file mode 100644 index 1491a89..0000000 --- a/backend/konduktor/collection_service.py +++ /dev/null @@ -1,319 +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 . import beatgrid - -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 - ) - markers = beatgrid.grid_markers(e) - 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=beatgrid.effective_bpm(e), - 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=bool(markers), - grid_markers=len(markers), - 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 diff --git a/backend/konduktor/core/__init__.py b/backend/konduktor/core/__init__.py new file mode 100644 index 0000000..2dad5af --- /dev/null +++ b/backend/konduktor/core/__init__.py @@ -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. +""" diff --git a/backend/konduktor/core/adapter.py b/backend/konduktor/core/adapter.py new file mode 100644 index 0000000..1b2e679 --- /dev/null +++ b/backend/konduktor/core/adapter.py @@ -0,0 +1,133 @@ +"""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 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 + + +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 ------------------------------------------------- + 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: ... + 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: 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: ... + 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: ... + def path_prefix_suggestions(self) -> dict: ... + def remap_preview(self, mapping: PathMapping) -> dict: ... + def remap_locations(self, mapping: PathMapping) -> int: ... + + # ---- 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, ...] + + def can_open(self, path: Path) -> bool: ... + def open(self, path: Path) -> LibraryAdapter: ... + def detect(self) -> list: ... + def describe(self, path: Path) -> object: ... diff --git a/backend/konduktor/core/audio_tags.py b/backend/konduktor/core/audio_tags.py new file mode 100644 index 0000000..bee8dc5 --- /dev/null +++ b/backend/konduktor/core/audio_tags.py @@ -0,0 +1,314 @@ +"""Write track metadata into audio files' embedded tags (best-effort). + +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 +that rather than failing the whole save. + +Field writes are frame/atom-level, so unrelated tags (cover art, beatgrid BPM, +key, track number, private frames) are preserved — verified against real files. +""" +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path + +# 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 + + +@dataclass +class TagResult: + ok: bool + status: str # "written" | "file-not-found" | "unsupported-format" | "error" + detail: str = "" + + +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(): + return None + ext = path.suffix.lower() + try: + if ext in (".mp3", ".aif", ".aiff"): + from mutagen.id3 import ID3, ID3NoHeaderError + + try: + id3 = ID3(path) + except ID3NoHeaderError: + return None + apics = id3.getall("APIC") + if not apics: + return None + front = next((a for a in apics if a.type == 3), apics[0]) + return bytes(front.data), (front.mime or "image/jpeg") + if ext in (".m4a", ".mp4"): + from mutagen.mp4 import MP4 + + covr = MP4(path).tags.get("covr") if MP4(path).tags else None + if not covr: + return None + c = covr[0] + from mutagen.mp4 import MP4Cover + + mime = "image/png" if c.imageformat == MP4Cover.FORMAT_PNG else "image/jpeg" + return bytes(c), mime + if ext == ".flac": + from mutagen.flac import FLAC + + pics = FLAC(path).pictures + if not pics: + return None + front = next((p for p in pics if p.type == 3), pics[0]) + return bytes(front.data), (front.mime or "image/jpeg") + except Exception: # noqa: BLE001 + return None + return None + + +def write_cover(path: Path, data: bytes, mime: str) -> TagResult: + """Replace the file's embedded front cover art. Best-effort.""" + if not path.exists(): + return TagResult(False, "file-not-found", str(path)) + ext = path.suffix.lower() + mime = mime if mime in ("image/jpeg", "image/png") else "image/jpeg" + try: + if ext in (".mp3", ".aif", ".aiff"): + from mutagen.id3 import APIC + + if ext == ".mp3": + from mutagen.id3 import ID3, ID3NoHeaderError + + try: + tags = ID3(path) + except ID3NoHeaderError: + tags = ID3() + tags.delall("APIC") + tags.add(APIC(encoding=3, mime=mime, type=3, desc="", data=data)) + tags.save(path) + else: + from mutagen.aiff import AIFF + + audio = AIFF(path) + if audio.tags is None: + audio.add_tags() + audio.tags.delall("APIC") + audio.tags.add(APIC(encoding=3, mime=mime, type=3, desc="", data=data)) + audio.save() + elif ext in (".m4a", ".mp4"): + from mutagen.mp4 import MP4, MP4Cover + + audio = MP4(path) + if audio.tags is None: + audio.add_tags() + fmt = MP4Cover.FORMAT_PNG if mime == "image/png" else MP4Cover.FORMAT_JPEG + audio.tags["covr"] = [MP4Cover(data, imageformat=fmt)] + audio.save() + elif ext == ".flac": + from mutagen.flac import FLAC, Picture + + audio = FLAC(path) + audio.clear_pictures() + pic = Picture() + pic.type = 3 + pic.mime = mime + pic.data = data + audio.add_picture(pic) + audio.save() + else: + return TagResult(False, "unsupported-format", ext) + except Exception as ex: # noqa: BLE001 + return TagResult(False, "error", f"{type(ex).__name__}: {ex}") + return TagResult(True, "written") + + +def _clean(v) -> str | None: + if v is None: + return None + s = str(v).strip() + return s or None + + +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, popm_email=popm_email) + elif ext in (".aif", ".aiff"): + _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": + _write_flac(path, meta) + else: + # WAV and anything else: tag support is weak/inconsistent — skip. + return TagResult(False, "unsupported-format", ext) + except Exception as ex: # noqa: BLE001 — best-effort; report, don't crash save + return TagResult(False, "error", f"{type(ex).__name__}: {ex}") + return TagResult(True, "written") + + +# ---- ID3 (mp3 / aiff) -------------------------------------------------- +def _apply_id3(id3, meta: TagMeta, popm_email: str = DEFAULT_POPM_EMAIL) -> None: + from mutagen.id3 import ( + COMM, + POPM, + TALB, + TCON, + TDRC, + TIT2, + TIT3, + TPE1, + TPE4, + TPUB, + TXXX, + ) + + simple = { + "title": TIT2, + "artist": TPE1, + "album": TALB, + "genre": TCON, + "label": TPUB, + "remixer": TPE4, + "mix": TIT3, + "release_date": TDRC, + } + for field, frame in simple.items(): + if field in meta: + val = _clean(meta[field]) + id3.delall(frame.__name__) + if val is not None: + id3.add(frame(encoding=3, text=[val])) + if "producer" in meta: + id3.delall("TXXX:PRODUCER") + val = _clean(meta["producer"]) + if val is not None: + id3.add(TXXX(encoding=3, desc="PRODUCER", text=[val])) + if "comment" in meta: + id3.delall("COMM") + val = _clean(meta["comment"]) + if val is not None: + id3.add(COMM(encoding=3, lang="eng", desc="", text=[val])) + if "rating" in meta: + id3.delall("POPM") + stars = int(meta["rating"] or 0) + if stars > 0: + id3.add( + POPM( + email=popm_email, + rating=max(0, min(5, stars)) * 51, + count=0, + ) + ) + + +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, popm_email) + id3.save(path) + + +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, popm_email) + audio.save() + + +# ---- MP4 (m4a / stem) -------------------------------------------------- +def _write_mp4(path: Path, meta: TagMeta) -> None: + from mutagen.mp4 import MP4, MP4FreeForm + + audio = MP4(path) + if audio.tags is None: + audio.add_tags() + t = audio.tags + standard = { + "title": "\xa9nam", + "artist": "\xa9ART", + "album": "\xa9alb", + "genre": "\xa9gen", + "comment": "\xa9cmt", + "release_date": "\xa9day", + } + for field, atom in standard.items(): + if field in meta: + val = _clean(meta[field]) + if val is None: + t.pop(atom, None) + else: + t[atom] = [val] + # No standard MP4 atoms for these — use iTunes-style freeform atoms. + freeform = {"label": "LABEL", "remixer": "REMIXER", "producer": "PRODUCER", "mix": "MIX"} + for field, name in freeform.items(): + if field in meta: + key = f"----:com.apple.iTunes:{name}" + val = _clean(meta[field]) + if val is None: + t.pop(key, None) + else: + t[key] = [MP4FreeForm(val.encode("utf-8"))] + if "rating" in meta: + key = "----:com.apple.iTunes:RATING" + stars = int(meta["rating"] or 0) + if stars > 0: + t[key] = [MP4FreeForm(str(max(0, min(5, stars)) * 51).encode("utf-8"))] + else: + t.pop(key, None) + audio.save() + + +# ---- FLAC -------------------------------------------------------------- +def _write_flac(path: Path, meta: TagMeta) -> None: + from mutagen.flac import FLAC + + audio = FLAC(path) + mapping = { + "title": "title", + "artist": "artist", + "album": "album", + "genre": "genre", + "label": "label", + "remixer": "remixer", + "producer": "producer", + "comment": "comment", + "mix": "mixname", + "release_date": "date", + } + for field, vc in mapping.items(): + if field in meta: + val = _clean(meta[field]) + if val is None: + audio.pop(vc, None) + else: + audio[vc] = [val] + if "rating" in meta: + stars = int(meta["rating"] or 0) + if stars > 0: + audio["rating"] = [str(max(0, min(5, stars)) * 51)] + else: + audio.pop("rating", None) + audio.save() diff --git a/backend/konduktor/core/auto_hotcues.py b/backend/konduktor/core/auto_hotcues.py new file mode 100644 index 0000000..46e0f5d --- /dev/null +++ b/backend/konduktor/core/auto_hotcues.py @@ -0,0 +1,236 @@ +"""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 _segment_for(t: float, markers: list[tuple[float, float]]) -> tuple[float, float]: + """The ``(start, bpm)`` of the beatgrid segment containing ``t``. + + Times before the first marker use the first segment, extrapolated backwards + — the same convention the deck draws with. + """ + seg = markers[0] + for m in markers: + if m[0] <= t: + seg = m + else: + break + return seg + + +def snap_to_phrase( + t: float, markers: list[tuple[float, float]], phrase_bars: int = 16 +) -> float: + """Snap ``t`` to the nearest phrase boundary OF ITS OWN SEGMENT. + + Snapping is deliberately segment-local rather than a running phrase count + across the whole track: a flexible grid exists precisely because the tempo + drifted, so carrying a phrase count across a marker seam would propagate the + very error the marker was placed to correct. With a single marker this is + exactly the old ``anchor + round((t - anchor) / phrase) * phrase``. + """ + anchor, bpm = _segment_for(t, markers) + phrase = phrase_bars * 4 * (60.0 / bpm) + return anchor + round((t - anchor) / phrase) * phrase + + +def select_hotcues( + boundaries: list[tuple[float, float]], + *, + markers: list[tuple[float, 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. + + ``markers`` is the beatgrid as ``[(start_sec, bpm), ...]`` ordered by start — + a constant-tempo track is simply a one-element list. + + Snaps each boundary to the nearest ``phrase_bars``-bar grid point of its own + tempo segment (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 not markers or markers[0][1] <= 0: + return [] + + # Tolerance for "same place as an existing cue" and the end clamp. Marker + # BPMs differ by well under 1% in practice, so the first is representative. + beat = 60.0 / markers[0][1] + + # Snap to phrase grid; dedupe (keep the strongest energy seen at each point). + snapped: dict[float, float] = {} + for t, energy in boundaries: + p = snap_to_phrase(t, markers, phrase_bars) + 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 diff --git a/backend/konduktor/core/capabilities.py b/backend/konduktor/core/capabilities.py new file mode 100644 index 0000000..a0f7485 --- /dev/null +++ b/backend/konduktor/core/capabilities.py @@ -0,0 +1,81 @@ +"""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 + +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): + 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"] + 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 + cues: CueCapabilities = CueCapabilities() + grid: GridCapabilities = GridCapabilities() + tracks: TrackCapabilities = TrackCapabilities() + playlists: PlaylistCapabilities = PlaylistCapabilities() + save: SaveCapabilities diff --git a/backend/konduktor/core/edit_journal.py b/backend/konduktor/core/edit_journal.py new file mode 100644 index 0000000..8a63795 --- /dev/null +++ b/backend/konduktor/core/edit_journal.py @@ -0,0 +1,170 @@ +"""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.""" + return {c.target for c in self.changes if c.scope == "track" 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.""" + if old_id == new_id: + return + for i, c in enumerate(self.changes): + if c.target == old_id and c.scope in ("track", "cue", "grid", "lock"): + self.changes[i] = Change(c.scope, c.op, new_id, 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'}" + + # --- 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) + for op, verb in ( + ("create", "created"), + ("rename", "renamed"), + ("delete", "deleted"), + ("entries", "reordered"), + ): + 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} playlist{'' if len(names) == 1 else 's'} {joined}") + else: + parts.append(f"{verb} {len(names)} playlists") + + # --- 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:] diff --git a/backend/konduktor/core/model.py b/backend/konduktor/core/model.py new file mode 100644 index 0000000..5eba549 --- /dev/null +++ b/backend/konduktor/core/model.py @@ -0,0 +1,157 @@ +"""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 pydantic import BaseModel, ConfigDict, Field + + +class Track(BaseModel): + """A single track, flattened from a Traktor collection ENTRY.""" + + id: str # primary key: "", used to join playlist entries + 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 + bpm: float | None = None + key: str | None = None # Traktor display key, e.g. "10m" + rating: int = 0 # 0-5 stars (derived from RANKING/51) + playcount: int | None = None + length: int | None = None # seconds + bitrate: int | None = None + 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 + has_grid: bool = False + grid_markers: int = 0 # >1 = a flexible (multi-tempo) beatgrid + is_stem: bool = False # a Stem file ( child) vs a normal audio track + + +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 — either a FOLDER or a PLAYLIST/SMARTLIST.""" + + id: str # stable synthetic id ("pl-" / "fld-") + name: str + type: str # "FOLDER" | "PLAYLIST" | "SMARTLIST" + uuid: str | None = None + count: int = 0 # track count (for playlists) + children: list["PlaylistNode"] = [] + + +PlaylistNode.model_rebuild() + + +# ---- write request bodies ---- + + +class CuePoint(BaseModel): + name: str | None = None + type: int # Traktor: 0 cue, 1 fade-in, 2 fade-out, 3 load, 4 grid, 5 loop + start: float # seconds + length: float # seconds (>0 for loops) + hotcue: int # -1 if not assigned to a hotcue slot + color: str | None = None # "#RRGGBB" if set + # Index of the grid marker this cue is the companion of, if any. Such a cue + # holds a real hotcue slot but belongs to the beatgrid and is not editable. + 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] = [] + locked: bool = False # Traktor LOCK flag + cues: list[CuePoint] = [] # cue/loop markers (grid markers themselves excluded) + + +class AutoHotcue(BaseModel): + slot: int # 0–7 + start: float # seconds + name: str | None = None # positional label (e.g. "Drop") + type: int = 0 # plain cue + length: float = 0.0 # seconds (>0 for a loop hotcue) + + +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] = [] + + +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 diff --git a/backend/konduktor/core/pathmap.py b/backend/konduktor/core/pathmap.py new file mode 100644 index 0000000..e440b1b --- /dev/null +++ b/backend/konduktor/core/pathmap.py @@ -0,0 +1,83 @@ +"""Per-collection OS-path prefix remapping. + +A Traktor collection stores absolute audio-file paths. When the same collection +is used on another machine (a portable USB that mounts elsewhere, a relocated +library), those paths aren't reachable. A ``PathMapping`` translates a stored +path prefix (``from_prefix``) to a local one (``to_prefix``). + +This module is intentionally pure (no I/O beyond ``~`` expansion) so it can be +unit-tested and reused by both the runtime resolver (``PlaylistStore``) and the +write-back operation. See ``file_tags.resolve_path`` for the LOCATION -> OS path +step this composes with. +""" +from __future__ import annotations + +import os +from dataclasses import dataclass +from pathlib import Path + + + +def _norm(prefix: str | None) -> str: + """Normalize a prefix for matching: expand ``~``, strip a trailing slash.""" + if not prefix: + return "" + p = os.path.expanduser(prefix.strip()) + # Strip a single trailing separator (both / and \) but keep a bare root. + if len(p) > 1: + p = p.rstrip("/\\") + return p + + +@dataclass(frozen=True) +class PathMapping: + """A single ``from_prefix`` -> ``to_prefix`` OS-path prefix substitution.""" + + from_prefix: str = "" + to_prefix: str = "" + + @classmethod + def make(cls, from_prefix: str | None, to_prefix: str | None) -> "PathMapping": + return cls(_norm(from_prefix), _norm(to_prefix)) + + @property + def empty(self) -> bool: + return not self.from_prefix or not self.to_prefix + + def matches(self, os_path: Path) -> bool: + """True if ``os_path`` is at or under ``from_prefix`` (segment-aware, + so ``/a/b`` matches ``/a/b`` and ``/a/b/c`` but not ``/a/bc``).""" + if self.empty: + return False + s = str(os_path) + if s == self.from_prefix: + return True + return s.startswith(self.from_prefix + os.sep) or s.startswith(self.from_prefix + "/") + + def apply(self, os_path: Path) -> Path: + """Rebase ``os_path`` from ``from_prefix`` onto ``to_prefix``. Returns the + path unchanged when it doesn't match (non-matching tracks untouched).""" + if not self.matches(os_path): + return os_path + rest = str(os_path)[len(self.from_prefix):] + # `rest` starts with a separator (or is empty when the path == from_prefix). + return Path(self.to_prefix + rest) + + +def common_dir_prefix(paths: list[str]) -> str: + """Longest directory prefix shared by all ``paths`` (segment-aware). + + Operates on each path's parent directory, so the result is always a folder + (never a partial filename), and degrades to ``""`` when the paths share no + common root. Used to auto-suggest the ``from`` prefix in the remap editor. + """ + if not paths: + return "" + dirs = [p.replace("\\", "/").rsplit("/", 1)[0] for p in paths] + common: list[str] = [] + for segs in zip(*(d.split("/") for d in dirs)): + if len(set(segs)) == 1: + common.append(segs[0]) + else: + break + return "/".join(common) diff --git a/backend/konduktor/core/query.py b/backend/konduktor/core/query.py new file mode 100644 index 0000000..f333f9c --- /dev/null +++ b/backend/konduktor/core/query.py @@ -0,0 +1,176 @@ +"""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 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], + ) diff --git a/backend/konduktor/discovery.py b/backend/konduktor/discovery.py index 9c53270..eba5dfe 100644 --- a/backend/konduktor/discovery.py +++ b/backend/konduktor/discovery.py @@ -1,62 +1,11 @@ -"""Locate Traktor collections in their default install locations. +"""Compatibility shim — this module moved to ``konduktor.adapters.traktor.discovery``. -Traktor stores each version's data under a versioned folder: - ~/Documents/Native Instruments/Traktor /collection.nml -This is the same relative path on macOS and Windows (both under the user's -Documents folder), so a single glob covers both. +Kept so the existing test suite keeps importing the old path unchanged while the +adapter refactor lands; removed in the final cleanup step. Replacing the entry in +``sys.modules`` makes this module *be* the new one, so private names resolve too. """ -from __future__ import annotations +import sys -import re -from pathlib import Path +from .adapters.traktor import discovery as _moved -_VERSION_RE = re.compile(r"(\d+(?:\.\d+)*)") - - -def _traktor_root() -> Path: - return Path.home() / "Documents" / "Native Instruments" - - -def _version_key(version: str | None) -> tuple[int, ...]: - """Sortable tuple for a dotted version string; missing/odd → lowest.""" - if not version: - return (0,) - try: - return tuple(int(p) for p in version.split(".")) - except ValueError: - return (0,) - - -def describe(path: Path) -> dict: - """Build a candidate record for a collection.nml path. The label/version - come from the parent folder name (e.g. 'Traktor 4.5.0').""" - parent = path.parent.name - m = _VERSION_RE.search(parent) - exists = path.is_file() - return { - "path": str(path), - "label": parent or path.name, - "version": m.group(1) if m else None, - "modified": (path.stat().st_mtime if exists else None), - "exists": exists, - } - - -def detect_collections() -> list[dict]: - """All Traktor collection.nml files found in default locations, newest - Traktor version first (then most-recently-modified).""" - root = _traktor_root() - found: list[dict] = [] - if not root.is_dir(): - return found - for d in sorted(root.iterdir()): - if not d.is_dir() or not d.name.lower().startswith("traktor"): - continue - nml = d / "collection.nml" - if nml.is_file(): - found.append(describe(nml)) - found.sort( - key=lambda c: (_version_key(c["version"]), c["modified"] or 0.0), - reverse=True, - ) - return found +sys.modules[__name__] = _moved diff --git a/backend/konduktor/file_tags.py b/backend/konduktor/file_tags.py index c82d52e..11e34ea 100644 --- a/backend/konduktor/file_tags.py +++ b/backend/konduktor/file_tags.py @@ -1,321 +1,17 @@ -"""Write track metadata into audio files' embedded tags (best-effort). +"""Compatibility shim — this module was split. -Konduktor's source of truth is the `.nml`; 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 -that rather than failing the whole save. - -Field writes are frame/atom-level, so unrelated tags (cover art, beatgrid BPM, -key, track number, private frames) are preserved — verified against real files. +The mutagen read/write half is format-agnostic and moved to +``konduktor.core.audio_tags``; ``resolve_path`` encodes Traktor's LOCATION +convention and moved to ``konduktor.adapters.traktor.locations``. Kept so the +existing test suite keeps importing the old path unchanged; removed in the final +cleanup step. """ -from __future__ import annotations - -from dataclasses import dataclass -from pathlib import Path - -# The safe, editable metadata we sync to files (mirrors PlaylistStore.EDITABLE_FIELDS). -# rating is 0–5 stars. -TagMeta = dict # keys: title, artist, album, genre, label, remixer, producer, -# comment, mix, release_date, rating - - -@dataclass -class TagResult: - ok: bool - status: str # "written" | "file-not-found" | "unsupported-format" | "error" - 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/. - """ - 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(): - return None - ext = path.suffix.lower() - try: - if ext in (".mp3", ".aif", ".aiff"): - from mutagen.id3 import ID3, ID3NoHeaderError - - try: - id3 = ID3(path) - except ID3NoHeaderError: - return None - apics = id3.getall("APIC") - if not apics: - return None - front = next((a for a in apics if a.type == 3), apics[0]) - return bytes(front.data), (front.mime or "image/jpeg") - if ext in (".m4a", ".mp4"): - from mutagen.mp4 import MP4 - - covr = MP4(path).tags.get("covr") if MP4(path).tags else None - if not covr: - return None - c = covr[0] - from mutagen.mp4 import MP4Cover - - mime = "image/png" if c.imageformat == MP4Cover.FORMAT_PNG else "image/jpeg" - return bytes(c), mime - if ext == ".flac": - from mutagen.flac import FLAC - - pics = FLAC(path).pictures - if not pics: - return None - front = next((p for p in pics if p.type == 3), pics[0]) - return bytes(front.data), (front.mime or "image/jpeg") - except Exception: # noqa: BLE001 - return None - return None - - -def write_cover(path: Path, data: bytes, mime: str) -> TagResult: - """Replace the file's embedded front cover art. Best-effort.""" - if not path.exists(): - return TagResult(False, "file-not-found", str(path)) - ext = path.suffix.lower() - mime = mime if mime in ("image/jpeg", "image/png") else "image/jpeg" - try: - if ext in (".mp3", ".aif", ".aiff"): - from mutagen.id3 import APIC - - if ext == ".mp3": - from mutagen.id3 import ID3, ID3NoHeaderError - - try: - tags = ID3(path) - except ID3NoHeaderError: - tags = ID3() - tags.delall("APIC") - tags.add(APIC(encoding=3, mime=mime, type=3, desc="", data=data)) - tags.save(path) - else: - from mutagen.aiff import AIFF - - audio = AIFF(path) - if audio.tags is None: - audio.add_tags() - audio.tags.delall("APIC") - audio.tags.add(APIC(encoding=3, mime=mime, type=3, desc="", data=data)) - audio.save() - elif ext in (".m4a", ".mp4"): - from mutagen.mp4 import MP4, MP4Cover - - audio = MP4(path) - if audio.tags is None: - audio.add_tags() - fmt = MP4Cover.FORMAT_PNG if mime == "image/png" else MP4Cover.FORMAT_JPEG - audio.tags["covr"] = [MP4Cover(data, imageformat=fmt)] - audio.save() - elif ext == ".flac": - from mutagen.flac import FLAC, Picture - - audio = FLAC(path) - audio.clear_pictures() - pic = Picture() - pic.type = 3 - pic.mime = mime - pic.data = data - audio.add_picture(pic) - audio.save() - else: - return TagResult(False, "unsupported-format", ext) - except Exception as ex: # noqa: BLE001 - return TagResult(False, "error", f"{type(ex).__name__}: {ex}") - return TagResult(True, "written") - - -def _clean(v) -> str | None: - if v is None: - return None - s = str(v).strip() - return s or None - - -def write_tags(path: Path, meta: TagMeta) -> 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) - elif ext in (".aif", ".aiff"): - _write_aiff(path, meta) - elif ext in (".m4a", ".mp4") or path.name.lower().endswith(".stem.m4a"): - _write_mp4(path, meta) - elif ext == ".flac": - _write_flac(path, meta) - else: - # WAV and anything else: tag support is weak/inconsistent — skip. - return TagResult(False, "unsupported-format", ext) - except Exception as ex: # noqa: BLE001 — best-effort; report, don't crash save - return TagResult(False, "error", f"{type(ex).__name__}: {ex}") - return TagResult(True, "written") - - -# ---- ID3 (mp3 / aiff) -------------------------------------------------- -def _apply_id3(id3, meta: TagMeta) -> None: - from mutagen.id3 import ( - COMM, - POPM, - TALB, - TCON, - TDRC, - TIT2, - TIT3, - TPE1, - TPE4, - TPUB, - TXXX, - ) - - simple = { - "title": TIT2, - "artist": TPE1, - "album": TALB, - "genre": TCON, - "label": TPUB, - "remixer": TPE4, - "mix": TIT3, - "release_date": TDRC, - } - for field, frame in simple.items(): - if field in meta: - val = _clean(meta[field]) - id3.delall(frame.__name__) - if val is not None: - id3.add(frame(encoding=3, text=[val])) - if "producer" in meta: - id3.delall("TXXX:PRODUCER") - val = _clean(meta["producer"]) - if val is not None: - id3.add(TXXX(encoding=3, desc="PRODUCER", text=[val])) - if "comment" in meta: - id3.delall("COMM") - val = _clean(meta["comment"]) - if val is not None: - id3.add(COMM(encoding=3, lang="eng", desc="", text=[val])) - if "rating" in meta: - id3.delall("POPM") - stars = int(meta["rating"] or 0) - if stars > 0: - id3.add( - POPM( - email="traktor@native-instruments.de", - rating=max(0, min(5, stars)) * 51, - count=0, - ) - ) - - -def _write_id3(path: Path, meta: TagMeta, id3_only: bool) -> None: - from mutagen.id3 import ID3, ID3NoHeaderError - - try: - id3 = ID3(path) - except ID3NoHeaderError: - id3 = ID3() - _apply_id3(id3, meta) - id3.save(path) - - -def _write_aiff(path: Path, meta: TagMeta) -> None: - from mutagen.aiff import AIFF - - audio = AIFF(path) - if audio.tags is None: - audio.add_tags() - _apply_id3(audio.tags, meta) - audio.save() - - -# ---- MP4 (m4a / stem) -------------------------------------------------- -def _write_mp4(path: Path, meta: TagMeta) -> None: - from mutagen.mp4 import MP4, MP4FreeForm - - audio = MP4(path) - if audio.tags is None: - audio.add_tags() - t = audio.tags - standard = { - "title": "\xa9nam", - "artist": "\xa9ART", - "album": "\xa9alb", - "genre": "\xa9gen", - "comment": "\xa9cmt", - "release_date": "\xa9day", - } - for field, atom in standard.items(): - if field in meta: - val = _clean(meta[field]) - if val is None: - t.pop(atom, None) - else: - t[atom] = [val] - # No standard MP4 atoms for these — use iTunes-style freeform atoms. - freeform = {"label": "LABEL", "remixer": "REMIXER", "producer": "PRODUCER", "mix": "MIX"} - for field, name in freeform.items(): - if field in meta: - key = f"----:com.apple.iTunes:{name}" - val = _clean(meta[field]) - if val is None: - t.pop(key, None) - else: - t[key] = [MP4FreeForm(val.encode("utf-8"))] - if "rating" in meta: - key = "----:com.apple.iTunes:RATING" - stars = int(meta["rating"] or 0) - if stars > 0: - t[key] = [MP4FreeForm(str(max(0, min(5, stars)) * 51).encode("utf-8"))] - else: - t.pop(key, None) - audio.save() - - -# ---- FLAC -------------------------------------------------------------- -def _write_flac(path: Path, meta: TagMeta) -> None: - from mutagen.flac import FLAC - - audio = FLAC(path) - mapping = { - "title": "title", - "artist": "artist", - "album": "album", - "genre": "genre", - "label": "label", - "remixer": "remixer", - "producer": "producer", - "comment": "comment", - "mix": "mixname", - "release_date": "date", - } - for field, vc in mapping.items(): - if field in meta: - val = _clean(meta[field]) - if val is None: - audio.pop(vc, None) - else: - audio[vc] = [val] - if "rating" in meta: - stars = int(meta["rating"] or 0) - if stars > 0: - audio["rating"] = [str(max(0, min(5, stars)) * 51)] - else: - audio.pop("rating", None) - audio.save() +from .adapters.traktor.locations import resolve_path # noqa: F401 +from .core.audio_tags import ( # noqa: F401 + DEFAULT_POPM_EMAIL, + TagMeta, + TagResult, + read_cover, + write_cover, + write_tags, +) diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index 2e928b6..dd44eae 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -13,13 +13,14 @@ from fastapi import FastAPI, File, Form, HTTPException, Query, Response, UploadF from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse -from . import __version__, beatgrid -from . import auto_hotcues as ah +from . import __version__ +from .adapters.traktor import projection +from .core import auto_hotcues as ah from . import history, prefs -from .collection_service import CollectionService -from .discovery import describe, detect_collections -from .path_mapping import PathMapping -from .playlist_store import PlaylistError, PlaylistStore +from .adapters.traktor.adapter import TraktorAdapter +from .adapters.traktor.discovery import describe, detect_collections +from .core.pathmap import PathMapping +from .adapters.traktor.store import PlaylistError, PlaylistStore from .schemas import ( AutoGridRequest, AutoHotcue, @@ -80,24 +81,23 @@ class AppState: def __init__(self) -> None: self.path: Path | None = None - self.service: CollectionService | None = None - self.store: PlaylistStore | None = None + self.adapter: TraktorAdapter | None = None @property def loaded(self) -> bool: - return self.service is not None + return self.adapter is not None def open(self, path: Path) -> None: - # Both raise on an invalid/parse-incompatible or playlist-less file; - # only commit to the new collection if BOTH succeed. - service = CollectionService(path) - store = PlaylistStore(path) + # Raises on an invalid/parse-incompatible file; only commit to the new + # collection once it has parsed. One parse — the adapter builds its read + # projection from the same object graph the commands mutate. + adapter = TraktorAdapter(path) # Apply this collection's saved OS-path remapping (per-machine, keyed by # the collection's local path) so runtime translation is live on open. saved = prefs.get_path_mapping(str(path)) if saved: - store.set_path_mapping(PathMapping.make(saved["from"], saved["to"])) - self.path, self.service, self.store = path, service, store + adapter.store.set_path_mapping(PathMapping.make(saved["from"], saved["to"])) + self.path, self.adapter = path, adapter # Version history: record an "as I found it" baseline (deduped, so # re-opening an unchanged collection is a no-op). Best-effort. history.ensure_baseline(path) @@ -114,18 +114,18 @@ if _env_nml and Path(_env_nml).exists(): pass -def require_service() -> CollectionService: +def require_service() -> TraktorAdapter: if not STATE.loaded: raise HTTPException(409, "No collection loaded") - assert STATE.service is not None - return STATE.service + assert STATE.adapter is not None + return STATE.adapter def require_store() -> PlaylistStore: if not STATE.loaded: raise HTTPException(409, "No collection loaded") - assert STATE.store is not None - return STATE.store + assert STATE.adapter is not None + return STATE.adapter.store # ---- collection selection --------------------------------------------- @@ -454,49 +454,17 @@ def track_audio(track_id: str) -> FileResponse: return FileResponse(path, media_type=mime) -def _build_track_cues(entry) -> TrackCues: - """Project an ENTRY's beatgrid + cues. - - 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, and each is tagged with the marker it - belongs to so the UI can show it as beatgrid-owned rather than editable. - """ - markers = beatgrid.grid_markers(entry) - comps = beatgrid.companions(entry) - marker_of = {id(c): i for i, c in comps.items()} - grid_markers = [ - GridMarker( - start=(m.start or 0.0) / 1000.0, # Traktor stores START in 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 = [ - CuePoint( - name=c.name, - type=c.type if c.type is not None else 0, - start=(c.start or 0.0) / 1000.0, - length=(c.len or 0.0) / 1000.0, - hotcue=c.hotcue if c.hotcue is not None else -1, - color=c.color, - grid_marker=marker_of.get(id(c)), - ) - for c in (entry.cue_v2 or []) - if getattr(c, "grid", None) is None - ] - return TrackCues( - grid_markers=grid_markers, locked=bool(entry.lock), cues=cues - ) +# Compatibility alias — the cue projection moved into the Traktor adapter. +# Kept so test_save_fidelity's invariant K imports the old name unchanged while +# the refactor lands; removed in the final cleanup step. +_build_track_cues = projection.to_track_cues def _cues_for(track_id: str) -> TrackCues: entry = require_store().model_entry(track_id) if entry is None: raise HTTPException(404, "Track not found") - return _build_track_cues(entry) + return projection.to_track_cues(entry) @app.get("/api/tracks/cues", response_model=TrackCues) @@ -511,7 +479,7 @@ def _sync_cue_edit(track_id: str) -> TrackCues: entry = store.model_entry(track_id) if entry is not None: require_service().replace_track(track_id, entry) - return _build_track_cues(entry) if entry is not None else TrackCues() + return projection.to_track_cues(entry) if entry is not None else TrackCues() @app.post("/api/tracks/hotcue", response_model=TrackCues) @@ -537,7 +505,7 @@ def auto_hotcues(body: AutoHotcuesRequest) -> TrackCues: entry = store.model_entry(body.track_id) if entry is None: raise HTTPException(404, "Track not found") - cues = _build_track_cues(entry) + cues = projection.to_track_cues(entry) if not cues.grid_markers: raise HTTPException(400, "Set a beatgrid before using Auto Hotcues") path = store.audio_path(body.track_id) diff --git a/backend/konduktor/path_mapping.py b/backend/konduktor/path_mapping.py index e7efd10..78b4c25 100644 --- a/backend/konduktor/path_mapping.py +++ b/backend/konduktor/path_mapping.py @@ -1,127 +1,10 @@ -"""Per-collection OS-path prefix remapping. +"""Compatibility shim — this module was split. -A Traktor collection stores absolute audio-file paths. When the same collection -is used on another machine (a portable USB that mounts elsewhere, a relocated -library), those paths aren't reachable. A ``PathMapping`` translates a stored -path prefix (``from_prefix``) to a local one (``to_prefix``). - -This module is intentionally pure (no I/O beyond ``~`` expansion) so it can be -unit-tested and reused by both the runtime resolver (``PlaylistStore``) and the -write-back operation. See ``file_tags.resolve_path`` for the LOCATION -> OS path -step this composes with. +``PathMapping``/``common_dir_prefix`` are format-agnostic and moved to +``konduktor.core.pathmap``; ``os_path_to_location`` is the inverse of Traktor's +``resolve_path`` and moved to ``konduktor.adapters.traktor.locations``. Kept so +the existing test suite keeps importing the old path unchanged; removed in the +final cleanup step. """ -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: - """Normalize a prefix for matching: expand ``~``, strip a trailing slash.""" - if not prefix: - return "" - p = os.path.expanduser(prefix.strip()) - # Strip a single trailing separator (both / and \) but keep a bare root. - if len(p) > 1: - p = p.rstrip("/\\") - return p - - -@dataclass(frozen=True) -class PathMapping: - """A single ``from_prefix`` -> ``to_prefix`` OS-path prefix substitution.""" - - from_prefix: str = "" - to_prefix: str = "" - - @classmethod - def make(cls, from_prefix: str | None, to_prefix: str | None) -> "PathMapping": - return cls(_norm(from_prefix), _norm(to_prefix)) - - @property - def empty(self) -> bool: - return not self.from_prefix or not self.to_prefix - - def matches(self, os_path: Path) -> bool: - """True if ``os_path`` is at or under ``from_prefix`` (segment-aware, - so ``/a/b`` matches ``/a/b`` and ``/a/b/c`` but not ``/a/bc``).""" - if self.empty: - return False - s = str(os_path) - if s == self.from_prefix: - return True - return s.startswith(self.from_prefix + os.sep) or s.startswith(self.from_prefix + "/") - - def apply(self, os_path: Path) -> Path: - """Rebase ``os_path`` from ``from_prefix`` onto ``to_prefix``. Returns the - path unchanged when it doesn't match (non-matching tracks untouched).""" - if not self.matches(os_path): - return os_path - rest = str(os_path)[len(self.from_prefix):] - # `rest` starts with a separator (or is empty when the path == from_prefix). - return Path(self.to_prefix + rest) - - -def common_dir_prefix(paths: list[str]) -> str: - """Longest directory prefix shared by all ``paths`` (segment-aware). - - Operates on each path's parent directory, so the result is always a folder - (never a partial filename), and degrades to ``""`` when the paths share no - common root. Used to auto-suggest the ``from`` prefix in the remap editor. - """ - if not paths: - return "" - dirs = [p.replace("\\", "/").rsplit("/", 1)[0] for p in paths] - common: list[str] = [] - for segs in zip(*(d.split("/") for d in dirs)): - if len(set(segs)) == 1: - common.append(segs[0]) - 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 +from .adapters.traktor.locations import os_path_to_location # noqa: F401 +from .core.pathmap import PathMapping, common_dir_prefix # noqa: F401 diff --git a/backend/konduktor/playlist_store.py b/backend/konduktor/playlist_store.py index 4cc755f..f60c91c 100644 --- a/backend/konduktor/playlist_store.py +++ b/backend/konduktor/playlist_store.py @@ -1,1017 +1,11 @@ -"""Editable playlist store backed by the traktor-nml-utils dataclass model. +"""Compatibility shim — this module moved to ``konduktor.adapters.traktor.store``. -Design goals: - * minimal diff — unedited playlists must serialize byte-for-byte as Traktor - wrote them (the xsdata serializer used by the library reproduces Traktor's - exact formatting; lxml does not), - * surgical — the ~14 MB COLLECTION stays byte-identical (we splice only the - span back into the original file bytes), - * safe — every save is committed to the collection's version history (see - ``history.py``); the commit is additive and never alters the saved bytes. - -We edit the parsed dataclass model in memory (create/rename/delete/set-entries), -then on save render the full model, extract just the freshly-rendered -… span, and splice it into the untouched original bytes. - -Playlists are identified by their stable UUID; folders by a synthetic path id -(``fld:/``). Smart playlists are read-only. +Kept so the existing test suite keeps importing the old path unchanged while the +adapter refactor lands; removed in the final cleanup step. Replacing the entry in +``sys.modules`` makes this module *be* the new one, so private names resolve too. """ -from __future__ import annotations +import sys -import threading -import uuid as uuidlib -from dataclasses import dataclass -from pathlib import Path +from .adapters.traktor import store as _moved -from traktor_nml_utils import ( - TraktorCollection, - format_traktor_layout, - restore_traktor_float_format, -) -from traktor_nml_utils.models.collection import ( - Albumtype, - CueV2Type, - Entrytype, - GridType, - Infotype, - Nodetype, - Playlisttype, - Primarykeytype, - Subnodestype, - Tempotype, -) -from xsdata.formats.dataclass.serializers import XmlSerializer - -from . import __version__, beatgrid, history -from .path_mapping import PathMapping -from .schemas import PlaylistNode - - -class PlaylistError(Exception): - pass - - -@dataclass -class FileTagResult: - track_id: str - file: str - ok: bool - status: str # "written" | "file-not-found" | "unsupported-format" | "error" - detail: str = "" - - -@dataclass -class SaveOutcome: - commit: str | None # sha of the version-history commit (None if deduped/failed) - tag_results: list[FileTagResult] - - -class PlaylistStore: - def __init__(self, nml_path: Path): - self.nml_path = Path(nml_path) - self._lock = threading.RLock() - self.dirty = False - # Active OS-path prefix remapping (empty = identity). Survives _load(). - self._path_mapping = PathMapping() - self._load() - - # ---- load ---------------------------------------------------------- - def _load(self) -> None: - self._collection = TraktorCollection(path=self.nml_path) - self._nml = self._collection.nml - # Index collection entries by their Traktor primary key (volume+dir+file) - # so track-metadata edits can find their ENTRY in O(1). - self._entry_by_key: dict[str, Entrytype] = {} - for e in self._nml.collection.entry: - loc = e.location - if loc: - key = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}" - self._entry_by_key[key] = e - # track_id -> set of field names edited this session (drives file-tag sync) - self._track_edits: dict[str, set[str]] = {} - # track_id -> (image_bytes, mime) of staged replacement cover art - self._track_art: dict[str, tuple[bytes, str]] = {} - # (category, detail, track_id) events this session -> commit summary. - # track_id lets prep edits report how many distinct tracks were affected. - self._edit_events: list[tuple[str, str | None, str | None]] = [] - self.dirty = False - - def _note(self, category: str, detail: str | None = None, track_id: str | None = None) -> None: - """Record a human-meaningful edit for the next commit's summary.""" - self._edit_events.append((category, detail, track_id)) - - def _root(self) -> Nodetype: - node = self._nml.playlists.node if self._nml.playlists else None - if node is None: - raise PlaylistError("PLAYLISTS has no root NODE") - return node - - @staticmethod - def _children(node: Nodetype) -> list[Nodetype]: - return list(node.subnodes.node) if node.subnodes else [] - - # ---- tree walking -------------------------------------------------- - def tree(self) -> list[PlaylistNode]: - with self._lock: - return [self._to_model(c, []) for c in self._children(self._root())] - - def _to_model(self, node: Nodetype, parent_path: list[str]) -> PlaylistNode: - ntype = node.type or "FOLDER" - name = node.name or "(unnamed)" - if ntype == "PLAYLIST" or node.playlist is not None: - pl = node.playlist - keys = self._entry_keys_of(pl) if pl is not None else [] - return PlaylistNode( - id=pl.uuid if pl and pl.uuid else name, - name=name, - type="PLAYLIST", - uuid=pl.uuid if pl else None, - count=len(keys), - ) - if ntype == "SMARTLIST" or node.smartplaylist is not None: - return PlaylistNode( - id="sl:" + "/".join(parent_path + [name]), name=name, type="SMARTLIST" - ) - path = parent_path + [name] - return PlaylistNode( - id="fld:" + "/".join(path), - name=name, - type="FOLDER", - children=[self._to_model(c, path) for c in self._children(node)], - ) - - @staticmethod - def _entry_keys_of(pl: Playlisttype) -> list[str]: - return [ - e.primarykey.key - for e in (pl.entry or []) - if e.primarykey and e.primarykey.key - ] - - # ---- lookups ------------------------------------------------------- - def _iter_nodes(self, node: Nodetype): - yield node - for c in self._children(node): - yield from self._iter_nodes(c) - - def _find_playlist_node(self, playlist_uuid: str) -> Nodetype | None: - for n in self._iter_nodes(self._root()): - if n.playlist is not None and n.playlist.uuid == playlist_uuid: - return n - return None - - def _find_parent_of(self, target: Nodetype) -> Nodetype | None: - for n in self._iter_nodes(self._root()): - if n.subnodes and target in n.subnodes.node: - return n - return None - - def _find_folder(self, folder_id: str | None) -> Nodetype: - root = self._root() - if folder_id in (None, "", "fld:"): - return root - if not folder_id.startswith("fld:"): - raise PlaylistError(f"Not a folder id: {folder_id}") - cur = root - for name in folder_id[len("fld:") :].split("/"): - match = next( - ( - c - for c in self._children(cur) - if (c.type or "FOLDER") == "FOLDER" and c.name == name - ), - None, - ) - if match is None: - raise PlaylistError(f"Folder not found: {folder_id}") - cur = match - return cur - - def entry_keys(self, playlist_uuid: str) -> list[str] | None: - with self._lock: - node = self._find_playlist_node(playlist_uuid) - return None if node is None else self._entry_keys_of(node.playlist) - - # ---- edits --------------------------------------------------------- - def create_playlist(self, name: str, parent_id: str | None = None) -> str: - with self._lock: - folder = self._find_folder(parent_id) - if folder.subnodes is None: - folder.subnodes = Subnodestype(node=[], count=0) - new_uuid = uuidlib.uuid4().hex - node = Nodetype( - type="PLAYLIST", - name=name, - playlist=Playlisttype(entry=[], entries=0, type="LIST", uuid=new_uuid), - ) - folder.subnodes.node.append(node) - folder.subnodes.count = len(folder.subnodes.node) - self._note("playlist-create", name) - self.dirty = True - return new_uuid - - def rename_playlist(self, playlist_uuid: str, name: str) -> None: - with self._lock: - node = self._find_playlist_node(playlist_uuid) - if node is None: - raise PlaylistError(f"Playlist not found: {playlist_uuid}") - node.name = name - self._note("playlist-rename", name) - self.dirty = True - - def delete_playlist(self, playlist_uuid: str) -> None: - with self._lock: - node = self._find_playlist_node(playlist_uuid) - if node is None: - raise PlaylistError(f"Playlist not found: {playlist_uuid}") - parent = self._find_parent_of(node) - if parent is None: - raise PlaylistError("Cannot delete a top-level node") - parent.subnodes.node.remove(node) - parent.subnodes.count = len(parent.subnodes.node) - self._note("playlist-delete", node.name) - self.dirty = True - - def set_entries(self, playlist_uuid: str, entries: list[tuple[str, str]]) -> None: - with self._lock: - node = self._find_playlist_node(playlist_uuid) - if node is None: - raise PlaylistError(f"Playlist not found: {playlist_uuid}") - pl = node.playlist - pl.entry = [ - Entrytype(primarykey=Primarykeytype(type=ptype or "TRACK", key=key)) - for key, ptype in entries - ] - pl.entries = len(pl.entry) - self._note("playlist-entries", node.name) - self.dirty = True - - # ---- track metadata editing --------------------------------------- - # Safe, free-text-ish fields only. Deliberately NOT editable here: file path - # (it's the primary key), bpm/key (audio/grid territory), and read-only info - # like bitrate/playcount. - _INFO_FIELDS = {"genre", "label", "remixer", "producer", "comment", "mix", "release_date"} - EDITABLE_FIELDS = {"title", "artist", "album", "rating"} | _INFO_FIELDS - - def set_track_metadata(self, track_id: str, fields: dict) -> None: - with self._lock: - entry = self._entry_by_key.get(track_id) - if entry is None: - raise PlaylistError(f"Track not found: {track_id}") - if entry.info is None: - entry.info = Infotype() - for k, v in fields.items(): - if k in ("title", "artist"): - setattr(entry, k, v or None) - elif k == "album": - if entry.album is None: - entry.album = Albumtype() - entry.album.title = v or None - elif k in self._INFO_FIELDS: - setattr(entry.info, k, v or None) - elif k == "rating": - stars = max(0, min(5, int(v))) if v is not None else 0 - # Traktor RANKING = stars * 51; unrated has no RANKING attr. - entry.info.ranking = stars * 51 or None - else: - continue # unknown / read-only fields are ignored - self._track_edits.setdefault(track_id, set()).add(k) - self.dirty = True - - def model_entry(self, track_id: str) -> Entrytype | None: - with self._lock: - return self._entry_by_key.get(track_id) - - # ---- hotcues ------------------------------------------------------ - # Creatable/editable types: 0 cue, 1 fade-in, 2 fade-out, 3 load, 5 loop. - # A loop (type 5) carries a length; the point types don't. Grid markers - # (type 4, redefine the beatgrid) are excluded. Cues are NML-only. - POINT_CUE_TYPES = {0, 1, 2, 3} # types the dropdown can switch between - CREATABLE_TYPES = {0, 1, 2, 3, 5} - - def _entry_or_raise(self, track_id: str) -> Entrytype: - entry = self._entry_by_key.get(track_id) - if entry is None: - raise PlaylistError(f"Track not found: {track_id}") - return entry - - @staticmethod - def _reject_if_companion(entry: Entrytype, slot: int) -> None: - """Refuse to touch a slot held by a grid marker's companion cue. - - Traktor pairs most grid markers with a white cue in a real hotcue slot. - Overwriting, retyping or deleting one desyncs it from its marker, so the - beatgrid commands own these slots — move or delete the marker instead. - """ - cue = next((c for c in (entry.cue_v2 or []) if c.hotcue == slot), None) - if cue is not None and beatgrid.is_companion(entry, cue): - raise PlaylistError( - f"Hotcue {slot + 1} belongs to a beatgrid marker — " - "move or delete the marker instead" - ) - - def set_hotcue( - self, - track_id: str, - slot: int, - start_sec: float, - cue_type: int, - length_sec: float = 0.0, - name: str | None = None, - ) -> None: - """Create (or reposition + retype) the hotcue in `slot` at `start_sec`. - - `length_sec` > 0 makes it a loop (used with cue_type 5). `name` sets the - cue label on create; when unset it falls back to Traktor's "n.n.".""" - if not 0 <= slot <= 7: - raise PlaylistError(f"Invalid hotcue slot: {slot}") - if cue_type not in self.CREATABLE_TYPES: - raise PlaylistError(f"Unsupported cue type: {cue_type}") - with self._lock: - entry = self._entry_or_raise(track_id) - self._reject_if_companion(entry, slot) - start_ms = max(0.0, start_sec * 1000.0) # Traktor stores START/LEN in ms - len_ms = max(0.0, length_sec * 1000.0) - existing = next( - (c for c in (entry.cue_v2 or []) if c.hotcue == slot), None - ) - if existing is not None: - existing.start = start_ms - existing.type = cue_type - existing.len = len_ms - else: - if entry.cue_v2 is None: - entry.cue_v2 = [] - entry.cue_v2.append( - CueV2Type( - name=name or "n.n.", # Traktor's default name for a manual cue - displ_order=0, - type=cue_type, - start=start_ms, - len=len_ms, - repeats=-1, - hotcue=slot, - color=None, - grid=None, - ) - ) - # "add" only when it's a genuinely new hotcue; repositioning/retyping - # an existing slot is a "modify" (keeps the net add/remove count honest). - self._note("hotcue", "modify" if existing is not None else "add", track_id) - self.dirty = True - - def place_hotcues( - self, track_id: str, specs: list, *, overwrite: bool = False - ) -> None: - """Batch-create hotcues from `specs` (each has .slot/.start/.name and - optional .type/.length). With `overwrite` False (the default), slots that - already hold a hotcue are skipped so hand-placed cues are never clobbered. - Used by Auto Hotcues.""" - with self._lock: - entry = self._entry_or_raise(track_id) - occupied = { - c.hotcue for c in (entry.cue_v2 or []) if c.hotcue is not None and c.hotcue >= 0 - } - # Companion slots belong to the beatgrid — never fill them, even - # with overwrite=True (occupied alone only guards them while False). - protected = { - c.hotcue for c in beatgrid.companions(entry).values() if c.hotcue is not None - } - for spec in specs: - if spec.slot in protected or (not overwrite and spec.slot in occupied): - continue - self.set_hotcue( - track_id, - spec.slot, - spec.start, - getattr(spec, "type", 0), - getattr(spec, "length", 0.0), - name=getattr(spec, "name", None), - ) - - def set_hotcue_type(self, track_id: str, slot: int, cue_type: int) -> None: - """Change the type of the existing hotcue in `slot` (keeps its position).""" - if cue_type not in self.POINT_CUE_TYPES: - raise PlaylistError(f"Unsupported cue type: {cue_type}") - with self._lock: - entry = self._entry_or_raise(track_id) - self._reject_if_companion(entry, slot) - cue = next((c for c in (entry.cue_v2 or []) if c.hotcue == slot), None) - if cue is None: - raise PlaylistError(f"Hotcue {slot} is not set") - cue.type = cue_type - self._note("hotcue", "modify", track_id) - self.dirty = True - - def delete_hotcue(self, track_id: str, slot: int) -> None: - with self._lock: - entry = self._entry_or_raise(track_id) - self._reject_if_companion(entry, slot) - before = entry.cue_v2 or [] - entry.cue_v2 = [c for c in before if c.hotcue != slot] - if len(entry.cue_v2) != len(before): # only count an actual removal - self._note("hotcue", "delete", track_id) - self.dirty = True - - # ---- beatgrid ----------------------------------------------------- - # A beatgrid is an ORDERED LIST of markers (see beatgrid.py); a constant - # grid is a list of length one. Markers are addressed by their index in that - # start-ordered list. CUE_V2 has no id attribute and save() reparses the - # whole file, so any synthetic id would have to be rebuilt by position - # anyway — the index IS the identity. - _MARKER_MIN_GAP_MS = 1.0 - - @staticmethod - def _grid_marker(entry: Entrytype) -> CueV2Type | None: - """The first grid marker BY START — the one mirrors.""" - return beatgrid.first_marker(entry) - - @staticmethod - def _sync_tempo(entry: Entrytype) -> None: - """Mirror from the first marker (7968/7968 in the reference - collection). Called last by every grid mutator, so a move that changes - which marker is first re-mirrors for free. - - With no markers left, TEMPO is LEFT ALONE: Traktor keeps the analysed - BPM on gridless tracks (53 such entries exist in the reference file). - """ - marker = beatgrid.first_marker(entry) - if marker is None or marker.grid is None or not marker.grid.bpm: - return - if entry.tempo is None: - entry.tempo = Tempotype(bpm=marker.grid.bpm, bpm_quality=100.0) - else: - entry.tempo.bpm = marker.grid.bpm - - @staticmethod - def _sort_cues(entry: Entrytype) -> None: - """Keep CUE_V2 ascending by START — true for 8485/8485 reference - entries, so an inserted marker must not become the one exception. - Stable, so a marker stays ahead of a companion at an identical START. - """ - if entry.cue_v2: - entry.cue_v2.sort(key=lambda c: c.start or 0.0) - - def _markers_or_raise( - self, entry: Entrytype, index: int - ) -> tuple[list[CueV2Type], CueV2Type]: - markers = beatgrid.grid_markers(entry) - if not markers: - raise PlaylistError("Track has no beatgrid") - if not 0 <= index < len(markers): - raise PlaylistError( - f"Grid marker {index} out of range (track has {len(markers)})" - ) - return markers, markers[index] - - def _drop_grid(self, entry: Entrytype) -> None: - """Remove every marker AND every companion. No _note — callers do that.""" - doomed = {id(m) for m in beatgrid.grid_markers(entry)} - doomed |= {id(c) for c in beatgrid.companions(entry).values()} - entry.cue_v2 = [c for c in (entry.cue_v2 or []) if id(c) not in doomed] - - def add_grid_marker( - self, - track_id: str, - start_sec: float, - bpm: float | None = None, - name: str | None = None, - ) -> int: - """Add a beatgrid marker at `start_sec`; returns its index. - - With `bpm` unset the marker INHERITS the tempo of the section it lands - in, so splitting a section is musically a no-op until it's retempoed. - Creates no companion cue — Traktor tolerates markers without one, and - inventing them would silently consume the user's hotcue slots. - """ - if bpm is not None and bpm <= 0: - raise PlaylistError(f"BPM must be positive: {bpm}") - with self._lock: - entry = self._entry_or_raise(track_id) - start_ms = max(0.0, start_sec * 1000.0) - markers = beatgrid.grid_markers(entry) - for m in markers: - if abs((m.start or 0.0) - start_ms) < self._MARKER_MIN_GAP_MS: - raise PlaylistError("A grid marker already exists at that position") - if bpm is None: - bpm = self._bpm_governing(entry, start_ms) - if bpm is None: - raise PlaylistError("No BPM available to create a beatgrid") - if entry.cue_v2 is None: - entry.cue_v2 = [] - entry.cue_v2.append( - CueV2Type( - name=name or ("AutoGrid" if not markers else "n.n."), - displ_order=0, - type=4, - start=start_ms, - len=0.0, - repeats=-1, - hotcue=-1, - color=None, - grid=GridType(bpm=bpm), - ) - ) - self._sort_cues(entry) - self._sync_tempo(entry) - self._note("grid", "marker-add", track_id) - self.dirty = True - return next( - i - for i, m in enumerate(beatgrid.grid_markers(entry)) - if abs((m.start or 0.0) - start_ms) < 1e-9 - ) - - @staticmethod - def _bpm_governing(entry: Entrytype, start_ms: float) -> float | None: - """The tempo in force at `start_ms`: the last marker at or before it, - else the first marker (extrapolated backwards), else .""" - markers = beatgrid.grid_markers(entry) - if not markers: - return entry.tempo.bpm if entry.tempo else None - governing = markers[0] - for m in markers: - if (m.start or 0.0) <= start_ms: - governing = m - else: - break - return governing.grid.bpm if governing.grid else None - - def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> None: - """Move marker `index`, DRAGGING ITS COMPANION with it. - - The new position is CLAMPED between the neighbouring markers rather than - allowed to reorder them, so an index can never go stale mid-edit. Phase - nudges are +/-1 and +/-10 ms, so this is no practical constraint; - restructuring a grid is add-then-delete. - """ - with self._lock: - entry = self._entry_or_raise(track_id) - markers, marker = self._markers_or_raise(entry, index) - start_ms = max(0.0, start_sec * 1000.0) - if index > 0: - lo = (markers[index - 1].start or 0.0) + self._MARKER_MIN_GAP_MS - start_ms = max(start_ms, lo) - if index < len(markers) - 1: - hi = (markers[index + 1].start or 0.0) - self._MARKER_MIN_GAP_MS - start_ms = min(start_ms, hi) - companion = beatgrid.companions(entry).get(index) - marker.start = start_ms - if companion is not None: - # Copy the float — never recompute from seconds. A 1-ULP drift - # here would change the rendered bytes and break byte-reverts. - companion.start = marker.start - self._sync_tempo(entry) - self._note("grid", "marker-move", track_id) - self.dirty = True - - def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> None: - """Set marker `index`'s tempo (governs until the next marker).""" - if bpm <= 0: - raise PlaylistError(f"BPM must be positive: {bpm}") - with self._lock: - entry = self._entry_or_raise(track_id) - _, marker = self._markers_or_raise(entry, index) - if marker.grid is None: - marker.grid = GridType(bpm=bpm) - else: - marker.grid.bpm = bpm - self._sync_tempo(entry) - self._note("grid", "marker-bpm", track_id) - self.dirty = True - - def delete_grid_marker(self, track_id: str, index: int) -> None: - """Remove marker `index` and its companion (freeing that hotcue slot).""" - with self._lock: - entry = self._entry_or_raise(track_id) - markers, marker = self._markers_or_raise(entry, index) - companion = beatgrid.companions(entry).get(index) - doomed = {id(marker)} | ({id(companion)} if companion is not None else set()) - entry.cue_v2 = [c for c in (entry.cue_v2 or []) if id(c) not in doomed] - self._sync_tempo(entry) - # Removing the last marker IS deleting the grid — report it as one. - self._note( - "grid", "delete" if len(markers) == 1 else "marker-delete", track_id - ) - self.dirty = True - - def replace_grid( - self, track_id: str, markers: list[tuple[float, float]] - ) -> None: - """Throw the grid away and rebuild it from `markers` [(start_sec, bpm)]. - - Serves both Auto Grid (a single marker) and the deck's Reset (restore - the list as loaded) as one atomic, single-event command. Companions of - the old grid go with it; none are created. - """ - for start_sec, bpm in markers: - if bpm <= 0: - raise PlaylistError(f"BPM must be positive: {bpm}") - with self._lock: - entry = self._entry_or_raise(track_id) - self._drop_grid(entry) - if entry.cue_v2 is None: - entry.cue_v2 = [] - for i, (start_sec, bpm) in enumerate( - sorted(markers, key=lambda m: m[0]) - ): - entry.cue_v2.append( - CueV2Type( - name="AutoGrid" if i == 0 else "n.n.", - displ_order=0, - type=4, - start=max(0.0, start_sec * 1000.0), - len=0.0, - repeats=-1, - hotcue=-1, - color=None, - grid=GridType(bpm=bpm), - ) - ) - self._sort_cues(entry) - self._sync_tempo(entry) - self._note("grid", "replace", track_id) - self.dirty = True - - def place_grid_companion( - self, track_id: str, index: int, *, prefer_slot: int = 0 - ) -> int | None: - """Give marker `index` the white beat-1 hotcue Traktor writes beside its - own markers: `prefer_slot` when free, else the lowest free slot. - - Returns the slot used, or None when the bank is full or the marker - already has a companion. NEVER overwrites. This is the ONLY place - Konduktor creates a companion — grid edits never do — because it is a - deliberate, user-invoked feature (Auto Grid), not a side effect. - """ - with self._lock: - entry = self._entry_or_raise(track_id) - _, marker = self._markers_or_raise(entry, index) - if index in beatgrid.companions(entry): - return None - used = { - c.hotcue - for c in (entry.cue_v2 or []) - if c.hotcue is not None and c.hotcue >= 0 - } - slot = next( - (s for s in [prefer_slot, *range(8)] if 0 <= s <= 7 and s not in used), - None, - ) - if slot is None: - return None - entry.cue_v2.append( - CueV2Type( - name=marker.name or "AutoGrid", - displ_order=0, - type=0, - start=marker.start, # copy the float, not start_sec * 1000 - len=0.0, - repeats=-1, - hotcue=slot, - color=beatgrid.COMPANION_COLOR, - grid=None, - ) - ) - self._sort_cues(entry) - self._note("grid", "marker-add", track_id) - self.dirty = True - return slot - - def delete_grid(self, track_id: str) -> None: - """Remove EVERY grid marker AND EVERY companion; is kept. - - Dropping companions is the debris fix: the old code stripped markers - only, leaving orphan white cues squatting in hotcue slots. - """ - with self._lock: - entry = self._entry_or_raise(track_id) - self._drop_grid(entry) - self._note("grid", "delete", track_id) - self.dirty = True - - def set_lock(self, track_id: str, locked: bool) -> None: - with self._lock: - entry = self._entry_or_raise(track_id) - entry.lock = 1 if locked else None - self._note("lock", "on" if locked else "off", track_id) - self.dirty = True - - # ---- cover art ----------------------------------------------------- - def set_track_art(self, track_id: str, data: bytes, mime: str) -> None: - with self._lock: - if track_id not in self._entry_by_key: - raise PlaylistError(f"Track not found: {track_id}") - self._track_art[track_id] = (data, mime) - self.dirty = True - - def set_path_mapping(self, mapping: PathMapping) -> None: - """Set the active OS-path prefix remapping (applied at resolve time).""" - with self._lock: - self._path_mapping = mapping - - def _resolve(self, loc) -> "Path | None": - """Resolve a LOCATION to an OS path, applying the active path mapping. - - The single FS chokepoint: LOCATION -> `resolve_path` -> prefix remap. - Falls back to the un-remapped path when the remapped target doesn't - exist, so a misconfigured mapping never makes a present file unreachable. - """ - from . import file_tags - - if loc is None: - return None - base = file_tags.resolve_path(loc.volume, loc.dir, loc.file) - if self._path_mapping.empty: - return base - remapped = self._path_mapping.apply(base) - if remapped == base: - return base - return remapped if remapped.exists() else base - - def cover_art(self, track_id: str) -> tuple[bytes, str] | None: - """Staged replacement if present, else the file's current embedded art.""" - from . import file_tags - - with self._lock: - if track_id in self._track_art: - return self._track_art[track_id] - entry = self._entry_by_key.get(track_id) - if entry is None or entry.location is None: - return None - path = self._resolve(entry.location) - return file_tags.read_cover(path) if path else None - - def audio_path(self, track_id: str) -> "Path | None": - """Resolve a track's audio file to an OS path (for playback streaming).""" - with self._lock: - entry = self._entry_by_key.get(track_id) - if entry is None or entry.location is None: - return None - return self._resolve(entry.location) - - def path_prefix_suggestions(self) -> dict: - """Auto-suggest ``from`` prefixes by resolving every track's LOCATION and - finding the common directory prefix per volume. Returns a ``primary`` - (the largest group's prefix) plus per-group prefixes ranked by track - count, so the editor can prefill and offer alternatives.""" - from collections import defaultdict - - from . import file_tags - from .path_mapping import common_dir_prefix - - with self._lock: - groups: dict[str, list[str]] = defaultdict(list) - for e in self._nml.collection.entry: - loc = e.location - if not loc: - continue - groups[loc.volume or ""].append( - str(file_tags.resolve_path(loc.volume, loc.dir, loc.file)) - ) - ranked = sorted( - ( - {"prefix": common_dir_prefix(paths), "count": len(paths)} - for paths in groups.values() - ), - key=lambda g: g["count"], - reverse=True, - ) - ranked = [g for g in ranked if g["prefix"]] - return {"primary": ranked[0]["prefix"] if ranked else "", "groups": ranked[:5]} - - def remap_preview(self, mapping: PathMapping) -> dict: - """How a mapping would affect the collection, without changing anything: - total tracks, how many match ``from``, and how many exist at ``to`` - (plus a few samples). Powers the mapping editor's validation line.""" - from . import file_tags - - with self._lock: - total = matched = existing = 0 - samples: list[dict] = [] - for e in self._nml.collection.entry: - loc = e.location - if not loc: - continue - total += 1 - base = file_tags.resolve_path(loc.volume, loc.dir, loc.file) - if mapping.matches(base): - matched += 1 - target = mapping.apply(base) - ok = target.exists() - if ok: - existing += 1 - if len(samples) < 5: - samples.append({"from": str(base), "to": str(target), "exists": ok}) - return {"total": total, "matched": matched, "existing": existing, "samples": samples} - - def remap_locations(self, mapping: PathMapping) -> int: - """Permanently rewrite matching track LOCATIONs to the mapping's ``to`` - prefix — a deliberate library move (write-back). - - Because ``track_id`` IS the LOCATION key (``volume+dir+file``), every - playlist ``PRIMARYKEY`` that referenced a moved track is rewritten too, - so playlists keep pointing at their tracks. Non-matching entries are - untouched. Returns the number of tracks rewritten; the caller saves. - """ - from . import file_tags - from .path_mapping import os_path_to_location - - if mapping.empty: - return 0 - with self._lock: - key_remap: dict[str, str] = {} - for e in self._nml.collection.entry: - loc = e.location - if not loc: - continue - base = file_tags.resolve_path(loc.volume, loc.dir, loc.file) - if not mapping.matches(base): - continue - target = mapping.apply(base) - volume, dir_, file = os_path_to_location(target) - old_key = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}" - new_key = f"{volume or ''}{dir_ or ''}{file or ''}" - if old_key == new_key: - continue # no-op (e.g. from == to); leave byte-identical - loc.volume, loc.dir, loc.file = volume, dir_, file - key_remap[old_key] = new_key - if not key_remap: - return 0 - # Rewrite playlist entry primary keys that referenced moved tracks. - for node in self._iter_nodes(self._root()): - pl = node.playlist - if pl is None or not pl.entry: - continue - for entry in pl.entry: - pk = entry.primarykey - if pk and pk.key in key_remap: - pk.key = key_remap[pk.key] - self._note("remap", str(len(key_remap))) - self.dirty = True - return len(key_remap) - - def _entry_field_value(self, entry: Entrytype, field: str): - """Read a single editable field's current value from the model, in the - shape file_tags expects (rating as 0–5 stars).""" - if field == "title": - return entry.title - if field == "artist": - return entry.artist - if field == "album": - return entry.album.title if entry.album else None - if field == "rating": - r = entry.info.ranking if entry.info else None - return round(r / 51) if r else 0 - return getattr(entry.info, field, None) if entry.info else None - - def count_playlists(self) -> int: - with self._lock: - return sum(1 for n in self._iter_nodes(self._root()) if n.playlist is not None) - - # ---- persistence --------------------------------------------------- - def save(self) -> "SaveOutcome": - with self._lock: - new_data = self._render() - tmp = self.nml_path.with_suffix(self.nml_path.suffix + ".tmp") - tmp.write_bytes(new_data) - tmp.replace(self.nml_path) - # Best-effort: sync the edited fields into each edited track's file. - tag_results = self._sync_file_tags() - # Version history: commit the saved bytes (additive — never touches the - # file we just wrote). Summary is computed before _load() clears state. - commit = history.commit(self.nml_path, new_data, self._edit_summary(), __version__) - self._load() # clears dirty + _track_edits + _edit_events - return SaveOutcome(commit=commit, tag_results=tag_results) - - def _edit_summary(self) -> 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'}" - - # --- track metadata + cover art (already counted per-track) --- - n_meta = len(self._track_edits.keys() | self._track_art.keys()) - if n_meta: - parts.append(f"edited {tracks(n_meta)}") - - # --- playlists (name-bearing) --- - pl_names: dict[str, list[str]] = {} - for cat, detail, _tid in self._edit_events: - if cat.startswith("playlist-") and detail: - pl_names.setdefault(cat, []).append(detail) - for cat, verb in ( - ("playlist-create", "created"), - ("playlist-rename", "renamed"), - ("playlist-delete", "deleted"), - ("playlist-entries", "reordered"), - ): - names = pl_names.get(cat, []) - if not names: - continue - if len(names) <= 2: - joined = ", ".join(f"'{n}'" for n in names) - parts.append(f"{verb} playlist{'' if len(names) == 1 else 's'} {joined}") - else: - parts.append(f"{verb} {len(names)} playlists") - - # --- 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 cat, detail, tid in self._edit_events: - if cat == "hotcue": - if tid: - hc_tracks.add(tid) - if detail == "add": - hc_add += 1 - elif detail == "delete": - hc_del += 1 - elif cat == "grid": - # "delete" is the ONLY deletion detail. Everything else — including - # details 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 detail == "delete" else grid_edit).add(tid or "") - elif cat == "lock": - (lock_on if detail == "on" else lock_off).add(tid 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 cat, detail, _tid in self._edit_events: - if cat == "remap" and detail: - parts.append(f"remapped {detail} file paths") - - if not parts: - return "Saved changes" - summary = "; ".join(parts) - return summary[0].upper() + summary[1:] - - def _sync_file_tags(self) -> list["FileTagResult"]: - from . import file_tags - - results: list[FileTagResult] = [] - # Union of tracks with edited fields and/or replaced art. - for track_id in self._track_edits.keys() | self._track_art.keys(): - entry = self._entry_by_key.get(track_id) - if entry is None or entry.location is None: - continue - path = self._resolve(entry.location) - if path is None: - continue - r = None - if track_id in self._track_edits: - meta = {f: self._entry_field_value(entry, f) for f in self._track_edits[track_id]} - r = file_tags.write_tags(path, meta) - if track_id in self._track_art: - data, mime = self._track_art[track_id] - r = file_tags.write_cover(path, data, mime) - if r is not None: - results.append( - FileTagResult( - track_id=track_id, file=str(path), ok=r.ok, status=r.status, detail=r.detail - ) - ) - return results - - def _render(self) -> bytes: - """Render the whole model exactly as the library's save() does. - - The two post-processing steps restore Traktor's precise layout (expanded - empty tags, 6-decimal floats, newlines), so a no-op render reproduces the - file byte-for-byte and only the objects we actually edited (playlists - AND/OR track entries) diff. Verified by backend/test_save_fidelity.py. - """ - s = XmlSerializer().render(self._nml) - s = restore_traktor_float_format(s, self._nml) - s = format_traktor_layout(s) - return s.encode("utf-8") +sys.modules[__name__] = _moved diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index 19c7158..e39bf56 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -4,89 +4,6 @@ from __future__ import annotations from pydantic import BaseModel, ConfigDict, Field -class Track(BaseModel): - """A single track, flattened from a Traktor collection ENTRY.""" - - id: str # primary key: "", used to join playlist entries - 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 - bpm: float | None = None - key: str | None = None # Traktor display key, e.g. "10m" - rating: int = 0 # 0-5 stars (derived from RANKING/51) - playcount: int | None = None - length: int | None = None # seconds - bitrate: int | None = None - 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 - has_grid: bool = False - grid_markers: int = 0 # >1 = a flexible (multi-tempo) beatgrid - is_stem: bool = False # a Stem file ( child) vs a normal audio track - - -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 — either a FOLDER or a PLAYLIST/SMARTLIST.""" - - id: str # stable synthetic id ("pl-" / "fld-") - name: str - type: str # "FOLDER" | "PLAYLIST" | "SMARTLIST" - uuid: str | None = None - count: int = 0 # track count (for playlists) - children: list["PlaylistNode"] = [] - - -PlaylistNode.model_rebuild() - - -# ---- write request bodies ---- - - class CreatePlaylist(BaseModel): name: str parent_id: str | None = None # folder id ("fld:..."); None = root @@ -126,36 +43,6 @@ class HistoryEntry(BaseModel): summary: str # human-readable edit summary -class CuePoint(BaseModel): - name: str | None = None - type: int # Traktor: 0 cue, 1 fade-in, 2 fade-out, 3 load, 4 grid, 5 loop - start: float # seconds - length: float # seconds (>0 for loops) - hotcue: int # -1 if not assigned to a hotcue slot - color: str | None = None # "#RRGGBB" if set - # Index of the grid marker this cue is the companion of, if any. Such a cue - # holds a real hotcue slot but belongs to the beatgrid and is not editable. - 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] = [] - locked: bool = False # Traktor LOCK flag - cues: list[CuePoint] = [] # cue/loop markers (grid markers themselves excluded) - - class AddGridMarker(BaseModel): track_id: str start: float # seconds @@ -188,14 +75,6 @@ class SetHotcue(BaseModel): name: str | None = None # cue label; defaults to Traktor's "n.n." when unset -class AutoHotcue(BaseModel): - slot: int # 0–7 - start: float # seconds - name: str | None = None # positional label (e.g. "Drop") - type: int = 0 # plain cue - length: float = 0.0 # seconds (>0 for a loop hotcue) - - class AutoHotcuesRequest(BaseModel): track_id: str max_cues: int | None = None # defaults to MAX_HOTCUES (8) server-side @@ -269,30 +148,26 @@ class PathMappingInfo(BaseModel): to: str = "" -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] = [] - - class RemapResult(BaseModel): rewritten: int # tracks whose LOCATION was rewritten commit: str | None = None # sha of the version-history commit for the rewrite -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 +# The generic model lives in core.model; re-exported here so the HTTP layer has +# one import site. The dependency runs schemas -> core, never the reverse. +from .core.model import ( # noqa: E402,F401 + AutoHotcue, + CuePoint, + Facets, + GenreCount, + GridMarker, + PlaylistNode, + PrefixGroup, + PrefixSuggestions, + RemapPreview, + RemapSample, + Stats, + Track, + TrackCues, + TrackPage, +) diff --git a/backend/run_tests.sh b/backend/run_tests.sh index b0b6d48..8609201 100755 --- a/backend/run_tests.sh +++ b/backend/run_tests.sh @@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")" source .venv/bin/activate fail=0 -for t in test_save_fidelity.py test_phase3.py test_history.py; do +for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_phase3.py test_history.py; do echo "──────────────────────────────────────────" echo "▶ $t" echo "──────────────────────────────────────────" diff --git a/backend/test_layering.py b/backend/test_layering.py new file mode 100644 index 0000000..cd63d16 --- /dev/null +++ b/backend/test_layering.py @@ -0,0 +1,50 @@ +"""Layering guard: `core` must not know any platform exists. + +The whole value of the adapter split is that `konduktor.core` can be read as the +contract a future Rekordbox or Serato adapter is written against. One stray +import of a native type would quietly make it Traktor-shaped again, and nothing +else in the suite would notice. +""" +import ast +import sys +from pathlib import Path + +CORE = Path(__file__).resolve().parent / "konduktor" / "core" +FORBIDDEN = ("traktor_nml_utils", "konduktor.adapters", "xsdata") + +failed = False + + +def check(label, cond, detail=""): + global failed + print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else "")) + if not cond: + failed = True + + +print("== core/ imports nothing platform-specific ==") +offences: list[str] = [] +for src in sorted(CORE.rglob("*.py")): + tree = ast.parse(src.read_text()) + for node in ast.walk(tree): + names: list[str] = [] + if isinstance(node, ast.Import): + names = [a.name for a in node.names] + elif isinstance(node, ast.ImportFrom): + # level > 0 is a relative import; ".." from core/ reaches konduktor, + # which is allowed (paths, prefs), but "...adapters" is not. + names = [node.module or ""] + if node.level and "adapters" in (node.module or ""): + offences.append(f"{src.name}: relative import of {node.module}") + for n in names: + if any(n == f or n.startswith(f + ".") for f in FORBIDDEN): + offences.append(f"{src.name}: {n}") + +check("no core module imports a native library type", not offences, "; ".join(offences)) + +print("== adapters own their native model ==") +store = (CORE.parent / "adapters" / "traktor" / "store.py").read_text() +check("the Traktor store is where traktor_nml_utils lives", "traktor_nml_utils" in store) + +print("\nRESULT:", "FAILED" if failed else "ALL PASSED") +sys.exit(1 if failed else 0) diff --git a/backend/test_save_fidelity.py b/backend/test_save_fidelity.py index c5863a5..5a4de1c 100644 --- a/backend/test_save_fidelity.py +++ b/backend/test_save_fidelity.py @@ -30,7 +30,6 @@ os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-fidelity-a REAL = Path(__file__).resolve().parents[1] / "collection.nml" -from konduktor.collection_service import CollectionService # noqa: E402 from konduktor.playlist_store import PlaylistError, PlaylistStore # noqa: E402 failed = False @@ -92,7 +91,6 @@ with tempfile.TemporaryDirectory() as d: shutil.copy2(REAL, work) original = work.read_bytes() - svc = CollectionService(work) store = PlaylistStore(work) def walk(n): @@ -107,7 +105,7 @@ with tempfile.TemporaryDirectory() as d: uuid = target.playlist.uuid keys = store.entry_keys(uuid) - store.set_entries(uuid, svc.entries_for(list(reversed(keys)))) + store.set_entries(uuid, store.entries_for(list(reversed(keys)))) store.save() edited = work.read_bytes() diff --git a/backend/test_traktor_adapter.py b/backend/test_traktor_adapter.py new file mode 100644 index 0000000..9d730c8 --- /dev/null +++ b/backend/test_traktor_adapter.py @@ -0,0 +1,191 @@ +"""Tests for the generic adapter layer. + +`test_save_fidelity.py` exercises the Traktor STORE and the bytes it writes; +nothing there touches the projection. Without this file the entire generic layer +— the single parse, the index refresh after each command, the cue-type +translation, capabilities — would be untested by the suite that gates saves. + +Runs against a temp copy of the real collection, like the other suites. +""" +import os +import shutil +import sys +import tempfile +import warnings +from pathlib import Path + +warnings.filterwarnings("ignore") +os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-adapter-appdata-") + +REAL = Path(__file__).resolve().parents[1] / "collection.nml" + +import traktor_nml_utils as tnu # noqa: E402 + +from konduktor.adapters.traktor.adapter import TraktorAdapter # noqa: E402 +from konduktor.core.adapter import LibraryAdapter, Unsupported # noqa: E402 +from konduktor.core.model import AutoHotcue # noqa: E402 +from konduktor.core.pathmap import PathMapping # noqa: E402 + +failed = False + + +def check(label, cond, detail=""): + global failed + print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else "")) + if not cond: + failed = True + + +# ---- opening: exactly one parse --------------------------------------- +print("== opening a library parses it exactly once ==") +with tempfile.TemporaryDirectory() as d: + work = Path(d) / "collection.nml" + shutil.copy2(REAL, work) + + parses = {"n": 0} + original_init = tnu.TraktorCollection.__init__ + + def counting_init(self, *a, **kw): + parses["n"] += 1 + return original_init(self, *a, **kw) + + tnu.TraktorCollection.__init__ = counting_init + try: + adapter = TraktorAdapter(work) + finally: + tnu.TraktorCollection.__init__ = original_init + + # The whole point of collapsing the read model into the adapter: the 14MB + # file used to be parsed twice into two graphs that could drift apart. + check("parsed once, not twice", parses["n"] == 1, f"{parses['n']} parses") + check("projection is populated", len(adapter.tracks) == 8485, str(len(adapter.tracks))) + check("primary-key index agrees with the list", len(adapter.by_key) > 8000) + check("implements the LibraryAdapter protocol", isinstance(adapter, LibraryAdapter)) + + # runtime_checkable only verifies method PRESENCE, so check a signature too. + import inspect + + sig = inspect.signature(adapter.set_cue) + check( + "set_cue takes the generic cue vocabulary", + {"slot", "start_sec", "cue_type", "role"} <= set(sig.parameters), + str(list(sig.parameters)), + ) + +# ---- capabilities ------------------------------------------------------- +print("== capabilities describe Traktor, not an assumed floor ==") +with tempfile.TemporaryDirectory() as d: + work = Path(d) / "collection.nml" + shutil.copy2(REAL, work) + adapter = TraktorAdapter(work) + caps = adapter.capabilities() + check("platform reported", caps.platform == "traktor") + check("version read from the NML header", caps.version == "20", str(caps.version)) + check("8 hotcue slots", caps.cues.hotcue_slots == 8) + check("no memory cues on Traktor", caps.cues.memory_cues is False) + check("loops are a cue type, not a separate bank", caps.cues.loops == "cue_type") + check("flexible beatgrids supported", caps.grid.flexible is True) + check("grid is lockable", caps.grid.lockable is True) + check("save facts present for the UI to compose copy from", + caps.save.app_name == "Traktor" and caps.save.overwrite_risk == "on_exit") + +# ---- commands refresh the projection ------------------------------------ +print("== every command refreshes the read projection ==") +with tempfile.TemporaryDirectory() as d: + work = Path(d) / "collection.nml" + shutil.copy2(REAL, work) + adapter = TraktorAdapter(work) + + # metadata + tid = next(t.id for t in adapter.tracks if t.title) + adapter.set_track_metadata(tid, {"genre": "Konduktor Test Genre"}) + check("metadata edit is visible in the projection", + adapter.track(tid).genre == "Konduktor Test Genre") + + # cues — a free slot on a track with a grid, so the companion guard is clear + tid2 = next( + t.id for t in adapter.tracks + if t.has_grid and (cues := adapter.track_cues(t.id)) + and len({c.hotcue for c in cues.cues if c.hotcue >= 0}) < 7 + ) + before = adapter.track(tid2).hotcue_count + used = {c.hotcue for c in adapter.track_cues(tid2).cues if c.hotcue >= 0} + free = next(s for s in range(8) if s not in used) + fresh = adapter.set_cue(tid2, slot=free, start_sec=12.5, cue_type="cue") + check("set_cue returns fresh cues", any(c.hotcue == free for c in fresh.cues)) + check("hotcue count in the projection incremented", + adapter.track(tid2).hotcue_count == before + 1) + + # cue type translation, both directions + adapter.set_cue_type(tid2, free, "load") + check("generic cue type maps to Traktor's encoding", + next(c.type for c in adapter.track_cues(tid2).cues if c.hotcue == free) == 3) + try: + adapter.set_cue(tid2, slot=free, start_sec=1.0, cue_type="cue", role="memory") + check("memory cues are refused on Traktor", False, "no error raised") + except Unsupported: + check("memory cues are refused on Traktor", True) + + # grid + grid_before = len(adapter.track_cues(tid2).grid_markers) + adapter.add_grid_marker(tid2, adapter.track_cues(tid2).grid_markers[0].start + 40.0) + check("grid marker added and projected", + len(adapter.track_cues(tid2).grid_markers) == grid_before + 1) + check("marker count reached the track projection", + adapter.track(tid2).grid_markers == grid_before + 1) + +# ---- analysed grid vs plain replace -------------------------------------- +print("== set_analysed_grid writes Traktor's own shape, replace_grid does not ==") +with tempfile.TemporaryDirectory() as d: + work = Path(d) / "collection.nml" + shutil.copy2(REAL, work) + adapter = TraktorAdapter(work) + tid = next(t.id for t in adapter.tracks if t.has_grid) + + cues = adapter.replace_grid(tid, [(1.0, 128.0)]) + check("replace_grid sets exactly the markers given", len(cues.grid_markers) == 1) + check("replace_grid creates no companion cue", cues.grid_markers[0].companion is None) + + cues = adapter.set_analysed_grid(tid, [(1.0, 128.0)]) + check("set_analysed_grid pairs the marker with a companion", + cues.grid_markers[0].companion is not None) + +# ---- remap rebuilds the index (track ids change) -------------------------- +print("== a path remap rebuilds the projection, because track ids change ==") +with tempfile.TemporaryDirectory() as d: + work = Path(d) / "collection.nml" + shutil.copy2(REAL, work) + adapter = TraktorAdapter(work) + + # Use the adapter's own suggestion: the remap matches RESOLVED OS paths, + # which is not the same string as Track.filepath (a display path). + prefix = adapter.path_prefix_suggestions()["primary"] + matched = { + t.id + for t in adapter.tracks + if (ap := adapter.audio_path(t.id)) and str(ap).startswith(prefix) + } + old_id = next(iter(matched)) + n = adapter.remap_locations(PathMapping.make(prefix, "/Volumes/KonduktorTest")) + check("remap rewrote some locations", n > 0, str(n)) + check("the old track id is gone from the index", adapter.track(old_id) is None) + check("the index still holds every track", len(adapter.tracks) == 8485) + +# ---- place_cues takes the generic spec ------------------------------------ +print("== batch cue placement takes a typed spec ==") +with tempfile.TemporaryDirectory() as d: + work = Path(d) / "collection.nml" + shutil.copy2(REAL, work) + adapter = TraktorAdapter(work) + tid = next( + t.id for t in adapter.tracks + if len({c.hotcue for c in adapter.track_cues(t.id).cues if c.hotcue >= 0}) < 6 + ) + used = {c.hotcue for c in adapter.track_cues(tid).cues if c.hotcue >= 0} + free = [s for s in range(8) if s not in used][:2] + adapter.place_cues(tid, [AutoHotcue(slot=free[0], start=30.0, name="Drop")]) + placed = next((c for c in adapter.track_cues(tid).cues if c.hotcue == free[0]), None) + check("batch-placed cue exists with its name", placed is not None and placed.name == "Drop") + +print("\nRESULT:", "FAILED" if failed else "ALL PASSED") +sys.exit(1 if failed else 0) From c9e85bbdb50deab7fa5fdf34e51ca76117c8ced6 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Thu, 17 Sep 2026 17:30:36 +0200 Subject: [PATCH 04/64] Updated backend --- CLAUDE.md | 95 +++-- backend/konduktor/adapters/__init__.py | 3 + .../konduktor/adapters/traktor/__init__.py | 11 +- backend/konduktor/adapters/traktor/adapter.py | 14 +- backend/konduktor/adapters/traktor/driver.py | 40 ++ backend/konduktor/adapters/traktor/store.py | 24 +- backend/konduktor/app_state.py | 75 ++++ backend/konduktor/auto_hotcues.py | 11 - backend/konduktor/beatgrid.py | 11 - backend/konduktor/core/registry.py | 61 +++ backend/konduktor/discovery.py | 11 - backend/konduktor/file_tags.py | 17 - backend/konduktor/history.py | 49 ++- backend/konduktor/main.py | 373 +++++++----------- backend/konduktor/path_mapping.py | 10 - backend/konduktor/playlist_store.py | 11 - backend/test_save_fidelity.py | 59 +-- 17 files changed, 497 insertions(+), 378 deletions(-) create mode 100644 backend/konduktor/adapters/traktor/driver.py create mode 100644 backend/konduktor/app_state.py delete mode 100644 backend/konduktor/auto_hotcues.py delete mode 100644 backend/konduktor/beatgrid.py create mode 100644 backend/konduktor/core/registry.py delete mode 100644 backend/konduktor/discovery.py delete mode 100644 backend/konduktor/file_tags.py delete mode 100644 backend/konduktor/path_mapping.py delete mode 100644 backend/konduktor/playlist_store.py diff --git a/CLAUDE.md b/CLAUDE.md index d3931c6..19e0044 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -16,34 +16,61 @@ given a mobile version. Two independent apps that talk over HTTP: -- **`backend/`** — Python + FastAPI. Parses `collection.nml` via - `traktor-nml-utils` and serves a query + edit API. Entry point: +- **`backend/`** — Python + FastAPI. Entry point: [backend/konduktor/main.py](backend/konduktor/main.py). - - `collection_service.py` — the **read** model: loads the NML, flattens ENTRYs - into `Track` objects, indexes them by primary key. All query logic - (filter/sort/facets/stats) lives here. `replace_track()` refreshes one - projection after an edit (bridges the read model and the edit store). - - `playlist_store.py` (`PlaylistStore`) — the **edit** model: owns the parsed - dataclass NML and applies all edits (playlists, track metadata, cover art, - AND track-prep edits: hotcues/cues, beatgrid/BPM, lock), then renders + - saves. See "Write path" below. - - `file_tags.py` — reads/writes embedded audio-file tags & cover art (mutagen) - and resolves Traktor `LOCATION`s to OS paths. Best-effort. - - `discovery.py` — finds Traktor collections in their default install location - (`~/Documents/Native Instruments/Traktor /collection.nml`) for the - picker's "Automatic" option; sorts newest Traktor version first. - - `prefs.py` — tiny persisted user-prefs store in `userprefs.json` (resolved - relative to the package so it travels with the app; gitignored). Holds the - last-opened collection path, the library column layout, and the prep deck's - main-waveform zoom (`mainZoomSec`). Best-effort I/O. - - `schemas.py` — Pydantic response/request models. - - `main.py` — FastAPI routes (all under `/api`). Holds an `AppState` with the - currently-loaded collection; it starts **unloaded** and the collection is - chosen at runtime via `POST /api/collection/open` (data routes 409 until - then). `GET /api/fs/list` powers the in-app file browser; - `GET /api/collection/options` feeds the picker's auto-detect + last-opened - shortcuts; `GET`/`PATCH /api/prefs` persist UI prefs. Setting `KONDUKTOR_NML` - auto-loads on startup (dev/tests). + + **Architecture: projection + command replay.** The generic model is a *read + projection*; edits are strictly-generic commands that a per-platform **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 the only model that works for formats you cannot + regenerate (a Rekordbox SQLite row, a Serato tag inside an audio file). Traktor + is currently the only adapter; see `.claude/discussions/` for the decision log. + + - `core/` — **platform-independent. Must not import `traktor_nml_utils` or + `konduktor.adapters`** (`test_layering.py` enforces this). This is the + contract a Rekordbox or Serato adapter will be written against. + - `model.py` — the generic model (`Track`, `CuePoint`, `GridMarker`, + `TrackCues`, `PlaylistNode`, `Facets`, `Stats`, …). Served straight to HTTP. + - `adapter.py` — the `LibraryAdapter` / `LibraryDriver` protocols and the + error tree (`NotFound` → 404, `InvalidCommand` → 400, `Unsupported` → 422), + mapped to status codes once in `main.py` rather than per route. + - `capabilities.py` — `Capabilities`: what the loaded library can persist, so + the UI can gate controls instead of branching on the platform. + - `query.py` (`TrackIndex`) — all query/filter/sort/facet/stats logic, over + generic `Track`s. Shared so "sort by artist" cannot mean different things + on different platforms behind one UI. + - `edit_journal.py` (`EditJournal`) — every edit this session at **field + resolution** (`track/set/genre`, `cue/add/slot:1`, `grid/marker-bpm/marker:0`). + Drives the file-tag sync, the version-history message, and `retarget()` + when a path remap changes track ids. Recording `before` keeps undo cheap later. + - `registry.py` — adapter selection by **`can_open()` probe**, not extension + (Rekordbox is a `.db`, Serato is a directory). + - `audio_tags.py`, `pathmap.py`, `auto_hotcues.py` — format-agnostic helpers. + - `adapters/traktor/` — everything that knows NML exists. + - `store.py` (`TraktorStore`) — the retained native model: owns the parsed + dataclass NML, applies every edit, renders + saves. See "Write path". + - `adapter.py` (`TraktorAdapter`) — owns the store **and** the `TrackIndex` + built from it, so projection and native model cannot drift. Translates the + generic cue vocabulary to Traktor's integers (the only place that mapping + exists). **Every mutating command returns its refreshed projection** — a + forgotten refresh would be a silently stale UI no byte test would catch. + - `projection.py` — native → generic (`to_track`, `to_track_cues`). + - `driver.py`/`discovery.py` — `can_open`, default-location detection, restore. + - `beatgrid.py`, `locations.py`, `capabilities.py` — Traktor's grid/companion + rules, LOCATION ↔ OS path conversion, and its capability set. + - `app_state.py` — the one loaded library, and the **version-history commit**. + History is app-level: the adapter returns the bytes it wrote plus a summary, + and `AppState.save()` versions them. Every write path must go through it. + - `prefs.py` — persisted user prefs (`userprefs.json` in the per-OS app-data + dir). Last-opened collection, library column layout, prep-deck zoom. Best-effort. + - `schemas.py` — HTTP request bodies + envelopes; re-exports `core.model`. + - `main.py` — thin FastAPI routes (all under `/api`), talking only to the + adapter. Starts **unloaded**; the library is chosen at runtime via + `POST /api/collection/open` (data routes 409 until then). + `GET /api/capabilities` feeds the UI's gating; `GET /api/fs/list` powers the + file browser; `GET`/`PATCH /api/prefs` persist UI prefs. Setting + `KONDUKTOR_NML` auto-loads on startup (dev/tests). - **`frontend/`** — React + TypeScript + Vite. A dark, virtualized track explorer. Entry: [frontend/src/App.tsx](frontend/src/App.tsx). - `api.ts` — typed client + all API types (keep in sync with backend @@ -129,6 +156,11 @@ serialization path.** It enforces: The guard that catches serialization regressions like the lxml reformatting bug. - `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays Traktor-valid, backup-first, COLLECTION byte-identical, original untouched. +- `test_traktor_adapter.py` — the **generic layer**: one parse per open, the + projection refreshing after every command family, cue-type translation, + capabilities, and `set_analysed_grid` vs `replace_grid`. `test_save_fidelity` + covers the store and its bytes; without this the adapter layer would be untested. +- `test_layering.py` — `core/` imports nothing platform-specific. Also validate the backend interactively at `http://localhost:8000/docs` and the frontend at `http://localhost:5173`. @@ -231,6 +263,10 @@ that number and nothing else — everything derives from it: - ✅ Flexible beatgrids — the grid is a marker list end to end (marker-level commands, piecewise beat math, playhead-derived marker editing). Step 1 of the multi-platform plan in `.claude/discussions/`. +- ✅ Generic model + adapter interface (Traktor as the only adapter) — step 2 of + the multi-platform plan. Backend done; the wire format and UI are still + Traktor-shaped (cue type integers, 8 hard-coded hotcue slots) and are next. +- ⬜ Rekordbox adapter; ⬜ Serato adapter; ⬜ export/conversion - ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging ## Write path (playlists + track metadata + prep) @@ -259,7 +295,10 @@ diff — no COLLECTION splicing needed. `set_hotcue(track_id, slot, start_sec, type, length_sec)` creates/replaces a `CUE_V2` (types 0 cue, 1 fade-in, 2 fade-out, 3 load, 5 loop; START/LEN stored in **ms**; a loop hotcue carries LEN); `set_hotcue_type` changes just the type; - `delete_hotcue` removes a slot. Hotcue commands **refuse a slot held by a grid + `delete_hotcue` removes a slot. (The adapter exposes these generically as + `set_cue`/`set_cue_type`/`delete_cue`, taking a `cue_type` STRING — `cue`, + `fade_in`, `fade_out`, `load`, `loop` — which the Traktor adapter maps to the + integers below.) Hotcue commands **refuse a slot held by a grid marker's companion cue** (see "Beatgrid"). Beatgrid commands are marker-level: `add_grid_marker` (inherits the governing tempo when no BPM is given), `move_grid_marker` (clamped between its neighbours, drags the companion), diff --git a/backend/konduktor/adapters/__init__.py b/backend/konduktor/adapters/__init__.py index 8c7d8a9..28daab3 100644 --- a/backend/konduktor/adapters/__init__.py +++ b/backend/konduktor/adapters/__init__.py @@ -1,3 +1,6 @@ """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. """ +from . import traktor # noqa: F401 — registers the Traktor driver diff --git a/backend/konduktor/adapters/traktor/__init__.py b/backend/konduktor/adapters/traktor/__init__.py index 1fb1975..7d3a1d8 100644 --- a/backend/konduktor/adapters/traktor/__init__.py +++ b/backend/konduktor/adapters/traktor/__init__.py @@ -1 +1,10 @@ -"""The Traktor adapter: NML v20 (Traktor Pro 4) via ``traktor-nml-utils``.""" +"""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. +""" +from ...core import registry +from .driver import TraktorDriver + +TRAKTOR = TraktorDriver() +registry.register(TRAKTOR) diff --git a/backend/konduktor/adapters/traktor/adapter.py b/backend/konduktor/adapters/traktor/adapter.py index 004751e..0c6267c 100644 --- a/backend/konduktor/adapters/traktor/adapter.py +++ b/backend/konduktor/adapters/traktor/adapter.py @@ -2,7 +2,7 @@ This is the object the app talks to. It holds: - * a ``PlaylistStore`` — the retained NATIVE model, which is the write target. + * 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. @@ -21,12 +21,13 @@ from ...core.pathmap import PathMapping from ...core.query import TrackIndex from . import capabilities as caps from . import projection -from .store import PlaylistError, PlaylistStore +from .store import PlaylistError, TraktorStore # Generic cue vocabulary -> Traktor's CUE_V2 TYPE encoding. This table is the # only place the integers exist outside the store; type 4 is a grid marker and # is never a cue, so it has no generic name. 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()} class TraktorAdapter: @@ -34,7 +35,7 @@ class TraktorAdapter: def __init__(self, path: Path): self.path = Path(path) - self._store = PlaylistStore(self.path) + self._store = TraktorStore(self.path) self._index = TrackIndex() self._rebuild() @@ -81,7 +82,7 @@ class TraktorAdapter: # 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) -> PlaylistStore: + def store(self) -> TraktorStore: return self._store def entries_for(self, track_ids: list[str]) -> list[tuple[str, str]]: @@ -94,8 +95,11 @@ class TraktorAdapter: 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(PlaylistStore.EDITABLE_FIELDS)) + return caps.capabilities_for(self.path, sorted(TraktorStore.EDITABLE_FIELDS)) # ---- playlists ------------------------------------------------------- def playlist_tree(self) -> list[PlaylistNode]: diff --git a/backend/konduktor/adapters/traktor/driver.py b/backend/konduktor/adapters/traktor/driver.py new file mode 100644 index 0000000..27bbd78 --- /dev/null +++ b/backend/konduktor/adapters/traktor/driver.py @@ -0,0 +1,40 @@ +"""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" + + 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" str: """Delegates to the journal; kept as a method because save() and the diff --git a/backend/konduktor/app_state.py b/backend/konduktor/app_state.py new file mode 100644 index 0000000..455979c --- /dev/null +++ b/backend/konduktor/app_state.py @@ -0,0 +1,75 @@ +"""The one loaded library, and the version-history bookkeeping around saving it. + +Exactly one library is open 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. + +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 +from pathlib import Path + +from . import __version__, adapters, history, prefs # noqa: F401 — registers adapters +from .core import registry +from .core.adapter import LibraryAdapter +from .core.pathmap import PathMapping + + +class AppState: + """Holds the currently-loaded library (selectable at runtime).""" + + def __init__(self) -> None: + self.path: Path | None = None + self.adapter: LibraryAdapter | None = None + + @property + def loaded(self) -> bool: + return self.adapter is not None + + 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) + # 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 + # 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 + outcome = self.adapter.save() + commit = history.commit( + self.path, outcome.snapshot, outcome.summary, __version__ + ) + return outcome, commit + + +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 diff --git a/backend/konduktor/auto_hotcues.py b/backend/konduktor/auto_hotcues.py deleted file mode 100644 index cf23e33..0000000 --- a/backend/konduktor/auto_hotcues.py +++ /dev/null @@ -1,11 +0,0 @@ -"""Compatibility shim — this module moved to ``konduktor.core.auto_hotcues``. - -Kept so the existing test suite keeps importing the old path unchanged while the -adapter refactor lands; removed in the final cleanup step. Replacing the entry in -``sys.modules`` makes this module *be* the new one, so private names resolve too. -""" -import sys - -from .core import auto_hotcues as _moved - -sys.modules[__name__] = _moved diff --git a/backend/konduktor/beatgrid.py b/backend/konduktor/beatgrid.py deleted file mode 100644 index 3d53c56..0000000 --- a/backend/konduktor/beatgrid.py +++ /dev/null @@ -1,11 +0,0 @@ -"""Compatibility shim — this module moved to ``konduktor.adapters.traktor.beatgrid``. - -Kept so the existing test suite keeps importing the old path unchanged while the -adapter refactor lands; removed in the final cleanup step. Replacing the entry in -``sys.modules`` makes this module *be* the new one, so private names resolve too. -""" -import sys - -from .adapters.traktor import beatgrid as _moved - -sys.modules[__name__] = _moved diff --git a/backend/konduktor/core/registry.py b/backend/konduktor/core/registry.py new file mode 100644 index 0000000..7bd42ed --- /dev/null +++ b/backend/konduktor/core/registry.py @@ -0,0 +1,61 @@ +"""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_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 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() -> tuple[str, ...]: + """File extensions the in-app browser should show, across all platforms.""" + seen: list[str] = [] + for d in _DRIVERS: + for suffix in d.suffixes: + if suffix not in seen: + seen.append(suffix) + return tuple(seen) diff --git a/backend/konduktor/discovery.py b/backend/konduktor/discovery.py deleted file mode 100644 index eba5dfe..0000000 --- a/backend/konduktor/discovery.py +++ /dev/null @@ -1,11 +0,0 @@ -"""Compatibility shim — this module moved to ``konduktor.adapters.traktor.discovery``. - -Kept so the existing test suite keeps importing the old path unchanged while the -adapter refactor lands; removed in the final cleanup step. Replacing the entry in -``sys.modules`` makes this module *be* the new one, so private names resolve too. -""" -import sys - -from .adapters.traktor import discovery as _moved - -sys.modules[__name__] = _moved diff --git a/backend/konduktor/file_tags.py b/backend/konduktor/file_tags.py deleted file mode 100644 index 11e34ea..0000000 --- a/backend/konduktor/file_tags.py +++ /dev/null @@ -1,17 +0,0 @@ -"""Compatibility shim — this module was split. - -The mutagen read/write half is format-agnostic and moved to -``konduktor.core.audio_tags``; ``resolve_path`` encodes Traktor's LOCATION -convention and moved to ``konduktor.adapters.traktor.locations``. Kept so the -existing test suite keeps importing the old path unchanged; removed in the final -cleanup step. -""" -from .adapters.traktor.locations import resolve_path # noqa: F401 -from .core.audio_tags import ( # noqa: F401 - DEFAULT_POPM_EMAIL, - TagMeta, - TagResult, - read_cover, - write_cover, - write_tags, -) diff --git a/backend/konduktor/history.py b/backend/konduktor/history.py index 451c1b0..22e73ce 100644 --- a/backend/konduktor/history.py +++ b/backend/konduktor/history.py @@ -10,7 +10,7 @@ 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 a fixed name inside each repo (``collection.nml``); the + * 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). @@ -32,7 +32,17 @@ from . import paths log = logging.getLogger(__name__) -_TRACKED_NAME = "collection.nml" +_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 " @@ -53,8 +63,8 @@ def _repo_dir(nml_path: Path) -> Path: return paths.app_data_dir() / "history" / _key(nml_path) -def _tracked_file(repo_dir: Path) -> Path: - return repo_dir / _TRACKED_NAME +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: @@ -77,7 +87,25 @@ def _open_or_init(nml_path: Path) -> Path: return repo_dir -def _head_blob(repo: Repo) -> bytes | None: +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() @@ -85,7 +113,10 @@ def _head_blob(repo: Repo) -> bytes | None: return None commit = repo[head] tree = repo[commit.tree] - _mode, blob_sha = tree[_TRACKED_NAME.encode()] + try: + _mode, blob_sha = _tree_blob(tree, nml_path) + except KeyError: + return None return repo[blob_sha].data @@ -98,9 +129,9 @@ def commit(nml_path: Path, data: bytes, message: str, app_version: str) -> str | try: repo_dir = _open_or_init(nml_path) with Repo(str(repo_dir)) as repo: - if _head_blob(repo) == data: + if _head_blob(repo, nml_path) == data: return None # nothing changed since last version - path = _tracked_file(repo_dir) + 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() @@ -153,7 +184,7 @@ def read_version(nml_path: Path, commit_id: str) -> bytes | None: with Repo(str(repo_dir)) as repo: c = repo[commit_id.encode()] tree = repo[c.tree] - _mode, blob_sha = tree[_TRACKED_NAME.encode()] + _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) diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index dd44eae..d3b9300 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -11,16 +11,24 @@ from pathlib import Path from fastapi import FastAPI, File, Form, HTTPException, Query, Response, UploadFile from fastapi.middleware.cors import CORSMiddleware -from fastapi.responses import FileResponse +from fastapi.responses import FileResponse, JSONResponse -from . import __version__ -from .adapters.traktor import projection +from . import __version__, history, prefs +from .adapters.traktor.adapter import NATIVE_TO_CUE_TYPE +from .adapters.traktor.discovery import describe +from .app_state import STATE from .core import auto_hotcues as ah -from . import history, prefs -from .adapters.traktor.adapter import TraktorAdapter -from .adapters.traktor.discovery import describe, detect_collections +from .core import registry +from .core.adapter import ( + AdapterError, + InvalidCommand, + LibraryAdapter, + LibraryNotSupported, + NotFound, + Unsupported, +) +from .core.capabilities import Capabilities from .core.pathmap import PathMapping -from .adapters.traktor.store import PlaylistError, PlaylistStore from .schemas import ( AutoGridRequest, AutoHotcue, @@ -29,7 +37,6 @@ from .schemas import ( CollectionOptions, CollectionStatus, CreatePlaylist, - CuePoint, EditState, EditTrack, Facets, @@ -37,7 +44,6 @@ from .schemas import ( FsEntry, FsListing, AddGridMarker, - GridMarker, GridMarkerEdit, ReplaceGrid, HistoryEntry, @@ -76,56 +82,37 @@ app.add_middleware( ) -class AppState: - """Holds the currently-loaded collection (selectable at runtime).""" +def _cue_type_name(native: int) -> str: + """Map the wire's Traktor cue integer onto the generic vocabulary. - def __init__(self) -> None: - self.path: Path | None = None - self.adapter: TraktorAdapter | None = None - - @property - def loaded(self) -> bool: - return self.adapter is not None - - def open(self, path: Path) -> None: - # Raises on an invalid/parse-incompatible file; only commit to the new - # collection once it has parsed. One parse — the adapter builds its read - # projection from the same object graph the commands mutate. - adapter = TraktorAdapter(path) - # Apply this collection's saved OS-path remapping (per-machine, keyed by - # the collection's local path) so runtime translation is live on open. - saved = prefs.get_path_mapping(str(path)) - if saved: - adapter.store.set_path_mapping(PathMapping.make(saved["from"], saved["to"])) - self.path, self.adapter = path, adapter - # Version history: record an "as I found it" baseline (deduped, so - # re-opening an unchanged collection is a no-op). Best-effort. - history.ensure_baseline(path) + Transitional: the HTTP contract still carries Traktor's encoding, so the + translation happens here at the boundary rather than in the adapter. + """ + name = NATIVE_TO_CUE_TYPE.get(native) + if name is None: + raise HTTPException(400, f"Unsupported cue type: {native}") + return name -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 - - -def require_service() -> TraktorAdapter: +def require_adapter() -> LibraryAdapter: + """The loaded library, or a 409. Routes talk to this and nothing else.""" if not STATE.loaded: raise HTTPException(409, "No collection loaded") assert STATE.adapter is not None return STATE.adapter -def require_store() -> PlaylistStore: - if not STATE.loaded: - raise HTTPException(409, "No collection loaded") - assert STATE.adapter is not None - return STATE.adapter.store +@app.exception_handler(AdapterError) +def _adapter_error(_request, exc: AdapterError): + """Map the adapter's error vocabulary onto status codes in one place, so no + route has to guess whether a given failure is a 400 or a 404.""" + status = { + NotFound: 404, + InvalidCommand: 400, + Unsupported: 422, + LibraryNotSupported: 400, + }.get(type(exc), 400) + return JSONResponse(status_code=status, content={"detail": str(exc)}) # ---- collection selection --------------------------------------------- @@ -138,8 +125,8 @@ def collection_status() -> CollectionStatus: return CollectionStatus( loaded=True, path=str(STATE.path), - tracks=len(require_service().tracks), - playlists=require_store().count_playlists(), + tracks=len(require_adapter().tracks), + playlists=require_adapter().playlist_count(), ) @@ -150,10 +137,10 @@ def open_collection(body: OpenCollection) -> CollectionStatus: raise HTTPException(400, f"File not found: {path}") try: STATE.open(path) - except PlaylistError as ex: - raise HTTPException(400, f"Not a valid Traktor collection: {ex}") + except AdapterError as ex: + raise HTTPException(400, f"Not a valid collection: {ex}") except Exception as ex: # noqa: BLE001 - raise HTTPException(400, f"Could not parse as a Traktor collection: {ex}") + raise HTTPException(400, f"Could not open that collection: {ex}") prefs.set_last_collection(str(path)) return collection_status() @@ -162,7 +149,7 @@ def open_collection(body: OpenCollection) -> CollectionStatus: def collection_options() -> CollectionOptions: """Startup shortcuts for the picker: the best auto-detected Traktor collection and the last one opened (may no longer exist → exists=False).""" - detected = detect_collections() + detected = registry.detect_all() auto = CollectionCandidate(**detected[0]) if detected else None recent = None last = prefs.get_last_collection() @@ -174,7 +161,7 @@ def collection_options() -> CollectionOptions: @app.get("/api/collection/path-mapping", response_model=PathMappingInfo) def get_path_mapping() -> PathMappingInfo: """The current collection's saved OS-path remapping (blank if none).""" - require_store() + require_adapter() saved = prefs.get_path_mapping(str(STATE.path)) if saved: return PathMappingInfo.model_validate({"from": saved["from"], "to": saved["to"]}) @@ -186,12 +173,12 @@ def put_path_mapping(body: PathMappingInfo) -> PathMappingInfo: """Set (or, with blank prefixes, clear) the current collection's remapping. Persists to userprefs AND updates the live store so playback/analysis re-resolve immediately — no reopen needed. Never touches the .nml.""" - store = require_store() + a = require_adapter() mapping = PathMapping.make(body.from_, body.to) prefs.set_path_mapping( str(STATE.path), mapping.from_prefix or None, mapping.to_prefix or None ) - store.set_path_mapping(mapping) + a.set_path_mapping(mapping) return PathMappingInfo.model_validate( {"from": mapping.from_prefix, "to": mapping.to_prefix} ) @@ -201,8 +188,7 @@ def put_path_mapping(body: PathMappingInfo) -> PathMappingInfo: def suggest_path_prefix() -> PrefixSuggestions: """Auto-detected `from` prefix candidates (common directory per volume), so the editor can prefill the stored prefix.""" - store = require_store() - return PrefixSuggestions.model_validate(store.path_prefix_suggestions()) + return PrefixSuggestions.model_validate(require_adapter().path_prefix_suggestions()) @app.get("/api/collection/path-mapping/preview", response_model=RemapPreview) @@ -211,8 +197,9 @@ def preview_path_mapping( ) -> RemapPreview: """Validate a candidate mapping before saving/committing: how many tracks match `from` and how many exist at `to`.""" - store = require_store() - return RemapPreview.model_validate(store.remap_preview(PathMapping.make(from_, to))) + return RemapPreview.model_validate( + require_adapter().remap_preview(PathMapping.make(from_, to)) + ) @app.post("/api/collection/remap-paths", response_model=RemapResult) @@ -221,15 +208,16 @@ def remap_paths(body: PathMappingInfo) -> RemapResult: playlist references that join to them) to the `to` prefix, then save (a version-history commit is written). Destructive and OS-specific — the UI warns accordingly.""" - store = require_store() mapping = PathMapping.make(body.from_, body.to) if mapping.empty: raise HTTPException(400, "Both a `from` and `to` prefix are required") - count = store.remap_locations(mapping) + count = require_adapter().remap_locations(mapping) if count == 0: return RemapResult(rewritten=0, commit=None) - outcome = store.save() - return RemapResult(rewritten=count, commit=outcome.commit) + # Through AppState, not the adapter: this is the one route besides /api/save + # that writes, and skipping it would leave a gap in the version history. + _outcome, commit = STATE.save() + return RemapResult(rewritten=count, commit=commit) @app.get("/api/prefs") @@ -260,7 +248,7 @@ def fs_list(path: str | None = None) -> FsListing: try: if entry.is_dir(): dirs.append(FsEntry(name=entry.name, path=str(entry))) - elif entry.suffix.lower() == ".nml": + elif entry.suffix.lower() in registry.browsable_suffixes(): files.append(FsEntry(name=entry.name, path=str(entry))) except OSError: continue @@ -280,10 +268,15 @@ def health() -> dict: return {"status": "ok", "loaded": STATE.loaded, "path": str(STATE.path) if STATE.path else None} +@app.get("/api/capabilities", response_model=Capabilities) +def capabilities() -> Capabilities: + """What the loaded library can persist, so the UI can gate its controls.""" + return require_adapter().capabilities() + + @app.get("/api/state", response_model=EditState) def state() -> EditState: - store = require_store() - return EditState(dirty=store.dirty, nml_path=str(STATE.path)) + return EditState(dirty=require_adapter().dirty, nml_path=str(STATE.path)) @app.post("/api/reload") @@ -291,7 +284,7 @@ def reload_collection() -> dict: if not STATE.loaded: raise HTTPException(409, "No collection loaded") STATE.open(STATE.path) # re-parse current file from disk - return {"status": "reloaded", "tracks": len(require_service().tracks)} + return {"status": "reloaded", "tracks": len(require_adapter().tracks)} # ---- read: stats / facets / tracks ------------------------------------ @@ -299,12 +292,13 @@ def reload_collection() -> dict: @app.get("/api/stats", response_model=Stats) def stats() -> Stats: - return require_service().stats(playlist_count=require_store().count_playlists()) + a = require_adapter() + return a.stats(playlist_count=a.playlist_count()) @app.get("/api/facets", response_model=Facets) def facets() -> Facets: - return require_service().facets() + return require_adapter().facets() @app.get("/api/tracks", response_model=TrackPage) @@ -321,7 +315,7 @@ def tracks( limit: int = Query(100, ge=1, le=20000), offset: int = Query(0, ge=0), ) -> TrackPage: - return require_service().query_tracks( + return require_adapter().query_tracks( q=q, genre=genre, key=key, bpm_min=bpm_min, bpm_max=bpm_max, rating_min=rating_min, has_cues=has_cues, sort=sort, order=order, limit=limit, offset=offset, @@ -333,16 +327,15 @@ def tracks( @app.get("/api/playlists", response_model=list[PlaylistNode]) def playlists() -> list[PlaylistNode]: - return require_store().tree() + return require_adapter().playlist_tree() @app.get("/api/playlists/{playlist_id}/tracks", response_model=list[Track]) def playlist_tracks(playlist_id: str) -> list[Track]: - keys = require_store().entry_keys(playlist_id) - if keys is None: + tracks = require_adapter().playlist_tracks(playlist_id) + if tracks is None: raise HTTPException(404, f"Playlist not found: {playlist_id}") - svc = require_service() - return [svc.by_key[k] for k in keys if k in svc.by_key] + return tracks # ---- write: playlist editing ------------------------------------------ @@ -350,76 +343,54 @@ def playlist_tracks(playlist_id: str) -> list[Track]: @app.post("/api/playlists", response_model=PlaylistNode) def create_playlist(body: CreatePlaylist) -> PlaylistNode: - store = require_store() - try: - new_uuid = store.create_playlist(body.name.strip() or "New Playlist", body.parent_id) - except PlaylistError as ex: - raise HTTPException(400, str(ex)) - return PlaylistNode(id=new_uuid, name=body.name, type="PLAYLIST", uuid=new_uuid, count=0) + new_id = require_adapter().create_playlist( + body.name.strip() or "New Playlist", body.parent_id + ) + return PlaylistNode(id=new_id, name=body.name, type="PLAYLIST", uuid=new_id, count=0) @app.patch("/api/playlists/{playlist_uuid}") def rename_playlist(playlist_uuid: str, body: RenamePlaylist) -> dict: - try: - require_store().rename_playlist(playlist_uuid, body.name.strip()) - except PlaylistError as ex: - raise HTTPException(404, str(ex)) + require_adapter().rename_playlist(playlist_uuid, body.name.strip()) return {"status": "renamed", "id": playlist_uuid, "name": body.name} @app.delete("/api/playlists/{playlist_uuid}") def delete_playlist(playlist_uuid: str) -> dict: - try: - require_store().delete_playlist(playlist_uuid) - except PlaylistError as ex: - raise HTTPException(404, str(ex)) + require_adapter().delete_playlist(playlist_uuid) return {"status": "deleted", "id": playlist_uuid} @app.put("/api/playlists/{playlist_uuid}/entries") def set_entries(playlist_uuid: str, body: SetEntries) -> dict: - store = require_store() - entries = require_service().entries_for(body.track_ids) - try: - store.set_entries(playlist_uuid, entries) - except PlaylistError as ex: - raise HTTPException(404, str(ex)) - return {"status": "updated", "id": playlist_uuid, "count": len(entries)} + n = require_adapter().set_playlist_entries(playlist_uuid, body.track_ids) + return {"status": "updated", "id": playlist_uuid, "count": n} @app.post("/api/playlists/{playlist_uuid}/add") def add_entries(playlist_uuid: str, body: SetEntries) -> dict: """Append tracks to a playlist (skips ids already present).""" - store = require_store() - current = store.entry_keys(playlist_uuid) + a = require_adapter() + current = a.playlist_entries(playlist_uuid) if current is None: raise HTTPException(404, f"Playlist not found: {playlist_uuid}") have = set(current) added = [tid for tid in body.track_ids if tid not in have] - entries = require_service().entries_for(current + added) - store.set_entries(playlist_uuid, entries) - return {"status": "added", "id": playlist_uuid, "added": len(added), "count": len(entries)} + n = a.set_playlist_entries(playlist_uuid, current + added) + return {"status": "added", "id": playlist_uuid, "added": len(added), "count": n} @app.patch("/api/tracks") def edit_track(body: EditTrack) -> dict: """Edit a single track's safe metadata fields (in-memory; persisted on save).""" - store = require_store() - try: - store.set_track_metadata(body.track_id, body.fields) - except PlaylistError as ex: - raise HTTPException(404, str(ex)) - # Keep the read projection in sync so the edit shows immediately. - entry = store.model_entry(body.track_id) - if entry is not None: - require_service().replace_track(body.track_id, entry) + require_adapter().set_track_metadata(body.track_id, body.fields) return {"status": "updated", "id": body.track_id} @app.get("/api/tracks/art") def track_art(track_id: str) -> Response: """Stream a track's embedded cover art (staged replacement if unsaved).""" - art = require_store().cover_art(track_id) + art = require_adapter().cover_art(track_id) if art is None: raise HTTPException(404, "No cover art") data, mime = art @@ -442,7 +413,7 @@ _AUDIO_MIME = { @app.get("/api/tracks/audio") def track_audio(track_id: str) -> FileResponse: """Stream a track's audio file for playback (supports HTTP Range/seeking).""" - path = require_store().audio_path(track_id) + path = require_adapter().audio_path(track_id) if path is None: raise HTTPException(404, "Track not found") if not path.exists(): @@ -454,17 +425,11 @@ def track_audio(track_id: str) -> FileResponse: return FileResponse(path, media_type=mime) -# Compatibility alias — the cue projection moved into the Traktor adapter. -# Kept so test_save_fidelity's invariant K imports the old name unchanged while -# the refactor lands; removed in the final cleanup step. -_build_track_cues = projection.to_track_cues - - def _cues_for(track_id: str) -> TrackCues: - entry = require_store().model_entry(track_id) - if entry is None: + cues = require_adapter().track_cues(track_id) + if cues is None: raise HTTPException(404, "Track not found") - return projection.to_track_cues(entry) + return cues @app.get("/api/tracks/cues", response_model=TrackCues) @@ -473,25 +438,17 @@ def track_cues(track_id: str) -> TrackCues: return _cues_for(track_id) -def _sync_cue_edit(track_id: str) -> TrackCues: - """After a hotcue edit, refresh the read projection and return fresh cues.""" - store = require_store() - entry = store.model_entry(track_id) - if entry is not None: - require_service().replace_track(track_id, entry) - return projection.to_track_cues(entry) if entry is not None else TrackCues() - - @app.post("/api/tracks/hotcue", response_model=TrackCues) def create_hotcue(body: SetHotcue) -> TrackCues: """Create (or reposition + retype) the hotcue in a slot at a position.""" - try: - require_store().set_hotcue( - body.track_id, body.slot, body.start, body.type, body.length, name=body.name - ) - except PlaylistError as ex: - raise HTTPException(400, str(ex)) - return _sync_cue_edit(body.track_id) + return require_adapter().set_cue( + body.track_id, + slot=body.slot, + start_sec=body.start, + cue_type=_cue_type_name(body.type), + length_sec=body.length, + name=body.name, + ) @app.post("/api/tracks/auto-hotcues", response_model=TrackCues) @@ -501,14 +458,13 @@ def auto_hotcues(body: AutoHotcuesRequest) -> TrackCues: Detects section boundaries (librosa Laplacian segmentation), snaps them to the track's beatgrid phrases, names them positionally, and places up to MAX_HOTCUES into empty slots only (never overwrites). Requires a beatgrid.""" - store = require_store() - entry = store.model_entry(body.track_id) - if entry is None: + a = require_adapter() + cues = a.track_cues(body.track_id) + if cues is None: raise HTTPException(404, "Track not found") - cues = projection.to_track_cues(entry) if not cues.grid_markers: raise HTTPException(400, "Set a beatgrid before using Auto Hotcues") - path = store.audio_path(body.track_id) + path = a.audio_path(body.track_id) if path is None or not path.exists(): raise HTTPException(400, "Audio file not found (is the drive mounted?)") @@ -517,8 +473,9 @@ def auto_hotcues(body: AutoHotcuesRequest) -> TrackCues: except Exception as ex: # analysis is best-effort; never 500 the UI raise HTTPException(400, f"Analysis failed: {ex}") + slots = a.capabilities().cues.hotcue_slots occupied = {c.hotcue for c in cues.cues if c.hotcue is not None and c.hotcue >= 0} - free = [s for s in range(ah.MAX_HOTCUES) if s not in occupied] + free = [s for s in range(slots) if s not in occupied] existing_times = [c.start for c in cues.cues if c.hotcue is not None and c.hotcue >= 0] specs = ah.select_hotcues( boundaries, @@ -526,15 +483,11 @@ def auto_hotcues(body: AutoHotcuesRequest) -> TrackCues: duration=duration, free_slots=free, existing_times=existing_times, - max_cues=body.max_cues or ah.MAX_HOTCUES, + max_cues=body.max_cues or slots, ) if not specs: return cues # no confident structure / no free slots — leave untouched - try: - store.place_hotcues(body.track_id, [AutoHotcue(**s) for s in specs]) - except PlaylistError as ex: - raise HTTPException(400, str(ex)) - return _sync_cue_edit(body.track_id) + return a.place_cues(body.track_id, [AutoHotcue(**s) for s in specs]) @app.post("/api/tracks/auto-grid", response_model=TrackCues) @@ -542,54 +495,39 @@ def auto_grid(body: AutoGridRequest) -> TrackCues: """Detect tempo + first beat and build a beatgrid: sets BPM, sets hotcue 1 (slot 0) to the first beat, and anchors the grid to that position. Octave (half/double) errors are left for the user to fix with the ×2/÷2 controls.""" - store = require_store() - if store.model_entry(body.track_id) is None: + a = require_adapter() + if a.track(body.track_id) is None: raise HTTPException(404, "Track not found") - path = store.audio_path(body.track_id) + path = a.audio_path(body.track_id) if path is None or not path.exists(): raise HTTPException(400, "Audio file not found (is the drive mounted?)") try: bpm, first_beat = ah.detect_grid(str(path)) except Exception as ex: # analysis is best-effort; never 500 the UI raise HTTPException(400, f"Analysis failed: {ex}") - try: - store.replace_grid(body.track_id, [(first_beat, bpm)]) - # Traktor pairs its own grid markers with a white beat-1 cue; mirror - # that, but never over an existing hotcue (the old code clobbered slot 0). - store.place_grid_companion(body.track_id, 0, prefer_slot=0) - except PlaylistError as ex: - raise HTTPException(400, str(ex)) - return _sync_cue_edit(body.track_id) + # "Analysed", not "replace": each platform writes an analysis result in its + # own shape (Traktor pairs the first marker with a beat-1 cue). + return a.set_analysed_grid(body.track_id, [(first_beat, bpm)]) @app.patch("/api/tracks/hotcue", response_model=TrackCues) def edit_hotcue_type(body: SetHotcueType) -> TrackCues: """Change the type of an existing hotcue (keeps its position).""" - try: - require_store().set_hotcue_type(body.track_id, body.slot, body.type) - except PlaylistError as ex: - raise HTTPException(400, str(ex)) - return _sync_cue_edit(body.track_id) + return require_adapter().set_cue_type( + body.track_id, body.slot, _cue_type_name(body.type) + ) @app.delete("/api/tracks/hotcue", response_model=TrackCues) def delete_hotcue(track_id: str, slot: int) -> TrackCues: """Remove the hotcue in a slot.""" - try: - require_store().delete_hotcue(track_id, slot) - except PlaylistError as ex: - raise HTTPException(400, str(ex)) - return _sync_cue_edit(track_id) + return require_adapter().delete_cue(track_id, slot) @app.post("/api/tracks/grid/marker", response_model=TrackCues) def add_grid_marker(body: AddGridMarker) -> TrackCues: """Add a beatgrid marker. Omitting `bpm` inherits the governing tempo.""" - try: - require_store().add_grid_marker(body.track_id, body.start, body.bpm) - except PlaylistError as ex: - raise HTTPException(400, str(ex)) - return _sync_cue_edit(body.track_id) + return require_adapter().add_grid_marker(body.track_id, body.start, body.bpm) @app.patch("/api/tracks/grid/marker", response_model=TrackCues) @@ -599,84 +537,64 @@ def edit_grid_marker(body: GridMarkerEdit) -> TrackCues: BPM is applied before the move: a tempo change can never reorder markers, so `index` is still valid for the move afterwards. """ - store = require_store() - try: - if body.bpm is not None: - store.set_grid_marker_bpm(body.track_id, body.index, body.bpm) - if body.start is not None: - store.move_grid_marker(body.track_id, body.index, body.start) - except PlaylistError as ex: - raise HTTPException(400, str(ex)) - return _sync_cue_edit(body.track_id) + a = require_adapter() + cues = a.track_cues(body.track_id) + if body.bpm is not None: + cues = a.set_grid_marker_bpm(body.track_id, body.index, body.bpm) + if body.start is not None: + cues = a.move_grid_marker(body.track_id, body.index, body.start) + if cues is None: + raise HTTPException(404, "Track not found") + return cues @app.delete("/api/tracks/grid/marker", response_model=TrackCues) def remove_grid_marker(track_id: str, index: int) -> TrackCues: """Delete one grid marker (and its companion cue).""" - try: - require_store().delete_grid_marker(track_id, index) - except PlaylistError as ex: - raise HTTPException(400, str(ex)) - return _sync_cue_edit(track_id) + return require_adapter().delete_grid_marker(track_id, index) @app.put("/api/tracks/grid", response_model=TrackCues) def replace_grid(body: ReplaceGrid) -> TrackCues: """Replace the whole beatgrid (the deck's Reset). `markers: []` clears it.""" - try: - require_store().replace_grid( - body.track_id, [(m.start, m.bpm) for m in body.markers] - ) - except PlaylistError as ex: - raise HTTPException(400, str(ex)) - return _sync_cue_edit(body.track_id) + return require_adapter().replace_grid( + body.track_id, [(m.start, m.bpm) for m in body.markers] + ) @app.delete("/api/tracks/grid", response_model=TrackCues) def remove_grid(track_id: str) -> TrackCues: """Delete every grid marker and its companion cue. is kept.""" - try: - require_store().delete_grid(track_id) - except PlaylistError as ex: - raise HTTPException(400, str(ex)) - return _sync_cue_edit(track_id) + return require_adapter().delete_grid(track_id) @app.patch("/api/tracks/lock", response_model=TrackCues) def edit_lock(body: SetLock) -> TrackCues: """Toggle Traktor's LOCK flag on a track.""" - try: - require_store().set_lock(body.track_id, body.locked) - except PlaylistError as ex: - raise HTTPException(400, str(ex)) - return _sync_cue_edit(body.track_id) + return require_adapter().set_grid_lock(body.track_id, body.locked) @app.put("/api/tracks/art") async def set_track_art(track_id: str = Form(...), file: UploadFile = File(...)) -> dict: """Stage replacement cover art for a track (written to the file on save).""" - store = require_store() + a = require_adapter() data = await file.read() if not data: raise HTTPException(400, "Empty image") - mime = file.content_type or "image/jpeg" - try: - store.set_track_art(track_id, data, mime) - except PlaylistError as ex: - raise HTTPException(404, str(ex)) + a.set_cover_art(track_id, data, file.content_type or "image/jpeg") return {"status": "staged", "id": track_id, "bytes": len(data)} @app.post("/api/save", response_model=SaveResult) def save() -> SaveResult: - store = require_store() - if not store.dirty: - return SaveResult(saved=False, commit=None, playlists=store.count_playlists()) - outcome = store.save() + a = require_adapter() + if not a.dirty: + return SaveResult(saved=False, commit=None, playlists=a.playlist_count()) + outcome, commit = STATE.save() return SaveResult( saved=True, - commit=outcome.commit, - playlists=store.count_playlists(), + commit=commit, + playlists=a.playlist_count(), file_tags=[FileTagOutcome(**r.__dict__) for r in outcome.tag_results], ) @@ -687,7 +605,7 @@ def save() -> SaveResult: @app.get("/api/history", response_model=list[HistoryEntry]) def get_history() -> list[HistoryEntry]: """All saved versions of the current collection, newest first.""" - require_store() + require_adapter() return [HistoryEntry(**e.__dict__) for e in history.list_history(STATE.path)] @@ -696,14 +614,13 @@ def restore_version(commit_id: str) -> CollectionStatus: """Restore the collection to a past version. Writes that version back as a NEW forward save (a fresh commit on top of history — never a rewind), then reloads. The user should close Traktor first (it overwrites on exit).""" - require_store() + require_adapter() data = history.read_version(STATE.path, commit_id) if data is None: raise HTTPException(404, f"Version not found: {commit_id}") path = STATE.path - tmp = path.with_suffix(path.suffix + ".tmp") - tmp.write_bytes(data) - tmp.replace(path) + # The adapter's driver owns writing its own format back, even for a restore. + registry.driver_for(path).restore(path, data) history.commit(path, data, f"Restored version {commit_id[:8]}", __version__) STATE.open(path) # rebuild read + edit models from the restored file return collection_status() @@ -712,6 +629,6 @@ def restore_version(commit_id: str) -> CollectionStatus: @app.delete("/api/history") def clear_history() -> dict: """Permanently delete ALL version history for the current collection.""" - require_store() + require_adapter() history.clear_history(STATE.path) return {"status": "cleared"} diff --git a/backend/konduktor/path_mapping.py b/backend/konduktor/path_mapping.py deleted file mode 100644 index 78b4c25..0000000 --- a/backend/konduktor/path_mapping.py +++ /dev/null @@ -1,10 +0,0 @@ -"""Compatibility shim — this module was split. - -``PathMapping``/``common_dir_prefix`` are format-agnostic and moved to -``konduktor.core.pathmap``; ``os_path_to_location`` is the inverse of Traktor's -``resolve_path`` and moved to ``konduktor.adapters.traktor.locations``. Kept so -the existing test suite keeps importing the old path unchanged; removed in the -final cleanup step. -""" -from .adapters.traktor.locations import os_path_to_location # noqa: F401 -from .core.pathmap import PathMapping, common_dir_prefix # noqa: F401 diff --git a/backend/konduktor/playlist_store.py b/backend/konduktor/playlist_store.py deleted file mode 100644 index f60c91c..0000000 --- a/backend/konduktor/playlist_store.py +++ /dev/null @@ -1,11 +0,0 @@ -"""Compatibility shim — this module moved to ``konduktor.adapters.traktor.store``. - -Kept so the existing test suite keeps importing the old path unchanged while the -adapter refactor lands; removed in the final cleanup step. Replacing the entry in -``sys.modules`` makes this module *be* the new one, so private names resolve too. -""" -import sys - -from .adapters.traktor import store as _moved - -sys.modules[__name__] = _moved diff --git a/backend/test_save_fidelity.py b/backend/test_save_fidelity.py index 5a4de1c..40940ab 100644 --- a/backend/test_save_fidelity.py +++ b/backend/test_save_fidelity.py @@ -1,4 +1,8 @@ -"""Regression guard for save fidelity — keeps playlist diffs minimal. +"""Regression guard for save fidelity — the Traktor adapter's byte contract. + +This is deliberately a TRAKTOR test: it constructs the store directly and +asserts on rendered bytes, which is exactly the level the guarantee lives at. +The generic layer above it is covered by test_traktor_adapter.py. This is the test that would have caught the lxml reformatting bug. It asserts two invariants against a COPY of the real collection: @@ -30,7 +34,7 @@ os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-fidelity-a REAL = Path(__file__).resolve().parents[1] / "collection.nml" -from konduktor.playlist_store import PlaylistError, PlaylistStore # noqa: E402 +from konduktor.adapters.traktor.store import PlaylistError, TraktorStore # noqa: E402 failed = False @@ -71,7 +75,7 @@ with tempfile.TemporaryDirectory() as d: work = Path(d) / "collection.nml" shutil.copy2(REAL, work) before = work.read_bytes() - store = PlaylistStore(work) + store = TraktorStore(work) store.save() # no edits after = work.read_bytes() check("whole file identical after no-op save", before == after) @@ -91,7 +95,7 @@ with tempfile.TemporaryDirectory() as d: shutil.copy2(REAL, work) original = work.read_bytes() - store = PlaylistStore(work) + store = TraktorStore(work) def walk(n): yield n @@ -139,7 +143,7 @@ with tempfile.TemporaryDirectory() as d: shutil.copy2(REAL, work) original = work.read_bytes() - store = PlaylistStore(work) + store = TraktorStore(work) # pick the first track that has a resolvable primary key entry = store._nml.collection.entry[0] loc = entry.location @@ -185,7 +189,7 @@ with tempfile.TemporaryDirectory() as d: shutil.copy2(REAL, work) original = work.read_bytes() - store = PlaylistStore(work) + store = TraktorStore(work) entry = store._nml.collection.entry[0] loc = entry.location track_id = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}" @@ -224,21 +228,21 @@ with tempfile.TemporaryDirectory() as d: check("hotcue START stored in ms", new_cue is not None and abs(new_cue.start - 42500.0) < 1) # Create then delete must round-trip back to a byte-identical file. - store2 = PlaylistStore(work) # reload the edited file + store2 = TraktorStore(work) # reload the edited file store2.delete_hotcue(track_id, slot) store2.save() check("create+delete round-trips to the original bytes", work.read_bytes() == original) # ---- Invariant E: a beatgrid edit is fully localized ------------------- print("== E. grid marker edit touches only that track's ENTRY ==") -from konduktor import beatgrid as bg # noqa: E402 +from konduktor.adapters.traktor import beatgrid as bg # noqa: E402 with tempfile.TemporaryDirectory() as d: work = Path(d) / "collection.nml" shutil.copy2(REAL, work) original = work.read_bytes() - store = PlaylistStore(work) + store = TraktorStore(work) def _key(e): loc = e.location @@ -305,7 +309,7 @@ with tempfile.TemporaryDirectory() as d: check("companion kept its hotcue slot", comp is not None and comp.hotcue == comp_slot) # Reverting BPM + position round-trips to the original bytes. - store2 = PlaylistStore(work) + store2 = TraktorStore(work) store2.set_grid_marker_bpm(track_id, 0, orig_bpm) store2.move_grid_marker(track_id, 0, orig_anchor_ms / 1000.0) store2.save() @@ -314,13 +318,13 @@ with tempfile.TemporaryDirectory() as d: # ---- Invariant F: batch place_hotcues (Auto Hotcues) ------------------- print("== F. place_hotcues fills empty slots only, names round-trip, localized ==") with tempfile.TemporaryDirectory() as d: - from konduktor.schemas import AutoHotcue + from konduktor.core.model import AutoHotcue from traktor_nml_utils import TraktorCollection work = Path(d) / "collection.nml" shutil.copy2(REAL, work) - store = PlaylistStore(work) + store = TraktorStore(work) entry = store._nml.collection.entry[0] loc = entry.location track_id = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}" @@ -340,7 +344,7 @@ with tempfile.TemporaryDirectory() as d: original = work.read_bytes() # Batch: one spec targets the occupied slot (must be skipped), two fill free slots. - store2 = PlaylistStore(work) + store2 = TraktorStore(work) e2 = store2._nml.collection.entry[0] now_used = {c.hotcue for c in (e2.cue_v2 or []) if c.hotcue is not None and c.hotcue >= 0} free = [s for s in range(8) if s not in now_used][:2] @@ -377,7 +381,7 @@ with tempfile.TemporaryDirectory() as d: # ---- Invariant G: select_hotcues placement logic (pure, no audio) ------ print("== G. select_hotcues: phrase-snap, empty-slots, names, existing-cue avoidance ==") -from konduktor import auto_hotcues as ah # noqa: E402 +from konduktor.core import auto_hotcues as ah # noqa: E402 # 128 BPM => beat 0.46875s, 16-bar phrase = 30.0s exactly; marker at 0.0. BPM, ANCHOR, DUR = 128.0, 0.0, 300.0 @@ -424,8 +428,9 @@ check("flexible grid: post-seam points snap to that segment's 32s phrase", print("== H. remap_locations rewrites LOCATIONs (+ playlist keys), localized, round-trips ==") from collections import Counter # noqa: E402 -from konduktor.file_tags import resolve_path # noqa: E402 -from konduktor.path_mapping import PathMapping, os_path_to_location # noqa: E402 +from konduktor.adapters.traktor.locations import resolve_path # noqa: E402 +from konduktor.core.pathmap import PathMapping # noqa: E402 +from konduktor.adapters.traktor.locations import os_path_to_location # noqa: E402 from traktor_nml_utils import TraktorCollection # noqa: E402 @@ -447,7 +452,7 @@ with tempfile.TemporaryDirectory() as d: shutil.copy2(REAL, work) original = work.read_bytes() - store = PlaylistStore(work) + store = TraktorStore(work) pl_keys = { k for n in store._iter_nodes(store._root()) @@ -492,7 +497,7 @@ with tempfile.TemporaryDirectory() as d: check("H1: moved ENTRY has the new VOLUME", moved.location.volume == "KONDUKTOR_TEST_H1") # Reverting (to -> from) round-trips to the original bytes exactly. - store2 = PlaylistStore(work) + store2 = TraktorStore(work) store2.remap_locations(PathMapping.make(to_prefix, from_prefix)) store2.save() check("H1: revert round-trips to original bytes", work.read_bytes() == original) @@ -502,7 +507,7 @@ with tempfile.TemporaryDirectory() as d: work = Path(d) / "collection.nml" shutil.copy2(REAL, work) - store = PlaylistStore(work) + store = TraktorStore(work) # A collection entry whose key appears in at least one playlist. pl_keys = { k @@ -535,7 +540,7 @@ with tempfile.TemporaryDirectory() as d: ) check("H2: collection ENTRY location rewritten", moved is not None) - store3 = PlaylistStore(work) + store3 = TraktorStore(work) all_pl_keys = { k for node in store3._iter_nodes(store3._root()) @@ -566,7 +571,7 @@ with tempfile.TemporaryDirectory() as d: # Synthesize the flexible grid rather than relying on the handful of real # ones: those are the user's own data and could change at any time. - store = PlaylistStore(work) + store = TraktorStore(work) entry = next( e for e in store._nml.collection.entry if e.tempo and len(bg.grid_markers(e)) == 1 @@ -600,14 +605,14 @@ with tempfile.TemporaryDirectory() as d: original[:os_] + b"@@" + original[oe:] == two[:es_] + b"@@" + two[ee:]) # Removing it must return the file to its original bytes exactly. - store2 = PlaylistStore(work) + store2 = TraktorStore(work) store2.delete_grid_marker(track_id, 1) store2.save() check("I: deleting the added marker round-trips to original bytes", work.read_bytes() == original) # Moves clamp between neighbours rather than reordering the list. - store3 = PlaylistStore(work) + store3 = TraktorStore(work) store3.add_grid_marker(track_id, (m0_start + 60_000.0) / 1000.0, bpm=m0_bpm * 0.99) store3.move_grid_marker(track_id, 0, (m0_start + 120_000.0) / 1000.0) e3 = store3.model_entry(track_id) @@ -631,7 +636,7 @@ with tempfile.TemporaryDirectory() as d: shutil.copy2(REAL, work) original = work.read_bytes() - store = PlaylistStore(work) + store = TraktorStore(work) entry = next( e for e in store._nml.collection.entry if bg.companions(e).get(0) is not None ) @@ -660,7 +665,7 @@ with tempfile.TemporaryDirectory() as d: check("J: a non-companion slot is still editable", store.dirty is True) # Auto Hotcues must skip companion slots even when told to overwrite. - store2 = PlaylistStore(work) + store2 = TraktorStore(work) spec = type("S", (), {"slot": slot, "start": 42.0, "name": "X", "type": 0, "length": 0.0})() store2.place_hotcues(track_id, [spec], overwrite=True) e2 = store2.model_entry(track_id) @@ -682,7 +687,7 @@ _flex = [e for e in _real if len(bg.grid_markers(e)) > 1] if not _flex: print(" [SKIP] no flexible-grid entries in the reference collection") else: - import konduktor.main as _m + from konduktor.adapters.traktor import projection as _proj ok_order = ok_tempo = ok_proj = ok_comp = True for e in _flex: @@ -690,7 +695,7 @@ else: ok_order &= all(ms[i].start < ms[i + 1].start for i in range(len(ms) - 1)) if e.tempo and e.tempo.bpm: ok_tempo &= abs(e.tempo.bpm - ms[0].grid.bpm) < 1e-6 - tc = _m._build_track_cues(e) + tc = _proj.to_track_cues(e) ok_proj &= len(tc.grid_markers) == len(ms) and all( abs(g.bpm - m.grid.bpm) < 1e-9 and abs(g.start - (m.start or 0) / 1000.0) < 1e-9 for g, m in zip(tc.grid_markers, ms) From 6e24f5ef1d8a84a6851fd9a33439215a5c91e870 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Thu, 17 Sep 2026 22:24:56 +0200 Subject: [PATCH 05/64] Switched to more generic wording --- CLAUDE.md | 28 ++- backend/konduktor/adapters/traktor/adapter.py | 20 +- .../konduktor/adapters/traktor/cue_types.py | 13 ++ .../konduktor/adapters/traktor/projection.py | 94 +++++++-- backend/konduktor/adapters/traktor/store.py | 14 +- backend/konduktor/core/model.py | 91 +++++++-- backend/konduktor/main.py | 119 +++++++---- backend/konduktor/schemas.py | 29 ++- backend/test_history.py | 2 +- backend/test_phase3.py | 4 +- backend/test_save_fidelity.py | 12 +- backend/test_traktor_adapter.py | 22 +- frontend/src/App.tsx | 31 ++- frontend/src/api.ts | 190 ++++++++++++------ frontend/src/components/CollectionPicker.tsx | 19 +- frontend/src/components/EditTagsDialog.tsx | 24 +-- frontend/src/components/HistoryPanel.tsx | 8 +- frontend/src/components/HotcueBar.tsx | 51 +++-- frontend/src/components/PrepStrip.tsx | 93 ++++++--- frontend/src/components/RatingStars.tsx | 23 ++- frontend/src/components/SaveBar.tsx | 10 +- frontend/src/components/SelectionBar.tsx | 2 +- frontend/src/components/Sidebar.tsx | 22 +- frontend/src/components/Toolbar.tsx | 4 +- frontend/src/lib/capabilities.tsx | 32 +++ frontend/src/lib/cues.ts | 84 ++++++-- frontend/src/lib/format.ts | 20 +- frontend/src/lib/platformCopy.ts | 41 ++++ frontend/src/lib/trackColumns.tsx | 13 +- 29 files changed, 796 insertions(+), 319 deletions(-) create mode 100644 backend/konduktor/adapters/traktor/cue_types.py create mode 100644 frontend/src/lib/capabilities.tsx create mode 100644 frontend/src/lib/platformCopy.ts diff --git a/CLAUDE.md b/CLAUDE.md index 19e0044..25d4e62 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -73,8 +73,20 @@ Two independent apps that talk over HTTP: `KONDUKTOR_NML` auto-loads on startup (dev/tests). - **`frontend/`** — React + TypeScript + Vite. A dark, virtualized track explorer. Entry: [frontend/src/App.tsx](frontend/src/App.tsx). - - `api.ts` — typed client + all API types (keep in sync with backend - `schemas.py`). + - `api.ts` — typed client + all API types. **Generic, not Traktor-shaped**: + cue types are the strings `cue`/`fade_in`/`fade_out`/`load`/`loop`, a cue has + a `role` (`hotcue`/`memory`) and a nullable `slot`, and `editable` + + `readonly_reason` say whether the adapter will accept a command on it — gate + on `editable`, never on a platform-specific reason like `grid_marker`. Keep + in lockstep with `core/model.py`; land both in the same commit. + - `lib/capabilities.tsx` — `useCaps()` over `GET /api/capabilities`. The app + does not render until capabilities resolve, so no first frame can offer an + edit the adapter would reject. Containers call `useCaps()`; presentational + leaves take plain values as props. **No component branches on the platform.** + - `lib/platformCopy.ts` — composes user-facing wording from the *facts* the + adapter supplies (`app_name`, `library_label`, `overwrite_risk`), so + "Close Traktor before saving — it overwrites collection.nml on exit" stays + specific without being hard-coded. Never put finished sentences in the API. - `components/` — `CollectionPicker` (startup chooser: Automatic / Open last / Find manually — the last reveals a file browser), `Sidebar` (playlist tree + create/rename/delete), `SaveBar`, `Toolbar` (search/filters + `ColumnsMenu`), @@ -113,7 +125,13 @@ Two independent apps that talk over HTTP: analysis + paint), `beatgrid.ts` (the marker-list beat math — every beat/bar/snap/jump calculation goes through it), `cues.ts` (draw cues/loop/beatgrid/cue-point). See "Prep engine" below. - - `lib/trackColumns.tsx` — single source of truth for the library table's + - Capability-gated today: hotcue bank size (`HotcueBar`, the auto-cue guard and + the digit shortcuts all read `cues.hotcue_slots`), the cue-type dropdown + (`cues.types`), the rating scale (`tracks.rating_max`), the grid Lock button + (`grid.lockable`). Carried but deliberately unused until a second adapter + exists: `slot_labels: 'letter'`, `palette`, `loops: 'separate_bank'`, and + memory-cue *editing* (one-platform features stay preserved-but-uneditable). +- `lib/trackColumns.tsx` — single source of truth for the library table's columns (defs, default widths/visibility/order, the Columns-menu list, the inline `InlineEdit` cell, and the `TableMeta.onEditField` augmentation). - Data flow: the whole library is fetched once (`/api/tracks?limit=20000`); @@ -264,8 +282,8 @@ that number and nothing else — everything derives from it: commands, piecewise beat math, playhead-derived marker editing). Step 1 of the multi-platform plan in `.claude/discussions/`. - ✅ Generic model + adapter interface (Traktor as the only adapter) — step 2 of - the multi-platform plan. Backend done; the wire format and UI are still - Traktor-shaped (cue type integers, 8 hard-coded hotcue slots) and are next. + the multi-platform plan. Backend, wire format and UI are all generic; nothing + above `adapters/traktor/` knows what Traktor is. - ⬜ Rekordbox adapter; ⬜ Serato adapter; ⬜ export/conversion - ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging diff --git a/backend/konduktor/adapters/traktor/adapter.py b/backend/konduktor/adapters/traktor/adapter.py index 0c6267c..dfe4531 100644 --- a/backend/konduktor/adapters/traktor/adapter.py +++ b/backend/konduktor/adapters/traktor/adapter.py @@ -13,6 +13,7 @@ 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 @@ -21,13 +22,10 @@ from ...core.pathmap import PathMapping from ...core.query import TrackIndex from . import capabilities as caps from . import projection +from .cue_types import CUE_TYPE_TO_NATIVE from .store import PlaylistError, TraktorStore -# Generic cue vocabulary -> Traktor's CUE_V2 TYPE encoding. This table is the -# only place the integers exist outside the store; type 4 is a grid marker and -# is never a cue, so it has no generic name. -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()} + class TraktorAdapter: @@ -186,8 +184,18 @@ class TraktorAdapter: 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, cues, overwrite=overwrite) + self._store.place_hotcues(track_id, native, overwrite=overwrite) return self._refresh(track_id) # ---- beatgrid --------------------------------------------------------- diff --git a/backend/konduktor/adapters/traktor/cue_types.py b/backend/konduktor/adapters/traktor/cue_types.py new file mode 100644 index 0000000..07b8405 --- /dev/null +++ b/backend/konduktor/adapters/traktor/cue_types.py @@ -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()} diff --git a/backend/konduktor/adapters/traktor/projection.py b/backend/konduktor/adapters/traktor/projection.py index c79e435..8421ac0 100644 --- a/backend/konduktor/adapters/traktor/projection.py +++ b/backend/konduktor/adapters/traktor/projection.py @@ -5,8 +5,49 @@ Everything above this file sees generic types exclusively. """ from __future__ import annotations +import re + from ...core.model import CuePoint, GridMarker, Track, TrackCues from . import beatgrid +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})$") + + +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 primary_key(location) -> str: @@ -38,6 +79,7 @@ def to_track(e) -> Track: 1 for c in cues if c.hotcue is not None and c.hotcue >= 0 ) markers = beatgrid.grid_markers(e) + 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, @@ -51,19 +93,21 @@ def to_track(e) -> Track: comment=info.comment 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=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, + 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=hotcues, - has_grid=bool(markers), - grid_markers=len(markers), - is_stem=getattr(e, "stems", None) is not None, + grid_marker_count=len(markers), + grid_locked=bool(e.lock), + media_kind="stem" if getattr(e, "stems", None) is not None else "audio", ) @@ -87,19 +131,31 @@ def to_track_cues(entry) -> TrackCues: ) for i, m in enumerate(markers) ] - cues = [ - CuePoint( - name=c.name, - type=c.type if c.type is not None else 0, - start=(c.start or 0.0) / 1000.0, - length=(c.len or 0.0) / 1000.0, - hotcue=c.hotcue if c.hotcue is not None else -1, - color=c.color, - grid_marker=marker_of.get(id(c)), + 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=(c.start or 0.0) / 1000.0, + length=(c.len or 0.0) / 1000.0, + slot=slot, + color=c.color, + # A grid marker's companion belongs to the beatgrid: the store + # refuses hotcue commands on it, so say so up front. + editable=marker is None, + readonly_reason="beatgrid_companion" if marker is not None else None, + grid_marker=marker, + ) ) - for c in (entry.cue_v2 or []) - if getattr(c, "grid", None) is None - ] return TrackCues( - grid_markers=grid_markers, locked=bool(entry.lock), cues=cues + grid_markers=grid_markers, grid_locked=bool(entry.lock), cues=cues ) diff --git a/backend/konduktor/adapters/traktor/store.py b/backend/konduktor/adapters/traktor/store.py index f2908c1..db36022 100644 --- a/backend/konduktor/adapters/traktor/store.py +++ b/backend/konduktor/adapters/traktor/store.py @@ -154,20 +154,26 @@ class TraktorStore: return PlaylistNode( id=pl.uuid if pl and pl.uuid else name, name=name, - type="PLAYLIST", - uuid=pl.uuid if pl else None, + kind="playlist", count=len(keys), + selectable=True, + can_add_tracks=True, + can_reorder=True, + can_rename=True, + can_delete=True, ) if ntype == "SMARTLIST" or node.smartplaylist is not None: + # Rule-based, so it has no static entry list to show or edit. return PlaylistNode( - id="sl:" + "/".join(parent_path + [name]), name=name, type="SMARTLIST" + id="sl:" + "/".join(parent_path + [name]), name=name, kind="smart" ) path = parent_path + [name] return PlaylistNode( id="fld:" + "/".join(path), name=name, - type="FOLDER", + kind="folder", children=[self._to_model(c, path) for c in self._children(node)], + can_contain_children=True, ) @staticmethod diff --git a/backend/konduktor/core/model.py b/backend/konduktor/core/model.py index 5eba549..854486e 100644 --- a/backend/konduktor/core/model.py +++ b/backend/konduktor/core/model.py @@ -9,13 +9,17 @@ 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 Track(BaseModel): - """A single track, flattened from a Traktor collection ENTRY.""" + """A single track in the library, as the app sees it.""" - id: str # primary key: "", used to join playlist entries + id: str # the adapter's stable track key; opaque above the adapter artist: str | None = None title: str | None = None album: str | None = None @@ -26,20 +30,27 @@ class Track(BaseModel): mix: str | None = None comment: str | None = None bpm: float | None = None - key: str | None = None # Traktor display key, e.g. "10m" + # 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 + # 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 - has_grid: bool = False - grid_markers: int = 0 # >1 = a flexible (multi-tempo) beatgrid - is_stem: bool = False # a Stem file ( child) vs a normal audio track + # 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): @@ -79,15 +90,27 @@ class Stats(BaseModel): class PlaylistNode(BaseModel): - """A node in the playlist tree — either a FOLDER or a PLAYLIST/SMARTLIST.""" + """A node in the playlist tree. - id: str # stable synthetic id ("pl-" / "fld-") + `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 - type: str # "FOLDER" | "PLAYLIST" | "SMARTLIST" - uuid: str | None = None + 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() @@ -97,13 +120,20 @@ PlaylistNode.model_rebuild() class CuePoint(BaseModel): name: str | None = None - type: int # Traktor: 0 cue, 1 fade-in, 2 fade-out, 3 load, 4 grid, 5 loop + 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) - hotcue: int # -1 if not assigned to a hotcue slot - color: str | None = None # "#RRGGBB" if set - # Index of the grid marker this cue is the companion of, if any. Such a cue - # holds a real hotcue slot but belongs to the beatgrid and is not editable. + 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["beatgrid_companion", "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 @@ -121,16 +151,39 @@ class TrackCues(BaseModel): # 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] = [] - locked: bool = False # Traktor LOCK flag + grid_locked: bool = False cues: list[CuePoint] = [] # cue/loop markers (grid markers themselves excluded) class AutoHotcue(BaseModel): - slot: int # 0–7 + """One cue in a batch placement (Auto Hotcues).""" + + slot: int start: float # seconds name: str | None = None # positional label (e.g. "Drop") - type: int = 0 # plain cue - length: float = 0.0 # seconds (>0 for a loop hotcue) + 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.""" + + platform: str + name: str + library_label: str + selects: Literal["file", "directory"] = "file" + installed: bool = False class RemapSample(BaseModel): diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index d3b9300..9adcf7b 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -14,7 +14,6 @@ from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse, JSONResponse from . import __version__, history, prefs -from .adapters.traktor.adapter import NATIVE_TO_CUE_TYPE from .adapters.traktor.discovery import describe from .app_state import STATE from .core import auto_hotcues as ah @@ -38,6 +37,8 @@ from .schemas import ( CollectionStatus, CreatePlaylist, EditState, + LibraryInfo, + PlatformOption, EditTrack, Facets, FileTagOutcome, @@ -56,9 +57,9 @@ from .schemas import ( RenamePlaylist, SaveResult, SetEntries, - SetHotcue, - SetHotcueType, - SetLock, + SetCue, + SetCueType, + SetGridLock, Stats, Track, TrackCues, @@ -82,18 +83,6 @@ app.add_middleware( ) -def _cue_type_name(native: int) -> str: - """Map the wire's Traktor cue integer onto the generic vocabulary. - - Transitional: the HTTP contract still carries Traktor's encoding, so the - translation happens here at the boundary rather than in the adapter. - """ - name = NATIVE_TO_CUE_TYPE.get(native) - if name is None: - raise HTTPException(400, f"Unsupported cue type: {native}") - return name - - def require_adapter() -> LibraryAdapter: """The loaded library, or a 409. Routes talk to this and nothing else.""" if not STATE.loaded: @@ -118,7 +107,7 @@ def _adapter_error(_request, exc: AdapterError): # ---- collection selection --------------------------------------------- -@app.get("/api/collection", response_model=CollectionStatus) +@app.get("/api/library", response_model=CollectionStatus) def collection_status() -> CollectionStatus: if not STATE.loaded: return CollectionStatus(loaded=False) @@ -127,10 +116,11 @@ def collection_status() -> CollectionStatus: path=str(STATE.path), tracks=len(require_adapter().tracks), playlists=require_adapter().playlist_count(), + library=_library_info(), ) -@app.post("/api/collection/open", response_model=CollectionStatus) +@app.post("/api/library/open", response_model=CollectionStatus) def open_collection(body: OpenCollection) -> CollectionStatus: path = Path(body.path).expanduser() if not path.exists() or not path.is_file(): @@ -145,7 +135,7 @@ def open_collection(body: OpenCollection) -> CollectionStatus: return collection_status() -@app.get("/api/collection/options", response_model=CollectionOptions) +@app.get("/api/library/options", response_model=CollectionOptions) def collection_options() -> CollectionOptions: """Startup shortcuts for the picker: the best auto-detected Traktor collection and the last one opened (may no longer exist → exists=False).""" @@ -158,7 +148,7 @@ def collection_options() -> CollectionOptions: return CollectionOptions(auto=auto, recent=recent) -@app.get("/api/collection/path-mapping", response_model=PathMappingInfo) +@app.get("/api/library/path-mapping", response_model=PathMappingInfo) def get_path_mapping() -> PathMappingInfo: """The current collection's saved OS-path remapping (blank if none).""" require_adapter() @@ -168,7 +158,7 @@ def get_path_mapping() -> PathMappingInfo: return PathMappingInfo() -@app.put("/api/collection/path-mapping", response_model=PathMappingInfo) +@app.put("/api/library/path-mapping", response_model=PathMappingInfo) def put_path_mapping(body: PathMappingInfo) -> PathMappingInfo: """Set (or, with blank prefixes, clear) the current collection's remapping. Persists to userprefs AND updates the live store so playback/analysis @@ -184,14 +174,14 @@ def put_path_mapping(body: PathMappingInfo) -> PathMappingInfo: ) -@app.get("/api/collection/path-mapping/suggest", response_model=PrefixSuggestions) +@app.get("/api/library/path-mapping/suggest", response_model=PrefixSuggestions) def suggest_path_prefix() -> PrefixSuggestions: """Auto-detected `from` prefix candidates (common directory per volume), so the editor can prefill the stored prefix.""" return PrefixSuggestions.model_validate(require_adapter().path_prefix_suggestions()) -@app.get("/api/collection/path-mapping/preview", response_model=RemapPreview) +@app.get("/api/library/path-mapping/preview", response_model=RemapPreview) def preview_path_mapping( from_: str = Query("", alias="from"), to: str = Query("") ) -> RemapPreview: @@ -202,7 +192,7 @@ def preview_path_mapping( ) -@app.post("/api/collection/remap-paths", response_model=RemapResult) +@app.post("/api/library/remap-paths", response_model=RemapResult) def remap_paths(body: PathMappingInfo) -> RemapResult: """Write-back: permanently rewrite matching track LOCATIONs (and the playlist references that join to them) to the `to` prefix, then save (a @@ -268,6 +258,42 @@ def health() -> dict: return {"status": "ok", "loaded": STATE.loaded, "path": str(STATE.path) if STATE.path else None} +def _library_info() -> LibraryInfo: + """Identity of the loaded library, for display and for composing warnings.""" + caps = require_adapter().capabilities() + return LibraryInfo( + platform=caps.platform, + name=caps.save.app_name, + library_label=caps.save.library_label, + path=str(STATE.path), + display_name=Path(str(STATE.path)).name, + version=caps.version, + ) + + +@app.get("/api/platforms", response_model=list[PlatformOption]) +def platforms() -> list[PlatformOption]: + """Every DJ platform Konduktor can open — used by the picker BEFORE a + library is loaded, where capabilities are not yet available.""" + out = [] + for d in registry.drivers(): + found = [] + try: + found = d.detect() + except OSError: + pass + out.append( + PlatformOption( + platform=d.platform, + name=d.display_name, + library_label=getattr(d, "library_label", ""), + selects="file", + installed=bool(found), + ) + ) + return out + + @app.get("/api/capabilities", response_model=Capabilities) def capabilities() -> Capabilities: """What the loaded library can persist, so the UI can gate its controls.""" @@ -276,7 +302,7 @@ def capabilities() -> Capabilities: @app.get("/api/state", response_model=EditState) def state() -> EditState: - return EditState(dirty=require_adapter().dirty, nml_path=str(STATE.path)) + return EditState(dirty=require_adapter().dirty, library=_library_info()) @app.post("/api/reload") @@ -346,7 +372,17 @@ def create_playlist(body: CreatePlaylist) -> PlaylistNode: new_id = require_adapter().create_playlist( body.name.strip() or "New Playlist", body.parent_id ) - return PlaylistNode(id=new_id, name=body.name, type="PLAYLIST", uuid=new_id, count=0) + return PlaylistNode( + id=new_id, + name=body.name, + kind="playlist", + count=0, + selectable=True, + can_add_tracks=True, + can_reorder=True, + can_rename=True, + can_delete=True, + ) @app.patch("/api/playlists/{playlist_uuid}") @@ -438,20 +474,21 @@ def track_cues(track_id: str) -> TrackCues: return _cues_for(track_id) -@app.post("/api/tracks/hotcue", response_model=TrackCues) -def create_hotcue(body: SetHotcue) -> TrackCues: - """Create (or reposition + retype) the hotcue in a slot at a position.""" +@app.post("/api/tracks/cue", response_model=TrackCues) +def create_cue(body: SetCue) -> TrackCues: + """Create (or reposition + retype) the cue in a slot at a position.""" return require_adapter().set_cue( body.track_id, slot=body.slot, start_sec=body.start, - cue_type=_cue_type_name(body.type), + cue_type=body.type, + role=body.role, length_sec=body.length, name=body.name, ) -@app.post("/api/tracks/auto-hotcues", response_model=TrackCues) +@app.post("/api/tracks/cue/auto", response_model=TrackCues) def auto_hotcues(body: AutoHotcuesRequest) -> TrackCues: """Analyze the track's audio and place structural hotcues into empty slots. @@ -490,7 +527,7 @@ def auto_hotcues(body: AutoHotcuesRequest) -> TrackCues: return a.place_cues(body.track_id, [AutoHotcue(**s) for s in specs]) -@app.post("/api/tracks/auto-grid", response_model=TrackCues) +@app.post("/api/tracks/grid/auto", response_model=TrackCues) def auto_grid(body: AutoGridRequest) -> TrackCues: """Detect tempo + first beat and build a beatgrid: sets BPM, sets hotcue 1 (slot 0) to the first beat, and anchors the grid to that position. Octave @@ -510,16 +547,14 @@ def auto_grid(body: AutoGridRequest) -> TrackCues: return a.set_analysed_grid(body.track_id, [(first_beat, bpm)]) -@app.patch("/api/tracks/hotcue", response_model=TrackCues) -def edit_hotcue_type(body: SetHotcueType) -> TrackCues: - """Change the type of an existing hotcue (keeps its position).""" - return require_adapter().set_cue_type( - body.track_id, body.slot, _cue_type_name(body.type) - ) +@app.patch("/api/tracks/cue", response_model=TrackCues) +def edit_cue_type(body: SetCueType) -> TrackCues: + """Change the type of an existing cue (keeps its position).""" + return require_adapter().set_cue_type(body.track_id, body.slot, body.type) -@app.delete("/api/tracks/hotcue", response_model=TrackCues) -def delete_hotcue(track_id: str, slot: int) -> TrackCues: +@app.delete("/api/tracks/cue", response_model=TrackCues) +def delete_cue(track_id: str, slot: int) -> TrackCues: """Remove the hotcue in a slot.""" return require_adapter().delete_cue(track_id, slot) @@ -568,8 +603,8 @@ def remove_grid(track_id: str) -> TrackCues: return require_adapter().delete_grid(track_id) -@app.patch("/api/tracks/lock", response_model=TrackCues) -def edit_lock(body: SetLock) -> TrackCues: +@app.patch("/api/tracks/grid/lock", response_model=TrackCues) +def edit_grid_lock(body: SetGridLock) -> TrackCues: """Toggle Traktor's LOCK flag on a track.""" return require_adapter().set_grid_lock(body.track_id, body.locked) diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index e39bf56..3f4e250 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -3,6 +3,8 @@ from __future__ import annotations from pydantic import BaseModel, ConfigDict, Field +from .core.capabilities import CueRole, CueType + class CreatePlaylist(BaseModel): name: str @@ -61,18 +63,20 @@ class ReplaceGrid(BaseModel): markers: list[GridMarker] = [] # [] is equivalent to deleting the grid -class SetLock(BaseModel): +class SetGridLock(BaseModel): track_id: str locked: bool -class SetHotcue(BaseModel): +class SetCue(BaseModel): track_id: str - slot: int # 0–7 + slot: int # bank slot; capabilities.cues.hotcue_slots bounds it start: float # seconds - type: int # 0 cue, 1 fade-in, 2 fade-out, 3 load, 5 loop - length: float = 0.0 # seconds (>0 for a loop hotcue) - name: str | None = None # cue label; defaults to Traktor's "n.n." when unset + type: CueType = "cue" + role: CueRole = "hotcue" + length: float = 0.0 # seconds (>0 for a loop cue) + name: str | None = None + color: str | None = None class AutoHotcuesRequest(BaseModel): @@ -84,15 +88,15 @@ class AutoGridRequest(BaseModel): track_id: str -class SetHotcueType(BaseModel): +class SetCueType(BaseModel): track_id: str slot: int - type: int + type: CueType class EditState(BaseModel): - dirty: bool # unsaved in-memory playlist changes exist - nml_path: str + dirty: bool # unsaved in-memory changes exist + library: LibraryInfo # ---- collection selection ---- @@ -103,6 +107,9 @@ class CollectionStatus(BaseModel): path: str | None = None tracks: int | None = None playlists: int | None = None + # Identity of the loaded library, so the UI can name it without parsing the + # path (a Serato library is a directory, not a file). + library: LibraryInfo | None = None class OpenCollection(BaseModel): @@ -157,6 +164,8 @@ class RemapResult(BaseModel): # one import site. The dependency runs schemas -> core, never the reverse. from .core.model import ( # noqa: E402,F401 AutoHotcue, + LibraryInfo, + PlatformOption, CuePoint, Facets, GenreCount, diff --git a/backend/test_history.py b/backend/test_history.py index 9517360..3f6df68 100644 --- a/backend/test_history.py +++ b/backend/test_history.py @@ -49,7 +49,7 @@ client = TestClient(main.app) def first_playlist(nodes): for n in nodes: - if n["type"] == "PLAYLIST": + if n["kind"] == "playlist": return n if n.get("children"): found = first_playlist(n["children"]) diff --git a/backend/test_phase3.py b/backend/test_phase3.py index 1af1255..1bf7f5c 100644 --- a/backend/test_phase3.py +++ b/backend/test_phase3.py @@ -53,7 +53,7 @@ check.failed = False print("== initial read ==") pls = client.get("/api/playlists").json() flat = lambda ns: [x for n in ns for x in [n] + flat(n.get("children", []))] -playlists = [n for n in flat(pls) if n["type"] == "PLAYLIST"] +playlists = [n for n in flat(pls) if n["kind"] == "playlist"] print(f" {len(playlists)} playlists, e.g. {[p['name'] for p in playlists[:3]]}") donor = next(p for p in playlists if p["count"] >= 5) donor_tracks = client.get(f"/api/playlists/{donor['id']}/tracks").json() @@ -64,7 +64,7 @@ collection_before = collection_span(WORK.read_bytes()) print("== create + add + reorder + rename ==") created = client.post("/api/playlists", json={"name": "Konduktor Test"}).json() -new_uuid = created["uuid"] +new_uuid = created["id"] check("create returns uuid", bool(new_uuid)) r = client.put(f"/api/playlists/{new_uuid}/entries", json={"track_ids": track_ids}) diff --git a/backend/test_save_fidelity.py b/backend/test_save_fidelity.py index 40940ab..fd8c7e4 100644 --- a/backend/test_save_fidelity.py +++ b/backend/test_save_fidelity.py @@ -23,6 +23,7 @@ import os import shutil import sys import tempfile +from types import SimpleNamespace import warnings from pathlib import Path @@ -318,9 +319,14 @@ with tempfile.TemporaryDirectory() as d: # ---- Invariant F: batch place_hotcues (Auto Hotcues) ------------------- print("== F. place_hotcues fills empty slots only, names round-trip, localized ==") with tempfile.TemporaryDirectory() as d: - from konduktor.core.model import AutoHotcue from traktor_nml_utils import TraktorCollection + # The store is the NATIVE layer, so its specs carry Traktor's own cue TYPE + # integer. The generic AutoHotcue (string types) is translated by the adapter + # before it gets here — test_traktor_adapter.py covers that path. + def spec(slot, start, name, type=0, length=0.0): + return SimpleNamespace(slot=slot, start=start, name=name, type=type, length=length) + work = Path(d) / "collection.nml" shutil.copy2(REAL, work) @@ -348,8 +354,8 @@ with tempfile.TemporaryDirectory() as d: e2 = store2._nml.collection.entry[0] now_used = {c.hotcue for c in (e2.cue_v2 or []) if c.hotcue is not None and c.hotcue >= 0} free = [s for s in range(8) if s not in now_used][:2] - specs = [AutoHotcue(slot=hand_slot, start=99.0, name="SHOULD-NOT-OVERWRITE")] - specs += [AutoHotcue(slot=s, start=30.0 + i * 10, name=f"Auto {i}") for i, s in enumerate(free)] + specs = [spec(slot=hand_slot, start=99.0, name="SHOULD-NOT-OVERWRITE")] + specs += [spec(slot=s, start=30.0 + i * 10, name=f"Auto {i}") for i, s in enumerate(free)] store2.place_hotcues(track_id, specs) store2.save() edited = work.read_bytes() diff --git a/backend/test_traktor_adapter.py b/backend/test_traktor_adapter.py index 9d730c8..d37d77d 100644 --- a/backend/test_traktor_adapter.py +++ b/backend/test_traktor_adapter.py @@ -105,21 +105,21 @@ with tempfile.TemporaryDirectory() as d: # cues — a free slot on a track with a grid, so the companion guard is clear tid2 = next( t.id for t in adapter.tracks - if t.has_grid and (cues := adapter.track_cues(t.id)) - and len({c.hotcue for c in cues.cues if c.hotcue >= 0}) < 7 + if t.grid_marker_count and (cues := adapter.track_cues(t.id)) + and len({c.slot for c in cues.cues if c.slot is not None}) < 7 ) before = adapter.track(tid2).hotcue_count - used = {c.hotcue for c in adapter.track_cues(tid2).cues if c.hotcue >= 0} + used = {c.slot for c in adapter.track_cues(tid2).cues if c.slot is not None} free = next(s for s in range(8) if s not in used) fresh = adapter.set_cue(tid2, slot=free, start_sec=12.5, cue_type="cue") - check("set_cue returns fresh cues", any(c.hotcue == free for c in fresh.cues)) + check("set_cue returns fresh cues", any(c.slot == free for c in fresh.cues)) check("hotcue count in the projection incremented", adapter.track(tid2).hotcue_count == before + 1) # cue type translation, both directions adapter.set_cue_type(tid2, free, "load") - check("generic cue type maps to Traktor's encoding", - next(c.type for c in adapter.track_cues(tid2).cues if c.hotcue == free) == 3) + check("cue type round-trips through the generic vocabulary", + next(c.type for c in adapter.track_cues(tid2).cues if c.slot == free) == "load") try: adapter.set_cue(tid2, slot=free, start_sec=1.0, cue_type="cue", role="memory") check("memory cues are refused on Traktor", False, "no error raised") @@ -132,7 +132,7 @@ with tempfile.TemporaryDirectory() as d: check("grid marker added and projected", len(adapter.track_cues(tid2).grid_markers) == grid_before + 1) check("marker count reached the track projection", - adapter.track(tid2).grid_markers == grid_before + 1) + adapter.track(tid2).grid_marker_count == grid_before + 1) # ---- analysed grid vs plain replace -------------------------------------- print("== set_analysed_grid writes Traktor's own shape, replace_grid does not ==") @@ -140,7 +140,7 @@ with tempfile.TemporaryDirectory() as d: work = Path(d) / "collection.nml" shutil.copy2(REAL, work) adapter = TraktorAdapter(work) - tid = next(t.id for t in adapter.tracks if t.has_grid) + tid = next(t.id for t in adapter.tracks if t.grid_marker_count) cues = adapter.replace_grid(tid, [(1.0, 128.0)]) check("replace_grid sets exactly the markers given", len(cues.grid_markers) == 1) @@ -179,12 +179,12 @@ with tempfile.TemporaryDirectory() as d: adapter = TraktorAdapter(work) tid = next( t.id for t in adapter.tracks - if len({c.hotcue for c in adapter.track_cues(t.id).cues if c.hotcue >= 0}) < 6 + if len({c.slot for c in adapter.track_cues(t.id).cues if c.slot is not None}) < 6 ) - used = {c.hotcue for c in adapter.track_cues(tid).cues if c.hotcue >= 0} + used = {c.slot for c in adapter.track_cues(tid).cues if c.slot is not None} free = [s for s in range(8) if s not in used][:2] adapter.place_cues(tid, [AutoHotcue(slot=free[0], start=30.0, name="Drop")]) - placed = next((c for c in adapter.track_cues(tid).cues if c.hotcue == free[0]), None) + placed = next((c for c in adapter.track_cues(tid).cues if c.slot == free[0]), None) check("batch-placed cue exists with its name", placed is not None and placed.name == "Drop") print("\nRESULT:", "FAILED" if failed else "ALL PASSED") diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index c0047aa..4b0bd55 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,6 +1,8 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useQuery, useQueryClient } from '@tanstack/react-query' import type { ColumnSizingState, SortingState, VisibilityState } from '@tanstack/react-table' +import { CapabilitiesContext } from './lib/capabilities' +import { writeHint } from './lib/platformCopy' import { api, type Track } from './api' import { DEFAULT_COLUMN_ORDER, @@ -113,6 +115,22 @@ export default function App() { } }, [columnVisibility, columnOrder, columnSizing]) + const collection = useQuery({ queryKey: ['collection'], queryFn: api.collection }) + const loaded = collection.data?.loaded ?? false + // What the loaded library can persist. Never stale within a session, and the + // app does not render until it resolves — so no first frame can offer an edit + // the adapter would reject. + const capabilities = useQuery({ + queryKey: ['capabilities'], + queryFn: api.capabilities, + enabled: loaded, + staleTime: Infinity, + }) + const save = capabilities.data?.save + // From the adapter, not a path split: a Serato library is a directory. + const libraryName = collection.data?.library?.display_name ?? null + const writeHintText = save ? writeHint(save) : 'save to write it to disk' + const notify = useCallback((kind: ToastMsg['kind'], text: string) => { setToast({ id: Date.now(), kind, text }) }, []) @@ -128,16 +146,13 @@ export default function App() { qc.invalidateQueries({ queryKey: ['playlist'] }) qc.invalidateQueries({ queryKey: ['state'] }) qc.invalidateQueries({ queryKey: ['facets'] }) - qc.invalidateQueries({ queryKey: ['stats'] }) - notify('success', `Updated ${String(field)} — Save to write to Traktor`) + notify('success', `Updated ${String(field)} — ${writeHintText}`) }) .catch((e) => onError((e as Error).message)) }, - [qc, notify, onError], + [qc, notify, onError, writeHintText], ) - const collection = useQuery({ queryKey: ['collection'], queryFn: api.collection }) - const loaded = collection.data?.loaded ?? false // NOTE: all hooks must run on every render (Rules of Hooks). Data queries are // gated with `enabled: loaded` so they don't fire before a collection is open; @@ -206,7 +221,7 @@ export default function App() { qc.invalidateQueries() // refetch everything for the newly-opened collection } - if (collection.isLoading) { + if (collection.isLoading || (loaded && !capabilities.data)) { return (
Loading… @@ -241,6 +256,7 @@ export default function App() { ) return ( +
setToast(null)} /> {menu && ( @@ -387,11 +403,12 @@ export default function App() { total={tracks.length} sourceName={isAll ? 'All Tracks' : source.name} loading={loading} - collectionName={collection.data?.path?.split('/').pop() ?? null} + collectionName={capabilities.data ? libraryName : null} onChangeCollection={() => setForcePicker(true)} />
+ ) } diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 3639b3d..e6e2a4e 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -12,20 +12,27 @@ export interface Track { mix: string | null comment: string | null bpm: number | null + /** The platform's own display string, shown verbatim: "10m", "8A", "Am". */ key: string | null + /** Camelot wheel position 1-12 + mode, parsed by the ADAPTER — notation is + * platform knowledge, not display formatting. Null when unparseable. */ + key_wheel: number | null + key_mode: 'major' | 'minor' | null rating: number playcount: number | null length: number | null bitrate: number | null + /** ISO-8601 "YYYY-MM-DD", normalised by the adapter. */ import_date: string | null last_played: string | null release_date: string | null filepath: string | null cue_count: number hotcue_count: number - has_grid: boolean - grid_markers: number // >1 = a flexible (multi-tempo) beatgrid - is_stem: boolean + /** 0 = no beatgrid, 1 = constant tempo, >1 = a flexible (multi-tempo) grid. */ + grid_marker_count: number + grid_locked: boolean + media_kind: MediaKind } export interface TrackPage { @@ -48,29 +55,21 @@ export interface Facets { total_tracks: number } -export interface Stats { - total_tracks: number - total_playlists: number - rated: number - unrated: number - missing_key: number - missing_genre: number - missing_bpm: number - no_cues: number - rating_breakdown: Record - bpm_histogram: { bucket: string; count: number }[] - top_genres: GenreCount[] -} - -export type PlaylistType = 'FOLDER' | 'PLAYLIST' | 'SMARTLIST' - export interface PlaylistNode { + /** Opaque, adapter-minted. The UI never constructs, parses or prefixes it. */ id: string name: string - type: PlaylistType - uuid: string | null + /** For choosing an icon only — every behavioural question is answered by the + * flags below, so the UI never infers what a node can do from its kind. */ + kind: PlaylistKind count: number children: PlaylistNode[] + selectable: boolean + can_add_tracks: boolean + can_reorder: boolean + can_rename: boolean + can_delete: boolean + can_contain_children: boolean } export type SortField = @@ -99,19 +98,31 @@ export interface TrackQuery { offset?: number } +export type Platform = string +export type CueRole = 'hotcue' | 'memory' +export type CueType = 'cue' | 'fade_in' | 'fade_out' | 'load' | 'loop' +export type MediaKind = 'audio' | 'stem' | 'video' +export type PlaylistKind = 'folder' | 'playlist' | 'smart' +export type TrackField = + | 'title' | 'artist' | 'album' | 'genre' | 'label' | 'remixer' + | 'producer' | 'mix' | 'release_date' | 'comment' | 'rating' + export interface CuePoint { name: string | null - type: number // 0 cue, 1 fade-in, 2 fade-out, 3 load, 4 grid, 5 loop + type: CueType + /** Memory cues have no bank slot. Only Rekordbox has them, so they are + * preserved and shown but not editable anywhere yet. */ + role: CueRole start: number // seconds length: number // seconds (>0 for loops) - hotcue: number // -1 if not a hotcue - color: string | null // "#RRGGBB" - /** - * Index of the grid marker this cue is the companion of, if any. Traktor - * pairs most grid markers with a white cue that occupies a real hotcue slot; - * it belongs to the beatgrid, so it is shown read-only and the backend - * refuses hotcue edits on it. - */ + slot: number | null // bank slot; null for a cue not in a bank + color: string | null // "#RRGGBB" as the platform stored it + /** False when the adapter refuses commands on this cue. Gate on THIS, never + * on a platform-specific reason like grid_marker. */ + editable: boolean + readonly_reason: 'beatgrid_companion' | 'platform_managed' | null + /** Index of the grid marker this cue mirrors, where the platform pairs them. + * A display hint only; null on platforms that do not. */ grid_marker: number | null } @@ -131,18 +142,74 @@ export interface TrackCues { * render and edit wrongly. */ grid_markers: GridMarker[] - locked: boolean + grid_locked: boolean cues: CuePoint[] } +export interface CueCapabilities { + hotcue_slots: number + slot_labels: 'number' | 'letter' + memory_cues: boolean + max_memory_cues: number | null + types: CueType[] + color: 'none' | 'free' | 'palette' + palette: string[] + named: boolean + loops: 'none' | 'cue_type' | 'separate_bank' + loop_slots: number | null +} + +export interface SaveCapabilities { + /** Structured facts, never finished sentences — the UI composes the wording + * (see lib/platformCopy.ts) so it stays specific without being hard-coded. */ + app_name: string + library_label: string + overwrite_risk: 'none' | 'on_exit' | 'while_running' + history: boolean +} + +export interface Capabilities { + platform: Platform + version: string | null + cues: CueCapabilities + grid: { editable: boolean; flexible: boolean; lockable: boolean } + tracks: { + rating_max: number + editable_fields: TrackField[] + media_kinds: MediaKind[] + artwork: boolean + artwork_note: string | null + } + playlists: { folders: boolean; smart: 'none' | 'read_only'; reorder: boolean } + save: SaveCapabilities +} + +export interface LibraryInfo { + platform: Platform + name: string // the DJ app's name, e.g. "Traktor" + library_label: string // e.g. "collection.nml" + path: string + display_name: string + version: string | null +} + +export interface PlatformOption { + platform: Platform + name: string + library_label: string + selects: 'file' | 'directory' + installed: boolean +} + export interface EditState { dirty: boolean - nml_path: string + library: LibraryInfo } export interface CollectionStatus { loaded: boolean path: string | null + library: LibraryInfo | null tracks: number | null playlists: number | null } @@ -259,28 +326,29 @@ function qs(params: Record): string { export const api = { // ---- collection selection ---- - collection: () => getJSON('/api/collection'), + collection: () => getJSON('/api/library'), openCollection: (path: string) => - send('POST', '/api/collection/open', { path }), - collectionOptions: () => getJSON('/api/collection/options'), + send('POST', '/api/library/open', { path }), + collectionOptions: () => getJSON('/api/library/options'), listDir: (path?: string) => getJSON(`/api/fs/list${path ? `?path=${encodeURIComponent(path)}` : ''}`), // ---- path remapping (per-collection OS-path prefix translation) ---- - getPathMapping: () => getJSON('/api/collection/path-mapping'), + getPathMapping: () => getJSON('/api/library/path-mapping'), suggestPrefix: () => - getJSON('/api/collection/path-mapping/suggest'), + getJSON('/api/library/path-mapping/suggest'), putPathMapping: (m: PathMapping) => - send('PUT', '/api/collection/path-mapping', m), + send('PUT', '/api/library/path-mapping', m), previewRemap: (from: string, to: string) => getJSON( - `/api/collection/path-mapping/preview?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`, + `/api/library/path-mapping/preview?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`, ), // Write-back: permanently rewrite matching LOCATIONs in the .nml (committed to history). remapPaths: (from: string, to: string) => - send('POST', '/api/collection/remap-paths', { from, to }), + send('POST', '/api/library/remap-paths', { from, to }), - stats: () => getJSON('/api/stats'), + capabilities: () => getJSON('/api/capabilities'), + platforms: () => getJSON('/api/platforms'), facets: () => getJSON('/api/facets'), playlists: () => getJSON('/api/playlists'), tracks: (query: TrackQuery) => @@ -292,18 +360,18 @@ export const api = { state: () => getJSON('/api/state'), createPlaylist: (name: string, parentId?: string) => send('POST', '/api/playlists', { name, parent_id: parentId ?? null }), - renamePlaylist: (uuid: string, name: string) => - send<{ status: string }>('PATCH', `/api/playlists/${uuid}`, { name }), - deletePlaylist: (uuid: string) => - send<{ status: string }>('DELETE', `/api/playlists/${uuid}`), - setEntries: (uuid: string, trackIds: string[]) => - send<{ status: string; count: number }>('PUT', `/api/playlists/${uuid}/entries`, { + renamePlaylist: (nodeId: string, name: string) => + send<{ status: string }>('PATCH', `/api/playlists/${encodeURIComponent(nodeId)}`, { name }), + deletePlaylist: (nodeId: string) => + send<{ status: string }>('DELETE', `/api/playlists/${encodeURIComponent(nodeId)}`), + setEntries: (nodeId: string, trackIds: string[]) => + send<{ status: string; count: number }>('PUT', `/api/playlists/${encodeURIComponent(nodeId)}/entries`, { track_ids: trackIds, }), - addEntries: (uuid: string, trackIds: string[]) => + addEntries: (nodeId: string, trackIds: string[]) => send<{ status: string; added: number; count: number }>( 'POST', - `/api/playlists/${uuid}/add`, + `/api/playlists/${encodeURIComponent(nodeId)}/add`, { track_ids: trackIds }, ), getPrefs: () => getJSON>('/api/prefs'), @@ -325,15 +393,15 @@ export const api = { `${API_BASE}/api/tracks/audio?track_id=${encodeURIComponent(trackId)}`, trackCues: (trackId: string) => getJSON(`/api/tracks/cues?track_id=${encodeURIComponent(trackId)}`), - createHotcue: ( + createCue: ( trackId: string, slot: number, start: number, - type: number, + type: CueType, length = 0, name?: string, ) => - send('POST', '/api/tracks/hotcue', { + send('POST', '/api/tracks/cue', { track_id: trackId, slot, start, @@ -342,20 +410,20 @@ export const api = { name, }), // Backend analyses the audio and places structural hotcues into empty slots. - autoHotcues: (trackId: string, maxCues?: number) => - send('POST', '/api/tracks/auto-hotcues', { + autoCues: (trackId: string, maxCues?: number) => + send('POST', '/api/tracks/cue/auto', { track_id: trackId, max_cues: maxCues, }), // Backend detects tempo + first beat: sets BPM, hotcue 1, and grid anchor. autoGrid: (trackId: string) => - send('POST', '/api/tracks/auto-grid', { track_id: trackId }), - setHotcueType: (trackId: string, slot: number, type: number) => - send('PATCH', '/api/tracks/hotcue', { track_id: trackId, slot, type }), - deleteHotcue: (trackId: string, slot: number) => + send('POST', '/api/tracks/grid/auto', { track_id: trackId }), + setCueType: (trackId: string, slot: number, type: CueType) => + send('PATCH', '/api/tracks/cue', { track_id: trackId, slot, type }), + deleteCue: (trackId: string, slot: number) => send( 'DELETE', - `/api/tracks/hotcue?track_id=${encodeURIComponent(trackId)}&slot=${slot}`, + `/api/tracks/cue?track_id=${encodeURIComponent(trackId)}&slot=${slot}`, ), /** Retempo and/or move one marker. `index` is its position in grid_markers; * a move is clamped between its neighbours rather than reordering them. */ @@ -378,8 +446,8 @@ export const api = { send('PUT', '/api/tracks/grid', { track_id: trackId, markers }), deleteGrid: (trackId: string) => send('DELETE', `/api/tracks/grid?track_id=${encodeURIComponent(trackId)}`), - setLock: (trackId: string, locked: boolean) => - send('PATCH', '/api/tracks/lock', { track_id: trackId, locked }), + setGridLock: (trackId: string, locked: boolean) => + send('PATCH', '/api/tracks/grid/lock', { track_id: trackId, locked }), uploadArt: async (trackId: string, file: File) => { const fd = new FormData() fd.append('track_id', trackId) diff --git a/frontend/src/components/CollectionPicker.tsx b/frontend/src/components/CollectionPicker.tsx index 6eefce7..22686c6 100644 --- a/frontend/src/components/CollectionPicker.tsx +++ b/frontend/src/components/CollectionPicker.tsx @@ -52,6 +52,13 @@ export function CollectionPicker({ onOpened, onCancel }: Props) { const [manual, setManual] = useState('') const options = useQuery({ queryKey: ['collectionOptions'], queryFn: api.collectionOptions }) + // The picker runs BEFORE a library is open, so capabilities do not exist yet — + // /api/platforms is the pre-load equivalent. + const { data: platforms } = useQuery({ queryKey: ['platforms'], queryFn: api.platforms }) + // One platform today, so name it; with more, stay general rather than listing. + const only = platforms?.length === 1 ? platforms[0] : null + const appName = only?.name ?? 'DJ' + const fileLabel = only?.library_label ?? 'library file' const listing = useQuery({ queryKey: ['fs', dir ?? '~'], queryFn: () => api.listDir(dir), @@ -76,12 +83,12 @@ export function CollectionPicker({ onOpened, onCancel }: Props) {
- Select your Traktor collection + Select your {appName} library
{mode === 'choose' ? 'Open automatically, resume your last one, or browse.' - : 'Choose a collection.nml file to open.'} + : `Choose a ${fileLabel} to open.`}
{mode === 'browse' && ( @@ -112,8 +119,8 @@ export function CollectionPicker({ onOpened, onCancel }: Props) { auto ? `${auto.label} · modified ${formatWhen(auto.modified)}` : options.isLoading - ? 'Searching for a Traktor collection…' - : 'No Traktor collection found in the default location' + ? `Searching for a ${appName} library…` + : `No ${appName} library found in the default location` } disabled={!auto} busy={open.isPending} @@ -136,7 +143,7 @@ export function CollectionPicker({ onOpened, onCancel }: Props) { setMode('browse')} /> @@ -218,7 +225,7 @@ export function CollectionPicker({ onOpened, onCancel }: Props) { onKeyDown={(e) => { if (e.key === 'Enter' && manual.trim()) open.mutate(manual.trim()) }} - placeholder="…or paste a full path to collection.nml" + placeholder={`…or paste a full path to ${fileLabel}`} className="min-w-0 flex-1 rounded-md border border-line bg-ink-850 px-3 py-2 font-mono text-xs text-text outline-none placeholder:text-faint focus:border-accent" /> - ))} + {rating > 0 && (

BPM, key and path aren’t editable here. Changes apply in-app; click - Save to Traktor to write them to disk. - New album art is written into the file; Traktor may need a manual + {saveLabel(caps.save)} to write them to disk. + New album art is written into the file.{' '} + {caps.tracks.artwork_note} + {'' /* platform-specific footnote, supplied by the adapter */} “Import Cover Art” to refresh its own cached thumbnail.

diff --git a/frontend/src/components/HistoryPanel.tsx b/frontend/src/components/HistoryPanel.tsx index f312c2b..bd175d4 100644 --- a/frontend/src/components/HistoryPanel.tsx +++ b/frontend/src/components/HistoryPanel.tsx @@ -1,6 +1,8 @@ import { useState } from 'react' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { api, type HistoryEntry } from '../api' +import { useCaps } from '../lib/capabilities' +import { restoreWarning } from '../lib/platformCopy' import type { ToastMsg } from './Toast' interface Props { @@ -37,9 +39,10 @@ function summaryChips(summary: string): string[] { * a purely-local git repo (see backend history.py); this lists them newest-first * and lets the user restore any past version (written back as a new forward save) * or wipe the entire history. Restore overwrites the collection on disk, so the - * user must close Traktor first (it rewrites the .nml on exit). + * user is warned first, in the loaded platform's own terms. */ export function HistoryPanel({ onClose, onNotify, onError }: Props) { + const caps = useCaps() const qc = useQueryClient() const history = useQuery({ queryKey: ['history'], queryFn: api.history }) const [confirmingId, setConfirmingId] = useState(null) @@ -87,8 +90,7 @@ export function HistoryPanel({ onClose, onNotify, onError }: Props) {
Version History
- Every save is a restorable version of this collection. Close Traktor before - restoring — it overwrites the collection on exit. + Every save is a restorable version of this library. {restoreWarning(caps.save)}
diff --git a/frontend/src/components/HotcueBar.tsx b/frontend/src/components/HotcueBar.tsx index b332d73..c837d0a 100644 --- a/frontend/src/components/HotcueBar.tsx +++ b/frontend/src/components/HotcueBar.tsx @@ -1,14 +1,21 @@ import type { CuePoint } from '../api' -import { contrastText, cueColor, GRID_MARKER_COLOR } from '../lib/cues' +import { contrastText, cueColor, cueGlyph } from '../lib/cues' interface Props { cues: CuePoint[] + /** Bank size, from capabilities — not every platform has eight. */ + slotCount: number + /** How a slot is labelled ("1".."8" or "A".."H"). */ + slotLabel: (slot: number) => string selectedSlot: number | null onSlotPress: (slot: number) => void onSlotRelease: (slot: number) => void } -const SLOTS = [0, 1, 2, 3, 4, 5, 6, 7] // Traktor hotcue slots → labelled 1–8 +const READONLY_LABELS: Record = { + beatgrid_companion: 'Beatgrid marker — managed by the grid controls', + platform_managed: 'Managed by the DJ app — not editable here', +} /** * The 8 hotcue slots, colour-coded by cue type when assigned (gray when empty). @@ -24,14 +31,24 @@ const SLOTS = [0, 1, 2, 3, 4, 5, 6, 7] // Traktor hotcue slots → labelled 1– * the backend refuses hotcue edits on them, and showing that up front is better * than surfacing the refusal as an error. */ -export function HotcueBar({ cues, selectedSlot, onSlotPress, onSlotRelease }: Props) { +export function HotcueBar({ + cues, + slotCount, + slotLabel, + selectedSlot, + onSlotPress, + onSlotRelease, +}: Props) { return (
- {SLOTS.map((slot) => { - const cue = cues.find((c) => c.hotcue === slot) ?? null - const isMarker = cue?.grid_marker != null - const selected = selectedSlot === slot && !isMarker - const color = cue ? (isMarker ? GRID_MARKER_COLOR : cueColor(cue)) : null + {Array.from({ length: slotCount }, (_, i) => i).map((slot) => { + const cue = cues.find((c) => c.role === 'hotcue' && c.slot === slot) ?? null + // Gate on `editable`, never on why: a platform-owned cue is a read-only + // case, not a Traktor-companion case. + const locked = cue != null && !cue.editable + const selected = selectedSlot === slot && !locked + const color = cue ? cueColor(cue) : null + const glyph = cue ? cueGlyph(cue) : '' return ( ) })} diff --git a/frontend/src/components/PrepStrip.tsx b/frontend/src/components/PrepStrip.tsx index 3b5a7bb..4b201c2 100644 --- a/frontend/src/components/PrepStrip.tsx +++ b/frontend/src/components/PrepStrip.tsx @@ -1,7 +1,9 @@ import { useEffect, useMemo, useRef, useState } from 'react' import { useQuery, useQueryClient } from '@tanstack/react-query' -import { api, type GridMarker, type Track, type TrackCues } from '../api' +import { api, type CueType, type GridMarker, type Track, type TrackCues } from '../api' import { buildBeatGrid, GRID_EPS } from '../lib/beatgrid' +import { slotLabeller, useCaps } from '../lib/capabilities' +import { CUE_TYPE_LABELS } from '../lib/cues' import { analyzeWaveform, type WaveColumn } from '../lib/waveform' import { ScratchEngine } from '../lib/scratchEngine' import { PlaybackEngine } from '../lib/playbackEngine' @@ -29,13 +31,22 @@ function fmt(secs: number): string { return `${m}:${s.toString().padStart(2, '0')}` } -const CUE_TYPES: { value: number; label: string }[] = [ - { value: 0, label: 'Cue' }, - { value: 1, label: 'Fade-In' }, - { value: 2, label: 'Fade-Out' }, - { value: 3, label: 'Load' }, -] -const LOOP_TYPE = 5 +/** + * Digit key -> bank slot: 1..9 map to slots 0..8 and 0 maps to slot 10. + * + * Ten digits is the physical ceiling, so a bank larger than that simply has no + * shortcut for its tail. Returns null when the key is not a digit or the slot is + * beyond this platform's bank — an 8-slot bank behaves exactly as before. + */ +const DIGIT_RE = /^(?:Digit|Numpad)([0-9])$/ + +function slotForDigit(code: string, slotCount: number): number | null { + const m = code.match(DIGIT_RE) + if (!m) return null + const slot = m[1] === '0' ? 9 : Number(m[1]) - 1 + return slot < slotCount ? slot : null +} + const LOOP_SIZES = [1 / 32, 1 / 16, 1 / 8, 1 / 4, 1 / 2, 1, 2, 4, 8, 16, 32] /** @@ -549,8 +560,17 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) // eslint-disable-next-line react-hooks/exhaustive-deps }, [grid]) + // ---- capability-derived ----------------------------------------------- + const caps = useCaps() + const slotCount = caps.cues.hotcue_slots + const slotLabel = slotLabeller(caps) + // Loops are a cue TYPE on some platforms and a separate bank on others; the + // dropdown only ever offers the point types. + const pointCueTypes = caps.cues.types.filter((t) => t !== 'loop') + // ---- hotcues ---------------------------------------------------------- - const hotcueAt = (slot: number) => cueData?.cues.find((c) => c.hotcue === slot) ?? null + const hotcueAt = (slot: number) => + cueData?.cues.find((c) => c.role === 'hotcue' && c.slot === slot) ?? null const applyCueEdit = (fresh: TrackCues) => { setCueData(fresh) @@ -597,10 +617,10 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) // Setting a hotcue while a loop is active stores it as a loop hotcue. if (loopActive && loopRegion) { const len = loopRegion.end - loopRegion.start - applyCueEdit(await api.createHotcue(track.id, slot, loopRegion.start, LOOP_TYPE, len)) + applyCueEdit(await api.createCue(track.id, slot, loopRegion.start, 'loop', len)) } else { const t = snapTime(playbackRef.current?.getPosition() ?? current) - applyCueEdit(await api.createHotcue(track.id, slot, t, 0)) + applyCueEdit(await api.createCue(track.id, slot, t, 'cue')) } setSelectedSlot(slot) } catch (e) { @@ -613,7 +633,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) if (!eng || !eng.ready) return getCtx() // A loop hotcue jumps to its start AND re-engages a loop of its length. - if (cue.type === LOOP_TYPE && cue.length > 0) { + if (cue.type === 'loop' && cue.length > 0) { seek(cue.start) engagLoop(cue.start, cue.start + cue.length, beatsForLoop(cue.start, cue.length)) } else { @@ -633,15 +653,15 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) const runAutoHotcues = async () => { if (!track || !canAutoCue || autoBusy) return const hotcueCount = (c: TrackCues | null) => - c?.cues.filter((x) => x.hotcue >= 0).length ?? 0 - if (hotcueCount(cueData) >= 8) { - onError?.('No free hotcue slots — delete some first') + c?.cues.filter((x) => x.role === 'hotcue' && x.slot != null).length ?? 0 + if (hotcueCount(cueData) >= slotCount) { + onError?.(`No free hotcue slots (${slotCount} of ${slotCount} used) — delete some first`) return } setAutoBusy(true) try { const before = hotcueCount(cueData) - const fresh = await api.autoHotcues(track.id) + const fresh = await api.autoCues(track.id) applyCueEdit(fresh) const placed = Math.max(0, hotcueCount(fresh) - before) if (placed === 0) { @@ -656,10 +676,10 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) } } - const changeSelectedType = async (type: number) => { + const changeSelectedType = async (type: CueType) => { if (!track || selectedSlot == null) return try { - applyCueEdit(await api.setHotcueType(track.id, selectedSlot, type)) + applyCueEdit(await api.setCueType(track.id, selectedSlot, type)) } catch (e) { onError?.((e as Error).message) } @@ -668,7 +688,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) const deleteSelected = async () => { if (!track || selectedSlot == null) return try { - applyCueEdit(await api.deleteHotcue(track.id, selectedSlot)) + applyCueEdit(await api.deleteCue(track.id, selectedSlot)) setSelectedSlot(null) } catch (e) { onError?.((e as Error).message) @@ -680,7 +700,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) if (!track || !existing) return // nothing to remove in an empty slot if (existing.grid_marker != null) return // beatgrid-owned: delete the marker instead try { - applyCueEdit(await api.deleteHotcue(track.id, slot)) + applyCueEdit(await api.deleteCue(track.id, slot)) if (selectedSlot === slot) setSelectedSlot(null) } catch (e) { onError?.((e as Error).message) @@ -757,7 +777,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) const toggleLock = async () => { if (!track) return try { - applyCueEdit(await api.setLock(track.id, !cueData?.locked)) + applyCueEdit(await api.setGridLock(track.id, !cueData?.grid_locked)) } catch (e) { onError?.((e as Error).message) } @@ -799,6 +819,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) beatJump, prevMarker, nextMarker, + slotCount, }) shortcutsRef.current = { toggle, @@ -810,6 +831,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) beatJump, prevMarker, nextMarker, + slotCount, } useEffect(() => { const onKey = (e: KeyboardEvent) => { @@ -840,10 +862,9 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) else shortcutsRef.current.beatJump(1) return } - const digit = e.code.match(/^(?:Digit|Numpad)([1-8])$/) - if (digit) { + const slot = slotForDigit(e.code, shortcutsRef.current.slotCount) + if (slot != null) { e.preventDefault() - const slot = Number(digit[1]) - 1 if (e.shiftKey) void shortcutsRef.current.deleteHotcueSlot(slot) else void shortcutsRef.current.onSlotPress(slot) } @@ -851,8 +872,8 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) // keyup ends a held hotcue's momentary preview (release). const onKeyRelease = (e: KeyboardEvent) => { if (e.code === 'KeyC') shortcutsRef.current.onCueRelease() - const digit = e.code.match(/^(?:Digit|Numpad)([1-8])$/) - if (digit) shortcutsRef.current.onSlotRelease(Number(digit[1]) - 1) + const slot = slotForDigit(e.code, shortcutsRef.current.slotCount) + if (slot != null) shortcutsRef.current.onSlotRelease(slot) } window.addEventListener('keydown', onKey) window.addEventListener('keyup', onKeyRelease) @@ -893,7 +914,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) markerStart={activeMarker?.start ?? null} atMarker={atMarker} beforeFirst={beforeFirstMarker} - locked={cueData?.locked ?? false} + locked={cueData?.grid_locked ?? false} canReset={originalGridRef.current != null} onSetBpm={setBpm} onNudgeBpm={nudgeBpm} @@ -1034,24 +1055,32 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
- {selectedCue && selectedCue.type === LOOP_TYPE ? ( + {selectedCue && selectedCue.type === 'loop' ? ( Loop + ) : pointCueTypes.length < 2 ? ( + // One point type means there is nothing to choose between — + // show it rather than a dropdown that cannot change anything. + + {selectedCue ? CUE_TYPE_LABELS[selectedCue.type] : '—'} + ) : ( diff --git a/frontend/src/components/RatingStars.tsx b/frontend/src/components/RatingStars.tsx index 4f17cfd..cdee86d 100644 --- a/frontend/src/components/RatingStars.tsx +++ b/frontend/src/components/RatingStars.tsx @@ -2,22 +2,25 @@ import { useState } from 'react' interface Props { value: number - /** When provided, the stars become clickable to set the rating (0–5). */ + /** Scale length, from capabilities.tracks.rating_max. */ + max?: number + /** When provided, the stars become clickable to set the rating. */ onChange?: (value: number) => void } -// Compact 5-star rating. Read-only by default (shows a dash when unrated). When -// `onChange` is given it's interactive: always shows five stars — hollow (☆) up -// to the rating, solid gold (★) below it — with hover preview. Clicking a star -// sets that rating; clicking the current top star again clears it to 0. -export function RatingStars({ value, onChange }: Props) { +// Compact star rating. Read-only by default (shows a dash when unrated). When +// `onChange` is given it's interactive: hollow (☆) above the rating, solid gold +// (★) up to it, with hover preview. Clicking a star sets that rating; clicking +// the current top star again clears it to 0. +export function RatingStars({ value, max = 5, onChange }: Props) { const [hover, setHover] = useState(0) + const stars = Array.from({ length: max }, (_, i) => i + 1) if (!onChange) { if (!value) return — return ( - - {[1, 2, 3, 4, 5].map((i) => ( + + {stars.map((i) => ( {i <= value ? '★' : '☆'} @@ -28,8 +31,8 @@ export function RatingStars({ value, onChange }: Props) { const shown = hover || value return ( - - {[1, 2, 3, 4, 5].map((i) => ( + + {stars.map((i) => ( - {node.can_rename && !renaming && ( - <> - - - - {node.count} - - + {/* Each action gates on ITS OWN flag: a platform may allow renaming but + not deleting. The count shows either way — it is information, not an + action, and hiding it on a read-only library loses real data. */} + {!renaming && node.can_rename && ( + + )} + {!renaming && node.can_delete && ( + + )} + {!renaming && !isFolder && ( + + {node.count} + )}
{isFolder && open && node.children.length > 0 && ( @@ -162,6 +172,9 @@ function NodeRow({ export function Sidebar({ source, onSelect, onError, onOpenHistory }: Props) { const qc = useQueryClient() + // There is no per-node flag for "you may create a NEW playlist" — the node + // flags describe existing nodes — so this is the library-level gate. + const canCreate = useCaps().writable const [creating, setCreating] = useState(false) const [newName, setNewName] = useState('') const { data: playlists, isLoading } = useQuery({ @@ -205,16 +218,18 @@ export function Sidebar({ source, onSelect, onError, onOpenHistory }: Props) { Playlists - + {canCreate && ( + + )}
diff --git a/frontend/src/lib/capabilities.tsx b/frontend/src/lib/capabilities.tsx index f58b6eb..bf42d8e 100644 --- a/frontend/src/lib/capabilities.tsx +++ b/frontend/src/lib/capabilities.tsx @@ -30,3 +30,9 @@ export function slotLabeller(caps: Capabilities): (slot: number) => string { ? (slot) => String.fromCharCode(65 + slot) : (slot) => String(slot + 1) } + +/** Whether the loaded library accepts edits at all. Gate every edit affordance + * on this in addition to the relevant per-feature capability. */ +export function useWritable(): boolean { + return useCaps().writable +} diff --git a/frontend/src/lib/platformCopy.ts b/frontend/src/lib/platformCopy.ts index 7144708..2a60570 100644 --- a/frontend/src/lib/platformCopy.ts +++ b/frontend/src/lib/platformCopy.ts @@ -6,7 +6,7 @@ * staying genuinely specific — the pre-save warning is a real, per-platform * hazard and must not be watered down into something vague. */ -import type { SaveCapabilities } from '../api' +import type { Capabilities, SaveCapabilities } from '../api' export function saveLabel(save: SaveCapabilities): string { return `Save to ${save.app_name}` @@ -39,3 +39,28 @@ export function restoreWarning(save: SaveCapabilities): string | null { export function writeHint(save: SaveCapabilities): string { return `Save to ${save.app_name} to write it to disk` } + +/** + * Why this library is read-only, or null when it is editable. + * + * The two causes need genuinely different wording: a missing feature is a gap + * the user should expect Konduktor to close, whereas a cloud-synced library is + * a deliberate, permanent refusal that protects their other machines — and a + * user told only "read-only" would reasonably file the second as a bug. + */ +export function readOnlyNotice(caps: Capabilities): string | null { + if (caps.writable) return null + switch (caps.readonly_cause) { + case 'cloud_synced': + return `This ${caps.save.app_name} library is synced with ${caps.save.app_name} Cloud, so Konduktor will not write to it — an edit it did not make could break syncing on your other devices.` + case 'platform_incomplete': + default: + return `Konduktor can read ${caps.save.app_name} libraries but cannot save changes to them yet.` + } +} + +/** Compact form for a badge or a disabled control's tooltip. */ +export function readOnlyShort(caps: Capabilities): string | null { + if (caps.writable) return null + return caps.readonly_cause === 'cloud_synced' ? 'Read-only · cloud-synced' : 'Read-only' +} From 43e712afbd6ab163f406d4642b0a3f350b0e968c Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Fri, 18 Sep 2026 12:59:44 +0200 Subject: [PATCH 08/64] Extended Rekordbox support --- .claude/handoffs/rekordbox-adapter.md | 68 +++++ CLAUDE.md | 44 +++- .../konduktor/adapters/rekordbox/adapter.py | 100 ++++++-- .../adapters/rekordbox/capabilities.py | 34 ++- backend/konduktor/adapters/rekordbox/store.py | 190 +++++++++++++- .../adapters/traktor/capabilities.py | 1 + backend/konduktor/adapters/traktor/store.py | 9 +- backend/konduktor/app_state.py | 23 +- backend/konduktor/core/adapter.py | 23 ++ backend/konduktor/core/capabilities.py | 4 + backend/run_tests.sh | 2 +- backend/test_rekordbox_adapter.py | 86 +++++-- backend/test_rekordbox_fidelity.py | 241 ++++++++++++++++++ frontend/src/api.ts | 3 + frontend/src/components/PrepStrip.tsx | 56 ++-- frontend/src/components/TrackTable.tsx | 18 +- frontend/src/lib/trackColumns.tsx | 35 ++- 17 files changed, 837 insertions(+), 100 deletions(-) create mode 100644 backend/test_rekordbox_fidelity.py diff --git a/.claude/handoffs/rekordbox-adapter.md b/.claude/handoffs/rekordbox-adapter.md index c701392..cb97080 100644 --- a/.claude/handoffs/rekordbox-adapter.md +++ b/.claude/handoffs/rekordbox-adapter.md @@ -758,3 +758,71 @@ they will need components to actually read them: **this change did not retrofit per-feature gating**, it added the library-level gate that was missing. A platform that is writable but cannot, say, edit a beatgrid would still offer the control today. + +--- + +## 11. Milestone 2: metadata + playlist writes + +**Scope decision (Ben, 2026-09-18): shipping Rekordbox writes with NO undo is +accepted.** `capabilities.save.history` stays `False` — a Rekordbox library is +`master.db` + ~200 ANLZ files + `masterPlaylists6.xml`, and restoring the +database alone would roll back Rekordbox's auth token and sampler state (§8.9). +Rekordbox's own `master.backup.db` is the only safety net. Revisit only if Ben +asks; do not silently add a half-backup. + +What turns on here: **track metadata and playlists**. Cues and the beatgrid stay +read-only until milestone 3 (§8.2, §8.4 — both are hand-written write paths). + +### Milestone 2 landed + +`./run_tests.sh` green at **258 assertions**; `npm run build` + 25 vitest pass. +Rekordbox now accepts **track metadata and playlist** edits. Cues and the +beatgrid still refuse, and now say so through `cues.editable` / `grid.editable` +rather than through the library-level flag. + +**Per-feature gating came first, deliberately.** §10 warned that flipping +`writable` would re-expose every prep control, because `caps.writable` was the +only gate in the app. So `cues.editable` was added to `CueCapabilities` +(symmetric with `grid.editable`), the 12 PrepStrip handlers were split onto +`refuseCueEdit` / `refuseGridEdit`, and the tables now gate **per field** via a +`editableFields` set in the table meta — `InlineEdit` takes a `readOnly` prop and +`RatingStars` simply loses its `onChange`. Without that, milestone 2 would have +shipped a regression. + +**Three real bugs found by building it:** + +1. **Foreign-key edits projected as no-ops.** `artist`/`album`/`genre`/`label`/ + `remixer` are FKs into lookup tables. Setting the id does not move + SQLAlchemy's cached relationship, so re-projecting immediately read the OLD + name back — the API returned `genre: null` for an edit that had in fact + worked. Fixed with a flush + expire; pinned by a test that sets both a brand + new lookup value and an existing one. +2. **`close()` did not release the file.** `pyrekordbox`'s `close()` only closes + the session; the pooled connection keeps the OS handle, so `master.db` could + not be replaced. Now disposes the engine. This surfaced as a `disk I/O error` + in the fidelity test and would have surfaced in production as a failed + restore or a locked library. +3. **Nothing ever closed the previous library.** `AppState.open()` replaced the + adapter without closing it, leaking a handle per library switch. It now closes + the old one *after* the new one parses, so a failed open leaves the current + library intact. + +**`SaveOutcome` was promoted to `core/adapter.py`** under the two-platform rule, +with `snapshot` now optional — Rekordbox has no single blob that IS the library. +`AppState.save()` gates version history on `capabilities.save.history` instead of +assuming every platform is versioned. + +Also corrected in CLAUDE.md: the cue routes are `/api/tracks/cue`, not +`/api/tracks/hotcue`. + +### What milestone 3 inherits + +- `cues.editable` / `grid.editable` are the flags to flip, and the UI already + gates on them — no frontend work should be needed beyond flipping them. +- `beatgrid.beats_from_markers()` is written and unit-tested as the inverse of + the read projection. +- The cue write must maintain **both** `djmdCue` rows and the `contentCue` JSON + mirror + `rb_cue_count` (§8.2), and should decide deliberately whether to stamp + `rb_local_usn` on `djmdCue` rows — Rekordbox itself leaves them NULL. +- `test_rekordbox_fidelity.py` is the harness to extend: add a cue edit and a + grid edit as phases F and G, asserting the same "exactly these rows" property. diff --git a/CLAUDE.md b/CLAUDE.md index e0dc140..04aa7b0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -59,7 +59,8 @@ Two independent apps that talk over HTTP: - `driver.py`/`discovery.py` — `can_open`, default-location detection, restore. - `beatgrid.py`, `locations.py`, `capabilities.py` — Traktor's grid/companion rules, LOCATION ↔ OS path conversion, and its capability set. - - `adapters/rekordbox/` — **READ-ONLY** (milestone 1 of the Rekordbox work). + - `adapters/rekordbox/` — **track metadata + playlists writable; cues and the + beatgrid still read-only** (milestone 2). `master.db` is SQLCipher-encrypted SQLite, read via `pyrekordbox`. Every mutating command raises `Unsupported` and `capabilities()` advertises nothing as editable, so the UI never offers an edit. Three things differ from Traktor @@ -79,7 +80,23 @@ Two independent apps that talk over HTTP: mapping is NOT a plain index and is deliberately left to the UI. Writes are refused outright on a **cloud-synced** library (detected by a server-issued `usn` on any row): a bad sync state would propagate to the - user's other machines, which version history cannot undo. + user's other machines, and there is no version history here to undo it. + Every command passes through `_require_writable()` so a command added later + cannot forget that check. + Edits accumulate in the SQLAlchemy session and `save()` commits — which maps + onto Konduktor's "edit in memory, Save writes to disk" model exactly, since + `pyrekordbox`'s `commit()` is what assigns Rekordbox's USNs. A real Rekordbox + 7 was verified to accept a library written this way, display the edit, leave + the row alone, and continue from the counter it was left at. + `artist`/`album`/`genre`/`label`/`remixer` are **foreign keys into lookup + tables**, so a write is find-or-create (pyrekordbox's `add_*` RAISES on an + existing name) followed by a **flush + expire** — without which the ORM + re-reads the stale relationship and a successful edit projects as a no-op. + `producer`/`mix` are absent from `editable_fields`: Rekordbox has no column + for them and its Composer is a different field. + `close()` disposes the SQLAlchemy engine, not just the session — otherwise + the OS file handle stays open and `master.db` cannot be replaced. `AppState` + closes the previous adapter when opening a new library. - `app_state.py` — the one loaded library, and the **version-history commit**. History is app-level: the adapter returns the bytes it wrote plus a summary, and `AppState.save()` versions them. Every write path must go through it. @@ -219,6 +236,12 @@ serialization path.** It enforces: projection, playlist tree, capabilities and the refusal of all 21 commands against a **temp copy** of the local Rekordbox library. Skips cleanly when no Rekordbox is installed, so it is safe on any machine. +- `test_rekordbox_fidelity.py` — the **row-level analogue of the byte diff**: a + full table dump before/after, compared row by row (a byte diff is meaningless + against SQLite). Asserts a no-op save changes zero rows; a one-field edit + changes exactly two — the track and `agentRegistry.localUpdateCount` — with the + counter up by one and the edited row stamped with it; edits are invisible on + disk until save; and playlist create/fill/rename/delete round-trip. - `test_layering.py` — `core/` imports nothing platform-specific, and no adapter imports another platform's library (checked on real imports via AST, so merely naming a platform in a comment is fine). @@ -327,12 +350,15 @@ that number and nothing else — everything derives from it: - ✅ Generic model + adapter interface (Traktor as the only adapter) — step 2 of the multi-platform plan. Backend, wire format and UI are all generic; nothing above `adapters/traktor/` knows what Traktor is. -- 🟡 Rekordbox adapter — **read-only milestone done**: a Rekordbox library opens, - projects and browses through the generic layer (tracks, playlists, cues, - beatgrid), with every command refused. Research for the write path is captured - in `.claude/handoffs/rekordbox-adapter.md` §8, incl. the verified result that - Rekordbox accepts Konduktor-written rows when USNs are maintained. Remaining: - metadata/playlist writes, then the hand-written cue store and ANLZ grid store. +- 🟡 Rekordbox adapter — **read + metadata/playlist writes done** (milestones 1 + and 2). A Rekordbox library opens, projects, browses and now accepts track + metadata and playlist edits, verified row-by-row by `test_rekordbox_fidelity.py` + and end to end through the API. Research is captured in + `.claude/handoffs/rekordbox-adapter.md` §8, incl. the verified result that + Rekordbox accepts Konduktor-written rows when USNs are maintained. Remaining + (milestone 3): the hand-written cue store (`djmdCue` + the `contentCue` JSON + mirror) and the ANLZ beatgrid store. **No version history on Rekordbox** — + accepted scope decision, see handoff §11. - ⬜ Serato adapter; ⬜ export/conversion - ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging @@ -389,7 +415,7 @@ diff — no COLLECTION splicing needed. `POST/PATCH/DELETE /api/playlists[...]`, `PUT .../entries` (replace), `POST .../add` (append); `PATCH /api/tracks` (metadata); `GET/PUT /api/tracks/art` (cover art); `GET /api/tracks/audio` (Range-aware stream for playback/analysis); - `GET /api/tracks/cues`, `POST/PATCH/DELETE /api/tracks/hotcue`, + `GET /api/tracks/cues`, `POST/PATCH/DELETE /api/tracks/cue`, `POST/PATCH/DELETE /api/tracks/grid/marker`, `PUT /api/tracks/grid` (replace), `DELETE /api/tracks/grid`, `PATCH /api/tracks/lock` (prep); `POST /api/save`. diff --git a/backend/konduktor/adapters/rekordbox/adapter.py b/backend/konduktor/adapters/rekordbox/adapter.py index b0a593a..a02fe70 100644 --- a/backend/konduktor/adapters/rekordbox/adapter.py +++ b/backend/konduktor/adapters/rekordbox/adapter.py @@ -5,14 +5,17 @@ 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. -**Read-only milestone.** Every mutating command raises `Unsupported`, and -`capabilities()` reports nothing as editable, so a correct UI never offers one -in the first place; the raise is the backstop, not the mechanism. +**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 for a second, permanent reason on a cloud-synced library: +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. That check lives here so it cannot be bypassed by a -future command path forgetting it. +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 @@ -48,6 +51,25 @@ class RekordboxAdapter: ] ) + 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. + """ + counts = self._store.cue_counts() + row = self._store.content(track_id) + self._index.replace(projection.to_track(row, counts.get(str(row.ID), (0, 0)))) + + 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: self._store._load() self._cloud_synced = self._store.cloud_synced @@ -55,7 +77,11 @@ class RekordboxAdapter: # ---- identity -------------------------------------------------------- def capabilities(self) -> Capabilities: - return caps.capabilities_for(self.path, cloud_synced=self._cloud_synced) + return caps.capabilities_for( + self.path, + cloud_synced=self._cloud_synced, + editable_fields=sorted(RekordboxStore.EDITABLE_FIELDS), + ) @property def cloud_synced(self) -> bool: @@ -107,6 +133,7 @@ class RekordboxAdapter: 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] = {} @@ -122,10 +149,13 @@ class RekordboxAdapter: children=[], # A smart playlist has no static entry list; a folder has no tracks. selectable=kind == "playlist", - can_add_tracks=False, - can_reorder=False, - can_rename=False, - can_delete=False, + # 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") @@ -184,13 +214,38 @@ class RekordboxAdapter: def remap_locations(self, mapping: PathMapping) -> int: 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 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) + # ---- save ------------------------------------------------------------- @property def dirty(self) -> bool: - return False + return self._store.dirty def save(self): - raise Unsupported(self._readonly_reason("Saving")) + self._require_writable("Saving") + return self._store.save() def snapshot(self) -> bytes: """The library's bytes, for version history. @@ -216,20 +271,11 @@ class RekordboxAdapter: def _refuse(self, what: str): raise Unsupported(self._readonly_reason(what)) - def create_playlist(self, name: str, parent_id: str | None = None) -> str: - self._refuse("Creating playlists") - - 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_track_metadata(self, track_id: str, fields: dict) -> Track | None: - self._refuse("Editing track metadata") + 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 set_cover_art(self, track_id: str, data: bytes, mime: str) -> None: self._refuse("Editing cover art") diff --git a/backend/konduktor/adapters/rekordbox/capabilities.py b/backend/konduktor/adapters/rekordbox/capabilities.py index dbaa09f..8163b67 100644 --- a/backend/konduktor/adapters/rekordbox/capabilities.py +++ b/backend/konduktor/adapters/rekordbox/capabilities.py @@ -1,10 +1,14 @@ """What a Rekordbox library can persist. -**Milestone 1 reports everything as read-only.** The spike verified that -Rekordbox accepts writes that maintain its USN columns (see the handoff's -Findings), but the write path is not built yet, and the capability system exists -precisely so the UI never offers an edit that will not persist. Every flag here -is therefore false/empty until milestone 2 turns them on one at a time. +**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: @@ -35,7 +39,11 @@ HOTCUE_SLOTS = 8 def capabilities_for( - path, version: str | None = None, *, cloud_synced: bool = False + 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 @@ -43,9 +51,12 @@ def capabilities_for( return Capabilities( platform="rekordbox", version=version, - writable=False, - readonly_cause="cloud_synced" if cloud_synced else "platform_incomplete", + writable=not cloud_synced, + readonly_cause="cloud_synced" if cloud_synced else None, cues=CueCapabilities( + # Milestone 3: the cue store is hand-written (djmdCue rows plus the + # contentCue JSON mirror, kept consistent) and does not exist yet. + editable=False, hotcue_slots=HOTCUE_SLOTS, slot_labels="letter", # Rekordbox is the only platform with memory cues, so they are @@ -61,12 +72,15 @@ def capabilities_for( grid=GridCapabilities(editable=False, flexible=True, lockable=False), tracks=TrackCapabilities( rating_max=5, # Rekordbox stores 0-5 directly, unlike Traktor's /51 - editable_fields=[], # read-only in this milestone + # 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 []), media_kinds=["audio"], artwork=False, artwork_note=None, ), - playlists=PlaylistCapabilities(folders=True, smart="read_only", reorder=False), + playlists=PlaylistCapabilities(folders=True, smart="read_only", reorder=True), save=SaveCapabilities( app_name="Rekordbox", library_label="master.db", diff --git a/backend/konduktor/adapters/rekordbox/store.py b/backend/konduktor/adapters/rekordbox/store.py index 19235ab..411fd3a 100644 --- a/backend/konduktor/adapters/rekordbox/store.py +++ b/backend/konduktor/adapters/rekordbox/store.py @@ -3,8 +3,16 @@ This is the only module that knows ``pyrekordbox`` exists. It owns the decrypted SQLCipher session, the ANLZ analysis files, and the caches the projection reads. -**Read-only in this milestone.** The write path is deliberately absent rather -than stubbed: a store that cannot write cannot half-write. +**Writes cover track metadata and playlists.** Cues and the beatgrid are +deliberately absent rather than stubbed — they are separate stores (two DB tables +kept consistent, and the ANLZ analysis files) and a store that cannot write them +cannot half-write them. + +Edits accumulate in the SQLAlchemy session and are only made permanent by +`save()`, which maps exactly onto Konduktor's "edit in memory, Save writes to +disk" model. `pyrekordbox`'s `commit()` is what assigns Rekordbox's update +sequence numbers, and a real Rekordbox was verified to accept and continue from +the result — see the handoff's Findings. Two things here are not obvious and are load-bearing: @@ -24,7 +32,8 @@ from pathlib import Path from sqlalchemy import func, select, text from sqlalchemy.orm import joinedload -from ...core.adapter import LibraryNotSupported, NotFound +from ...core.adapter import InvalidCommand, LibraryNotSupported, NotFound, SaveOutcome +from ...core.edit_journal import EditJournal from ...core.pathmap import PathMapping log = logging.getLogger(__name__) @@ -37,6 +46,7 @@ class RekordboxStore: self.path = Path(path) self._mapping = PathMapping() self._grid_cache: dict[str, tuple[list[float], list[float]] | None] = {} + self._journal = EditJournal() self._load() # ---- open ------------------------------------------------------------ @@ -54,10 +64,22 @@ class RekordboxStore: self._by_id: dict[str, object] | None = None def close(self) -> None: + """Release the session AND the pooled connection. + + `pyrekordbox`'s own `close()` only closes the SQLAlchemy session, which + returns the connection to the engine's pool — the OS file handle stays + open. Disposing the engine is what actually releases `master.db`, and + without it the file cannot be replaced (a restore, or a test copying a + fresh library over it) on any platform that locks open files. + """ try: self._db.close() except Exception: # noqa: BLE001 — closing must never raise pass + try: + self._db.engine.dispose() + except Exception: # noqa: BLE001 + pass # ---- identity -------------------------------------------------------- @property @@ -253,3 +275,165 @@ class RekordboxStore: return [ str(c.FolderPath) for c in self.iter_content() if getattr(c, "FolderPath", None) ] + + # ---- writes: track metadata ----------------------------------------- + # + # Deliberately NOT editable: the file path (it is the track's identity), + # BPM and key (audio/grid territory), and Rekordbox's own read-only + # bookkeeping. `producer` and `mix` are Traktor concepts with no Rekordbox + # column — Rekordbox has a Composer, which is not the same field — so they + # are simply absent from the set rather than mapped to something close. + _DIRECT_FIELDS = { + "title": "Title", + "comment": "Commnt", + "release_date": "ReleaseDate", + } + # Fields stored as a foreign key into a lookup table, which must be + # found-or-created: `add_*` in pyrekordbox RAISES on an existing name. + _LOOKUP_FIELDS = { + "artist": ("DjmdArtist", "ArtistID", "add_artist"), + "album": ("DjmdAlbum", "AlbumID", "add_album"), + "genre": ("DjmdGenre", "GenreID", "add_genre"), + "label": ("DjmdLabel", "LabelID", "add_label"), + # A remixer IS an artist in Rekordbox — same table, different column. + "remixer": ("DjmdArtist", "RemixerID", "add_artist"), + } + EDITABLE_FIELDS = set(_DIRECT_FIELDS) | set(_LOOKUP_FIELDS) | {"rating"} + + def _lookup_id(self, table_name: str, adder: str, name: str) -> str | None: + """The id of the lookup row called `name`, creating it if needed.""" + if not name: + return None + table = getattr(self._tables, table_name) + existing = self._db.session.query(table).filter_by(Name=name).first() + if existing is not None: + return str(existing.ID) + row = getattr(self._db, adder)(name) + return str(row.ID) + + def set_track_metadata(self, track_id: str, fields: dict) -> None: + row = self.content(track_id) + for key, value in fields.items(): + if key not in self.EDITABLE_FIELDS: + continue # unknown/!safe fields are ignored, never guessed at + if key == "rating": + try: + stars = int(value or 0) + except (TypeError, ValueError): + raise InvalidCommand(f"Rating must be a number, got {value!r}") from None + if not 0 <= stars <= 5: + raise InvalidCommand(f"Rating must be 0-5, got {stars}") + before, new = row.Rating, stars + row.Rating = stars + elif key in self._DIRECT_FIELDS: + column = self._DIRECT_FIELDS[key] + before = getattr(row, column) + new = (value or None) if isinstance(value, str) else value + setattr(row, column, new) + else: + table_name, column, adder = self._LOOKUP_FIELDS[key] + before = getattr(row, column) + new = self._lookup_id(table_name, adder, (value or "").strip()) + setattr(row, column, new) + self._journal.record("track", "set", track_id, key, before, new) + # Artist/album/genre/label are FOREIGN KEYS. Setting the id does not move + # the ORM's cached relationship, so re-projecting the row immediately + # would read the OLD name back and report a successful edit as a no-op. + # Flush pushes the ids into the transaction; expiring the row makes the + # next attribute access reload the joined rows with them. + self._db.flush() + self._db.session.expire(row) + + # ---- writes: playlists ------------------------------------------------ + def _playlist(self, node_id: str): + t = self._tables + row = ( + self._db.session.query(t.DjmdPlaylist) + .filter(t.DjmdPlaylist.ID == str(node_id)) + .first() + ) + if row is None: + raise NotFound(f"No playlist {node_id!r}") + return row + + def create_playlist(self, name: str, parent_id: str | None = None) -> str: + name = (name or "").strip() + if not name: + raise InvalidCommand("A playlist needs a name") + parent = self._playlist(parent_id) if parent_id else None + if parent is not None and int(parent.Attribute or 0) != int( + self._tables.PlaylistType.FOLDER + ): + raise InvalidCommand("A playlist can only be created inside a folder") + row = self._db.create_playlist(name, parent=parent) + self._journal.record("playlist", "create", name) + return str(row.ID) + + def rename_playlist(self, node_id: str, name: str) -> None: + name = (name or "").strip() + if not name: + raise InvalidCommand("A playlist needs a name") + row = self._playlist(node_id) + self._db.rename_playlist(row, name) + self._journal.record("playlist", "rename", name) + + def delete_playlist(self, node_id: str) -> None: + row = self._playlist(node_id) + name = row.Name + self._db.delete_playlist(row) + self._journal.record("playlist", "delete", name) + + def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: + """Replace a playlist's contents, in the given order. + + Rekordbox keys order by `DjmdSongPlaylist.TrackNo`, and there is no + bulk reorder — so this clears the list and re-adds it. `add_to_playlist` + is used one row at a time because it is what maintains Rekordbox's own + USN ordering for these rows. + """ + t = self._tables + playlist = self._playlist(node_id) + if int(playlist.Attribute or 0) != int(t.PlaylistType.PLAYLIST): + raise InvalidCommand("Only a plain playlist has an editable track list") + known = {tid for tid in track_ids if self._by_id and str(tid) in self._by_id} + unknown = [tid for tid in track_ids if tid not in known] + if unknown: + raise NotFound(f"Unknown track(s): {', '.join(map(str, unknown[:3]))}") + existing = ( + self._db.session.query(t.DjmdSongPlaylist) + .filter(t.DjmdSongPlaylist.PlaylistID == str(node_id)) + .all() + ) + for song in existing: + self._db.remove_from_playlist(playlist, song) + for n, track_id in enumerate(track_ids, start=1): + self._db.add_to_playlist(playlist, str(track_id), track_no=n) + self._journal.record("playlist", "entries", playlist.Name, after=len(track_ids)) + return len(track_ids) + + # ---- save -------------------------------------------------------------- + @property + def dirty(self) -> bool: + return self._journal.dirty + + def edited_fields(self, track_id: str) -> set[str]: + return self._journal.fields_for(track_id) + + def save(self) -> SaveOutcome: + """Make the session's edits permanent. + + `commit(autoinc=True)` is what assigns Rekordbox's update sequence + numbers — one increment per change, stamped onto each changed row. A real + Rekordbox was verified to accept a library written this way and to carry + on from the counter it was left at. + + `snapshot` is None: a Rekordbox library is `master.db` plus its analysis + files plus a playlist XML, so there is no single blob to version, and + `capabilities.save.history` says so. + """ + summary = self._journal.summary() + self._db.commit(autoinc=True) + self._journal.clear() + # Reads go through the same session, so nothing needs re-projecting from + # scratch — but the grid cache is keyed by track and survives a save. + return SaveOutcome(summary=summary, snapshot=None, tag_results=[]) diff --git a/backend/konduktor/adapters/traktor/capabilities.py b/backend/konduktor/adapters/traktor/capabilities.py index 2e98f33..080b190 100644 --- a/backend/konduktor/adapters/traktor/capabilities.py +++ b/backend/konduktor/adapters/traktor/capabilities.py @@ -43,6 +43,7 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities: 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. diff --git a/backend/konduktor/adapters/traktor/store.py b/backend/konduktor/adapters/traktor/store.py index db36022..cf74f79 100644 --- a/backend/konduktor/adapters/traktor/store.py +++ b/backend/konduktor/adapters/traktor/store.py @@ -42,7 +42,7 @@ from traktor_nml_utils.models.collection import ( ) from xsdata.formats.dataclass.serializers import XmlSerializer -from ...core.adapter import InvalidCommand +from ...core.adapter import InvalidCommand, SaveOutcome from ...core.edit_journal import EditJournal from ...core.pathmap import common_dir_prefix from ...core.pathmap import PathMapping @@ -73,13 +73,6 @@ class FileTagResult: detail: str = "" -@dataclass -class SaveOutcome: - summary: str # human-readable edit summary, for the version-history message - snapshot: bytes # exactly the bytes written, for the version-history commit - tag_results: list[FileTagResult] - - class TraktorStore: def __init__(self, nml_path: Path): self.nml_path = Path(nml_path) diff --git a/backend/konduktor/app_state.py b/backend/konduktor/app_state.py index 455979c..d26b02c 100644 --- a/backend/konduktor/app_state.py +++ b/backend/konduktor/app_state.py @@ -39,6 +39,17 @@ class AppState: # 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 + 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)) @@ -58,9 +69,15 @@ class AppState: """ assert self.adapter is not None and self.path is not None outcome = self.adapter.save() - commit = history.commit( - self.path, outcome.snapshot, outcome.summary, __version__ - ) + # 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__ + ) return outcome, commit diff --git a/backend/konduktor/core/adapter.py b/backend/konduktor/core/adapter.py index 1b2e679..82c146e 100644 --- a/backend/konduktor/core/adapter.py +++ b/backend/konduktor/core/adapter.py @@ -18,6 +18,7 @@ Two rules keep this honest: """ from __future__ import annotations +from dataclasses import dataclass, field from pathlib import Path from typing import Protocol, runtime_checkable @@ -26,6 +27,28 @@ from .model import Facets, PlaylistNode, Stats, Track, TrackCues, TrackPage from .pathmap import PathMapping +@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) + + class AdapterError(Exception): """Base for every failure an adapter reports to the HTTP layer.""" diff --git a/backend/konduktor/core/capabilities.py b/backend/konduktor/core/capabilities.py index b08fe42..c6858ca 100644 --- a/backend/konduktor/core/capabilities.py +++ b/backend/konduktor/core/capabilities.py @@ -29,6 +29,10 @@ 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 diff --git a/backend/run_tests.sh b/backend/run_tests.sh index 5f99397..980559e 100755 --- a/backend/run_tests.sh +++ b/backend/run_tests.sh @@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")" source .venv/bin/activate fail=0 -for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_rekordbox_adapter.py test_phase3.py test_history.py; do +for t in 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; do echo "──────────────────────────────────────────" echo "▶ $t" echo "──────────────────────────────────────────" diff --git a/backend/test_rekordbox_adapter.py b/backend/test_rekordbox_adapter.py index f3f7b55..d17e3d5 100644 --- a/backend/test_rekordbox_adapter.py +++ b/backend/test_rekordbox_adapter.py @@ -34,12 +34,28 @@ from konduktor.adapters.rekordbox.cue_types import ( # noqa: E402 from konduktor.adapters.rekordbox.driver import RekordboxDriver # noqa: E402 from konduktor.adapters.rekordbox.projection import parse_key # noqa: E402 from konduktor.core import registry # noqa: E402 -from konduktor.core.adapter import LibraryAdapter, Unsupported # noqa: E402 +from konduktor.core.adapter import ( # noqa: E402 + InvalidCommand, + LibraryAdapter, + NotFound, + Unsupported, +) from konduktor.core.model import GridMarker # noqa: E402 failed = False +def _raises(fn, exc) -> bool: + """True when `fn` raises exactly the expected adapter error.""" + try: + fn() + except exc: + return True + except Exception: # noqa: BLE001 — the wrong error is still a failure + return False + return False + + def check(label, cond, detail=""): global failed print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else "")) @@ -195,13 +211,15 @@ with tempfile.TemporaryDirectory() as d: print("== capabilities gate the UI ==") caps = adapter.capabilities() check("platform is rekordbox", caps.platform == "rekordbox") - # The distinction that makes the UI honest: "cannot be written at all" is - # not the same as every per-feature flag happening to be false. - check("the library reports itself as NOT writable", caps.writable is False) - check("and says why, as a fact the UI can word", - caps.readonly_cause == "platform_incomplete", str(caps.readonly_cause)) + # Milestone 2: the library IS writable, but only for what is implemented. + # The library-level flag and the per-feature flags are separate gates on + # purpose — see the cue/grid refusals below. + check("a local library is writable", caps.writable is True) + check("with no read-only cause", caps.readonly_cause is None, str(caps.readonly_cause)) check("per-feature flags still describe what Rekordbox CAN do", caps.cues.memory_cues and caps.grid.flexible) + check("cues are NOT editable yet (milestone 3)", caps.cues.editable is False) + check("the grid is NOT editable yet (milestone 3)", caps.grid.editable is False) check("8 hot cue slots, labelled by letter", caps.cues.hotcue_slots == 8 and caps.cues.slot_labels == "letter") check("memory cues are supported", caps.cues.memory_cues) @@ -212,19 +230,19 @@ with tempfile.TemporaryDirectory() as d: check("cue colour is a palette, not free RGB", caps.cues.color == "palette") check("the grid is flexible but not editable yet", caps.grid.flexible and not caps.grid.editable) - check("no field is advertised as editable", caps.tracks.editable_fields == []) + check("the editable field set is advertised", bool(caps.tracks.editable_fields)) + # Rekordbox has no column for these; Traktor does. Mapping them onto its + # Composer field would silently write the wrong thing. + check("producer/mix are absent rather than approximated", + "producer" not in caps.tracks.editable_fields + and "mix" not in caps.tracks.editable_fields) check("version history is off (multi-artefact library)", caps.save.history is False) check("the save warning says Rekordbox holds the library open", caps.save.overwrite_risk == "while_running") check("library label is master.db", caps.save.library_label == "master.db") - print("== every command is refused, with a reason ==") + print("== the unimplemented stores still refuse, with a reason ==") commands = { - "set_track_metadata": lambda: adapter.set_track_metadata(sample.id, {"title": "x"}), - "create_playlist": lambda: adapter.create_playlist("x"), - "rename_playlist": lambda: adapter.rename_playlist("1", "x"), - "delete_playlist": lambda: adapter.delete_playlist("1"), - "set_playlist_entries": lambda: adapter.set_playlist_entries("1", []), "set_cover_art": lambda: adapter.set_cover_art(sample.id, b"", "image/jpeg"), "set_cue": lambda: adapter.set_cue(sample.id, slot=1, start_sec=0.0, cue_type="cue"), "set_cue_type": lambda: adapter.set_cue_type(sample.id, 1, "cue"), @@ -239,7 +257,8 @@ with tempfile.TemporaryDirectory() as d: "delete_grid": lambda: adapter.delete_grid(sample.id), "set_grid_lock": lambda: adapter.set_grid_lock(sample.id, True), "remap_locations": lambda: adapter.remap_locations(None), - "save": lambda: adapter.save(), + # save() works now; snapshot() must not, because a Rekordbox library is + # more than one file and there is nothing to version. "snapshot": lambda: adapter.snapshot(), } refused = [] @@ -251,8 +270,43 @@ with tempfile.TemporaryDirectory() as d: pass except Exception as ex: # noqa: BLE001 — anything else is the wrong error refused.append(f"{name} ({type(ex).__name__})") - check("every mutating command raises Unsupported", not refused, ", ".join(refused)) - check("the adapter is never dirty while read-only", adapter.dirty is False) + check("every cue/grid command still raises Unsupported", not refused, ", ".join(refused)) + check("refusing a command leaves the adapter clean", adapter.dirty is False) + + print("== metadata writes, including the foreign-key fields ==") + # artist/album/genre/label are FKs into lookup tables, not columns. Setting + # one must (a) find-or-create the lookup row — pyrekordbox's add_* RAISES on + # an existing name — and (b) return a projection that reflects the new value, + # which needs a flush+expire or the ORM reads the stale relationship back. + writable_target = adapter.tracks[0] + updated = adapter.set_track_metadata( + writable_target.id, + {"genre": "Konduktor Probe Genre", "artist": "Konduktor Probe Artist", "rating": 4}, + ) + check("the command returns the refreshed projection", updated is not None) + if updated: + check("a NEW lookup value is reflected immediately", + updated.genre == "Konduktor Probe Genre" and updated.artist == "Konduktor Probe Artist", + f"{updated.genre!r} / {updated.artist!r}") + check("a direct column is reflected immediately", updated.rating == 4, str(updated.rating)) + check("the index holds the same refreshed track", + adapter.track(writable_target.id).genre == "Konduktor Probe Genre") + # Re-using an EXISTING lookup value must not try to create it again. + existing_genre = next( + (t.genre for t in adapter.tracks if t.genre and t.id != writable_target.id), None + ) + if existing_genre: + again = adapter.set_track_metadata(writable_target.id, {"genre": existing_genre}) + check("an existing lookup value is reused, not re-created", + again is not None and again.genre == existing_genre, + str(again.genre if again else None)) + check("an out-of-range rating is rejected", + _raises(lambda: adapter.set_track_metadata(writable_target.id, {"rating": 9}), + InvalidCommand)) + check("an unknown track is a NotFound", + _raises(lambda: adapter.set_track_metadata("nope", {"title": "x"}), NotFound)) + check("unknown fields are ignored, never guessed at", + adapter.set_track_metadata(writable_target.id, {"not_a_field": "x"}) is not None) print("== a cloud-synced library is refused permanently, not pending a milestone ==") # The one failure mode version history cannot undo: a local edit the sync diff --git a/backend/test_rekordbox_fidelity.py b/backend/test_rekordbox_fidelity.py new file mode 100644 index 0000000..4cb6ac0 --- /dev/null +++ b/backend/test_rekordbox_fidelity.py @@ -0,0 +1,241 @@ +"""Rekordbox's analogue of `test_save_fidelity.py`. + +The project's core safety property is: **an edit changes only what it was +supposed to change.** For Traktor that is a byte diff of the whole file. A byte +diff is meaningless against SQLite — page layout, free lists and vacuuming move +bytes that carry no meaning — so the equivalent here is a **full table dump +before and after, compared row by row**. + +Runs against a TEMP COPY of the local Rekordbox library, and skips cleanly when +no Rekordbox is installed. + +Two things about the expected diff are NOT noise and must stay asserted: + + * `agentRegistry.localUpdateCount` changes on every save. It is Rekordbox's + global update counter, and NOT bumping it is what would corrupt the library. + * the edited row's own `rb_local_usn` is stamped with that new counter value. + +A real Rekordbox 7 was verified to accept a library written exactly this way, +display the edit, leave the row untouched, and carry on from the counter it was +left at — see the handoff's Findings section. +""" +import os +import shutil +import sys +import tempfile +import warnings +from pathlib import Path + +warnings.filterwarnings("ignore") +os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-rbfid-appdata-") + +from konduktor.adapters.rekordbox import discovery # noqa: E402 +from konduktor.adapters.rekordbox.adapter import RekordboxAdapter # noqa: E402 + +failed = False + + +def check(label, cond, detail=""): + global failed + print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else "")) + if not cond: + failed = True + + +# ---- the row-level dump/diff harness ----------------------------------- +def dump(db_path: Path) -> dict: + """Every row of every table, keyed by primary key.""" + import sqlcipher3.dbapi2 as sqlcipher + from pyrekordbox.db6.database import BLOB + from pyrekordbox.utils import deobfuscate + + con = sqlcipher.connect(str(db_path)) + con.execute(f"PRAGMA key='{deobfuscate(BLOB)}'") + cur = con.cursor() + # Materialise the table list FIRST: reusing one cursor for the outer and the + # inner queries silently truncates the outer iteration to a single row. + names = [ + r[0] + for r in cur.execute( + "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name" + ).fetchall() + ] + out: dict[str, dict] = {} + for table in names: + if table == "sqlite_sequence": + continue + cols = [r[1] for r in cur.execute(f'PRAGMA table_info("{table}")').fetchall()] + pk = "ID" if "ID" in cols else cols[0] + rows = {} + for r in cur.execute(f'SELECT * FROM "{table}"').fetchall(): + d = dict(zip(cols, r)) + rows[str(d.get(pk))] = d + out[table] = rows + con.close() + return out + + +def diff(before: dict, after: dict, ignore_columns=("updated_at", "created_at")) -> list: + """(table, pk, kind, detail) for every row-level change.""" + changes = [] + for table in sorted(set(before) | set(after)): + rows_a, rows_b = before.get(table, {}), after.get(table, {}) + for pk in sorted(set(rows_a) | set(rows_b)): + if pk not in rows_a: + changes.append((table, pk, "INSERT", rows_b[pk])) + elif pk not in rows_b: + changes.append((table, pk, "DELETE", rows_a[pk])) + else: + fields = { + k: (rows_a[pk][k], rows_b[pk].get(k)) + for k in rows_a[pk] + if k not in ignore_columns and rows_a[pk][k] != rows_b[pk].get(k) + } + if fields: + changes.append((table, pk, "UPDATE", fields)) + return changes + + +def describe(changes) -> str: + return "; ".join(f"{t}/{pk} {kind}" for t, pk, kind, _ in changes) or "(none)" + + +def clean_copy(src: Path, dest: Path, *, closing=()) -> None: + """Copy a library WITHOUT any stale write-ahead log. + + A `-wal` left beside a replaced `.db` is replayed onto it by SQLite and + corrupts it. This cost real debugging time during the research spike. + + `closing` is any adapters still holding the destination open: replacing a + SQLite file under a live connection is an I/O error at best. + """ + for adapter in closing: + adapter.close() + for ext in ("-wal", "-shm"): + stale = Path(str(dest) + ext) + if stale.exists(): + stale.unlink() + shutil.copy2(src, dest) + + +found = discovery.detect_libraries() +if not found: + print("== SKIPPED: no Rekordbox library found on this machine ==") + print("\nRESULT: ALL PASSED") + sys.exit(0) + +REAL = Path(found[0]["path"]) +print(f"(using a temp copy of {REAL})") + +with tempfile.TemporaryDirectory() as d: + work = Path(d) / "master.db" + clean_copy(REAL, work) + share = REAL.parent / "share" + if share.is_dir(): + shutil.copytree(share, Path(d) / "share") + + # ---- A: a no-op save changes nothing -------------------------------- + print("== A: opening and saving without editing changes no row ==") + before = dump(work) + adapter = RekordboxAdapter(work) + check("a freshly opened library is not dirty", adapter.dirty is False) + adapter.save() + changes = diff(before, dump(work)) + check("a no-op save changes zero rows", not changes, describe(changes)) + + # ---- B: one metadata edit touches one row + the counter -------------- + print("== B: a single metadata edit is localized ==") + clean_copy(REAL, work, closing=[adapter]) + before = dump(work) + adapter = RekordboxAdapter(work) + target = adapter.tracks[0] + original_title = target.title + adapter.set_track_metadata(target.id, {"title": "KONDUKTOR FIDELITY PROBE"}) + check("the edit makes the adapter dirty", adapter.dirty is True) + check("the projection updates immediately", + adapter.track(target.id).title == "KONDUKTOR FIDELITY PROBE") + adapter.save() + check("saving clears dirty", adapter.dirty is False) + + changes = diff(before, dump(work)) + tables_touched = {t for t, _, _, _ in changes} + check("exactly two rows change", len(changes) == 2, describe(changes)) + check("they are the track and the update counter", + tables_touched == {"djmdContent", "agentRegistry"}, str(tables_touched)) + + content = [c for c in changes if c[0] == "djmdContent"] + check("the changed track is the one edited", + len(content) == 1 and content[0][1] == target.id, describe(content)) + if content: + fields = content[0][3] + check("only Title and the row's USN changed", + set(fields) == {"Title", "rb_local_usn"}, str(sorted(fields))) + check("Title holds the new value", fields.get("Title", (None, None))[1] == "KONDUKTOR FIDELITY PROBE") + + registry = [c for c in changes if c[0] == "agentRegistry"] + check("the global update counter is the registry row that changed", + len(registry) == 1 and registry[0][1] == "localUpdateCount", describe(registry)) + if registry: + old_usn, new_usn = registry[0][3]["int_1"] + check("the counter increments by exactly one edit", new_usn == old_usn + 1, + f"{old_usn} -> {new_usn}") + # This is the invariant Rekordbox itself relies on to notice the change. + if content: + check("the edited row is stamped with the new counter value", + content[0][3].get("rb_local_usn", (None, None))[1] == new_usn, + str(content[0][3].get("rb_local_usn"))) + + # ---- C: the edit survives a reopen ---------------------------------- + print("== C: the edit is really on disk ==") + reopened = RekordboxAdapter(work) + check("the new title is there after reopening", + reopened.track(target.id).title == "KONDUKTOR FIDELITY PROBE", + str(reopened.track(target.id).title)) + check("the original title is gone", original_title != "KONDUKTOR FIDELITY PROBE") + + # ---- D: an unsaved edit is not on disk ------------------------------ + print("== D: edits are held until save, like every other platform ==") + clean_copy(REAL, work, closing=[adapter, reopened]) + before = dump(work) + adapter = RekordboxAdapter(work) + adapter.set_track_metadata(adapter.tracks[0].id, {"title": "NEVER SAVED"}) + changes = diff(before, dump(work)) + check("an unsaved edit has written nothing to disk", not changes, describe(changes)) + + # ---- E: playlist edits ----------------------------------------------- + print("== E: a playlist round-trips ==") + clean_copy(REAL, work, closing=[adapter]) + adapter = RekordboxAdapter(work) + before_tree = adapter.playlist_tree() + ids = [t.id for t in adapter.tracks[:3]] + node_id = adapter.create_playlist("Konduktor Test Playlist") + adapter.set_playlist_entries(node_id, ids) + adapter.save() + + reopened = RekordboxAdapter(work) + names = {n.name for n in reopened.playlist_tree()} + check("the playlist exists after a reopen", "Konduktor Test Playlist" in names, str(names)) + check("its entries are the tracks added, in order", + reopened.playlist_entries(node_id) == ids, + f"{reopened.playlist_entries(node_id)} vs {ids}") + tracks = reopened.playlist_tracks(node_id) + check("and they resolve to real projected tracks", + tracks is not None and [t.id for t in tracks] == ids) + + reopened.rename_playlist(node_id, "Konduktor Renamed") + reopened.save() + again = RekordboxAdapter(work) + check("a rename round-trips", + "Konduktor Renamed" in {n.name for n in again.playlist_tree()}) + + again.delete_playlist(node_id) + again.save() + final = RekordboxAdapter(work) + check("a delete round-trips", + "Konduktor Renamed" not in {n.name for n in final.playlist_tree()}) + check("the rest of the tree is untouched", + len(final.playlist_tree()) == len(before_tree), + f"{len(final.playlist_tree())} vs {len(before_tree)}") + +print("\nRESULT:", "FAILED" if failed else "ALL PASSED") +sys.exit(1 if failed else 0) diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 5bb1675..4298351 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -147,6 +147,9 @@ export interface TrackCues { } export interface CueCapabilities { + /** Whether cues can be created or changed. Symmetric with grid.editable: a + * platform can be writable overall while its cue store is not implemented. */ + editable: boolean hotcue_slots: number slot_labels: 'number' | 'letter' memory_cues: boolean diff --git a/frontend/src/components/PrepStrip.tsx b/frontend/src/components/PrepStrip.tsx index ce3fb29..5455d45 100644 --- a/frontend/src/components/PrepStrip.tsx +++ b/frontend/src/components/PrepStrip.tsx @@ -563,13 +563,31 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) // ---- capability-derived ----------------------------------------------- const caps = useCaps() - // A read-only library refuses every edit. Guarding at the point of INTENT - // means the user gets the reason instead of a 422 from the adapter's backstop, - // and the deck stays fully usable for listening — which is most of its value - // on a library you cannot write. - const refuseIfReadOnly = () => { - if (caps.writable) return false - onError?.(readOnlyNotice(caps) ?? 'This library is read-only.') + // Edits are guarded at the point of INTENT, so the user gets the reason + // instead of a 422 from the adapter's backstop, and the deck stays fully + // usable for listening — which is most of its value on a library you cannot + // write. + // + // TWO gates, not one. `writable` is the library; `cues.editable` and + // `grid.editable` are the features. A platform can be writable overall while + // its cue or grid store is not implemented yet, so gating only on `writable` + // would re-expose these controls the moment that flips — which is exactly how + // this would regress unnoticed when Rekordbox writes land. + const canEditCues = caps.writable && caps.cues.editable + const canEditGrid = caps.writable && caps.grid.editable + const refuseCueEdit = () => { + if (canEditCues) return false + onError?.( + readOnlyNotice(caps) ?? `Cues cannot be edited on ${caps.save.app_name} libraries yet.`, + ) + return true + } + const refuseGridEdit = () => { + if (canEditGrid) return false + onError?.( + readOnlyNotice(caps) ?? + `The beatgrid cannot be edited on ${caps.save.app_name} libraries yet.`, + ) return true } const slotCount = caps.cues.hotcue_slots @@ -623,7 +641,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) return } if (!cue) { - if (refuseIfReadOnly()) return + if (refuseCueEdit()) return try { // Setting a hotcue while a loop is active stores it as a loop hotcue. if (loopActive && loopRegion) { @@ -663,7 +681,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) const canAutoCue = grid != null const runAutoHotcues = async () => { if (!track || !canAutoCue || autoBusy) return - if (refuseIfReadOnly()) return + if (refuseCueEdit()) return const hotcueCount = (c: TrackCues | null) => c?.cues.filter((x) => x.role === 'hotcue' && x.slot != null).length ?? 0 if (hotcueCount(cueData) >= slotCount) { @@ -690,7 +708,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) const changeSelectedType = async (type: CueType) => { if (!track || selectedSlot == null) return - if (refuseIfReadOnly()) return + if (refuseCueEdit()) return try { applyCueEdit(await api.setCueType(track.id, selectedSlot, type)) } catch (e) { @@ -700,7 +718,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) const deleteSelected = async () => { if (!track || selectedSlot == null) return - if (refuseIfReadOnly()) return + if (refuseCueEdit()) return try { applyCueEdit(await api.deleteCue(track.id, selectedSlot)) setSelectedSlot(null) @@ -713,7 +731,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) const existing = hotcueAt(slot) if (!track || !existing) return // nothing to remove in an empty slot if (existing.grid_marker != null) return // beatgrid-owned: delete the marker instead - if (refuseIfReadOnly()) return + if (refuseCueEdit()) return try { applyCueEdit(await api.deleteCue(track.id, slot)) if (selectedSlot === slot) setSelectedSlot(null) @@ -738,7 +756,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) const editMarker = async (index: number, patch: { bpm?: number; start?: number }) => { if (!track || index < 0) return - if (refuseIfReadOnly()) return + if (refuseGridEdit()) return try { applyCueEdit(await api.setGridMarker(track.id, index, patch)) } catch (e) { @@ -760,7 +778,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) // Uses the raw playhead, not snapTime: a marker defines where beats are. const addMarkerHere = async () => { if (!track) return - if (refuseIfReadOnly()) return + if (refuseGridEdit()) return try { applyCueEdit(await api.addGridMarker(track.id, playheadNow())) } catch (e) { @@ -769,7 +787,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) } const deleteMarkerHere = async () => { if (!track || activeMarkerIndex < 0) return - if (refuseIfReadOnly()) return + if (refuseGridEdit()) return try { applyCueEdit(await api.deleteGridMarker(track.id, activeMarkerIndex)) } catch (e) { @@ -786,7 +804,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) const resetGrid = async () => { const o = originalGridRef.current if (!track || !o) return - if (refuseIfReadOnly()) return + if (refuseGridEdit()) return try { applyCueEdit(await api.replaceGridMarkers(track.id, o)) } catch (e) { @@ -795,7 +813,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) } const toggleLock = async () => { if (!track) return - if (refuseIfReadOnly()) return + if (refuseGridEdit()) return try { applyCueEdit(await api.setGridLock(track.id, !cueData?.grid_locked)) } catch (e) { @@ -804,7 +822,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) } const deleteGrid = async () => { if (!track) return - if (refuseIfReadOnly()) return + if (refuseGridEdit()) return try { applyCueEdit(await api.deleteGrid(track.id)) } catch (e) { @@ -814,7 +832,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) // Analyze: backend detects BPM + first beat, sets the grid anchor and hotcue 1. const runAnalyzeGrid = async () => { if (!track || gridBusy) return - if (refuseIfReadOnly()) return + if (refuseGridEdit()) return setGridBusy(true) try { applyCueEdit(await api.autoGrid(track.id)) diff --git a/frontend/src/components/TrackTable.tsx b/frontend/src/components/TrackTable.tsx index 3c17475..54567cf 100644 --- a/frontend/src/components/TrackTable.tsx +++ b/frontend/src/components/TrackTable.tsx @@ -1,4 +1,4 @@ -import { useEffect, useRef, useState, type MutableRefObject } from 'react' +import { useEffect, useMemo, useRef, useState, type MutableRefObject } from 'react' import { flexRender, getCoreRowModel, @@ -11,6 +11,7 @@ import { type VisibilityState, } from '@tanstack/react-table' import { useVirtualizer } from '@tanstack/react-virtual' +import { useCaps } from '../lib/capabilities' import { DndContext, PointerSensor, @@ -31,6 +32,15 @@ import { CSS } from '@dnd-kit/utilities' import type { Track } from '../api' import { TRACK_COLUMNS } from '../lib/trackColumns' +/** Fields this platform can persist, for the table's per-cell edit gating. + * Platforms differ in WHICH fields they accept, so the all-or-nothing + * `onEditField` handler is not enough on its own. */ +function useEditableFields(): ReadonlySet { + const caps = useCaps() + return useMemo(() => new Set(caps.tracks.editable_fields), [caps.tracks.editable_fields]) +} + + const ROW_HEIGHT = 44 // Stable reference. A controlled `state.sorting` that's a fresh `[]` each render // (with no `onSortingChange`) makes TanStack Table re-sync its internal state @@ -259,11 +269,12 @@ export function TrackTable({ onEditField, activeTrackId, }: Props) { + const editableFields = useEditableFields() const table = useReactTable({ data: tracks, columns: TRACK_COLUMNS, state: { sorting, columnVisibility, columnOrder, columnSizing }, - meta: { onEditField }, + meta: { onEditField, editableFields }, onSortingChange: (updater) => onSortingChange(typeof updater === 'function' ? updater(sorting) : updater), onColumnSizingChange: (updater) => @@ -457,11 +468,12 @@ export function PlaylistTable({ const [items, setItems] = useState(tracks) useEffect(() => setItems(tracks), [tracks]) + const editableFields = useEditableFields() const table = useReactTable({ data: items, columns: TRACK_COLUMNS, state: { sorting: NO_SORTING, columnVisibility, columnOrder, columnSizing }, - meta: { onEditField }, + meta: { onEditField, editableFields }, enableSorting: false, // playlist order is manual onColumnSizingChange: (updater) => onColumnSizingChange(typeof updater === 'function' ? updater(columnSizing) : updater), diff --git a/frontend/src/lib/trackColumns.tsx b/frontend/src/lib/trackColumns.tsx index 4ff33b1..c093292 100644 --- a/frontend/src/lib/trackColumns.tsx +++ b/frontend/src/lib/trackColumns.tsx @@ -22,6 +22,12 @@ declare module '@tanstack/react-table' { // eslint-disable-next-line @typescript-eslint/no-unused-vars interface TableMeta { onEditField?: (track: Track, field: keyof Track, value: string | number) => void + /** Fields the loaded platform can actually persist + * (`capabilities.tracks.editable_fields`). A field outside this set renders + * read-only: the platform-level `onEditField` gate is all-or-nothing, and + * platforms genuinely differ in WHICH fields they accept. Undefined means + * "not gated" — every field with a handler stays editable. */ + editableFields?: ReadonlySet } } @@ -34,11 +40,14 @@ function InlineEdit({ display, onCommit, className = 'w-full min-w-0 truncate text-muted', + readOnly = false, }: { value: string | null display?: ReactNode onCommit: (v: string) => void className?: string + /** Render the value without offering an editor. */ + readOnly?: boolean }) { const [editing, setEditing] = useState(false) const [val, setVal] = useState('') @@ -70,6 +79,13 @@ function InlineEdit({ /> ) } + if (readOnly) { + return ( +
+ {display ?? (value?.trim() ? value : —)} +
+ ) + } return (
{ @@ -85,12 +101,20 @@ function InlineEdit({ ) } +/** Whether this table may edit `field`, per the platform's capabilities. */ +function canEdit(c: CellContext, field: string): boolean { + const meta = c.table.options.meta + if (!meta?.onEditField) return false + return meta.editableFields ? meta.editableFields.has(field) : true +} + // Cell renderer factory for a plain editable text field. function editable(field: keyof Track, className?: string) { return (c: CellContext) => ( c.table.options.meta?.onEditField?.(c.row.original, field, v)} /> ) @@ -111,11 +135,13 @@ export const TRACK_COLUMNS: ColumnDef[] = [ value={title} display={title || Untitled} className="w-full min-w-0 truncate font-medium text-text" + readOnly={!canEdit(c, 'title')} onCommit={(v) => edit?.(r, 'title', v)} /> edit?.(r, 'artist', v)} />
@@ -185,7 +211,13 @@ export const TRACK_COLUMNS: ColumnDef[] = [ cell: (c) => ( c.table.options.meta?.onEditField?.(c.row.original, 'rating', v)} + // RatingStars is read-only without an onChange, which is exactly the + // behaviour wanted when the platform cannot persist a rating. + onChange={ + canEdit(c, 'rating') + ? (v) => c.table.options.meta?.onEditField?.(c.row.original, 'rating', v) + : undefined + } /> ), }), @@ -257,6 +289,7 @@ export const TRACK_COLUMNS: ColumnDef[] = [ {formatDate(c.getValue() as string | null)}} + readOnly={!canEdit(c, 'release_date')} onCommit={(v) => c.table.options.meta?.onEditField?.(c.row.original, 'release_date', v)} /> ), From 30065a94fe43badfd184e9587d78f4fe48ae5478 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Sat, 19 Sep 2026 09:57:26 +0200 Subject: [PATCH 09/64] Improved Rekordbox adapter --- .claude/handoffs/rekordbox-adapter.md | 98 ++++++ CLAUDE.md | 43 ++- .../konduktor/adapters/rekordbox/adapter.py | 77 ++++- .../adapters/rekordbox/capabilities.py | 14 +- .../konduktor/adapters/rekordbox/cue_types.py | 15 + backend/konduktor/adapters/rekordbox/store.py | 284 +++++++++++++++++- backend/test_rekordbox_adapter.py | 85 +++++- backend/test_rekordbox_fidelity.py | 80 +++++ 8 files changed, 658 insertions(+), 38 deletions(-) diff --git a/.claude/handoffs/rekordbox-adapter.md b/.claude/handoffs/rekordbox-adapter.md index cb97080..3fcf695 100644 --- a/.claude/handoffs/rekordbox-adapter.md +++ b/.claude/handoffs/rekordbox-adapter.md @@ -826,3 +826,101 @@ Also corrected in CLAUDE.md: the cue routes are `/api/tracks/cue`, not `rb_local_usn` on `djmdCue` rows — Rekordbox itself leaves them NULL. - `test_rekordbox_fidelity.py` is the harness to extend: add a cue edit and a grid edit as phases F and G, asserting the same "exactly these rows" property. + +### Milestone 3a landed: hot cue writes + +`./run_tests.sh` green at **288 assertions**. `cues.editable` is now true; +`grid.editable` is still false. + +Every native field convention was read off the real library before writing any +of it, and all of them are asserted in `test_rekordbox_fidelity.py` phase F: + +| Field | Value Konduktor writes | Evidence | +|---|---|---| +| `InFrame` / `OutFrame` | `floor(msec × 150 / 1000)` | matches every row in the library | +| `ContentUUID` | the **track's** UUID | verified == `djmdContent.UUID` | +| `contentCue.ID` | the **track's** UUID too | same | +| uncoloured cue | `Color=-1, ColorTableIndex=NULL` | how Rekordbox wrote Ben's uncoloured hot cues | +| loop | `Color=255, ColorTableIndex=0, ActiveLoop=0, CueMicrosec=0` | how Rekordbox wrote both loops | +| `BeatLoopSize` | `(beats << 16) \| 1`, beats from the track's own tempo | §8.11, verified at two tempos | + +Fidelity phases F and G assert that a cue write touches **only** `djmdCue`, +`contentCue` and `agentRegistry` — never `djmdContent` — that the mirror holds +one record per live cue row with `rb_cue_count` agreeing, and that a delete +clears both. + +**Memory cues are refused**, not because they are hard but because of the +two-platform promotion rule: Rekordbox is the only platform that has them, so +they are projected and displayed and never written. `role="memory"` raises +`Unsupported` with that explanation. + +### Milestone 3b: the beatgrid — read this before starting + +`pyrekordbox`'s ANLZ tags **cannot change the number of beats**. `PQTZAnlzTag`'s +`set()`, `set_beats()`, `set_bpms()` and `set_times()` all raise unless the new +sequence is exactly as long as the existing one ("For now only values of existing +beats can be set"). Since a tempo change alters how many beats fit in a track, +every real grid edit changes that count. + +So a grid write means manipulating `tag.content.entries` (a `construct` +ListContainer) directly, setting `content.entry_count`, and calling the tag's +`update_len()` — which exists for exactly this and recomputes +`len_tag = len_header + 8 × entries`. `check_parse()` asserts the count and the +list agree, so it is worth calling after. + +Two further things that make this the riskiest piece so far: +- the grid lives in **two files** — `PQTZ` in `.DAT` and `PQT2` in `.EXT` — which + presumably must stay consistent; and `djmdContent.BPM` (tempo ×100) is a third + copy that Rekordbox shows in the library list. +- `.DAT`/`.EXT` round-trip byte-identically today (§8.3), which is the property + that makes a grid write verifiable at all. **Re-check it after any write**: if + a rebuilt file stops being byte-identical in the regions we did not touch, the + write is corrupting something. + +`beatgrid.beats_from_markers()` is already written and unit-tested as the exact +inverse of the read projection, so the marker→beat maths is not the hard part. + +### Milestone 3a verification: point cues confirmed, LOOP WRITES DISABLED + +The staged acceptance test was run in Rekordbox 7. Two results, one good and one +that changed the plan. + +**Good: Rekordbox accepted the cue rows verbatim.** A re-read after the session +showed both rows byte-for-byte as Konduktor wrote them — same `Kind`, same +`BeatLoopSize`, same USN stamps. No repair, no renumbering. The write mechanism +and the `contentCue` mirror are sound, and a point cue written with `Kind=2` +landed on **pad B** exactly as predicted. + +**Bad: a cue row carrying `OutMsec` does not land in the slot its `Kind` names.** +Written with `Kind=4` plus an out-point, it appeared as a **memory cue** with pad +D left empty (confirmed from a screenshot of the deck — only B lit). The loop's +*length* was right (4 beats), so `BeatLoopSize` is correct; only its placement is +wrong. Rekordbox's own 4-beat loop on pad F — the 6th pad — stores `Kind=7`, so +loops evidently use a slot encoding that has not been measured. + +**So loop writing is now refused** (`WRITABLE_CUE_TYPES = ["cue"]`, and +`capabilities.cues.types` reports only `cue`). Loops are still READ and projected +with their length — losing them from the projection would be worse than being +unable to edit them. Writing one anyway would have silently created a memory cue, +which Konduktor deliberately cannot edit or delete, on a platform with no version +history. + +**To finish loops, measure the encoding**: in Rekordbox, put a 4-beat loop on pad +**D** and another on pad **E** of any track, quit, and read the `Kind` values — +two points on known pads, plus Rekordbox-authored loop rows to diff field by +field against Konduktor's. Until then this is the one gap in cue support. + +### Found while verifying: pyrekordbox refuses to commit while Rekordbox runs + +`pyrekordbox.commit()` raises `RuntimeError` outright when it detects a Rekordbox +process. That contradicts the settled decision to **warn but proceed** (§6), and +the check is **process-wide rather than per-file** — so it refuses to write a +temp copy while the user has an entirely different library open, which made the +whole test suite fail purely because Rekordbox happened to be running. + +`RekordboxStore._commit()` now suppresses that veto for the duration of the call +and logs a warning instead, so everything else `commit()` does — the USN +auto-increment and keeping `masterPlaylists6.xml`'s timestamps in step — still +runs as the library intends. `store.app_running` exposes the detection for +warning the user rather than blocking them. A test pins the behaviour by faking +a running process. diff --git a/CLAUDE.md b/CLAUDE.md index 04aa7b0..a3ed3fe 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -59,8 +59,8 @@ Two independent apps that talk over HTTP: - `driver.py`/`discovery.py` — `can_open`, default-location detection, restore. - `beatgrid.py`, `locations.py`, `capabilities.py` — Traktor's grid/companion rules, LOCATION ↔ OS path conversion, and its capability set. - - `adapters/rekordbox/` — **track metadata + playlists writable; cues and the - beatgrid still read-only** (milestone 2). + - `adapters/rekordbox/` — **track metadata, playlists and hot cues writable; + the beatgrid still read-only** (milestones 2 and 3a). `master.db` is SQLCipher-encrypted SQLite, read via `pyrekordbox`. Every mutating command raises `Unsupported` and `capabilities()` advertises nothing as editable, so the UI never offers an edit. Three things differ from Traktor @@ -74,7 +74,25 @@ Two independent apps that talk over HTTP: track has a BPM) that `track_cues()` corrects. - **Cues live in two places** that must agree: `djmdCue` rows and a JSON mirror in `contentCue.Cues` (+ `rb_cue_count`). Rekordbox stamps - `rb_local_usn` on `contentCue`, never on the cue rows. + `rb_local_usn` on `contentCue`, never on the cue rows. Every cue write ends + in `_sync_content_cue()`, which rebuilds the mirror from the rows — leaving + it stale is this platform's version of Traktor's companion-cue desync. + Field conventions are read off a real library, not guessed: + `InFrame`/`OutFrame` are the position in frames at **150 fps**, a cue's + `ContentUUID` and its mirror row's `ID` are both the **track's UUID**, an + uncoloured cue is `Color=-1, ColorTableIndex=NULL`, and a loop is + `Color=255, ColorTableIndex=0` with `BeatLoopSize = (beats << 16) | 1`. + **Memory cues stay preserved-but-uneditable** (Rekordbox is the only + platform with them — the two-platform promotion rule), and **saved loops + are read but not written**: verified in Rekordbox, a cue row carrying + `OutMsec` does NOT land in the hot cue slot its `Kind` names — it becomes a + memory cue — so writing one would silently create an object Konduktor + cannot then edit. `cue_types.WRITABLE_CUE_TYPES` is the narrower set. + - **Saving warns but does not block when Rekordbox is running.** + `pyrekordbox.commit()` refuses outright, and its check is process-wide + rather than per-file, so `RekordboxStore._commit()` suppresses that veto + and logs instead — otherwise a temp copy could not be written while the + user had a different library open. - **`djmdCue.Kind` is an OPAQUE slot id**: 0 = memory cue, N = hot cue slot N. Pads A and C store 1 and 3, but the 6th pad stored 7 — so the slot→letter mapping is NOT a plain index and is deliberately left to the UI. @@ -350,15 +368,16 @@ that number and nothing else — everything derives from it: - ✅ Generic model + adapter interface (Traktor as the only adapter) — step 2 of the multi-platform plan. Backend, wire format and UI are all generic; nothing above `adapters/traktor/` knows what Traktor is. -- 🟡 Rekordbox adapter — **read + metadata/playlist writes done** (milestones 1 - and 2). A Rekordbox library opens, projects, browses and now accepts track - metadata and playlist edits, verified row-by-row by `test_rekordbox_fidelity.py` - and end to end through the API. Research is captured in - `.claude/handoffs/rekordbox-adapter.md` §8, incl. the verified result that - Rekordbox accepts Konduktor-written rows when USNs are maintained. Remaining - (milestone 3): the hand-written cue store (`djmdCue` + the `contentCue` JSON - mirror) and the ANLZ beatgrid store. **No version history on Rekordbox** — - accepted scope decision, see handoff §11. +- 🟡 Rekordbox adapter — **read + metadata/playlist/hot-cue writes done** + (milestones 1, 2 and 3a). A Rekordbox library opens, projects, browses and + accepts track metadata, playlist and hot cue edits, verified row-by-row by + `test_rekordbox_fidelity.py` and end to end through the API. Research is + captured in `.claude/handoffs/rekordbox-adapter.md` §8, incl. the verified + result that Rekordbox accepts Konduktor-written rows when USNs are maintained. + Remaining (3b): the ANLZ beatgrid store — riskier, because `pyrekordbox`'s ANLZ + tags refuse to change the NUMBER of beats, so a grid rewrite means manipulating + the `construct` containers directly and calling `update_len()`. **No version + history on Rekordbox** — accepted scope decision, see handoff §11. - ⬜ Serato adapter; ⬜ export/conversion - ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging diff --git a/backend/konduktor/adapters/rekordbox/adapter.py b/backend/konduktor/adapters/rekordbox/adapter.py index a02fe70..ddc75c9 100644 --- a/backend/konduktor/adapters/rekordbox/adapter.py +++ b/backend/konduktor/adapters/rekordbox/adapter.py @@ -51,6 +51,15 @@ class RekordboxAdapter: ] ) + 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. @@ -238,6 +247,62 @@ class RekordboxAdapter: 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 == "loop": + # Reading loops is fine; writing one is not. A cue row with an + # out-point does not land in the slot its Kind names — verified in + # Rekordbox — so it would silently become an uneditable memory cue. + raise Unsupported( + "Saved loops can be read but not yet written to Rekordbox libraries" + ) + 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 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) + # ---- save ------------------------------------------------------------- @property def dirty(self) -> bool: @@ -283,18 +348,6 @@ class RekordboxAdapter: def cover_art(self, track_id: str) -> tuple[bytes, str] | None: return None - 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 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") diff --git a/backend/konduktor/adapters/rekordbox/capabilities.py b/backend/konduktor/adapters/rekordbox/capabilities.py index 8163b67..d41d899 100644 --- a/backend/konduktor/adapters/rekordbox/capabilities.py +++ b/backend/konduktor/adapters/rekordbox/capabilities.py @@ -30,7 +30,7 @@ from ...core.capabilities import ( SaveCapabilities, TrackCapabilities, ) -from .cue_types import CUE_TYPES +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 @@ -54,16 +54,20 @@ def capabilities_for( writable=not cloud_synced, readonly_cause="cloud_synced" if cloud_synced else None, cues=CueCapabilities( - # Milestone 3: the cue store is hand-written (djmdCue rows plus the - # contentCue JSON mirror, kept consistent) and does not exist yet. - editable=False, + # 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 - types=CUE_TYPES, + # Loops are READ but not written — see cue_types.WRITABLE_CUE_TYPES. + types=WRITABLE_CUE_TYPES, color="palette", palette=[], # TODO milestone 2: the built-in cue colour table named=True, # djmdCue.Comment diff --git a/backend/konduktor/adapters/rekordbox/cue_types.py b/backend/konduktor/adapters/rekordbox/cue_types.py index f2fe01f..b992310 100644 --- a/backend/konduktor/adapters/rekordbox/cue_types.py +++ b/backend/konduktor/adapters/rekordbox/cue_types.py @@ -23,6 +23,21 @@ MEMORY_KIND = 0 # Rekordbox has no fade-in/fade-out/load cues; those are Traktor-only. CUE_TYPES = ["cue", "loop"] +# What Konduktor will WRITE, which is currently narrower than what it reads. +# +# A loop is projected and displayed correctly, but writing one is disabled: a +# cue row carrying `OutMsec` does NOT land in the hot cue slot its `Kind` names. +# Verified in Rekordbox 7 — a row written with `Kind=4` plus an out-point showed +# up as a MEMORY cue with pad D left empty, while an identical row without an +# out-point landed on pad B exactly as `Kind=2` predicts. Rekordbox's own 4-beat +# loop on pad F (the 6th pad) stores `Kind=7`, so loops evidently use a different +# slot encoding that has not been measured yet. +# +# Writing one anyway would silently create a MEMORY cue — which Konduktor +# deliberately cannot edit or delete — on a platform with no version history. +# Preserving a loop we cannot place is strictly better than misplacing it. +WRITABLE_CUE_TYPES = ["cue"] + def role_and_slot(kind: int | None) -> tuple[str, int | None]: """(role, slot) for a native ``Kind``.""" diff --git a/backend/konduktor/adapters/rekordbox/store.py b/backend/konduktor/adapters/rekordbox/store.py index 411fd3a..da89e90 100644 --- a/backend/konduktor/adapters/rekordbox/store.py +++ b/backend/konduktor/adapters/rekordbox/store.py @@ -26,7 +26,10 @@ Two things here are not obvious and are load-bearing: """ from __future__ import annotations +import json import logging +import uuid +from datetime import datetime from pathlib import Path from sqlalchemy import func, select, text @@ -35,10 +38,20 @@ from sqlalchemy.orm import joinedload from ...core.adapter import InvalidCommand, LibraryNotSupported, NotFound, SaveOutcome from ...core.edit_journal import EditJournal from ...core.pathmap import PathMapping +from .cue_types import beat_loop_size log = logging.getLogger(__name__) +def _iso_stamp(value) -> str: + """Rekordbox writes timestamps in the JSON mirror as ISO-8601 with a + +00:00 offset and millisecond precision (e.g. 2026-09-17T20:55:13.862+00:00). + """ + if isinstance(value, datetime): + return value.strftime("%Y-%m-%dT%H:%M:%S.") + f"{value.microsecond // 1000:03d}+00:00" + return str(value) + + class RekordboxStore: """One open Rekordbox library.""" @@ -432,8 +445,277 @@ class RekordboxStore: `capabilities.save.history` says so. """ summary = self._journal.summary() - self._db.commit(autoinc=True) + self._commit() self._journal.clear() # Reads go through the same session, so nothing needs re-projecting from # scratch — but the grid cache is keyed by track and survives a save. return SaveOutcome(summary=summary, snapshot=None, tag_results=[]) + + def _commit(self) -> None: + """Commit, warning rather than refusing if Rekordbox is running. + + `pyrekordbox.commit()` raises outright when it sees a Rekordbox process. + That is not Konduktor's behaviour: the settled decision is to **warn but + proceed**, matching how Traktor is handled — the user is told, not + blocked on a detection heuristic. The check is also process-wide rather + than per-file, so it would refuse to write a temp copy of a library while + Rekordbox had an entirely different one open, which makes tests depend on + whether the app happens to be running. + + The veto is suppressed by neutralising the process probe for the duration + of the call, so every other thing `commit()` does — the USN + auto-increment, the session commit, and keeping `masterPlaylists6.xml`'s + timestamps in step — still runs as the library intends. Duplicating that + body here would silently drift from it on upgrade. + """ + from pyrekordbox.db6 import database as rb_database + + if rb_database.get_rekordbox_pid(): + log.warning( + "Rekordbox appears to be running; saving anyway. It may overwrite " + "or re-sync the library while it is open." + ) + original = rb_database.get_rekordbox_pid + rb_database.get_rekordbox_pid = lambda *a, **kw: 0 + try: + self._db.commit(autoinc=True) + finally: + rb_database.get_rekordbox_pid = original + + @property + def app_running(self) -> bool: + """Whether a Rekordbox process is up — for warning the user, not blocking.""" + try: + from pyrekordbox.db6 import database as rb_database + + return bool(rb_database.get_rekordbox_pid()) + except Exception: # noqa: BLE001 — detection must never break a save + return False + + # ---- writes: cues ----------------------------------------------------- + # + # Rekordbox keeps cues in TWO places that must agree: normalized `djmdCue` + # rows, and a denormalized JSON mirror in `contentCue.Cues` alongside a + # `rb_cue_count`. Every mutation here ends in `_sync_content_cue()`. + # + # Field conventions below are read off a real library (see the handoff's + # Findings), not guessed: + # * `Kind` is the bank slot; 0 means a memory cue. + # * a loop is an ordinary cue row with `OutMsec` > 0 plus `BeatLoopSize`. + # * `InFrame`/`OutFrame` are the position in frames at 150 fps. + # * an uncoloured cue is `Color=-1, ColorTableIndex=NULL`; Rekordbox writes + # `Color=255, ColorTableIndex=0` on the loops and auto-cues it creates. + + _FPS = 150 # Rekordbox stores cue positions in frames as well as ms + + @staticmethod + def _frames(msec: int) -> int: + return int(msec * RekordboxStore._FPS / 1000) + + def _cue_row(self, track_id: str, slot: int): + """The hot cue occupying `slot` on this track, or None.""" + t = self._tables + return ( + self._db.session.query(t.DjmdCue) + .filter(t.DjmdCue.ContentID == str(track_id)) + .filter(t.DjmdCue.Kind == int(slot)) + .filter(t.DjmdCue.rb_local_deleted == 0) + .first() + ) + + def _loop_beats(self, track_id: str, start_sec: float, length_sec: float) -> int | None: + """Musical length of a loop, from the track's own tempo at that point.""" + if length_sec <= 0: + return None + bpm = None + grid = self.anlz_grid(track_id) + if grid: + times, bpms = grid + for t, b in zip(times, bpms): + if t <= start_sec: + bpm = b + else: + break + if bpm is None and bpms: + bpm = bpms[0] + if not bpm: + raw = getattr(self.content(track_id), "BPM", 0) or 0 + bpm = raw / 100.0 if raw else None + if not bpm: + return None + beats = round(length_sec / (60.0 / bpm)) + return max(1, int(beats)) + + def set_cue( + self, + track_id: str, + *, + slot: int, + start_sec: float, + cue_type: str, + length_sec: float = 0.0, + name: str | None = None, + ) -> None: + """Create or replace the cue in `slot`. A loop is a cue with a length.""" + if start_sec < 0: + raise InvalidCommand("A cue cannot be before the start of the track") + if int(slot) < 1: + raise InvalidCommand("Hot cue slots start at 1") + row = self.content(track_id) + in_ms = int(round(start_sec * 1000)) + is_loop = cue_type == "loop" and length_sec > 0 + out_ms = int(round((start_sec + length_sec) * 1000)) if is_loop else -1 + + existing = self._cue_row(track_id, slot) + op = "add" if existing is None else "modify" + cue = existing + if cue is None: + t = self._tables + cue = t.DjmdCue.create( + ID=str(self._db.generate_unused_id(t.DjmdCue)), + ContentID=str(track_id), + # Verified: a cue's ContentUUID is the TRACK's UUID, which is also + # the id of its contentCue mirror row. + ContentUUID=str(row.UUID), + UUID=str(uuid.uuid4()), + Kind=int(slot), + rb_data_status=0, + rb_local_data_status=0, + rb_local_deleted=0, + rb_local_synced=0, + ) + self._db.add(cue) + + cue.InMsec = in_ms + cue.InFrame = self._frames(in_ms) + cue.InMpegFrame = 0 + cue.InMpegAbs = 0 + cue.OutMsec = out_ms + cue.OutFrame = self._frames(out_ms) if is_loop else 0 + cue.OutMpegFrame = 0 + cue.OutMpegAbs = 0 + cue.Kind = int(slot) + if is_loop: + beats = self._loop_beats(track_id, start_sec, length_sec) + cue.BeatLoopSize = beat_loop_size(beats) if beats else None + cue.ActiveLoop = 0 + cue.CueMicrosec = 0 + cue.Color = 255 + cue.ColorTableIndex = 0 + else: + cue.BeatLoopSize = None + cue.ActiveLoop = None + cue.CueMicrosec = None + cue.Color = -1 + cue.ColorTableIndex = None + cue.Comment = name or None + + self._db.flush() + self._sync_content_cue(track_id) + self._journal.record("cue", op, track_id, f"slot:{slot}") + + def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> None: + cue = self._cue_row(track_id, slot) + if cue is None: + raise NotFound(f"No cue in slot {slot}") + start = (cue.InMsec or 0) / 1000.0 + length = 0.0 + if cue_type == "loop": + if cue.OutMsec and cue.OutMsec > 0: + length = (cue.OutMsec - (cue.InMsec or 0)) / 1000.0 + else: + raise InvalidCommand( + "Turning a cue into a loop needs a length — set the loop first" + ) + self.set_cue( + track_id, slot=slot, start_sec=start, cue_type=cue_type, + length_sec=length, name=cue.Comment, + ) + + def delete_cue(self, track_id: str, slot: int) -> None: + cue = self._cue_row(track_id, slot) + if cue is None: + raise NotFound(f"No cue in slot {slot}") + self._db.delete(cue) + self._db.flush() + self._sync_content_cue(track_id) + self._journal.record("cue", "delete", track_id, f"slot:{slot}") + + def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> None: + """Batch placement (Auto Hotcues). Fills empty slots unless overwriting.""" + for cue in cues: + slot = int(getattr(cue, "slot")) + if not overwrite and self._cue_row(track_id, slot) is not None: + continue + self.set_cue( + track_id, + slot=slot, + start_sec=float(getattr(cue, "start", 0.0)), + cue_type=getattr(cue, "type", "cue"), + length_sec=float(getattr(cue, "length", 0.0) or 0.0), + name=getattr(cue, "name", None), + ) + + def _sync_content_cue(self, track_id: str) -> None: + """Rebuild the denormalized `contentCue` mirror for a track. + + Rekordbox keeps a JSON copy of every cue alongside a count, and stamps + its USN on THAT row rather than on the individual cue rows — it is the + sync unit. Leaving it stale after editing `djmdCue` would make the two + disagree, which is this platform's version of Traktor's companion-cue + trap. + + Keys whose value is NULL are omitted, which is what Rekordbox's own + serializer does in every row observed. + """ + t = self._tables + row = self.content(track_id) + cues = ( + self._db.session.query(t.DjmdCue) + .filter(t.DjmdCue.ContentID == str(track_id)) + .filter(t.DjmdCue.rb_local_deleted == 0) + .order_by(t.DjmdCue.InMsec) + .all() + ) + fields = ( + "ID", "ContentID", "ContentUUID", "InMsec", "InFrame", "InMpegFrame", + "InMpegAbs", "OutMsec", "OutFrame", "OutMpegFrame", "OutMpegAbs", + "Kind", "Color", "ColorTableIndex", "ActiveLoop", "Comment", + "BeatLoopSize", "CueMicrosec", "UUID", + ) + records = [] + for cue in cues: + rec = {} + for field in fields: + value = getattr(cue, field, None) + if value is None: + continue + rec[field] = value + for stamp in ("created_at", "updated_at"): + value = getattr(cue, stamp, None) + if value is not None: + rec[stamp] = _iso_stamp(value) + records.append(rec) + + mirror = ( + self._db.session.query(t.ContentCue) + .filter(t.ContentCue.ContentID == str(track_id)) + .first() + ) + if mirror is None: + if not records: + return + mirror = t.ContentCue.create( + # Verified: the mirror's id IS the track's UUID. + ID=str(row.UUID), + ContentID=str(track_id), + UUID=str(uuid.uuid4()), + rb_data_status=0, + rb_local_data_status=0, + rb_local_deleted=0, + rb_local_synced=0, + ) + self._db.add(mirror) + mirror.Cues = json.dumps(records, ensure_ascii=False) + mirror.rb_cue_count = len(records) + self._db.flush() diff --git a/backend/test_rekordbox_adapter.py b/backend/test_rekordbox_adapter.py index d17e3d5..f12b4e1 100644 --- a/backend/test_rekordbox_adapter.py +++ b/backend/test_rekordbox_adapter.py @@ -40,7 +40,7 @@ from konduktor.core.adapter import ( # noqa: E402 NotFound, Unsupported, ) -from konduktor.core.model import GridMarker # noqa: E402 +from konduktor.core.model import GridMarker, TrackCues # noqa: E402 failed = False @@ -218,12 +218,16 @@ with tempfile.TemporaryDirectory() as d: check("with no read-only cause", caps.readonly_cause is None, str(caps.readonly_cause)) check("per-feature flags still describe what Rekordbox CAN do", caps.cues.memory_cues and caps.grid.flexible) - check("cues are NOT editable yet (milestone 3)", caps.cues.editable is False) - check("the grid is NOT editable yet (milestone 3)", caps.grid.editable is False) + check("hot cues are editable", caps.cues.editable is True) + check("the grid is NOT editable yet (milestone 3b)", caps.grid.editable is False) check("8 hot cue slots, labelled by letter", caps.cues.hotcue_slots == 8 and caps.cues.slot_labels == "letter") check("memory cues are supported", caps.cues.memory_cues) - check("no Traktor-only cue types are claimed", caps.cues.types == ["cue", "loop"]) + # Loops are READ but not WRITTEN — a cue row with an out-point does not land + # in the slot its Kind names (verified in Rekordbox), so offering it would + # silently create an uneditable memory cue. + check("only writable cue types are advertised", caps.cues.types == ["cue"], + str(caps.cues.types)) # A loop is a cue with an out-point, NOT a separate bank — verified on a real # library, and the opposite of what the original plan assumed. check("a loop is a cue type, not a separate bank", caps.cues.loops == "cue_type") @@ -244,10 +248,6 @@ with tempfile.TemporaryDirectory() as d: print("== the unimplemented stores still refuse, with a reason ==") commands = { "set_cover_art": lambda: adapter.set_cover_art(sample.id, b"", "image/jpeg"), - "set_cue": lambda: adapter.set_cue(sample.id, slot=1, start_sec=0.0, cue_type="cue"), - "set_cue_type": lambda: adapter.set_cue_type(sample.id, 1, "cue"), - "delete_cue": lambda: adapter.delete_cue(sample.id, 1), - "place_cues": lambda: adapter.place_cues(sample.id, []), "add_grid_marker": lambda: adapter.add_grid_marker(sample.id, 0.0), "move_grid_marker": lambda: adapter.move_grid_marker(sample.id, 0, 1.0), "set_grid_marker_bpm": lambda: adapter.set_grid_marker_bpm(sample.id, 0, 120.0), @@ -308,6 +308,75 @@ with tempfile.TemporaryDirectory() as d: check("unknown fields are ignored, never guessed at", adapter.set_track_metadata(writable_target.id, {"not_a_field": "x"}) is not None) + print("== hot cue writes ==") + cue_track = next((t for t in adapter.tracks if t.bpm), adapter.tracks[0]) + tc = adapter.set_cue(cue_track.id, slot=6, start_sec=30.0, cue_type="cue", name="Probe") + placed = [c for c in tc.cues if c.slot == 6] + check("the command returns the refreshed cues", len(placed) == 1, str(len(placed))) + if placed: + check("the cue is where it was put", abs(placed[0].start - 30.0) < 0.001) + check("it is a hot cue with a slot", placed[0].role == "hotcue" and placed[0].slot == 6) + check("its name round-trips", placed[0].name == "Probe", str(placed[0].name)) + check("writing a loop is refused until its slot encoding is known", + _raises(lambda: adapter.set_cue(cue_track.id, slot=7, start_sec=60.0, + cue_type="loop", length_sec=1.92), Unsupported)) + # Reading one must still work: Rekordbox libraries contain loops and losing + # them from the projection would be worse than not being able to edit them. + looped = [ + c + for t in adapter.tracks[:40] + for c in (adapter.track_cues(t.id) or TrackCues()).cues + if c.type == "loop" + ] + if looped: + check("existing loops are still projected, with their length", + all(c.length > 0 for c in looped), str([c.length for c in looped])) + # Replacing an occupied slot must not leave two cues in it. + tc = adapter.set_cue(cue_track.id, slot=6, start_sec=45.0, cue_type="cue") + in_six = [c for c in tc.cues if c.slot == 6] + check("re-setting a slot replaces rather than duplicates", len(in_six) == 1, str(len(in_six))) + if in_six: + check("and moves it", abs(in_six[0].start - 45.0) < 0.001) + tc = adapter.delete_cue(cue_track.id, 6) + check("a deleted slot is empty", not [c for c in tc.cues if c.slot == 6]) + check("deleting an empty slot is NotFound", + _raises(lambda: adapter.delete_cue(cue_track.id, 6), NotFound)) + check("a Traktor-only cue type is Unsupported", + _raises(lambda: adapter.set_cue(cue_track.id, slot=2, start_sec=1.0, + cue_type="fade_in"), Unsupported)) + # Rekordbox is the ONLY platform with memory cues, so they stay + # preserved-but-uneditable under the two-platform promotion rule. + check("memory cues are shown but not writable", + _raises(lambda: adapter.set_cue(cue_track.id, slot=1, start_sec=1.0, + cue_type="cue", role="memory"), Unsupported)) + check("slot 0 is rejected — it is the memory-cue encoding, not a bank slot", + _raises(lambda: adapter.set_cue(cue_track.id, slot=0, start_sec=1.0, + cue_type="cue"), InvalidCommand)) + check("a negative position is rejected", + _raises(lambda: adapter.set_cue(cue_track.id, slot=2, start_sec=-1.0, + cue_type="cue"), InvalidCommand)) + + print("== saving warns but proceeds while Rekordbox is running ==") + # pyrekordbox's own commit() refuses outright if it sees a Rekordbox process. + # Konduktor's settled behaviour is to warn, not block — matching Traktor — + # and the library's check is process-wide, so it would otherwise refuse to + # write a temp copy while the user had a different library open. + from pyrekordbox.db6 import database as _rb_database + + _real_pid = _rb_database.get_rekordbox_pid + _rb_database.get_rekordbox_pid = lambda *a, **kw: 4242 # pretend it is running + try: + adapter.set_track_metadata(sample.id, {"title": "Saved While Running"}) + adapter.save() + check("a save completes with Rekordbox running", True) + except Exception as ex: # noqa: BLE001 + check("a save completes with Rekordbox running", False, f"{type(ex).__name__}: {ex}") + finally: + _rb_database.get_rekordbox_pid = _real_pid + check("and the edit really landed", + adapter.track(sample.id).title == "Saved While Running", + str(adapter.track(sample.id).title)) + print("== a cloud-synced library is refused permanently, not pending a milestone ==") # The one failure mode version history cannot undo: a local edit the sync # server did not issue could corrupt the user's OTHER machines. Detection is diff --git a/backend/test_rekordbox_fidelity.py b/backend/test_rekordbox_fidelity.py index 4cb6ac0..d7d83eb 100644 --- a/backend/test_rekordbox_fidelity.py +++ b/backend/test_rekordbox_fidelity.py @@ -237,5 +237,85 @@ with tempfile.TemporaryDirectory() as d: len(final.playlist_tree()) == len(before_tree), f"{len(final.playlist_tree())} vs {len(before_tree)}") + # ---- F: a cue write touches the cue row AND its mirror --------------- + print("== F: a hot cue write is localized, and keeps the mirror in step ==") + clean_copy(REAL, work, closing=[adapter, again, final, reopened]) + before = dump(work) + adapter = RekordboxAdapter(work) + cue_track = next((t for t in adapter.tracks if t.bpm), adapter.tracks[0]) + adapter.set_cue(cue_track.id, slot=6, start_sec=30.0, cue_type="cue", name="Probe") + adapter.save() + changes = diff(before, dump(work)) + tables_touched = {t for t, _, _, _ in changes} + # djmdCue gains a row, contentCue's mirror is rewritten, the counter moves. + # Nothing else may move — in particular not djmdContent. + check("only the cue, its mirror and the counter change", + tables_touched == {"djmdCue", "contentCue", "agentRegistry"}, + str(tables_touched)) + cue_rows = [c for c in changes if c[0] == "djmdCue"] + check("exactly one cue row is inserted", + len(cue_rows) == 1 and cue_rows[0][2] == "INSERT", describe(cue_rows)) + if cue_rows and cue_rows[0][2] == "INSERT": + row = cue_rows[0][3] + check("it is a hot cue in the slot asked for", row["Kind"] == 6, str(row["Kind"])) + check("positions are stored in ms AND frames at 150fps", + row["InMsec"] == 30000 and row["InFrame"] == 4500, + f"{row['InMsec']}/{row['InFrame']}") + check("a non-loop has no out-point", row["OutMsec"] == -1, str(row["OutMsec"])) + check("an uncoloured cue matches Rekordbox's own convention", + row["Color"] == -1 and row["ColorTableIndex"] is None, + f"{row['Color']}/{row['ColorTableIndex']}") + check("the cue points at its track's UUID", + row["ContentUUID"] == dump(work)["djmdContent"][cue_track.id]["UUID"]) + + # The mirror is the trap: leaving it stale is this platform's version of + # Traktor's companion-cue desync. + mirror = [c for c in changes if c[0] == "contentCue"] + check("the JSON mirror was rewritten", len(mirror) == 1, describe(mirror)) + after = dump(work) + mirror_row = next( + (r for r in after["contentCue"].values() if r["ContentID"] == cue_track.id), None + ) + check("a mirror row exists for the track", mirror_row is not None) + if mirror_row: + import json as _json + + records = _json.loads(mirror_row["Cues"]) + live = [ + r for r in after["djmdCue"].values() + if r["ContentID"] == cue_track.id and not r["rb_local_deleted"] + ] + check("the mirror holds one record per cue row", + len(records) == len(live), f"{len(records)} vs {len(live)}") + check("rb_cue_count agrees with both", + mirror_row["rb_cue_count"] == len(live), + f"{mirror_row['rb_cue_count']} vs {len(live)}") + check("the mirror's id is the track's UUID", + mirror_row["ID"] == after["djmdContent"][cue_track.id]["UUID"]) + check("the new cue is in the mirror", any(r["Kind"] == 6 for r in records)) + + # ---- G: deleting a cue removes it from both places ------------------- + print("== G: deleting a cue clears the row and the mirror ==") + adapter.delete_cue(cue_track.id, 6) + adapter.save() + after = dump(work) + live = [ + r for r in after["djmdCue"].values() + if r["ContentID"] == cue_track.id and r["Kind"] == 6 and not r["rb_local_deleted"] + ] + check("the cue row is gone", not live, str(len(live))) + mirror_row = next( + (r for r in after["contentCue"].values() if r["ContentID"] == cue_track.id), None + ) + if mirror_row: + import json as _json + + records = _json.loads(mirror_row["Cues"]) + check("and gone from the mirror too", not any(r["Kind"] == 6 for r in records)) + check("with rb_cue_count updated", + mirror_row["rb_cue_count"] == len(records), + f"{mirror_row['rb_cue_count']} vs {len(records)}") + adapter.close() + print("\nRESULT:", "FAILED" if failed else "ALL PASSED") sys.exit(1 if failed else 0) From 5aeb9956cd19bca02ff69116d9975c21f912f2fd Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Sat, 19 Sep 2026 11:01:51 +0200 Subject: [PATCH 10/64] Added grid support to Rekordbox Adapter --- .claude/handoffs/rekordbox-adapter.md | 81 +++++++++++ CLAUDE.md | 41 ++++-- .../konduktor/adapters/rekordbox/adapter.py | 76 ++++++---- .../konduktor/adapters/rekordbox/beatgrid.py | 48 +++++++ .../adapters/rekordbox/capabilities.py | 5 +- backend/konduktor/adapters/rekordbox/store.py | 130 ++++++++++++++++++ backend/test_rekordbox_adapter.py | 68 +++++++-- backend/test_rekordbox_fidelity.py | 64 +++++++++ 8 files changed, 465 insertions(+), 48 deletions(-) diff --git a/.claude/handoffs/rekordbox-adapter.md b/.claude/handoffs/rekordbox-adapter.md index 3fcf695..ec0d164 100644 --- a/.claude/handoffs/rekordbox-adapter.md +++ b/.claude/handoffs/rekordbox-adapter.md @@ -924,3 +924,84 @@ auto-increment and keeping `masterPlaylists6.xml`'s timestamps in step — still runs as the library intends. `store.app_running` exposes the detection for warning the user rather than blocking them. A test pins the behaviour by faking a running process. + +### Milestone 3b progress: the grid can be written, but only half of it + +**The mechanical problem is solved.** `beatgrid.write_pqtz()` rebuilds a `.DAT`'s +`PQTZ` entry list from scratch — including changing the number of beats, which +`pyrekordbox`'s own setters refuse — by replacing `content.entries`, setting +`entry_count`, and calling the tag's `update_len()`. Verified on a real file: +resizing 374 → 367 beats produced exactly the expected byte-size delta, re-parsed +correctly, and left **every other tag byte-identical**. + +**The blocker is `.EXT`.** The grid exists twice: `PQTZ` in `.DAT` and the +"extended" `PQT2` in `.EXT`. `PQT2` carries a 2-byte-per-beat array whose second +byte `pyrekordbox` literally names `unkown`, plus an undecoded `u3` field. +Inspection did not crack it: the value drifts ~2.75 per beat with a jump at each +bar boundary and must wrap within 8 bits, so it is neither a time nor a simple +index. Writing guesses into it would corrupt real user data on a platform with no +version history, so **`PQT2` is left untouched**. + +That leaves one empirical question, and it decides the whole feature: + +> **Does Rekordbox read the grid from `PQTZ` (`.DAT`) or from `PQT2` (`.EXT`)?** + +A test is staged: Demo Track 1's `PQTZ` rewritten to **half-time (64 BPM, 184 +beats)**, `.EXT` and `master.db` untouched, installed as a single-file copy. +Half-time is chosen because it is unmistakable — beat markers at half density and +a 64 BPM readout — rather than a subtle shift someone has to judge. + +- **If Rekordbox shows the half-time grid**: `PQTZ` is authoritative, and grid + editing is feasible. `PQT2` may still need attention for CDJ export, which is + out of scope anyway. +- **If it shows the original 128 BPM grid**: `PQT2` wins, and grid editing stays + out of reach until someone decodes it. That is a legitimate result — Rekordbox + support would ship as library management + cues, with grid editing remaining a + Traktor feature. + +Note `djmdContent.BPM` is deliberately left at 128 in this test, so the library +list and the deck disagreeing is itself a signal about which copy is read where. + +### Milestone 3b landed: the beatgrid writes + +**`PQTZ` is authoritative — verified in Rekordbox 7.** The staged half-time test +showed the deck at 64 BPM with the grid correctly half-timed. Afterwards the +`.DAT` was byte-identical to what Konduktor wrote, `.EXT` and `.2EX` were +untouched, and Rekordbox did **not** reconcile `djmdContent.BPM`, which sat at +128 while the deck showed 64. + +Three things follow, all now implemented: + +1. **Only `.DAT`'s `PQTZ` is written.** The stale extended grid in `.EXT` does + not trouble Rekordbox's own display; it would matter only for CDJ export, + which is out of scope. +2. **`djmdContent.BPM` is Konduktor's to maintain**, mirroring the first marker — + the same relationship Traktor's `` has to its first grid marker. + Without it the library list and the deck disagree. +3. **Grid edits are buffered until `save()`.** ANLZ edits are file writes, so + applying them at command time would put an unsaved edit on disk and break the + save contract every other platform obeys. `save()` writes the files first and + commits the database second, so a failed file write leaves nothing committed. + +The full marker vocabulary works — add / move (clamped between neighbours) / +retempo / delete / replace / delete-grid — including genuinely **flexible +multi-tempo grids**, end to end through the HTTP API. + +Fidelity phase H is the safety net: an unsaved grid edit does not touch the file; +`.EXT`/`.2EX` stay byte-identical; **every tag in the rewritten `.DAT` except +`PQTZ` is byte-identical**; and in the database only `BPM` + the row USN + the +counter move. Suite: **316 assertions**. + +### Remaining Rekordbox gaps + +- **Saved loops** — read but not written (§ above). Needs the slot encoding + measured: a 4-beat loop on pads D and E, then read the `Kind` values. +- ~~A Konduktor-written FLEXIBLE grid has not been seen in Rekordbox.~~ + **VERIFIED 2026-09-19**: Demo Track 1 written as 128 BPM dropping to 90 at + 1:00 displayed exactly that in Rekordbox 7 — the deck's BPM readout followed + the tempo change at the marker. Multi-marker grids are confirmed end to end, + which is the last thing milestone 3 was waiting on. +- **Cover art** — never investigated; `tracks.artwork` is false. +- **`PQT2` is undecoded**, so the extended grid drifts out of step with `PQTZ` + after any Konduktor grid edit. Harmless for Rekordbox itself; would need + solving before any CDJ/USB export (currently rejected as out of scope). diff --git a/CLAUDE.md b/CLAUDE.md index a3ed3fe..1f5acf7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -65,10 +65,25 @@ Two independent apps that talk over HTTP: mutating command raises `Unsupported` and `capabilities()` advertises nothing as editable, so the UI never offers an edit. Three things differ from Traktor and are the reason this adapter is not a copy of it: - - **The beatgrid is NOT in the database.** There is no grid table at all; it + - **The beatgrid is NOT in the database, and is written to ONE tag of ONE + file.** There is no grid table at all; it lives in per-track ANLZ analysis files as a `PQTZ` tag listing EVERY BEAT. `beatgrid.py` collapses those into the generic marker list on read and - expands them back on write. `store.anlz_grid()` parses them **lazily** — + expands them back on write. `write_pqtz()` rebuilds the entry list + directly — `pyrekordbox`'s own setters refuse to change the NUMBER of + beats, which every real edit does — then calls the tag's `update_len()`. + **Only `.DAT`'s `PQTZ` is written.** `.EXT` holds a second "extended" grid + (`PQT2`) whose per-beat byte `pyrekordbox` itself calls `unkown`, so + writing it would mean guessing at bytes in data with no version history. + Verified in Rekordbox 7: it reads the grid AND the deck's BPM from `PQTZ`, + leaves a Konduktor-written `.DAT` untouched, and is unbothered by the stale + `.EXT` (which would matter only for CDJ export — out of scope). It does + **not** reconcile `djmdContent.BPM`, so the adapter maintains that column + itself, mirroring the first marker exactly as Traktor's `` does. + Grid edits are **buffered until `save()`** so ANLZ file writes obey the same + "edit in memory, Save writes to disk" contract as everything else; `save()` + writes the files BEFORE committing the database, so a failed file write + leaves nothing committed. `store.anlz_grid()` parses them **lazily** — ~1.4 ms each, i.e. ~12 s for a library of 8,500 if done at open — so `Track.grid_marker_count` carries a documented approximation (1 when the track has a BPM) that `track_cues()` corrects. @@ -368,16 +383,18 @@ that number and nothing else — everything derives from it: - ✅ Generic model + adapter interface (Traktor as the only adapter) — step 2 of the multi-platform plan. Backend, wire format and UI are all generic; nothing above `adapters/traktor/` knows what Traktor is. -- 🟡 Rekordbox adapter — **read + metadata/playlist/hot-cue writes done** - (milestones 1, 2 and 3a). A Rekordbox library opens, projects, browses and - accepts track metadata, playlist and hot cue edits, verified row-by-row by - `test_rekordbox_fidelity.py` and end to end through the API. Research is - captured in `.claude/handoffs/rekordbox-adapter.md` §8, incl. the verified - result that Rekordbox accepts Konduktor-written rows when USNs are maintained. - Remaining (3b): the ANLZ beatgrid store — riskier, because `pyrekordbox`'s ANLZ - tags refuse to change the NUMBER of beats, so a grid rewrite means manipulating - the `construct` containers directly and calling `update_len()`. **No version - history on Rekordbox** — accepted scope decision, see handoff §11. +- 🟡 Rekordbox adapter — **read + metadata/playlist/hot-cue/beatgrid writes + done** (milestones 1–3). A Rekordbox library opens, projects, browses and + accepts track metadata, playlist, hot cue and beatgrid edits — including + flexible multi-tempo grids, confirmed rendering correctly in Rekordbox 7 — + verified row-by-row by + `test_rekordbox_fidelity.py`, end to end through the API, and in Rekordbox 7 + itself. Research is captured in `.claude/handoffs/rekordbox-adapter.md` §8, + incl. the verified result that Rekordbox accepts Konduktor-written rows when + USNs are maintained. Remaining gaps: **saved loops** (a cue row with an + out-point does not land in the slot its `Kind` names — encoding unmeasured) and + **cover art**. **No version history on Rekordbox** — accepted scope decision, + see handoff §11. - ⬜ Serato adapter; ⬜ export/conversion - ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging diff --git a/backend/konduktor/adapters/rekordbox/adapter.py b/backend/konduktor/adapters/rekordbox/adapter.py index ddc75c9..4abec9c 100644 --- a/backend/konduktor/adapters/rekordbox/adapter.py +++ b/backend/konduktor/adapters/rekordbox/adapter.py @@ -23,7 +23,7 @@ from pathlib import Path from ...core.adapter import Unsupported from ...core.capabilities import Capabilities -from ...core.model import PlaylistNode, Track, TrackCues +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 @@ -303,6 +303,56 @@ class RekordboxAdapter: 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: @@ -348,26 +398,6 @@ class RekordboxAdapter: def cover_art(self, track_id: str) -> tuple[bytes, str] | None: return None - 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("Editing the beatgrid") - def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues: - self._refuse("Locking the beatgrid") + # Rekordbox has no per-track grid lock; capabilities.grid.lockable says so. + raise Unsupported("Rekordbox has no beatgrid lock") diff --git a/backend/konduktor/adapters/rekordbox/beatgrid.py b/backend/konduktor/adapters/rekordbox/beatgrid.py index 005b86e..e9c9081 100644 --- a/backend/konduktor/adapters/rekordbox/beatgrid.py +++ b/backend/konduktor/adapters/rekordbox/beatgrid.py @@ -78,3 +78,51 @@ def beats_from_markers( 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 diff --git a/backend/konduktor/adapters/rekordbox/capabilities.py b/backend/konduktor/adapters/rekordbox/capabilities.py index d41d899..decd073 100644 --- a/backend/konduktor/adapters/rekordbox/capabilities.py +++ b/backend/konduktor/adapters/rekordbox/capabilities.py @@ -73,7 +73,10 @@ def capabilities_for( named=True, # djmdCue.Comment loops="cue_type", ), - grid=GridCapabilities(editable=False, flexible=True, lockable=False), + # 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 diff --git a/backend/konduktor/adapters/rekordbox/store.py b/backend/konduktor/adapters/rekordbox/store.py index da89e90..84b6b2b 100644 --- a/backend/konduktor/adapters/rekordbox/store.py +++ b/backend/konduktor/adapters/rekordbox/store.py @@ -60,6 +60,9 @@ class RekordboxStore: self._mapping = PathMapping() self._grid_cache: dict[str, tuple[list[float], list[float]] | None] = {} self._journal = EditJournal() + # Grid edits buffered until save(): ANLZ files are written to disk, so + # applying them at command time would break the save contract. + self._pending_grids: dict[str, tuple[list, list, list]] = {} self._load() # ---- open ------------------------------------------------------------ @@ -445,6 +448,9 @@ class RekordboxStore: `capabilities.save.history` says so. """ summary = self._journal.summary() + # Files first: if an analysis file cannot be written, nothing should have + # been committed to the database either. + self._flush_grids() self._commit() self._journal.clear() # Reads go through the same session, so nothing needs re-projecting from @@ -719,3 +725,127 @@ class RekordboxStore: mirror.Cues = json.dumps(records, ensure_ascii=False) mirror.rb_cue_count = len(records) self._db.flush() + + # ---- writes: the beatgrid --------------------------------------------- + # + # The grid lives in the track's ANLZ `.DAT` (`PQTZ`), not in the database. + # Verified in Rekordbox 7: it reads the grid and the deck's BPM readout from + # `PQTZ`, leaves a rewritten `.DAT` exactly as Konduktor wrote it, ignores + # the stale extended grid in `.EXT` — and does NOT reconcile + # `djmdContent.BPM`, which stayed at the old tempo while the deck showed the + # new one. So that column is Konduktor's to maintain. + # + # Edits are BUFFERED and the files are written on save(), so the grid obeys + # the same "edit in memory, Save writes to disk" contract as everything else + # — an unsaved grid change must not already be on disk. + + def current_markers(self, track_id: str) -> list: + """The track's grid as a generic marker list (pending edits included).""" + from . import beatgrid as grid_math + + grid = self.anlz_grid(track_id) + if grid is None: + return [] + times, bpms = grid + return grid_math.markers_from_beats(times, bpms) + + def track_duration(self, track_id: str) -> float: + """Seconds, for expanding markers back into beats.""" + length = getattr(self.content(track_id), "Length", None) + if length: + return float(length) + grid = self.anlz_grid(track_id) + if grid and grid[0]: + return float(grid[0][-1]) + 1.0 + return 0.0 + + def replace_grid(self, track_id: str, markers: list) -> None: + """Set the grid to exactly these markers. The one primitive; every + marker-level command is expressed as a read-modify-replace on top.""" + from . import beatgrid as grid_math + + for m in markers: + if m.bpm <= 0: + raise InvalidCommand(f"A beatgrid marker needs a positive tempo, got {m.bpm}") + if m.start < 0: + raise InvalidCommand("A beatgrid marker cannot be before the track starts") + ordered = sorted(markers, key=lambda m: m.start) + duration = self.track_duration(track_id) + beat_nums, bpms, times = grid_math.beats_from_markers(ordered, duration) + # Buffer as the same (times, bpms) shape the reader returns, so the + # projection needs no special case for an unsaved grid. + self._pending_grids[str(track_id)] = (beat_nums, bpms, times) + self._grid_cache[str(track_id)] = (times, bpms) if times else None + # TEMPO mirrors the first marker, exactly as Traktor's does — + # Rekordbox will not do it for us. + row = self.content(track_id) + row.BPM = int(round(ordered[0].bpm * 100)) if ordered else 0 + self._journal.record("grid", "replace" if ordered else "delete", track_id) + + def delete_grid(self, track_id: str) -> None: + self.replace_grid(track_id, []) + + def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> None: + from ...core.model import GridMarker + + markers = self.current_markers(track_id) + if bpm is None: + # Inherit the tempo governing this point, like Traktor's add does. + governing = [m for m in markers if m.start <= start_sec] + bpm = governing[-1].bpm if governing else (markers[0].bpm if markers else None) + if not bpm: + raise InvalidCommand("The first marker on an ungridded track needs a tempo") + if any(abs(m.start - start_sec) < 0.001 for m in markers): + raise InvalidCommand("There is already a marker here") + markers.append(GridMarker(start=float(start_sec), bpm=float(bpm))) + self.replace_grid(track_id, markers) + + def _marker_at(self, track_id: str, index: int) -> tuple[list, int]: + markers = self.current_markers(track_id) + if not 0 <= index < len(markers): + raise NotFound(f"No grid marker {index}") + return markers, index + + def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> None: + markers, i = self._marker_at(track_id, index) + # Clamp between neighbours so the list cannot reorder under the caller. + low = markers[i - 1].start + 0.001 if i > 0 else 0.0 + high = markers[i + 1].start - 0.001 if i + 1 < len(markers) else None + target = max(low, float(start_sec)) + if high is not None: + target = min(target, high) + markers[i] = markers[i].model_copy(update={"start": target}) + self.replace_grid(track_id, markers) + + def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> None: + markers, i = self._marker_at(track_id, index) + if bpm <= 0: + raise InvalidCommand(f"A tempo must be positive, got {bpm}") + markers[i] = markers[i].model_copy(update={"bpm": float(bpm)}) + self.replace_grid(track_id, markers) + + def delete_grid_marker(self, track_id: str, index: int) -> None: + markers, i = self._marker_at(track_id, index) + del markers[i] + self.replace_grid(track_id, markers) + + def _flush_grids(self) -> None: + """Write buffered grids into their ANLZ files. Called by save(). + + Only `.DAT`'s `PQTZ` is written — `.EXT`'s extended grid carries + undecoded bytes, and Rekordbox was verified to read the grid from + `PQTZ` and to be untroubled by the other being stale. + """ + from . import beatgrid as grid_math + + for track_id, (beat_nums, bpms, times) in list(self._pending_grids.items()): + rel = getattr(self.content(track_id), "AnalysisDataPath", None) + if not rel: + raise InvalidCommand( + "This track has no analysis file, so it has nowhere to store a beatgrid" + ) + path = self.path.parent / "share" / str(rel).lstrip("/\\") + if not path.is_file(): + raise InvalidCommand(f"Analysis file is missing: {path}") + grid_math.write_pqtz(path, beat_nums, bpms, times) + self._pending_grids.clear() diff --git a/backend/test_rekordbox_adapter.py b/backend/test_rekordbox_adapter.py index f12b4e1..512b1b2 100644 --- a/backend/test_rekordbox_adapter.py +++ b/backend/test_rekordbox_adapter.py @@ -219,7 +219,8 @@ with tempfile.TemporaryDirectory() as d: check("per-feature flags still describe what Rekordbox CAN do", caps.cues.memory_cues and caps.grid.flexible) check("hot cues are editable", caps.cues.editable is True) - check("the grid is NOT editable yet (milestone 3b)", caps.grid.editable is False) + check("the grid is editable", caps.grid.editable is True) + check("but has no lock — Rekordbox has no such concept", caps.grid.lockable is False) check("8 hot cue slots, labelled by letter", caps.cues.hotcue_slots == 8 and caps.cues.slot_labels == "letter") check("memory cues are supported", caps.cues.memory_cues) @@ -232,8 +233,6 @@ with tempfile.TemporaryDirectory() as d: # library, and the opposite of what the original plan assumed. check("a loop is a cue type, not a separate bank", caps.cues.loops == "cue_type") check("cue colour is a palette, not free RGB", caps.cues.color == "palette") - check("the grid is flexible but not editable yet", - caps.grid.flexible and not caps.grid.editable) check("the editable field set is advertised", bool(caps.tracks.editable_fields)) # Rekordbox has no column for these; Traktor does. Mapping them onto its # Composer field would silently write the wrong thing. @@ -245,16 +244,10 @@ with tempfile.TemporaryDirectory() as d: caps.save.overwrite_risk == "while_running") check("library label is master.db", caps.save.library_label == "master.db") - print("== the unimplemented stores still refuse, with a reason ==") + print("== what Rekordbox genuinely cannot do still refuses, with a reason ==") commands = { "set_cover_art": lambda: adapter.set_cover_art(sample.id, b"", "image/jpeg"), - "add_grid_marker": lambda: adapter.add_grid_marker(sample.id, 0.0), - "move_grid_marker": lambda: adapter.move_grid_marker(sample.id, 0, 1.0), - "set_grid_marker_bpm": lambda: adapter.set_grid_marker_bpm(sample.id, 0, 120.0), - "delete_grid_marker": lambda: adapter.delete_grid_marker(sample.id, 0), - "replace_grid": lambda: adapter.replace_grid(sample.id, []), - "set_analysed_grid": lambda: adapter.set_analysed_grid(sample.id, []), - "delete_grid": lambda: adapter.delete_grid(sample.id), + # Rekordbox genuinely has no per-track grid lock, unlike Traktor's LOCK. "set_grid_lock": lambda: adapter.set_grid_lock(sample.id, True), "remap_locations": lambda: adapter.remap_locations(None), # save() works now; snapshot() must not, because a Rekordbox library is @@ -270,7 +263,7 @@ with tempfile.TemporaryDirectory() as d: pass except Exception as ex: # noqa: BLE001 — anything else is the wrong error refused.append(f"{name} ({type(ex).__name__})") - check("every cue/grid command still raises Unsupported", not refused, ", ".join(refused)) + check("each raises Unsupported rather than failing oddly", not refused, ", ".join(refused)) check("refusing a command leaves the adapter clean", adapter.dirty is False) print("== metadata writes, including the foreign-key fields ==") @@ -356,6 +349,57 @@ with tempfile.TemporaryDirectory() as d: _raises(lambda: adapter.set_cue(cue_track.id, slot=2, start_sec=-1.0, cue_type="cue"), InvalidCommand)) + print("== beatgrid edits ==") + grid_track = next((t for t in adapter.tracks if t.bpm), None) + if grid_track: + check("a gridded track starts with at least one marker", + len(adapter.track_cues(grid_track.id).grid_markers) >= 1) + # Put the grid into a KNOWN state first. Reading whatever the library + # happens to hold made this section depend on the user's own edits — it + # broke the moment the reference library gained a marker at 60s. + tc = adapter.replace_grid(grid_track.id, [(0.05, 120.0)]) + check("the grid can be reset to a single known marker", + len(tc.grid_markers) == 1 and tc.grid_markers[0].bpm == 120.0, + str([(m.start, m.bpm) for m in tc.grid_markers])) + tc = adapter.set_grid_marker_bpm(grid_track.id, 0, 130.0) + check("retempo changes the marker", tc.grid_markers[0].bpm == 130.0, + str(tc.grid_markers[0].bpm)) + # Rekordbox does NOT reconcile the BPM column with the grid — verified in + # the real app, where the deck showed the new tempo and the list the old. + check("the BPM column follows the first marker", + adapter.track(grid_track.id).bpm == 130.0, + str(adapter.track(grid_track.id).bpm)) + tc = adapter.add_grid_marker(grid_track.id, 60.0, 140.0) + check("a second marker makes the grid flexible", len(tc.grid_markers) == 2, + str(len(tc.grid_markers))) + check("markers stay ordered by position", + tc.grid_markers[0].start < tc.grid_markers[1].start) + check("Rekordbox markers never carry a companion cue", + all(m.companion is None for m in tc.grid_markers)) + # A move is clamped between neighbours so the list cannot reorder. + tc = adapter.move_grid_marker(grid_track.id, 1, 0.0) + check("moving a marker past its neighbour is clamped", + tc.grid_markers[1].start > tc.grid_markers[0].start, + f"{tc.grid_markers[0].start} / {tc.grid_markers[1].start}") + tc = adapter.delete_grid_marker(grid_track.id, 1) + check("a marker can be deleted", len(tc.grid_markers) == 1, str(len(tc.grid_markers))) + check("grid_marker_count follows the real grid", + adapter.track(grid_track.id).grid_marker_count == 1) + tc = adapter.delete_grid(grid_track.id) + check("the whole grid can be deleted", tc.grid_markers == []) + check("and the BPM column is cleared with it", + adapter.track(grid_track.id).bpm is None, + str(adapter.track(grid_track.id).bpm)) + tc = adapter.replace_grid(grid_track.id, [(0.05, 128.0)]) + check("replace_grid accepts (start, bpm) tuples from the route layer", + len(tc.grid_markers) == 1 and tc.grid_markers[0].bpm == 128.0) + check("a non-positive tempo is rejected", + _raises(lambda: adapter.set_grid_marker_bpm(grid_track.id, 0, 0), InvalidCommand)) + check("an unknown marker index is NotFound", + _raises(lambda: adapter.set_grid_marker_bpm(grid_track.id, 9, 120.0), NotFound)) + check("Rekordbox has no grid lock", + _raises(lambda: adapter.set_grid_lock(grid_track.id, True), Unsupported)) + print("== saving warns but proceeds while Rekordbox is running ==") # pyrekordbox's own commit() refuses outright if it sees a Rekordbox process. # Konduktor's settled behaviour is to warn, not block — matching Traktor — diff --git a/backend/test_rekordbox_fidelity.py b/backend/test_rekordbox_fidelity.py index d7d83eb..40539ff 100644 --- a/backend/test_rekordbox_fidelity.py +++ b/backend/test_rekordbox_fidelity.py @@ -317,5 +317,69 @@ with tempfile.TemporaryDirectory() as d: f"{mirror_row['rb_cue_count']} vs {len(records)}") adapter.close() + # ---- H: a grid write touches ONE tag of ONE file --------------------- + print("== H: a beatgrid write is localized to the .DAT's PQTZ tag ==") + from pyrekordbox.anlz import AnlzFile + + adapter = RekordboxAdapter(work) # phase G closed the previous one + grid_track = next((t for t in adapter.tracks if t.bpm), None) + if grid_track is None: + check("a gridded track exists to test with", False, "none found") + else: + rel = str(dump(work)["djmdContent"][grid_track.id]["AnalysisDataPath"]).lstrip("/") + dat = Path(d) / "share" / rel + ext = dat.with_suffix(".EXT") + two_ex = dat.with_suffix(".2EX") + before_dat = dat.read_bytes() + before_ext = ext.read_bytes() if ext.is_file() else None + before_2ex = two_ex.read_bytes() if two_ex.is_file() else None + before_db = dump(work) + + adapter.set_grid_marker_bpm(grid_track.id, 0, 130.0) + # The save contract: an unsaved grid edit must not be on disk yet. + check("an unsaved grid edit has not touched the analysis file", + dat.read_bytes() == before_dat) + adapter.save() + + check("the analysis file changed", dat.read_bytes() != before_dat) + # The extended grid carries undecoded bytes and is deliberately not + # written. Rekordbox was verified to read PQTZ and ignore this being stale. + if before_ext is not None: + check(".EXT is left untouched", ext.read_bytes() == before_ext) + if before_2ex is not None: + check(".2EX is left untouched", two_ex.read_bytes() == before_2ex) + + # The real localization test: every OTHER tag in the rewritten .DAT must + # be byte-identical. This is the ANLZ analogue of "only edited objects + # diff", and it is what would catch a rebuild corrupting the file. + old_tags = {t.type: t.build() for t in AnlzFile.parse(before_dat).tags if t.type != "PQTZ"} + new_tags = {t.type: t.build() for t in AnlzFile.parse_file(str(dat)).tags if t.type != "PQTZ"} + check("the same tags are present afterwards", + set(old_tags) == set(new_tags), f"{sorted(old_tags)} vs {sorted(new_tags)}") + differing = [k for k in old_tags if k in new_tags and old_tags[k] != new_tags[k]] + check("every tag except PQTZ is byte-identical", not differing, ", ".join(differing)) + + reread = AnlzFile.parse_file(str(dat)) + pqtz = next(t for t in reread.tags if t.type == "PQTZ") + check("the new tempo is really in the file", + abs(float(pqtz.bpms[0]) - 130.0) < 0.001, str(pqtz.bpms[0])) + check("the grid still covers the track", + len(pqtz.beats) > 1 and float(pqtz.times[-1]) > 0) + + # The BPM column is Konduktor's to maintain: Rekordbox does not + # reconcile it with the grid (verified in the real app). + changes = diff(before_db, dump(work)) + tables_touched = {t for t, _, _, _ in changes} + check("in the database, only the track's BPM and the counter move", + tables_touched == {"djmdContent", "agentRegistry"}, str(tables_touched)) + content = [c for c in changes if c[0] == "djmdContent"] + if content and content[0][2] == "UPDATE": + fields = content[0][3] + check("only BPM and the row USN changed", + set(fields) == {"BPM", "rb_local_usn"}, str(sorted(fields))) + check("BPM is stored x100", fields.get("BPM", (0, 0))[1] == 13000, + str(fields.get("BPM"))) + adapter.close() + print("\nRESULT:", "FAILED" if failed else "ALL PASSED") sys.exit(1 if failed else 0) From 00dd3fe7668cefa31398dc76bffa9df9258317c1 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Sat, 19 Sep 2026 12:40:05 +0200 Subject: [PATCH 11/64] Fixed Rekordbox hotcue issues --- .../konduktor/adapters/rekordbox/adapter.py | 7 - .../adapters/rekordbox/capabilities.py | 2 +- .../konduktor/adapters/rekordbox/cue_types.py | 63 +++++--- .../adapters/rekordbox/projection.py | 17 ++- backend/konduktor/adapters/rekordbox/store.py | 26 +++- backend/test_rekordbox_adapter.py | 79 +++++++--- backend/test_rekordbox_fidelity.py | 25 +++- dev-sandbox.sh | 140 ++++++++++++++++++ frontend/src/components/EditTagsDialog.tsx | 57 ++++--- 9 files changed, 327 insertions(+), 89 deletions(-) create mode 100755 dev-sandbox.sh diff --git a/backend/konduktor/adapters/rekordbox/adapter.py b/backend/konduktor/adapters/rekordbox/adapter.py index 4abec9c..9b5fae5 100644 --- a/backend/konduktor/adapters/rekordbox/adapter.py +++ b/backend/konduktor/adapters/rekordbox/adapter.py @@ -249,13 +249,6 @@ class RekordboxAdapter: # ---- commands: cues --------------------------------------------------- def _check_cue_type(self, cue_type: str) -> None: - if cue_type == "loop": - # Reading loops is fine; writing one is not. A cue row with an - # out-point does not land in the slot its Kind names — verified in - # Rekordbox — so it would silently become an uneditable memory cue. - raise Unsupported( - "Saved loops can be read but not yet written to Rekordbox libraries" - ) if cue_type not in caps.WRITABLE_CUE_TYPES: raise Unsupported(f"Rekordbox has no cue type {cue_type!r}") diff --git a/backend/konduktor/adapters/rekordbox/capabilities.py b/backend/konduktor/adapters/rekordbox/capabilities.py index decd073..e3cc73d 100644 --- a/backend/konduktor/adapters/rekordbox/capabilities.py +++ b/backend/konduktor/adapters/rekordbox/capabilities.py @@ -66,7 +66,7 @@ def capabilities_for( # projected and PRESERVED but not editable (two-platform rule). memory_cues=True, max_memory_cues=None, # unlimited - # Loops are READ but not written — see cue_types.WRITABLE_CUE_TYPES. + # Both cue types write; Rekordbox has no fade/load types. types=WRITABLE_CUE_TYPES, color="palette", palette=[], # TODO milestone 2: the built-in cue colour table diff --git a/backend/konduktor/adapters/rekordbox/cue_types.py b/backend/konduktor/adapters/rekordbox/cue_types.py index b992310..62c8387 100644 --- a/backend/konduktor/adapters/rekordbox/cue_types.py +++ b/backend/konduktor/adapters/rekordbox/cue_types.py @@ -5,7 +5,24 @@ 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 occupying bank slot ``Kind``. + * ``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 @@ -23,36 +40,42 @@ MEMORY_KIND = 0 # Rekordbox has no fade-in/fade-out/load cues; those are Traktor-only. CUE_TYPES = ["cue", "loop"] -# What Konduktor will WRITE, which is currently narrower than what it reads. -# -# A loop is projected and displayed correctly, but writing one is disabled: a -# cue row carrying `OutMsec` does NOT land in the hot cue slot its `Kind` names. -# Verified in Rekordbox 7 — a row written with `Kind=4` plus an out-point showed -# up as a MEMORY cue with pad D left empty, while an identical row without an -# out-point landed on pad B exactly as `Kind=2` predicts. Rekordbox's own 4-beat -# loop on pad F (the 6th pad) stores `Kind=7`, so loops evidently use a different -# slot encoding that has not been measured yet. -# -# Writing one anyway would silently create a MEMORY cue — which Konduktor -# deliberately cannot edit or delete — on a platform with no version history. -# Preserving a loop we cannot place is strictly better than misplacing it. -WRITABLE_CUE_TYPES = ["cue"] +# 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, slot) for a native ``Kind``.""" - if kind is None or kind == MEMORY_KIND: + """(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 - return "hotcue", int(kind) + 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, slot). Inverse of `role_and_slot`.""" + """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") - return int(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: diff --git a/backend/konduktor/adapters/rekordbox/projection.py b/backend/konduktor/adapters/rekordbox/projection.py index fac9533..c68d3d6 100644 --- a/backend/konduktor/adapters/rekordbox/projection.py +++ b/backend/konduktor/adapters/rekordbox/projection.py @@ -133,8 +133,13 @@ def to_track_cues(cue_rows: list, grid: tuple[list[float], list[float]] | None) into the generic marker list. Rekordbox pairs nothing with a grid marker, so `companion` is always None — that is a Traktor convention. - Every cue is projected as `editable=False` in this milestone, because the - adapter refuses every command; the UI gates on that flag alone. + `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: @@ -146,20 +151,22 @@ def to_track_cues(cue_rows: list, grid: tuple[list[float], list[float]] | None) 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=cue_type(out_msec), + type=kind, role=role, start=in_msec / 1000.0, length=length, slot=slot, color=_cue_color(c), - editable=False, - readonly_reason="platform_managed", + editable=editable, + readonly_reason=None if editable else "platform_managed", grid_marker=None, ) ) diff --git a/backend/konduktor/adapters/rekordbox/store.py b/backend/konduktor/adapters/rekordbox/store.py index 84b6b2b..e048108 100644 --- a/backend/konduktor/adapters/rekordbox/store.py +++ b/backend/konduktor/adapters/rekordbox/store.py @@ -33,12 +33,13 @@ from datetime import datetime from pathlib import Path from sqlalchemy import func, select, text +from sqlalchemy.exc import OperationalError from sqlalchemy.orm import joinedload from ...core.adapter import InvalidCommand, LibraryNotSupported, NotFound, SaveOutcome from ...core.edit_journal import EditJournal from ...core.pathmap import PathMapping -from .cue_types import beat_loop_size +from .cue_types import beat_loop_size, kind_for log = logging.getLogger(__name__) @@ -485,6 +486,16 @@ class RekordboxStore: rb_database.get_rekordbox_pid = lambda *a, **kw: 0 try: self._db.commit(autoinc=True) + except OperationalError as ex: + # Suppressing pyrekordbox's veto does not remove SQLite's own lock: + # a running Rekordbox really does hold the database, and the raw + # error is an unhelpful 500. Say what happened and what to do. + if "locked" not in str(ex).lower(): + raise + raise InvalidCommand( + "Rekordbox has the library open, so it cannot be written right " + "now. Close Rekordbox and save again — your changes are still here." + ) from ex finally: rb_database.get_rekordbox_pid = original @@ -519,12 +530,12 @@ class RekordboxStore: return int(msec * RekordboxStore._FPS / 1000) def _cue_row(self, track_id: str, slot: int): - """The hot cue occupying `slot` on this track, or None.""" + """The hot cue occupying the 0-based generic `slot`, or None.""" t = self._tables return ( self._db.session.query(t.DjmdCue) .filter(t.DjmdCue.ContentID == str(track_id)) - .filter(t.DjmdCue.Kind == int(slot)) + .filter(t.DjmdCue.Kind == kind_for("hotcue", slot)) .filter(t.DjmdCue.rb_local_deleted == 0) .first() ) @@ -565,13 +576,14 @@ class RekordboxStore: """Create or replace the cue in `slot`. A loop is a cue with a length.""" if start_sec < 0: raise InvalidCommand("A cue cannot be before the start of the track") - if int(slot) < 1: - raise InvalidCommand("Hot cue slots start at 1") + if int(slot) < 0: + raise InvalidCommand(f"Hot cue slot cannot be negative, got {slot}") row = self.content(track_id) in_ms = int(round(start_sec * 1000)) is_loop = cue_type == "loop" and length_sec > 0 out_ms = int(round((start_sec + length_sec) * 1000)) if is_loop else -1 + kind = kind_for("hotcue", slot) existing = self._cue_row(track_id, slot) op = "add" if existing is None else "modify" cue = existing @@ -584,7 +596,7 @@ class RekordboxStore: # the id of its contentCue mirror row. ContentUUID=str(row.UUID), UUID=str(uuid.uuid4()), - Kind=int(slot), + Kind=kind, rb_data_status=0, rb_local_data_status=0, rb_local_deleted=0, @@ -600,7 +612,7 @@ class RekordboxStore: cue.OutFrame = self._frames(out_ms) if is_loop else 0 cue.OutMpegFrame = 0 cue.OutMpegAbs = 0 - cue.Kind = int(slot) + cue.Kind = kind if is_loop: beats = self._loop_beats(track_id, start_sec, length_sec) cue.BeatLoopSize = beat_loop_size(beats) if beats else None diff --git a/backend/test_rekordbox_adapter.py b/backend/test_rekordbox_adapter.py index 512b1b2..9ab6b60 100644 --- a/backend/test_rekordbox_adapter.py +++ b/backend/test_rekordbox_adapter.py @@ -66,8 +66,24 @@ def check(label, cond, detail=""): # ---- pure units: no library required ----------------------------------- print("== cue encoding ==") check("Kind 0 is a memory cue with no slot", role_and_slot(0) == ("memory", None)) -check("Kind N is hot cue slot N", role_and_slot(5) == ("hotcue", 5)) -check("round-trips back to Kind", kind_for(*role_and_slot(5)) == 5 and kind_for("memory", None) == 0) +# The generic slot is 0-BASED (slot 0 is the pad the UI labels "A", matching how +# Traktor stores HOTCUE); Rekordbox's Kind is 1-based. Conflating them shifts +# every cue by one pad, which is exactly what shipped before it was caught. +check("Kind 1 is hot cue slot 0 — the pad labelled A", role_and_slot(1) == ("hotcue", 0)) +check("slot 0 maps to Kind 1, not Kind 0", kind_for("hotcue", 0) == 1) +# MEASURED, not assumed: a loop was written at every Kind 1-8 and read off a real +# deck. Kind 4 is reserved and lands on no pad, so the bank is 1,2,3,5,6,7,8,9. +# Getting this wrong moves cues to the wrong pad or loses them from the bank. +EXPECTED_KINDS = [1, 2, 3, 5, 6, 7, 8, 9] # pads A..H +check("the bank skips the reserved Kind", + [kind_for("hotcue", i) for i in range(8)] == EXPECTED_KINDS, + str([kind_for("hotcue", i) for i in range(8)])) +check("and every one maps back to its own slot", + [role_and_slot(k)[1] for k in EXPECTED_KINDS] == list(range(8))) +check("the reserved Kind is no pad at all — Rekordbox shows it as a memory cue", + role_and_slot(4) == ("memory", None)) +check("pad D is Kind 5, not Kind 4", kind_for("hotcue", 3) == 5) +check("pad H is Kind 9", kind_for("hotcue", 7) == 9) # Verified against two real loops: 1 beat @125 BPM and 4 beats @120 BPM. check("BeatLoopSize encodes (beats << 16) | 1", beat_loop_size(4) == 262145 and beat_loop_size(1) == 65537) check("and decodes back", beats_in_loop(262145) == 4 and beats_in_loop(None) is None) @@ -157,8 +173,19 @@ with tempfile.TemporaryDirectory() as d: check("a memory cue has no slot", all(c.slot is None for c in tc.cues if c.role == "memory")) check("a hot cue has a slot", all(c.slot is not None for c in tc.cues if c.role == "hotcue")) - check("no cue claims to be editable in the read-only milestone", - all(not c.editable for c in tc.cues)) + # `editable` must track what the adapter will ACTUALLY accept — it is + # the only thing the UI gates on, and a stale `False` here showed every + # writable hot cue with a padlock. + check("ordinary hot cues are editable", + all(c.editable for c in tc.cues if c.role == "hotcue" and c.type != "loop")) + check("memory cues are preserved but not editable", + all(not c.editable for c in tc.cues if c.role == "memory")) + check("loops are editable like any other hot cue", + all(c.editable for c in tc.cues if c.type == "loop" and c.role == "hotcue")) + check("an uneditable cue always says why", + all(c.readonly_reason for c in tc.cues if not c.editable)) + check("an editable cue gives no reason", + all(c.readonly_reason is None for c in tc.cues if c.editable)) check("grid markers carry no companion (a Traktor convention)", all(m.companion is None for m in tc.grid_markers)) loops = [c for c in tc.cues if c.type == "loop"] @@ -224,10 +251,8 @@ with tempfile.TemporaryDirectory() as d: check("8 hot cue slots, labelled by letter", caps.cues.hotcue_slots == 8 and caps.cues.slot_labels == "letter") check("memory cues are supported", caps.cues.memory_cues) - # Loops are READ but not WRITTEN — a cue row with an out-point does not land - # in the slot its Kind names (verified in Rekordbox), so offering it would - # silently create an uneditable memory cue. - check("only writable cue types are advertised", caps.cues.types == ["cue"], + # Rekordbox has no fade-in/fade-out/load cues; those are Traktor-only. + check("both Rekordbox cue types are writable", caps.cues.types == ["cue", "loop"], str(caps.cues.types)) # A loop is a cue with an out-point, NOT a separate bank — verified on a real # library, and the opposite of what the original plan assumed. @@ -310,20 +335,20 @@ with tempfile.TemporaryDirectory() as d: check("the cue is where it was put", abs(placed[0].start - 30.0) < 0.001) check("it is a hot cue with a slot", placed[0].role == "hotcue" and placed[0].slot == 6) check("its name round-trips", placed[0].name == "Probe", str(placed[0].name)) - check("writing a loop is refused until its slot encoding is known", - _raises(lambda: adapter.set_cue(cue_track.id, slot=7, start_sec=60.0, - cue_type="loop", length_sec=1.92), Unsupported)) - # Reading one must still work: Rekordbox libraries contain loops and losing - # them from the projection would be worse than not being able to edit them. - looped = [ - c - for t in adapter.tracks[:40] - for c in (adapter.track_cues(t.id) or TrackCues()).cues - if c.type == "loop" - ] - if looped: - check("existing loops are still projected, with their length", - all(c.length > 0 for c in looped), str([c.length for c in looped])) + # A loop is a cue with an out-point, not a separate bank object. + tc = adapter.set_cue(cue_track.id, slot=7, start_sec=60.0, cue_type="loop", length_sec=1.92) + loop = [c for c in tc.cues if c.slot == 7] + check("a loop can be written to the last pad", len(loop) == 1 and loop[0].type == "loop", + str([(c.slot, c.type) for c in tc.cues])) + if loop: + check("the loop keeps its length", abs(loop[0].length - 1.92) < 0.002, str(loop[0].length)) + check("and is editable like any other hot cue", loop[0].editable) + # Every pad must be reachable — the reserved-Kind gap used to swallow pad D + # and shift everything above it. + for slot in range(8): + adapter.set_cue(cue_track.id, slot=slot, start_sec=5.0 + slot, cue_type="cue") + placed = {c.slot for c in adapter.track_cues(cue_track.id).cues if c.slot is not None} + check("all eight pads are individually addressable", placed == set(range(8)), str(sorted(placed))) # Replacing an occupied slot must not leave two cues in it. tc = adapter.set_cue(cue_track.id, slot=6, start_sec=45.0, cue_type="cue") in_six = [c for c in tc.cues if c.slot == 6] @@ -342,8 +367,14 @@ with tempfile.TemporaryDirectory() as d: check("memory cues are shown but not writable", _raises(lambda: adapter.set_cue(cue_track.id, slot=1, start_sec=1.0, cue_type="cue", role="memory"), Unsupported)) - check("slot 0 is rejected — it is the memory-cue encoding, not a bank slot", - _raises(lambda: adapter.set_cue(cue_track.id, slot=0, start_sec=1.0, + # Slot 0 is the FIRST pad, not an error: it is Kind=1 natively. + tc = adapter.set_cue(cue_track.id, slot=0, start_sec=1.0, cue_type="cue") + first = [c for c in tc.cues if c.slot == 0] + check("slot 0 is the first pad (A), not an error", len(first) == 1, str(len(first))) + tc = adapter.set_cue(cue_track.id, slot=7, start_sec=2.0, cue_type="cue") + check("slot 7 is the last pad (H)", any(c.slot == 7 for c in tc.cues)) + check("a negative slot is rejected", + _raises(lambda: adapter.set_cue(cue_track.id, slot=-1, start_sec=1.0, cue_type="cue"), InvalidCommand)) check("a negative position is rejected", _raises(lambda: adapter.set_cue(cue_track.id, slot=2, start_sec=-1.0, diff --git a/backend/test_rekordbox_fidelity.py b/backend/test_rekordbox_fidelity.py index 40539ff..69754e0 100644 --- a/backend/test_rekordbox_fidelity.py +++ b/backend/test_rekordbox_fidelity.py @@ -240,10 +240,20 @@ with tempfile.TemporaryDirectory() as d: # ---- F: a cue write touches the cue row AND its mirror --------------- print("== F: a hot cue write is localized, and keeps the mirror in step ==") clean_copy(REAL, work, closing=[adapter, again, final, reopened]) - before = dump(work) adapter = RekordboxAdapter(work) cue_track = next((t for t in adapter.tracks if t.bpm), adapter.tracks[0]) - adapter.set_cue(cue_track.id, slot=6, start_sec=30.0, cue_type="cue", name="Probe") + # Empty the bank FIRST so "one row inserted" is a fact about this edit, not + # about whatever the reference library happened to hold. Reading the existing + # cues instead made this assertion flip to UPDATE the moment the real library + # gained a cue in the same slot. + for existing in list(adapter.track_cues(cue_track.id).cues): + if existing.slot is not None: + adapter.delete_cue(cue_track.id, existing.slot) + adapter.save() + before = dump(work) + # Generic slot 5 is the pad labelled F, stored natively as Kind=7 — the bank + # skips the reserved Kind 4, so pads from D up are shifted by two. + adapter.set_cue(cue_track.id, slot=5, start_sec=30.0, cue_type="cue", name="Probe") adapter.save() changes = diff(before, dump(work)) tables_touched = {t for t, _, _, _ in changes} @@ -257,7 +267,8 @@ with tempfile.TemporaryDirectory() as d: len(cue_rows) == 1 and cue_rows[0][2] == "INSERT", describe(cue_rows)) if cue_rows and cue_rows[0][2] == "INSERT": row = cue_rows[0][3] - check("it is a hot cue in the slot asked for", row["Kind"] == 6, str(row["Kind"])) + check("the 0-based slot is stored as its measured Kind", + row["Kind"] == 7, str(row["Kind"])) check("positions are stored in ms AND frames at 150fps", row["InMsec"] == 30000 and row["InFrame"] == 4500, f"{row['InMsec']}/{row['InFrame']}") @@ -292,16 +303,16 @@ with tempfile.TemporaryDirectory() as d: f"{mirror_row['rb_cue_count']} vs {len(live)}") check("the mirror's id is the track's UUID", mirror_row["ID"] == after["djmdContent"][cue_track.id]["UUID"]) - check("the new cue is in the mirror", any(r["Kind"] == 6 for r in records)) + check("the new cue is in the mirror", any(r["Kind"] == 7 for r in records)) # ---- G: deleting a cue removes it from both places ------------------- print("== G: deleting a cue clears the row and the mirror ==") - adapter.delete_cue(cue_track.id, 6) + adapter.delete_cue(cue_track.id, 5) adapter.save() after = dump(work) live = [ r for r in after["djmdCue"].values() - if r["ContentID"] == cue_track.id and r["Kind"] == 6 and not r["rb_local_deleted"] + if r["ContentID"] == cue_track.id and r["Kind"] == 7 and not r["rb_local_deleted"] ] check("the cue row is gone", not live, str(len(live))) mirror_row = next( @@ -311,7 +322,7 @@ with tempfile.TemporaryDirectory() as d: import json as _json records = _json.loads(mirror_row["Cues"]) - check("and gone from the mirror too", not any(r["Kind"] == 6 for r in records)) + check("and gone from the mirror too", not any(r["Kind"] == 7 for r in records)) check("with rb_cue_count updated", mirror_row["rb_cue_count"] == len(records), f"{mirror_row['rb_cue_count']} vs {len(records)}") diff --git a/dev-sandbox.sh b/dev-sandbox.sh new file mode 100755 index 0000000..a03e633 --- /dev/null +++ b/dev-sandbox.sh @@ -0,0 +1,140 @@ +#!/usr/bin/env bash +# Start Konduktor for hands-on testing, protecting what actually needs it. +# +# Clicking around the real app means clicking real Save buttons, so the TRAKTOR +# collection is copied into a throwaway sandbox — it is 8,485 entries of real, +# irreplaceable library. The REKORDBOX library is opened live, because it is a +# disposable test library kept for exactly this. +# +# Prefs and version history always go to a temp directory, so testing never +# disturbs the real ones. Ctrl-C stops both servers. +# +# Override either source with KONDUKTOR_TRAKTOR_SRC / KONDUKTOR_REKORDBOX_SRC, +# or set KONDUKTOR_COPY_REKORDBOX=1 to sandbox Rekordbox too. +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +# Refuse to start if something is already SERVING on the ports. +# +# This is load-bearing, not a nicety: if :8000 is taken, this script's backend +# dies quietly and the browser talks to whatever was already there — quite +# possibly a server holding the real Traktor collection. The window would still +# claim to be a sandbox while every Save went somewhere else entirely. +# +# `-sTCP:LISTEN` matters: a plain `lsof -ti:PORT` also matches CLIENT sockets, so +# a browser tab left open on the old app looks exactly like a running server and +# blocks startup for no reason. +for port_and_what in "8000:backend" "5173:frontend"; do + port="${port_and_what%%:*}" + what="${port_and_what##*:}" + if lsof -ti:"$port" -sTCP:LISTEN >/dev/null 2>&1; then + cat >&2 </dev/null || true' EXIT INT TERM + +cat <(caps.tracks.editable_fields) + const fields = TEXT_FIELDS.filter((f) => editable.has(f.key as string)) + const canRate = editable.has('rating') const qc = useQueryClient() const { data: facets } = useQuery({ queryKey: ['facets'], queryFn: api.facets }) @@ -45,11 +52,11 @@ export function EditTagsDialog({ track, onClose, onApplied, onError }: Props) { const changedFields = () => { const changed: Record = {} - for (const { key } of TEXT_FIELDS) { + for (const { key } of fields) { const orig = (track[key] as string | null) ?? '' if (form[key] !== orig) changed[key] = form[key] } - if (rating !== track.rating) changed.rating = rating + if (canRate && rating !== track.rating) changed.rating = rating return changed } @@ -125,26 +132,38 @@ export function EditTagsDialog({ track, onClose, onApplied, onError }: Props) { Album art - pickArt(e.target.files?.[0] ?? null)} - /> - - {artFile && ( -
{artFile.name} (applies on Save)
+ {/* Replacing art is only offered where the adapter can write it; + the existing image is still shown either way. */} + {caps.tracks.artwork ? ( + <> + pickArt(e.target.files?.[0] ?? null)} + /> + + {artFile && ( +
+ {artFile.name} (applies on Save) +
+ )} + + ) : ( +
+ Cover art can’t be changed on {caps.save.app_name} libraries. +
)}
- {TEXT_FIELDS.map(({ key, label, textarea }) => ( + {fields.map(({ key, label, textarea }) => (