Implemented raw waveform mode

This commit is contained in:
patben8 committed 2026-10-15 10:26:41 +02:00
1 parent 1464b1e211
commit 8230722105
10 files changed
+862 -16

No files matched your search

+56
View File
@@ -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)
})
})
+128
View File
@@ -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
}
+48
View File
@@ -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//tQ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VVVVVVVVVVV' +
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//tSxKGDwAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVV' +
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVX/+1LEoYPAAAGkAAAAIAAANIAAAARVVVVVVVVVVVVVVVVVVVVVVVVV' +
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVQ=='
+1
View File
@@ -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" />,
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" />,
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" />,
+143
View File
@@ -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)
}
})
})
+362
View File
@@ -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)
}
}
+15 -3
View File
@@ -12,6 +12,9 @@
// 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.
import { alignDecoded, mp3HeaderFrame } from './decodeAlign'
import { bufferReader, rawWaveFromMono, type RawWave } from './rawWave'
export interface WaveColumn {
peak: number // 0..1 amplitude of the full mix
low: number // 0..1 band energies, each normalised to its own maximum
@@ -97,17 +100,21 @@ export interface WaveformAnalysis {
cols: WaveColumn[]
/** The decoded audio, retained for the scratch engine (reused, not re-decoded). */
buffer: AudioBuffer
/** The raw waveform of the same audio. */
raw: RawWave
}
async function decodeUrl(url: string): Promise<AudioBuffer> {
const resp = await fetch(url)
if (!resp.ok) throw new Error(`audio fetch failed: ${resp.status}`)
const arr = await resp.arrayBuffer()
// Read BEFORE decoding: decodeAudioData detaches `arr`.
const header = mp3HeaderFrame(new Uint8Array(arr))
const AC: typeof AudioContext =
window.AudioContext ?? (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext
const ctx = new AC()
try {
return await ctx.decodeAudioData(arr)
return await alignDecoded(await ctx.decodeAudioData(arr), header)
} finally {
void ctx.close()
}
@@ -129,7 +136,8 @@ export async function analyzeWaveform(url: string, buckets?: number): Promise<Wa
const d = audio.getChannelData(c)
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 {
@@ -138,6 +146,8 @@ export interface StemAnalysis {
/** Per stem, per column: amplitude 0..1 — the main view's lanes. */
lanes: Float32Array[]
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 mono = new Float32Array(len)
const tmp = new Float32Array(len)
const raws: RawWave[] = []
const lanes = buffers.map((buf) => {
const lane = new Float32Array(n)
const chs = buf.numberOfChannels
@@ -172,6 +183,7 @@ export async function analyzeStems(urls: string[], buckets?: number): Promise<St
const b = (i * scale) | 0
if (a > lane[b]) lane[b] = a
}
raws.push(rawWaveFromMono(monoStem, sr, bufferReader(buf)))
return lane
})
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)
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[]> {