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

+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>
)
},