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'} + > + ⊞ + + )} ) },