Added support for flexible beatgrids

This commit is contained in:
patben8 committed 2026-09-17 15:14:07 +02:00
1 parent 3f51444e2a
commit dd97f27ac7
20 files changed
+2176 -346

No files matched your search

+42 -4
View File
@@ -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<TrackCues>('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<TrackCues>('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<TrackCues>('POST', '/api/tracks/grid/marker', { track_id: trackId, start, bpm }),
deleteGridMarker: (trackId: string, index: number) =>
send<TrackCues>(
'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<TrackCues>('PUT', '/api/tracks/grid', { track_id: trackId, markers }),
deleteGrid: (trackId: string) =>
send<TrackCues>('DELETE', `/api/tracks/grid?track_id=${encodeURIComponent(trackId)}`),
setLock: (trackId: string, locked: boolean) =>
+170 -23
View File
@@ -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<number[]>([])
@@ -96,7 +139,39 @@ export function GridControls({
{bpm != null ? bpm.toFixed(2) : '––'}
</button>
)}
<div className="text-[10px] font-semibold uppercase tracking-wider text-faint">BPM</div>
{!hasGrid ? (
<div className="text-[10px] font-semibold uppercase tracking-wider text-faint">
No grid
</div>
) : !flexible ? (
<div className="text-[10px] font-semibold uppercase tracking-wider text-faint">BPM</div>
) : (
// Flexible grid: show which marker is in charge and let the user step
// between them (which seeks — there is no separate selection).
<div
className={
'flex items-center justify-center gap-1 text-[10px] font-semibold tabular-nums ' +
(beforeFirst ? 'text-faint' : 'text-gold')
}
title={
beforeFirst
? "Playhead is before the first marker — marker 1's tempo extrapolates backwards"
: `Editing marker ${markerIndex + 1} of ${markerCount}`
}
>
<button onClick={onPrevMarker} className="px-1 hover:text-accent" title="Previous marker">
‹
</button>
<span>
{beforeFirst ? '↤ ' : '⊞ '}
{markerIndex + 1}/{markerCount}
{markerStart != null ? ` · ${markerTime(markerStart)}` : ''}
</span>
<button onClick={onNextMarker} className="px-1 hover:text-accent" title="Next marker">
›
</button>
</div>
)}
</div>
{/* BPM nudge — coarse ±0.25 (outer) / fine ±0.01 (inner) */}
@@ -140,16 +215,31 @@ export function GridControls({
{/* halve / double / tap / reset */}
<div className="flex gap-1">
<button className={BTN} onClick={onHalve} disabled={bpm == null} title="Halve BPM">
<button
className={BTN}
onClick={onHalve}
disabled={bpm == null}
title={flexible ? `Halve BPM of marker ${markerIndex + 1}` : 'Halve BPM'}
>
/2
</button>
<button className={BTN} onClick={onDouble} disabled={bpm == null} title="Double BPM">
<button
className={BTN}
onClick={onDouble}
disabled={bpm == null}
title={flexible ? `Double BPM of marker ${markerIndex + 1}` : 'Double BPM'}
>
×2
</button>
<button className={BTN} onClick={tap} title="Tap tempo">
TAP
</button>
<button className={BTN} onClick={onReset} title="Reset to loaded values">
<button
className={BTN}
onClick={onReset}
disabled={!canReset}
title="Restore the beatgrid as loaded"
>
Reset
</button>
</div>
@@ -159,19 +249,49 @@ export function GridControls({
<span className="mr-0.5 text-[10px] font-semibold uppercase tracking-wider text-faint">
Grid
</span>
<button className={BTN} onClick={() => onNudge(-10)} disabled={!hasGrid} title="−10 ms">
{/* Phase nudges move the GOVERNING marker — deliberately not gated on
atMarker, since the drift is heard at the playhead, not at the marker. */}
<button
className={BTN}
onClick={() => onNudgeMarker(-10)}
disabled={!hasGrid}
title="Move this marker −10 ms"
>
◀◀
</button>
<button className={BTN} onClick={() => onNudge(-1)} disabled={!hasGrid} title="−1 ms">
<button
className={BTN}
onClick={() => onNudgeMarker(-1)}
disabled={!hasGrid}
title="Move this marker −1 ms"
>
◀
</button>
<button className={BTN} onClick={onSetHere} title="Set beat 1 at the playhead">
SET
<button
className={BTN}
onClick={onAddMarker}
title={
hasGrid
? 'Add a grid marker at the playhead'
: 'Set the beatgrid at the playhead'
}
>
{hasGrid ? '+ Mrk' : 'SET'}
</button>
<button className={BTN} onClick={() => onNudge(1)} disabled={!hasGrid} title="+1 ms">
<button
className={BTN}
onClick={() => onNudgeMarker(1)}
disabled={!hasGrid}
title="Move this marker +1 ms"
>
▶
</button>
<button className={BTN} onClick={() => onNudge(10)} disabled={!hasGrid} title="+10 ms">
<button
className={BTN}
onClick={() => onNudgeMarker(10)}
disabled={!hasGrid}
title="Move this marker +10 ms"
>
▶▶
</button>
</div>
@@ -190,9 +310,36 @@ export function GridControls({
>
{locked ? '🔒 Locked' : '🔓 Lock'}
</button>
{/* 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. */}
<button
className={BTN}
onClick={onDeleteGrid}
onClick={onDeleteMarker}
disabled={!atMarker || !flexible}
title={
!flexible
? 'Use Delete grid to remove the last marker'
: atMarker
? `Delete grid marker ${markerIndex + 1}`
: 'Park the playhead on a marker to delete it (‹ › to step)'
}
>
🗑 Mrk
</button>
<button
className={BTN}
onClick={() => {
if (
confirm(
flexible
? `Delete this track's beatgrid? All ${markerCount} grid markers will be removed.`
: "Delete this track's beatgrid?",
)
) {
onDeleteGrid()
}
}}
disabled={!hasGrid}
title="Delete beatgrid"
>
@@ -213,4 +360,4 @@ export function GridControls({
</div>
</div>
)
}
})
+18 -9
View File
@@ -1,5 +1,5 @@
import type { CuePoint } from '../api'
import { contrastText, cueColor } from '../lib/cues'
import { contrastText, cueColor, GRID_MARKER_COLOR } from '../lib/cues'
interface Props {
cues: CuePoint[]
@@ -17,14 +17,21 @@ const SLOTS = [0, 1, 2, 3, 4, 5, 6, 7] // Traktor hotcue slots → labelled 1–
* (pointer capture, so a release outside the button still fires) so the parent
* can implement momentary "cue preview" (play while held). Press creates when
* empty and jumps/triggers when assigned; release ends any preview.
*
* A slot may be held by a grid marker's companion cue (Traktor writes one beside
* most of its own markers). Those belong to the beatgrid, so they are shown with
* the marker colour and a ⊞ instead of a number, and pressing one only seeks —
* the backend refuses hotcue edits on them, and showing that up front is better
* than surfacing the refusal as an error.
*/
export function HotcueBar({ cues, selectedSlot, onSlotPress, onSlotRelease }: Props) {
return (
<div className="flex flex-1 items-stretch gap-px">
{SLOTS.map((slot) => {
const cue = cues.find((c) => c.hotcue === slot) ?? null
const selected = selectedSlot === slot
const color = cue ? cueColor(cue) : null
const isMarker = cue?.grid_marker != null
const selected = selectedSlot === slot && !isMarker
const color = cue ? (isMarker ? GRID_MARKER_COLOR : cueColor(cue)) : null
return (
<button
key={slot}
@@ -38,11 +45,13 @@ export function HotcueBar({ cues, selectedSlot, onSlotPress, onSlotRelease }: Pr
onPointerUp={() => onSlotRelease(slot)}
onPointerCancel={() => onSlotRelease(slot)}
title={
cue
? cue.name && cue.name !== 'n.n.'
? `${slot + 1}: ${cue.name}`
: `Hotcue ${slot + 1}`
: `Hotcue ${slot + 1} — click to set at playhead`
isMarker
? `Beatgrid marker ${(cue!.grid_marker ?? 0) + 1} — managed by the grid controls`
: cue
? cue.name && cue.name !== 'n.n.'
? `${slot + 1}: ${cue.name}`
: `Hotcue ${slot + 1}`
: `Hotcue ${slot + 1} — click to set at playhead`
}
style={color ? { backgroundColor: color, color: contrastText(color) } : undefined}
className={
@@ -51,7 +60,7 @@ export function HotcueBar({ cues, selectedSlot, onSlotPress, onSlotRelease }: Pr
(selected ? ' ring-2 ring-inset ring-white/80' : '')
}
>
{slot + 1}
{isMarker ? '⊞' : slot + 1}
</button>
)
})}
+2 -3
View File
@@ -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 (
<div className="flex h-10 shrink-0 items-stretch gap-px border-t border-line bg-ink-950">
+8 -6
View File
@@ -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)
+198 -121
View File
@@ -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<WaveColumn[] | null>(null)
const [waveStatus, setWaveStatus] = useState<'loading' | 'ready' | 'error'>('loading')
const [cueData, setCueData] = useState<TrackCues | null>(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<number | null>(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<number | null>(null)
const loopInRef = useRef<number | null>(null) // armed manual loop-in point
const originalGridRef = useRef<{ bpm: number | null; anchor: number | null } | null>(null)
const originalGridRef = useRef<GridMarker[] | null>(null)
const audioCtxRef = useRef<AudioContext | null>(null) // playback
const scratchCtxRef = useRef<AudioContext | null>(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 && (
<GridControls
bpm={gridBpm}
bpm={activeMarker?.bpm ?? null}
markerIndex={activeMarkerIndex}
markerCount={grid?.count ?? 0}
markerStart={activeMarker?.start ?? null}
atMarker={atMarker}
beforeFirst={beforeFirstMarker}
locked={cueData?.locked ?? false}
hasGrid={gridAnchor != null}
canReset={originalGridRef.current != null}
onSetBpm={setBpm}
onNudgeBpm={nudgeBpm}
onHalve={halveBpm}
onDouble={doubleBpm}
onNudge={nudgeGrid}
onSetHere={setGridHere}
onNudgeMarker={nudgeGrid}
onAddMarker={addMarkerHere}
onDeleteMarker={deleteMarkerHere}
onPrevMarker={prevMarker}
onNextMarker={nextMarker}
onReset={resetGrid}
onToggleLock={toggleLock}
onDeleteGrid={deleteGrid}
@@ -907,8 +984,8 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
duration={duration}
cues={cueData?.cues ?? []}
cuePoint={cuePoint}
bpm={cueData?.bpm ?? null}
gridAnchor={cueData?.grid_anchor ?? null}
grid={grid}
activeMarker={activeMarkerIndex}
loop={activeLoop}
secPerView={secPerView}
onZoomChange={setSecPerView}
@@ -938,7 +1015,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
</div>
<LoopControls
bpm={cueData?.bpm ?? null}
hasGrid={grid != null}
active={loopActive}
activeBeats={activeBeats}
canToggle={loopRegion != null}
+191
View File
@@ -0,0 +1,191 @@
import { describe, expect, it } from 'vitest'
import { BEATS_PER_BAR, buildBeatGrid, type GridMarker } from './beatgrid'
const grid = (markers: GridMarker[]) => {
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([])
})
})
+304
View File
@@ -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)
}
+76 -21
View File
@@ -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<number, string> = {
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()
}
}
+10 -2
View File
@@ -211,11 +211,19 @@ export const TRACK_COLUMNS: ColumnDef<Track, any>[] = [
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 (
<span className="flex items-center gap-1 tabular-nums">
<span className={n > 0 ? 'text-text' : 'text-faint'}>{n}</span>
{grid && <span className="text-[10px] text-mint" title="Beatgrid analyzed">⊞</span>}
{c.row.original.has_grid && (
<span
className={markers > 1 ? 'text-[10px] text-gold' : 'text-[10px] text-mint'}
title={markers > 1 ? `Flexible beatgrid (${markers} markers)` : 'Beatgrid analyzed'}
>
⊞
</span>
)}
</span>
)
},