@webmusic/bridge 0.0.0-stage → 0.2.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.
@@ -0,0 +1,375 @@
1
+ import { TimeMap, Score } from '@webmusic/score';
2
+ import { BeatGrid, AudioClip } from '@webmusic/audio';
3
+ import { TransportClockReader } from '@webmusic/kernel/transport';
4
+ import { TickSourceOptions } from '@webmusic/kernel/tick';
5
+ import { TransportSnapshot, TransportEvent, TransportCommand, TransportCommit } from '@webmusic/kernel/sync';
6
+ export { TransportCommand, TransportCommit, TransportEvent, TransportSnapshot } from '@webmusic/kernel/sync';
7
+ import { AudioClipPlayer } from '@webmusic/audio/play/headless';
8
+ import { ScorePlayer, TonePlayer } from '@webmusic/score/play/headless';
9
+ import { RenderOptions } from '@webmusic/score/play';
10
+ import { TranscribedNote } from '@webmusic/audio/analyze/transcribe';
11
+
12
+ interface BeatGridFromTimeMapOptions {
13
+ /** How many quarters of the score timeline to sample. */
14
+ durationQuarters: number;
15
+ /** Beat subdivisions per quarter note (default 1: beat = quarter). */
16
+ beatsPerQuarter?: number;
17
+ /** Maximum number of beat samples to allocate. Default 1,000,000. */
18
+ maxBeats?: number;
19
+ }
20
+ declare const DEFAULT_MAX_MAPPED_BEATS = 1000000;
21
+ /**
22
+ * Sample a {@link TimeMap} into a {@link BeatGrid}: one beat per
23
+ * `1/beatsPerQuarter` quarter from 0 through `durationQuarters`. Lossless up
24
+ * to the sampling density — tempo changes between sampled beats interpolate
25
+ * linearly on the grid.
26
+ */
27
+ declare function beatGridFromTimeMap(map: TimeMap, options: BeatGridFromTimeMapOptions): BeatGrid;
28
+ /**
29
+ * Approximate a {@link TimeMap} from a {@link BeatGrid}: beat index becomes
30
+ * the quarter axis and every inter-beat interval one tempo segment. The
31
+ * grid's absolute offset is NOT representable (a TimeMap always maps quarter
32
+ * 0 to second 0) — align `grid.beats[0]` on the consumer side. Zero-length
33
+ * intervals are rejected: they would demand an infinite tempo.
34
+ */
35
+ declare function timeMapFromBeatGrid(grid: BeatGrid): TimeMap;
36
+
37
+ /** Both factory directions use one buffer engine and group-owned loop/rate. */
38
+ type FactoryClipOptions = Omit<NonNullable<ConstructorParameters<typeof AudioClipPlayer>[1]>, 'engine' | 'mediaAdapterFactory' | 'loop' | 'rate'> & {
39
+ engine?: 'buffer';
40
+ };
41
+
42
+ /** Read-only clock view a transport may expose (kernel TransportClockReader). */
43
+ type SyncTransportClockView = TransportClockReader;
44
+ /**
45
+ * Minimal structural surface the sync needs from the score-side transport.
46
+ * Everything is on the NOMINAL score-seconds axis (the rendered-clip
47
+ * timeline) — v2 dropped the rate-scaled members entirely.
48
+ *
49
+ * When `clock` is present (ScorePlayer exposes its kernel transport clock),
50
+ * the sync anchors by READING the clock — no sampling, no skew, and an armed
51
+ * scheduled start is visible through `holding`. Transports without a clock
52
+ * (TonePlayer, third parties) fall back to sampled anchoring; the sync then
53
+ * runs them behind a kernel MirrorClockMaster exactly as v1's inline mirror
54
+ * did.
55
+ */
56
+ interface SyncScoreTransport {
57
+ /**
58
+ * Start playback. The sync passes a proposed start time (absolute
59
+ * AudioContext seconds, a lead-in ahead) — a master supporting scheduled
60
+ * starts (ScorePlayer) arms its clock there so the clip can join at the
61
+ * exact same instant. Masters without the capability simply take no
62
+ * parameter and start immediately (a narrower signature satisfies this
63
+ * member structurally); the sync detects the difference by observing
64
+ * `clock.holding`, never through a declared flag.
65
+ */
66
+ play(when?: number): Promise<void> | void;
67
+ pause(): void;
68
+ stop(): void;
69
+ /**
70
+ * Seek to a NOMINAL score-seconds position. A returned promise settles
71
+ * once the seek has been applied and any mid-playback restart attempted;
72
+ * the sync awaits it before re-anchoring the clip, which is what makes
73
+ * mid-playback seeks land sample-accurately. The promise MAY resolve with
74
+ * the transport left paused when the restart failed (ScorePlayer swallows
75
+ * restart errors) — the sync treats that as a failed resume: it pauses the
76
+ * clip, settles into the paused state and reports 'resume after seek'
77
+ * through {@link ScoreAudioSyncOptions.onOperationError}.
78
+ *
79
+ * While playing, the sync passes a proposed re-entry time the same way
80
+ * {@link play} does, so a transport supporting scheduled re-anchoring
81
+ * brings both sides back in together. Transports that ignore it resume
82
+ * immediately and the clip re-joins a lead-in later, as before.
83
+ */
84
+ seekNominal(nominalSeconds: number, when?: number): void | Promise<void>;
85
+ setRate?(rate: number): void;
86
+ /** Nominal score-timeline position. */
87
+ readonly nominalSeconds: number;
88
+ /** Read-only transport clock (nominal axis), when the transport has one. */
89
+ readonly clock?: SyncTransportClockView;
90
+ dispose?(): void;
91
+ }
92
+ /**
93
+ * Role-neutral names for the two participants. The sync is defined by ROLE,
94
+ * not by family: the first constructor argument drives the transport and the
95
+ * second follows it. The score-mastered pairing these interfaces were named
96
+ * for is the default (see {@link createSyncedPlayback}), and the reverse —
97
+ * a recording driving the score — is assembled by the adapters in
98
+ * `audio-master.ts`. Prefer these names in role-generic code. They are the
99
+ * BRIDGE's shapes; the kernel's own role contracts are adapted onto them in
100
+ * the constructor.
101
+ */
102
+ type SyncMasterTransport = SyncScoreTransport;
103
+ /** @see SyncMasterTransport */
104
+ type SyncFollowerTransport = SyncClipTransport;
105
+ /** Minimal structural surface the sync needs from the clip-side transport. */
106
+ interface SyncClipTransport {
107
+ play(when?: number): Promise<void> | void;
108
+ pause(): void;
109
+ stop(): void;
110
+ seek(seconds: number): void;
111
+ setRate?(rate: number): void;
112
+ readonly seconds: number;
113
+ readonly playing?: boolean;
114
+ /**
115
+ * Read-only transport clock on the clip's own seconds axis, when the
116
+ * transport has one (AudioClipPlayer exposes the buffer engine's). When
117
+ * present, the drift monitor reads the clip position and running state
118
+ * from the clock instead of sampling `seconds`/`playing` — the same
119
+ * skew-free read-through the score side gets. (AudioClipPlayer's clock is
120
+ * unwrapped under clip-side loops, but the sync never sets one: looping
121
+ * is driven through master seeks, so the two axes agree here.)
122
+ */
123
+ readonly clock?: SyncTransportClockView;
124
+ dispose?(): void;
125
+ }
126
+ interface ScoreAudioSyncOptions {
127
+ /** Scheduling headroom before the clip joins, in seconds. Default 0.06. */
128
+ leadInSeconds?: number;
129
+ /** Clip seconds corresponding to score-seconds zero. Default 0. */
130
+ clipOffsetSeconds?: number;
131
+ /** Reseek the clip when |clip − expected| exceeds this. Default 0.03 s. */
132
+ driftToleranceSeconds?: number;
133
+ /** Drift check cadence. Default 250 ms. 0 disables drift checks; natural-stop and loop watching remain active. */
134
+ driftCheckIntervalMs?: number;
135
+ /** Loop region in score seconds; also settable at runtime via {@link ScoreAudioSync.setLoop}. */
136
+ loop?: SyncLoopRegion | null;
137
+ /** Injectable tick source options (tests; custom hosting). */
138
+ tick?: TickSourceOptions;
139
+ /**
140
+ * Observer for failures of the sync's own fire-and-forget operations
141
+ * (drift and rate re-joins, loop wraps, pause/stop reconciliation). Those
142
+ * run behind the command queue with no caller promise to reject, and on
143
+ * failure they settle the sync into a paused state — without an observer
144
+ * that settlement is silent. Observer exceptions are swallowed.
145
+ */
146
+ onOperationError?: (operation: string, error: unknown) => void;
147
+ }
148
+ /** A loop region on the nominal score-seconds axis. */
149
+ interface SyncLoopRegion {
150
+ startSeconds: number;
151
+ endSeconds: number;
152
+ }
153
+ /**
154
+ * Drives a score player and a clip player as one transport. Positions are in
155
+ * NOMINAL score seconds (the rendered-clip timeline); the clip is expected to
156
+ * run `clipOffsetSeconds` ahead of the score's zero (use 0 for a clip
157
+ * rendered from the same score).
158
+ */
159
+ declare class ScoreAudioSync {
160
+ #private;
161
+ constructor(score: SyncScoreTransport, clip: SyncClipTransport, context: BaseAudioContext, options?: ScoreAudioSyncOptions);
162
+ /**
163
+ * The shared transport clock (nominal score seconds): a read-through to the
164
+ * score transport's own clock when it has one, else the kernel mirror. The
165
+ * sync never mutates a transport-owned clock.
166
+ */
167
+ get clock(): SyncTransportClockView;
168
+ /** Coherent state on the nominal master-seconds axis. */
169
+ get snapshot(): TransportSnapshot;
170
+ /** Subscribe before receiving the current snapshot. Detaching the observer
171
+ * does not stop either player. Subsequent events describe command invalidation,
172
+ * committed/superseded settlement, errors and disposal. */
173
+ subscribe(listener: (event: TransportEvent) => void): () => void;
174
+ /** Await a command's participant settlement. Seek positions and loop bounds
175
+ * are nominal master seconds; rate never changes that coordinate system.
176
+ * The shared 0.25–4 rate range also applies to this command surface. */
177
+ dispatch(command: TransportCommand): Promise<TransportCommit>;
178
+ /**
179
+ * Set (or clear) a loop region on the score-seconds axis, live. The wrap
180
+ * runs through {@link seek}, so it inherits the shared re-entry origin:
181
+ * both transports leave the boundary together on one audio-clock instant,
182
+ * with no score-only opening on each cycle. A worker-backed tick watcher
183
+ * detects the boundary, so the wrap INSTANT still trails the true boundary
184
+ * by watcher delivery, preparation and lead-in delays; browser throttling
185
+ * prevents a fixed upper bound. Landing the wrap on
186
+ * the boundary itself needs the scheduler to commit notes across it (or
187
+ * the clip to loop natively), which is a separate design.
188
+ */
189
+ setLoop(loop: SyncLoopRegion | null): void;
190
+ get loop(): SyncLoopRegion | null;
191
+ /** Current transport position in nominal score seconds. */
192
+ get seconds(): number;
193
+ /**
194
+ * Start both transports on one shared audio-clock origin. The sync
195
+ * proposes `now + leadInSeconds` to the score master; one that supports
196
+ * scheduled starts arms there and the clip joins at that very instant, so
197
+ * with buffer-engine playback both make their first sound together. A
198
+ * master that ignores the proposal starts immediately and the clip joins
199
+ * a lead-in later, offset-matched to its anchor, exactly as before.
200
+ */
201
+ play(): Promise<void>;
202
+ pause(): void;
203
+ stop(): void;
204
+ /**
205
+ * Seek both transports to a score-seconds position. While playing, the
206
+ * sync proposes a shared re-entry origin exactly as {@link play} does and
207
+ * then re-joins the clip there, so both sides come back in together
208
+ * instead of the score resuming a lead-in ahead of the clip. Loop wraps
209
+ * run through this path and inherit the same shared origin.
210
+ */
211
+ seek(scoreSeconds: number): Promise<void>;
212
+ /**
213
+ * Set the shared playback rate on both transports. The score scheduler's
214
+ * retune is synchronous, so the clip re-joins immediately on the audio
215
+ * clock. The group owns the session command; each engine retains its own
216
+ * transport clock until shared-instance injection is implemented.
217
+ */
218
+ setRate(rate: number): void;
219
+ dispose(): void;
220
+ /**
221
+ * One drift check. Corrections re-join on the audio clock (the same
222
+ * scheduled-start dance as {@link play}) rather than command-level seeking,
223
+ * so a correction lands sample-accurately instead of chasing the score by
224
+ * one JS-tick each time.
225
+ */
226
+ checkDrift(): number;
227
+ }
228
+ interface CreateSyncedPlaybackOptions extends ScoreAudioSyncOptions {
229
+ /** Shared AudioContext. If omitted, the factory creates one and sync.dispose() closes it. */
230
+ context?: AudioContext;
231
+ /** ScorePlayer options. An initial tempo must imply a shared rate within 0.25–4×. */
232
+ scoreOptions?: ConstructorParameters<typeof ScorePlayer>[1];
233
+ /**
234
+ * Options forwarded to the AudioClipPlayer constructor. The engine is not
235
+ * selectable here: only the buffer engine can join sample-accurately, so
236
+ * the sync always builds a buffer-engine player ('buffer' is accepted,
237
+ * anything else throws). The media adapter and clip-side loop/rate
238
+ * overrides are rejected; use the sync's setLoop()/setRate() instead.
239
+ * Construct the players and a {@link ScoreAudioSync} directly to pair a
240
+ * score with other clip transports.
241
+ */
242
+ clipOptions?: FactoryClipOptions;
243
+ }
244
+ /**
245
+ * Construct a score player, a clip player and a {@link ScoreAudioSync} on one
246
+ * shared AudioContext — the safe way to get synchronized playback. The clip
247
+ * must carry decoded samples (streaming/URL-only clips cannot feed the
248
+ * buffer engine). To pair a clip from {@link renderScoreToClip} here, render
249
+ * with `tailSeconds: 0`; otherwise use {@link createAudioMasteredPlayback} so
250
+ * the clip can finish after the score's natural end.
251
+ */
252
+ declare function createSyncedPlayback(score: Score, clip: AudioClip, options?: CreateSyncedPlaybackOptions): {
253
+ sync: ScoreAudioSync;
254
+ scorePlayer: ScorePlayer;
255
+ clipPlayer: AudioClipPlayer;
256
+ };
257
+ /**
258
+ * Render a score offline into an {@link AudioClip}. With the default positive
259
+ * tail, use the clip as master so its final samples are not cut off when the
260
+ * score stops; `tailSeconds: 0` permits a score-mastered pairing. A tempo
261
+ * override that differs from the score's base tempo changes the clip's
262
+ * content axis and cannot be paired by either fixed-offset factory.
263
+ */
264
+ declare function renderScoreToClip(score: Score, options?: RenderOptions): Promise<AudioClip>;
265
+
266
+ /** Options shared by the reverse-role adapters. */
267
+ interface AudioMasterAdapterOptions {
268
+ /** Finite, non-negative clip seconds corresponding to score-seconds zero. Default 0. */
269
+ clipOffsetSeconds?: number;
270
+ }
271
+ /**
272
+ * Present an {@link AudioClipPlayer} as the sync's MASTER transport.
273
+ *
274
+ * A scheduled re-anchor (`seekNominal(position, when)`) is expressed as
275
+ * pause → seek → `play(when)`: the engine's own `seek` restarts immediately
276
+ * while playing, and its `play` is a no-op unless paused, so this is the
277
+ * sequence that actually arms the clock at `when` rather than starting at
278
+ * once. That is what lets a follower join the reversed pairing on a shared
279
+ * origin, exactly as the clip does in the forward one.
280
+ */
281
+ declare function clipAsMaster(clip: AudioClipPlayer): SyncMasterTransport;
282
+ /**
283
+ * Present a {@link ScorePlayer} as the sync's FOLLOWER transport, on the
284
+ * master clip's seconds axis.
285
+ *
286
+ * Three translations happen here.
287
+ *
288
+ * 1. Rate-invariant positions: `seekNominal`/`nominalSeconds`, never
289
+ * `seek`/`seconds`, which are rate-scaled and would desync the pairing at
290
+ * any rate but 1.
291
+ * 2. The clip-offset shift, so the sync itself needs no offset here.
292
+ * 3. The LEAD-IN region. A recording may hold material before score-zero — a
293
+ * count-in, an anacrusis, room tone — and there the score has no position
294
+ * at all: the requested one is negative and `seekNominal` clamps it to the
295
+ * start. Starting the score anyway would have it run the whole recording
296
+ * that much early, so a scheduled start is deferred by exactly the
297
+ * remaining lead-in, and the score enters when the recording actually
298
+ * reaches score-zero.
299
+ */
300
+ declare function scoreAsFollower(score: ScorePlayer, options?: AudioMasterAdapterOptions): SyncFollowerTransport;
301
+ interface CreateAudioMasteredPlaybackOptions extends ScoreAudioSyncOptions {
302
+ /** Shared AudioContext. If omitted, the factory creates one and sync.dispose() closes it. */
303
+ context?: AudioContext;
304
+ /** ScorePlayer options; tempo is group-owned and must be set with `sync.setRate()`. */
305
+ scoreOptions?: ConstructorParameters<typeof ScorePlayer>[1];
306
+ /**
307
+ * Options forwarded to the AudioClipPlayer constructor. As in the forward
308
+ * pairing the engine is not selectable: only the buffer engine holds a
309
+ * sample-accurate clock, and here it is the MASTER's clock, so nothing
310
+ * downstream could be accurate without it. The media adapter and clip-side
311
+ * loop/rate overrides are rejected; use the sync's setLoop()/setRate().
312
+ */
313
+ clipOptions?: FactoryClipOptions;
314
+ }
315
+ /**
316
+ * Construct an audio-mastered pairing: the CLIP drives the transport and the
317
+ * score follows it, on one shared AudioContext. This is the configuration for
318
+ * following a real recording — a performance, a rehearsal take — with the
319
+ * notation tracking it, rather than the score-mastered
320
+ * `createSyncedPlayback`, where the clip is typically a backing track
321
+ * rendered from the score itself.
322
+ *
323
+ * Positions are on the CLIP's seconds axis (the master's axis). Pass
324
+ * `clipOffsetSeconds` when the recording does not begin at score-seconds
325
+ * zero. The score player is returned so callers can silence it
326
+ * (`setVolume(0)`) when the recording is meant to be the only sounding
327
+ * source, which is the usual case here.
328
+ */
329
+ declare function createAudioMasteredPlayback(score: Score, clip: AudioClip, options?: CreateAudioMasteredPlaybackOptions): {
330
+ sync: ScoreAudioSync;
331
+ scorePlayer: ScorePlayer;
332
+ clipPlayer: AudioClipPlayer;
333
+ };
334
+
335
+ interface ScoreFromTranscriptionOptions {
336
+ /** Tempo of the produced score. Default 120 (pass the transcriber's bpm). */
337
+ bpm?: number;
338
+ /** Time signature. Default 4/4. */
339
+ timeSignature?: {
340
+ numerator: number;
341
+ denominator: number;
342
+ };
343
+ /**
344
+ * Notation grid in subdivisions per quarter note: onsets/durations snap to
345
+ * `1/grid` quarters and durations never collapse below one grid unit.
346
+ * Default 4 (sixteenth notes). Pass 0 to keep exact (unquantized) values
347
+ * on the 1/480 tick grid.
348
+ */
349
+ quantizeGrid?: number;
350
+ /** Score title. Default 'Transcription'. */
351
+ title?: string;
352
+ /** Part name. Default 'Transcribed'. */
353
+ partName?: string;
354
+ /** Maximum number of input note events to process. Default 100,000. */
355
+ maxNotes?: number;
356
+ /** Maximum number of measures to materialize. Default 4,096. */
357
+ maxMeasures?: number;
358
+ }
359
+ declare const DEFAULT_MAX_TRANSCRIPTION_NOTES = 100000;
360
+ declare const DEFAULT_MAX_TRANSCRIPTION_MEASURES = 4096;
361
+ /**
362
+ * Assemble a Score from transcribed note events. Notes with a MIDI pitch
363
+ * outside [0, 127] are skipped (transcription noise); velocities clamp into
364
+ * the 1..127 MIDI range; measures are laid out to cover the material.
365
+ */
366
+ declare function scoreFromTranscription(notes: readonly TranscribedNote[], options?: ScoreFromTranscriptionOptions): Score;
367
+
368
+ type Satisfies<T extends U, U> = T;
369
+ type SyncTransportContract = [
370
+ Satisfies<ScorePlayer, SyncScoreTransport>,
371
+ Satisfies<TonePlayer, SyncScoreTransport>,
372
+ Satisfies<AudioClipPlayer, SyncClipTransport>
373
+ ];
374
+
375
+ export { type AudioMasterAdapterOptions, type BeatGridFromTimeMapOptions, type CreateAudioMasteredPlaybackOptions, type CreateSyncedPlaybackOptions, DEFAULT_MAX_MAPPED_BEATS, DEFAULT_MAX_TRANSCRIPTION_MEASURES, DEFAULT_MAX_TRANSCRIPTION_NOTES, ScoreAudioSync, type ScoreAudioSyncOptions, type ScoreFromTranscriptionOptions, type SyncClipTransport, type SyncFollowerTransport, type SyncLoopRegion, type SyncMasterTransport, type SyncScoreTransport, type SyncTransportClockView, type SyncTransportContract, beatGridFromTimeMap, clipAsMaster, createAudioMasteredPlayback, createSyncedPlayback, renderScoreToClip, scoreAsFollower, scoreFromTranscription, timeMapFromBeatGrid };