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

+17
View File
@@ -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<TrackCues>(`/api/tracks/cues?track_id=${encodeURIComponent(trackId)}`),
uploadArt: async (trackId: string, file: File) => {
const fd = new FormData()
fd.append('track_id', trackId)
+20 -3
View File
@@ -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.
+15 -2
View File
@@ -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<HTMLDivElement>(null)
const canvasRef = useRef<HTMLCanvasElement>(null)
const cacheRef = useRef<HTMLCanvasElement | null>(null)
const timeRef = useRef(0)
const durRef = useRef(0)
const cuesRef = useRef<CuePoint[]>(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<HTMLDivElement>) => {
if (!duration) return
const rect = e.currentTarget.getBoundingClientRect()
+45 -4
View File
@@ -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<WaveColumn[] | null>(null)
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.
const audioCtxRef = useRef<AudioContext | null>(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}
/>
)}
+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)
}
}