mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Implemented new audio engine and deck engine
This commit is contained in:
1 parent
4fdb2b7ce1
commit
f5e7202f3f
19 files changed
+1794
-577
No files matched your search
@@ -51,3 +51,6 @@ backend/dist/
|
|||||||
# ---- Stem engine (PyInstaller onedir build) ----
|
# ---- Stem engine (PyInstaller onedir build) ----
|
||||||
engine/build/
|
engine/build/
|
||||||
engine/dist/
|
engine/dist/
|
||||||
|
|
||||||
|
# ---- Rubber Band build (frontend/rubberband/build.sh downloads + compiles here) ----
|
||||||
|
frontend/rubberband/upstream/
|
||||||
@@ -1334,11 +1334,10 @@ Two independent apps that talk over HTTP:
|
|||||||
- **Stem playback** (decided 2026-09-30): a stem FILE always loads its four
|
- **Stem playback** (decided 2026-09-30): a stem FILE always loads its four
|
||||||
stems (`trackStemsFor` / `trackStemUrl` in `api.ts`) and the deck plays
|
stems (`trackStemsFor` / `trackStemUrl` in `api.ts`) and the deck plays
|
||||||
their SUM, as Traktor's stem deck does — the mix stream is never decoded,
|
their SUM, as Traktor's stem deck does — the mix stream is never decoded,
|
||||||
which also saves a full-length buffer. `PlaybackEngine.load` takes several
|
which also saves a full-length buffer. The deck's worklet (`lib/audio/`)
|
||||||
buffers: one source + gain each, all started at ONE scheduled context
|
takes several stems and reads them all at ONE position, so they stay
|
||||||
time (so they stay sample-locked through seeks and loops), mute/solo as
|
sample-locked through seeks, loops and scratch (which hears what is
|
||||||
ramped gains, never a restart. `ScratchEngine.loadStems` keeps ONE summed
|
audible); mute/solo are ramped gains, never a restart.
|
||||||
copy of the audible stems (not four), re-summed in slices on a mute change.
|
|
||||||
`analyzeStems` returns the overview's three-band columns (of the sum) plus
|
`analyzeStems` returns the overview's three-band columns (of the sum) plus
|
||||||
one amplitude lane per stem, each normalised to its own 99.5th percentile
|
one amplitude lane per stem, each normalised to its own 99.5th percentile
|
||||||
but never below 5% of the loudest (a silent stem stays silent).
|
but never below 5% of the loudest (a silent stem stays silent).
|
||||||
@@ -1347,8 +1346,10 @@ Two independent apps that talk over HTTP:
|
|||||||
Q W E R mute stems 1-4, Shift+ solos. **Solo is not a mode**: it SETS the
|
Q W E R mute stems 1-4, Shift+ solos. **Solo is not a mode**: it SETS the
|
||||||
mutes (every other stem muted), so each stem stays freely mutable after
|
mutes (every other stem muted), so each stem stays freely mutable after
|
||||||
it; soloing the one stem still playing unmutes all. Mutes reset per track. Memory is
|
it; soloing the one stem still playing unmutes all. Mutes reset per track. Memory is
|
||||||
the cost: ~140 MB per stem for 6 minutes, i.e. the same four buffers as
|
the cost: ~127 MB of stereo PCM per stem for 6 minutes in the worklet,
|
||||||
the file holds streams, and no more.
|
plus a half-size mono copy each on the main thread for the raw waveform —
|
||||||
|
~6 stereo-track units for a stem track (it was 5: four buffers plus a
|
||||||
|
summed scratch copy), 1.5 for a plain track (it was 2).
|
||||||
- **Prep strip** (DJ deck across the top of the window): `PrepStrip` owns it,
|
- **Prep strip** (DJ deck across the top of the window): `PrepStrip` owns it,
|
||||||
in three rows. **Header**: cover, title/artist · album · genre, a Read-only
|
in three rows. **Header**: cover, title/artist · album · genre, a Read-only
|
||||||
badge, the readout well (ELAPSED / REMAIN to tenths, KEY, and `BpmReadout` —
|
badge, the readout well (ELAPSED / REMAIN to tenths, KEY, and `BpmReadout` —
|
||||||
@@ -1384,7 +1385,7 @@ Two independent apps that talk over HTTP:
|
|||||||
outline (`drawLoop(…, idle)`), so the toggle shows what it would restore.
|
outline (`drawLoop(…, idle)`), so the toggle shows what it would restore.
|
||||||
**‹ › (and ←/→) MOVE an engaged loop by its own length**, Traktor-style,
|
**‹ › (and ←/→) MOVE an engaged loop by its own length**, Traktor-style,
|
||||||
and only jump the playhead when no loop is engaged. The move sets the new
|
and only jump the playhead when no loop is engaged. The move sets the new
|
||||||
loop BEFORE seeking: `PlaybackEngine.seek` honours the loop in force, so
|
loop BEFORE seeking: the deck's seek honours the loop in force, so
|
||||||
seeking first wraps the playhead back into the old loop.
|
seeking first wraps the playhead back into the old loop.
|
||||||
- **Memory cues** (decided 2026-10-16, [the discussion](.claude/discussions/discuss-memory-cues-2026-10-16.md)):
|
- **Memory cues** (decided 2026-10-16, [the discussion](.claude/discussions/discuss-memory-cues-2026-10-16.md)):
|
||||||
Mem mode replaces the pads with `MemoryCueStrip` — chips in TIME order,
|
Mem mode replaces the pads with `MemoryCueStrip` — chips in TIME order,
|
||||||
@@ -1406,8 +1407,8 @@ Two independent apps that talk over HTTP:
|
|||||||
type dropdown or delete button. Rename re-sets the slot with its own start/type/length plus the
|
type dropdown or delete button. Rename re-sets the slot with its own start/type/length plus the
|
||||||
new name, since `set_cue` replaces a slot. A non-editable cue gets the
|
new name, since `set_cue` replaces a slot. A non-editable cue gets the
|
||||||
same menu disabled, not no menu.
|
same menu disabled, not no menu.
|
||||||
Prep libs live in `src/lib/`: `playbackEngine.ts` (Web Audio, seamless loops),
|
Prep libs live in `src/lib/`: `audio/` (the deck's worklet engine:
|
||||||
`scratchEngine.ts` (drag-to-scratch), `waveform.ts` (frequency-colored
|
playback, loops, scratch, varispeed, keylock), `waveform.ts` (frequency-colored
|
||||||
analysis + paint), `beatgrid.ts` (the marker-list beat math — every
|
analysis + paint), `beatgrid.ts` (the marker-list beat math — every
|
||||||
beat/bar/snap/jump calculation goes through it), `cues.ts` (draw
|
beat/bar/snap/jump calculation goes through it), `cues.ts` (draw
|
||||||
cues/loop/beatgrid/cue-point). See "Prep engine" below.
|
cues/loop/beatgrid/cue-point). See "Prep engine" below.
|
||||||
@@ -2711,19 +2712,37 @@ diff — no COLLECTION splicing needed.
|
|||||||
The prep strip plays every track through the **Web Audio API** (a plain
|
The prep strip plays every track through the **Web Audio API** (a plain
|
||||||
`<audio>` element can't do reverse/arbitrary-rate scratch or seamless loops).
|
`<audio>` element can't do reverse/arbitrary-rate scratch or seamless loops).
|
||||||
|
|
||||||
- `playbackEngine.ts` — an `AudioBufferSourceNode` with a `startOffset`/
|
- **`lib/audio/` — one AudioWorklet per deck** (2026-11-02, the first step of
|
||||||
`startedAt` position model; `getPosition()` reads the AudioContext clock
|
performance mode; [the discussion](.claude/discussions/discuss-performance-mode-2026-11-02.md)).
|
||||||
(high-res → smooth playhead). Seamless loops via native `loopStart`/`loopEnd`;
|
`deckCore.ts` renders a deck block by block: transport, seamless loops, the
|
||||||
`setLoop()` re-anchors position so enabling/disabling a loop doesn't desync.
|
stems in lockstep (ONE position for all), mute/solo as ramped gains,
|
||||||
- `scratchEngine.ts` — a persistent (idle-silent) `ScriptProcessorNode` that,
|
varispeed (cubic interpolation) and scratch (the old ScriptProcessor's
|
||||||
while dragging the main waveform, plays PCM at a position gliding toward the
|
drag/inertia feel; a release coasts and the deck PLAYS ON BY ITSELF, so there
|
||||||
cursor, then coasts with inertia on release.
|
is no gap). `deckProcessor.worklet.ts` wraps it (`?worker&url`, bundled
|
||||||
- **CRITICAL gotcha**: playing an `AudioBuffer` "acquires the content" in
|
self-contained); `deckEngine.ts` is the main thread's handle, with the old
|
||||||
Firefox and **detaches** any `getChannelData()` views held elsewhere. The
|
PlaybackEngine's surface: commands are async, so it answers from a model
|
||||||
scratch engine therefore **copies** the PCM in `load()` (never holds the
|
(last report + context clock, `position.ts`) that each command updates at
|
||||||
playback buffer's views). Playback and scratch also run on **separate
|
once, and a GENERATION drops reports older than the latest positional
|
||||||
`AudioContext`s** — sharing one goes silent after a source has played.
|
command. `context.ts` is the app's ONE AudioContext (never closed; a deck
|
||||||
- `waveform.ts` — decodes once (buffer reused by both engines, no re-decode),
|
disconnects its own nodes) with a master bus. It replaced an
|
||||||
|
AudioBufferSourceNode for playback plus a ScriptProcessorNode on a SECOND
|
||||||
|
AudioContext for scratch (sharing one went silent in Firefox once a source
|
||||||
|
had played), which left nowhere for a mixer to sit.
|
||||||
|
**Keylock** = Rubber Band R2 in the worklet (`stretcher.ts`,
|
||||||
|
`rubberband.wasm` built by `frontend/rubberband/build.sh` — see its README
|
||||||
|
for why it is OUR build: licence). One stereo stretcher per stem; R3 does not
|
||||||
|
fit 8 on one render thread (measured). After any seek the deck plays
|
||||||
|
varispeed AT ONCE, primes the stretchers over `WARM_QUANTA` blocks aimed at
|
||||||
|
where the playhead will be, and crossfades when aligned — priming 4 stems in
|
||||||
|
one block would be a dropout per hotcue. Aligned within ±3 ms, no drift over
|
||||||
|
a minute (`deckCore.test.ts`, which drives the real `.wasm` in Node). At
|
||||||
|
rate 1 the stretcher is bypassed.
|
||||||
|
**The PCM is TRANSFERRED to the worklet** (`waveform.DecodedAudio`, copied
|
||||||
|
out of the AudioBuffer once); the main thread keeps only a mono downmix for
|
||||||
|
the raw waveform. (The Firefox detach gotcha — playing an AudioBuffer
|
||||||
|
detaches `getChannelData()` views — no longer bites: nothing plays an
|
||||||
|
AudioBuffer now.)
|
||||||
|
- `waveform.ts` — decodes once (the PCM goes to the deck's worklet, no re-decode),
|
||||||
splits into 3 bands via `OfflineAudioContext` biquads, and paints them as
|
splits into 3 bands via `OfflineAudioContext` biquads, and paints them as
|
||||||
**three layers**, not one blended colour per column: bass (orange) first and
|
**three layers**, not one blended colour per column: bass (orange) first and
|
||||||
tallest, then mids (violet) and highs (cyan) with a `screen` blend — no green,
|
tallest, then mids (violet) and highs (cyan) with a `screen` blend — no green,
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
# Rubber Band (keylock)
|
||||||
|
|
||||||
|
`src/lib/audio/rubberband.wasm` is the [Rubber Band Library](https://breakfastquay.com/rubberband/)
|
||||||
|
3.3.0 compiled to WebAssembly with Konduktor's own glue (`glue.c`). The deck's
|
||||||
|
audio worklet uses it for keylock: tempo changes without a pitch change. It
|
||||||
|
runs the R2 ("faster") engine in real-time mode.
|
||||||
|
|
||||||
|
**Licence.** Rubber Band is GPL-2.0-or-later. Every upstream source file says
|
||||||
|
"either version 2 of the License, or (at your option) any later version", and
|
||||||
|
its bundled `src/ext` code (KissFFT, Speex resampler, getopt, pommier) is
|
||||||
|
permissive. That is what allows it to combine with Konduktor's AGPL-3.0, via
|
||||||
|
GPLv3 §13. Do NOT replace it with a prebuilt npm package:
|
||||||
|
`rubberband-wasm`'s glue is labelled "GPLv2" without "or later", and
|
||||||
|
`@echogarden/rubberband-wasm` is GPL-2.0-only. Neither can be combined with
|
||||||
|
AGPL-3.0.
|
||||||
|
|
||||||
|
**Corresponding source** for the `.wasm`: `build.sh` plus `glue.c` plus the
|
||||||
|
upstream release it downloads, which is pinned by version and SHA-256.
|
||||||
|
|
||||||
|
**Rebuilding** is needed only when bumping Rubber Band or changing the glue:
|
||||||
|
run `./build.sh`, which needs `emcc` on PATH (`brew install emscripten`). The
|
||||||
|
`.wasm` is checked in, so neither `npm run dev` nor a release build needs
|
||||||
|
emscripten.
|
||||||
|
|
||||||
|
**Measured** (2026-11-02, Apple M3 Pro, stereo 44.1 kHz, 128-frame quanta):
|
||||||
|
about 40-55x realtime in both JavaScriptCore (WKWebView) and V8 (WebView2).
|
||||||
|
p99 is about 0.17 ms per quantum against a 2.9 ms budget, so 8 stretchers
|
||||||
|
(2 stem decks) fit on the one audio render thread. The R3 ("finer") engine is
|
||||||
|
about 11x realtime and does not fit at 8. `-msimd128` measured no faster than
|
||||||
|
the `-Oz` npm build.
|
||||||
Executable
+48
@@ -0,0 +1,48 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Builds src/lib/audio/rubberband.wasm — the Rubber Band Library compiled to
|
||||||
|
# WebAssembly with Konduktor's own glue (glue.c) — for the deck's keylock.
|
||||||
|
#
|
||||||
|
# The .wasm is checked in, so dev and release builds need no emscripten; rerun
|
||||||
|
# this only when bumping Rubber Band or changing the glue. Needs emcc on PATH
|
||||||
|
# (macOS: `brew install emscripten`).
|
||||||
|
#
|
||||||
|
# Upstream is pinned by version AND SHA-256. Rubber Band is GPL-2.0-or-later
|
||||||
|
# ("either version 2 of the License, or (at your option) any later version"),
|
||||||
|
# which is what lets it combine with Konduktor's AGPL-3.0 — do NOT swap in a
|
||||||
|
# prebuilt npm package: their glue is labelled GPL-2.0(-only).
|
||||||
|
set -euo pipefail
|
||||||
|
cd "$(dirname "$0")"
|
||||||
|
|
||||||
|
VERSION=3.3.0
|
||||||
|
SHA256=d9ef89e2b8ef9f85b13ac3c2faec30e20acf2c9f3a9c8c45ce637f2bc95e576c
|
||||||
|
TARBALL="upstream/rubberband-${VERSION}.tar.bz2"
|
||||||
|
SRC="upstream/rubberband-${VERSION}"
|
||||||
|
OUT=../src/lib/audio/rubberband.wasm
|
||||||
|
|
||||||
|
mkdir -p upstream
|
||||||
|
if [ ! -f "$TARBALL" ]; then
|
||||||
|
curl -fsSL -o "$TARBALL" "https://breakfastquay.com/files/releases/rubberband-${VERSION}.tar.bz2"
|
||||||
|
fi
|
||||||
|
echo "${SHA256} ${TARBALL}" | shasum -a 256 -c -
|
||||||
|
rm -rf "$SRC"
|
||||||
|
tar xjf "$TARBALL" -C upstream
|
||||||
|
|
||||||
|
# -O3 + SIMD for speed on the audio thread (every deck's stretchers share one
|
||||||
|
# render thread). Single-threaded: RubberBandSingle.cpp sets NO_THREADING.
|
||||||
|
FLAGS=(-O3 -flto -msimd128 -fno-rtti -I"$SRC/rubberband")
|
||||||
|
|
||||||
|
# Rubber Band is C++, the glue C: compile each with its own driver, link as C++.
|
||||||
|
OBJ=upstream/obj
|
||||||
|
mkdir -p "$OBJ"
|
||||||
|
em++ "${FLAGS[@]}" -c "$SRC/single/RubberBandSingle.cpp" -o "$OBJ/rubberband.o"
|
||||||
|
emcc "${FLAGS[@]}" -c glue.c -o "$OBJ/glue.o"
|
||||||
|
em++ "${FLAGS[@]}" "$OBJ/rubberband.o" "$OBJ/glue.o" \
|
||||||
|
-sSTANDALONE_WASM=1 \
|
||||||
|
-sALLOW_MEMORY_GROWTH=1 \
|
||||||
|
-sFILESYSTEM=0 \
|
||||||
|
-sASSERTIONS=0 \
|
||||||
|
-sERROR_ON_UNDEFINED_SYMBOLS=1 \
|
||||||
|
--no-entry \
|
||||||
|
-o "$OUT"
|
||||||
|
|
||||||
|
echo "wrote $OUT ($(wc -c < "$OUT" | tr -d ' ') bytes)"
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
/*
|
||||||
|
* Konduktor's WebAssembly interface to the Rubber Band Library, used by the
|
||||||
|
* deck's keylock (time-stretch without a pitch change). Part of Konduktor,
|
||||||
|
* licensed under the GNU AGPL-3.0 (see LICENSE at the repository root).
|
||||||
|
*
|
||||||
|
* Plain exports of the C API the deck worklet calls, plus malloc/free so it
|
||||||
|
* can place its sample buffers in the module's memory. Rubber Band itself is
|
||||||
|
* GPL-2.0-or-later (see README.md here).
|
||||||
|
*/
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <emscripten.h>
|
||||||
|
#include <rubberband-c.h>
|
||||||
|
|
||||||
|
#define EXPORT EMSCRIPTEN_KEEPALIVE
|
||||||
|
|
||||||
|
EXPORT void *kd_malloc(size_t size) { return malloc(size); }
|
||||||
|
EXPORT void kd_free(void *ptr) { free(ptr); }
|
||||||
|
|
||||||
|
EXPORT RubberBandState kd_new(unsigned int sample_rate, unsigned int channels,
|
||||||
|
RubberBandOptions options, double time_ratio,
|
||||||
|
double pitch_scale) {
|
||||||
|
return rubberband_new(sample_rate, channels, options, time_ratio, pitch_scale);
|
||||||
|
}
|
||||||
|
EXPORT void kd_delete(RubberBandState s) { rubberband_delete(s); }
|
||||||
|
EXPORT void kd_reset(RubberBandState s) { rubberband_reset(s); }
|
||||||
|
|
||||||
|
EXPORT void kd_set_time_ratio(RubberBandState s, double r) { rubberband_set_time_ratio(s, r); }
|
||||||
|
EXPORT void kd_set_pitch_scale(RubberBandState s, double p) { rubberband_set_pitch_scale(s, p); }
|
||||||
|
EXPORT void kd_set_max_process_size(RubberBandState s, unsigned int n) {
|
||||||
|
rubberband_set_max_process_size(s, n);
|
||||||
|
}
|
||||||
|
|
||||||
|
EXPORT unsigned int kd_get_preferred_start_pad(RubberBandState s) {
|
||||||
|
return rubberband_get_preferred_start_pad(s);
|
||||||
|
}
|
||||||
|
EXPORT unsigned int kd_get_start_delay(RubberBandState s) { return rubberband_get_start_delay(s); }
|
||||||
|
EXPORT unsigned int kd_get_samples_required(RubberBandState s) {
|
||||||
|
return rubberband_get_samples_required(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
EXPORT void kd_process(RubberBandState s, const float *const *input, unsigned int samples,
|
||||||
|
int final) {
|
||||||
|
rubberband_process(s, input, samples, final);
|
||||||
|
}
|
||||||
|
EXPORT int kd_available(RubberBandState s) { return rubberband_available(s); }
|
||||||
|
EXPORT unsigned int kd_retrieve(RubberBandState s, float *const *output, unsigned int samples) {
|
||||||
|
return rubberband_retrieve(s, output, samples);
|
||||||
|
}
|
||||||
@@ -24,8 +24,8 @@ import { analyzeStems, analyzeWaveform, type WaveColumn } from '../lib/waveform'
|
|||||||
import type { RawWave } from '../lib/rawWave'
|
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 { DeckEngine } from '../lib/audio/deckEngine'
|
||||||
import { PlaybackEngine } from '../lib/playbackEngine'
|
import { resumeAudio } from '../lib/audio/context'
|
||||||
import { invalidateTrackLists } from '../lib/trackQueries'
|
import { invalidateTrackLists } from '../lib/trackQueries'
|
||||||
import { AutoCueDialog, eventLabel } from './AutoCueDialog'
|
import { AutoCueDialog, eventLabel } from './AutoCueDialog'
|
||||||
import { TrackInfoDialog } from './TrackInfoDialog'
|
import { TrackInfoDialog } from './TrackInfoDialog'
|
||||||
@@ -104,9 +104,9 @@ function slotForDigit(code: string, slotCount: number): number | null {
|
|||||||
/**
|
/**
|
||||||
* The DJ-style "prep strip" across the top of the window: transport controls on
|
* The DJ-style "prep strip" across the top of the window: transport controls on
|
||||||
* the left, waveforms on the right (a scrolling zoomable main view above a
|
* the left, waveforms on the right (a scrolling zoomable main view above a
|
||||||
* whole-track overview), plus loop + hotcue controls. Playback runs through the
|
* whole-track overview), plus loop + hotcue controls. Playback, loops and
|
||||||
* Web Audio PlaybackEngine (seamless loops); the same decoded buffer feeds the
|
* scratch all run in the deck's audio worklet (DeckEngine); the audio is
|
||||||
* scratch engine and both waveform views.
|
* decoded once for it and both waveform views.
|
||||||
*/
|
*/
|
||||||
export function PrepStrip({
|
export function PrepStrip({
|
||||||
track,
|
track,
|
||||||
@@ -172,13 +172,13 @@ export function PrepStrip({
|
|||||||
const [loopInPoint, setLoopInPoint] = useState<number | null>(null)
|
const [loopInPoint, setLoopInPoint] = useState<number | null>(null)
|
||||||
const originalGridRef = useRef<GridMarker[] | null>(null)
|
const originalGridRef = useRef<GridMarker[] | null>(null)
|
||||||
|
|
||||||
const audioCtxRef = useRef<AudioContext | null>(null) // playback
|
// The deck's audio (created once, asynchronously: the worklet module loads
|
||||||
const scratchCtxRef = useRef<AudioContext | null>(null) // scratch (kept separate!)
|
// first). playbackRef is set once it exists; getEngine() awaits it.
|
||||||
const playbackRef = useRef<PlaybackEngine | null>(null)
|
const playbackRef = useRef<DeckEngine | null>(null)
|
||||||
const scratchRef = useRef<ScratchEngine | null>(null)
|
const enginePromiseRef = useRef<Promise<DeckEngine> | null>(null)
|
||||||
const wasPlayingRef = useRef(false)
|
const wasPlayingRef = useRef(false)
|
||||||
const scratchRafRef = useRef(0)
|
const scratchRafRef = useRef(0)
|
||||||
const engagedRef = useRef(false) // scratch engine is dragging or coasting
|
const engagedRef = useRef(false) // the deck is scratching (dragging or coasting)
|
||||||
const pendingPlayRef = useRef(false) // a play was requested; start once ready
|
const pendingPlayRef = useRef(false) // a play was requested; start once ready
|
||||||
const loadedIdRef = useRef<string | null>(null) // trackId whose buffer is loaded
|
const loadedIdRef = useRef<string | null>(null) // trackId whose buffer is loaded
|
||||||
const [gridBusy, setGridBusy] = useState(false)
|
const [gridBusy, setGridBusy] = useState(false)
|
||||||
@@ -238,43 +238,35 @@ export function PrepStrip({
|
|||||||
writePrefs({ cueBankMode: bankMode })
|
writePrefs({ cueBankMode: bankMode })
|
||||||
}, [bankMode, writePrefs])
|
}, [bankMode, writePrefs])
|
||||||
|
|
||||||
const getCtx = (): AudioContext => {
|
const getEngine = (): Promise<DeckEngine> => {
|
||||||
if (!audioCtxRef.current) {
|
if (!enginePromiseRef.current) {
|
||||||
audioCtxRef.current = new (window.AudioContext ??
|
enginePromiseRef.current = DeckEngine.create().then((eng) => {
|
||||||
(window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext)()
|
playbackRef.current = eng
|
||||||
|
eng.setOnEnded(() => setPlaying(false))
|
||||||
|
// The deck hands itself back after a scratch's coast settles.
|
||||||
|
eng.setOnScratchDone((resumed) => scratchDoneRef.current(resumed))
|
||||||
|
return eng
|
||||||
|
})
|
||||||
|
enginePromiseRef.current.catch(() => {
|
||||||
|
enginePromiseRef.current = null
|
||||||
|
})
|
||||||
}
|
}
|
||||||
void audioCtxRef.current.resume()
|
return enginePromiseRef.current
|
||||||
return audioCtxRef.current
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Tear everything down when the strip itself unmounts (e.g. the collection
|
// Tear the deck's audio down when the strip itself unmounts (e.g. the
|
||||||
// picker early-returns and replaces the whole UI). Without this, the playback
|
// collection picker early-returns and replaces the whole UI) — otherwise a
|
||||||
// source keeps running in an AudioContext that's never closed, so a fresh
|
// remount would play a SECOND track over the orphaned one. The AudioContext
|
||||||
// remount plays a SECOND track on top of the orphaned one. Closing both
|
// is the app's and stays; this deck's nodes leave it.
|
||||||
// contexts is the surefire kill; runs once, on unmount.
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
return () => {
|
return () => {
|
||||||
playbackRef.current?.pause()
|
const pending = enginePromiseRef.current
|
||||||
scratchRef.current?.dispose()
|
enginePromiseRef.current = null
|
||||||
void audioCtxRef.current?.close()
|
playbackRef.current = null
|
||||||
void scratchCtxRef.current?.close()
|
void pending?.then((eng) => eng.dispose())
|
||||||
audioCtxRef.current = null
|
|
||||||
scratchCtxRef.current = null
|
|
||||||
}
|
}
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
// The scratch engine gets its OWN AudioContext: a ScriptProcessorNode is
|
|
||||||
// unreliable sharing a context with the playback source node (it goes silent
|
|
||||||
// once a source has played), so we keep them fully separate.
|
|
||||||
const getScratchCtx = (): AudioContext => {
|
|
||||||
if (!scratchCtxRef.current) {
|
|
||||||
scratchCtxRef.current = new (window.AudioContext ??
|
|
||||||
(window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext)()
|
|
||||||
}
|
|
||||||
void scratchCtxRef.current.resume()
|
|
||||||
return scratchCtxRef.current
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reset transport + loop state when the loaded track changes.
|
// Reset transport + loop state when the loaded track changes.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
playbackRef.current?.pause()
|
playbackRef.current?.pause()
|
||||||
@@ -307,8 +299,6 @@ export function PrepStrip({
|
|||||||
// Analyse once per track; the decoded buffer feeds both the playback and
|
// Analyse once per track; the decoded buffer feeds both the playback and
|
||||||
// scratch engines (no re-decode) and both waveform views share the columns.
|
// scratch engines (no re-decode) and both waveform views share the columns.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
scratchRef.current?.dispose()
|
|
||||||
scratchRef.current = null
|
|
||||||
if (!trackId) {
|
if (!trackId) {
|
||||||
setCols(null)
|
setCols(null)
|
||||||
setRaw(null)
|
setRaw(null)
|
||||||
@@ -330,13 +320,13 @@ 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, raw: null, raws: res.raws }
|
return { cols: res.cols, audios: res.audios, 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, raw: res.raw, raws: null }
|
return { cols: res.cols, audios: [res.audio], lanes: null, stems: null, raw: res.raw, raws: null }
|
||||||
})
|
})
|
||||||
load
|
Promise.all([load, getEngine()])
|
||||||
.then((res) => {
|
.then(([res, eng]) => {
|
||||||
if (cancelled) return
|
if (cancelled) return
|
||||||
setCols(res.cols)
|
setCols(res.cols)
|
||||||
setRaw(res.raw)
|
setRaw(res.raw)
|
||||||
@@ -344,24 +334,15 @@ export function PrepStrip({
|
|||||||
setStems(res.stems)
|
setStems(res.stems)
|
||||||
setStemLanes(res.lanes)
|
setStemLanes(res.lanes)
|
||||||
setWaveStatus('ready')
|
setWaveStatus('ready')
|
||||||
const ctx = getCtx()
|
// The PCM moves to the audio thread here (transferred, not copied).
|
||||||
const sc = new ScratchEngine()
|
eng.load(res.audios)
|
||||||
if (res.stems) sc.loadStems(res.buffers, res.buffers.map(() => 1))
|
setDuration(res.audios[0].duration)
|
||||||
else sc.load(res.buffers[0])
|
|
||||||
sc.attach(getScratchCtx()) // own context; warm up so the first scratch isn't silent
|
|
||||||
scratchRef.current = sc
|
|
||||||
if (!playbackRef.current) {
|
|
||||||
playbackRef.current = new PlaybackEngine()
|
|
||||||
playbackRef.current.setOnEnded(() => setPlaying(false))
|
|
||||||
}
|
|
||||||
playbackRef.current.load(ctx, res.stems ? res.buffers : res.buffers[0])
|
|
||||||
setDuration(res.buffers[0].duration)
|
|
||||||
setReady(true)
|
setReady(true)
|
||||||
loadedIdRef.current = trackId
|
loadedIdRef.current = trackId
|
||||||
// A play was requested (library row button) → start now that it's ready.
|
// A play was requested (library row button) → start now that it's ready.
|
||||||
if (pendingPlayRef.current) {
|
if (pendingPlayRef.current) {
|
||||||
pendingPlayRef.current = false
|
pendingPlayRef.current = false
|
||||||
playbackRef.current.play()
|
eng.play()
|
||||||
setPlaying(true)
|
setPlaying(true)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -414,7 +395,7 @@ export function PrepStrip({
|
|||||||
const toggle = () => {
|
const toggle = () => {
|
||||||
const eng = playbackRef.current
|
const eng = playbackRef.current
|
||||||
if (!eng || !eng.ready) return
|
if (!eng || !eng.ready) return
|
||||||
getCtx() // ensure the context resumes on this user gesture
|
resumeAudio() // resume on this user gesture
|
||||||
// Play pressed during a momentary cue preview → latch playback on so it
|
// Play pressed during a momentary cue preview → latch playback on so it
|
||||||
// keeps going after the hotcue button is released.
|
// keeps going after the hotcue button is released.
|
||||||
const pv = previewRef.current
|
const pv = previewRef.current
|
||||||
@@ -473,7 +454,7 @@ export function PrepStrip({
|
|||||||
const eng = playbackRef.current
|
const eng = playbackRef.current
|
||||||
if (!eng || !eng.ready) return
|
if (!eng || !eng.ready) return
|
||||||
setCueHeld(true)
|
setCueHeld(true)
|
||||||
getCtx()
|
resumeAudio()
|
||||||
if (eng.playing) {
|
if (eng.playing) {
|
||||||
leaveLoopFor(cuePoint)
|
leaveLoopFor(cuePoint)
|
||||||
eng.pause()
|
eng.pause()
|
||||||
@@ -518,7 +499,7 @@ export function PrepStrip({
|
|||||||
const eng = playbackRef.current
|
const eng = playbackRef.current
|
||||||
if (loadedIdRef.current === trackId && eng?.ready) {
|
if (loadedIdRef.current === trackId && eng?.ready) {
|
||||||
pendingPlayRef.current = false
|
pendingPlayRef.current = false
|
||||||
getCtx()
|
resumeAudio()
|
||||||
eng.play()
|
eng.play()
|
||||||
setPlaying(true)
|
setPlaying(true)
|
||||||
setCurrent(eng.getPosition())
|
setCurrent(eng.getPosition())
|
||||||
@@ -606,62 +587,52 @@ export function PrepStrip({
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ---- scratch ----------------------------------------------------------
|
// ---- scratch ----------------------------------------------------------
|
||||||
const finalizeScratch = () => {
|
// The deck scratches itself: a drag moves its position, a release coasts to
|
||||||
|
// playing speed (or a stop) and it plays on BY ITSELF, then says so — so
|
||||||
|
// there is no gap between the coast and the music. React only mirrors it.
|
||||||
|
const scratchDone = (resumed: boolean) => {
|
||||||
cancelAnimationFrame(scratchRafRef.current)
|
cancelAnimationFrame(scratchRafRef.current)
|
||||||
engagedRef.current = false
|
engagedRef.current = false
|
||||||
const sc = scratchRef.current
|
const eng = playbackRef.current
|
||||||
if (!sc) return
|
if (eng) setCurrent(eng.getPosition())
|
||||||
const finalSec = sc.end()
|
setPlaying(resumed)
|
||||||
const pb = playbackRef.current
|
|
||||||
if (pb) pb.seek(finalSec)
|
|
||||||
setCurrent(finalSec)
|
|
||||||
if (wasPlayingRef.current && pb) {
|
|
||||||
pb.play()
|
|
||||||
setPlaying(true)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
const scratchDoneRef = useRef(scratchDone)
|
||||||
|
scratchDoneRef.current = scratchDone
|
||||||
|
|
||||||
const runScratchRaf = () => {
|
const runScratchRaf = () => {
|
||||||
cancelAnimationFrame(scratchRafRef.current)
|
cancelAnimationFrame(scratchRafRef.current)
|
||||||
const sc = scratchRef.current!
|
|
||||||
const tick = () => {
|
const tick = () => {
|
||||||
setCurrent(sc.getPositionSec())
|
const eng = playbackRef.current
|
||||||
if (sc.finished) {
|
if (!eng || !engagedRef.current) return
|
||||||
finalizeScratch()
|
setCurrent(eng.getPosition())
|
||||||
return
|
|
||||||
}
|
|
||||||
scratchRafRef.current = requestAnimationFrame(tick)
|
scratchRafRef.current = requestAnimationFrame(tick)
|
||||||
}
|
}
|
||||||
scratchRafRef.current = requestAnimationFrame(tick)
|
scratchRafRef.current = requestAnimationFrame(tick)
|
||||||
}
|
}
|
||||||
|
|
||||||
const onScratchStart = () => {
|
const onScratchStart = () => {
|
||||||
const sc = scratchRef.current
|
const eng = playbackRef.current
|
||||||
if (engagedRef.current && sc) {
|
if (!eng || !eng.ready) return
|
||||||
sc.regrab() // re-grab while coasting
|
if (engagedRef.current) {
|
||||||
|
eng.scratchRegrab() // re-grab while coasting
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
const pb = playbackRef.current
|
wasPlayingRef.current = eng.playing
|
||||||
wasPlayingRef.current = !!pb && pb.playing
|
if (eng.playing) setPlaying(false)
|
||||||
if (pb && pb.playing) {
|
eng.scratchBegin(eng.getPosition())
|
||||||
pb.pause()
|
engagedRef.current = true
|
||||||
setPlaying(false)
|
runScratchRaf()
|
||||||
}
|
|
||||||
if (sc && sc.loaded) {
|
|
||||||
sc.begin(getScratchCtx(), current)
|
|
||||||
engagedRef.current = true
|
|
||||||
runScratchRaf()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const onScratchMove = (t: number) => {
|
const onScratchMove = (t: number) => {
|
||||||
if (engagedRef.current) scratchRef.current!.setTargetSec(t)
|
if (engagedRef.current) playbackRef.current?.scratchTarget(t)
|
||||||
else setCurrent(t)
|
else setCurrent(t)
|
||||||
}
|
}
|
||||||
|
|
||||||
const onScratchEnd = (t: number) => {
|
const onScratchEnd = (t: number) => {
|
||||||
if (engagedRef.current) {
|
if (engagedRef.current) {
|
||||||
scratchRef.current!.release(wasPlayingRef.current)
|
playbackRef.current?.scratchRelease(wasPlayingRef.current)
|
||||||
} else {
|
} else {
|
||||||
seek(t)
|
seek(t)
|
||||||
if (wasPlayingRef.current) {
|
if (wasPlayingRef.current) {
|
||||||
@@ -849,7 +820,7 @@ export function PrepStrip({
|
|||||||
setSelectedSlot(slot)
|
setSelectedSlot(slot)
|
||||||
const eng = playbackRef.current
|
const eng = playbackRef.current
|
||||||
if (!eng || !eng.ready) return
|
if (!eng || !eng.ready) return
|
||||||
getCtx()
|
resumeAudio()
|
||||||
enterCue(cue)
|
enterCue(cue)
|
||||||
seek(cue.start)
|
seek(cue.start)
|
||||||
// Paused at press → momentary preview: play while held.
|
// Paused at press → momentary preview: play while held.
|
||||||
@@ -978,7 +949,7 @@ export function PrepStrip({
|
|||||||
const callMemoryCue = (cue: CuePoint) => {
|
const callMemoryCue = (cue: CuePoint) => {
|
||||||
const eng = playbackRef.current
|
const eng = playbackRef.current
|
||||||
if (!eng || !eng.ready) return
|
if (!eng || !eng.ready) return
|
||||||
getCtx()
|
resumeAudio()
|
||||||
enterCue(cue)
|
enterCue(cue)
|
||||||
seek(cue.start)
|
seek(cue.start)
|
||||||
setCuePoint(cue.start)
|
setCuePoint(cue.start)
|
||||||
@@ -1256,7 +1227,6 @@ export function PrepStrip({
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!stems) return
|
if (!stems) return
|
||||||
playbackRef.current?.setGains(stemLevels)
|
playbackRef.current?.setGains(stemLevels)
|
||||||
scratchRef.current?.setLevels(stemLevels)
|
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [stemLevelKey])
|
}, [stemLevelKey])
|
||||||
// Solo = "mute every stem but this one". Soloing a stem that is already the
|
// Solo = "mute every stem but this one". Soloing a stem that is already the
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
// The app's ONE AudioContext. Every deck plays into it, so the decks can be
|
||||||
|
// mixed (and limited) before the speakers; two contexts cannot be connected.
|
||||||
|
// Never closed: a deck that goes away disconnects its own nodes.
|
||||||
|
|
||||||
|
import deckWorkletUrl from './deckProcessor.worklet.ts?worker&url'
|
||||||
|
import rubberbandUrl from './rubberband.wasm?url'
|
||||||
|
|
||||||
|
let ctx: AudioContext | null = null
|
||||||
|
let master: GainNode | null = null
|
||||||
|
let worklet: Promise<ArrayBuffer | null> | null = null
|
||||||
|
|
||||||
|
export function audioContext(): AudioContext {
|
||||||
|
if (!ctx) {
|
||||||
|
const AC: typeof AudioContext =
|
||||||
|
window.AudioContext ?? (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext
|
||||||
|
ctx = new AC({ latencyHint: 'interactive' })
|
||||||
|
master = ctx.createGain()
|
||||||
|
master.connect(ctx.destination)
|
||||||
|
}
|
||||||
|
return ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Resume on a user gesture (autoplay policy). */
|
||||||
|
export function resumeAudio(): void {
|
||||||
|
void audioContext().resume()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where decks connect: the master bus. */
|
||||||
|
export function masterInput(): AudioNode {
|
||||||
|
audioContext()
|
||||||
|
return master!
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register the deck processor (once per context) and fetch Rubber Band's
|
||||||
|
* module bytes for keylock. Resolves to null bytes when the module cannot be
|
||||||
|
* fetched — the decks then play without keylock rather than not at all.
|
||||||
|
*/
|
||||||
|
export function loadDeckWorklet(): Promise<ArrayBuffer | null> {
|
||||||
|
if (!worklet) {
|
||||||
|
const c = audioContext()
|
||||||
|
const bytes = fetch(rubberbandUrl)
|
||||||
|
.then((r) => (r.ok ? r.arrayBuffer() : null))
|
||||||
|
.catch(() => null)
|
||||||
|
worklet = c.audioWorklet.addModule(deckWorkletUrl).then(() => bytes)
|
||||||
|
worklet.catch(() => {
|
||||||
|
worklet = null
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return worklet
|
||||||
|
}
|
||||||
@@ -0,0 +1,293 @@
|
|||||||
|
/// <reference types="node" />
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import { DeckCore, QUANTUM, WARM_QUANTA, type DeckSource } from './deckCore'
|
||||||
|
import { extrapolate } from './position'
|
||||||
|
import { RubberBand } from './stretcher'
|
||||||
|
|
||||||
|
const SR = 44100
|
||||||
|
const rb = () => new RubberBand(new WebAssembly.Module(readFileSync(new URL('./rubberband.wasm', import.meta.url))))
|
||||||
|
|
||||||
|
/** A mono track whose every sample is distinct: sample i = i / len. */
|
||||||
|
function ramp(len: number): DeckSource {
|
||||||
|
const ch = new Float32Array(len)
|
||||||
|
for (let i = 0; i < len; i++) ch[i] = i / len
|
||||||
|
return { stems: [[ch]], length: len, sampleRate: SR }
|
||||||
|
}
|
||||||
|
|
||||||
|
function sine(freq: number, seconds: number, clicksEvery?: number): Float32Array {
|
||||||
|
const len = Math.round(seconds * SR)
|
||||||
|
const ch = new Float32Array(len)
|
||||||
|
for (let i = 0; i < len; i++) ch[i] = 0.5 * Math.sin((2 * Math.PI * freq * i) / SR)
|
||||||
|
if (clicksEvery) for (let i = 0; i < len; i += clicksEvery) ch[i] = 1
|
||||||
|
return ch
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Render `blocks` blocks; returns the left channel. */
|
||||||
|
function run(core: DeckCore, blocks: number): Float32Array {
|
||||||
|
const out = new Float32Array(blocks * QUANTUM)
|
||||||
|
const l = new Float32Array(QUANTUM)
|
||||||
|
const r = new Float32Array(QUANTUM)
|
||||||
|
for (let b = 0; b < blocks; b++) {
|
||||||
|
core.render(l, r)
|
||||||
|
out.set(l, b * QUANTUM)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Frequency by counting upward zero crossings. */
|
||||||
|
function pitch(x: Float32Array): number {
|
||||||
|
let n = 0
|
||||||
|
for (let i = 1; i < x.length; i++) if (x[i - 1] < 0 && x[i] >= 0) n++
|
||||||
|
return (n * SR) / x.length
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('DeckCore transport', () => {
|
||||||
|
it('plays the source sample for sample at rate 1', () => {
|
||||||
|
const core = new DeckCore(SR, null)
|
||||||
|
const src = ramp(SR)
|
||||||
|
core.load(src)
|
||||||
|
core.play()
|
||||||
|
const out = run(core, 20)
|
||||||
|
for (let i = 0; i < out.length; i++) expect(out[i]).toBeCloseTo(src.stems[0][0][i], 6)
|
||||||
|
expect(core.positionSec).toBeCloseTo((20 * QUANTUM) / SR, 9)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('is silent and still while paused, and resumes where it stopped', () => {
|
||||||
|
const core = new DeckCore(SR, null)
|
||||||
|
core.load(ramp(SR))
|
||||||
|
core.play()
|
||||||
|
run(core, 4)
|
||||||
|
core.pause()
|
||||||
|
const at = core.positionSec
|
||||||
|
expect(run(core, 4).every((v) => v === 0)).toBe(true)
|
||||||
|
expect(core.positionSec).toBe(at)
|
||||||
|
core.play()
|
||||||
|
expect(run(core, 1)[0]).toBeCloseTo((4 * QUANTUM) / SR, 6)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('loops seamlessly between whole-sample bounds', () => {
|
||||||
|
const core = new DeckCore(SR, null)
|
||||||
|
const src = ramp(SR)
|
||||||
|
core.load(src)
|
||||||
|
const start = 1000
|
||||||
|
const end = 1300
|
||||||
|
core.seek(start / SR)
|
||||||
|
core.setLoop(start / SR, end / SR, true)
|
||||||
|
core.play()
|
||||||
|
const out = run(core, 10)
|
||||||
|
for (let i = 0; i < out.length; i++) {
|
||||||
|
expect(out[i]).toBeCloseTo(src.stems[0][0][start + (i % (end - start))], 6)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('jumps into a loop engaged behind the playhead', () => {
|
||||||
|
const core = new DeckCore(SR, null)
|
||||||
|
core.load(ramp(SR))
|
||||||
|
core.seek(0.5)
|
||||||
|
core.setLoop(0.1, 0.2, true)
|
||||||
|
expect(core.positionSec).toBeCloseTo(0.1, 9)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('varispeed: rate 2 reads every other sample', () => {
|
||||||
|
const core = new DeckCore(SR, null)
|
||||||
|
const src = ramp(SR)
|
||||||
|
core.load(src)
|
||||||
|
core.setRate(2)
|
||||||
|
core.play()
|
||||||
|
const out = run(core, 5)
|
||||||
|
for (let i = 0; i < out.length; i++) expect(out[i]).toBeCloseTo(src.stems[0][0][2 * i], 5)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('reports the end of the track once and stops', () => {
|
||||||
|
const core = new DeckCore(SR, null)
|
||||||
|
core.load(ramp(QUANTUM * 3 + 10))
|
||||||
|
core.play()
|
||||||
|
const events: string[] = []
|
||||||
|
for (let b = 0; b < 6; b++) {
|
||||||
|
run(core, 1)
|
||||||
|
events.push(...core.events)
|
||||||
|
}
|
||||||
|
expect(events).toEqual(['ended'])
|
||||||
|
expect(core.playing).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('plays stems in lockstep, and a mute ramps one out', () => {
|
||||||
|
const a = sine(220, 1)
|
||||||
|
const b = sine(330, 1)
|
||||||
|
const core = new DeckCore(SR, null)
|
||||||
|
core.load({ stems: [[a], [b]], length: a.length, sampleRate: SR })
|
||||||
|
core.play()
|
||||||
|
const both = run(core, 4)
|
||||||
|
for (let i = 0; i < both.length; i++) expect(both[i]).toBeCloseTo(a[i] + b[i], 5)
|
||||||
|
core.setGains([1, 0])
|
||||||
|
run(core, 40) // the 4 ms ramp settles
|
||||||
|
const at = Math.round(core.positionSec * SR)
|
||||||
|
const solo = run(core, 4)
|
||||||
|
for (let i = 0; i < solo.length; i++) expect(solo[i]).toBeCloseTo(a[at + i], 4)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('DeckCore scratch', () => {
|
||||||
|
it('follows the drag, then coasts back to playing speed and plays on by itself', () => {
|
||||||
|
const core = new DeckCore(SR, null)
|
||||||
|
core.load(ramp(SR * 4))
|
||||||
|
core.play()
|
||||||
|
run(core, 10)
|
||||||
|
core.scratchBegin(1)
|
||||||
|
expect(core.scratching).toBe(true)
|
||||||
|
core.scratchTarget(1.2)
|
||||||
|
run(core, 200)
|
||||||
|
expect(core.positionSec).toBeGreaterThan(1.1)
|
||||||
|
core.scratchRelease(true)
|
||||||
|
const events: string[] = []
|
||||||
|
for (let b = 0; b < 2000 && !events.length; b++) {
|
||||||
|
run(core, 1)
|
||||||
|
events.push(...core.events)
|
||||||
|
}
|
||||||
|
expect(events).toEqual(['scratchDone'])
|
||||||
|
expect(core.playing).toBe(true)
|
||||||
|
const before = core.positionSec
|
||||||
|
run(core, 10)
|
||||||
|
expect(core.positionSec - before).toBeCloseTo((10 * QUANTUM) / SR, 6)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a release without resume settles paused', () => {
|
||||||
|
const core = new DeckCore(SR, null)
|
||||||
|
core.load(ramp(SR * 4))
|
||||||
|
core.scratchBegin(1)
|
||||||
|
core.scratchTarget(1.5)
|
||||||
|
run(core, 100)
|
||||||
|
core.scratchRelease(false)
|
||||||
|
for (let b = 0; b < 3000 && core.scratching; b++) run(core, 1)
|
||||||
|
expect(core.scratching).toBe(false)
|
||||||
|
expect(core.playing).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('DeckCore keylock', () => {
|
||||||
|
it('keeps the pitch while the tempo changes; plain varispeed does not', () => {
|
||||||
|
const tone = sine(440, 6)
|
||||||
|
const src: DeckSource = { stems: [[tone]], length: tone.length, sampleRate: SR }
|
||||||
|
|
||||||
|
const plain = new DeckCore(SR, rb())
|
||||||
|
plain.load(src)
|
||||||
|
plain.setRate(1.1)
|
||||||
|
plain.play()
|
||||||
|
expect(pitch(run(plain, 300).subarray(50 * QUANTUM))).toBeCloseTo(484, -1)
|
||||||
|
|
||||||
|
const locked = new DeckCore(SR, rb())
|
||||||
|
locked.load(src)
|
||||||
|
locked.setKeylock(true)
|
||||||
|
locked.setRate(1.1)
|
||||||
|
locked.play()
|
||||||
|
const out = run(locked, 300)
|
||||||
|
expect(locked.stretching).toBe(true)
|
||||||
|
expect(pitch(out.subarray(50 * QUANTUM))).toBeCloseTo(440, -1)
|
||||||
|
// The tempo still changed: the playhead ran at 1.1x.
|
||||||
|
expect(locked.positionSec).toBeCloseTo((1.1 * 300 * QUANTUM) / SR, 6)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('answers a seek at once (varispeed while priming), then hands over to the stretcher', () => {
|
||||||
|
const tone = sine(440, 6)
|
||||||
|
const core = new DeckCore(SR, rb())
|
||||||
|
core.load({ stems: [[tone]], length: tone.length, sampleRate: SR })
|
||||||
|
core.setKeylock(true)
|
||||||
|
core.setRate(0.94)
|
||||||
|
core.play()
|
||||||
|
run(core, 100)
|
||||||
|
core.seek(3)
|
||||||
|
const first = run(core, 1)
|
||||||
|
expect(Math.max(...first.map(Math.abs))).toBeGreaterThan(0.3) // sound in the very first block
|
||||||
|
expect(core.stretching).toBe(false)
|
||||||
|
run(core, WARM_QUANTA + 4)
|
||||||
|
expect(core.stretching).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('stretched output stays aligned with the playhead', () => {
|
||||||
|
// A click every 0.5 s of SOURCE; at 1.05x with keylock each should be heard
|
||||||
|
// where the playhead says it is, within a few ms.
|
||||||
|
const every = SR / 2
|
||||||
|
const tone = sine(110, 8, every).map((v, i) => (i % every === 0 ? 1 : v * 0.1))
|
||||||
|
const core = new DeckCore(SR, rb())
|
||||||
|
core.load({ stems: [[tone]], length: tone.length, sampleRate: SR })
|
||||||
|
core.setKeylock(true)
|
||||||
|
core.setRate(1.05)
|
||||||
|
core.play()
|
||||||
|
const blocks = 1200
|
||||||
|
const out = new Float32Array(blocks * QUANTUM)
|
||||||
|
const posAt = new Float64Array(blocks)
|
||||||
|
const l = new Float32Array(QUANTUM)
|
||||||
|
const r = new Float32Array(QUANTUM)
|
||||||
|
for (let b = 0; b < blocks; b++) {
|
||||||
|
posAt[b] = core.positionSec
|
||||||
|
core.render(l, r)
|
||||||
|
out.set(l, b * QUANTUM)
|
||||||
|
}
|
||||||
|
// Expected output frame of the click at source second s: the block whose
|
||||||
|
// playhead passes s, plus the fraction within it.
|
||||||
|
const errors: number[] = []
|
||||||
|
for (let s = 1; s < 3; s += 0.5) {
|
||||||
|
const b = posAt.findIndex((p) => p > s) - 1
|
||||||
|
const expected = b * QUANTUM + ((s - posAt[b]) * SR) / 1.05
|
||||||
|
let best = 0
|
||||||
|
let at = 0
|
||||||
|
for (let i = Math.round(expected - 2000); i < expected + 2000; i++) {
|
||||||
|
if (Math.abs(out[i]) > best) {
|
||||||
|
best = Math.abs(out[i])
|
||||||
|
at = i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
errors.push(((at - expected) / SR) * 1000)
|
||||||
|
}
|
||||||
|
for (const e of errors) expect(Math.abs(e)).toBeLessThan(6)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('every stem gets its own stretcher and a mute stays instant', () => {
|
||||||
|
const a = sine(220, 4)
|
||||||
|
const b = sine(660, 4)
|
||||||
|
const core = new DeckCore(SR, rb())
|
||||||
|
core.load({ stems: [[a], [b]], length: a.length, sampleRate: SR })
|
||||||
|
core.setKeylock(true)
|
||||||
|
core.setRate(1.08)
|
||||||
|
core.play()
|
||||||
|
run(core, 60)
|
||||||
|
expect(core.stretching).toBe(true)
|
||||||
|
core.setGains([1, 0])
|
||||||
|
run(core, 40)
|
||||||
|
expect(pitch(run(core, 200))).toBeCloseTo(220, -1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('back at rate 1 the stretcher is bypassed', () => {
|
||||||
|
const tone = sine(440, 4)
|
||||||
|
const core = new DeckCore(SR, rb())
|
||||||
|
core.load({ stems: [[tone]], length: tone.length, sampleRate: SR })
|
||||||
|
core.setKeylock(true)
|
||||||
|
core.setRate(1.05)
|
||||||
|
core.play()
|
||||||
|
run(core, 60)
|
||||||
|
expect(core.stretching).toBe(true)
|
||||||
|
core.setRate(1)
|
||||||
|
run(core, 2)
|
||||||
|
expect(core.stretching).toBe(false)
|
||||||
|
const at = Math.round(core.positionSec * SR)
|
||||||
|
const out = run(core, 4)
|
||||||
|
for (let i = 0; i < out.length; i++) expect(out[i]).toBeCloseTo(tone[at + i], 5)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('extrapolate', () => {
|
||||||
|
const noLoop = { start: 0, end: 0, on: false }
|
||||||
|
it('holds still while paused', () => {
|
||||||
|
expect(extrapolate({ pos: 5, time: 1, speed: 1, playing: false, scratching: false }, 3, noLoop, 100)).toBe(5)
|
||||||
|
})
|
||||||
|
it('advances by the speed and clamps at the end', () => {
|
||||||
|
const m = { pos: 5, time: 1, speed: 1.1, playing: true, scratching: false }
|
||||||
|
expect(extrapolate(m, 3, noLoop, 100)).toBeCloseTo(7.2, 9)
|
||||||
|
expect(extrapolate(m, 300, noLoop, 100)).toBe(100)
|
||||||
|
})
|
||||||
|
it('wraps inside an engaged loop', () => {
|
||||||
|
const m = { pos: 9, time: 0, speed: 1, playing: true, scratching: false }
|
||||||
|
expect(extrapolate(m, 2.5, { start: 8, end: 10, on: true }, 100)).toBeCloseTo(9.5, 9)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,607 @@
|
|||||||
|
// One deck's audio, rendered a block at a time: the body of the deck's
|
||||||
|
// AudioWorklet (`deckProcessor.worklet.ts`), kept free of worklet globals so it
|
||||||
|
// can be driven directly in tests.
|
||||||
|
//
|
||||||
|
// ONE chain does everything the deck plays: transport, seamless loops, the
|
||||||
|
// stems in lockstep (one position for all of them), mute/solo as ramped gains,
|
||||||
|
// varispeed (the pitch fader), keylock and scratch. It replaced an
|
||||||
|
// AudioBufferSourceNode for playback plus a ScriptProcessorNode on a SECOND
|
||||||
|
// AudioContext for scratch: those two could not share a context (the scratch
|
||||||
|
// node went silent once a source had played), so there was no single place a
|
||||||
|
// mixer could sit.
|
||||||
|
//
|
||||||
|
// Positions are SOURCE samples (the decoded audio's own rate); a step of
|
||||||
|
// `rate * srcRate / ctxRate` source samples per output frame plays at `rate`.
|
||||||
|
//
|
||||||
|
// KEYLOCK runs the stems through Rubber Band (R2, real time) whenever the rate
|
||||||
|
// is not 1. A stretcher has to be primed before its output lines up with the
|
||||||
|
// playhead, and priming four stems at once would blow one block's budget — a
|
||||||
|
// dropout on every hotcue. So after a seek (or play, loop jump, scratch
|
||||||
|
// hand-back, rate change while priming) the deck plays the plain varispeed path
|
||||||
|
// at once, primes the stretchers over the next blocks aimed at where the
|
||||||
|
// playhead WILL be, and crossfades over one block when the stretched output is
|
||||||
|
// aligned. Near rate 1 those few ms of varispeed are inaudible.
|
||||||
|
|
||||||
|
import { MAX_BLOCK, type RubberBand, Stretcher } from './stretcher'
|
||||||
|
|
||||||
|
/** An AudioWorklet's block length. */
|
||||||
|
export const QUANTUM = 128
|
||||||
|
|
||||||
|
export interface DeckSource {
|
||||||
|
/** Per stem (a plain track is one), per channel (1 or 2). */
|
||||||
|
stems: Float32Array[][]
|
||||||
|
/** Frames, the same for every stem. */
|
||||||
|
length: number
|
||||||
|
sampleRate: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export type DeckEvent = 'ended' | 'scratchDone'
|
||||||
|
|
||||||
|
type Mode = 'stopped' | 'playing' | 'drag' | 'inertia'
|
||||||
|
type StretchState = 'off' | 'warming' | 'on'
|
||||||
|
|
||||||
|
// Scratch feel — the values the ScriptProcessor scratch engine was tuned with.
|
||||||
|
const GLIDE = 400 // samples: how tightly position chases the target while dragging
|
||||||
|
const RATE_CAP = 12 // max source samples per output frame (pitch ceiling)
|
||||||
|
const INERTIA_FRICTION = 0.9998 // per-frame easing toward the target velocity (~0.4 s)
|
||||||
|
const SETTLE_EPS = 0.02 // |velocity - target| below this = settled
|
||||||
|
|
||||||
|
/** Blocks of varispeed while the stretchers prime (~29 ms at 44.1 kHz). */
|
||||||
|
export const WARM_QUANTA = 10
|
||||||
|
/** Input frames fed per stem per block while priming — keeps a 4-stem prime
|
||||||
|
* well inside a block's budget beside the other deck. */
|
||||||
|
const WARM_BUDGET = 384
|
||||||
|
/** Stem mute/solo ramp (s). */
|
||||||
|
const GAIN_TAU = 0.004
|
||||||
|
|
||||||
|
export class DeckCore {
|
||||||
|
private stems: Float32Array[][] = []
|
||||||
|
private len = 0
|
||||||
|
private srcRate = 44100
|
||||||
|
|
||||||
|
private mode: Mode = 'stopped'
|
||||||
|
/** Playhead, in source samples. */
|
||||||
|
private pos = 0
|
||||||
|
private rate = 1
|
||||||
|
private keylock = false
|
||||||
|
|
||||||
|
private loopOn = false
|
||||||
|
private loopStart = 0
|
||||||
|
private loopEnd = 0
|
||||||
|
private loopLen = 0
|
||||||
|
/** loopLen rounded, for whole-sample index maps. */
|
||||||
|
private loopLenI = 0
|
||||||
|
|
||||||
|
private gainTarget: number[] = []
|
||||||
|
private gainNow: number[] = []
|
||||||
|
private readonly gainCoef: number
|
||||||
|
/** Per stem, this block's per-frame gains (shared by both paths in a crossfade). */
|
||||||
|
private gainBuf: Float32Array[] = []
|
||||||
|
|
||||||
|
// Scratch (source samples, and source samples per output frame).
|
||||||
|
private target = 0
|
||||||
|
private velocity = 0
|
||||||
|
private targetVelocity = 0
|
||||||
|
private resume = false
|
||||||
|
|
||||||
|
// Keylock.
|
||||||
|
private stretchers: Stretcher[] = []
|
||||||
|
private sState: StretchState = 'off'
|
||||||
|
private needRewarm = false
|
||||||
|
private warmRate = 0
|
||||||
|
/** Next pre-roll frame to feed while priming (may be < 0: silence). */
|
||||||
|
private feedPos = 0
|
||||||
|
private primeLeft = 0
|
||||||
|
private discardLeft = 0
|
||||||
|
/** Per stem: next source frame to feed (loop-wrapped). */
|
||||||
|
private readPtr: number[] = []
|
||||||
|
/** Source position of the stretchers' next output frame, while priming. */
|
||||||
|
private outPos = 0
|
||||||
|
|
||||||
|
private readonly inTmp = [new Float32Array(MAX_BLOCK), new Float32Array(MAX_BLOCK)]
|
||||||
|
private readonly dropTmp = [new Float32Array(MAX_BLOCK), new Float32Array(MAX_BLOCK)]
|
||||||
|
private outTmp: Float32Array[][] = []
|
||||||
|
private readonly xL = new Float32Array(QUANTUM)
|
||||||
|
private readonly xR = new Float32Array(QUANTUM)
|
||||||
|
|
||||||
|
/** Things that happened during the last render, for the processor to report. */
|
||||||
|
readonly events: DeckEvent[] = []
|
||||||
|
|
||||||
|
readonly ctxRate: number
|
||||||
|
private readonly rb: RubberBand | null
|
||||||
|
|
||||||
|
constructor(ctxRate: number, rb: RubberBand | null) {
|
||||||
|
this.ctxRate = ctxRate
|
||||||
|
this.rb = rb
|
||||||
|
this.gainCoef = Math.exp(-1 / (GAIN_TAU * ctxRate))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- state -----------------------------------------------------------
|
||||||
|
|
||||||
|
get loaded(): boolean {
|
||||||
|
return this.len > 0
|
||||||
|
}
|
||||||
|
get positionSec(): number {
|
||||||
|
return this.pos / this.srcRate
|
||||||
|
}
|
||||||
|
get playing(): boolean {
|
||||||
|
return this.mode === 'playing'
|
||||||
|
}
|
||||||
|
get scratching(): boolean {
|
||||||
|
return this.mode === 'drag' || this.mode === 'inertia'
|
||||||
|
}
|
||||||
|
/** Track seconds per second right now. */
|
||||||
|
get speed(): number {
|
||||||
|
if (this.mode === 'playing') return this.rate
|
||||||
|
if (this.scratching) return (this.velocity * this.ctxRate) / this.srcRate
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
/** Is keylock's stretched output what is heard? (tests) */
|
||||||
|
get stretching(): boolean {
|
||||||
|
return this.sState === 'on'
|
||||||
|
}
|
||||||
|
private get step(): number {
|
||||||
|
return (this.rate * this.srcRate) / this.ctxRate
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- commands --------------------------------------------------------
|
||||||
|
|
||||||
|
load(src: DeckSource): void {
|
||||||
|
this.disposeStretchers()
|
||||||
|
this.stems = src.stems
|
||||||
|
this.len = src.length
|
||||||
|
this.srcRate = src.sampleRate
|
||||||
|
this.mode = 'stopped'
|
||||||
|
this.pos = 0
|
||||||
|
this.loopOn = false
|
||||||
|
this.gainTarget = src.stems.map(() => 1)
|
||||||
|
this.gainNow = src.stems.map(() => 1)
|
||||||
|
this.gainBuf = src.stems.map(() => new Float32Array(QUANTUM))
|
||||||
|
this.outTmp = src.stems.map(() => [new Float32Array(QUANTUM), new Float32Array(QUANTUM)])
|
||||||
|
this.readPtr = src.stems.map(() => 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
play(): void {
|
||||||
|
if (!this.len) return
|
||||||
|
if (this.pos >= this.len - 0.01 * this.srcRate) this.pos = 0 // restart from the top at the end
|
||||||
|
this.mode = 'playing'
|
||||||
|
this.needRewarm = true
|
||||||
|
}
|
||||||
|
|
||||||
|
pause(): void {
|
||||||
|
if (this.mode === 'playing') this.mode = 'stopped'
|
||||||
|
this.sState = 'off'
|
||||||
|
}
|
||||||
|
|
||||||
|
seek(sec: number): void {
|
||||||
|
this.pos = Math.max(0, Math.min(sec * this.srcRate, this.len))
|
||||||
|
this.needRewarm = true
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoop(startSec: number, endSec: number, enabled: boolean): void {
|
||||||
|
const wasOn = this.loopOn
|
||||||
|
this.loopStart = startSec * this.srcRate
|
||||||
|
this.loopEnd = endSec * this.srcRate
|
||||||
|
this.loopLen = this.loopEnd - this.loopStart
|
||||||
|
this.loopLenI = Math.max(1, Math.round(this.loopLen))
|
||||||
|
this.loopOn = enabled && this.loopLen > 0
|
||||||
|
// Already past the new end: jump into it (as an AudioBufferSourceNode did).
|
||||||
|
if (this.loopOn && this.pos >= this.loopEnd) {
|
||||||
|
this.pos = this.loopStart
|
||||||
|
this.needRewarm = true
|
||||||
|
}
|
||||||
|
if (this.sState !== 'off') {
|
||||||
|
// The stretchers were fed AHEAD of the playhead. Re-prime if that input
|
||||||
|
// no longer matches the new loop: fed past the new end, or wrapped by a
|
||||||
|
// loop that is now gone.
|
||||||
|
const wrapped = this.readPtr.some((r) => r < this.pos)
|
||||||
|
if (this.loopOn ? wrapped || this.readPtr.some((r) => r >= this.loopEnd) : wasOn && wrapped) {
|
||||||
|
this.needRewarm = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setGains(levels: number[]): void {
|
||||||
|
this.gainTarget = this.stems.map((_, i) => levels[i] ?? 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
setRate(rate: number): void {
|
||||||
|
this.rate = Math.max(0.05, rate)
|
||||||
|
if (this.sState === 'on') for (const s of this.stretchers) s.setRatios(1 / this.step, this.pitchScale)
|
||||||
|
}
|
||||||
|
|
||||||
|
setKeylock(on: boolean): void {
|
||||||
|
this.keylock = on
|
||||||
|
}
|
||||||
|
|
||||||
|
scratchBegin(sec: number): void {
|
||||||
|
if (!this.len) return
|
||||||
|
this.mode = 'drag'
|
||||||
|
this.pos = Math.max(0, Math.min(sec * this.srcRate, this.len - 1))
|
||||||
|
this.target = this.pos
|
||||||
|
this.velocity = 0
|
||||||
|
this.sState = 'off'
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Re-grab while the platter is still coasting: resume dragging from here. */
|
||||||
|
scratchRegrab(): void {
|
||||||
|
if (!this.scratching) return
|
||||||
|
this.mode = 'drag'
|
||||||
|
this.target = this.pos
|
||||||
|
}
|
||||||
|
|
||||||
|
scratchTarget(sec: number): void {
|
||||||
|
this.target = Math.max(0, Math.min(this.len - 1, sec * this.srcRate))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Release the platter: coast toward playing speed (resume) or a stop. The
|
||||||
|
* deck then plays on (or stays paused) BY ITSELF — no hand-back round trip,
|
||||||
|
* so there is no gap between the coast and the music. */
|
||||||
|
scratchRelease(resume: boolean): void {
|
||||||
|
if (!this.scratching) return
|
||||||
|
this.resume = resume
|
||||||
|
this.targetVelocity = resume ? this.step : 0
|
||||||
|
this.mode = 'inertia'
|
||||||
|
}
|
||||||
|
|
||||||
|
dispose(): void {
|
||||||
|
this.disposeStretchers()
|
||||||
|
this.stems = []
|
||||||
|
this.len = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- rendering ---------------------------------------------------------
|
||||||
|
|
||||||
|
/** Render one block into `outL` / `outR` (QUANTUM frames). */
|
||||||
|
render(outL: Float32Array, outR: Float32Array): void {
|
||||||
|
const n = outL.length
|
||||||
|
this.events.length = 0
|
||||||
|
if (!this.len || this.mode === 'stopped') {
|
||||||
|
outL.fill(0)
|
||||||
|
outR.fill(0)
|
||||||
|
this.advanceGains(n)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
this.advanceGains(n)
|
||||||
|
if (this.scratching) {
|
||||||
|
this.renderScratch(outL, outR, n)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const wantStretch = this.keylock && this.rb != null && Math.abs(this.rate - 1) > 1e-6
|
||||||
|
if (!wantStretch) {
|
||||||
|
this.needRewarm = false
|
||||||
|
if (this.sState === 'on') {
|
||||||
|
// Leave the stretched path: crossfade it out over this block.
|
||||||
|
this.renderStretched(this.xL, this.xR, n)
|
||||||
|
this.renderDirect(outL, outR, n)
|
||||||
|
crossfade(this.xL, this.xR, outL, outR, n)
|
||||||
|
} else {
|
||||||
|
this.renderDirect(outL, outR, n)
|
||||||
|
}
|
||||||
|
this.sState = 'off'
|
||||||
|
} else {
|
||||||
|
if (this.needRewarm || this.sState === 'off' || (this.sState === 'warming' && this.rate !== this.warmRate)) {
|
||||||
|
this.startWarm()
|
||||||
|
}
|
||||||
|
this.needRewarm = false
|
||||||
|
if (this.sState === 'warming') {
|
||||||
|
if (this.warmStep()) {
|
||||||
|
this.renderStretched(this.xL, this.xR, n)
|
||||||
|
this.renderDirect(outL, outR, n)
|
||||||
|
crossfade(outL, outR, this.xL, this.xR, n)
|
||||||
|
outL.set(this.xL)
|
||||||
|
outR.set(this.xR)
|
||||||
|
this.sState = 'on'
|
||||||
|
} else {
|
||||||
|
this.renderDirect(outL, outR, n)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this.renderStretched(outL, outR, n)
|
||||||
|
this.pos = this.wrap(this.pos + this.step * n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!this.loopOn && this.pos >= this.len) {
|
||||||
|
this.pos = this.len
|
||||||
|
this.mode = 'stopped'
|
||||||
|
this.sState = 'off'
|
||||||
|
this.events.push('ended')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private advanceGains(n: number): void {
|
||||||
|
const a = this.gainCoef
|
||||||
|
for (let s = 0; s < this.gainBuf.length; s++) {
|
||||||
|
const buf = this.gainBuf[s]
|
||||||
|
const t = this.gainTarget[s]
|
||||||
|
let g = this.gainNow[s]
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
g = t + (g - t) * a
|
||||||
|
buf[i] = g
|
||||||
|
}
|
||||||
|
this.gainNow[s] = g
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private wrap(p: number): number {
|
||||||
|
if (this.loopOn && p >= this.loopEnd) p = this.loopStart + ((p - this.loopStart) % this.loopLen)
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Sample k of channel `ch`; past a loop's end reads from its start. */
|
||||||
|
private at(ch: Float32Array, k: number, looped: boolean): number {
|
||||||
|
if (looped && k >= this.loopEnd) k -= this.loopLenI
|
||||||
|
return k >= 0 && k < this.len ? ch[k] : 0
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Cubic (Hermite) read at fractional position p. */
|
||||||
|
private read(ch: Float32Array, p: number, looped: boolean): number {
|
||||||
|
const i = Math.floor(p)
|
||||||
|
const f = p - i
|
||||||
|
const xm1 = this.at(ch, i - 1, looped)
|
||||||
|
const x0 = this.at(ch, i, looped)
|
||||||
|
const x1 = this.at(ch, i + 1, looped)
|
||||||
|
const x2 = this.at(ch, i + 2, looped)
|
||||||
|
const c1 = 0.5 * (x1 - xm1)
|
||||||
|
const c2 = xm1 - 2.5 * x0 + 2 * x1 - 0.5 * x2
|
||||||
|
const c3 = 0.5 * (x2 - xm1) + 1.5 * (x0 - x1)
|
||||||
|
return ((c3 * f + c2) * f + c1) * f + x0
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mix every stem at position p, frame i of the block. */
|
||||||
|
private frame(p: number, i: number, looped: boolean, outL: Float32Array, outR: Float32Array): void {
|
||||||
|
let l = 0
|
||||||
|
let r = 0
|
||||||
|
for (let s = 0; s < this.stems.length; s++) {
|
||||||
|
const g = this.gainBuf[s][i]
|
||||||
|
if (g < 1e-5) continue
|
||||||
|
const chs = this.stems[s]
|
||||||
|
const vl = this.read(chs[0], p, looped)
|
||||||
|
l += vl * g
|
||||||
|
r += (chs.length > 1 ? this.read(chs[1], p, looped) : vl) * g
|
||||||
|
}
|
||||||
|
outL[i] = l
|
||||||
|
outR[i] = r
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The varispeed path; advances the playhead. */
|
||||||
|
private renderDirect(outL: Float32Array, outR: Float32Array, n: number): void {
|
||||||
|
const step = this.step
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
if (!this.loopOn && this.pos >= this.len) {
|
||||||
|
outL[i] = 0
|
||||||
|
outR[i] = 0
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
this.frame(this.pos, i, this.loopOn, outL, outR)
|
||||||
|
this.pos += step
|
||||||
|
if (this.loopOn && this.pos >= this.loopEnd) this.pos -= this.loopLen
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private renderScratch(outL: Float32Array, outR: Float32Array, n: number): void {
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
if (this.mode === 'drag') {
|
||||||
|
const diff = this.target - this.pos
|
||||||
|
if (Math.abs(diff) < 1) {
|
||||||
|
// Hand at rest on the platter: no movement, no sound.
|
||||||
|
this.velocity = 0
|
||||||
|
outL[i] = 0
|
||||||
|
outR[i] = 0
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
let step = diff / GLIDE
|
||||||
|
if (step > RATE_CAP) step = RATE_CAP
|
||||||
|
else if (step < -RATE_CAP) step = -RATE_CAP
|
||||||
|
this.pos += step
|
||||||
|
this.velocity = this.velocity * 0.9 + step * 0.1 // smoothed, for release momentum
|
||||||
|
} else if (this.mode === 'inertia') {
|
||||||
|
this.velocity = this.targetVelocity + (this.velocity - this.targetVelocity) * INERTIA_FRICTION
|
||||||
|
this.pos += this.velocity
|
||||||
|
if (Math.abs(this.velocity - this.targetVelocity) < SETTLE_EPS) this.settle()
|
||||||
|
} else {
|
||||||
|
// Settled mid-block: the rest of it plays (or stays silent) normally.
|
||||||
|
if (this.mode === 'playing') {
|
||||||
|
this.frame(this.pos, i, false, outL, outR)
|
||||||
|
this.pos += this.step
|
||||||
|
} else {
|
||||||
|
outL[i] = 0
|
||||||
|
outR[i] = 0
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// Clamp to the track; hitting an edge kills momentum.
|
||||||
|
if (this.pos < 0) {
|
||||||
|
this.pos = 0
|
||||||
|
this.velocity = 0
|
||||||
|
if (this.mode === 'inertia') this.settle()
|
||||||
|
} else if (this.pos > this.len - 1) {
|
||||||
|
this.pos = this.len - 1
|
||||||
|
this.velocity = 0
|
||||||
|
if (this.mode === 'inertia') this.settle()
|
||||||
|
}
|
||||||
|
this.frame(this.pos, i, false, outL, outR)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private settle(): void {
|
||||||
|
this.mode = this.resume ? 'playing' : 'stopped'
|
||||||
|
this.velocity = 0
|
||||||
|
this.needRewarm = true
|
||||||
|
this.events.push('scratchDone')
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- keylock -------------------------------------------------------------
|
||||||
|
|
||||||
|
private get pitchScale(): number {
|
||||||
|
return this.srcRate / this.ctxRate
|
||||||
|
}
|
||||||
|
|
||||||
|
private ensureStretchers(): void {
|
||||||
|
if (this.stretchers.length === this.stems.length || !this.rb) return
|
||||||
|
this.disposeStretchers()
|
||||||
|
this.stretchers = this.stems.map(() => new Stretcher(this.rb!, this.srcRate, 2))
|
||||||
|
}
|
||||||
|
|
||||||
|
private disposeStretchers(): void {
|
||||||
|
for (const s of this.stretchers) s.dispose()
|
||||||
|
this.stretchers = []
|
||||||
|
this.sState = 'off'
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Aim the stretchers at where the playhead will be WARM_QUANTA blocks from
|
||||||
|
* now, and start priming them. */
|
||||||
|
private startWarm(): void {
|
||||||
|
this.ensureStretchers()
|
||||||
|
const step = this.step
|
||||||
|
for (const s of this.stretchers) {
|
||||||
|
s.reset()
|
||||||
|
s.setRatios(1 / step, this.pitchScale)
|
||||||
|
}
|
||||||
|
const s0 = this.stretchers[0]
|
||||||
|
const q = Math.round(this.wrap(this.pos + WARM_QUANTA * QUANTUM * step))
|
||||||
|
this.primeLeft = s0.startPad
|
||||||
|
this.feedPos = q - this.primeLeft
|
||||||
|
this.discardLeft = s0.startDelay
|
||||||
|
this.readPtr = this.stems.map(() => q)
|
||||||
|
this.outPos = q
|
||||||
|
this.warmRate = this.rate
|
||||||
|
this.sState = 'warming'
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One block's priming work. True when the stretched output is aligned with
|
||||||
|
* the playhead and a block of it is ready. */
|
||||||
|
private warmStep(): boolean {
|
||||||
|
const s0 = this.stretchers[0]
|
||||||
|
let budget = WARM_BUDGET
|
||||||
|
for (let guard = 0; guard < 64; guard++) {
|
||||||
|
if (this.primeLeft > 0) {
|
||||||
|
if (budget <= 0) return false
|
||||||
|
const k = Math.min(this.primeLeft, budget, MAX_BLOCK)
|
||||||
|
this.feedPreroll(k)
|
||||||
|
this.primeLeft -= k
|
||||||
|
budget -= k
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
const avail = s0.available
|
||||||
|
if (this.discardLeft > 0) {
|
||||||
|
if (avail > 0) {
|
||||||
|
this.drop(Math.min(avail, this.discardLeft, MAX_BLOCK))
|
||||||
|
this.discardLeft -= Math.min(avail, this.discardLeft, MAX_BLOCK)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Primed: the next output frame plays source position `outPos`.
|
||||||
|
const lag = this.lagFrames()
|
||||||
|
if (lag > 0) {
|
||||||
|
// The playhead has passed it (priming ran long): skip ahead.
|
||||||
|
if (avail > 0) {
|
||||||
|
const k = Math.min(avail, lag, MAX_BLOCK)
|
||||||
|
this.drop(k)
|
||||||
|
this.outPos = this.wrap(this.outPos + k * this.step)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
} else if (lag < 0) {
|
||||||
|
return false // primed early: wait for the playhead to arrive
|
||||||
|
} else if (avail >= QUANTUM) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (budget <= 0) return false
|
||||||
|
const k = Math.min(Math.max(s0.required, 1), budget, MAX_BLOCK)
|
||||||
|
this.feedLooped(k)
|
||||||
|
budget -= k
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whole output frames from `outPos` forward to the playhead (negative =
|
||||||
|
* `outPos` is still ahead). Modulo the loop when one is engaged. */
|
||||||
|
private lagFrames(): number {
|
||||||
|
const step = this.step
|
||||||
|
let d = this.pos - this.outPos
|
||||||
|
if (this.loopOn && this.loopLen > 0) {
|
||||||
|
d = ((d % this.loopLen) + this.loopLen) % this.loopLen
|
||||||
|
if (d > this.loopLen / 2) d -= this.loopLen
|
||||||
|
}
|
||||||
|
return Math.abs(d) < step ? 0 : Math.round(d / step)
|
||||||
|
}
|
||||||
|
|
||||||
|
private drop(k: number): void {
|
||||||
|
for (const s of this.stretchers) s.retrieve(this.dropTmp, k)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pre-roll before the start point: straight, zeros outside the track. */
|
||||||
|
private feedPreroll(k: number): void {
|
||||||
|
const [tl, tr] = this.inTmp
|
||||||
|
for (let s = 0; s < this.stems.length; s++) {
|
||||||
|
const chs = this.stems[s]
|
||||||
|
for (let j = 0; j < k; j++) {
|
||||||
|
const idx = this.feedPos + j
|
||||||
|
const ok = idx >= 0 && idx < this.len
|
||||||
|
tl[j] = ok ? chs[0][idx] : 0
|
||||||
|
tr[j] = ok ? chs[chs.length > 1 ? 1 : 0][idx] : 0
|
||||||
|
}
|
||||||
|
this.stretchers[s].process(this.inTmp, k)
|
||||||
|
}
|
||||||
|
this.feedPos += k
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Feed stem s `k` frames from its read pointer, wrapping at the loop. */
|
||||||
|
private feedStem(s: number, k: number): void {
|
||||||
|
const [tl, tr] = this.inTmp
|
||||||
|
const chs = this.stems[s]
|
||||||
|
const right = chs[chs.length > 1 ? 1 : 0]
|
||||||
|
let idx = this.readPtr[s]
|
||||||
|
for (let j = 0; j < k; j++) {
|
||||||
|
if (this.loopOn && idx >= this.loopEnd) idx -= this.loopLenI
|
||||||
|
const ok = idx >= 0 && idx < this.len
|
||||||
|
tl[j] = ok ? chs[0][idx] : 0
|
||||||
|
tr[j] = ok ? right[idx] : 0
|
||||||
|
idx++
|
||||||
|
}
|
||||||
|
if (this.loopOn && idx >= this.loopEnd) idx -= this.loopLenI
|
||||||
|
this.readPtr[s] = idx
|
||||||
|
this.stretchers[s].process(this.inTmp, k)
|
||||||
|
}
|
||||||
|
|
||||||
|
private feedLooped(k: number): void {
|
||||||
|
for (let s = 0; s < this.stems.length; s++) this.feedStem(s, k)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The stretched path: a block from every stretcher, mixed with the gains.
|
||||||
|
* Leaves the playhead alone (the caller advances it). */
|
||||||
|
private renderStretched(outL: Float32Array, outR: Float32Array, n: number): void {
|
||||||
|
outL.fill(0)
|
||||||
|
outR.fill(0)
|
||||||
|
for (let s = 0; s < this.stretchers.length; s++) {
|
||||||
|
const st = this.stretchers[s]
|
||||||
|
for (let guard = 0; st.available < n && guard < 32; guard++) {
|
||||||
|
this.feedStem(s, Math.min(Math.max(st.required, 1), MAX_BLOCK))
|
||||||
|
}
|
||||||
|
const buf = this.outTmp[s]
|
||||||
|
const got = st.retrieve(buf, n)
|
||||||
|
const g = this.gainBuf[s]
|
||||||
|
for (let i = 0; i < got; i++) {
|
||||||
|
outL[i] += buf[0][i] * g[i]
|
||||||
|
outR[i] += buf[1][i] * g[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `to` = `from` fading out + `to` fading in, linearly over the block. */
|
||||||
|
function crossfade(
|
||||||
|
fromL: Float32Array,
|
||||||
|
fromR: Float32Array,
|
||||||
|
toL: Float32Array,
|
||||||
|
toR: Float32Array,
|
||||||
|
n: number,
|
||||||
|
): void {
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
const t = (i + 0.5) / n
|
||||||
|
toL[i] = fromL[i] * (1 - t) + toL[i] * t
|
||||||
|
toR[i] = fromR[i] * (1 - t) + toR[i] * t
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
// The main thread's handle on one deck's audio worklet (`deckCore.ts` does the
|
||||||
|
// work). Same surface as the PlaybackEngine it replaced, plus rate, keylock
|
||||||
|
// and scratch, which used to be a separate engine on a separate AudioContext.
|
||||||
|
//
|
||||||
|
// The worklet runs on the audio thread, so every command is asynchronous. The
|
||||||
|
// engine therefore answers from its own model of the deck — the last report,
|
||||||
|
// extrapolated by the context clock, and updated at once by each command — so
|
||||||
|
// `getPosition()` right after `seek(t)` is `t`, as callers expect. Each
|
||||||
|
// position-changing command bumps a generation; a report from before it is
|
||||||
|
// ignored, so a stale position can never snap the playhead back.
|
||||||
|
|
||||||
|
import type { DecodedAudio } from '../waveform'
|
||||||
|
import { audioContext, loadDeckWorklet, masterInput, resumeAudio } from './context'
|
||||||
|
import type { DeckCommand, DeckInbound, DeckOutbound } from './deckProcessor.worklet'
|
||||||
|
import { extrapolate, type Loop, type Model } from './position'
|
||||||
|
|
||||||
|
export class DeckEngine {
|
||||||
|
readonly output: GainNode
|
||||||
|
private readonly ctx: AudioContext
|
||||||
|
private readonly node: AudioWorkletNode
|
||||||
|
private gen = 0
|
||||||
|
private m: Model = { pos: 0, time: 0, speed: 0, playing: false, scratching: false }
|
||||||
|
private loop: Loop = { start: 0, end: 0, on: false }
|
||||||
|
private rate = 1
|
||||||
|
private _duration = 0
|
||||||
|
private _keylockAvailable = false
|
||||||
|
private onEnded: (() => void) | null = null
|
||||||
|
private onScratchDone: ((playing: boolean) => void) | null = null
|
||||||
|
|
||||||
|
/** The worklet module loads asynchronously, once per app. */
|
||||||
|
static async create(): Promise<DeckEngine> {
|
||||||
|
const wasm = await loadDeckWorklet()
|
||||||
|
return new DeckEngine(wasm)
|
||||||
|
}
|
||||||
|
|
||||||
|
private constructor(wasm: ArrayBuffer | null) {
|
||||||
|
this.ctx = audioContext()
|
||||||
|
this.node = new AudioWorkletNode(this.ctx, 'konduktor-deck', {
|
||||||
|
numberOfInputs: 0,
|
||||||
|
numberOfOutputs: 1,
|
||||||
|
outputChannelCount: [2],
|
||||||
|
processorOptions: { wasm },
|
||||||
|
})
|
||||||
|
this.output = this.ctx.createGain()
|
||||||
|
this.node.connect(this.output)
|
||||||
|
this.output.connect(masterInput())
|
||||||
|
this.node.port.onmessage = (e: MessageEvent<DeckOutbound>) => this.receive(e.data)
|
||||||
|
}
|
||||||
|
|
||||||
|
private receive(msg: DeckOutbound): void {
|
||||||
|
if (msg.type === 'error') {
|
||||||
|
console.warn(msg.message)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (msg.gen !== this.gen) return // a report from before the latest command
|
||||||
|
if (msg.type === 'state') {
|
||||||
|
this._keylockAvailable = msg.keylockAvailable
|
||||||
|
this.m = { pos: msg.pos, time: msg.time, speed: msg.speed, playing: msg.playing, scratching: msg.scratching }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
this.m = { ...this.m, pos: msg.pos, time: this.ctx.currentTime, speed: msg.playing ? this.rate : 0, playing: msg.playing, scratching: false }
|
||||||
|
if (msg.event === 'ended') this.onEnded?.()
|
||||||
|
else this.onScratchDone?.(msg.playing)
|
||||||
|
}
|
||||||
|
|
||||||
|
private send(cmd: DeckCommand, positional = true): void {
|
||||||
|
if (positional) this.gen++
|
||||||
|
const m: DeckInbound = { type: 'cmd', gen: this.gen, cmd }
|
||||||
|
this.node.port.postMessage(m)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Re-take the model at "now" before a change, so the change starts from
|
||||||
|
* the true position. */
|
||||||
|
private reanchor(): void {
|
||||||
|
this.m = { ...this.m, pos: this.getPosition(), time: this.ctx.currentTime }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- loading ------------------------------------------------------------
|
||||||
|
|
||||||
|
/** One track, or several stems played in lockstep. The PCM is TRANSFERRED to
|
||||||
|
* the audio thread: the caller must not use these arrays afterwards. */
|
||||||
|
load(audio: DecodedAudio | DecodedAudio[]): void {
|
||||||
|
const list = Array.isArray(audio) ? audio : [audio]
|
||||||
|
const length = Math.min(...list.map((a) => a.length))
|
||||||
|
const sampleRate = list[0].sampleRate
|
||||||
|
const stems = list.map((a) => a.channels)
|
||||||
|
const transfer = [...new Set(stems.flat().map((c) => c.buffer as ArrayBuffer))]
|
||||||
|
this.gen++
|
||||||
|
const m: DeckInbound = { type: 'load', gen: this.gen, source: { stems, length, sampleRate } }
|
||||||
|
this.node.port.postMessage(m, transfer)
|
||||||
|
this._duration = length / sampleRate
|
||||||
|
this.m = { pos: 0, time: this.ctx.currentTime, speed: 0, playing: false, scratching: false }
|
||||||
|
this.loop = { start: 0, end: 0, on: false }
|
||||||
|
}
|
||||||
|
|
||||||
|
setOnEnded(cb: () => void): void {
|
||||||
|
this.onEnded = cb
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Called when a scratch's coast settles; the deck is then playing (if the
|
||||||
|
* release asked to resume) or paused — it hands itself back. */
|
||||||
|
setOnScratchDone(cb: (playing: boolean) => void): void {
|
||||||
|
this.onScratchDone = cb
|
||||||
|
}
|
||||||
|
|
||||||
|
get ready(): boolean {
|
||||||
|
return this._duration > 0
|
||||||
|
}
|
||||||
|
get duration(): number {
|
||||||
|
return this._duration
|
||||||
|
}
|
||||||
|
get playing(): boolean {
|
||||||
|
return this.m.playing
|
||||||
|
}
|
||||||
|
get scratching(): boolean {
|
||||||
|
return this.m.scratching
|
||||||
|
}
|
||||||
|
get loopEnabled(): boolean {
|
||||||
|
return this.loop.on
|
||||||
|
}
|
||||||
|
/** Rubber Band loaded in the worklet (known after its first report). */
|
||||||
|
get keylockAvailable(): boolean {
|
||||||
|
return this._keylockAvailable
|
||||||
|
}
|
||||||
|
|
||||||
|
getPosition(): number {
|
||||||
|
return extrapolate(this.m, this.ctx.currentTime, this.loop, this._duration)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- transport ------------------------------------------------------------
|
||||||
|
|
||||||
|
play(): void {
|
||||||
|
if (!this.ready || this.m.playing) return
|
||||||
|
resumeAudio()
|
||||||
|
let pos = this.m.pos
|
||||||
|
if (pos >= this._duration - 0.01) pos = 0 // restart from the top at the end
|
||||||
|
this.m = { pos, time: this.ctx.currentTime, speed: this.rate, playing: true, scratching: false }
|
||||||
|
this.send({ op: 'play' })
|
||||||
|
}
|
||||||
|
|
||||||
|
pause(): void {
|
||||||
|
if (!this.m.playing) return
|
||||||
|
this.m = { ...this.m, pos: this.getPosition(), time: this.ctx.currentTime, speed: 0, playing: false }
|
||||||
|
this.send({ op: 'pause' })
|
||||||
|
}
|
||||||
|
|
||||||
|
seek(t: number): void {
|
||||||
|
const sec = Math.max(0, Math.min(t, this._duration))
|
||||||
|
this.m = { ...this.m, pos: sec, time: this.ctx.currentTime }
|
||||||
|
this.send({ op: 'seek', sec })
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Set the loop region and whether it is active. Bounds apply live if playing. */
|
||||||
|
setLoop(start: number, end: number, enabled: boolean): void {
|
||||||
|
this.reanchor()
|
||||||
|
this.loop = { start, end, on: enabled && end > start }
|
||||||
|
if (this.loop.on && this.m.pos >= end) this.m = { ...this.m, pos: start }
|
||||||
|
this.send({ op: 'loop', start, end, on: enabled })
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoopEnabled(enabled: boolean): void {
|
||||||
|
this.setLoop(this.loop.start, this.loop.end, enabled)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Per-stem levels (0 = muted) — the stems' mute/solo. Ramped, not stepped. */
|
||||||
|
setGains(levels: number[]): void {
|
||||||
|
this.send({ op: 'gains', levels }, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Playback speed (1 = the file's own tempo): the pitch fader. */
|
||||||
|
setRate(rate: number): void {
|
||||||
|
this.reanchor()
|
||||||
|
this.rate = rate
|
||||||
|
if (this.m.playing) this.m = { ...this.m, speed: rate }
|
||||||
|
this.send({ op: 'rate', rate })
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Keylock: keep the pitch while the rate changes. */
|
||||||
|
setKeylock(on: boolean): void {
|
||||||
|
this.send({ op: 'keylock', on }, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- scratch ----------------------------------------------------------------
|
||||||
|
|
||||||
|
scratchBegin(sec: number): void {
|
||||||
|
resumeAudio()
|
||||||
|
this.m = { pos: sec, time: this.ctx.currentTime, speed: 0, playing: false, scratching: true }
|
||||||
|
this.send({ op: 'scratchBegin', sec })
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Re-grab while the platter is still coasting. */
|
||||||
|
scratchRegrab(): void {
|
||||||
|
this.send({ op: 'scratchRegrab' }, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
scratchTarget(sec: number): void {
|
||||||
|
this.send({ op: 'scratchTarget', sec }, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Release the platter: coast to playing speed (resume) or to a stop. */
|
||||||
|
scratchRelease(resume: boolean): void {
|
||||||
|
this.send({ op: 'scratchRelease', resume }, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
dispose(): void {
|
||||||
|
const m: DeckInbound = { type: 'dispose' }
|
||||||
|
this.node.port.postMessage(m)
|
||||||
|
this.node.disconnect()
|
||||||
|
this.output.disconnect()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
// The deck's AudioWorkletProcessor: a thin shell around DeckCore (see there).
|
||||||
|
// Loaded once per AudioContext by `context.ts` (`?worker&url`, so Vite bundles
|
||||||
|
// its imports). Commands arrive on the port and apply before the next block;
|
||||||
|
// the playhead is reported at the START of a block, stamped with that block's
|
||||||
|
// context time, so the main thread can extrapolate it smoothly.
|
||||||
|
|
||||||
|
import { DeckCore, type DeckSource } from './deckCore'
|
||||||
|
import { RubberBand } from './stretcher'
|
||||||
|
|
||||||
|
// AudioWorkletGlobalScope — not in TypeScript's DOM lib.
|
||||||
|
declare const sampleRate: number
|
||||||
|
declare const currentTime: number
|
||||||
|
declare function registerProcessor(name: string, ctor: unknown): void
|
||||||
|
declare class AudioWorkletProcessor {
|
||||||
|
readonly port: MessagePort
|
||||||
|
constructor(options?: unknown)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Report the playhead every this many blocks (~5.8 ms at 44.1 kHz), and
|
||||||
|
* always on the block after a command. */
|
||||||
|
const REPORT_EVERY = 2
|
||||||
|
|
||||||
|
export type DeckCommand =
|
||||||
|
| { op: 'play' }
|
||||||
|
| { op: 'pause' }
|
||||||
|
| { op: 'seek'; sec: number }
|
||||||
|
| { op: 'loop'; start: number; end: number; on: boolean }
|
||||||
|
| { op: 'gains'; levels: number[] }
|
||||||
|
| { op: 'rate'; rate: number }
|
||||||
|
| { op: 'keylock'; on: boolean }
|
||||||
|
| { op: 'scratchBegin'; sec: number }
|
||||||
|
| { op: 'scratchRegrab' }
|
||||||
|
| { op: 'scratchTarget'; sec: number }
|
||||||
|
| { op: 'scratchRelease'; resume: boolean }
|
||||||
|
|
||||||
|
export type DeckInbound =
|
||||||
|
| { type: 'load'; gen: number; source: DeckSource }
|
||||||
|
| { type: 'cmd'; gen: number; cmd: DeckCommand }
|
||||||
|
| { type: 'dispose' }
|
||||||
|
|
||||||
|
export interface DeckReport {
|
||||||
|
type: 'state'
|
||||||
|
/** The last position-changing command applied. */
|
||||||
|
gen: number
|
||||||
|
/** Context time of the block this position starts. */
|
||||||
|
time: number
|
||||||
|
pos: number
|
||||||
|
speed: number
|
||||||
|
playing: boolean
|
||||||
|
scratching: boolean
|
||||||
|
keylockAvailable: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export type DeckOutbound =
|
||||||
|
| DeckReport
|
||||||
|
| { type: 'event'; event: 'ended' | 'scratchDone'; gen: number; pos: number; playing: boolean }
|
||||||
|
| { type: 'error'; message: string }
|
||||||
|
|
||||||
|
class DeckProcessor extends AudioWorkletProcessor {
|
||||||
|
private readonly core: DeckCore
|
||||||
|
private readonly rbOk: boolean
|
||||||
|
private gen = 0
|
||||||
|
private tick = 0
|
||||||
|
private dirty = true
|
||||||
|
private alive = true
|
||||||
|
|
||||||
|
constructor(options: { processorOptions?: { wasm?: ArrayBuffer | null } }) {
|
||||||
|
super()
|
||||||
|
let rb: RubberBand | null = null
|
||||||
|
const wasm = options.processorOptions?.wasm
|
||||||
|
if (wasm) {
|
||||||
|
try {
|
||||||
|
rb = new RubberBand(new WebAssembly.Module(wasm))
|
||||||
|
} catch (e) {
|
||||||
|
this.port.postMessage({ type: 'error', message: `keylock unavailable: ${e}` })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.rbOk = rb != null
|
||||||
|
this.core = new DeckCore(sampleRate, rb)
|
||||||
|
this.port.onmessage = (e: MessageEvent<DeckInbound>) => this.receive(e.data)
|
||||||
|
}
|
||||||
|
|
||||||
|
private receive(m: DeckInbound): void {
|
||||||
|
if (m.type === 'dispose') {
|
||||||
|
this.core.dispose()
|
||||||
|
this.alive = false
|
||||||
|
return
|
||||||
|
}
|
||||||
|
this.gen = m.gen
|
||||||
|
this.dirty = true
|
||||||
|
if (m.type === 'load') {
|
||||||
|
this.core.load(m.source)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const c = m.cmd
|
||||||
|
const core = this.core
|
||||||
|
switch (c.op) {
|
||||||
|
case 'play':
|
||||||
|
return core.play()
|
||||||
|
case 'pause':
|
||||||
|
return core.pause()
|
||||||
|
case 'seek':
|
||||||
|
return core.seek(c.sec)
|
||||||
|
case 'loop':
|
||||||
|
return core.setLoop(c.start, c.end, c.on)
|
||||||
|
case 'gains':
|
||||||
|
return core.setGains(c.levels)
|
||||||
|
case 'rate':
|
||||||
|
return core.setRate(c.rate)
|
||||||
|
case 'keylock':
|
||||||
|
return core.setKeylock(c.on)
|
||||||
|
case 'scratchBegin':
|
||||||
|
return core.scratchBegin(c.sec)
|
||||||
|
case 'scratchRegrab':
|
||||||
|
return core.scratchRegrab()
|
||||||
|
case 'scratchTarget':
|
||||||
|
return core.scratchTarget(c.sec)
|
||||||
|
case 'scratchRelease':
|
||||||
|
return core.scratchRelease(c.resume)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
process(_inputs: Float32Array[][], outputs: Float32Array[][]): boolean {
|
||||||
|
if (!this.alive) return false
|
||||||
|
const out = outputs[0]
|
||||||
|
if (this.dirty || ++this.tick >= REPORT_EVERY) {
|
||||||
|
this.tick = 0
|
||||||
|
this.dirty = false
|
||||||
|
const core = this.core
|
||||||
|
const report: DeckReport = {
|
||||||
|
type: 'state',
|
||||||
|
gen: this.gen,
|
||||||
|
time: currentTime,
|
||||||
|
pos: core.positionSec,
|
||||||
|
speed: core.speed,
|
||||||
|
playing: core.playing,
|
||||||
|
scratching: core.scratching,
|
||||||
|
keylockAvailable: this.rbOk,
|
||||||
|
}
|
||||||
|
this.port.postMessage(report)
|
||||||
|
}
|
||||||
|
this.core.render(out[0], out[1] ?? out[0])
|
||||||
|
for (const event of this.core.events) {
|
||||||
|
this.port.postMessage({
|
||||||
|
type: 'event',
|
||||||
|
event,
|
||||||
|
gen: this.gen,
|
||||||
|
pos: this.core.positionSec,
|
||||||
|
playing: this.core.playing,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
registerProcessor('konduktor-deck', DeckProcessor)
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
// The deck's playhead between the worklet's reports (see deckEngine.ts).
|
||||||
|
|
||||||
|
export interface Model {
|
||||||
|
pos: number
|
||||||
|
/** Context time `pos` was true at. */
|
||||||
|
time: number
|
||||||
|
/** Track seconds per second. */
|
||||||
|
speed: number
|
||||||
|
playing: boolean
|
||||||
|
scratching: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Loop {
|
||||||
|
start: number
|
||||||
|
end: number
|
||||||
|
on: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The playhead now, from a model taken at `m.time`. Pure (tests). */
|
||||||
|
export function extrapolate(m: Model, now: number, loop: Loop, duration: number): number {
|
||||||
|
if (!m.playing) return m.pos
|
||||||
|
let p = m.pos + Math.max(0, now - m.time) * m.speed
|
||||||
|
if (loop.on && loop.end > loop.start && p >= loop.end && m.pos < loop.end) {
|
||||||
|
p = loop.start + ((p - loop.start) % (loop.end - loop.start))
|
||||||
|
}
|
||||||
|
return Math.min(p, duration)
|
||||||
|
}
|
||||||
Executable
BIN
Binary file not shown.
@@ -0,0 +1,178 @@
|
|||||||
|
// Rubber Band (keylock's time-stretcher) from inside the deck's audio worklet.
|
||||||
|
//
|
||||||
|
// `rubberband.wasm` is built by `frontend/rubberband/build.sh` (upstream 3.3.0
|
||||||
|
// + Konduktor's own glue). It is a standalone WASI module; the few imports it
|
||||||
|
// declares are stubbed here, because the library, built with NO_TIMING and
|
||||||
|
// NO_THREADING, only touches them for diagnostics.
|
||||||
|
//
|
||||||
|
// Every buffer passed to the library lives in the module's own memory, and that
|
||||||
|
// memory can GROW (a new stretcher allocates). Growth detaches every view on the
|
||||||
|
// old buffer, so views are re-made whenever `memory.buffer` is a new object.
|
||||||
|
|
||||||
|
interface RbExports {
|
||||||
|
memory: WebAssembly.Memory
|
||||||
|
_initialize?: () => void
|
||||||
|
kd_malloc(size: number): number
|
||||||
|
kd_free(ptr: number): void
|
||||||
|
kd_new(sampleRate: number, channels: number, options: number, timeRatio: number, pitchScale: number): number
|
||||||
|
kd_delete(s: number): void
|
||||||
|
kd_reset(s: number): void
|
||||||
|
kd_set_time_ratio(s: number, r: number): void
|
||||||
|
kd_set_pitch_scale(s: number, p: number): void
|
||||||
|
kd_set_max_process_size(s: number, n: number): void
|
||||||
|
kd_get_preferred_start_pad(s: number): number
|
||||||
|
kd_get_start_delay(s: number): number
|
||||||
|
kd_get_samples_required(s: number): number
|
||||||
|
kd_process(s: number, input: number, samples: number, final: number): void
|
||||||
|
kd_available(s: number): number
|
||||||
|
kd_retrieve(s: number, output: number, samples: number): number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** RubberBandOptionProcessRealTime | ThreadingNever | EngineFaster (R2:
|
||||||
|
* measured to fit 8 stretchers on one render thread; R3 does not). */
|
||||||
|
const OPTIONS = 0x00000001 | 0x00010000
|
||||||
|
|
||||||
|
/** The largest block ever passed to process() or retrieve(). */
|
||||||
|
export const MAX_BLOCK = 512
|
||||||
|
|
||||||
|
export class RubberBand {
|
||||||
|
readonly x: RbExports
|
||||||
|
private heap: ArrayBuffer | null = null
|
||||||
|
private f32: Float32Array = new Float32Array(0)
|
||||||
|
private u32: Uint32Array = new Uint32Array(0)
|
||||||
|
|
||||||
|
constructor(module: WebAssembly.Module) {
|
||||||
|
let memory: WebAssembly.Memory | null = null
|
||||||
|
const u32 = () => new Uint32Array(memory!.buffer)
|
||||||
|
const ok = () => 0
|
||||||
|
const imports = {
|
||||||
|
env: { emscripten_notify_memory_growth: ok },
|
||||||
|
wasi_snapshot_preview1: {
|
||||||
|
// fd_write must report every byte written, or libc retries forever.
|
||||||
|
fd_write: (_fd: number, iovs: number, n: number, written: number) => {
|
||||||
|
const v = u32()
|
||||||
|
let total = 0
|
||||||
|
for (let i = 0; i < n; i++) total += v[(iovs >> 2) + i * 2 + 1]
|
||||||
|
v[written >> 2] = total
|
||||||
|
return 0
|
||||||
|
},
|
||||||
|
fd_read: ok,
|
||||||
|
fd_close: ok,
|
||||||
|
fd_seek: ok,
|
||||||
|
clock_time_get: ok,
|
||||||
|
environ_sizes_get: (count: number, size: number) => {
|
||||||
|
const v = u32()
|
||||||
|
v[count >> 2] = 0
|
||||||
|
v[size >> 2] = 0
|
||||||
|
return 0
|
||||||
|
},
|
||||||
|
environ_get: ok,
|
||||||
|
proc_exit: ok,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
const inst = new WebAssembly.Instance(module, imports)
|
||||||
|
this.x = inst.exports as unknown as RbExports
|
||||||
|
memory = this.x.memory
|
||||||
|
this.x._initialize?.()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Float32 view of the module's memory (re-made after a growth). */
|
||||||
|
floats(): Float32Array {
|
||||||
|
if (this.heap !== this.x.memory.buffer) this.views()
|
||||||
|
return this.f32
|
||||||
|
}
|
||||||
|
|
||||||
|
words(): Uint32Array {
|
||||||
|
if (this.heap !== this.x.memory.buffer) this.views()
|
||||||
|
return this.u32
|
||||||
|
}
|
||||||
|
|
||||||
|
private views(): void {
|
||||||
|
this.heap = this.x.memory.buffer
|
||||||
|
this.f32 = new Float32Array(this.heap)
|
||||||
|
this.u32 = new Uint32Array(this.heap)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One real-time stretcher of `channels` channels. `timeRatio` is output frames
|
||||||
|
* per input frame; `pitchScale` corrects for a source decoded at another rate
|
||||||
|
* than the context plays at (1 when they agree).
|
||||||
|
*/
|
||||||
|
export class Stretcher {
|
||||||
|
readonly channels: number
|
||||||
|
private readonly rb: RubberBand
|
||||||
|
private readonly s: number
|
||||||
|
private readonly inPtrs: number
|
||||||
|
private readonly outPtrs: number
|
||||||
|
private readonly inBufs: number[] = []
|
||||||
|
private readonly outBufs: number[] = []
|
||||||
|
|
||||||
|
constructor(rb: RubberBand, sampleRate: number, channels: number) {
|
||||||
|
this.rb = rb
|
||||||
|
this.channels = channels
|
||||||
|
const x = rb.x
|
||||||
|
this.s = x.kd_new(sampleRate, channels, OPTIONS, 1, 1)
|
||||||
|
x.kd_set_max_process_size(this.s, MAX_BLOCK)
|
||||||
|
this.inPtrs = x.kd_malloc(channels * 4)
|
||||||
|
this.outPtrs = x.kd_malloc(channels * 4)
|
||||||
|
for (let c = 0; c < channels; c++) {
|
||||||
|
this.inBufs.push(x.kd_malloc(MAX_BLOCK * 4))
|
||||||
|
this.outBufs.push(x.kd_malloc(MAX_BLOCK * 4))
|
||||||
|
}
|
||||||
|
const w = rb.words()
|
||||||
|
for (let c = 0; c < channels; c++) {
|
||||||
|
w[(this.inPtrs >> 2) + c] = this.inBufs[c]
|
||||||
|
w[(this.outPtrs >> 2) + c] = this.outBufs[c]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
reset(): void {
|
||||||
|
this.rb.x.kd_reset(this.s)
|
||||||
|
}
|
||||||
|
|
||||||
|
setRatios(timeRatio: number, pitchScale: number): void {
|
||||||
|
this.rb.x.kd_set_time_ratio(this.s, timeRatio)
|
||||||
|
this.rb.x.kd_set_pitch_scale(this.s, pitchScale)
|
||||||
|
}
|
||||||
|
|
||||||
|
get startPad(): number {
|
||||||
|
return this.rb.x.kd_get_preferred_start_pad(this.s)
|
||||||
|
}
|
||||||
|
|
||||||
|
get startDelay(): number {
|
||||||
|
return this.rb.x.kd_get_start_delay(this.s)
|
||||||
|
}
|
||||||
|
|
||||||
|
get required(): number {
|
||||||
|
return this.rb.x.kd_get_samples_required(this.s)
|
||||||
|
}
|
||||||
|
|
||||||
|
get available(): number {
|
||||||
|
return Math.max(0, this.rb.x.kd_available(this.s))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Feed `n` (<= MAX_BLOCK) frames, channel c from `input[c]`. */
|
||||||
|
process(input: Float32Array[], n: number): void {
|
||||||
|
const f = this.rb.floats()
|
||||||
|
for (let c = 0; c < this.channels; c++) f.set(input[c].subarray(0, n), this.inBufs[c] >> 2)
|
||||||
|
this.rb.x.kd_process(this.s, this.inPtrs, n, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Retrieve up to `n` (<= MAX_BLOCK) frames into `out[c]`; returns how many. */
|
||||||
|
retrieve(out: Float32Array[], n: number): number {
|
||||||
|
const got = this.rb.x.kd_retrieve(this.s, this.outPtrs, n)
|
||||||
|
const f = this.rb.floats()
|
||||||
|
for (let c = 0; c < this.channels; c++) {
|
||||||
|
const at = this.outBufs[c] >> 2
|
||||||
|
out[c].set(f.subarray(at, at + got))
|
||||||
|
}
|
||||||
|
return got
|
||||||
|
}
|
||||||
|
|
||||||
|
dispose(): void {
|
||||||
|
const x = this.rb.x
|
||||||
|
for (const p of [...this.inBufs, ...this.outBufs, this.inPtrs, this.outPtrs]) x.kd_free(p)
|
||||||
|
x.kd_delete(this.s)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -117,7 +117,8 @@ export async function alignDecoded(buffer: AudioBuffer, header: boolean | null):
|
|||||||
numberOfChannels: buffer.numberOfChannels,
|
numberOfChannels: buffer.numberOfChannels,
|
||||||
sampleRate: buffer.sampleRate,
|
sampleRate: buffer.sampleRate,
|
||||||
})
|
})
|
||||||
// copyFromChannel, never getChannelData: see the detach gotcha in scratchEngine.
|
// copyFromChannel, never getChannelData: an AudioBuffer a source node has
|
||||||
|
// played can detach its getChannelData views (Firefox).
|
||||||
const tmp = new Float32Array(buffer.length)
|
const tmp = new Float32Array(buffer.length)
|
||||||
for (let c = 0; c < buffer.numberOfChannels; c++) {
|
for (let c = 0; c < buffer.numberOfChannels; c++) {
|
||||||
buffer.copyFromChannel(tmp, c)
|
buffer.copyFromChannel(tmp, c)
|
||||||
|
|||||||
@@ -1,200 +0,0 @@
|
|||||||
// Web Audio playback for the prep deck. Plays the already-decoded AudioBuffer
|
|
||||||
// through an AudioBufferSourceNode, which gives sample-accurate, gapless loops
|
|
||||||
// via native loopStart/loopEnd — something an <audio> element can't do.
|
|
||||||
//
|
|
||||||
// A source node is one-shot, so play/seek recreate it; position is derived from
|
|
||||||
// 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 buffers: AudioBuffer[] = []
|
|
||||||
private gain: GainNode | 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
|
|
||||||
private loopOn = false
|
|
||||||
private loopStart = 0
|
|
||||||
private loopEnd = 0
|
|
||||||
private onEnded: (() => void) | null = null
|
|
||||||
|
|
||||||
/** One buffer (a plain track) or several played in lockstep (the stems). */
|
|
||||||
load(ctx: AudioContext, buffer: AudioBuffer | AudioBuffer[]): void {
|
|
||||||
this.ctx = ctx
|
|
||||||
this.stopSource()
|
|
||||||
this.buffers = Array.isArray(buffer) ? buffer : [buffer]
|
|
||||||
if (!this.gain) {
|
|
||||||
this.gain = ctx.createGain()
|
|
||||||
this.gain.connect(ctx.destination)
|
|
||||||
}
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
setOnEnded(cb: () => void): void {
|
|
||||||
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
|
|
||||||
}
|
|
||||||
get duration(): number {
|
|
||||||
return this.buffer?.duration ?? 0
|
|
||||||
}
|
|
||||||
get loopEnabled(): boolean {
|
|
||||||
return this.loopOn
|
|
||||||
}
|
|
||||||
|
|
||||||
getPosition(): number {
|
|
||||||
if (!this.buffer || !this.ctx || !this._playing) return this.startOffset
|
|
||||||
// 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)
|
|
||||||
}
|
|
||||||
return Math.min(pos, this.buffer.duration)
|
|
||||||
}
|
|
||||||
|
|
||||||
private startSource(offset: number): void {
|
|
||||||
if (!this.ctx || !this.buffer || !this.gain) return
|
|
||||||
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.stopSource()
|
|
||||||
this.onEnded?.()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
this.sources = started
|
|
||||||
this.startedAt = when
|
|
||||||
this.startOffset = offset
|
|
||||||
this._playing = true
|
|
||||||
}
|
|
||||||
|
|
||||||
private stopSource(): void {
|
|
||||||
for (const src of this.sources) {
|
|
||||||
src.onended = null
|
|
||||||
try {
|
|
||||||
src.stop()
|
|
||||||
} catch {
|
|
||||||
/* already stopped */
|
|
||||||
}
|
|
||||||
src.disconnect()
|
|
||||||
}
|
|
||||||
this.sources = []
|
|
||||||
}
|
|
||||||
|
|
||||||
play(): void {
|
|
||||||
if (!this.ctx || !this.buffer || this._playing) return
|
|
||||||
void this.ctx.resume()
|
|
||||||
let off = this.startOffset
|
|
||||||
if (off >= this.buffer.duration - 0.01) off = 0 // restart from top if at the end
|
|
||||||
this.startSource(off)
|
|
||||||
}
|
|
||||||
|
|
||||||
pause(): void {
|
|
||||||
if (!this._playing) return
|
|
||||||
this.startOffset = this.getPosition()
|
|
||||||
this.stopSource()
|
|
||||||
this._playing = false
|
|
||||||
}
|
|
||||||
|
|
||||||
seek(t: number): void {
|
|
||||||
const clamped = Math.max(0, Math.min(t, this.duration))
|
|
||||||
if (this._playing) {
|
|
||||||
this.stopSource()
|
|
||||||
this.startOffset = clamped
|
|
||||||
this.startSource(clamped)
|
|
||||||
} else {
|
|
||||||
this.startOffset = clamped
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Snapshot the true buffer position into (startOffset, startedAt) so the
|
|
||||||
// position model stays correct after the loop params change. Must be called
|
|
||||||
// BEFORE mutating loopOn/loopStart/loopEnd (it reads the current/old params).
|
|
||||||
private reanchor(): void {
|
|
||||||
if (this._playing && this.ctx) {
|
|
||||||
this.startOffset = this.getPosition()
|
|
||||||
this.startedAt = this.ctx.currentTime
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Set the loop region and whether it's active. Bounds apply live if playing. */
|
|
||||||
setLoop(start: number, end: number, enabled: boolean): void {
|
|
||||||
this.reanchor() // capture the real position under the OLD loop state first
|
|
||||||
this.loopStart = start
|
|
||||||
this.loopEnd = end
|
|
||||||
this.loopOn = enabled
|
|
||||||
for (const src of this.sources) {
|
|
||||||
if (enabled && end > start) {
|
|
||||||
src.loop = true
|
|
||||||
src.loopStart = start
|
|
||||||
src.loopEnd = end
|
|
||||||
} else {
|
|
||||||
src.loop = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// If the playhead is already at/past the loop end, jump into it (the live
|
|
||||||
// node won't loop back on its own from beyond loopEnd).
|
|
||||||
if (enabled && end > start && this.startOffset >= end) {
|
|
||||||
this.seek(start)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
setLoopEnabled(enabled: boolean): void {
|
|
||||||
this.setLoop(this.loopStart, this.loopEnd, enabled)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -13,9 +13,9 @@
|
|||||||
// Two data paths, by how many samples one pixel covers:
|
// Two data paths, by how many samples one pixel covers:
|
||||||
// * many (wide zoom): min/max per RAW_BLOCK samples, summarised once at load
|
// * 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;
|
// (~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
|
// * few (deep zoom): the visible window read straight from the mono
|
||||||
// AudioBuffer each frame. No full-length mono copy is kept; the playback
|
// downmix each frame. The deck keeps that half-size copy rather than the
|
||||||
// engine holds the buffer anyway.
|
// stereo PCM, which is transferred to its audio worklet.
|
||||||
// Each pixel is a vertical stroke from the lowest to the highest sample in it,
|
// 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
|
// 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.
|
// envelope, zoomed in it narrows to one continuous line, with no switch-over.
|
||||||
@@ -41,28 +41,8 @@ export interface RawWave {
|
|||||||
readMono: (start: number, dest: Float32Array) => void
|
readMono: (start: number, dest: Float32Array) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A reader of an AudioBuffer's mono downmix. copyFromChannel copies, so this
|
/** Summarise a mono downmix. `readMono` defaults to reading `mono` itself,
|
||||||
* never holds a view the playback engine could detach (the Firefox gotcha). */
|
* which the deck keeps for the purpose. */
|
||||||
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(
|
export function rawWaveFromMono(
|
||||||
mono: Float32Array,
|
mono: Float32Array,
|
||||||
sampleRate: number,
|
sampleRate: number,
|
||||||
|
|||||||
@@ -1,223 +0,0 @@
|
|||||||
// A minimal "scratch" engine: while the user drags the waveform we play the
|
|
||||||
// decoded audio at a position that glides toward the cursor's target. Fast drags
|
|
||||||
// → high pitch, reverse drags → reverse audio, holding still → silence — the
|
|
||||||
// characteristic scratch behaviour, which a plain <audio> element can't do
|
|
||||||
// (no reverse, no arbitrary rate).
|
|
||||||
//
|
|
||||||
// On release the engine coasts: it keeps the drag velocity and eases it toward a
|
|
||||||
// target speed with friction (momentum/flywheel feel) — to a stop if playback was
|
|
||||||
// paused, or up to normal speed if it was playing. When it settles, `finished`
|
|
||||||
// flips true and the caller hands the position back to the playback engine.
|
|
||||||
//
|
|
||||||
// The ScriptProcessorNode is created ONCE (via attach) and kept alive, sitting in
|
|
||||||
// an 'idle' mode that outputs silence between scratches. Creating it fresh per
|
|
||||||
// scratch caused a start-up delay where a short drag was silent until the node
|
|
||||||
// began firing; a warmed-up persistent node produces sound immediately.
|
|
||||||
|
|
||||||
const BUFFER_SIZE = 512
|
|
||||||
const GLIDE = 400 // samples: how tightly position chases the target while dragging
|
|
||||||
const RATE_CAP = 12 // max samples advanced per output sample (pitch ceiling)
|
|
||||||
const INERTIA_FRICTION = 0.9998 // per-sample easing toward the target velocity (~0.4s spin-down)
|
|
||||||
const SETTLE_EPS = 0.02 // |velocity - target| below this → settled
|
|
||||||
|
|
||||||
type Mode = 'idle' | 'drag' | 'inertia' | 'done'
|
|
||||||
|
|
||||||
export class ScratchEngine {
|
|
||||||
private channels: Float32Array[] = []
|
|
||||||
private length = 0
|
|
||||||
private sr = 44100
|
|
||||||
private ctxRate = 44100
|
|
||||||
private node: ScriptProcessorNode | null = null
|
|
||||||
private position = 0 // in source samples
|
|
||||||
private target = 0 // drag target, in source samples
|
|
||||||
private velocity = 0 // source samples advanced per output sample
|
|
||||||
private targetVelocity = 0 // inertia goal
|
|
||||||
private mode: Mode = 'idle'
|
|
||||||
|
|
||||||
load(buffer: AudioBuffer): void {
|
|
||||||
// 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)))
|
|
||||||
}
|
|
||||||
this.length = buffer.length
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
get finished(): boolean {
|
|
||||||
return this.mode === 'done'
|
|
||||||
}
|
|
||||||
|
|
||||||
getPositionSec(): number {
|
|
||||||
return this.position / this.sr
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Create the (persistent, idle) audio node once. Safe to call repeatedly. */
|
|
||||||
attach(ctx: AudioContext): void {
|
|
||||||
this.ctxRate = ctx.sampleRate
|
|
||||||
if (!this.node) {
|
|
||||||
const node = ctx.createScriptProcessor(BUFFER_SIZE, 0, 2)
|
|
||||||
node.onaudioprocess = (e) => this.render(e)
|
|
||||||
node.connect(ctx.destination)
|
|
||||||
this.node = node
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Enter scratch mode at the given position (node is already running). */
|
|
||||||
begin(ctx: AudioContext, positionSec: number): void {
|
|
||||||
if (!this.loaded) return
|
|
||||||
this.attach(ctx)
|
|
||||||
this.position = positionSec * this.sr
|
|
||||||
this.target = this.position
|
|
||||||
this.velocity = 0
|
|
||||||
this.mode = 'drag'
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Re-grab while the platter is still coasting: resume dragging from here. */
|
|
||||||
regrab(): void {
|
|
||||||
this.mode = 'drag'
|
|
||||||
this.target = this.position
|
|
||||||
}
|
|
||||||
|
|
||||||
setTargetSec(sec: number): void {
|
|
||||||
this.target = Math.max(0, Math.min(this.length - 1, sec * this.sr))
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Release the platter: coast with the current velocity, easing toward normal
|
|
||||||
* speed (resume=true) or a stop (resume=false). `finished` flips when settled. */
|
|
||||||
release(resume: boolean): void {
|
|
||||||
this.targetVelocity = resume ? this.sr / this.ctxRate : 0
|
|
||||||
this.mode = 'inertia'
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Leave scratch mode; the node stays alive (idle). Returns final position (s). */
|
|
||||||
end(): number {
|
|
||||||
this.mode = 'idle'
|
|
||||||
return this.position / this.sr
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Tear down the node (on track change / unmount). */
|
|
||||||
dispose(): void {
|
|
||||||
if (this.node) {
|
|
||||||
this.node.disconnect()
|
|
||||||
this.node.onaudioprocess = null
|
|
||||||
this.node = null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private sample(outs: Float32Array[], i: number, chN: number): void {
|
|
||||||
const i0 = Math.floor(this.position)
|
|
||||||
const frac = this.position - i0
|
|
||||||
for (let c = 0; c < chN; c++) {
|
|
||||||
const src = this.channels[Math.min(c, this.channels.length - 1)]
|
|
||||||
outs[c][i] = i0 + 1 < this.length ? src[i0] * (1 - frac) + src[i0 + 1] * frac : src[i0]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private silence(outs: Float32Array[], i: number, chN: number): void {
|
|
||||||
for (let c = 0; c < chN; c++) outs[c][i] = 0
|
|
||||||
}
|
|
||||||
|
|
||||||
private render(e: AudioProcessingEvent): void {
|
|
||||||
const out = e.outputBuffer
|
|
||||||
const n = out.length
|
|
||||||
const chN = out.numberOfChannels
|
|
||||||
const outs: Float32Array[] = []
|
|
||||||
for (let c = 0; c < chN; c++) outs.push(out.getChannelData(c))
|
|
||||||
|
|
||||||
for (let i = 0; i < n; i++) {
|
|
||||||
if (this.mode === 'drag') {
|
|
||||||
const diff = this.target - this.position
|
|
||||||
if (Math.abs(diff) < 1) {
|
|
||||||
// Hand at rest on the platter → no movement, no sound.
|
|
||||||
this.velocity = 0
|
|
||||||
this.silence(outs, i, chN)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
let step = diff / GLIDE
|
|
||||||
if (step > RATE_CAP) step = RATE_CAP
|
|
||||||
else if (step < -RATE_CAP) step = -RATE_CAP
|
|
||||||
this.position += step
|
|
||||||
this.velocity = this.velocity * 0.9 + step * 0.1 // smoothed, for release momentum
|
|
||||||
} else if (this.mode === 'inertia') {
|
|
||||||
this.velocity = this.targetVelocity + (this.velocity - this.targetVelocity) * INERTIA_FRICTION
|
|
||||||
this.position += this.velocity
|
|
||||||
if (Math.abs(this.velocity - this.targetVelocity) < SETTLE_EPS) {
|
|
||||||
this.mode = 'done'
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// idle / done → silent (node stays alive and firing).
|
|
||||||
this.silence(outs, i, chN)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// Clamp to the track; hitting an edge kills momentum.
|
|
||||||
if (this.position < 0) {
|
|
||||||
this.position = 0
|
|
||||||
this.velocity = 0
|
|
||||||
if (this.mode === 'inertia') this.mode = 'done'
|
|
||||||
} else if (this.position > this.length - 1) {
|
|
||||||
this.position = this.length - 1
|
|
||||||
this.velocity = 0
|
|
||||||
if (this.mode === 'inertia') this.mode = 'done'
|
|
||||||
}
|
|
||||||
this.sample(outs, i, chN)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -13,7 +13,7 @@
|
|||||||
// 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 { alignDecoded, mp3HeaderFrame } from './decodeAlign'
|
||||||
import { bufferReader, rawWaveFromMono, type RawWave } from './rawWave'
|
import { 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
|
||||||
@@ -96,10 +96,26 @@ export function paintWave(
|
|||||||
ctx.globalCompositeOperation = prevOp
|
ctx.globalCompositeOperation = prevOp
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Decoded PCM, one array per channel — what the deck's worklet plays. Plain
|
||||||
|
* arrays rather than the AudioBuffer they came from, so they can be
|
||||||
|
* TRANSFERRED to the audio thread and the AudioBuffer dropped. */
|
||||||
|
export interface DecodedAudio {
|
||||||
|
channels: Float32Array[]
|
||||||
|
sampleRate: number
|
||||||
|
length: number
|
||||||
|
duration: number
|
||||||
|
}
|
||||||
|
|
||||||
|
function decoded(buf: AudioBuffer): DecodedAudio {
|
||||||
|
const channels: Float32Array[] = []
|
||||||
|
for (let c = 0; c < buf.numberOfChannels; c++) channels.push(buf.getChannelData(c).slice())
|
||||||
|
return { channels, sampleRate: buf.sampleRate, length: buf.length, duration: buf.duration }
|
||||||
|
}
|
||||||
|
|
||||||
export interface WaveformAnalysis {
|
export interface WaveformAnalysis {
|
||||||
cols: WaveColumn[]
|
cols: WaveColumn[]
|
||||||
/** The decoded audio, retained for the scratch engine (reused, not re-decoded). */
|
/** The decoded audio, for the deck (decoded once, not again for playback). */
|
||||||
buffer: AudioBuffer
|
audio: DecodedAudio
|
||||||
/** The raw waveform of the same audio. */
|
/** The raw waveform of the same audio. */
|
||||||
raw: RawWave
|
raw: RawWave
|
||||||
}
|
}
|
||||||
@@ -136,8 +152,10 @@ 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
|
||||||
}
|
}
|
||||||
const raw = rawWaveFromMono(mono, audio.sampleRate, bufferReader(audio))
|
// The raw view reads the mono downmix itself: the PCM goes to the audio
|
||||||
return { cols: await analyzeMono(mono, audio.sampleRate, buckets), buffer: audio, raw }
|
// thread, so the main thread keeps this half-size copy instead.
|
||||||
|
const raw = rawWaveFromMono(mono, audio.sampleRate)
|
||||||
|
return { cols: await analyzeMono(mono, audio.sampleRate, buckets), audio: decoded(audio), raw }
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface StemAnalysis {
|
export interface StemAnalysis {
|
||||||
@@ -145,7 +163,7 @@ export interface StemAnalysis {
|
|||||||
cols: WaveColumn[]
|
cols: WaveColumn[]
|
||||||
/** 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[]
|
audios: DecodedAudio[]
|
||||||
/** Per stem: the raw waveform of its lane. */
|
/** Per stem: the raw waveform of its lane. */
|
||||||
raws: RawWave[]
|
raws: RawWave[]
|
||||||
}
|
}
|
||||||
@@ -183,7 +201,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)))
|
raws.push(rawWaveFromMono(monoStem, sr))
|
||||||
return lane
|
return lane
|
||||||
})
|
})
|
||||||
const ceilOf = (v: Float32Array) => {
|
const ceilOf = (v: Float32Array) => {
|
||||||
@@ -196,7 +214,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, raws }
|
return { cols: await analyzeMono(mono, sr, n), lanes, audios: buffers.map(decoded), 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