diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index 3d44d9e..07b51c5 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -30,6 +30,8 @@ from .schemas import ( RenamePlaylist, SaveResult, SetEntries, + SetHotcue, + SetHotcueType, Stats, Track, TrackCues, @@ -330,12 +332,7 @@ def track_audio(track_id: str) -> FileResponse: return FileResponse(path, media_type=mime) -@app.get("/api/tracks/cues", response_model=TrackCues) -def track_cues(track_id: str) -> TrackCues: - """Beatgrid + cue/loop markers for a track (read-only, from the NML).""" - entry = require_store().model_entry(track_id) - if entry is None: - raise HTTPException(404, "Track not found") +def _build_track_cues(entry) -> TrackCues: grid_anchor: float | None = None grid_bpm: float | None = None cues: list[CuePoint] = [] @@ -361,6 +358,58 @@ def track_cues(track_id: str) -> TrackCues: return TrackCues(bpm=bpm, grid_anchor=grid_anchor, cues=cues) +def _cues_for(track_id: str) -> TrackCues: + entry = require_store().model_entry(track_id) + if entry is None: + raise HTTPException(404, "Track not found") + return _build_track_cues(entry) + + +@app.get("/api/tracks/cues", response_model=TrackCues) +def track_cues(track_id: str) -> TrackCues: + """Beatgrid + cue/loop markers for a track (read-only, from the NML).""" + return _cues_for(track_id) + + +def _sync_cue_edit(track_id: str) -> TrackCues: + """After a hotcue edit, refresh the read projection and return fresh cues.""" + store = require_store() + entry = store.model_entry(track_id) + if entry is not None: + require_service().replace_track(track_id, entry) + return _build_track_cues(entry) if entry is not None else TrackCues() + + +@app.post("/api/tracks/hotcue", response_model=TrackCues) +def create_hotcue(body: SetHotcue) -> TrackCues: + """Create (or reposition + retype) the hotcue in a slot at a position.""" + try: + require_store().set_hotcue(body.track_id, body.slot, body.start, body.type) + except PlaylistError as ex: + raise HTTPException(400, str(ex)) + return _sync_cue_edit(body.track_id) + + +@app.patch("/api/tracks/hotcue", response_model=TrackCues) +def edit_hotcue_type(body: SetHotcueType) -> TrackCues: + """Change the type of an existing hotcue (keeps its position).""" + try: + require_store().set_hotcue_type(body.track_id, body.slot, body.type) + except PlaylistError as ex: + raise HTTPException(400, str(ex)) + return _sync_cue_edit(body.track_id) + + +@app.delete("/api/tracks/hotcue", response_model=TrackCues) +def delete_hotcue(track_id: str, slot: int) -> TrackCues: + """Remove the hotcue in a slot.""" + try: + require_store().delete_hotcue(track_id, slot) + except PlaylistError as ex: + raise HTTPException(400, str(ex)) + return _sync_cue_edit(track_id) + + @app.put("/api/tracks/art") async def set_track_art(track_id: str = Form(...), file: UploadFile = File(...)) -> dict: """Stage replacement cover art for a track (written to the file on save).""" diff --git a/backend/konduktor/playlist_store.py b/backend/konduktor/playlist_store.py index 7d803a3..855860c 100644 --- a/backend/konduktor/playlist_store.py +++ b/backend/konduktor/playlist_store.py @@ -31,6 +31,7 @@ from traktor_nml_utils import ( ) from traktor_nml_utils.models.collection import ( Albumtype, + CueV2Type, Entrytype, Infotype, Nodetype, @@ -265,6 +266,69 @@ class PlaylistStore: with self._lock: return self._entry_by_key.get(track_id) + # ---- hotcues (beatgrid-independent point markers) ----------------- + # Only self-contained point types are editable here: 0 cue, 1 fade-in, + # 2 fade-out, 3 load. Loops (need a length) and grid markers (redefine the + # beatgrid) are deliberately excluded. Cues are NML-only (not synced to files). + POINT_CUE_TYPES = {0, 1, 2, 3} + + def _entry_or_raise(self, track_id: str) -> Entrytype: + entry = self._entry_by_key.get(track_id) + if entry is None: + raise PlaylistError(f"Track not found: {track_id}") + return entry + + def set_hotcue(self, track_id: str, slot: int, start_sec: float, cue_type: int) -> None: + """Create (or reposition + retype) the hotcue in `slot` at `start_sec`.""" + if not 0 <= slot <= 7: + raise PlaylistError(f"Invalid hotcue slot: {slot}") + if cue_type not in self.POINT_CUE_TYPES: + raise PlaylistError(f"Unsupported cue type: {cue_type}") + with self._lock: + entry = self._entry_or_raise(track_id) + start_ms = max(0.0, start_sec * 1000.0) # Traktor stores START in ms + existing = next( + (c for c in (entry.cue_v2 or []) if c.hotcue == slot), None + ) + if existing is not None: + existing.start = start_ms + existing.type = cue_type + else: + if entry.cue_v2 is None: + entry.cue_v2 = [] + entry.cue_v2.append( + CueV2Type( + name="n.n.", # Traktor's default name for a manual cue + displ_order=0, + type=cue_type, + start=start_ms, + len=0.0, + repeats=-1, + hotcue=slot, + color=None, + grid=None, + ) + ) + self.dirty = True + + def set_hotcue_type(self, track_id: str, slot: int, cue_type: int) -> None: + """Change the type of the existing hotcue in `slot` (keeps its position).""" + if cue_type not in self.POINT_CUE_TYPES: + raise PlaylistError(f"Unsupported cue type: {cue_type}") + with self._lock: + entry = self._entry_or_raise(track_id) + cue = next((c for c in (entry.cue_v2 or []) if c.hotcue == slot), None) + if cue is None: + raise PlaylistError(f"Hotcue {slot} is not set") + cue.type = cue_type + self.dirty = True + + def delete_hotcue(self, track_id: str, slot: int) -> None: + with self._lock: + entry = self._entry_or_raise(track_id) + entry.cue_v2 = [c for c in (entry.cue_v2 or []) if c.hotcue != slot] + self.dirty = True + # ---- cover art ----------------------------------------------------- def set_track_art(self, track_id: str, data: bytes, mime: str) -> None: with self._lock: diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index b6eb652..fc1ba41 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -133,6 +133,19 @@ class TrackCues(BaseModel): cues: list[CuePoint] = [] # cue/loop markers (grid markers excluded) +class SetHotcue(BaseModel): + track_id: str + slot: int # 0–7 + start: float # seconds + type: int # 0 cue, 1 fade-in, 2 fade-out, 3 load + + +class SetHotcueType(BaseModel): + track_id: str + slot: int + type: int + + class EditState(BaseModel): dirty: bool # unsaved in-memory playlist changes exist nml_path: str diff --git a/backend/test_save_fidelity.py b/backend/test_save_fidelity.py index c0c1995..f475d39 100644 --- a/backend/test_save_fidelity.py +++ b/backend/test_save_fidelity.py @@ -175,5 +175,56 @@ with tempfile.TemporaryDirectory() as d: check("re-parses + genre persisted", e0.info.genre == "KONDUKTOR-FIDELITY-TEST") check("rating persisted (4 stars => RANKING 204)", e0.info.ranking == 204) +# ---- Invariant D: a hotcue edit is fully localized --------------------- +print("== D. hotcue create touches only that track's ENTRY ==") +with tempfile.TemporaryDirectory() as d: + work = Path(d) / "collection.nml" + shutil.copy2(REAL, work) + original = work.read_bytes() + + store = PlaylistStore(work) + entry = store._nml.collection.entry[0] + loc = entry.location + track_id = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}" + + # Use a free slot so we exercise the create path (not overwrite an existing). + used = {c.hotcue for c in (entry.cue_v2 or []) if c.hotcue is not None} + slot = next(s for s in range(8) if s not in used) + store.set_hotcue(track_id, slot, 42.5, 0) + store.save() + edited = work.read_bytes() + + check("file actually changed", original != edited) + + def entry_span(data: bytes, file_name: str): + marker = f'FILE="{file_name}"'.encode() + i = data.find(marker) + start = data.rfind(b"", i) + len(b"") + return start, end + + os_, oe = entry_span(original, loc.file) + es_, ee = entry_span(edited, loc.file) + check( + "everything outside the edited track's ENTRY is byte-identical", + original[:os_] + b"@@" + original[oe:] == edited[:es_] + b"@@" + edited[ee:], + ) + n = diff_count(original[os_:oe], edited[es_:ee]) + check("edited ENTRY diff is tiny (<= 3 tag-lines)", n <= 3, f"got {n}") + + from traktor_nml_utils import TraktorCollection + + reparsed = TraktorCollection(path=work) + e0 = reparsed.nml.collection.entry[0] + new_cue = next((c for c in (e0.cue_v2 or []) if c.hotcue == slot), None) + check("re-parses + hotcue persisted", new_cue is not None) + check("hotcue START stored in ms", new_cue is not None and abs(new_cue.start - 42500.0) < 1) + + # Create then delete must round-trip back to a byte-identical file. + store2 = PlaylistStore(work) # reload the edited file + store2.delete_hotcue(track_id, slot) + store2.save() + check("create+delete round-trips to the original bytes", work.read_bytes() == original) + print("\nRESULT:", "FAILED" if failed else "ALL PASSED") sys.exit(1 if failed else 0) diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 1463bc8..6844715 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -218,6 +218,15 @@ export const api = { audioUrl: (trackId: string) => `/api/tracks/audio?track_id=${encodeURIComponent(trackId)}`, trackCues: (trackId: string) => getJSON(`/api/tracks/cues?track_id=${encodeURIComponent(trackId)}`), + createHotcue: (trackId: string, slot: number, start: number, type: number) => + send('POST', '/api/tracks/hotcue', { track_id: trackId, slot, start, type }), + setHotcueType: (trackId: string, slot: number, type: number) => + send('PATCH', '/api/tracks/hotcue', { track_id: trackId, slot, type }), + deleteHotcue: (trackId: string, slot: number) => + send( + 'DELETE', + `/api/tracks/hotcue?track_id=${encodeURIComponent(trackId)}&slot=${slot}`, + ), uploadArt: async (trackId: string, file: File) => { const fd = new FormData() fd.append('track_id', trackId) diff --git a/frontend/src/components/HotcueBar.tsx b/frontend/src/components/HotcueBar.tsx new file mode 100644 index 0000000..00a49f0 --- /dev/null +++ b/frontend/src/components/HotcueBar.tsx @@ -0,0 +1,48 @@ +import type { CuePoint } from '../api' +import { contrastText, cueColor } from '../lib/cues' + +interface Props { + cues: CuePoint[] + selectedSlot: number | null + onSlotClick: (slot: number) => void +} + +const SLOTS = [0, 1, 2, 3, 4, 5, 6, 7] // Traktor hotcue slots → labelled 1–8 + +/** + * Traktor-style hotcue bar: all 8 hotcue slots, colour-coded by cue type when + * assigned (gray when empty). Clicking a slot selects it — the parent decides + * whether that creates a cue (empty slot) or jumps to it (assigned slot). + */ +export function HotcueBar({ cues, selectedSlot, onSlotClick }: Props) { + return ( +
+ {SLOTS.map((slot) => { + const cue = cues.find((c) => c.hotcue === slot) ?? null + const selected = selectedSlot === slot + const color = cue ? cueColor(cue) : null + return ( + + ) + })} +
+ ) +} diff --git a/frontend/src/components/LoopControls.tsx b/frontend/src/components/LoopControls.tsx new file mode 100644 index 0000000..9a7db63 --- /dev/null +++ b/frontend/src/components/LoopControls.tsx @@ -0,0 +1,118 @@ +import { useState } from 'react' + +interface Props { + bpm: number | null // beat-loops need a grid; 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 + snap: boolean + onToggleSnap: () => void + onSetLoop: (beats: number) => void + onLoopIn: () => void + onLoopOut: () => void + onToggleActive: () => void +} + +// Fixed beat-loop sizes, 1/32 → 32 beats. +const SIZES = [1 / 32, 1 / 16, 1 / 8, 1 / 4, 1 / 2, 1, 2, 4, 8, 16, 32] +const WINDOW = 6 // sizes shown at once (Traktor-style), shifted with the arrows +const DEFAULT_START = 3 // start on 1/4 … 8 + +function label(size: number): string { + return size < 1 ? `1/${Math.round(1 / size)}` : String(size) +} + +export function LoopControls({ + bpm, + active, + activeBeats, + canToggle, + snap, + onToggleSnap, + onSetLoop, + onLoopIn, + onLoopOut, + onToggleActive, +}: Props) { + const [start, setStart] = useState(DEFAULT_START) + const maxStart = SIZES.length - WINDOW + const visible = SIZES.slice(start, start + WINDOW) + const hasGrid = !!bpm && bpm > 0 + + const btn = + 'flex h-6 min-w-8 items-center justify-center rounded px-1.5 text-xs font-semibold ' + + 'border border-line text-muted hover:text-text disabled:opacity-30' + + return ( +
+ + + + {visible.map((size) => { + const isActive = active && activeBeats === size + return ( + + ) + })} + + +
+ + + + +
+ ) +} diff --git a/frontend/src/components/MainWaveform.tsx b/frontend/src/components/MainWaveform.tsx index c4e3506..db2a5a8 100644 --- a/frontend/src/components/MainWaveform.tsx +++ b/frontend/src/components/MainWaveform.tsx @@ -1,6 +1,6 @@ import { useEffect, useRef, useState } from 'react' import type { CuePoint } from '../api' -import { drawBeatgrid, drawCues } from '../lib/cues' +import { drawBeatgrid, drawCues, drawLoop } from '../lib/cues' import { paintWave, type WaveColumn } from '../lib/waveform' interface Props { @@ -10,6 +10,7 @@ interface Props { cues: CuePoint[] bpm: number | null gridAnchor: number | null + loop: { start: number; end: number } | null onSeek: (t: number) => void onScratchStart: () => void onScratchMove: (t: number) => void @@ -35,6 +36,7 @@ export function MainWaveform({ cues, bpm, gridAnchor, + loop, onSeek, onScratchStart, onScratchMove, @@ -70,12 +72,15 @@ export function MainWaveform({ const endSec = currentTime + half paintWave(ctx, cols, w, h, startSec / duration, endSec / duration) - // Beatgrid, then cue markers (extrapolated across the visible window). + const timeToX = (t: number) => ((t - startSec) / secPerView) * w + // Loop band (under the grid/cues), then beatgrid, then cue markers. + 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 (cues.length) { - const timeToX = (t: number) => ((t - startSec) / secPerView) * w drawCues(ctx, cues, w, h, dpr, timeToX, true) } } diff --git a/frontend/src/components/OverviewWaveform.tsx b/frontend/src/components/OverviewWaveform.tsx index bb60d3b..2ecb206 100644 --- a/frontend/src/components/OverviewWaveform.tsx +++ b/frontend/src/components/OverviewWaveform.tsx @@ -1,6 +1,6 @@ import { useCallback, useEffect, useRef } from 'react' import type { CuePoint } from '../api' -import { drawCues } from '../lib/cues' +import { drawCues, drawLoop } from '../lib/cues' import { paintWave, type WaveColumn } from '../lib/waveform' interface Props { @@ -8,6 +8,7 @@ interface Props { currentTime: number duration: number cues: CuePoint[] + loop: { start: number; end: number } | null onSeek: (t: number) => void } @@ -16,13 +17,14 @@ interface Props { * offscreen canvas) with a moving playhead + dimmed played region. Click to * seek anywhere in the track. */ -export function OverviewWaveform({ cols, currentTime, duration, cues, onSeek }: Props) { +export function OverviewWaveform({ cols, currentTime, duration, cues, loop, onSeek }: Props) { const wrapRef = useRef(null) const canvasRef = useRef(null) const cacheRef = useRef(null) const timeRef = useRef(0) const durRef = useRef(0) const cuesRef = useRef(cues) + const loopRef = useRef(loop) const renderCache = useCallback(() => { const canvas = canvasRef.current @@ -53,8 +55,10 @@ export function OverviewWaveform({ cols, currentTime, duration, cues, onSeek }: const px = Math.round((timeRef.current / dur) * w) ctx.fillStyle = 'rgba(10,11,15,0.55)' ctx.fillRect(0, 0, px, h) - // Cue markers (no beatgrid/labels in the overview). const dpr = window.devicePixelRatio || 1 + const lp = loopRef.current + if (lp) drawLoop(ctx, (lp.start / dur) * w, (lp.end / dur) * w, h, dpr) + // Cue markers (no beatgrid/labels in the overview). drawCues(ctx, cuesRef.current, w, h, dpr, (t) => (t / dur) * w, false) const pw = Math.max(2, Math.round(2 * dpr)) ctx.fillStyle = '#e6e9ef' @@ -93,11 +97,12 @@ export function OverviewWaveform({ cols, currentTime, duration, cues, onSeek }: draw() }, [currentTime, duration, draw]) - // Redraw when the cue set changes (new track). + // Redraw when the cue set or loop changes. useEffect(() => { cuesRef.current = cues + loopRef.current = loop draw() - }, [cues, draw]) + }, [cues, loop, draw]) const seek = (e: React.MouseEvent) => { if (!duration) return diff --git a/frontend/src/components/PrepStrip.tsx b/frontend/src/components/PrepStrip.tsx index 007ae88..2c5a4b3 100644 --- a/frontend/src/components/PrepStrip.tsx +++ b/frontend/src/components/PrepStrip.tsx @@ -1,7 +1,11 @@ import { useEffect, useRef, useState } from 'react' +import { useQueryClient } from '@tanstack/react-query' import { api, type Track, type TrackCues } from '../api' import { analyzeWaveform, type WaveColumn } from '../lib/waveform' import { ScratchEngine } from '../lib/scratchEngine' +import { PlaybackEngine } from '../lib/playbackEngine' +import { HotcueBar } from './HotcueBar' +import { LoopControls } from './LoopControls' import { MainWaveform } from './MainWaveform' import { OverviewWaveform } from './OverviewWaveform' @@ -18,45 +22,74 @@ function fmt(secs: number): string { return `${m}:${s.toString().padStart(2, '0')}` } +const CUE_TYPES: { value: number; label: string }[] = [ + { value: 0, label: 'Cue' }, + { value: 1, label: 'Fade-In' }, + { value: 2, label: 'Fade-Out' }, + { value: 3, label: 'Load' }, +] + /** * The DJ-style "prep strip" across the top of the window: transport controls on * the left, waveforms on the right (a scrolling zoomable main view above a - * whole-track overview). Playback is driven by a single hidden