# 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.

```bash
npm install @audio-ui/engine-playback
```

```ts
import { createWarpReader, fadeGain, playedClip, playedClips, RECORDING_LOADER_WORKER, /* … */ } from "@/lib/engine/playback";
```

- Used by: `arrangement`, `arrangement-engine`, `clip-player`, `dawproject`, `mixer-engine`, `rack`, `use-piano-roll-playback`

| Export | Kind | What it is |
| --- | --- | --- |
| `ArrangedAudio` | interface | An 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. |
| `createWarpReader` | function | Reads 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. |
| `FadeShape` | type | How a fade rises or falls: evenly, quick then slow, slow then quick, or eased at both ends. |
| `fadeGain` | function | The 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. |
| `PlayedClip` | interface | An audio clip as a player reads it: in whole frames of the arrangement, at the engine's sample rate. |
| `PlayedStretch` | interface | How 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. |
| `playedClip` | function | The 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. |
| `playedClips` | function | The 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. |
| `WarpMode` | type | How 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_WORKER` | const | The 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 `RecordingLoaderMessage`s. |
| `Compensation` | interface | How long each path waits, in frames, so that all of them line up at the main track. |
| `DelayedTrack` | interface | A path into the mixer as delay compensation sees it: how many frames its devices delay it. |
| `delayCompensation` | function | The waits that line every path up at the main track. |
| `panGains` | function | The 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. |
| `RoutedCompensation` | interface | How long each path waits, in frames, so that everything meeting anywhere meets on the same frame. |
| `RoutedTrack` | interface | A path into the mixer as routing sees it: its delay, where it plays into, and the returns it sends to. |
| `routedCompensation` | function | The 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. |
| `SoloState` | interface | What a solo lets through: each track's own output, and each of its sends. |
| `SoloTrack` | interface | A track as the solo sees it. |
| `soloState` | function | Which tracks a solo silences. |
| `Note` | interface | A 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. |
| `NoteId` | type | A note's id: unique within its clip. |
| `playedVelocity` | function | How 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. |
| `PlannedRecording` | interface | What the planner needs of a recording: its rate and its length in frames. |
| `pagesAhead` | function | The 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_PROCESSOR` | const | The name the clip player's processor is registered under in an AudioWorklet. |
| `ClipPlayerMessage` | type | What the main thread posts to a clip player's port. |
| `ClipPlayerReply` | type | What a clip player's processor posts back. |
| `RecordingLoaderMessage` | type | What the main thread posts to the loader of streamed recordings, a Worker. |
| `RecordingLoaderReply` | type | What the loader posts back. |
| `DECLICK_SECONDS` | const | How long a stop or a jump fades the sound out, and the sound after a jump in. |
| `DecodedRecording` | interface | A recording held in memory, decoded: one array of samples per channel. |
| `Recording` | type | A recording a clip plays: decoded in memory, or streamed. |
| `Recordings` | type | The recordings a player can read, by id. |
| `renderClips` | function | Adds what `clips` play over `length` frames of the arrangement from `position` into `output`, from index `at`. |
| `StreamedRecording` | interface | A recording read from the pages of a stream, which something else keeps filled ahead of playback. |
| `sourceIndexer` | function | Where 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. |
| `TrackRenderer` | class | What 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. |
| `createPagePool` | function | A pool of `slots` pages, in shared memory unless `shared` is false. |
| `createRecordingStream` | function | A recording of `length` frames read from `pool`, none of its pages there yet. |
| `PAGE_FRAMES` | const | How many frames a page holds: about 0.7 s at 48 kHz. |
| `PageCache` | class | Keeps 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. |
| `PagePool` | interface | The slots every streamed recording of a context reads from. |
| `PageReader` | type | Reads 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. |
| `PageRequest` | interface | One page of one recording. |
| `RecordingStream` | interface | A recording as the player reads it from the pool. |
| `slotOffset` | function | Where a slot's channel starts in the pool's samples. |
| `streamedSample` | function | A channel's sample at a frame: silence outside the recording, and while its page is not there. |
| `arrangementFrame` | function | The frame of the arrangement that plays at the audio clock's `frame`, at or after `state.at`: the state's position while stopped. |
| `continuesFrom` | function | Whether 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. |
| `heardFrame` | function | The 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). |
| `PlaybackRun` | interface | A stretch of a block that plays frames of the arrangement one after the other. |
| `PlaybackState` | interface | What the transport does from a frame of the audio clock on. |
| `playbackRuns` | function | The 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. |
| `rescaled` | function | The 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. |
| `STOPPED` | const | Stopped at the start, from the first frame on. |
| `startsInWindow` | function | The 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. |
| `toFrames` | function | A time in seconds as a whole number of frames: the nearest one. |
| `CLIP_PLAYER_WORKLET` | const | The 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_INPUTS` | const | A 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.

**In React**

The registry's [`clip-player`](/docs/lib/clip-player) runs it in an `AudioWorklet`, and the [`arrangement-engine`](/docs/lib/arrangement-engine) and [`mixer-engine`](/docs/lib/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:

```ts
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.

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

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

## The mixer

```ts
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.
