Implemented STEM playback

This commit is contained in:
patben8 committed 2026-10-01 10:55:09 +02:00
1 parent ae03a93f98
commit ecc0e4c8df
13 files changed
+775 -61

No files matched your search

+68 -31
View File
@@ -6,12 +6,20 @@
// the AudioContext clock (high-resolution, so the playhead is smooth without any
// wall-clock interpolation). Loop bounds can be changed on the live node, so
// enabling a loop mid-playback is seamless.
//
// A STEM track loads four buffers instead of one. Each gets its own source and
// gain, and every source is started at the SAME scheduled context time, so the
// stems stay sample-locked through play, seek and loops — the deck plays their
// sum, as Traktor's stem deck does. Muting is a gain change (ramped over a few
// ms so it does not click), never a restart.
export class PlaybackEngine {
private ctx: AudioContext | null = null
private buffer: AudioBuffer | null = null
private buffers: AudioBuffer[] = []
private gain: GainNode | null = null
private source: AudioBufferSourceNode | null = null
/** One per buffer; a plain track has one of each. */
private gains: GainNode[] = []
private sources: AudioBufferSourceNode[] = []
private startedAt = 0 // ctx time when the current source started
private startOffset = 0 // buffer position (s) at that moment / paused position
private _playing = false
@@ -20,14 +28,21 @@ export class PlaybackEngine {
private loopEnd = 0
private onEnded: (() => void) | null = null
load(ctx: AudioContext, buffer: AudioBuffer): void {
/** One buffer (a plain track) or several played in lockstep (the stems). */
load(ctx: AudioContext, buffer: AudioBuffer | AudioBuffer[]): void {
this.ctx = ctx
this.buffer = buffer
this.stopSource()
this.buffers = Array.isArray(buffer) ? buffer : [buffer]
if (!this.gain) {
this.gain = ctx.createGain()
this.gain.connect(ctx.destination)
}
this.stopSource()
for (const g of this.gains) g.disconnect()
this.gains = this.buffers.map(() => {
const g = ctx.createGain()
g.connect(this.gain!)
return g
})
this._playing = false
this.startOffset = 0
this.loopOn = false
@@ -37,9 +52,23 @@ export class PlaybackEngine {
this.onEnded = cb
}
private get buffer(): AudioBuffer | null {
return this.buffers[0] ?? null
}
get ready(): boolean {
return !!this.buffer
}
/** Per-buffer levels (0 = muted) — the stems' mute/solo. Ramped, not stepped. */
setGains(levels: number[]): void {
if (!this.ctx) return
const now = this.ctx.currentTime
this.gains.forEach((g, i) => {
g.gain.cancelScheduledValues(now)
g.gain.setTargetAtTime(levels[i] ?? 1, now, 0.004)
})
}
get playing(): boolean {
return this._playing
}
@@ -52,7 +81,8 @@ export class PlaybackEngine {
getPosition(): number {
if (!this.buffer || !this.ctx || !this._playing) return this.startOffset
let pos = this.startOffset + (this.ctx.currentTime - this.startedAt)
// max(0, …): a scheduled start is a few ms in the future.
let pos = this.startOffset + Math.max(0, this.ctx.currentTime - this.startedAt)
if (this.loopOn && this.loopEnd > this.loopStart && pos >= this.loopEnd) {
const len = this.loopEnd - this.loopStart
pos = this.loopStart + ((pos - this.loopStart) % len)
@@ -62,41 +92,48 @@ export class PlaybackEngine {
private startSource(offset: number): void {
if (!this.ctx || !this.buffer || !this.gain) return
const src = this.ctx.createBufferSource()
src.buffer = this.buffer
if (this.loopOn && this.loopEnd > this.loopStart) {
src.loop = true
src.loopStart = this.loopStart
src.loopEnd = this.loopEnd
}
src.connect(this.gain)
src.onended = () => {
if (this.source === src) {
const off = Math.max(0, Math.min(offset, this.buffer.duration - 0.001))
// One shared start time, a hair ahead so every source can make it: that is
// what keeps the stems sample-locked to each other.
const when = this.ctx.currentTime + (this.buffers.length > 1 ? 0.01 : 0)
const started = this.buffers.map((buf, i) => {
const src = this.ctx!.createBufferSource()
src.buffer = buf
if (this.loopOn && this.loopEnd > this.loopStart) {
src.loop = true
src.loopStart = this.loopStart
src.loopEnd = this.loopEnd
}
src.connect(this.gains[i] ?? this.gain!)
src.start(when, off)
return src
})
const first = started[0]
first.onended = () => {
if (this.sources[0] === first) {
// Natural end (our own stops null out onended first).
this._playing = false
this.source = null
this.stopSource()
this.onEnded?.()
}
}
const off = Math.max(0, Math.min(offset, this.buffer.duration - 0.001))
src.start(0, off)
this.source = src
this.startedAt = this.ctx.currentTime
this.sources = started
this.startedAt = when
this.startOffset = offset
this._playing = true
}
private stopSource(): void {
if (this.source) {
this.source.onended = null
for (const src of this.sources) {
src.onended = null
try {
this.source.stop()
src.stop()
} catch {
/* already stopped */
}
this.source.disconnect()
this.source = null
src.disconnect()
}
this.sources = []
}
play(): void {
@@ -141,13 +178,13 @@ export class PlaybackEngine {
this.loopStart = start
this.loopEnd = end
this.loopOn = enabled
if (this.source) {
for (const src of this.sources) {
if (enabled && end > start) {
this.source.loop = true
this.source.loopStart = start
this.source.loopEnd = end
src.loop = true
src.loopStart = start
src.loopEnd = end
} else {
this.source.loop = false
src.loop = false
}
}
// If the playhead is already at/past the loop end, jump into it (the live
+50
View File
@@ -38,6 +38,8 @@ export class ScratchEngine {
// COPY the PCM — do NOT hold getChannelData() views. When the playback engine
// plays this same AudioBuffer, the browser (Firefox) "acquires the content"
// and detaches those views to zero-length, which would silence the scratch.
this.stems = []
this.build++
this.channels = []
for (let c = 0; c < buffer.numberOfChannels; c++) {
this.channels.push(new Float32Array(buffer.getChannelData(c)))
@@ -46,6 +48,54 @@ export class ScratchEngine {
this.sr = buffer.sampleRate
}
// ---- stems: scratch what you hear -----------------------------------------
private stems: AudioBuffer[] = []
private build = 0 // generation: a newer mute change abandons an older rebuild
/** Load a stem track: ONE summed copy of the stems at `levels` (the deck's
* mute/solo) — not four, which would quadruple the memory. copyFromChannel
* rather than getChannelData, for the same detaching reason as `load`. */
loadStems(buffers: AudioBuffer[], levels: number[]): void {
this.stems = buffers
const first = buffers[0]
this.length = first.length
this.sr = first.sampleRate
this.channels = []
for (let c = 0; c < first.numberOfChannels; c++) this.channels.push(new Float32Array(first.length))
this.setLevels(levels)
}
/** Re-sum for new mute/solo levels. In slices over a few frames, so a toggle
* never stalls the page (a 6-minute track is tens of millions of samples);
* until it finishes, a scratch hears the previous mix. */
setLevels(levels: number[]): void {
if (!this.stems.length) return
const gen = ++this.build
const n = this.length
const next = this.channels.map(() => new Float32Array(n))
const tmp = new Float32Array(1 << 18)
let at = 0
const step = () => {
if (gen !== this.build) return
const end = Math.min(n, at + tmp.length)
const len = end - at
const view: Float32Array<ArrayBuffer> = len === tmp.length ? tmp : tmp.subarray(0, len)
this.stems.forEach((buf, s) => {
const g = levels[s] ?? 1
if (!g) return
for (let c = 0; c < next.length; c++) {
buf.copyFromChannel(view, Math.min(c, buf.numberOfChannels - 1), at)
const dst = next[c]
for (let i = 0; i < len; i++) dst[at + i] += view[i] * g
}
})
at = end
if (at < n) setTimeout(step, 0)
else this.channels = next
}
step()
}
get loaded(): boolean {
return this.length > 0
}
+116 -13
View File
@@ -99,38 +99,98 @@ export interface WaveformAnalysis {
buffer: AudioBuffer
}
export async function analyzeWaveform(url: string, buckets?: number): Promise<WaveformAnalysis> {
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()
const AC: typeof AudioContext =
window.AudioContext ?? (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext
const ctx = new AC()
let audio: AudioBuffer
try {
audio = await ctx.decodeAudioData(arr)
return await ctx.decodeAudioData(arr)
} finally {
void ctx.close()
}
}
const len = audio.length
const sr = audio.sampleRate
const chs = audio.numberOfChannels
function defaultBuckets(len: number, sr: number): number {
// Resolution scales with track length (~140 columns/sec) so the zoomed-in
// main waveform stays crisp; clamped so short/long tracks stay reasonable.
if (buckets == null) {
const seconds = len / sr
buckets = Math.min(48000, Math.max(1600, Math.round(seconds * 140)))
}
return Math.min(48000, Math.max(1600, Math.round((len / sr) * 140)))
}
export async function analyzeWaveform(url: string, buckets?: number): Promise<WaveformAnalysis> {
const audio = await decodeUrl(url)
const len = audio.length
const chs = audio.numberOfChannels
// Downmix to mono.
const mono = new Float32Array(len)
for (let c = 0; c < chs; c++) {
const d = audio.getChannelData(c)
for (let i = 0; i < len; i++) mono[i] += d[i] / chs
}
return { cols: await analyzeMono(mono, audio.sampleRate, buckets), buffer: audio }
}
export interface StemAnalysis {
/** The ordinary three-band columns, of the stems' SUM — the overview. */
cols: WaveColumn[]
/** Per stem, per column: amplitude 0..1 — the main view's lanes. */
lanes: Float32Array[]
buffers: AudioBuffer[]
}
/**
* A stem track: decode its stems (in parallel) and analyse them once. The mix
* stream is never decoded — the deck plays the stems' sum, and one fewer
* full-length buffer is ~140 MB less on a 6-minute track.
*
* Each lane is normalised to its OWN 99.5th percentile so a quiet vocal lane is
* still readable, but never below 5% of the loudest stem's, so a near-silent
* stem draws as near-silence rather than magnified noise.
*/
export async function analyzeStems(urls: string[], buckets?: number): Promise<StemAnalysis> {
const buffers = await Promise.all(urls.map(decodeUrl))
const len = Math.min(...buffers.map((b) => b.length))
const sr = buffers[0].sampleRate
const n = buckets ?? defaultBuckets(len, sr)
const scale = n / len
const mono = new Float32Array(len)
const tmp = new Float32Array(len)
const lanes = buffers.map((buf) => {
const lane = new Float32Array(n)
const chs = buf.numberOfChannels
const monoStem = new Float32Array(len)
for (let c = 0; c < chs; c++) {
buf.copyFromChannel(tmp, c)
for (let i = 0; i < len; i++) monoStem[i] += tmp[i] / chs
}
for (let i = 0; i < len; i++) {
const v = monoStem[i]
mono[i] += v
const a = Math.abs(v)
const b = (i * scale) | 0
if (a > lane[b]) lane[b] = a
}
return lane
})
const ceilOf = (v: Float32Array) => {
const sorted = Float32Array.from(v).sort()
return sorted[Math.floor((sorted.length - 1) * 0.995)]
}
const ceilings = lanes.map(ceilOf)
const loudest = Math.max(1e-6, ...ceilings)
lanes.forEach((lane, k) => {
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 }
}
async function analyzeMono(mono: Float32Array<ArrayBuffer>, sr: number, buckets?: number): Promise<WaveColumn[]> {
const len = mono.length
if (buckets == null) buckets = defaultBuckets(len, sr)
const scale = buckets / len
const lowE = new Float64Array(buckets)
@@ -214,5 +274,48 @@ export async function analyzeWaveform(url: string, buckets?: number): Promise<Wa
high: curve(highR[b] / maxH, 1.05),
}
}
return { cols, buffer: audio }
return cols
}
/**
* Paint one stem LANE: the stem's amplitude as symmetric bars in its own
* colour, across [y0, y0 + laneH). Same track-space binning as `paintWave`, so
* lanes and the plain view scroll identically. A muted stem is drawn faint.
*/
export function paintLane(
ctx: CanvasRenderingContext2D,
lane: Float32Array,
color: string,
w: number,
y0: number,
laneH: number,
startFrac: number,
endFrac: number,
opts: PaintOptions,
dim: boolean,
): void {
const n = lane.length
if (n === 0 || w === 0 || laneH <= 0 || endFrac <= startFrac) return
const mid = y0 + laneH / 2
const reach = laneH / 2 - 1
const colsPerPx = ((endFrac - startFrac) * n) / w
const colsPerBar = (opts.bar + opts.gap) * colsPerPx
const startCol = startFrac * n
const k0 = Math.floor(Math.max(0, startCol) / colsPerBar)
const k1 = Math.ceil(Math.min(n, endFrac * n) / colsPerBar)
const prevAlpha = ctx.globalAlpha
ctx.globalAlpha = dim ? 0.18 : 0.92
ctx.fillStyle = color
for (let k = k0; k < k1; k++) {
const c0 = k * colsPerBar
const i0 = Math.max(0, Math.floor(c0))
const i1 = Math.min(n, Math.max(i0 + 1, Math.ceil(c0 + colsPerBar)))
let v = 0
for (let i = i0; i < i1; i++) if (lane[i] > v) v = lane[i]
if (v <= 0) continue
const x = (c0 - startCol) / colsPerPx
const half = Math.max(0.5, v * reach)
ctx.fillRect(x, mid - half, opts.bar, half * 2)
}
ctx.globalAlpha = prevAlpha
}