LabDAW

playback

What plays when: audio clips placed in frames, the transport's state on the audio clock, the clip player's processor and its renderer, recordings streamed in pages, and the mixer's pan law, solo and delay compensation.

pnpm dlx shadcn@latest add @audio-ui/engine-playback
import { createWarpReader, fadeGain, playedClip, playedClips, RECORDING_LOADER_WORKER, /* … */ } from "@/lib/engine/playback";
Used byarrangement, arrangement-engine, clip-player, dawproject, mixer-engine, rack, use-piano-roll-playback
ExportKindWhat it is
ArrangedAudiointerfaceAn audio clip as an arrangement holds it, in seconds: where it lies, the stretch of its recording it plays, its gain, loop, direction and warp.
createWarpReaderfunctionReads a warp map from a clip's own time back to its source's, fast enough to be asked for every frame: it keeps the stretch it last answered from, since frames come in order.
FadeShapetypeHow a fade rises or falls: evenly, quick then slow, slow then quick, or eased at both ends.
fadeGainfunctionThe gain a fade of shape has progress of the way through it, from 0 (silent) to 1 (full): the curve of a fade-in; a fade-out plays it backwards.
PlayedClipinterfaceAn audio clip as a player reads it: in whole frames of the arrangement, at the engine's sample rate.
PlayedStretchinterfaceHow a clip stretches time, in frames of the arrangement: how far apart its grains start and how long they cross, how fast each reads, and whether each is lined up on the last.
playedClipfunctionThe clip a player reads from clip, playing the recording recording, at sampleRate: every time turned into the nearest frame, the fades shortened to fit, the gain as a ratio.
playedClipsfunctionThe clips a track's player reads, from an arrangement's audio clips: those that play (not deactivated, with a recording to play), each through playedClip, in the order they start.
WarpModetypeHow a clip plays at another speed than its recording's: with its pitch moving with it, in slices that keep their attacks, or in grains that keep a held note.
RECORDING_LOADER_WORKERconstThe loader of streamed recordings, as the source of a module: start it with new Worker(url, { type: "module" }) (from a Blob URL), then post it RecordingLoaderMessages.
CompensationinterfaceHow long each path waits, in frames, so that all of them line up at the main track.
DelayedTrackinterfaceA path into the mixer as delay compensation sees it: how many frames its devices delay it.
delayCompensationfunctionThe waits that line every path up at the main track.
panGainsfunctionThe gains of the left and right channels for a pan from -1 (left) to 1 (right): a constant-power law on sine curves, with both channels at unity in the centre and the side it is turned to at +3 dB at either end.
RoutedCompensationinterfaceHow long each path waits, in frames, so that everything meeting anywhere meets on the same frame.
RoutedTrackinterfaceA path into the mixer as routing sees it: its delay, where it plays into, and the returns it sends to.
routedCompensationfunctionThe waits that line every path up wherever paths meet: at a group, the sound of each of its tracks; at a return, each send; at the main track, the top tracks and groups and the returns.
SoloStateinterfaceWhat a solo lets through: each track's own output, and each of its sends.
SoloTrackinterfaceA track as the solo sees it.
soloStatefunctionWhich tracks a solo silences.
NoteinterfaceA note of a MIDI clip: its pitch, start and length, how hard and how likely it plays, how far its velocity may stray, and whether it is deactivated.
NoteIdtypeA note's id: unique within its clip.
playedVelocityfunctionHow hard a note plays this time round, from 0 to 1, or null when it does not: a deactivated note never plays, one with a chance plays that share of the times, and a deviation strays its velocity by up to that much, a new roll each time.
PlannedRecordinginterfaceWhat the planner needs of a recording: its rate and its length in frames.
pagesAheadfunctionThe pages a track's clips read over the count frames of the audio clock from frame, the soonest read first: what a loader should have in the pool before then.
CLIP_PLAYER_PROCESSORconstThe name the clip player's processor is registered under in an AudioWorklet.
ClipPlayerMessagetypeWhat the main thread posts to a clip player's port.
ClipPlayerReplytypeWhat a clip player's processor posts back.
RecordingLoaderMessagetypeWhat the main thread posts to the loader of streamed recordings, a Worker.
RecordingLoaderReplytypeWhat the loader posts back.
DECLICK_SECONDSconstHow long a stop or a jump fades the sound out, and the sound after a jump in.
DecodedRecordinginterfaceA recording held in memory, decoded: one array of samples per channel.
RecordingtypeA recording a clip plays: decoded in memory, or streamed.
RecordingstypeThe recordings a player can read, by id.
renderClipsfunctionAdds what clips play over length frames of the arrangement from position into output, from index at.
StreamedRecordinginterfaceA recording read from the pages of a stream, which something else keeps filled ahead of playback.
sourceIndexerfunctionWhere in its recording clip reads at the arrangement's frame frame, in frames of the recording (fractional when warped or at another rate), or NaN where it plays nothing: what both the player and the planner of a stream's pages follow.
TrackRendererclassWhat one track plays, block after block: its clips, through the states of the transport it is given, each from its own frame of the audio clock.
createPagePoolfunctionA pool of slots pages, in shared memory unless shared is false.
createRecordingStreamfunctionA recording of length frames read from pool, none of its pages there yet.
PAGE_FRAMESconstHow many frames a page holds: about 0.7 s at 48 kHz.
PageCacheclassKeeps the pages that are asked for in the pool: it loads those missing, in the order they come, into free slots or into the slots asked for longest ago, and never into a slot asked for in the same call.
PagePoolinterfaceThe slots every streamed recording of a context reads from.
PageReadertypeReads a page of a recording into its slot: one array per channel of the recording, pageFrames long, to fill from the page's first frame.
PageRequestinterfaceOne page of one recording.
RecordingStreaminterfaceA recording as the player reads it from the pool.
slotOffsetfunctionWhere a slot's channel starts in the pool's samples.
streamedSamplefunctionA channel's sample at a frame: silence outside the recording, and while its page is not there.
arrangementFramefunctionThe frame of the arrangement that plays at the audio clock's frame, at or after state.at: the state's position while stopped.
continuesFromfunctionWhether going from before to after at after.at carries on without a break: both play, and the frame of the arrangement at after.at is the same in both.
heardFramefunctionThe frame of the audio clock heard at the speakers at contextTime, the context's time of what is heard now (getOutputTimestamp().contextTime, or currentTime less the output latency where the browser has no timestamp), less delay frames the engine adds on the way (its delay compensation).
PlaybackRuninterfaceA stretch of a block that plays frames of the arrangement one after the other.
PlaybackStateinterfaceWhat the transport does from a frame of the audio clock on.
playbackRunsfunctionThe runs of the block of count frames from the audio clock's frame: the arrangement's frames it plays, cut where the loop comes round.
rescaledfunctionThe state that carries on from the audio clock's frame at once every time of the arrangement is ratio times what it was (a change of tempo: half the tempo makes every time twice as late): the position playing at at, and the loop, scaled, so the playhead stays on its bar and beat.
STOPPEDconstStopped at the start, from the first frame on.
startsInWindowfunctionThe items that start in the block of count frames from the audio clock's frame, each with the frame of the clock it starts at: what a scheduler of notes asks for its look-ahead window.
toFramesfunctionA time in seconds as a whole number of frames: the nearest one.
CLIP_PLAYER_WORKLETconstThe clip player's processor, as the source of a module: load it into a context with audioWorklet.addModule (from a Blob URL), then make a player with new AudioWorkletNode(context, CLIP_PLAYER_PROCESSOR).
CLIP_PLAYER_WORKLET_INPUTSconstA hash of the sources this bundle was made from, checked by a test.

Usage

An arrangement plays as blocks of frames on the audio thread. This module holds the arithmetic of that: which frame of the arrangement plays at a frame of the audio clock, which clips sound in a block and where each reads its recording, and how the mixer lines its paths up.

The registry's clip-player runs it in an AudioWorklet, and the arrangement-engine and mixer-engine build on it.

The clip player

CLIP_PLAYER_WORKLET is the player's processor as the source of a module. Load it once into a context, then make a player per track:

import { CLIP_PLAYER_PROCESSOR, CLIP_PLAYER_WORKLET, playedClips } from "@/lib/engine/playback";

const url = URL.createObjectURL(new Blob([CLIP_PLAYER_WORKLET], { type: "text/javascript" }));
await ctx.audioWorklet.addModule(url);

const player = new AudioWorkletNode(ctx, CLIP_PLAYER_PROCESSOR, {
  numberOfInputs: 0,
  numberOfOutputs: 1,
  outputChannelCount: [2],
});
player.connect(ctx.destination);

player.port.postMessage({ type: "recording", id: "take-1", channels, sampleRate: buffer.sampleRate });
player.port.postMessage({ type: "clips", clips: playedClips(track.clips, (clip) => clip.recordingId, ctx.sampleRate) });
player.port.postMessage({ type: "state", state: { at: 0, loop: null, playing: true, position: 0 } });

A recording posted through one player is there for every player of the context. playedClips turns an arrangement's clips into what the player reads, in whole frames: the clips that play, each with its place, its fades, its gain, its loop and its warp or stretch. The messages a player takes are ClipPlayerMessage: a decoded or a streamed recording, forget, the clips, a state of the transport, sync (answered once every message before it is in) and dispose.

The transport

A PlaybackState says what plays from a frame of the audio clock on: whether it plays, the frame of the arrangement at that frame, and the loop. STOPPED is the state at rest. playbackRuns(state, frame, count) cuts a block into runs of consecutive frames of the arrangement, cut where the loop comes round; arrangementFrame is the one frame, rescaled carries a state through a change of tempo, and heardFrame turns the context's time of what is heard now (getOutputTimestamp().contextTime) into a frame of the audio clock, for a playhead that matches the speakers.

TrackRenderer is what one track plays, block after block. A state that arrives late takes over at once and still plays the frames its clock says, and a stop or a jump fades out over DECLICK_SECONDS (2 ms), so it does not click.

Streamed recordings

A recording too long to hold decoded is read from pages in shared memory. createPagePool(slots) makes the pool every streamed recording of a context reads from, createRecordingStream a recording in it, and RECORDING_LOADER_WORKER is the worker that loads pages into it from a file in the origin private file system. pagesAhead lists the pages the next frames will read, soonest first, and PageCache keeps them in the pool. A page that is not there yet plays as silence.

Notes

A note of a clip has a velocity, a chance and a deviation. playedVelocity(note) is how hard it plays this time round, or null when it does not: a deactivated note never plays, one with a chance of 0.5 plays every other time on average, and a deviation strays its velocity by up to that much, a new roll each time. The arrangement engine and the piano roll's playback both play notes through it, so a note sounds the same in either.

import { playedVelocity } from "@/lib/engine/playback";

const velocity = playedVelocity(note);
if (velocity !== null) {
  instrument.noteOn({ pitch: note.pitch, velocity }, at);
}

The mixer

import { delayCompensation, panGains, soloState } from "@/lib/engine/playback";

panGains(0); // [1, 1]: both channels at unity in the centre
panGains(-1); // [1.414, 0]: the side it is turned to at +3 dB

const solo = soloState([
  { id: "drums", kind: "track", soloed: true },
  { id: "bass", kind: "track", soloed: false },
  { id: "verb", kind: "return", soloed: false },
]);
solo.heard("bass"); // false
solo.sends("drums", "verb"); // true: a soloed track's sends still reach its return

const { tracks, total } = delayCompensation(
  [{ id: "drums", latency: 128 }, { id: "bass", latency: 0 }],
  []
);
// bass waits 128 frames after its chain, so both reach the main track together

soloState takes groups too: a group is heard while a track in it is soloed. routedCompensation lines paths up wherever they meet, at a group, a return or the main track, for a mixer that routes tracks into groups.

Built by Ouest Labs, the source code is available on GitHub.
RSS