mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 18:22:53 +01:00
Implemented raw waveform mode
This commit is contained in:
1 parent
1464b1e211
commit
8230722105
10 files changed
+862
-16
No files matched your search
@@ -1037,8 +1037,10 @@ Two independent apps that talk over HTTP:
|
|||||||
badge, the readout well (ELAPSED / REMAIN to tenths, KEY, and `BpmReadout` —
|
badge, the readout well (ELAPSED / REMAIN to tenths, KEY, and `BpmReadout` —
|
||||||
click to type an exact BPM; with no grid, a typed or tapped BPM CREATES one at the playhead, and
|
click to type an exact BPM; with no grid, a typed or tapped BPM CREATES one at the playhead, and
|
||||||
Set grid on a track with no BPM opens the readout to ask rather than failing), SNAP, Analyze, Auto hotcues. **Waveforms**:
|
Set grid on a track with no BPM opens the readout to ask rather than failing), SNAP, Analyze, Auto hotcues. **Waveforms**:
|
||||||
`MainWaveform` (scrolling; zoom +/− in its corner and Cmd/Ctrl+scroll, owned
|
`MainWaveform` (scrolling; zoom +/− in its corner and Cmd/Ctrl+scroll,
|
||||||
by `PrepStrip` so it survives track switches and persists) over
|
0.25–64 s across, owned by `PrepStrip` so it survives track switches and
|
||||||
|
persists; a toggle under the zoom buttons draws the RAW signal instead
|
||||||
|
of bars — `lib/rawWave.ts`, below; persisted as `mainWaveRaw`) over
|
||||||
`OverviewWaveform`, which frames the main view's visible range around the
|
`OverviewWaveform`, which frames the main view's visible range around the
|
||||||
playhead (it takes `secPerView` for exactly that). **Controls**: play, CUE, `LoopControls`, then EITHER
|
playhead (it takes `secPerView` for exactly that). **Controls**: play, CUE, `LoopControls`, then EITHER
|
||||||
`HotcueBar` OR — in **Grid mode** — `GridEditStrip`, then `TempoControls`
|
`HotcueBar` OR — in **Grid mode** — `GridEditStrip`, then `TempoControls`
|
||||||
@@ -2166,6 +2168,38 @@ The prep strip plays every track through the **Web Audio API** (a plain
|
|||||||
full scale for whole sections, so a linear map draws a solid orange wall
|
full scale for whole sections, so a linear map draws a solid orange wall
|
||||||
instead of the kick pulse. The main view draws 2 px bars with a 1 px gap,
|
instead of the kick pulse. The main view draws 2 px bars with a 1 px gap,
|
||||||
**binned in track space** so bars scroll rather than flicker.
|
**binned in track space** so bars scroll rather than flicker.
|
||||||
|
- `rawWave.ts` — **the raw waveform** (decided 2026-10-15,
|
||||||
|
[the discussion](.claude/discussions/discuss-raw-waveform-2026-10-15.md)):
|
||||||
|
the bars' ~7 ms columns of unsigned band energy hide where a kick starts, so
|
||||||
|
the main view can draw the signal itself as a thin line, after Traktor at
|
||||||
|
full zoom. Its own toggle (under the zoom buttons), NOT tied to Grid mode —
|
||||||
|
tried first, changed after use.
|
||||||
|
**Shape exact, colour approximate**: the tint is the bar palette weighted by
|
||||||
|
the ~7 ms band columns, lerped, mixed in OKLab with the CHROMA restored
|
||||||
|
(`bandColour`) — a plain RGB mean of orange/violet/cyan lands near grey and
|
||||||
|
read as mud; chosen from five variants rendered on real tracks; the scale is fixed by the track's loudest
|
||||||
|
sample (no per-view gain, so nothing pumps while scrolling). Each pixel is a
|
||||||
|
min→max stroke stretched to touch its neighbour's, so it reads as an
|
||||||
|
envelope zoomed out and a line zoomed in with no switch-over. Data: min/max
|
||||||
|
per 32 samples summarised at load (~4 MB / 6 min) for wide views; below 128
|
||||||
|
samples a pixel, the visible window read straight from the `AudioBuffer`
|
||||||
|
(`copyFromChannel` — no full-length mono copy). Bins sit on a track-space
|
||||||
|
grid like the bars'. A stem track's lanes each draw their own raw line, in
|
||||||
|
the stem's colour, each at its own peak floored at 5% of the loudest.
|
||||||
|
Measured in WKWebView: 0.3 ms a frame at 0.25 s, ~5 ms at 64 s.
|
||||||
|
- `decodeAlign.ts` — **the deck's decode vs the grid's time base.** Positions
|
||||||
|
are in the backend's PyAV decode; the deck decodes with `decodeAudioData`.
|
||||||
|
Measured 2026-10-15 with click files: identical on every format and engine
|
||||||
|
EXCEPT a **header-less MP3 under WebKit** (the macOS app), decoded 529
|
||||||
|
samples (12 ms) EARLY — CoreAudio trims the decoder delay with no header to
|
||||||
|
say so; FFmpeg (and Chromium/WebView2) do not. Invisible under bars, a
|
||||||
|
12 ms miss on the raw line. The engine's offset is MEASURED once per session
|
||||||
|
by decoding a built-in 2.7 KB header-less MP3 (`decodeProbe.ts`, click at a
|
||||||
|
known FFmpeg sample), and a header-less MP3's buffer (`mp3HeaderFrame`, a
|
||||||
|
port of `core/mp3_gapless.parse` behind an is-it-an-MP3 gate) is padded by
|
||||||
|
it in `decodeUrl` — so playback, scratch and both waveforms move together.
|
||||||
|
Not measured: a header without a trusted encoder-delay field; Edge on a real
|
||||||
|
Windows machine (Chromium on macOS matched).
|
||||||
- `cues.ts` — canvas drawers for cue markers (type-colored), the active loop
|
- `cues.ts` — canvas drawers for cue markers (type-colored), the active loop
|
||||||
band, the beatgrid (per-segment white beats/brighter downbeats, plus marker
|
band, the beatgrid (per-segment white beats/brighter downbeats, plus marker
|
||||||
lines — gold for the one governing the playhead, accent otherwise, with the
|
lines — gold for the one governing the playhead, accent otherwise, with the
|
||||||
|
|||||||
@@ -1,11 +1,19 @@
|
|||||||
import { useEffect, useRef } from 'react'
|
import { useEffect, useRef } from 'react'
|
||||||
import type { CuePoint } from '../api'
|
import type { CuePoint } from '../api'
|
||||||
import type { BeatGrid } from '../lib/beatgrid'
|
import type { BeatGrid } from '../lib/beatgrid'
|
||||||
|
import { Icon } from '../lib/icons'
|
||||||
import { drawBeatgrid, drawCuePoint, drawCues, drawLoop, drawLoopIn, drawPlayhead } from '../lib/cues'
|
import { drawBeatgrid, drawCuePoint, drawCues, drawLoop, drawLoopIn, drawPlayhead } from '../lib/cues'
|
||||||
|
import { laneScales, makeSpans, paintRaw, rawSpans, tintAt, type RawWave } from '../lib/rawWave'
|
||||||
import { paintLane, paintWave, type WaveColumn } from '../lib/waveform'
|
import { paintLane, paintWave, type WaveColumn } from '../lib/waveform'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
cols: WaveColumn[]
|
cols: WaveColumn[]
|
||||||
|
/** The samples, for the raw view. */
|
||||||
|
raw?: RawWave | null
|
||||||
|
/** Draw the raw signal as a thin line instead of bars (the toggle under
|
||||||
|
the zoom buttons; owned by the parent, which persists it). */
|
||||||
|
rawMode?: boolean
|
||||||
|
onRawModeChange?: (raw: boolean) => void
|
||||||
currentTime: number
|
currentTime: number
|
||||||
duration: number
|
duration: number
|
||||||
cues: CuePoint[]
|
cues: CuePoint[]
|
||||||
@@ -36,6 +44,8 @@ interface Props {
|
|||||||
|
|
||||||
export interface StemLane {
|
export interface StemLane {
|
||||||
data: Float32Array
|
data: Float32Array
|
||||||
|
/** The stem's samples, for the raw view. */
|
||||||
|
raw?: RawWave | null
|
||||||
name: string
|
name: string
|
||||||
color: string
|
color: string
|
||||||
/** Not muted. */
|
/** Not muted. */
|
||||||
@@ -50,7 +60,7 @@ const ALT = typeof navigator !== 'undefined' && /Mac/.test(navigator.platform) ?
|
|||||||
|
|
||||||
const DRAG_THRESHOLD = 3 // px before a press becomes a scratch (vs a click-seek)
|
const DRAG_THRESHOLD = 3 // px before a press becomes a scratch (vs a click-seek)
|
||||||
|
|
||||||
export const MIN_SEC = 2 // most zoomed-in (seconds across the view)
|
export const MIN_SEC = 0.25 // most zoomed-in (seconds across the view): a kick's attack spans dozens of px
|
||||||
export const MAX_SEC = 64 // most zoomed-out
|
export const MAX_SEC = 64 // most zoomed-out
|
||||||
export const DEFAULT_SEC = 16
|
export const DEFAULT_SEC = 16
|
||||||
|
|
||||||
@@ -62,6 +72,9 @@ export const DEFAULT_SEC = 16
|
|||||||
*/
|
*/
|
||||||
export function MainWaveform({
|
export function MainWaveform({
|
||||||
cols,
|
cols,
|
||||||
|
raw = null,
|
||||||
|
rawMode = false,
|
||||||
|
onRawModeChange,
|
||||||
currentTime,
|
currentTime,
|
||||||
duration,
|
duration,
|
||||||
cues,
|
cues,
|
||||||
@@ -89,6 +102,7 @@ export function MainWaveform({
|
|||||||
const dragRef = useRef<{ startX: number; startTime: number; lastT: number; moved: boolean } | null>(
|
const dragRef = useRef<{ startX: number; startTime: number; lastT: number; moved: boolean } | null>(
|
||||||
null,
|
null,
|
||||||
)
|
)
|
||||||
|
const spansRef = useRef(makeSpans())
|
||||||
|
|
||||||
// Draw closes over the latest props/state; a ref lets the ResizeObserver call
|
// Draw closes over the latest props/state; a ref lets the ResizeObserver call
|
||||||
// the current version without re-subscribing.
|
// the current version without re-subscribing.
|
||||||
@@ -111,7 +125,25 @@ export function MainWaveform({
|
|||||||
// 2 px bars with a 1 px gap: the texture that makes the scrolling view
|
// 2 px bars with a 1 px gap: the texture that makes the scrolling view
|
||||||
// read as discrete energy rather than a smear.
|
// read as discrete energy rather than a smear.
|
||||||
const bars = { bar: Math.max(1, Math.round(2 * dpr)), gap: Math.max(1, Math.round(dpr)) }
|
const bars = { bar: Math.max(1, Math.round(2 * dpr)), gap: Math.max(1, Math.round(dpr)) }
|
||||||
if (lanes && lanes.length) {
|
// The raw line's minimum stroke, so silence and flat stretches still read.
|
||||||
|
const thick = Math.max(1, 1.25 * dpr)
|
||||||
|
const spans = spansRef.current
|
||||||
|
if (rawMode && lanes && lanes.length && lanes.every((l) => l.raw)) {
|
||||||
|
const laneH = h / lanes.length
|
||||||
|
const scales = laneScales(lanes.map((l) => l.raw!.peak), laneH / 2 - thick)
|
||||||
|
lanes.forEach((lane, k) => {
|
||||||
|
rawSpans(lane.raw!, startSec, endSec, w, spans)
|
||||||
|
ctx.globalAlpha = lane.audible ? 0.92 : 0.18
|
||||||
|
paintRaw(ctx, spans, k * laneH, laneH, scales[k], thick, lane.color)
|
||||||
|
})
|
||||||
|
ctx.globalAlpha = 1
|
||||||
|
ctx.fillStyle = 'rgba(255,255,255,0.06)'
|
||||||
|
for (let k = 1; k < lanes.length; k++) ctx.fillRect(0, Math.round(k * laneH), w, Math.max(1, Math.round(dpr)))
|
||||||
|
} else if (rawMode && !lanes?.length && raw) {
|
||||||
|
rawSpans(raw, startSec, endSec, w, spans)
|
||||||
|
const scale = (h / 2 - thick) / Math.max(raw.peak, 1e-6)
|
||||||
|
paintRaw(ctx, spans, 0, h, scale, thick, (t) => tintAt(cols, duration, t))
|
||||||
|
} else if (lanes && lanes.length) {
|
||||||
// Stem lanes, Traktor-style: each stem its own strip in its own colour.
|
// Stem lanes, Traktor-style: each stem its own strip in its own colour.
|
||||||
const laneH = h / lanes.length
|
const laneH = h / lanes.length
|
||||||
lanes.forEach((lane, k) => {
|
lanes.forEach((lane, k) => {
|
||||||
@@ -263,9 +295,10 @@ export function MainWaveform({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Zoom controls (Traktor-style +/-). stopPropagation on down so tapping a
|
{/* Zoom in · raw/bars · zoom out, centred on the waveform's height.
|
||||||
button doesn't begin a scratch drag. */}
|
stopPropagation on down so tapping a button doesn't begin a scratch
|
||||||
<div className="absolute right-2 top-2 flex flex-col gap-1">
|
drag. */}
|
||||||
|
<div className="absolute right-2 top-1/2 flex -translate-y-1/2 flex-col gap-1">
|
||||||
<button
|
<button
|
||||||
onPointerDown={(e) => e.stopPropagation()}
|
onPointerDown={(e) => e.stopPropagation()}
|
||||||
onClick={zoomIn}
|
onClick={zoomIn}
|
||||||
@@ -275,6 +308,17 @@ export function MainWaveform({
|
|||||||
>
|
>
|
||||||
+
|
+
|
||||||
</button>
|
</button>
|
||||||
|
<button
|
||||||
|
onPointerDown={(e) => e.stopPropagation()}
|
||||||
|
onClick={() => onRawModeChange?.(!rawMode)}
|
||||||
|
aria-pressed={rawMode}
|
||||||
|
aria-label="Raw waveform"
|
||||||
|
className="btn-glass flex h-6 w-6 items-center justify-center rounded-lg text-text backdrop-blur-md"
|
||||||
|
title={rawMode ? 'Raw waveform — click for bars' : 'Bars — click for the raw waveform: the exact shape of every transient'}
|
||||||
|
>
|
||||||
|
{/* The icon shows the mode in force: bars, or the raw line. */}
|
||||||
|
<Icon name={rawMode ? 'sine' : 'wave'} size={14} />
|
||||||
|
</button>
|
||||||
<button
|
<button
|
||||||
onPointerDown={(e) => e.stopPropagation()}
|
onPointerDown={(e) => e.stopPropagation()}
|
||||||
onClick={zoomOut}
|
onClick={zoomOut}
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import { CUE_TYPE_LABELS, cueTypeColor } from '../lib/cues'
|
|||||||
import { keyColor } from '../lib/format'
|
import { keyColor } from '../lib/format'
|
||||||
import { readOnlyShort, readOnlyNotice } from '../lib/platformCopy'
|
import { readOnlyShort, readOnlyNotice } from '../lib/platformCopy'
|
||||||
import { analyzeStems, analyzeWaveform, type WaveColumn } from '../lib/waveform'
|
import { analyzeStems, analyzeWaveform, type WaveColumn } from '../lib/waveform'
|
||||||
|
import type { RawWave } from '../lib/rawWave'
|
||||||
import { setAmbientFromArt } from '../lib/ambient'
|
import { setAmbientFromArt } from '../lib/ambient'
|
||||||
import { Icon } from '../lib/icons'
|
import { Icon } from '../lib/icons'
|
||||||
import { ScratchEngine } from '../lib/scratchEngine'
|
import { ScratchEngine } from '../lib/scratchEngine'
|
||||||
@@ -114,6 +115,9 @@ export function PrepStrip({
|
|||||||
const [duration, setDuration] = useState(0)
|
const [duration, setDuration] = useState(0)
|
||||||
const [ready, setReady] = useState(false)
|
const [ready, setReady] = useState(false)
|
||||||
const [cols, setCols] = useState<WaveColumn[] | null>(null)
|
const [cols, setCols] = useState<WaveColumn[] | null>(null)
|
||||||
|
// The raw waveform's data: the mix's samples, or one per stem lane.
|
||||||
|
const [raw, setRaw] = useState<RawWave | null>(null)
|
||||||
|
const [stemRaws, setStemRaws] = useState<RawWave[] | null>(null)
|
||||||
// A stem track: its stems (from the FILE), their lanes, and which are muted
|
// A stem track: its stems (from the FILE), their lanes, and which are muted
|
||||||
// — reset per track, as Traktor's stem deck does. There is no separate solo
|
// — reset per track, as Traktor's stem deck does. There is no separate solo
|
||||||
// state: solo is a shortcut that SETS the mutes, so every stem stays freely
|
// state: solo is a shortcut that SETS the mutes, so every stem stays freely
|
||||||
@@ -130,6 +134,7 @@ export function PrepStrip({
|
|||||||
const [selectedSlot, setSelectedSlot] = useState<number | null>(null)
|
const [selectedSlot, setSelectedSlot] = useState<number | null>(null)
|
||||||
const [cuePoint, setCuePoint] = useState(0) // floating "CUE" point (frontend-only)
|
const [cuePoint, setCuePoint] = useState(0) // floating "CUE" point (frontend-only)
|
||||||
const [secPerView, setSecPerView] = useState(DEFAULT_SEC) // main-waveform zoom (persisted)
|
const [secPerView, setSecPerView] = useState(DEFAULT_SEC) // main-waveform zoom (persisted)
|
||||||
|
const [rawWave, setRawWave] = useState(false) // main waveform: raw line instead of bars (persisted)
|
||||||
// ONE size, in beats, for beat loops and beat jump alike (persisted).
|
// ONE size, in beats, for beat loops and beat jump alike (persisted).
|
||||||
const [beatSize, setBeatSize] = useState(4)
|
const [beatSize, setBeatSize] = useState(4)
|
||||||
const [loopMode, setLoopMode] = useState<LoopMode>('beat')
|
const [loopMode, setLoopMode] = useState<LoopMode>('beat')
|
||||||
@@ -164,7 +169,7 @@ export function PrepStrip({
|
|||||||
|
|
||||||
const trackId = track?.id ?? null
|
const trackId = track?.id ?? null
|
||||||
|
|
||||||
// Main-waveform zoom persists to userprefs.json so it survives track switches
|
// Main-waveform zoom (and the raw/bars toggle) persists to userprefs.json so it survives track switches
|
||||||
// (MainWaveform unmounts during each load) and app restarts. Hydrate once from
|
// (MainWaveform unmounts during each load) and app restarts. Hydrate once from
|
||||||
// the shared ['prefs'] query, then persist changes through the shared,
|
// the shared ['prefs'] query, then persist changes through the shared,
|
||||||
// debounced prefs writer (as App's column layout does).
|
// debounced prefs writer (as App's column layout does).
|
||||||
@@ -178,11 +183,12 @@ export function PrepStrip({
|
|||||||
if (typeof z === 'number' && isFinite(z)) {
|
if (typeof z === 'number' && isFinite(z)) {
|
||||||
setSecPerView(Math.min(MAX_SEC, Math.max(MIN_SEC, z)))
|
setSecPerView(Math.min(MAX_SEC, Math.max(MIN_SEC, z)))
|
||||||
}
|
}
|
||||||
|
if ((prefsQuery.data as { mainWaveRaw?: unknown }).mainWaveRaw === true) setRawWave(true)
|
||||||
}, [prefsQuery.data])
|
}, [prefsQuery.data])
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!zoomHydratedRef.current) return // don't clobber saved prefs pre-hydration
|
if (!zoomHydratedRef.current) return // don't clobber saved prefs pre-hydration
|
||||||
writePrefs({ mainZoomSec: secPerView })
|
writePrefs({ mainZoomSec: secPerView, mainWaveRaw: rawWave })
|
||||||
}, [secPerView, writePrefs])
|
}, [secPerView, rawWave, writePrefs])
|
||||||
|
|
||||||
// The loop/jump size persists the same way (survives track switches +
|
// The loop/jump size persists the same way (survives track switches +
|
||||||
// restarts). `beatJumpBeats` is its name from when only beat jump had a size;
|
// restarts). `beatJumpBeats` is its name from when only beat jump had a size;
|
||||||
@@ -271,11 +277,15 @@ export function PrepStrip({
|
|||||||
scratchRef.current = null
|
scratchRef.current = null
|
||||||
if (!trackId) {
|
if (!trackId) {
|
||||||
setCols(null)
|
setCols(null)
|
||||||
|
setRaw(null)
|
||||||
|
setStemRaws(null)
|
||||||
setWaveStatus('loading')
|
setWaveStatus('loading')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
let cancelled = false
|
let cancelled = false
|
||||||
setCols(null)
|
setCols(null)
|
||||||
|
setRaw(null)
|
||||||
|
setStemRaws(null)
|
||||||
setStems(null)
|
setStems(null)
|
||||||
setStemLanes(null)
|
setStemLanes(null)
|
||||||
setWaveStatus('loading')
|
setWaveStatus('loading')
|
||||||
@@ -286,15 +296,17 @@ export function PrepStrip({
|
|||||||
.then(async (found) => {
|
.then(async (found) => {
|
||||||
if (found.length) {
|
if (found.length) {
|
||||||
const res = await analyzeStems(found.map((_, k) => trackStemUrl(origin, trackId, k)))
|
const res = await analyzeStems(found.map((_, k) => trackStemUrl(origin, trackId, k)))
|
||||||
return { cols: res.cols, buffers: res.buffers, lanes: res.lanes, stems: found }
|
return { cols: res.cols, buffers: res.buffers, lanes: res.lanes, stems: found, raw: null, raws: res.raws }
|
||||||
}
|
}
|
||||||
const res = await analyzeWaveform(trackAudioUrl(origin, trackId))
|
const res = await analyzeWaveform(trackAudioUrl(origin, trackId))
|
||||||
return { cols: res.cols, buffers: [res.buffer], lanes: null, stems: null }
|
return { cols: res.cols, buffers: [res.buffer], lanes: null, stems: null, raw: res.raw, raws: null }
|
||||||
})
|
})
|
||||||
load
|
load
|
||||||
.then((res) => {
|
.then((res) => {
|
||||||
if (cancelled) return
|
if (cancelled) return
|
||||||
setCols(res.cols)
|
setCols(res.cols)
|
||||||
|
setRaw(res.raw)
|
||||||
|
setStemRaws(res.raws)
|
||||||
setStems(res.stems)
|
setStems(res.stems)
|
||||||
setStemLanes(res.lanes)
|
setStemLanes(res.lanes)
|
||||||
setWaveStatus('ready')
|
setWaveStatus('ready')
|
||||||
@@ -917,7 +929,9 @@ export function PrepStrip({
|
|||||||
const activeMarkerIndex = grid ? grid.markerIndexAt(current) : -1
|
const activeMarkerIndex = grid ? grid.markerIndexAt(current) : -1
|
||||||
const activeMarker = activeMarkerIndex >= 0 ? grid!.markers[activeMarkerIndex] : null
|
const activeMarker = activeMarkerIndex >= 0 ? grid!.markers[activeMarkerIndex] : null
|
||||||
// ~4px of the current zoom, so "on the marker" stays usable at 2s and 64s/view.
|
// ~4px of the current zoom, so "on the marker" stays usable at 2s and 64s/view.
|
||||||
const markerHitSec = Math.max(0.01, secPerView / 250)
|
// ~4 px of the view either side, so "at a marker" stays a marker-sized
|
||||||
|
// target at deep zoom instead of 4% of a 0.25 s view.
|
||||||
|
const markerHitSec = Math.max(0.001, secPerView / 250)
|
||||||
const atMarker = !!grid && grid.isOnMarker(current, markerHitSec)
|
const atMarker = !!grid && grid.isOnMarker(current, markerHitSec)
|
||||||
const beforeFirstMarker = !!grid && current < grid.markers[0].start - GRID_EPS
|
const beforeFirstMarker = !!grid && current < grid.markers[0].start - GRID_EPS
|
||||||
|
|
||||||
@@ -1097,6 +1111,7 @@ export function PrepStrip({
|
|||||||
stems && stemLanes
|
stems && stemLanes
|
||||||
? stems.map((st, k) => ({
|
? stems.map((st, k) => ({
|
||||||
data: stemLanes[k],
|
data: stemLanes[k],
|
||||||
|
raw: stemRaws?.[k] ?? null,
|
||||||
name: st.name,
|
name: st.name,
|
||||||
color: st.color,
|
color: st.color,
|
||||||
audible: stemLevels[k] > 0,
|
audible: stemLevels[k] > 0,
|
||||||
@@ -1390,6 +1405,9 @@ export function PrepStrip({
|
|||||||
{showWaves ? (
|
{showWaves ? (
|
||||||
<MainWaveform
|
<MainWaveform
|
||||||
cols={cols}
|
cols={cols}
|
||||||
|
raw={raw}
|
||||||
|
rawMode={rawWave}
|
||||||
|
onRawModeChange={setRawWave}
|
||||||
currentTime={current}
|
currentTime={current}
|
||||||
duration={duration}
|
duration={duration}
|
||||||
cues={cueData?.cues ?? []}
|
cues={cueData?.cues ?? []}
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
|
||||||
|
import { alignShift, mp3HeaderFrame } from './decodeAlign'
|
||||||
|
import { PROBE_MP3_BASE64 } from './decodeProbe'
|
||||||
|
|
||||||
|
/** A stereo MPEG-1 Layer III frame header (128 kbps, 44.1 kHz) followed by
|
||||||
|
* `tag` where a Xing/Info tag would sit, padded to 64 bytes. */
|
||||||
|
function frame(tag = '') {
|
||||||
|
const b = new Uint8Array(64)
|
||||||
|
b.set([0xff, 0xfb, 0x90, 0x00])
|
||||||
|
for (let i = 0; i < tag.length; i++) b[4 + 32 + i] = tag.charCodeAt(i)
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
function withId3(body: Uint8Array, size = 1000) {
|
||||||
|
const out = new Uint8Array(10 + size + body.length)
|
||||||
|
out.set([0x49, 0x44, 0x33, 4, 0, 0])
|
||||||
|
out.set([(size >> 21) & 127, (size >> 14) & 127, (size >> 7) & 127, size & 127], 6)
|
||||||
|
out.set(body, 10 + size)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('mp3HeaderFrame', () => {
|
||||||
|
it('sees a Xing / Info header, after an ID3 tag too', () => {
|
||||||
|
expect(mp3HeaderFrame(frame('Xing'))).toBe(true)
|
||||||
|
expect(mp3HeaderFrame(withId3(frame('Info'), 200_000))).toBe(true)
|
||||||
|
})
|
||||||
|
it('sees an MP3 without one', () => {
|
||||||
|
expect(mp3HeaderFrame(frame())).toBe(false)
|
||||||
|
expect(mp3HeaderFrame(withId3(frame()))).toBe(false)
|
||||||
|
})
|
||||||
|
it('reads the built-in probe as header-less', () => {
|
||||||
|
const bytes = Uint8Array.from(atob(PROBE_MP3_BASE64), (c) => c.charCodeAt(0))
|
||||||
|
expect(mp3HeaderFrame(bytes)).toBe(false)
|
||||||
|
})
|
||||||
|
it('is not fooled by a frame sync inside another format', () => {
|
||||||
|
const m4a = new Uint8Array(96)
|
||||||
|
m4a.set([0, 0, 0, 0x20, 0x66, 0x74, 0x79, 0x70]) // ....ftyp
|
||||||
|
m4a.set(frame(), 16)
|
||||||
|
expect(mp3HeaderFrame(m4a)).toBeNull()
|
||||||
|
const flac = withId3(new Uint8Array([0x66, 0x4c, 0x61, 0x43, ...frame()])) // ID3 + fLaC
|
||||||
|
expect(mp3HeaderFrame(flac)).toBeNull()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('alignShift', () => {
|
||||||
|
it("prepends what this engine trimmed, only on a header-less MP3", () => {
|
||||||
|
// WebKit measured 529 samples early at 44.1 kHz.
|
||||||
|
const early = -529 / 44100
|
||||||
|
expect(alignShift(false, early, 44100)).toBe(529)
|
||||||
|
expect(alignShift(false, early, 48000)).toBe(Math.round(529 * 48000 / 44100))
|
||||||
|
expect(alignShift(true, early, 44100)).toBe(0)
|
||||||
|
expect(alignShift(null, early, 44100)).toBe(0)
|
||||||
|
expect(alignShift(false, 0, 44100)).toBe(0)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
// The deck decodes audio in the BROWSER (decodeAudioData), while every stored
|
||||||
|
// position — grids, cues — is in the backend's decoded time base (PyAV/FFmpeg,
|
||||||
|
// `core/waveform.load`). Measured 2026-10-15 with click files: the two agree to
|
||||||
|
// the sample on every format EXCEPT a header-less MP3 under WebKit (the macOS
|
||||||
|
// app's WKWebView), which decodes 529 samples (12 ms) EARLY — CoreAudio trims
|
||||||
|
// the MP3 decoder delay even when no Xing/Info header says to, FFmpeg trims
|
||||||
|
// nothing. Chromium (WebView2) matches FFmpeg. Invisible under 7 ms bars, but
|
||||||
|
// the raw waveform would draw every beat line 12 ms off its kick.
|
||||||
|
//
|
||||||
|
// Rather than hard-code WebKit's number, this engine's offset is MEASURED once,
|
||||||
|
// by decoding a tiny built-in header-less MP3 (`decodeProbe.ts`) whose click
|
||||||
|
// FFmpeg places at a known sample, and a header-less MP3's decoded buffer is
|
||||||
|
// shifted by it — so playback, scratch and both waveforms share the grid's
|
||||||
|
// clock. An MP3 WITH a header was measured to agree on both engines and is
|
||||||
|
// never touched.
|
||||||
|
|
||||||
|
import { PROBE_MP3_BASE64, PROBE_ONSET, PROBE_RATE } from './decodeProbe'
|
||||||
|
|
||||||
|
/** How far past the ID3 tag to look for the first frame (junk, padding). */
|
||||||
|
const SCAN = 64 * 1024
|
||||||
|
|
||||||
|
interface Frame {
|
||||||
|
mpeg1: boolean
|
||||||
|
mono: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A Layer III frame header at `i`, or null. The backend's
|
||||||
|
* `core/mp3_gapless._frame_header`, kept in step with it. */
|
||||||
|
function frameHeader(b: Uint8Array, i: number): Frame | null {
|
||||||
|
if (i + 4 > b.length || b[i] !== 0xff || (b[i + 1] & 0xe0) !== 0xe0) return null
|
||||||
|
const version = (b[i + 1] >> 3) & 3
|
||||||
|
const layer = (b[i + 1] >> 1) & 3
|
||||||
|
const bitrate = b[i + 2] >> 4
|
||||||
|
const rate = (b[i + 2] >> 2) & 3
|
||||||
|
if (version === 1 || layer !== 1 || bitrate === 0 || bitrate === 15 || rate === 3) return null
|
||||||
|
return { mpeg1: version === 3, mono: b[i + 3] >> 6 === 3 }
|
||||||
|
}
|
||||||
|
|
||||||
|
const ascii = (b: Uint8Array, i: number, n: number) => String.fromCharCode(...b.subarray(i, i + n))
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether `bytes` is an MP3 whose first frame is a Xing / Info / VBRI header
|
||||||
|
* (true), an MP3 without one (false), or not an MP3 at all (null). The header
|
||||||
|
* test is the backend's `core/mp3_gapless.parse`; the "is it an MP3" gate is
|
||||||
|
* extra, because this sees every format the deck plays and a stray frame sync
|
||||||
|
* inside an M4A or FLAC must not count. An MP3 starts with an ID3v2 tag or with
|
||||||
|
* a frame — nothing else this app plays does (FLAC, RIFF, ftyp, FORM, OggS).
|
||||||
|
*/
|
||||||
|
export function mp3HeaderFrame(b: Uint8Array): boolean | null {
|
||||||
|
let start = 0
|
||||||
|
if (b.length >= 10 && b[0] === 0x49 && b[1] === 0x44 && b[2] === 0x33) {
|
||||||
|
const size = ((b[6] & 127) << 21) | ((b[7] & 127) << 14) | ((b[8] & 127) << 7) | (b[9] & 127)
|
||||||
|
start = 10 + size + (b[5] & 0x10 ? 10 : 0)
|
||||||
|
if (ascii(b, start, 4) === 'fLaC') return null // a FLAC carrying a (non-standard) ID3 tag
|
||||||
|
} else if (!frameHeader(b, 0)) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
const end = Math.min(b.length - 4, start + SCAN)
|
||||||
|
for (let i = start; i < end; i++) {
|
||||||
|
const h = frameHeader(b, i)
|
||||||
|
if (!h) continue
|
||||||
|
const side = h.mpeg1 ? (h.mono ? 17 : 32) : h.mono ? 9 : 17
|
||||||
|
const tag = ascii(b, i + 4 + side, 4)
|
||||||
|
if (tag === 'Xing' || tag === 'Info') return true
|
||||||
|
return ascii(b, i + 36, 4) === 'VBRI'
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The first sample of the probe's click (a quarter of its peak), or -1. */
|
||||||
|
function clickOnset(buf: AudioBuffer): number {
|
||||||
|
const d = new Float32Array(buf.length)
|
||||||
|
buf.copyFromChannel(d, 0)
|
||||||
|
let peak = 0
|
||||||
|
for (let i = 0; i < d.length; i++) peak = Math.max(peak, Math.abs(d[i]))
|
||||||
|
if (peak <= 0) return -1
|
||||||
|
for (let i = 0; i < d.length; i++) if (Math.abs(d[i]) > peak * 0.25) return i
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
|
||||||
|
async function measure(): Promise<number> {
|
||||||
|
const bytes = Uint8Array.from(atob(PROBE_MP3_BASE64), (c) => c.charCodeAt(0))
|
||||||
|
const buf = await new OfflineAudioContext(1, 1, PROBE_RATE).decodeAudioData(bytes.buffer)
|
||||||
|
const onset = clickOnset(buf)
|
||||||
|
// An onset nowhere near the click means the probe did not decode sensibly;
|
||||||
|
// shifting by it would be worse than the 12 ms it exists to fix.
|
||||||
|
if (onset < 0 || Math.abs(onset - PROBE_ONSET) > 4096) return 0
|
||||||
|
return (onset - PROBE_ONSET) / PROBE_RATE
|
||||||
|
}
|
||||||
|
|
||||||
|
let offset: Promise<number> | null = null
|
||||||
|
|
||||||
|
/** Seconds by which this engine decodes a header-less MP3 AHEAD of FFmpeg
|
||||||
|
* (negative = its audio starts earlier). Measured once per session; 0 if the
|
||||||
|
* probe cannot be decoded. */
|
||||||
|
export function headerlessMp3Offset(): Promise<number> {
|
||||||
|
return (offset ??= measure().catch(() => 0))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Samples to PREPEND (negative: drop from the start) to a buffer this engine
|
||||||
|
* decoded, to put it in the backend's time base. `header` is
|
||||||
|
* `mp3HeaderFrame` of the file's bytes, read before decoding detaches them.
|
||||||
|
*/
|
||||||
|
export function alignShift(header: boolean | null, offsetSec: number, sampleRate: number): number {
|
||||||
|
return header === false ? Math.round(-offsetSec * sampleRate) || 0 : 0
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `buffer`, decoded by this engine from a file whose `mp3HeaderFrame` is
|
||||||
|
* `header`, moved into the backend's time base (the same buffer if no move). */
|
||||||
|
export async function alignDecoded(buffer: AudioBuffer, header: boolean | null): Promise<AudioBuffer> {
|
||||||
|
if (header !== false) return buffer
|
||||||
|
const shift = alignShift(header, await headerlessMp3Offset(), buffer.sampleRate)
|
||||||
|
if (shift === 0) return buffer
|
||||||
|
const out = new AudioBuffer({
|
||||||
|
length: Math.max(1, buffer.length + shift),
|
||||||
|
numberOfChannels: buffer.numberOfChannels,
|
||||||
|
sampleRate: buffer.sampleRate,
|
||||||
|
})
|
||||||
|
// copyFromChannel, never getChannelData: see the detach gotcha in scratchEngine.
|
||||||
|
const tmp = new Float32Array(buffer.length)
|
||||||
|
for (let c = 0; c < buffer.numberOfChannels; c++) {
|
||||||
|
buffer.copyFromChannel(tmp, c)
|
||||||
|
if (shift > 0) out.copyToChannel(tmp, c, shift)
|
||||||
|
else out.copyToChannel(tmp.subarray(-shift), c, 0)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
// A 0.3 s mono 44.1 kHz MP3, 64 kbps, encoded by LAME (via FFmpeg) WITHOUT a
|
||||||
|
// Xing/Info header: silence with a 64-sample click at 0.1 s. FFmpeg decodes the
|
||||||
|
// click at sample PROBE_ONSET — 4410 + 1105 samples of start padding it does not
|
||||||
|
// trim, having no header to say how much. See decodeAlign.ts for its use.
|
||||||
|
|
||||||
|
export const PROBE_RATE = 44100
|
||||||
|
export const PROBE_ONSET = 5515
|
||||||
|
|
||||||
|
export const PROBE_MP3_BASE64 =
|
||||||
|
'SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjYyLjEyLjEwMgAAAAAAAAAAAAAA//tQxAADwAABpAAAACAAADSAAAAETEFNRTMu' +
|
||||||
|
'MTAwVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUxBTUUzLjEwMFVVVVVVVVVVVVVVVVVVVVVV' +
|
||||||
|
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||||
|
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVf/7UsRdg8AAAaQAAAAgAAA0gAAABFVVVVVVVVVVVVVVVVVV' +
|
||||||
|
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVKKKKKKKKKKKK/wgdhBp1G6J/rUrOW2H/vW0ArmeSx1nA' +
|
||||||
|
'Bvz47A8DIdw8/5YO8PZPH0bThO/80JBY9Meh+aUjp//Pzew4xQdy9kn//pM3PsNDizVDyVt///emf4ZFaJ2FDa5NVv///e+2' +
|
||||||
|
'MY972MpJd0tRpyR7////9nNzexlPfbGTJrUG12ih//tSxKGDwAABpAAAACAAADSAAAAElGgywARRdQUoCyGCWFuOpvQ2OnTR' +
|
||||||
|
'OlxYmJXK7DgEFJORBQDTkSM5RIlIiBoeCodWCrlgrLA0oGoKhsShosDTgaeJQ3yzvEUqCqw1ER4seWCvUHP/qBrlTvBpTEFN' +
|
||||||
|
'RTMuMTAwVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||||
|
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVX/+1LEoYPAAAGkAAAAIAAANIKAAARVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||||
|
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUxBTUUzLjEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||||
|
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||||
|
'VVVVVVVVVVVVVVVVVVVVVf/7UsT/gBEVjXM5lYAZYIlno55gAFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||||
|
'VVVVVVVVVVVVVVVVVVVVVVVVTEFNRTMuMTAwVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||||
|
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||||
|
'VVVVVVVVVVVV//tSxKGDwAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||||
|
'VVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||||
|
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||||
|
'VVX/+1LEoYPAAAGkAAAAIAAANIAAAARVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||||
|
'VVVVVUxBTUUzLjEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||||
|
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVf/7UsSh' +
|
||||||
|
'g8AAAaQAAAAgAAA0gAAABFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVTEFN' +
|
||||||
|
'RTMuMTAwVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||||
|
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//tSxKGDwAABpAAA' +
|
||||||
|
'ACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBV' +
|
||||||
|
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||||
|
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVX/+1LEoYPAAAGkAAAAIAAANIAA' +
|
||||||
|
'AARVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUxBTUUzLjEwMFVVVVVVVVVV' +
|
||||||
|
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||||
|
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVf/7UsShg8AAAaQAAAAgAAA0gAAABFVVVVVV' +
|
||||||
|
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVTEFNRTMuMTAwVVVVVVVVVVVVVVVVVVVV' +
|
||||||
|
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||||
|
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//tSxKGDwAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVV' +
|
||||||
|
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||||
|
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||||
|
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVX/+1LEoYPAAAGkAAAAIAAANIAAAARVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||||
|
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||||
|
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||||
|
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVQ=='
|
||||||
@@ -25,6 +25,7 @@ const PATHS = {
|
|||||||
),
|
),
|
||||||
sparkle: <path d="M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8zM19 16l.7 1.8 1.8.7-1.8.7L19 21l-.7-1.8-1.8-.7 1.8-.7z" strokeLinejoin="round" />,
|
sparkle: <path d="M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8zM19 16l.7 1.8 1.8.7-1.8.7L19 21l-.7-1.8-1.8-.7 1.8-.7z" strokeLinejoin="round" />,
|
||||||
wave: <path d="M3 12h2M7 8v8M11 5v14M15 9v6M19 11v2" />,
|
wave: <path d="M3 12h2M7 8v8M11 5v14M15 9v6M19 11v2" />,
|
||||||
|
sine: <path d="M2 12c2.5-8 5-8 7.5 0s5 8 7.5 0 3.5-5 5-3" strokeLinejoin="round" />,
|
||||||
folder: <path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" strokeLinejoin="round" />,
|
folder: <path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" strokeLinejoin="round" />,
|
||||||
folderOpen: <path d="M3 7a2 2 0 0 1 2-2h4l2 2h6a2 2 0 0 1 2 2v1M3 7v10a2 2 0 0 0 2 2h12.5a2 2 0 0 0 1.9-1.4L21 12a1 1 0 0 0-1-1.3H8.5a2 2 0 0 0-1.9 1.4L4 19" strokeLinejoin="round" />,
|
folderOpen: <path d="M3 7a2 2 0 0 1 2-2h4l2 2h6a2 2 0 0 1 2 2v1M3 7v10a2 2 0 0 0 2 2h12.5a2 2 0 0 0 1.9-1.4L21 12a1 1 0 0 0-1-1.3H8.5a2 2 0 0 0-1.9 1.4L4 19" strokeLinejoin="round" />,
|
||||||
playlist: <path d="M8 6h13M8 12h13M8 18h13M3.5 6h.01M3.5 12h.01M3.5 18h.01" />,
|
playlist: <path d="M8 6h13M8 12h13M8 18h13M3.5 6h.01M3.5 12h.01M3.5 18h.01" />,
|
||||||
|
|||||||
@@ -0,0 +1,143 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
|
||||||
|
import { laneScales, makeSpans, rawSpans, rawWaveFromMono, RAW_BLOCK, tintAt } from './rawWave'
|
||||||
|
import type { WaveColumn } from './waveform'
|
||||||
|
|
||||||
|
const SR = 44100
|
||||||
|
|
||||||
|
/** `sec` of silence with a one-sample click of `amp` at sample `at`. */
|
||||||
|
function click(sec: number, at: number, amp = 0.8) {
|
||||||
|
const mono = new Float32Array(Math.round(sec * SR))
|
||||||
|
mono[at] = amp
|
||||||
|
return rawWaveFromMono(mono, SR)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The bin whose centre time is nearest `sec`. */
|
||||||
|
const binAt = (s: ReturnType<typeof makeSpans>, sec: number) => {
|
||||||
|
let best = 0
|
||||||
|
for (let k = 0; k < s.n; k++) if (Math.abs(s.t[k] - sec) < Math.abs(s.t[best] - sec)) best = k
|
||||||
|
return best
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('rawWaveFromMono', () => {
|
||||||
|
it('summarises min/max per block and finds the peak', () => {
|
||||||
|
const mono = new Float32Array(RAW_BLOCK * 3)
|
||||||
|
mono[5] = 0.5
|
||||||
|
mono[RAW_BLOCK + 7] = -0.9
|
||||||
|
const raw = rawWaveFromMono(mono, SR)
|
||||||
|
expect(raw.min.length).toBe(3)
|
||||||
|
expect(raw.max[0]).toBeCloseTo(0.5)
|
||||||
|
expect(raw.min[1]).toBeCloseTo(-0.9)
|
||||||
|
expect(raw.peak).toBeCloseTo(0.9)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('rawSpans', () => {
|
||||||
|
// A 0.25 s view across 1200 px: ~9 samples a pixel — the SAMPLE path.
|
||||||
|
// A 16 s view: ~588 a pixel — the BLOCK path.
|
||||||
|
for (const [label, view] of [['deep zoom', 0.25], ['wide zoom', 16]] as const) {
|
||||||
|
it(`puts a click in the pixel that holds it (${label})`, () => {
|
||||||
|
const at = 2 * SR + 123
|
||||||
|
const raw = click(30, at)
|
||||||
|
const w = 1200
|
||||||
|
const start = at / SR - view / 2
|
||||||
|
const s = rawSpans(raw, start, start + view, w, makeSpans())
|
||||||
|
const k = binAt(s, at / SR)
|
||||||
|
expect(s.hi[k]).toBeCloseTo(0.8)
|
||||||
|
// Its pixel is where the playhead (the view's centre) is.
|
||||||
|
expect(Math.abs(Math.round(s.x0 + k) - w / 2)).toBeLessThanOrEqual(1)
|
||||||
|
// Far from it, silence.
|
||||||
|
expect(s.hi[k + 20]).toBe(0)
|
||||||
|
expect(s.hi[k - 20]).toBe(0)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
it('leaves bins outside the track empty', () => {
|
||||||
|
const raw = click(1, 100)
|
||||||
|
const s = rawSpans(raw, -0.5, 0.5, 1000, makeSpans())
|
||||||
|
expect(Number.isNaN(s.lo[10])).toBe(true)
|
||||||
|
expect(Number.isNaN(s.lo[900])).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('draws a sine as one continuous line at deep zoom', () => {
|
||||||
|
const mono = new Float32Array(SR)
|
||||||
|
for (let i = 0; i < mono.length; i++) mono[i] = Math.sin((2 * Math.PI * 60 * i) / SR) * 0.7
|
||||||
|
const s = rawSpans(rawWaveFromMono(mono, SR), 0.4, 0.65, 1200, makeSpans())
|
||||||
|
for (let k = 1; k < s.n; k++) {
|
||||||
|
// Each stroke overlaps the previous: no gap a line could fall through.
|
||||||
|
expect(s.lo[k]).toBeLessThanOrEqual(s.hi[k - 1] + 1e-6)
|
||||||
|
expect(s.hi[k]).toBeGreaterThanOrEqual(s.lo[k - 1] - 1e-6)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('interpolates when a pixel is narrower than a sample', () => {
|
||||||
|
const mono = new Float32Array(SR)
|
||||||
|
for (let i = 0; i < mono.length; i++) mono[i] = i / mono.length
|
||||||
|
// 0.01 s across 4000 px: ~0.11 samples a pixel.
|
||||||
|
const s = rawSpans(rawWaveFromMono(mono, SR), 0.5, 0.51, 4000, makeSpans())
|
||||||
|
const k = 2000
|
||||||
|
expect(s.lo[k]).toBeCloseTo(s.t[k], 3)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('agrees with itself across the block/sample switch-over', () => {
|
||||||
|
const mono = new Float32Array(10 * SR)
|
||||||
|
for (let i = 0; i < mono.length; i++) mono[i] = Math.sin(i * 0.001) * Math.sin(i * 0.37) * 0.9
|
||||||
|
const raw = rawWaveFromMono(mono, SR)
|
||||||
|
const w = 1000
|
||||||
|
// Just either side of 128 samples a pixel.
|
||||||
|
const sample = rawSpans(raw, 1, 1 + (127 * w) / SR, w, makeSpans())
|
||||||
|
const block = rawSpans(raw, 1, 1 + (129 * w) / SR, w, makeSpans())
|
||||||
|
// At the same time, the block path's extent contains the sample path's
|
||||||
|
// (it may smear by part of a block, never miss a peak).
|
||||||
|
for (const k of [100, 400, 700]) {
|
||||||
|
const j = binAt(block, sample.t[k])
|
||||||
|
const near = [j - 1, j, j + 1]
|
||||||
|
expect(Math.min(...near.map((i) => block.lo[i]))).toBeLessThanOrEqual(sample.lo[k] + 1e-6)
|
||||||
|
expect(Math.max(...near.map((i) => block.hi[i]))).toBeGreaterThanOrEqual(sample.hi[k] - 1e-6)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('bins in track space, so scrolling does not regroup samples', () => {
|
||||||
|
const mono = new Float32Array(4 * SR)
|
||||||
|
for (let i = 0; i < mono.length; i++) mono[i] = Math.sin(i * 0.013) * Math.sin(i * 0.41)
|
||||||
|
const raw = rawWaveFromMono(mono, SR)
|
||||||
|
const w = 800
|
||||||
|
const view = 8 // wide: block path
|
||||||
|
const a = rawSpans(raw, 0.5, 0.5 + view, w, makeSpans())
|
||||||
|
const lo = Array.from(a.lo.subarray(0, a.n))
|
||||||
|
const shift = (view / w) * 0.37 // a fraction of a pixel
|
||||||
|
const b = rawSpans(raw, 0.5 + shift, 0.5 + shift + view, w, makeSpans())
|
||||||
|
expect(Array.from(b.lo.subarray(0, b.n))).toEqual(lo)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('laneScales', () => {
|
||||||
|
it('scales each stem by its own peak', () => {
|
||||||
|
const [a, b] = laneScales([1, 0.5], 100)
|
||||||
|
expect(a).toBeCloseTo(100)
|
||||||
|
expect(b).toBeCloseTo(200)
|
||||||
|
})
|
||||||
|
it('never magnifies a near-silent stem past 5% of the loudest', () => {
|
||||||
|
const [, quiet] = laneScales([1, 0.001], 100)
|
||||||
|
expect(quiet).toBeCloseTo(100 / 0.05)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('tintAt', () => {
|
||||||
|
const col = (low: number, mid: number, high: number): WaveColumn => ({ peak: 1, low, mid, high })
|
||||||
|
const rgb = (s: string) => s.slice(4, -1).split(',').map(Number)
|
||||||
|
const saturation = (s: string) => Math.max(...rgb(s)) - Math.min(...rgb(s))
|
||||||
|
it('keeps each band its bar colour', () => {
|
||||||
|
const [r, g, b] = rgb(tintAt([col(1, 0, 0)], 1, 0.5))
|
||||||
|
expect(r).toBeGreaterThan(g)
|
||||||
|
expect(g).toBeGreaterThan(b) // orange
|
||||||
|
const [r2, , b2] = rgb(tintAt([col(0, 0, 1)], 1, 0.5))
|
||||||
|
expect(b2).toBeGreaterThan(r2) // cyan
|
||||||
|
})
|
||||||
|
it('never greys out where bands mix', () => {
|
||||||
|
// A plain weighted mean of orange + violet + cyan spreads only 26-56 here.
|
||||||
|
for (const mix of [col(1, 1, 1), col(1, 0, 1), col(0.6, 1, 0.4)]) {
|
||||||
|
expect(saturation(tintAt([mix], 1, 0.5))).toBeGreaterThan(90)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,362 @@
|
|||||||
|
// The RAW waveform: the main view's alternative to bars (the toggle under its
|
||||||
|
// zoom buttons, persisted as `mainWaveRaw`), after Traktor at full zoom — a thin
|
||||||
|
// signed line of the actual signal, its colour shifting with the frequency mix.
|
||||||
|
// The bars (`waveform.ts`) draw ~7 ms columns of unsigned band energy, which
|
||||||
|
// hides where a kick actually starts; this draws the samples.
|
||||||
|
//
|
||||||
|
// Decided (discussion 2026-10-15): the SHAPE is exact and the COLOUR is
|
||||||
|
// approximate — the tint comes from the bars' ~7 ms band columns, in the bars'
|
||||||
|
// palette blended in OKLab (`bandColour`), lerped between columns. The vertical scale is fixed by the track's
|
||||||
|
// loudest sample, so relative loudness is truthful and the height never pumps
|
||||||
|
// while scrolling.
|
||||||
|
//
|
||||||
|
// Two data paths, by how many samples one pixel covers:
|
||||||
|
// * many (wide zoom): min/max per RAW_BLOCK samples, summarised once at load
|
||||||
|
// (~4 MB for a 6-minute track) — a 64 s view reads ~90k block values;
|
||||||
|
// * few (deep zoom): the visible window read straight from the decoded
|
||||||
|
// AudioBuffer each frame. No full-length mono copy is kept; the playback
|
||||||
|
// engine holds the buffer anyway.
|
||||||
|
// Each pixel is a vertical stroke from the lowest to the highest sample in it,
|
||||||
|
// stretched to touch its neighbour's — zoomed out it reads as a filled
|
||||||
|
// envelope, zoomed in it narrows to one continuous line, with no switch-over.
|
||||||
|
|
||||||
|
import type { WaveColumn } from './waveform'
|
||||||
|
|
||||||
|
/** Samples per entry of the min/max summary. */
|
||||||
|
export const RAW_BLOCK = 32
|
||||||
|
/** Below this many samples per pixel, read samples instead of blocks: a pixel
|
||||||
|
* then spans at least 4 blocks, so block edges smear it by at most a quarter. */
|
||||||
|
const SAMPLE_PATH_BELOW = 4 * RAW_BLOCK
|
||||||
|
|
||||||
|
export interface RawWave {
|
||||||
|
sampleRate: number
|
||||||
|
/** Samples in the track. */
|
||||||
|
length: number
|
||||||
|
/** Min / max of the mono downmix per RAW_BLOCK samples. */
|
||||||
|
min: Float32Array
|
||||||
|
max: Float32Array
|
||||||
|
/** The loudest absolute sample — the fixed vertical scale. */
|
||||||
|
peak: number
|
||||||
|
/** Fill `dest` with the mono downmix from sample `start` (zeros outside). */
|
||||||
|
readMono: (start: number, dest: Float32Array) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A reader of an AudioBuffer's mono downmix. copyFromChannel copies, so this
|
||||||
|
* never holds a view the playback engine could detach (the Firefox gotcha). */
|
||||||
|
export function bufferReader(buffer: AudioBuffer): RawWave['readMono'] {
|
||||||
|
let tmp = new Float32Array(0)
|
||||||
|
const chs = buffer.numberOfChannels
|
||||||
|
return (start, dest) => {
|
||||||
|
dest.fill(0)
|
||||||
|
const from = Math.max(0, start)
|
||||||
|
const skip = from - start
|
||||||
|
const n = Math.min(dest.length - skip, buffer.length - from)
|
||||||
|
if (n <= 0) return
|
||||||
|
if (tmp.length < n) tmp = new Float32Array(n)
|
||||||
|
const view = tmp.subarray(0, n)
|
||||||
|
for (let c = 0; c < chs; c++) {
|
||||||
|
buffer.copyFromChannel(view, c, from)
|
||||||
|
for (let i = 0; i < n; i++) dest[skip + i] += view[i] / chs
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Summarise a mono downmix. `readMono` defaults to reading `mono` itself
|
||||||
|
* (tests); the deck passes `bufferReader` so `mono` can be dropped. */
|
||||||
|
export function rawWaveFromMono(
|
||||||
|
mono: Float32Array,
|
||||||
|
sampleRate: number,
|
||||||
|
readMono?: RawWave['readMono'],
|
||||||
|
): RawWave {
|
||||||
|
const len = mono.length
|
||||||
|
const nb = Math.max(1, Math.ceil(len / RAW_BLOCK))
|
||||||
|
const min = new Float32Array(nb)
|
||||||
|
const max = new Float32Array(nb)
|
||||||
|
let peak = 0
|
||||||
|
for (let b = 0; b < nb; b++) {
|
||||||
|
let lo = Infinity
|
||||||
|
let hi = -Infinity
|
||||||
|
const end = Math.min(len, (b + 1) * RAW_BLOCK)
|
||||||
|
for (let i = b * RAW_BLOCK; i < end; i++) {
|
||||||
|
const v = mono[i]
|
||||||
|
if (v < lo) lo = v
|
||||||
|
if (v > hi) hi = v
|
||||||
|
}
|
||||||
|
if (lo === Infinity) lo = hi = 0
|
||||||
|
min[b] = lo
|
||||||
|
max[b] = hi
|
||||||
|
peak = Math.max(peak, -lo, hi)
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
sampleRate,
|
||||||
|
length: len,
|
||||||
|
min,
|
||||||
|
max,
|
||||||
|
peak,
|
||||||
|
readMono:
|
||||||
|
readMono ??
|
||||||
|
((start, dest) => {
|
||||||
|
dest.fill(0)
|
||||||
|
for (let i = 0; i < dest.length; i++) {
|
||||||
|
const j = start + i
|
||||||
|
if (j >= 0 && j < len) dest[i] = mono[j]
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reusable per-pixel output of `rawSpans`. */
|
||||||
|
export interface RawSpans {
|
||||||
|
lo: Float32Array
|
||||||
|
hi: Float32Array
|
||||||
|
/** Track time at each bin's centre (for the colour). */
|
||||||
|
t: Float64Array
|
||||||
|
/** Bins filled; bin k is drawn at device pixel `round(x0 + k)`. */
|
||||||
|
n: number
|
||||||
|
x0: number
|
||||||
|
scratch: Float32Array
|
||||||
|
}
|
||||||
|
|
||||||
|
export function makeSpans(): RawSpans {
|
||||||
|
return { lo: new Float32Array(0), hi: new Float32Array(0), t: new Float64Array(0), n: 0, x0: 0, scratch: new Float32Array(0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Per-pixel min/max of `raw` across a `w`-pixel view of [startSec, endSec).
|
||||||
|
* Bins sit on a TRACK-space grid (bin g covers [g, g+1) pixel widths of track
|
||||||
|
* time), so a scrolling view moves bins rather than regrouping samples under
|
||||||
|
* them — the same reason `paintWave` bins in track space: regrouping makes
|
||||||
|
* every peak shimmer as the playhead advances. Bins outside the track are NaN.
|
||||||
|
*/
|
||||||
|
export function rawSpans(raw: RawWave, startSec: number, endSec: number, w: number, out: RawSpans): RawSpans {
|
||||||
|
const secPerPx = (endSec - startSec) / w
|
||||||
|
const spp = secPerPx * raw.sampleRate // samples per pixel
|
||||||
|
const g0 = Math.floor(startSec / secPerPx)
|
||||||
|
const n = w + 2
|
||||||
|
if (out.lo.length < n) {
|
||||||
|
out.lo = new Float32Array(n)
|
||||||
|
out.hi = new Float32Array(n)
|
||||||
|
out.t = new Float64Array(n)
|
||||||
|
}
|
||||||
|
out.n = n
|
||||||
|
out.x0 = g0 - startSec / secPerPx
|
||||||
|
const { lo, hi, t } = out
|
||||||
|
for (let k = 0; k < n; k++) t[k] = (g0 + k + 0.5) * secPerPx
|
||||||
|
|
||||||
|
if (spp >= SAMPLE_PATH_BELOW) {
|
||||||
|
const nb = raw.min.length
|
||||||
|
for (let k = 0; k < n; k++) {
|
||||||
|
const s0 = (g0 + k) * spp
|
||||||
|
const s1 = s0 + spp
|
||||||
|
if (s1 <= 0 || s0 >= raw.length) {
|
||||||
|
lo[k] = hi[k] = NaN
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
const b0 = Math.max(0, Math.floor(s0 / RAW_BLOCK))
|
||||||
|
const b1 = Math.min(nb, Math.max(b0 + 1, Math.ceil(s1 / RAW_BLOCK)))
|
||||||
|
let a = Infinity
|
||||||
|
let z = -Infinity
|
||||||
|
for (let b = b0; b < b1; b++) {
|
||||||
|
if (raw.min[b] < a) a = raw.min[b]
|
||||||
|
if (raw.max[b] > z) z = raw.max[b]
|
||||||
|
}
|
||||||
|
lo[k] = a
|
||||||
|
hi[k] = z
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// One read covers the window, plus a sample each side for interpolation.
|
||||||
|
const first = Math.floor(g0 * spp) - 1
|
||||||
|
const count = Math.ceil(n * spp) + 3
|
||||||
|
if (out.scratch.length < count) out.scratch = new Float32Array(count)
|
||||||
|
const win = out.scratch.subarray(0, count)
|
||||||
|
raw.readMono(first, win)
|
||||||
|
for (let k = 0; k < n; k++) {
|
||||||
|
const s0 = (g0 + k) * spp
|
||||||
|
const s1 = s0 + spp
|
||||||
|
if (s1 <= 0 || s0 >= raw.length) {
|
||||||
|
lo[k] = hi[k] = NaN
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
const i0 = Math.ceil(s0)
|
||||||
|
const i1 = Math.ceil(s1)
|
||||||
|
let a = Infinity
|
||||||
|
let z = -Infinity
|
||||||
|
for (let i = i0; i < i1; i++) {
|
||||||
|
const v = win[i - first]
|
||||||
|
if (v < a) a = v
|
||||||
|
if (v > z) z = v
|
||||||
|
}
|
||||||
|
if (a === Infinity) {
|
||||||
|
// Narrower than a sample: the line's value at the bin's centre.
|
||||||
|
const c = (s0 + s1) / 2
|
||||||
|
const i = Math.floor(c)
|
||||||
|
const f = c - i
|
||||||
|
a = z = win[i - first] * (1 - f) + win[i + 1 - first] * f
|
||||||
|
}
|
||||||
|
lo[k] = a
|
||||||
|
hi[k] = z
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Join each stroke to the previous one (by its ORIGINAL extent), so a steep
|
||||||
|
// edge stays a continuous line instead of a dotted one.
|
||||||
|
let pLo = NaN
|
||||||
|
let pHi = NaN
|
||||||
|
for (let k = 0; k < n; k++) {
|
||||||
|
const a = lo[k]
|
||||||
|
const z = hi[k]
|
||||||
|
if (a === a && pLo === pLo) {
|
||||||
|
if (a > pHi) lo[k] = pHi
|
||||||
|
if (z < pLo) hi[k] = pLo
|
||||||
|
}
|
||||||
|
pLo = a
|
||||||
|
pHi = z
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pixels per unit amplitude for each stem lane: each stem at its own peak,
|
||||||
|
* but never below 5% of the loudest stem's — the same floor as the bar lanes,
|
||||||
|
* so a near-silent stem draws as near-silence, not magnified noise. */
|
||||||
|
export function laneScales(peaks: number[], halfHeight: number): number[] {
|
||||||
|
const loudest = Math.max(1e-6, ...peaks)
|
||||||
|
return peaks.map((p) => halfHeight / Math.max(p, loudest * 0.05, 1e-6))
|
||||||
|
}
|
||||||
|
|
||||||
|
// The bars' band colours (waveform.ts LAYERS), as RGB.
|
||||||
|
const BANDS = [
|
||||||
|
[255, 138, 61], // bass
|
||||||
|
[143, 107, 255], // mids
|
||||||
|
[94, 231, 255], // highs
|
||||||
|
]
|
||||||
|
|
||||||
|
// sRGB <-> OKLab (Björn Ottosson's matrices).
|
||||||
|
function toLab([r, g, b]: number[]): number[] {
|
||||||
|
const lin = (v: number) => ((v /= 255) <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4)
|
||||||
|
const R = lin(r)
|
||||||
|
const G = lin(g)
|
||||||
|
const B = lin(b)
|
||||||
|
const l = Math.cbrt(0.4122214708 * R + 0.5363325363 * G + 0.0514459929 * B)
|
||||||
|
const m = Math.cbrt(0.2119034982 * R + 0.6806995451 * G + 0.1073969566 * B)
|
||||||
|
const s = Math.cbrt(0.0883024619 * R + 0.2817188376 * G + 0.6299787005 * B)
|
||||||
|
return [
|
||||||
|
0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,
|
||||||
|
1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s,
|
||||||
|
0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s,
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
function fromLab([L, A, B]: number[]): number[] {
|
||||||
|
const l = (L + 0.3963377774 * A + 0.2158037573 * B) ** 3
|
||||||
|
const m = (L - 0.1055613458 * A - 0.0638541728 * B) ** 3
|
||||||
|
const s = (L - 0.0894841775 * A - 1.291485548 * B) ** 3
|
||||||
|
const enc = (v: number) => {
|
||||||
|
v = Math.min(1, Math.max(0, v))
|
||||||
|
return 255 * (v <= 0.0031308 ? 12.92 * v : 1.055 * v ** (1 / 2.4) - 0.055)
|
||||||
|
}
|
||||||
|
return [
|
||||||
|
enc(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s),
|
||||||
|
enc(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s),
|
||||||
|
enc(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
const BAND_LAB = BANDS.map(toLab)
|
||||||
|
const BAND_CHROMA = BAND_LAB.map(([, a, b]) => Math.hypot(a, b))
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A column's colour from its band energies. Mixed in OKLab, then the CHROMA is
|
||||||
|
* put back to the bands' weighted chroma: a plain weighted mean of orange,
|
||||||
|
* violet and cyan lands near grey (they sit around the hue wheel), which read
|
||||||
|
* as mud on busy passages. Chosen 2026-10-15 from five candidates rendered on
|
||||||
|
* real tracks: orange + violet blends through pink (Traktor-like), highs stay
|
||||||
|
* cyan, and nothing greys out. Lifted a touch so it reads on the dark well.
|
||||||
|
*/
|
||||||
|
function bandColour(low: number, mid: number, high: number): number[] {
|
||||||
|
const w = [low, mid, high]
|
||||||
|
const sum = low + mid + high
|
||||||
|
if (sum < 1e-6) return BANDS[0]
|
||||||
|
const mix = [0, 1, 2].map((c) => BAND_LAB.reduce((acc, lab, b) => acc + lab[c] * w[b], 0) / sum)
|
||||||
|
const chroma = BAND_CHROMA.reduce((acc, ch, b) => acc + ch * w[b], 0) / sum
|
||||||
|
const k = chroma / Math.max(1e-6, Math.hypot(mix[1], mix[2]))
|
||||||
|
return fromLab([mix[0] + 0.04, mix[1] * k, mix[2] * k])
|
||||||
|
}
|
||||||
|
|
||||||
|
const columnRgb = new WeakMap<WaveColumn[], Float32Array>()
|
||||||
|
|
||||||
|
/** Each band column's colour (`bandColour`), computed once per analysis. */
|
||||||
|
function rgbOf(cols: WaveColumn[]): Float32Array {
|
||||||
|
let rgb = columnRgb.get(cols)
|
||||||
|
if (rgb) return rgb
|
||||||
|
rgb = new Float32Array(cols.length * 3)
|
||||||
|
for (let i = 0; i < cols.length; i++) rgb.set(bandColour(cols[i].low, cols[i].mid, cols[i].high), i * 3)
|
||||||
|
columnRgb.set(cols, rgb)
|
||||||
|
return rgb
|
||||||
|
}
|
||||||
|
|
||||||
|
const styles = new Map<number, string>()
|
||||||
|
|
||||||
|
/** The tint at track time `t`: lerped between the two nearest band columns,
|
||||||
|
* quantised to 32 levels a channel so a frame reuses a small set of strings. */
|
||||||
|
export function tintAt(cols: WaveColumn[], duration: number, t: number): string {
|
||||||
|
const rgb = rgbOf(cols)
|
||||||
|
const n = cols.length
|
||||||
|
const c = Math.min(n - 1, Math.max(0, (t / duration) * n - 0.5))
|
||||||
|
const i = Math.floor(c)
|
||||||
|
const j = Math.min(n - 1, i + 1)
|
||||||
|
const f = c - i
|
||||||
|
let key = 0
|
||||||
|
for (let ch = 0; ch < 3; ch++) {
|
||||||
|
const v = rgb[i * 3 + ch] * (1 - f) + rgb[j * 3 + ch] * f
|
||||||
|
key = (key << 5) | Math.min(31, Math.round(v / 8.226))
|
||||||
|
}
|
||||||
|
let s = styles.get(key)
|
||||||
|
if (!s) {
|
||||||
|
const r = ((key >> 10) & 31) * 8.226
|
||||||
|
const g = ((key >> 5) & 31) * 8.226
|
||||||
|
const b = (key & 31) * 8.226
|
||||||
|
s = `rgb(${r | 0},${g | 0},${b | 0})`
|
||||||
|
styles.set(key, s)
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Paint spans as a line centred in [y0, y0 + h). `scale` is pixels per unit
|
||||||
|
* amplitude; `thick` the minimum stroke (device px), so a flat stretch still
|
||||||
|
* reads as a line. `colour` is a fixed style or a per-bin function (by time).
|
||||||
|
*/
|
||||||
|
export function paintRaw(
|
||||||
|
ctx: CanvasRenderingContext2D,
|
||||||
|
s: RawSpans,
|
||||||
|
y0: number,
|
||||||
|
h: number,
|
||||||
|
scale: number,
|
||||||
|
thick: number,
|
||||||
|
colour: string | ((t: number) => string),
|
||||||
|
): void {
|
||||||
|
const mid = y0 + h / 2
|
||||||
|
const fixed = typeof colour === 'string'
|
||||||
|
if (fixed) ctx.fillStyle = colour
|
||||||
|
let current = ''
|
||||||
|
const wpx = Math.max(1, Math.round(thick * 0.8))
|
||||||
|
for (let k = 0; k < s.n; k++) {
|
||||||
|
const a = s.lo[k]
|
||||||
|
if (a !== a) continue
|
||||||
|
let top = mid - s.hi[k] * scale
|
||||||
|
let bot = mid - a * scale
|
||||||
|
if (bot - top < thick) {
|
||||||
|
const c = (top + bot) / 2
|
||||||
|
top = c - thick / 2
|
||||||
|
bot = c + thick / 2
|
||||||
|
}
|
||||||
|
if (!fixed) {
|
||||||
|
const style = colour(s.t[k])
|
||||||
|
if (style !== current) {
|
||||||
|
ctx.fillStyle = style
|
||||||
|
current = style
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ctx.fillRect(Math.round(s.x0 + k), top, wpx, bot - top)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -12,6 +12,9 @@
|
|||||||
// and the structure of a track — where the bass drops out, where the highs
|
// and the structure of a track — where the bass drops out, where the highs
|
||||||
// build — is visible at a glance. Still no green, matching Traktor's palette.
|
// build — is visible at a glance. Still no green, matching Traktor's palette.
|
||||||
|
|
||||||
|
import { alignDecoded, mp3HeaderFrame } from './decodeAlign'
|
||||||
|
import { bufferReader, rawWaveFromMono, type RawWave } from './rawWave'
|
||||||
|
|
||||||
export interface WaveColumn {
|
export interface WaveColumn {
|
||||||
peak: number // 0..1 amplitude of the full mix
|
peak: number // 0..1 amplitude of the full mix
|
||||||
low: number // 0..1 band energies, each normalised to its own maximum
|
low: number // 0..1 band energies, each normalised to its own maximum
|
||||||
@@ -97,17 +100,21 @@ export interface WaveformAnalysis {
|
|||||||
cols: WaveColumn[]
|
cols: WaveColumn[]
|
||||||
/** The decoded audio, retained for the scratch engine (reused, not re-decoded). */
|
/** The decoded audio, retained for the scratch engine (reused, not re-decoded). */
|
||||||
buffer: AudioBuffer
|
buffer: AudioBuffer
|
||||||
|
/** The raw waveform of the same audio. */
|
||||||
|
raw: RawWave
|
||||||
}
|
}
|
||||||
|
|
||||||
async function decodeUrl(url: string): Promise<AudioBuffer> {
|
async function decodeUrl(url: string): Promise<AudioBuffer> {
|
||||||
const resp = await fetch(url)
|
const resp = await fetch(url)
|
||||||
if (!resp.ok) throw new Error(`audio fetch failed: ${resp.status}`)
|
if (!resp.ok) throw new Error(`audio fetch failed: ${resp.status}`)
|
||||||
const arr = await resp.arrayBuffer()
|
const arr = await resp.arrayBuffer()
|
||||||
|
// Read BEFORE decoding: decodeAudioData detaches `arr`.
|
||||||
|
const header = mp3HeaderFrame(new Uint8Array(arr))
|
||||||
const AC: typeof AudioContext =
|
const AC: typeof AudioContext =
|
||||||
window.AudioContext ?? (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext
|
window.AudioContext ?? (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext
|
||||||
const ctx = new AC()
|
const ctx = new AC()
|
||||||
try {
|
try {
|
||||||
return await ctx.decodeAudioData(arr)
|
return await alignDecoded(await ctx.decodeAudioData(arr), header)
|
||||||
} finally {
|
} finally {
|
||||||
void ctx.close()
|
void ctx.close()
|
||||||
}
|
}
|
||||||
@@ -129,7 +136,8 @@ export async function analyzeWaveform(url: string, buckets?: number): Promise<Wa
|
|||||||
const d = audio.getChannelData(c)
|
const d = audio.getChannelData(c)
|
||||||
for (let i = 0; i < len; i++) mono[i] += d[i] / chs
|
for (let i = 0; i < len; i++) mono[i] += d[i] / chs
|
||||||
}
|
}
|
||||||
return { cols: await analyzeMono(mono, audio.sampleRate, buckets), buffer: audio }
|
const raw = rawWaveFromMono(mono, audio.sampleRate, bufferReader(audio))
|
||||||
|
return { cols: await analyzeMono(mono, audio.sampleRate, buckets), buffer: audio, raw }
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface StemAnalysis {
|
export interface StemAnalysis {
|
||||||
@@ -138,6 +146,8 @@ export interface StemAnalysis {
|
|||||||
/** Per stem, per column: amplitude 0..1 — the main view's lanes. */
|
/** Per stem, per column: amplitude 0..1 — the main view's lanes. */
|
||||||
lanes: Float32Array[]
|
lanes: Float32Array[]
|
||||||
buffers: AudioBuffer[]
|
buffers: AudioBuffer[]
|
||||||
|
/** Per stem: the raw waveform of its lane. */
|
||||||
|
raws: RawWave[]
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -157,6 +167,7 @@ export async function analyzeStems(urls: string[], buckets?: number): Promise<St
|
|||||||
const scale = n / len
|
const scale = n / len
|
||||||
const mono = new Float32Array(len)
|
const mono = new Float32Array(len)
|
||||||
const tmp = new Float32Array(len)
|
const tmp = new Float32Array(len)
|
||||||
|
const raws: RawWave[] = []
|
||||||
const lanes = buffers.map((buf) => {
|
const lanes = buffers.map((buf) => {
|
||||||
const lane = new Float32Array(n)
|
const lane = new Float32Array(n)
|
||||||
const chs = buf.numberOfChannels
|
const chs = buf.numberOfChannels
|
||||||
@@ -172,6 +183,7 @@ export async function analyzeStems(urls: string[], buckets?: number): Promise<St
|
|||||||
const b = (i * scale) | 0
|
const b = (i * scale) | 0
|
||||||
if (a > lane[b]) lane[b] = a
|
if (a > lane[b]) lane[b] = a
|
||||||
}
|
}
|
||||||
|
raws.push(rawWaveFromMono(monoStem, sr, bufferReader(buf)))
|
||||||
return lane
|
return lane
|
||||||
})
|
})
|
||||||
const ceilOf = (v: Float32Array) => {
|
const ceilOf = (v: Float32Array) => {
|
||||||
@@ -184,7 +196,7 @@ export async function analyzeStems(urls: string[], buckets?: number): Promise<St
|
|||||||
const top = Math.max(ceilings[k], loudest * 0.05, 1e-6)
|
const top = Math.max(ceilings[k], loudest * 0.05, 1e-6)
|
||||||
for (let b = 0; b < lane.length; b++) lane[b] = Math.min(1, lane[b] / top)
|
for (let b = 0; b < lane.length; b++) lane[b] = Math.min(1, lane[b] / top)
|
||||||
})
|
})
|
||||||
return { cols: await analyzeMono(mono, sr, n), lanes, buffers }
|
return { cols: await analyzeMono(mono, sr, n), lanes, buffers, raws }
|
||||||
}
|
}
|
||||||
|
|
||||||
async function analyzeMono(mono: Float32Array<ArrayBuffer>, sr: number, buckets?: number): Promise<WaveColumn[]> {
|
async function analyzeMono(mono: Float32Array<ArrayBuffer>, sr: number, buckets?: number): Promise<WaveColumn[]> {
|
||||||
|
|||||||
Reference in new issue
Block a user