Begun implementing playback

This commit is contained in:
Ben committed 2026-07-04 16:15:50 +02:00
1 parent 279e5ac34f
commit fa7375d0e9
9 files changed
+712 -49

No files matched your search

+16 -5
View File
@@ -12,6 +12,7 @@ import { Toast, type ToastMsg } from './components/Toast'
import { CollectionPicker } from './components/CollectionPicker'
import { ContextMenu } from './components/ContextMenu'
import { EditTagsDialog } from './components/EditTagsDialog'
import { PrepStrip } from './components/PrepStrip'
function applyFilters(tracks: Track[], f: Filters): Track[] {
const q = f.search.trim().toLowerCase()
@@ -43,6 +44,7 @@ export default function App() {
const [forcePicker, setForcePicker] = useState(false)
const [menu, setMenu] = useState<{ track: Track; x: number; y: number } | null>(null)
const [editing, setEditing] = useState<Track | null>(null)
const [prepTrack, setPrepTrack] = useState<Track | null>(null)
const notify = useCallback((kind: ToastMsg['kind'], text: string) => {
setToast({ id: Date.now(), kind, text })
@@ -119,13 +121,16 @@ export default function App() {
)
return (
<div className="flex h-screen w-screen overflow-hidden bg-ink-950">
<div className="flex h-screen w-screen flex-col overflow-hidden bg-ink-950">
<Toast toast={toast} onClose={() => setToast(null)} />
{menu && (
<ContextMenu
x={menu.x}
y={menu.y}
items={[{ label: 'Edit Tags…', onClick: () => setEditing(menu.track) }]}
items={[
{ label: 'Load to Deck', onClick: () => setPrepTrack(menu.track) },
{ label: 'Edit Tags…', onClick: () => setEditing(menu.track) },
]}
onClose={() => setMenu(null)}
/>
)}
@@ -137,9 +142,14 @@ export default function App() {
onError={onError}
/>
)}
<Sidebar source={source} onSelect={selectSource} onError={onError} />
<main className="relative flex min-w-0 flex-1 flex-col">
{/* Prep strip spans the top of the window; the library sits below it. */}
<PrepStrip track={prepTrack} onError={onError} />
<div className="flex min-h-0 flex-1 overflow-hidden">
<Sidebar source={source} onSelect={selectSource} onError={onError} />
<main className="relative flex min-w-0 flex-1 flex-col">
{isAll ? (
<Toolbar filters={filters} onChange={setFilters} />
) : (
@@ -203,7 +213,8 @@ export default function App() {
collectionName={collection.data?.path?.split('/').pop() ?? null}
onChangeCollection={() => setForcePicker(true)}
/>
</main>
</main>
</div>
</div>
)
}
+1
View File
@@ -200,6 +200,7 @@ export const api = {
editTrack: (trackId: string, fields: Record<string, string | number | null>) =>
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)}`,
uploadArt: async (trackId: string, file: File) => {
const fd = new FormData()
fd.append('track_id', trackId)
+112
View File
@@ -0,0 +1,112 @@
import { useEffect, useRef, useState } from 'react'
import { paintWave, type WaveColumn } from '../lib/waveform'
interface Props {
cols: WaveColumn[]
currentTime: number
duration: number
onSeek: (t: number) => void
}
const MIN_SEC = 2 // most zoomed-in (seconds across the view)
const MAX_SEC = 64 // most zoomed-out
const DEFAULT_SEC = 16
/**
* Traktor-style scrolling main waveform: the playhead is fixed at the centre and
* the waveform scrolls beneath it. Shows a time window [t - sec/2, t + sec/2];
* the zoom buttons change that window width. Repaints every frame (driven by the
* parent's rAF-updated currentTime).
*/
export function MainWaveform({ cols, currentTime, duration, onSeek }: Props) {
const wrapRef = useRef<HTMLDivElement>(null)
const canvasRef = useRef<HTMLCanvasElement>(null)
const [secPerView, setSecPerView] = useState(DEFAULT_SEC)
// Draw closes over the latest props/state; a ref lets the ResizeObserver call
// the current version without re-subscribing.
const draw = () => {
const canvas = canvasRef.current
const wrap = wrapRef.current
if (!canvas || !wrap) return
const dpr = window.devicePixelRatio || 1
const w = Math.max(1, Math.floor(wrap.clientWidth * dpr))
const h = Math.max(1, Math.floor(wrap.clientHeight * dpr))
if (canvas.width !== w) canvas.width = w
if (canvas.height !== h) canvas.height = h
const ctx = canvas.getContext('2d')!
ctx.clearRect(0, 0, w, h)
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)
}
// Fixed centre playhead.
const cx = Math.floor(w / 2)
ctx.fillStyle = '#e6e9ef'
ctx.fillRect(cx, 0, Math.max(1, Math.round(dpr)), h)
}
const drawRef = useRef(draw)
drawRef.current = draw
// Redraw after every render (covers currentTime advancing, zoom, new track).
useEffect(() => {
draw()
})
useEffect(() => {
const wrap = wrapRef.current
if (!wrap) return
const ro = new ResizeObserver(() => drawRef.current())
ro.observe(wrap)
return () => ro.disconnect()
}, [])
// Click to seek: map horizontal offset from centre to a time delta.
const seek = (e: React.MouseEvent<HTMLDivElement>) => {
if (!duration) return
const rect = e.currentTarget.getBoundingClientRect()
const ratioFromCenter = (e.clientX - rect.left) / rect.width - 0.5
const t = currentTime + ratioFromCenter * secPerView
onSeek(Math.min(duration, Math.max(0, t)))
}
const zoomIn = () => setSecPerView((s) => Math.max(MIN_SEC, s / 2))
const zoomOut = () => setSecPerView((s) => Math.min(MAX_SEC, s * 2))
return (
<div ref={wrapRef} onClick={seek} className="relative h-full w-full cursor-pointer">
<canvas ref={canvasRef} className="block h-full w-full" />
{/* Zoom controls (Traktor-style +/-) */}
<div className="absolute right-2 top-2 flex flex-col gap-1">
<button
onClick={(e) => {
e.stopPropagation()
zoomIn()
}}
disabled={secPerView <= MIN_SEC}
className="flex h-6 w-6 items-center justify-center rounded border border-line bg-ink-950/70 text-sm text-text hover:border-accent disabled:opacity-30"
title="Zoom in"
>
+
</button>
<button
onClick={(e) => {
e.stopPropagation()
zoomOut()
}}
disabled={secPerView >= MAX_SEC}
className="flex h-6 w-6 items-center justify-center rounded border border-line bg-ink-950/70 text-sm text-text hover:border-accent disabled:opacity-30"
title="Zoom out"
>
−
</button>
</div>
</div>
)
}
@@ -0,0 +1,100 @@
import { useCallback, useEffect, useRef } from 'react'
import { paintWave, type WaveColumn } from '../lib/waveform'
interface Props {
cols: WaveColumn[]
currentTime: number
duration: number
onSeek: (t: number) => void
}
/**
* Whole-track overview waveform: static coloured waveform (cached to an
* offscreen canvas) with a moving playhead + dimmed played region. Click to
* seek anywhere in the track.
*/
export function OverviewWaveform({ cols, currentTime, duration, 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 renderCache = useCallback(() => {
const canvas = canvasRef.current
if (!canvas || canvas.width === 0) return
let cache = cacheRef.current
if (!cache) {
cache = document.createElement('canvas')
cacheRef.current = cache
}
cache.width = canvas.width
cache.height = canvas.height
const ctx = cache.getContext('2d')!
ctx.clearRect(0, 0, cache.width, cache.height)
paintWave(ctx, cols, cache.width, cache.height, 0, 1)
}, [cols])
const draw = useCallback(() => {
const canvas = canvasRef.current
const cache = cacheRef.current
if (!canvas) return
const ctx = canvas.getContext('2d')!
const w = canvas.width
const h = canvas.height
ctx.clearRect(0, 0, w, h)
if (cache) ctx.drawImage(cache, 0, 0)
const dur = durRef.current
if (dur > 0) {
const px = Math.round((timeRef.current / dur) * w)
ctx.fillStyle = 'rgba(10,11,15,0.55)'
ctx.fillRect(0, 0, px, h)
ctx.fillStyle = '#e6e9ef'
ctx.fillRect(px, 0, 1, h)
}
}, [])
const resize = useCallback(() => {
const canvas = canvasRef.current
const wrap = wrapRef.current
if (!canvas || !wrap) return
const dpr = window.devicePixelRatio || 1
canvas.width = Math.max(1, Math.floor(wrap.clientWidth * dpr))
canvas.height = Math.max(1, Math.floor(wrap.clientHeight * dpr))
renderCache()
draw()
}, [renderCache, draw])
// Rebuild the cache when the columns change (new track) or on resize.
useEffect(() => {
resize()
}, [resize])
useEffect(() => {
const wrap = wrapRef.current
if (!wrap) return
const ro = new ResizeObserver(() => resize())
ro.observe(wrap)
return () => ro.disconnect()
}, [resize])
// Move the playhead as playback advances.
useEffect(() => {
timeRef.current = currentTime
durRef.current = duration
draw()
}, [currentTime, duration, draw])
const seek = (e: React.MouseEvent<HTMLDivElement>) => {
if (!duration) return
const rect = e.currentTarget.getBoundingClientRect()
const ratio = Math.min(1, Math.max(0, (e.clientX - rect.left) / rect.width))
onSeek(ratio * duration)
}
return (
<div ref={wrapRef} onClick={seek} className="h-full w-full cursor-pointer">
<canvas ref={canvasRef} className="block h-full w-full" />
</div>
)
}
+197
View File
@@ -0,0 +1,197 @@
import { useEffect, useRef, useState } from 'react'
import { api, type Track } from '../api'
import { analyzeWaveform, type WaveColumn } from '../lib/waveform'
import { MainWaveform } from './MainWaveform'
import { OverviewWaveform } from './OverviewWaveform'
interface Props {
/** The track currently loaded into the prep deck, if any. */
track: Track | null
onError?: (msg: string) => void
}
function fmt(secs: number): string {
if (!isFinite(secs) || secs < 0) return '0:00'
const m = Math.floor(secs / 60)
const s = Math.floor(secs % 60)
return `${m}:${s.toString().padStart(2, '0')}`
}
/**
* The DJ-style "prep strip" across the top of the window: transport controls on
* the left, waveforms on the right (a scrolling zoomable main view above a
* whole-track overview). Playback is driven by a single hidden <audio> element
* streamed from the backend (range-enabled, so seeking works). The frequency-
* coloured waveform is analysed once here and shared by both views.
*/
export function PrepStrip({ track, onError }: Props) {
const audioRef = useRef<HTMLAudioElement | null>(null)
const [playing, setPlaying] = useState(false)
const [current, setCurrent] = useState(0)
const [duration, setDuration] = useState(0)
const [loadError, setLoadError] = useState(false)
const [cols, setCols] = useState<WaveColumn[] | null>(null)
const [waveStatus, setWaveStatus] = useState<'loading' | 'ready' | 'error'>('loading')
const trackId = track?.id ?? null
// When the loaded track changes, reset transport state. The <audio> src is
// bound declaratively below, so changing trackId swaps the source.
useEffect(() => {
setPlaying(false)
setCurrent(0)
setDuration(0)
setLoadError(false)
}, [trackId])
// Analyse the waveform once per track; both waveform views share the result.
useEffect(() => {
if (!trackId) {
setCols(null)
setWaveStatus('loading')
return
}
let cancelled = false
setCols(null)
setWaveStatus('loading')
analyzeWaveform(api.audioUrl(trackId))
.then((c) => {
if (cancelled) return
setCols(c)
setWaveStatus('ready')
})
.catch(() => {
if (!cancelled) setWaveStatus('error')
})
return () => {
cancelled = true
}
}, [trackId])
const toggle = () => {
const el = audioRef.current
if (!el || !track) return
if (el.paused) {
el.play().catch(() => {
setLoadError(true)
setPlaying(false)
})
} else {
el.pause()
}
}
// Smoothly advance the playhead/time while playing (timeupdate is only ~4Hz).
useEffect(() => {
if (!playing) return
let raf = 0
const tick = () => {
const el = audioRef.current
if (el) setCurrent(el.currentTime)
raf = requestAnimationFrame(tick)
}
raf = requestAnimationFrame(tick)
return () => cancelAnimationFrame(raf)
}, [playing])
const seek = (t: number) => {
const el = audioRef.current
if (!el) return
el.currentTime = t
setCurrent(t)
}
const showWaves = track && !loadError && cols && waveStatus === 'ready'
return (
<div className="flex h-52 shrink-0 items-stretch gap-px border-b border-line bg-ink-950">
{/* Controls */}
<div className="flex w-72 shrink-0 flex-col justify-between bg-ink-900 px-4 py-3">
<div className="min-w-0">
{track ? (
<>
<div className="truncate text-sm font-semibold text-text" title={track.title ?? ''}>
{track.title ?? 'Untitled'}
</div>
<div className="truncate text-xs text-muted" title={track.artist ?? ''}>
{track.artist ?? 'Unknown artist'}
</div>
</>
) : (
<div className="text-xs uppercase tracking-wider text-faint">No track loaded</div>
)}
</div>
<div className="flex items-center gap-3">
<button
onClick={toggle}
disabled={!track || loadError}
className="flex h-9 w-9 items-center justify-center rounded-full border border-line bg-ink-850 text-text hover:border-accent disabled:opacity-40 disabled:hover:border-line"
title={playing ? 'Pause' : 'Play'}
>
{playing ? '❚❚' : '▶'}
</button>
<div className="tabular-nums text-xs text-faint">
{fmt(current)} / {fmt(duration)}
</div>
</div>
</div>
{/* Waveforms: scrolling main view above a whole-track overview. */}
<div className="relative flex min-w-0 flex-1 flex-col bg-ink-900">
{!track ? (
<div className="flex flex-1 items-center justify-center text-xs text-faint">
Load a track to prep it
</div>
) : loadError ? (
<div className="flex flex-1 items-center justify-center text-xs text-pink">
Could not load audio — file may be missing or unsupported by the browser.
</div>
) : (
<>
<div className="relative min-h-0 flex-1">
{showWaves ? (
<MainWaveform
cols={cols}
currentTime={current}
duration={duration}
onSeek={seek}
/>
) : (
<div className="flex h-full items-center justify-center text-xs text-faint">
{waveStatus === 'error' ? 'Waveform unavailable' : 'Analysing waveform…'}
</div>
)}
</div>
<div className="h-10 shrink-0 border-t border-line">
{showWaves && (
<OverviewWaveform
cols={cols}
currentTime={current}
duration={duration}
onSeek={seek}
/>
)}
</div>
</>
)}
</div>
{track && (
<audio
ref={audioRef}
src={api.audioUrl(track.id)}
onPlay={() => setPlaying(true)}
onPause={() => setPlaying(false)}
onEnded={() => setPlaying(false)}
onTimeUpdate={(e) => setCurrent(e.currentTarget.currentTime)}
onLoadedMetadata={(e) => setDuration(e.currentTarget.duration)}
onError={() => {
setLoadError(true)
onError?.('Could not load audio for this track')
}}
/>
)}
</div>
)
}
+172
View File
@@ -0,0 +1,172 @@
// Frequency-colored waveform analysis (Traktor "Spectrum" theme).
//
// The audio is downmixed to mono and split into three frequency bands with
// native BiquadFilters (via OfflineAudioContext — fast, off the main thread).
// Per output column we keep each band's RMS energy plus the amplitude peak.
// Colour = balance of the three bands (bass→red, mids→green, highs→blue);
// height = amplitude. This mirrors how Traktor's Spectrum waveform reads.
export interface WaveColumn {
peak: number // 0..1 amplitude (column height)
r: number // 0..1 colour channels (already contrast-boosted)
g: number
b: number
}
// Band crossover choices. Independent filters, so band energies don't strictly
// partition — that's fine, colour is normalised per column.
const LOW_HZ = 250
const MID_HZ = 1200
const MID_Q = 0.6
const HIGH_HZ = 5000
/**
* Paint a slice of the analysed columns across a canvas: source columns in the
* fractional range [startFrac, endFrac) (of the whole track) are mapped across
* the full canvas width, aggregating multiple columns per pixel (max peak,
* averaged colour). Fractions outside [0,1] paint blank — used by the scrolling
* main view so the lead-in/lead-out past the track edges stays empty.
*/
export function paintWave(
ctx: CanvasRenderingContext2D,
cols: WaveColumn[],
w: number,
h: number,
startFrac: number,
endFrac: number,
): void {
const n = cols.length
if (n === 0 || w === 0 || h === 0) return
const mid = h / 2
const span = (endFrac - startFrac) * n
for (let x = 0; x < w; x++) {
const c0 = startFrac * n + (x / w) * span
const c1 = startFrac * n + ((x + 1) / w) * span
const i0 = Math.floor(c0)
const i1 = Math.max(i0 + 1, Math.ceil(c1))
let peak = 0
let r = 0
let g = 0
let b = 0
let count = 0
for (let i = i0; i < i1; i++) {
if (i < 0 || i >= n) continue
const col = cols[i]
if (col.peak > peak) peak = col.peak
r += col.r
g += col.g
b += col.b
count++
}
if (count === 0) continue // outside the track → blank pixel
r /= count
g /= count
b /= count
const half = Math.max(0.5, peak * (mid - 1))
ctx.fillStyle = `rgb(${(r * 255) | 0},${(g * 255) | 0},${(b * 255) | 0})`
ctx.fillRect(x, mid - half, 1, half * 2)
}
}
export async function analyzeWaveform(url: string, buckets?: number): Promise<WaveColumn[]> {
const resp = await fetch(url)
if (!resp.ok) throw new Error(`audio fetch failed: ${resp.status}`)
const arr = await resp.arrayBuffer()
const AC: typeof AudioContext =
window.AudioContext ?? (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext
const ctx = new AC()
let audio: AudioBuffer
try {
audio = await ctx.decodeAudioData(arr)
} finally {
void ctx.close()
}
const len = audio.length
const sr = audio.sampleRate
const chs = audio.numberOfChannels
// Resolution scales with track length (~140 columns/sec) so the zoomed-in
// main waveform stays crisp; clamped so short/long tracks stay reasonable.
if (buckets == null) {
const seconds = len / sr
buckets = Math.min(48000, Math.max(1600, Math.round(seconds * 140)))
}
// Downmix to mono.
const mono = new Float32Array(len)
for (let c = 0; c < chs; c++) {
const d = audio.getChannelData(c)
for (let i = 0; i < len; i++) mono[i] += d[i] / chs
}
const scale = buckets / len
const lowE = new Float64Array(buckets)
const midE = new Float64Array(buckets)
const highE = new Float64Array(buckets)
const peak = new Float64Array(buckets)
const cnt = new Float64Array(buckets)
// Amplitude peak + sample count per column (from the mono mix).
for (let i = 0; i < len; i++) {
const b = (i * scale) | 0
const a = Math.abs(mono[i])
if (a > peak[b]) peak[b] = a
cnt[b]++
}
// Render one band through a native filter, accumulate its energy, then let the
// rendered buffer be GC'd before the next band (keeps peak memory to ~2 copies).
const accumBand = async (
target: Float64Array,
type: BiquadFilterType,
freq: number,
q?: number,
) => {
const off = new OfflineAudioContext(1, len, sr)
const buf = off.createBuffer(1, len, sr)
buf.copyToChannel(mono, 0)
const src = off.createBufferSource()
src.buffer = buf
const filter = off.createBiquadFilter()
filter.type = type
filter.frequency.value = freq
if (q != null) filter.Q.value = q
src.connect(filter)
filter.connect(off.destination)
src.start()
const rendered = await off.startRendering()
const data = rendered.getChannelData(0)
for (let i = 0; i < len; i++) {
const b = (i * scale) | 0
target[b] += data[i] * data[i]
}
}
await accumBand(lowE, 'lowpass', LOW_HZ)
await accumBand(midE, 'bandpass', MID_HZ, MID_Q)
await accumBand(highE, 'highpass', HIGH_HZ)
let maxPeak = 1e-6
for (let b = 0; b < buckets; b++) if (peak[b] > maxPeak) maxPeak = peak[b]
const cols: WaveColumn[] = new Array(buckets)
for (let b = 0; b < buckets; b++) {
const n = cnt[b] || 1
const l = Math.sqrt(lowE[b] / n)
const m = Math.sqrt(midE[b] / n)
const h = Math.sqrt(highE[b] / n)
// Normalise to the dominant band so colours stay vivid (brightness is not
// tied to loudness — amplitude is shown by height, like Traktor). Gamma
// sharpens the separation between bands.
const mx = Math.max(l, m, h, 1e-9)
cols[b] = {
peak: peak[b] / maxPeak,
r: Math.pow(l / mx, 1.3),
g: Math.pow(m / mx, 1.3),
b: Math.pow(h / mx, 1.3),
}
}
return cols
}