diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index 07aba05..3d44d9e 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -18,6 +18,7 @@ from .playlist_store import PlaylistError, PlaylistStore from .schemas import ( CollectionStatus, CreatePlaylist, + CuePoint, EditState, EditTrack, Facets, @@ -31,6 +32,7 @@ from .schemas import ( SetEntries, Stats, Track, + TrackCues, TrackPage, ) @@ -328,6 +330,37 @@ 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") + 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, + ) + ) + bpm = grid_bpm if grid_bpm is not None else (entry.tempo.bpm if entry.tempo else None) + return TrackCues(bpm=bpm, grid_anchor=grid_anchor, cues=cues) + + @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/schemas.py b/backend/konduktor/schemas.py index b9f8a45..b6eb652 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -118,6 +118,21 @@ class SaveResult(BaseModel): file_tags: list[FileTagOutcome] = [] +class CuePoint(BaseModel): + name: str | None = None + type: int # Traktor: 0 cue, 1 fade-in, 2 fade-out, 3 load, 4 grid, 5 loop + start: float # seconds + length: float # seconds (>0 for loops) + hotcue: int # -1 if not assigned to a hotcue slot + color: str | None = None # "#RRGGBB" if set + + +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) + cues: list[CuePoint] = [] # cue/loop markers (grid markers excluded) + + class EditState(BaseModel): dirty: bool # unsaved in-memory playlist changes exist nml_path: str diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 88338e6..1463bc8 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -97,6 +97,21 @@ export interface TrackQuery { offset?: number } +export interface CuePoint { + name: string | null + type: number // 0 cue, 1 fade-in, 2 fade-out, 3 load, 4 grid, 5 loop + start: number // seconds + length: number // seconds (>0 for loops) + hotcue: number // -1 if not a hotcue + color: string | null // "#RRGGBB" +} + +export interface TrackCues { + bpm: number | null + grid_anchor: number | null // seconds + cues: CuePoint[] +} + export interface EditState { dirty: boolean nml_path: string @@ -201,6 +216,8 @@ export const api = { send<{ status: string }>('PATCH', '/api/tracks', { track_id: trackId, fields }), artUrl: (trackId: string) => `/api/tracks/art?track_id=${encodeURIComponent(trackId)}`, audioUrl: (trackId: string) => `/api/tracks/audio?track_id=${encodeURIComponent(trackId)}`, + trackCues: (trackId: string) => + getJSON(`/api/tracks/cues?track_id=${encodeURIComponent(trackId)}`), uploadArt: async (trackId: string, file: File) => { const fd = new FormData() fd.append('track_id', trackId) diff --git a/frontend/src/components/MainWaveform.tsx b/frontend/src/components/MainWaveform.tsx index 93d1b99..c4e3506 100644 --- a/frontend/src/components/MainWaveform.tsx +++ b/frontend/src/components/MainWaveform.tsx @@ -1,10 +1,15 @@ import { useEffect, useRef, useState } from 'react' +import type { CuePoint } from '../api' +import { drawBeatgrid, drawCues } from '../lib/cues' import { paintWave, type WaveColumn } from '../lib/waveform' interface Props { cols: WaveColumn[] currentTime: number duration: number + cues: CuePoint[] + bpm: number | null + gridAnchor: number | null onSeek: (t: number) => void onScratchStart: () => void onScratchMove: (t: number) => void @@ -27,6 +32,9 @@ export function MainWaveform({ cols, currentTime, duration, + cues, + bpm, + gridAnchor, onSeek, onScratchStart, onScratchMove, @@ -58,9 +66,18 @@ export function MainWaveform({ if (cols.length && duration > 0) { const half = secPerView / 2 - const startFrac = (currentTime - half) / duration - const endFrac = (currentTime + half) / duration - paintWave(ctx, cols, w, h, startFrac, endFrac) + const startSec = currentTime - half + const endSec = currentTime + half + paintWave(ctx, cols, w, h, startSec / duration, endSec / duration) + + // Beatgrid, then cue markers (extrapolated across the visible window). + 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) + } } // Fixed centre playhead. diff --git a/frontend/src/components/OverviewWaveform.tsx b/frontend/src/components/OverviewWaveform.tsx index 06583eb..bb60d3b 100644 --- a/frontend/src/components/OverviewWaveform.tsx +++ b/frontend/src/components/OverviewWaveform.tsx @@ -1,10 +1,13 @@ import { useCallback, useEffect, useRef } from 'react' +import type { CuePoint } from '../api' +import { drawCues } from '../lib/cues' import { paintWave, type WaveColumn } from '../lib/waveform' interface Props { cols: WaveColumn[] currentTime: number duration: number + cues: CuePoint[] onSeek: (t: number) => void } @@ -13,12 +16,13 @@ interface Props { * offscreen canvas) with a moving playhead + dimmed played region. Click to * seek anywhere in the track. */ -export function OverviewWaveform({ cols, currentTime, duration, onSeek }: Props) { +export function OverviewWaveform({ cols, currentTime, duration, cues, 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 renderCache = useCallback(() => { const canvas = canvasRef.current @@ -49,7 +53,10 @@ export function OverviewWaveform({ cols, currentTime, duration, onSeek }: Props) const px = Math.round((timeRef.current / dur) * w) ctx.fillStyle = 'rgba(10,11,15,0.55)' ctx.fillRect(0, 0, px, h) - const pw = Math.max(2, Math.round(2 * (window.devicePixelRatio || 1))) + // Cue markers (no beatgrid/labels in the overview). + const dpr = window.devicePixelRatio || 1 + drawCues(ctx, cuesRef.current, w, h, dpr, (t) => (t / dur) * w, false) + const pw = Math.max(2, Math.round(2 * dpr)) ctx.fillStyle = '#e6e9ef' ctx.fillRect(px - Math.floor(pw / 2), 0, pw, h) } @@ -86,6 +93,12 @@ export function OverviewWaveform({ cols, currentTime, duration, onSeek }: Props) draw() }, [currentTime, duration, draw]) + // Redraw when the cue set changes (new track). + useEffect(() => { + cuesRef.current = cues + draw() + }, [cues, draw]) + const seek = (e: React.MouseEvent) => { if (!duration) return const rect = e.currentTarget.getBoundingClientRect() diff --git a/frontend/src/components/PrepStrip.tsx b/frontend/src/components/PrepStrip.tsx index 6b9b816..007ae88 100644 --- a/frontend/src/components/PrepStrip.tsx +++ b/frontend/src/components/PrepStrip.tsx @@ -1,5 +1,5 @@ import { useEffect, useRef, useState } from 'react' -import { api, type Track } from '../api' +import { api, type Track, type TrackCues } from '../api' import { analyzeWaveform, type WaveColumn } from '../lib/waveform' import { ScratchEngine } from '../lib/scratchEngine' import { MainWaveform } from './MainWaveform' @@ -33,6 +33,7 @@ export function PrepStrip({ track, onError }: Props) { const [loadError, setLoadError] = useState(false) const [cols, setCols] = useState(null) const [waveStatus, setWaveStatus] = useState<'loading' | 'ready' | 'error'>('loading') + const [cueData, setCueData] = useState(null) // Scratch engine (Web Audio) — holds the decoded buffer for the loaded track. const audioCtxRef = useRef(null) @@ -81,6 +82,27 @@ export function PrepStrip({ track, onError }: Props) { } }, [trackId]) + // Fetch beatgrid + cue markers for the loaded track. + useEffect(() => { + if (!trackId) { + setCueData(null) + return + } + let cancelled = false + setCueData(null) + api + .trackCues(trackId) + .then((d) => { + if (!cancelled) setCueData(d) + }) + .catch(() => { + if (!cancelled) setCueData(null) + }) + return () => { + cancelled = true + } + }, [trackId]) + const toggle = () => { const el = audioRef.current if (!el || !track) return @@ -94,18 +116,33 @@ export function PrepStrip({ track, onError }: Props) { } } - // Smoothly advance the playhead/time while playing (timeupdate is only ~4Hz). + // Smoothly advance the playhead while playing. HTMLAudioElement.currentTime + // only updates in coarse steps (tens of ms), which looks choppy when zoomed in, + // so we interpolate with the wall clock between the media clock's ticks and + // re-anchor whenever it actually advances. useEffect(() => { if (!playing) return let raf = 0 + let lastRaw = -1 + let anchorAudio = 0 + let anchorPerf = 0 const tick = () => { const el = audioRef.current - if (el) setCurrent(el.currentTime) + if (el) { + const raw = el.currentTime + if (raw !== lastRaw) { + lastRaw = raw + anchorAudio = raw + anchorPerf = performance.now() + } + const est = anchorAudio + (performance.now() - anchorPerf) / 1000 + setCurrent(duration ? Math.min(est, duration) : est) + } raf = requestAnimationFrame(tick) } raf = requestAnimationFrame(tick) return () => cancelAnimationFrame(raf) - }, [playing]) + }, [playing, duration]) const seek = (t: number) => { const el = audioRef.current @@ -241,6 +278,9 @@ export function PrepStrip({ track, onError }: Props) { cols={cols} currentTime={current} duration={duration} + cues={cueData?.cues ?? []} + bpm={cueData?.bpm ?? null} + gridAnchor={cueData?.grid_anchor ?? null} onSeek={seek} onScratchStart={onScratchStart} onScratchMove={onScratchMove} @@ -258,6 +298,7 @@ export function PrepStrip({ track, onError }: Props) { cols={cols} currentTime={current} duration={duration} + cues={cueData?.cues ?? []} onSeek={seek} /> )} diff --git a/frontend/src/lib/cues.ts b/frontend/src/lib/cues.ts new file mode 100644 index 0000000..47bdee1 --- /dev/null +++ b/frontend/src/lib/cues.ts @@ -0,0 +1,101 @@ +import type { CuePoint } from '../api' + +// Default marker colours by Traktor cue type, used when a cue has no explicit +// colour of its own. +const TYPE_COLORS: Record = { + 0: '#4f8cff', // cue — accent blue + 1: '#34d399', // fade-in — mint + 2: '#34d399', // fade-out — mint + 3: '#ffb020', // load — gold + 5: '#f472b6', // loop — pink +} + +export function cueColor(cue: CuePoint): string { + if (cue.color && /^#[0-9a-f]{6}$/i.test(cue.color)) return cue.color + return TYPE_COLORS[cue.type] ?? '#8b93a3' +} + +function withAlpha(hex: string, a: number): string { + const r = parseInt(hex.slice(1, 3), 16) + const g = parseInt(hex.slice(3, 5), 16) + const b = parseInt(hex.slice(5, 7), 16) + return `rgba(${r},${g},${b},${a})` +} + +/** + * Draw cue/loop markers onto a canvas. `timeToX` maps a time (seconds) to a + * device-pixel x. With `labels`, a small numbered flag is drawn at the top for + * hotcues (used on the main waveform); the overview passes labels=false. + */ +export function drawCues( + ctx: CanvasRenderingContext2D, + cues: CuePoint[], + w: number, + h: number, + dpr: number, + timeToX: (t: number) => number, + labels: boolean, +): void { + const lineW = Math.max(2, Math.round(2 * dpr)) + const flag = Math.round(13 * dpr) + for (const cue of cues) { + const color = cueColor(cue) + const x = Math.round(timeToX(cue.start)) + + // Loop region (len > 0): translucent band from start to end. + if (cue.length > 0) { + const x2 = Math.round(timeToX(cue.start + cue.length)) + if (x2 > 0 && x < w) { + ctx.fillStyle = withAlpha(color, 0.18) + ctx.fillRect(x, 0, Math.max(1, x2 - x), h) + } + } + + if (x < -flag || x > w + flag) continue + ctx.fillStyle = color + ctx.fillRect(x - Math.floor(lineW / 2), 0, lineW, h) + + if (labels && cue.hotcue >= 0) { + ctx.fillStyle = color + ctx.fillRect(x, 0, flag, flag) + ctx.fillStyle = '#0a0b0f' + ctx.font = `${Math.round(9 * dpr)}px system-ui, sans-serif` + ctx.textBaseline = 'top' + ctx.fillText(String(cue.hotcue + 1), x + Math.round(3 * dpr), Math.round(2 * dpr)) + } + } +} + +/** + * 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. + */ +export function drawBeatgrid( + ctx: CanvasRenderingContext2D, + bpm: number, + gridAnchor: number, + startSec: number, + endSec: number, + w: number, + h: number, + dpr: number, +): void { + if (bpm <= 0 || endSec <= startSec) return + const beat = 60 / bpm + const span = endSec - startSec + const beatPx = (beat / span) * w + const showBeats = beatPx >= 6 * 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) + ctx.fillStyle = downbeat ? 'rgba(255,255,255,0.5)' : 'rgba(255,255,255,0.2)' + ctx.fillRect(x, 0, downbeat ? Math.max(1, Math.round(dpr)) : 1, h) + } +}