@webmusic/bridge 0.2.0 → 0.4.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/dist/index.d.cts CHANGED
@@ -1,12 +1,10 @@
1
1
  import { TimeMap, Score } from '@webmusic/score';
2
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
3
  import { RenderOptions } from '@webmusic/score/play';
4
+ import { AudioPlayer, AudioClipPlayer } from '@webmusic/audio/play/headless';
5
+ import { ModuleContext, ModuleEnvironment, ProjectPluginFactory } from '@webmusic/kernel/module';
6
+ import { SessionTransport, ModuleSession, SessionParticipantLease } from '@webmusic/kernel/session';
7
+ import { HeadlessSynth, ScorePlayerModule, MidiAccessSource } from '@webmusic/score/play/headless';
10
8
  import { TranscribedNote } from '@webmusic/audio/analyze/transcribe';
11
9
 
12
10
  interface BeatGridFromTimeMapOptions {
@@ -34,303 +32,65 @@ declare function beatGridFromTimeMap(map: TimeMap, options: BeatGridFromTimeMapO
34
32
  */
35
33
  declare function timeMapFromBeatGrid(grid: BeatGrid): TimeMap;
36
34
 
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
35
  /**
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.
36
+ * Render a score offline into an {@link AudioClip} — a Score→Audio conversion
37
+ * that stays a data function (DEC-068). A positive tail (the default) keeps
38
+ * final samples after the score ends; `tailSeconds: 0` ends with the score. A
39
+ * tempo override changes the clip's content axis relative to the score.
55
40
  */
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. */
41
+ declare function renderScoreToClip(score: Score, options?: RenderOptions): Promise<AudioClip>;
42
+
43
+ interface CreateScoreAudioSessionOptions {
44
+ /** Borrowed context; without one the composition creates and owns a lazy one. */
45
+ context?: AudioContext;
46
+ /** Score synth; defaults to the oscillator. */
47
+ synth?: HeadlessSynth;
48
+ /** Session seconds → nominal Score seconds: `score = session * scale + offset`. */
49
+ scoreOffsetSeconds?: number;
50
+ scorePositionScale?: number;
51
+ /** Session seconds → clip seconds: `clip = session * scale + offset`. */
130
52
  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
- */
53
+ clipPositionScale?: number;
54
+ /** Lead-in before a shared start, in seconds. */
55
+ leadInSeconds?: number;
146
56
  onOperationError?: (operation: string, error: unknown) => void;
147
57
  }
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;
58
+ /** One Session conducting a Score engine and an Audio player (DEC-068). */
59
+ interface ScoreAudioSession {
60
+ /** The only command authority: play, pause, stop, seek, rate and loop go here. */
61
+ readonly session: SessionTransport;
62
+ readonly context: ModuleContext;
63
+ readonly scoreModule: ScorePlayerModule;
64
+ readonly clipPlayer: AudioPlayer;
65
+ /** Release both participants, their routes, the Session and an owned context. */
219
66
  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
67
  }
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
68
  /**
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.
69
+ * Compose a Score and an Audio clip under one Session — Bridge's replacement
70
+ * for the former master/follower sync family. Each engine is a Session
71
+ * participant with an explicit mapping from Session seconds into its own axis
72
+ * (`score-nominal-seconds`, `clip-seconds`); use `beatGridFromTimeMap` and
73
+ * `timeMapFromBeatGrid` to derive mappings between musical and audio time.
74
+ * Nothing is allocated until the Session prepares or plays.
263
75
  */
264
- declare function renderScoreToClip(score: Score, options?: RenderOptions): Promise<AudioClip>;
76
+ declare function createScoreAudioSession(score: Score, clip: AudioClip, options?: CreateScoreAudioSessionOptions): ScoreAudioSession;
265
77
 
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;
78
+ /** The engine surface a participant adapter needs; `AudioPlayer` and `AudioClipPlayer` both provide it. */
79
+ type AudioParticipantPlayer = Pick<AudioClipPlayer, 'play' | 'pause' | 'stop' | 'seek' | 'setRate' | 'seconds' | 'playing' | 'clock' | 'duration' | 'activateScheduling' | 'attachScheduling' | 'timingCapabilities'>;
80
+ interface AudioParticipantOptions {
81
+ offsetSeconds?: number;
82
+ positionScale?: number;
83
+ /** Prepare and route the player's output before the Session anchors a start. */
84
+ prepare: () => void | Promise<void>;
270
85
  }
271
86
  /**
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.
87
+ * Register a Headless Audio engine with a Session on the `clip-seconds` axis —
88
+ * the same axis `<audio-player>` uses, so Score and Audio mappings agree
89
+ * (DEC-068). Native buffer playback attaches and activates the shared
90
+ * scheduling anchor; other engines (document sequences, media streams,
91
+ * borrowed queues) are commanded by the Session without activation.
299
92
  */
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
- };
93
+ declare function registerAudioParticipant(session: ModuleSession, player: AudioParticipantPlayer, options: AudioParticipantOptions): SessionParticipantLease;
334
94
 
335
95
  interface ScoreFromTranscriptionOptions {
336
96
  /** Tempo of the produced score. Default 120 (pass the transcriber's bpm). */
@@ -365,11 +125,19 @@ declare const DEFAULT_MAX_TRANSCRIPTION_MEASURES = 4096;
365
125
  */
366
126
  declare function scoreFromTranscription(notes: readonly TranscribedNote[], options?: ScoreFromTranscriptionOptions): Score;
367
127
 
368
- type Satisfies<T extends U, U> = T;
369
- type SyncTransportContract = [
370
- Satisfies<ScorePlayer, SyncScoreTransport>,
371
- Satisfies<TonePlayer, SyncScoreTransport>,
372
- Satisfies<AudioClipPlayer, SyncClipTransport>
373
- ];
128
+ interface WebMusicProjectPluginOptions {
129
+ /** Where printing, script output and module failures go, and the clock for timed messages; see Kernel's `ModuleEnvironment`. */
130
+ readonly modules?: ModuleEnvironment;
131
+ /** Web MIDI for the MIDI modules; one is made when omitted, and asks for access only when a module needs a device. */
132
+ readonly midi?: MidiAccessSource;
133
+ }
134
+ /**
135
+ * The standard set (DEC-097): the Bridge's own players, rack, bus, effect and
136
+ * LFO, which need both domains, with the module types each package registers
137
+ * — Kernel's message, structure and sequence modules, Score's MIDI and sound
138
+ * modules, and Audio's buffer modules. Trusted, explicit factories; asset
139
+ * resolution and storage remain application responsibilities.
140
+ */
141
+ declare function createWebMusicProjectPlugins(options?: WebMusicProjectPluginOptions): readonly ProjectPluginFactory[];
374
142
 
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 };
143
+ export { type AudioParticipantOptions, type AudioParticipantPlayer, type BeatGridFromTimeMapOptions, type CreateScoreAudioSessionOptions, DEFAULT_MAX_MAPPED_BEATS, DEFAULT_MAX_TRANSCRIPTION_MEASURES, DEFAULT_MAX_TRANSCRIPTION_NOTES, type ScoreAudioSession, type ScoreFromTranscriptionOptions, type WebMusicProjectPluginOptions, beatGridFromTimeMap, createScoreAudioSession, createWebMusicProjectPlugins, registerAudioParticipant, renderScoreToClip, scoreFromTranscription, timeMapFromBeatGrid };