@dawcore/transport 0.0.14 → 0.0.16-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,16 +1,16 @@
1
1
  # @dawcore/transport
2
2
 
3
- Native Web Audio transport for multi-track audio scheduling, looping, tempo, and metronome. Zero npm dependencies.
3
+ Native Web Audio transport for the dawcore family — multi-track scheduling, looping, tempo automation, time signatures, and metronome. No Tone.js, zero npm dependencies.
4
4
 
5
5
  ## Features
6
6
 
7
7
  - **Native Web Audio** — No Tone.js, no `standardized-audio-context`. Direct `AudioContext` with full `sampleRate` and `latencyHint` control.
8
- - **Sliding window scheduler** — Schedules audio 200ms ahead via `requestAnimationFrame` for glitch-free playback.
8
+ - **Sliding window scheduler** — Schedules audio 200ms ahead, driven by a Web Worker timer so playback keeps running in a hidden tab (rAF stops there; main-thread timers throttle).
9
9
  - **Dual timeline** — Sample-absolute positions for audio clips, PPQN tick positions for metronome/MIDI.
10
10
  - **Built-in metronome** — Beat-grid click scheduling with accent on beat 1. Default synthesized click sounds out of the box.
11
11
  - **Count-in (pre-roll)** — Configurable bars of click sounds before playback begins. Beat-by-beat events for UI countdown.
12
- - **Per-track signal chain** — Native GainNode (volume) → StereoPannerNode → GainNode (mute) → effects hook → master output.
13
- - **Effects plugin hook** — `connectTrackOutput(trackId, node)` and `connectMasterOutput(node)` insert any `AudioNode` chain (Tone.js effects, WAM plugins, native nodes) per-track or on the master bus.
12
+ - **Per-track signal chain** — clip sources → effects insert (pre-fader) → GainNode (volume) → pan stage (a gain matrix, not a `StereoPannerNode` — see [Panning](#panning)) → GainNode (mute) → master output.
13
+ - **Effects plugin hook** — `connectTrackEffects(trackId, input, output)` (pre-fader track insert) and `connectMasterOutput(node)` insert any `AudioNode` chain (Tone.js effects, WAM plugins, native nodes) per-track or on the master bus.
14
14
  - **Type-safe coordinates** — Branded `Tick` and `Sample` types prevent accidentally passing seconds where ticks or samples are expected. Zero runtime cost.
15
15
  - **PlayoutAdapter bridge** — `NativePlayoutAdapter` implements the `PlayoutAdapter` interface from `@waveform-playlist/engine`.
16
16
 
@@ -20,7 +20,7 @@ Native Web Audio transport for multi-track audio scheduling, looping, tempo, and
20
20
  npm install @dawcore/transport
21
21
  ```
22
22
 
23
- No runtime dependencies. When using `NativePlayoutAdapter` (bridge to `@waveform-playlist/engine`), install `@waveform-playlist/core` and `@waveform-playlist/engine` alongside.
23
+ One runtime dependency, installed automatically: `@waveform-playlist/core` (dependency-free itself; the transport uses its shared pan stage). When using `NativePlayoutAdapter` (bridge to `@waveform-playlist/engine`), install `@waveform-playlist/engine` alongside.
24
24
 
25
25
  ## Quick Start
26
26
 
@@ -150,21 +150,26 @@ transport.setTempo(140, transport.barToTick(9), { interpolation: 'linear' }); /
150
150
  ### Effects
151
151
 
152
152
  ```typescript
153
- // Insert any AudioNode chain between track output and master
154
- const reverb = audioContext.createConvolver();
155
- reverb.buffer = impulseResponse;
156
- reverb.connect(transport.audioContext.destination);
153
+ // Insert any AudioNode chain on a track, PRE-FADER:
154
+ // clips → input … output → volume → pan → mute → master
155
+ // Pass the chain's first and last node; the transport wires both ends.
156
+ const highpass = audioContext.createBiquadFilter();
157
+ highpass.type = 'highpass';
158
+ const compressor = audioContext.createDynamicsCompressor();
159
+ highpass.connect(compressor);
157
160
 
158
- transport.connectTrackOutput('vocals', reverb);
161
+ transport.connectTrackEffects('vocals', highpass, compressor);
162
+ // A single-node effect is its own input and output:
163
+ // transport.connectTrackEffects('vocals', reverb, reverb);
159
164
 
160
- // Remove effects — restores direct routing to master
161
- transport.disconnectTrackOutput('vocals');
165
+ // Remove effects — restores the track's direct routing
166
+ transport.disconnectTrackEffects('vocals');
162
167
 
163
168
  // Master bus effects — inserted between master gain and destination
164
- const compressor = audioContext.createDynamicsCompressor();
165
- compressor.connect(audioContext.destination);
169
+ const limiter = audioContext.createDynamicsCompressor();
170
+ limiter.connect(audioContext.destination);
166
171
 
167
- transport.connectMasterOutput(compressor);
172
+ transport.connectMasterOutput(limiter);
168
173
 
169
174
  // Remove master effects — restores direct routing to destination.
170
175
  // Parallel taps on transport.masterOutputNode (analyzers, recorders)
@@ -172,6 +177,32 @@ transport.connectMasterOutput(compressor);
172
177
  transport.disconnectMasterOutput();
173
178
  ```
174
179
 
180
+ **Track effects are pre-fader inserts.** The chain sees the clips at their own level and channel layout; the track's volume, pan and mute come after it. So:
181
+
182
+ - Moving the volume fader changes the track's level in the mix, not how hard a compressor, limiter or distortion works.
183
+ - A mono clip reaches the chain as mono, at full level (not as two channels at −3 dB from a centred panner).
184
+ - Do **not** connect the chain's output to `masterOutputNode` yourself — the transport returns it into the track. Routing it to the master would bypass the fader, pan, mute and solo.
185
+ - Mute and solo silence a track including its effect tails.
186
+ - Pan is unaffected by what the chain outputs: the pan law follows the track's clips, not the chain. A stereo reverb on a mono track stays stereo and sits at the same centre level as the dry track (see [Panning](#panning)).
187
+
188
+ `setTracks()` rebuilds every track node and drops these hookups — reconnect afterwards. (Before 0.0.16 the hook was `connectTrackOutput(trackId, node)`, post-fader, with the caller wiring the chain to the master.)
189
+
190
+ ### Panning
191
+
192
+ A track is panned by a small gain matrix (`createPanStage` from `@waveform-playlist/core`), **not** by a Web Audio `StereoPannerNode`.
193
+
194
+ Why: a `StereoPannerNode` chooses its pan law from the signal it _receives_ — the equal-power law for mono input (−3 dB per side at centre), the stereo law for stereo input (unity at centre). With pre-fader effects the panner is fed by the effects chain, so the law would follow the chain's output instead of the track: a mono track with a stereo reverb or a typical WAM plugin would jump about 3 dB at centre and get a different pan curve the moment the effect was added.
195
+
196
+ The pan stage implements the same two laws — its output matches a `StereoPannerNode` fed the raw clip to within float rounding — but takes the law from the track's **source material**: the highest channel count among the track's clips (`trackChannelCount(track)`), re-evaluated on `setTracks`, `addTrack` and `updateTrack`.
197
+
198
+ - Mono track: equal-power pan. The stage never mixes the two channels, so a stereo effect stays stereo.
199
+ - Stereo track: the stereo law — centre passes both channels at unity; panning left folds the right channel into the left, and vice versa.
200
+ - A track with both mono and stereo clips uses the stereo law for all of them, so its mono clips play 3 dB louder at centre than they would on a mono-only track. Adding the first stereo clip to a mono track (or removing the last one) therefore shifts the track's mono clips by 3 dB at centre. (Before 0.0.16 the law depended on which clips happened to be sounding.)
201
+
202
+ The Tone.js adapter (`@waveform-playlist/playout`) and both offline renderers use the same stage, so pan positions and levels match across backends and between playback and export.
203
+
204
+ **Note:** tracks carry no effects. Use `connectTrackEffects`/`connectMasterOutput` for effects with the native transport. (The Tone.js adapter in `@waveform-playlist/playout` additionally accepts a `trackEffects` lookup of closure-style effects functions; `NativePlayoutAdapter` has no equivalent.)
205
+
175
206
  ## API
176
207
 
177
208
  ### Transport
@@ -198,6 +229,9 @@ new Transport(audioContext: AudioContext, options?: TransportOptions)
198
229
  - `stop()` — Stop and reset to beginning
199
230
  - `seek(time)` — Jump to a position (works during playback)
200
231
  - `getCurrentTime()` — Current transport position in seconds
232
+ - `getCurrentFrame(): ContextFrame` — the same position in whole AudioContext frames (elapsed time is counted in whole frames; context readings are snapped to the 128-frame render lattice). `ContextFrame` is branded separately from `Sample` because the SampleTimeline may run at a different `sampleRate` than the context
233
+ - `getCurrentSample(): Sample` — the same position in SampleTimeline samples (the `sampleRate` option's rate), rounded once
234
+ - `rebaseCount` (getter) — how many backward AudioContext clock readings were absorbed (see the `discontinuity` event)
201
235
  - `isPlaying()` — Whether transport is playing
202
236
 
203
237
  **Tracks:**
@@ -214,18 +248,21 @@ new Transport(audioContext: AudioContext, options?: TransportOptions)
214
248
  - `setMasterVolume(volume)`
215
249
 
216
250
  **Loop:**
217
- - `setLoop(enabled, startTick: Tick, endTick: Tick)` — Set loop region in ticks (primary API)
218
- - `setLoopSeconds(enabled, start, end)` — Set loop region in seconds (convenience)
219
- - `setLoopSamples(enabled, startSample: Sample, endSample: Sample)` — Set loop region in samples (convenience)
251
+ - `setLoop(enabled, startTick: Tick, endTick: Tick)` — Set loop region in ticks (primary API). Throws when `enabled` and the range is non-finite, empty or inverted; the previous loop stays in force.
252
+ - `setLoopSeconds(enabled, start, end)` — Set loop region in seconds (convenience, same validation)
253
+ - `setLoopSamples(enabled, startSample: Sample, endSample: Sample)` — Set loop region in samples (convenience, same validation)
220
254
 
221
255
  **Tempo & Meter:**
222
256
  - `setTempo(bpm, atTick?, options?)` / `getTempo(atTick?: Tick)` — options: `{ interpolation: 'step' | 'linear' | { type: 'curve', slope } }`. Returns `boolean`: a defaulted `atTick` is the single-BPM convenience path and is refused (with a warning) when the tempo map has more than one entry — pass an explicit `atTick` to modify a tempo curve.
223
257
  - `removeTempo(atTick: Tick)` — remove the tempo entry at a tick (the tick-0 entry cannot be removed)
224
258
  - `clearTempos()` — remove all tempo entries
259
+ - `tempoMap` (getter) — the current `TempoMap`. It is an immutable value: every edit that changes the map swaps in a new one, so a reference you hold keeps converting with the tempo it had. `TempoMap` itself exposes `withTempo(bpm, atTick?, options?)`, `withoutTempo(atTick)`, `withoutTempos()` (each returns a new map) and `entries` (frozen, tick-ordered, with cumulative `secondsAtTick`).
225
260
  - `setMeter(numerator, denominator, atTick?: Tick)` / `getMeter(atTick?: Tick)`
226
261
  - `removeMeter(atTick: Tick)` / `clearMeters()`
227
262
  - `barToTick(bar): Tick` / `tickToBar(tick: Tick)`
228
- - `timeToTick(seconds): Tick` / `tickToTime(tick: Tick)`
263
+ - `timeToTick(seconds): Tick` / `tickToTime(tick: number)` — `timeToTick` is the integer tick (`TempoMap.secondsToTicks` rounds the exact value once); `tickToTime` accepts an integer or fractional tick position
264
+ - `timeToTickExact(seconds): number` — fractional tick position, for sub-tick placement (e.g. a recorded note between ticks before quantising); `tickToTime` accepts it back. The same pairing exists one layer down: `TempoMap.secondsToTicks` / `secondsToTicksExact`, `SampleTimeline.samplesToTicks` / `samplesToTicksExact` (rounding happens once, in the integer variant), and `TempoMap.secondsToBeats` is continuous.
265
+ - `quantizeTick(tick, subdivision, { mode?, strength? }): Tick` — snap a (possibly fractional) tick to the meter grid. `subdivision`: `{ ticks: n }`, `{ note: 8, dotted?, triplet? }` (PPQN-independent), `'bar'` or `'beat'`; `mode`: `'nearest'` (default, ties go up) | `'next'` (ceiling) | `'previous'` (floor) — all idempotent, a tick already on a line stays (unlike Tone's strict `nextSubdivision`; pass `tick + 1` with `'next'` for the following line); `strength` 0–1. A fractional tick within 1e-6 of a line counts as on it. Grid lines restart at each bar line, so odd meters stay aligned. Also exported standalone as `quantizeTick(meterMap, …)`.
229
266
 
230
267
  **Metronome:**
231
268
  - `setMetronomeEnabled(enabled)`
@@ -239,19 +276,23 @@ new Transport(audioContext: AudioContext, options?: TransportOptions)
239
276
  - `isCountingIn()` — whether count-in is active
240
277
 
241
278
  **Effects:**
242
- - `connectTrackOutput(trackId, node)` — Insert per-track effects chain
243
- - `disconnectTrackOutput(trackId)` — Remove per-track effects chain
279
+ - `connectTrackEffects(trackId, input, output)` — Insert a per-track effects chain, pre-fader (the transport wires `output` back into the track)
280
+ - `disconnectTrackEffects(trackId)` — Remove the per-track effects chain
244
281
  - `connectMasterOutput(node)` — Insert master bus effects chain
245
282
  - `disconnectMasterOutput()` — Remove master bus effects chain
246
283
  - `masterOutputNode` (getter) — Master gain node, for parallel taps (analyzers, recorders) that should survive chain connect/disconnect
247
284
 
248
285
  **Events:**
249
286
  - `on(event, callback)` / `off(event, callback)`
250
- - Events: `play`, `pause`, `stop`, `seek`, `loop`, `tempochange`, `meterchange`, `countIn`, `countInEnd`
287
+ - Events: `play`, `pause`, `stop`, `ended`, `seek`, `loop`, `tick`, `tempochange`, `meterchange`, `countIn`, `countInEnd`, `discontinuity`, `error`
288
+ - `tick` — `{ seconds }`: one scheduler tick advanced the timeline (every `timerIntervalMs`, default 25 ms, while playing; driven by the Worker timer so it keeps its cadence in a hidden tab). For consumers that must poll the playhead for state the transport does not announce (e.g. a tempo-map boundary crossed mid-playback); UI position updates should still use `requestAnimationFrame`
289
+ - `ended` — a bounded `play(start, end)` reached `end` and the transport stopped itself; fires right after `stop` (so a handler may restart playback), never for a consumer `stop()`/`pause()`/`seek()`
290
+ - `discontinuity` — `{ seconds, shiftSeconds }`: the AudioContext clock went backwards while playing (defensive; the spec makes it monotonic). The position was held (`seconds` is what `getCurrentTime()` reports) and, outside a count-in, scheduled audio re-created from it; during a count-in the already-armed clicks are dropped. Diagnostics only — with no subscriber the first occurrence is warned to the console
251
291
  - `seek` payload: `{ seconds: number }`
252
292
  - `tempochange` payload: `{ bpm: number, atTick: Tick }`
253
293
  - `meterchange` payload: `{ numerator: number, denominator: number, atTick: Tick }`
254
294
  - `countIn` payload: `{ beat: number, totalBeats: number }`
295
+ - `error` payload: `SchedulerListenerError`, discriminated on `phase` — `{ phase: 'generate', fromTick, toTick }`, `{ phase: 'consume', event }` or `{ phase: 'positionJump', tick }`, each with `listener` and `error`. A scheduler listener (clip player, metronome, count-in, or your own) threw; the scheduler skipped it and kept going. Delivered on a microtask after the scheduler window completes. With no `error` subscriber at delivery time the failure goes to `console.warn` instead (once per listener and failure kind).
255
296
 
256
297
  **Cleanup:**
257
298
  - `dispose()` — Stop playback, disconnect all nodes, remove listeners
@@ -268,7 +309,11 @@ Implements `PlayoutAdapter` from `@waveform-playlist/engine`. All methods delega
268
309
  - `adapter.ppqn` — Tick resolution, read by the engine on construction
269
310
  - `adapter.masterOutputNode` — Master gain node for parallel taps (analyzers, recorders)
270
311
  - `adapter.init()` — Resumes a suspended AudioContext and waits for the hardware pipeline to warm up (Safari needs this before clips scheduled at time 0 play on time)
271
- - `setTempo(bpm, atTick?)`, `setMeter(numerator, denominator, atTick?)`, `ticksToSeconds(tick)`, `secondsToTicks(seconds)` — tempo/meter surface the engine uses for tick-based timeline math
312
+ - `setTempo(bpm, atTick?)`, `setMeter(numerator, denominator, atTick?)`, `ticksToSeconds(tick)`, `secondsToTicks(seconds)`, `secondsToTicksExact(seconds)` — tempo/meter surface the engine uses for tick-based timeline math
313
+
314
+ ### Advanced (Low-Level Building Blocks)
315
+
316
+ For consumers assembling a custom scheduler or embedding transport internals elsewhere, the layers underneath `Transport` are also exported: `Clock`, `Scheduler`, `Timer`, `SampleTimeline`, `TempoMap`, `MeterMap`, `MasterNode`, `TrackNode`, `ClipPlayer`, `MetronomePlayer`. See [`src/index.ts`](https://github.com/naomiaro/waveform-playlist/blob/main/packages/transport/src/index.ts) for the full export list — most consumers only need `Transport` and `NativePlayoutAdapter`.
272
317
 
273
318
  ## Examples
274
319