mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Improved TAP usability
This commit is contained in:
1 parent
394520c2cf
commit
f1087b60fa
4 files changed
+181
-17
No files matched your search
@@ -1,5 +1,6 @@
|
||||
import { useRef, useState } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { Icon } from '../lib/icons'
|
||||
import { MIN_TAPS, RESET_MS, TapTempo } from '../lib/tapTempo'
|
||||
|
||||
// The deck's beatgrid controls, in three pieces that live in three places:
|
||||
//
|
||||
@@ -94,7 +95,8 @@ export function TempoControls({
|
||||
lockable,
|
||||
flexible,
|
||||
markerIndex,
|
||||
onSetBpm,
|
||||
onTapStart,
|
||||
onTapBpm,
|
||||
onNudgeBpm,
|
||||
onHalve,
|
||||
onDouble,
|
||||
@@ -105,24 +107,37 @@ export function TempoControls({
|
||||
lockable: boolean
|
||||
flexible: boolean
|
||||
markerIndex: number
|
||||
onSetBpm: (bpm: number) => void
|
||||
/** A tap run began — the caller notes where, to anchor a grid there. */
|
||||
onTapStart: () => void
|
||||
/** A tapped tempo to commit; creates the grid when there is none. */
|
||||
onTapBpm: (bpm: number) => void
|
||||
onNudgeBpm: (delta: number) => void
|
||||
onHalve: () => void
|
||||
onDouble: () => void
|
||||
onToggleLock: () => void
|
||||
}) {
|
||||
const tapsRef = useRef<number[]>([])
|
||||
// One run of taps; its reading is shown on the button, so a press that is
|
||||
// not yet enough to commit still visibly counts.
|
||||
const tapperRef = useRef(new TapTempo())
|
||||
const committedRef = useRef<number | null>(null)
|
||||
const idleRef = useRef<ReturnType<typeof setTimeout>>(undefined)
|
||||
const [tapCount, setTapCount] = useState(0)
|
||||
const tap = () => {
|
||||
const now = performance.now()
|
||||
const taps = tapsRef.current
|
||||
if (taps.length && now - taps[taps.length - 1] > 2000) taps.length = 0 // reset after a pause
|
||||
taps.push(now)
|
||||
if (taps.length > 8) taps.shift()
|
||||
if (taps.length >= 2) {
|
||||
const avg = (now - taps[0]) / (taps.length - 1)
|
||||
onSetBpm(Math.round((60000 / avg) * 1000) / 1000)
|
||||
const { count, bpm: tapped } = tapperRef.current.tap(performance.now())
|
||||
if (count === 1) {
|
||||
committedRef.current = null
|
||||
onTapStart()
|
||||
}
|
||||
setTapCount(count)
|
||||
clearTimeout(idleRef.current)
|
||||
idleRef.current = setTimeout(() => setTapCount(0), RESET_MS)
|
||||
// Commit only when the snapped value moves: every set is an edit.
|
||||
if (tapped != null && tapped !== committedRef.current) {
|
||||
committedRef.current = tapped
|
||||
onTapBpm(tapped)
|
||||
}
|
||||
}
|
||||
useEffect(() => () => clearTimeout(idleRef.current), [])
|
||||
const off = bpm == null
|
||||
const of = flexible ? ` of marker ${markerIndex + 1}` : ''
|
||||
return (
|
||||
@@ -135,12 +150,13 @@ export function TempoControls({
|
||||
<button className={`${T_BTN} w-7`} onClick={onHalve} disabled={off} title={`Halve the BPM${of}`}>÷2</button>
|
||||
<button className={`${T_BTN} w-7`} onClick={onDouble} disabled={off} title={`Double the BPM${of}`}>×2</button>
|
||||
<button
|
||||
className={`${T_BTN} h-7 bg-ink-800 px-2 font-semibold tracking-[0.06em]`}
|
||||
className={`${T_BTN} h-7 min-w-[3.25rem] px-2 font-semibold tracking-[0.06em] ${
|
||||
tapCount ? 'bg-accent/20 text-accent' : 'bg-ink-800'
|
||||
}`}
|
||||
onClick={tap}
|
||||
disabled={off}
|
||||
title="Tap tempo"
|
||||
title={`Tap tempo — tap along for ${MIN_TAPS}+ beats; snaps to whole BPM`}
|
||||
>
|
||||
TAP
|
||||
{tapCount === 0 ? 'TAP' : tapCount < MIN_TAPS ? `${tapCount}/${MIN_TAPS}` : `TAP ${tapCount}`}
|
||||
</button>
|
||||
{lockable && (
|
||||
<button
|
||||
|
||||
@@ -877,6 +877,33 @@ export function PrepStrip({
|
||||
if (!activeMarker) return
|
||||
editMarker(activeMarkerIndex, { start: Math.max(0, activeMarker.start + deltaMs / 1000) })
|
||||
}
|
||||
// Tap tempo retempos the governing marker, or — with no grid — creates one
|
||||
// at the tempo tapped, anchored where the run began (the first tap is a beat
|
||||
// when tapping along; the Grid-mode nudges fix the phase). While that create
|
||||
// is in flight, later taps wait for it rather than creating a second grid.
|
||||
const tapAnchorRef = useRef(0)
|
||||
const tapCreateRef = useRef<Promise<boolean> | null>(null)
|
||||
const tapStart = () => {
|
||||
tapAnchorRef.current = playheadNow()
|
||||
}
|
||||
const tapBpm = async (bpm: number) => {
|
||||
if (!track) return
|
||||
// This closure predates the grid it is waiting for, so it cannot use
|
||||
// activeMarkerIndex — but a grid created by a tap has exactly one marker.
|
||||
if (tapCreateRef.current) {
|
||||
if (await tapCreateRef.current) editMarker(0, { bpm })
|
||||
return
|
||||
}
|
||||
if (markerCount > 0) return setBpm(bpm)
|
||||
if (refuseGridEdit()) return
|
||||
const create = api
|
||||
.addGridMarker(track.id, tapAnchorRef.current, bpm)
|
||||
.then((cues) => (applyCueEdit(cues), true))
|
||||
.catch((e) => (onError?.((e as Error).message), false))
|
||||
.finally(() => (tapCreateRef.current = null))
|
||||
tapCreateRef.current = create
|
||||
await create
|
||||
}
|
||||
// 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 () => {
|
||||
@@ -1338,7 +1365,8 @@ export function PrepStrip({
|
||||
lockable={caps.grid.lockable}
|
||||
flexible={markerCount > 1}
|
||||
markerIndex={activeMarkerIndex}
|
||||
onSetBpm={setBpm}
|
||||
onTapStart={tapStart}
|
||||
onTapBpm={tapBpm}
|
||||
onNudgeBpm={nudgeBpm}
|
||||
onHalve={halveBpm}
|
||||
onDouble={doubleBpm}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { MIN_TAPS, TapTempo, snapBpm } from './tapTempo'
|
||||
|
||||
/** Tap `n` beats at `bpm`, each press offset by the matching `jitter` ms. */
|
||||
function run(bpm: number, n: number, jitter: number[] = []) {
|
||||
const t = new TapTempo()
|
||||
const ms = 60000 / bpm
|
||||
let last = { count: 0, bpm: null as number | null }
|
||||
for (let i = 0; i < n; i++) last = t.tap(1000 + i * ms + (jitter[i % jitter.length] ?? 0))
|
||||
return last
|
||||
}
|
||||
|
||||
describe('snapBpm', () => {
|
||||
it('snaps near-whole values to the whole BPM', () => {
|
||||
expect(snapBpm(124.8)).toBe(125)
|
||||
expect(snapBpm(125.29)).toBe(125)
|
||||
})
|
||||
it('falls back to the nearest half between wholes', () => {
|
||||
expect(snapBpm(127.45)).toBe(127.5)
|
||||
expect(snapBpm(127.62)).toBe(127.5)
|
||||
})
|
||||
})
|
||||
|
||||
describe('TapTempo', () => {
|
||||
it('reports nothing until enough taps', () => {
|
||||
expect(run(125, MIN_TAPS - 1).bpm).toBeNull()
|
||||
expect(run(125, MIN_TAPS).bpm).toBe(125)
|
||||
})
|
||||
|
||||
it('averages out human jitter', () => {
|
||||
// ±25 ms per press: any single interval here is off by up to ~6 BPM.
|
||||
expect(run(126, 12, [0, 25, -20, 10, -25, 15, -5, 20]).bpm).toBe(126)
|
||||
})
|
||||
|
||||
it('restarts after a pause', () => {
|
||||
const t = new TapTempo()
|
||||
for (let i = 0; i < 5; i++) t.tap(i * 500)
|
||||
expect(t.tap(5 * 500 + 3000).count).toBe(1)
|
||||
})
|
||||
|
||||
it('restarts on a press far off the running tempo', () => {
|
||||
const t = new TapTempo()
|
||||
for (let i = 0; i < 5; i++) t.tap(i * 500)
|
||||
expect(t.tap(4 * 500 + 120).count).toBe(1) // double press
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,73 @@
|
||||
// Tap tempo: turn a run of button presses into a BPM worth committing.
|
||||
//
|
||||
// A human taps with roughly 20–30 ms of jitter per press, which at 125 BPM is
|
||||
// several BPM of error in any ONE interval. So:
|
||||
// - the tempo is the least-squares slope of tap time against tap number, which
|
||||
// uses every tap in the window rather than just the first and last;
|
||||
// - nothing is reported until MIN_TAPS, since two or three taps cannot tell
|
||||
// 126 from 131;
|
||||
// - the result snaps to a whole BPM (or a half where it sits clearly between
|
||||
// two), because tapping cannot resolve finer than that and nearly every
|
||||
// dance track is on a whole number — the ±0.01 nudges do the rest;
|
||||
// - a pause, or a press far off the running tempo (a double press, a missed
|
||||
// beat), starts a new run instead of dragging the estimate.
|
||||
|
||||
export const MIN_TAPS = 4
|
||||
const MAX_TAPS = 16
|
||||
/** Longest gap between taps that still continues a run (30 BPM). */
|
||||
export const RESET_MS = 2000
|
||||
/** How far one interval may stray from the running period before it restarts. */
|
||||
const OUTLIER = 0.35
|
||||
/** Within this of a whole BPM, snap to it; otherwise to the nearest half. */
|
||||
const WHOLE_SNAP = 0.3
|
||||
|
||||
export interface TapReading {
|
||||
/** Taps in the current run, including this one. */
|
||||
count: number
|
||||
/** Snapped BPM, or null until the run is long enough to trust. */
|
||||
bpm: number | null
|
||||
}
|
||||
|
||||
/** Least-squares slope of times against index: the mean beat period, in ms. */
|
||||
function period(taps: number[]): number {
|
||||
const n = taps.length
|
||||
const meanI = (n - 1) / 2
|
||||
const meanT = taps.reduce((a, b) => a + b, 0) / n
|
||||
let num = 0
|
||||
let den = 0
|
||||
for (let i = 0; i < n; i++) {
|
||||
num += (i - meanI) * (taps[i] - meanT)
|
||||
den += (i - meanI) ** 2
|
||||
}
|
||||
return num / den
|
||||
}
|
||||
|
||||
export function snapBpm(bpm: number): number {
|
||||
const whole = Math.round(bpm)
|
||||
return Math.abs(bpm - whole) <= WHOLE_SNAP ? whole : Math.round(bpm * 2) / 2
|
||||
}
|
||||
|
||||
export class TapTempo {
|
||||
private taps: number[] = []
|
||||
|
||||
/** Register a press at `now` (ms, monotonic). */
|
||||
tap(now: number): TapReading {
|
||||
const taps = this.taps
|
||||
const last = taps[taps.length - 1]
|
||||
if (last !== undefined) {
|
||||
const gap = now - last
|
||||
const expected = taps.length >= 2 ? period(taps) : gap
|
||||
if (gap > RESET_MS || gap <= 0 || Math.abs(gap - expected) > expected * OUTLIER) {
|
||||
taps.length = 0
|
||||
}
|
||||
}
|
||||
taps.push(now)
|
||||
if (taps.length > MAX_TAPS) taps.shift()
|
||||
if (taps.length < MIN_TAPS) return { count: taps.length, bpm: null }
|
||||
return { count: taps.length, bpm: snapBpm(60000 / period(taps)) }
|
||||
}
|
||||
|
||||
reset() {
|
||||
this.taps.length = 0
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user