Implemented beatgrid and cuepoint display in waveform

This commit is contained in:
Ben committed 2026-07-04 17:01:18 +02:00
1 parent 5454784cff
commit f88f1932dc
7 files changed
+246 -9

No files matched your search

+33
View File
@@ -18,6 +18,7 @@ from .playlist_store import PlaylistError, PlaylistStore
from .schemas import ( from .schemas import (
CollectionStatus, CollectionStatus,
CreatePlaylist, CreatePlaylist,
CuePoint,
EditState, EditState,
EditTrack, EditTrack,
Facets, Facets,
@@ -31,6 +32,7 @@ from .schemas import (
SetEntries, SetEntries,
Stats, Stats,
Track, Track,
TrackCues,
TrackPage, TrackPage,
) )
@@ -328,6 +330,37 @@ def track_audio(track_id: str) -> FileResponse:
return FileResponse(path, media_type=mime) 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") @app.put("/api/tracks/art")
async def set_track_art(track_id: str = Form(...), file: UploadFile = File(...)) -> dict: 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).""" """Stage replacement cover art for a track (written to the file on save)."""
+15
View File
@@ -118,6 +118,21 @@ class SaveResult(BaseModel):
file_tags: list[FileTagOutcome] = [] 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): class EditState(BaseModel):
dirty: bool # unsaved in-memory playlist changes exist dirty: bool # unsaved in-memory playlist changes exist
nml_path: str nml_path: str
+17
View File
@@ -97,6 +97,21 @@ export interface TrackQuery {
offset?: number 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 { export interface EditState {
dirty: boolean dirty: boolean
nml_path: string nml_path: string
@@ -201,6 +216,8 @@ export const api = {
send<{ status: string }>('PATCH', '/api/tracks', { track_id: trackId, fields }), send<{ status: string }>('PATCH', '/api/tracks', { track_id: trackId, fields }),
artUrl: (trackId: string) => `/api/tracks/art?track_id=${encodeURIComponent(trackId)}`, artUrl: (trackId: string) => `/api/tracks/art?track_id=${encodeURIComponent(trackId)}`,
audioUrl: (trackId: string) => `/api/tracks/audio?track_id=${encodeURIComponent(trackId)}`, audioUrl: (trackId: string) => `/api/tracks/audio?track_id=${encodeURIComponent(trackId)}`,
trackCues: (trackId: string) =>
getJSON<TrackCues>(`/api/tracks/cues?track_id=${encodeURIComponent(trackId)}`),
uploadArt: async (trackId: string, file: File) => { uploadArt: async (trackId: string, file: File) => {
const fd = new FormData() const fd = new FormData()
fd.append('track_id', trackId) fd.append('track_id', trackId)
+20 -3
View File
@@ -1,10 +1,15 @@
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import type { CuePoint } from '../api'
import { drawBeatgrid, drawCues } from '../lib/cues'
import { paintWave, type WaveColumn } from '../lib/waveform' import { paintWave, type WaveColumn } from '../lib/waveform'
interface Props { interface Props {
cols: WaveColumn[] cols: WaveColumn[]
currentTime: number currentTime: number
duration: number duration: number
cues: CuePoint[]
bpm: number | null
gridAnchor: number | null
onSeek: (t: number) => void onSeek: (t: number) => void
onScratchStart: () => void onScratchStart: () => void
onScratchMove: (t: number) => void onScratchMove: (t: number) => void
@@ -27,6 +32,9 @@ export function MainWaveform({
cols, cols,
currentTime, currentTime,
duration, duration,
cues,
bpm,
gridAnchor,
onSeek, onSeek,
onScratchStart, onScratchStart,
onScratchMove, onScratchMove,
@@ -58,9 +66,18 @@ export function MainWaveform({
if (cols.length && duration > 0) { if (cols.length && duration > 0) {
const half = secPerView / 2 const half = secPerView / 2
const startFrac = (currentTime - half) / duration const startSec = currentTime - half
const endFrac = (currentTime + half) / duration const endSec = currentTime + half
paintWave(ctx, cols, w, h, startFrac, endFrac) 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. // Fixed centre playhead.
+15 -2
View File
@@ -1,10 +1,13 @@
import { useCallback, useEffect, useRef } from 'react' import { useCallback, useEffect, useRef } from 'react'
import type { CuePoint } from '../api'
import { drawCues } from '../lib/cues'
import { paintWave, type WaveColumn } from '../lib/waveform' import { paintWave, type WaveColumn } from '../lib/waveform'
interface Props { interface Props {
cols: WaveColumn[] cols: WaveColumn[]
currentTime: number currentTime: number
duration: number duration: number
cues: CuePoint[]
onSeek: (t: number) => void onSeek: (t: number) => void
} }
@@ -13,12 +16,13 @@ interface Props {
* offscreen canvas) with a moving playhead + dimmed played region. Click to * offscreen canvas) with a moving playhead + dimmed played region. Click to
* seek anywhere in the track. * 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<HTMLDivElement>(null) const wrapRef = useRef<HTMLDivElement>(null)
const canvasRef = useRef<HTMLCanvasElement>(null) const canvasRef = useRef<HTMLCanvasElement>(null)
const cacheRef = useRef<HTMLCanvasElement | null>(null) const cacheRef = useRef<HTMLCanvasElement | null>(null)
const timeRef = useRef(0) const timeRef = useRef(0)
const durRef = useRef(0) const durRef = useRef(0)
const cuesRef = useRef<CuePoint[]>(cues)
const renderCache = useCallback(() => { const renderCache = useCallback(() => {
const canvas = canvasRef.current const canvas = canvasRef.current
@@ -49,7 +53,10 @@ export function OverviewWaveform({ cols, currentTime, duration, onSeek }: Props)
const px = Math.round((timeRef.current / dur) * w) const px = Math.round((timeRef.current / dur) * w)
ctx.fillStyle = 'rgba(10,11,15,0.55)' ctx.fillStyle = 'rgba(10,11,15,0.55)'
ctx.fillRect(0, 0, px, h) 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.fillStyle = '#e6e9ef'
ctx.fillRect(px - Math.floor(pw / 2), 0, pw, h) ctx.fillRect(px - Math.floor(pw / 2), 0, pw, h)
} }
@@ -86,6 +93,12 @@ export function OverviewWaveform({ cols, currentTime, duration, onSeek }: Props)
draw() draw()
}, [currentTime, duration, draw]) }, [currentTime, duration, draw])
// Redraw when the cue set changes (new track).
useEffect(() => {
cuesRef.current = cues
draw()
}, [cues, draw])
const seek = (e: React.MouseEvent<HTMLDivElement>) => { const seek = (e: React.MouseEvent<HTMLDivElement>) => {
if (!duration) return if (!duration) return
const rect = e.currentTarget.getBoundingClientRect() const rect = e.currentTarget.getBoundingClientRect()
+45 -4
View File
@@ -1,5 +1,5 @@
import { useEffect, useRef, useState } from 'react' 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 { analyzeWaveform, type WaveColumn } from '../lib/waveform'
import { ScratchEngine } from '../lib/scratchEngine' import { ScratchEngine } from '../lib/scratchEngine'
import { MainWaveform } from './MainWaveform' import { MainWaveform } from './MainWaveform'
@@ -33,6 +33,7 @@ export function PrepStrip({ track, onError }: Props) {
const [loadError, setLoadError] = useState(false) const [loadError, setLoadError] = useState(false)
const [cols, setCols] = useState<WaveColumn[] | null>(null) const [cols, setCols] = useState<WaveColumn[] | null>(null)
const [waveStatus, setWaveStatus] = useState<'loading' | 'ready' | 'error'>('loading') const [waveStatus, setWaveStatus] = useState<'loading' | 'ready' | 'error'>('loading')
const [cueData, setCueData] = useState<TrackCues | null>(null)
// Scratch engine (Web Audio) — holds the decoded buffer for the loaded track. // Scratch engine (Web Audio) — holds the decoded buffer for the loaded track.
const audioCtxRef = useRef<AudioContext | null>(null) const audioCtxRef = useRef<AudioContext | null>(null)
@@ -81,6 +82,27 @@ export function PrepStrip({ track, onError }: Props) {
} }
}, [trackId]) }, [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 toggle = () => {
const el = audioRef.current const el = audioRef.current
if (!el || !track) return 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(() => { useEffect(() => {
if (!playing) return if (!playing) return
let raf = 0 let raf = 0
let lastRaw = -1
let anchorAudio = 0
let anchorPerf = 0
const tick = () => { const tick = () => {
const el = audioRef.current 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)
} }
raf = requestAnimationFrame(tick) raf = requestAnimationFrame(tick)
return () => cancelAnimationFrame(raf) return () => cancelAnimationFrame(raf)
}, [playing]) }, [playing, duration])
const seek = (t: number) => { const seek = (t: number) => {
const el = audioRef.current const el = audioRef.current
@@ -241,6 +278,9 @@ export function PrepStrip({ track, onError }: Props) {
cols={cols} cols={cols}
currentTime={current} currentTime={current}
duration={duration} duration={duration}
cues={cueData?.cues ?? []}
bpm={cueData?.bpm ?? null}
gridAnchor={cueData?.grid_anchor ?? null}
onSeek={seek} onSeek={seek}
onScratchStart={onScratchStart} onScratchStart={onScratchStart}
onScratchMove={onScratchMove} onScratchMove={onScratchMove}
@@ -258,6 +298,7 @@ export function PrepStrip({ track, onError }: Props) {
cols={cols} cols={cols}
currentTime={current} currentTime={current}
duration={duration} duration={duration}
cues={cueData?.cues ?? []}
onSeek={seek} onSeek={seek}
/> />
)} )}
+101
View File
@@ -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<number, string> = {
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)
}
}