@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.
- package/LICENSE +21 -0
- package/README.md +101 -2
- package/dist/build-receipt.json +7 -0
- package/dist/index.cjs +746 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +375 -0
- package/dist/index.d.ts +375 -0
- package/dist/index.js +720 -0
- package/dist/index.js.map +1 -0
- package/package.json +68 -4
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,746 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __typeError = (msg) => {
|
|
7
|
+
throw TypeError(msg);
|
|
8
|
+
};
|
|
9
|
+
var __export = (target, all) => {
|
|
10
|
+
for (var name in all)
|
|
11
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
12
|
+
};
|
|
13
|
+
var __copyProps = (to, from, except, desc) => {
|
|
14
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
15
|
+
for (let key of __getOwnPropNames(from))
|
|
16
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
17
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
18
|
+
}
|
|
19
|
+
return to;
|
|
20
|
+
};
|
|
21
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
22
|
+
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
|
|
23
|
+
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
|
|
24
|
+
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
25
|
+
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
|
|
26
|
+
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
|
|
27
|
+
|
|
28
|
+
// src/index.ts
|
|
29
|
+
var index_exports = {};
|
|
30
|
+
__export(index_exports, {
|
|
31
|
+
DEFAULT_MAX_MAPPED_BEATS: () => DEFAULT_MAX_MAPPED_BEATS,
|
|
32
|
+
DEFAULT_MAX_TRANSCRIPTION_MEASURES: () => DEFAULT_MAX_TRANSCRIPTION_MEASURES,
|
|
33
|
+
DEFAULT_MAX_TRANSCRIPTION_NOTES: () => DEFAULT_MAX_TRANSCRIPTION_NOTES,
|
|
34
|
+
ScoreAudioSync: () => ScoreAudioSync,
|
|
35
|
+
beatGridFromTimeMap: () => beatGridFromTimeMap,
|
|
36
|
+
clipAsMaster: () => clipAsMaster,
|
|
37
|
+
createAudioMasteredPlayback: () => createAudioMasteredPlayback,
|
|
38
|
+
createSyncedPlayback: () => createSyncedPlayback,
|
|
39
|
+
renderScoreToClip: () => renderScoreToClip,
|
|
40
|
+
scoreAsFollower: () => scoreAsFollower,
|
|
41
|
+
scoreFromTranscription: () => scoreFromTranscription,
|
|
42
|
+
timeMapFromBeatGrid: () => timeMapFromBeatGrid
|
|
43
|
+
});
|
|
44
|
+
module.exports = __toCommonJS(index_exports);
|
|
45
|
+
|
|
46
|
+
// src/mapping.ts
|
|
47
|
+
var import_score = require("@webmusic/score");
|
|
48
|
+
var import_audio = require("@webmusic/audio");
|
|
49
|
+
var DEFAULT_MAX_MAPPED_BEATS = 1e6;
|
|
50
|
+
function beatGridFromTimeMap(map, options) {
|
|
51
|
+
const { durationQuarters, beatsPerQuarter = 1, maxBeats = DEFAULT_MAX_MAPPED_BEATS } = options;
|
|
52
|
+
if (!Number.isFinite(durationQuarters) || durationQuarters <= 0) {
|
|
53
|
+
throw new RangeError("durationQuarters must be finite and > 0");
|
|
54
|
+
}
|
|
55
|
+
if (!Number.isSafeInteger(beatsPerQuarter) || beatsPerQuarter < 1) {
|
|
56
|
+
throw new RangeError("beatsPerQuarter must be a positive safe integer");
|
|
57
|
+
}
|
|
58
|
+
if (!Number.isSafeInteger(maxBeats) || maxBeats < 2) {
|
|
59
|
+
throw new RangeError("maxBeats must be a safe integer >= 2");
|
|
60
|
+
}
|
|
61
|
+
const scaledDuration = durationQuarters * beatsPerQuarter;
|
|
62
|
+
const nearestInteger = Math.round(scaledDuration);
|
|
63
|
+
const ulpTolerance = Number.EPSILON * Math.max(1, Math.abs(scaledDuration)) * 4;
|
|
64
|
+
const normalizedDuration = Math.abs(scaledDuration - nearestInteger) <= ulpTolerance ? nearestInteger : scaledDuration;
|
|
65
|
+
const total = Math.ceil(normalizedDuration);
|
|
66
|
+
if (!Number.isSafeInteger(total) || total >= maxBeats) {
|
|
67
|
+
throw new RangeError(
|
|
68
|
+
`Beat-grid mapping would allocate more than maxBeats (${maxBeats.toLocaleString()}) samples.`
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
const beats = [];
|
|
72
|
+
for (let index = 0; index <= total; index++) {
|
|
73
|
+
beats.push(map.quartersToSeconds(new import_score.Rational(index, beatsPerQuarter)));
|
|
74
|
+
}
|
|
75
|
+
const tempo = map.tempoAt(import_score.Rational.ZERO);
|
|
76
|
+
const bpm = tempo.bpm * (tempo.unit ?? 1) * beatsPerQuarter;
|
|
77
|
+
return new import_audio.BeatGrid({ bpm, beats });
|
|
78
|
+
}
|
|
79
|
+
function timeMapFromBeatGrid(grid) {
|
|
80
|
+
const beats = grid.beats;
|
|
81
|
+
const tempi = [];
|
|
82
|
+
if (beats.length < 2) {
|
|
83
|
+
tempi.push({ atQuarters: import_score.Rational.ZERO, bpm: grid.bpm });
|
|
84
|
+
} else {
|
|
85
|
+
for (let index = 0; index < beats.length - 1; index++) {
|
|
86
|
+
const interval = beats[index + 1] - beats[index];
|
|
87
|
+
if (!(interval > 0)) {
|
|
88
|
+
throw new RangeError(`BeatGrid interval at beat ${index} is not positive (${interval}).`);
|
|
89
|
+
}
|
|
90
|
+
tempi.push({ atQuarters: new import_score.Rational(index, 1), bpm: 60 / interval });
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return new import_score.TimeMap(tempi, [
|
|
94
|
+
{ atQuarters: import_score.Rational.ZERO, measureNumber: 1, timeSignature: { numerator: 4, denominator: 4 } }
|
|
95
|
+
]);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// src/sync.ts
|
|
99
|
+
var import_sync = require("@webmusic/kernel/sync");
|
|
100
|
+
var import_audio_context = require("@webmusic/kernel/audio-context");
|
|
101
|
+
var import_audio2 = require("@webmusic/audio");
|
|
102
|
+
var import_headless = require("@webmusic/audio/play/headless");
|
|
103
|
+
var import_headless2 = require("@webmusic/score/play/headless");
|
|
104
|
+
var import_play = require("@webmusic/score/play");
|
|
105
|
+
|
|
106
|
+
// src/owned-context.ts
|
|
107
|
+
var ownedContexts = /* @__PURE__ */ new WeakMap();
|
|
108
|
+
function ownContext(owner, context, onOperationError) {
|
|
109
|
+
ownedContexts.set(owner, { context, onOperationError });
|
|
110
|
+
}
|
|
111
|
+
function releaseOwnedContext(owner) {
|
|
112
|
+
const owned = ownedContexts.get(owner);
|
|
113
|
+
if (!owned) return;
|
|
114
|
+
ownedContexts.delete(owner);
|
|
115
|
+
closeContext(owned.context, owned.onOperationError);
|
|
116
|
+
}
|
|
117
|
+
function closeContext(context, onOperationError) {
|
|
118
|
+
const report = (error) => {
|
|
119
|
+
try {
|
|
120
|
+
onOperationError?.("context.close", error);
|
|
121
|
+
} catch {
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
try {
|
|
125
|
+
void context.close().catch(report);
|
|
126
|
+
} catch (error) {
|
|
127
|
+
report(error);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// src/factory-clip-options.ts
|
|
132
|
+
function validatedClipOffsetSeconds(value) {
|
|
133
|
+
const offset = value ?? 0;
|
|
134
|
+
if (!Number.isFinite(offset) || offset < 0) {
|
|
135
|
+
throw new RangeError("clipOffsetSeconds must be finite and >= 0.");
|
|
136
|
+
}
|
|
137
|
+
return offset;
|
|
138
|
+
}
|
|
139
|
+
function assertFactoryClipOptions(factory, clip, options) {
|
|
140
|
+
const input = options;
|
|
141
|
+
if (input?.loop !== void 0) {
|
|
142
|
+
throw new RangeError(
|
|
143
|
+
`${factory} does not accept clipOptions.loop: native clip looping does not expose the wrapped group axis. Use ScoreAudioSync.setLoop to loop both transports together.`
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
if (input?.rate !== void 0) {
|
|
147
|
+
throw new RangeError(
|
|
148
|
+
`${factory} does not accept clipOptions.rate: the shared rate is owned by the transport group. Use ScoreAudioSync.setRate to change it on both transports.`
|
|
149
|
+
);
|
|
150
|
+
}
|
|
151
|
+
if (input?.engine !== void 0 && input.engine !== "buffer") {
|
|
152
|
+
throw new RangeError(
|
|
153
|
+
`${factory} always uses the buffer engine (only it supplies the required scheduled clock); got engine '${String(input.engine)}'. Construct the players and ScoreAudioSync directly to use another clip transport.`
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
if (input?.mediaAdapterFactory !== void 0) {
|
|
157
|
+
throw new RangeError(
|
|
158
|
+
`${factory} always uses the buffer engine; mediaAdapterFactory does not apply.`
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
if (!clip.hasSamples) {
|
|
162
|
+
throw new RangeError(
|
|
163
|
+
`${factory} requires a clip with decoded samples: the buffer engine cannot play a streaming (URL-only) clip. Decode the audio when loading it, or render a matched backing track with renderScoreToClip.`
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// src/render-provenance.ts
|
|
169
|
+
var REGISTRY_KEY = /* @__PURE__ */ Symbol.for("@webmusic/bridge/render-provenance-v1");
|
|
170
|
+
function renderProvenance(create) {
|
|
171
|
+
let registry = Reflect.get(globalThis, REGISTRY_KEY);
|
|
172
|
+
if (registry === void 0 && create) {
|
|
173
|
+
registry = /* @__PURE__ */ new WeakMap();
|
|
174
|
+
Object.defineProperty(globalThis, REGISTRY_KEY, {
|
|
175
|
+
value: registry,
|
|
176
|
+
enumerable: false,
|
|
177
|
+
writable: false,
|
|
178
|
+
configurable: false
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
return registry;
|
|
182
|
+
}
|
|
183
|
+
function recordRenderProvenance(clip, score, tempoScale, hasTail) {
|
|
184
|
+
renderProvenance(true).set(clip, { score, tempoScale, hasTail });
|
|
185
|
+
}
|
|
186
|
+
function assertRenderedClipAlignment(factory, score, clip, expandRepeats = false) {
|
|
187
|
+
const provenance = renderProvenance(false)?.get(clip);
|
|
188
|
+
if (!provenance) return;
|
|
189
|
+
if (provenance.score !== score) {
|
|
190
|
+
throw new RangeError(
|
|
191
|
+
`${factory} cannot pair a Bridge-rendered clip with a different Score instance. Render this score again with renderScoreToClip(), or use an ordinary clip if your application owns the alignment.`
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
if (expandRepeats) {
|
|
195
|
+
throw new RangeError(
|
|
196
|
+
`${factory} cannot expand repeats only in ScorePlayer for a Bridge-rendered clip: the score and clip would follow different timelines. Call expandRepeats(score) first, then renderScoreToClip(expandedScore) and pair that same expanded Score instance without scoreOptions.expandRepeats.`
|
|
197
|
+
);
|
|
198
|
+
}
|
|
199
|
+
if (provenance.tempoScale !== 1) {
|
|
200
|
+
throw new RangeError(
|
|
201
|
+
`${factory} cannot pair a clip rendered with a tempo override: its audio seconds do not match the score-seconds axis. Render at the score tempo, then change both players with sync.setRate().`
|
|
202
|
+
);
|
|
203
|
+
}
|
|
204
|
+
if (factory === "createSyncedPlayback" && provenance.hasTail) {
|
|
205
|
+
throw new RangeError(
|
|
206
|
+
"createSyncedPlayback cannot play the tail of a clip rendered from the same score: the score master stops at its natural end. Use createAudioMasteredPlayback(score, clip) to play the complete render, or render with tailSeconds: 0."
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// src/sync.ts
|
|
212
|
+
var MIN_SHARED_PLAYBACK_RATE = 0.25;
|
|
213
|
+
var MAX_SHARED_PLAYBACK_RATE = 4;
|
|
214
|
+
var _group, _score, _disposed, _ScoreAudioSync_instances, assertActive_fn;
|
|
215
|
+
var ScoreAudioSync = class {
|
|
216
|
+
constructor(score, clip, context, options = {}) {
|
|
217
|
+
__privateAdd(this, _ScoreAudioSync_instances);
|
|
218
|
+
__privateAdd(this, _group);
|
|
219
|
+
__privateAdd(this, _score);
|
|
220
|
+
__privateAdd(this, _disposed, false);
|
|
221
|
+
__privateSet(this, _score, score);
|
|
222
|
+
const clipOffset = validatedClipOffsetSeconds(options.clipOffsetSeconds);
|
|
223
|
+
const now = () => context.currentTime;
|
|
224
|
+
const commands = {
|
|
225
|
+
play: (when) => score.play(when),
|
|
226
|
+
pause: () => score.pause(),
|
|
227
|
+
stop: () => score.stop(),
|
|
228
|
+
seekPosition: (position, when) => score.seekNominal(position, when),
|
|
229
|
+
setRate: (rate) => score.setRate?.(rate),
|
|
230
|
+
get position() {
|
|
231
|
+
return score.nominalSeconds;
|
|
232
|
+
},
|
|
233
|
+
dispose: () => score.dispose?.()
|
|
234
|
+
};
|
|
235
|
+
const mirror = new import_sync.MirrorClockMaster(commands, now, {
|
|
236
|
+
reconcileToleranceSeconds: options.driftToleranceSeconds ?? 0.03
|
|
237
|
+
});
|
|
238
|
+
const master = {
|
|
239
|
+
play: (when) => mirror.play(when),
|
|
240
|
+
pause: () => mirror.pause(),
|
|
241
|
+
stop: () => mirror.stop(),
|
|
242
|
+
seekPosition: (position, when) => mirror.seekPosition(position, when),
|
|
243
|
+
setRate: (rate) => mirror.setRate(rate),
|
|
244
|
+
get position() {
|
|
245
|
+
return score.nominalSeconds;
|
|
246
|
+
},
|
|
247
|
+
get clock() {
|
|
248
|
+
return score.clock ?? mirror.clock;
|
|
249
|
+
},
|
|
250
|
+
// Dead reckoning is only meaningful while the transport has no clock of
|
|
251
|
+
// its own; once it exposes one the group reads the truth directly and
|
|
252
|
+
// the group's own master-stop check covers the stall case.
|
|
253
|
+
reconcile: (at) => score.clock ? "ok" : mirror.reconcile(at),
|
|
254
|
+
dispose: () => mirror.dispose()
|
|
255
|
+
};
|
|
256
|
+
const follower = {
|
|
257
|
+
play: (when) => clip.play(when),
|
|
258
|
+
pause: () => clip.pause(),
|
|
259
|
+
stop: () => clip.stop(),
|
|
260
|
+
seek: (position) => clip.seek(position),
|
|
261
|
+
setRate: (rate) => clip.setRate?.(rate),
|
|
262
|
+
get position() {
|
|
263
|
+
return clip.seconds;
|
|
264
|
+
},
|
|
265
|
+
get running() {
|
|
266
|
+
return clip.playing;
|
|
267
|
+
},
|
|
268
|
+
get clock() {
|
|
269
|
+
return clip.clock;
|
|
270
|
+
},
|
|
271
|
+
dispose: () => clip.dispose?.()
|
|
272
|
+
};
|
|
273
|
+
__privateSet(this, _group, new import_sync.TransportGroup(master, now, {
|
|
274
|
+
leadInSeconds: options.leadInSeconds,
|
|
275
|
+
driftToleranceSeconds: options.driftToleranceSeconds,
|
|
276
|
+
driftCheckIntervalMs: options.driftCheckIntervalMs,
|
|
277
|
+
loop: options.loop,
|
|
278
|
+
tick: options.tick,
|
|
279
|
+
onOperationError: options.onOperationError
|
|
280
|
+
}));
|
|
281
|
+
__privateGet(this, _group).addFollower(follower, { offsetSeconds: clipOffset });
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* The shared transport clock (nominal score seconds): a read-through to the
|
|
285
|
+
* score transport's own clock when it has one, else the kernel mirror. The
|
|
286
|
+
* sync never mutates a transport-owned clock.
|
|
287
|
+
*/
|
|
288
|
+
get clock() {
|
|
289
|
+
return __privateGet(this, _group).clock;
|
|
290
|
+
}
|
|
291
|
+
/** Coherent state on the nominal master-seconds axis. */
|
|
292
|
+
get snapshot() {
|
|
293
|
+
return __privateGet(this, _group).snapshot;
|
|
294
|
+
}
|
|
295
|
+
/** Subscribe before receiving the current snapshot. Detaching the observer
|
|
296
|
+
* does not stop either player. Subsequent events describe command invalidation,
|
|
297
|
+
* committed/superseded settlement, errors and disposal. */
|
|
298
|
+
subscribe(listener) {
|
|
299
|
+
__privateMethod(this, _ScoreAudioSync_instances, assertActive_fn).call(this);
|
|
300
|
+
return __privateGet(this, _group).subscribe(listener);
|
|
301
|
+
}
|
|
302
|
+
/** Await a command's participant settlement. Seek positions and loop bounds
|
|
303
|
+
* are nominal master seconds; rate never changes that coordinate system.
|
|
304
|
+
* The shared 0.25–4 rate range also applies to this command surface. */
|
|
305
|
+
dispatch(command) {
|
|
306
|
+
__privateMethod(this, _ScoreAudioSync_instances, assertActive_fn).call(this);
|
|
307
|
+
if (command.type === "rate") assertSharedRate(command.rate);
|
|
308
|
+
return __privateGet(this, _group).dispatch(command);
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* Set (or clear) a loop region on the score-seconds axis, live. The wrap
|
|
312
|
+
* runs through {@link seek}, so it inherits the shared re-entry origin:
|
|
313
|
+
* both transports leave the boundary together on one audio-clock instant,
|
|
314
|
+
* with no score-only opening on each cycle. A worker-backed tick watcher
|
|
315
|
+
* detects the boundary, so the wrap INSTANT still trails the true boundary
|
|
316
|
+
* by watcher delivery, preparation and lead-in delays; browser throttling
|
|
317
|
+
* prevents a fixed upper bound. Landing the wrap on
|
|
318
|
+
* the boundary itself needs the scheduler to commit notes across it (or
|
|
319
|
+
* the clip to loop natively), which is a separate design.
|
|
320
|
+
*/
|
|
321
|
+
setLoop(loop) {
|
|
322
|
+
__privateMethod(this, _ScoreAudioSync_instances, assertActive_fn).call(this);
|
|
323
|
+
__privateGet(this, _group).setLoop(loop);
|
|
324
|
+
}
|
|
325
|
+
get loop() {
|
|
326
|
+
return __privateGet(this, _group).loop;
|
|
327
|
+
}
|
|
328
|
+
/** Current transport position in nominal score seconds. */
|
|
329
|
+
get seconds() {
|
|
330
|
+
return __privateGet(this, _score).nominalSeconds;
|
|
331
|
+
}
|
|
332
|
+
/**
|
|
333
|
+
* Start both transports on one shared audio-clock origin. The sync
|
|
334
|
+
* proposes `now + leadInSeconds` to the score master; one that supports
|
|
335
|
+
* scheduled starts arms there and the clip joins at that very instant, so
|
|
336
|
+
* with buffer-engine playback both make their first sound together. A
|
|
337
|
+
* master that ignores the proposal starts immediately and the clip joins
|
|
338
|
+
* a lead-in later, offset-matched to its anchor, exactly as before.
|
|
339
|
+
*/
|
|
340
|
+
async play() {
|
|
341
|
+
__privateMethod(this, _ScoreAudioSync_instances, assertActive_fn).call(this);
|
|
342
|
+
return __privateGet(this, _group).play();
|
|
343
|
+
}
|
|
344
|
+
pause() {
|
|
345
|
+
if (__privateGet(this, _disposed)) return;
|
|
346
|
+
__privateGet(this, _group).pause();
|
|
347
|
+
}
|
|
348
|
+
stop() {
|
|
349
|
+
if (__privateGet(this, _disposed)) return;
|
|
350
|
+
__privateGet(this, _group).stop();
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* Seek both transports to a score-seconds position. While playing, the
|
|
354
|
+
* sync proposes a shared re-entry origin exactly as {@link play} does and
|
|
355
|
+
* then re-joins the clip there, so both sides come back in together
|
|
356
|
+
* instead of the score resuming a lead-in ahead of the clip. Loop wraps
|
|
357
|
+
* run through this path and inherit the same shared origin.
|
|
358
|
+
*/
|
|
359
|
+
async seek(scoreSeconds) {
|
|
360
|
+
__privateMethod(this, _ScoreAudioSync_instances, assertActive_fn).call(this);
|
|
361
|
+
if (!Number.isFinite(scoreSeconds) || scoreSeconds < 0) {
|
|
362
|
+
throw new RangeError("scoreSeconds must be finite and >= 0.");
|
|
363
|
+
}
|
|
364
|
+
return __privateGet(this, _group).seek(scoreSeconds);
|
|
365
|
+
}
|
|
366
|
+
/**
|
|
367
|
+
* Set the shared playback rate on both transports. The score scheduler's
|
|
368
|
+
* retune is synchronous, so the clip re-joins immediately on the audio
|
|
369
|
+
* clock. The group owns the session command; each engine retains its own
|
|
370
|
+
* transport clock until shared-instance injection is implemented.
|
|
371
|
+
*/
|
|
372
|
+
setRate(rate) {
|
|
373
|
+
__privateMethod(this, _ScoreAudioSync_instances, assertActive_fn).call(this);
|
|
374
|
+
assertSharedRate(rate);
|
|
375
|
+
__privateGet(this, _group).setRate(rate);
|
|
376
|
+
}
|
|
377
|
+
dispose() {
|
|
378
|
+
if (__privateGet(this, _disposed)) return;
|
|
379
|
+
__privateSet(this, _disposed, true);
|
|
380
|
+
try {
|
|
381
|
+
__privateGet(this, _group).dispose();
|
|
382
|
+
} finally {
|
|
383
|
+
releaseOwnedContext(this);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* One drift check. Corrections re-join on the audio clock (the same
|
|
388
|
+
* scheduled-start dance as {@link play}) rather than command-level seeking,
|
|
389
|
+
* so a correction lands sample-accurately instead of chasing the score by
|
|
390
|
+
* one JS-tick each time.
|
|
391
|
+
*/
|
|
392
|
+
checkDrift() {
|
|
393
|
+
__privateMethod(this, _ScoreAudioSync_instances, assertActive_fn).call(this);
|
|
394
|
+
return __privateGet(this, _group).checkDrift();
|
|
395
|
+
}
|
|
396
|
+
};
|
|
397
|
+
_group = new WeakMap();
|
|
398
|
+
_score = new WeakMap();
|
|
399
|
+
_disposed = new WeakMap();
|
|
400
|
+
_ScoreAudioSync_instances = new WeakSet();
|
|
401
|
+
assertActive_fn = function() {
|
|
402
|
+
if (__privateGet(this, _disposed)) throw new Error("ScoreAudioSync has been disposed.");
|
|
403
|
+
};
|
|
404
|
+
function createSyncedPlayback(score, clip, options = {}) {
|
|
405
|
+
const clipOptions = options.clipOptions;
|
|
406
|
+
assertFactoryClipOptions("createSyncedPlayback", clip, clipOptions);
|
|
407
|
+
const clipOffsetSeconds = validatedClipOffsetSeconds(options.clipOffsetSeconds);
|
|
408
|
+
const scoreOptions = options.scoreOptions;
|
|
409
|
+
assertRenderedClipAlignment("createSyncedPlayback", score, clip, scoreOptions?.expandRepeats);
|
|
410
|
+
assertInitialScoreTempo(score, scoreOptions?.tempo);
|
|
411
|
+
const context = options.context ?? (0, import_audio_context.createWebAudioContext)("Web Audio is not available. Pass an existing AudioContext in options.context.");
|
|
412
|
+
let scorePlayer;
|
|
413
|
+
let clipPlayer;
|
|
414
|
+
try {
|
|
415
|
+
scorePlayer = new import_headless2.ScorePlayer(score, { ...scoreOptions, audioContext: context });
|
|
416
|
+
clipPlayer = new import_headless.AudioClipPlayer(clip, {
|
|
417
|
+
...clipOptions,
|
|
418
|
+
audioContext: context,
|
|
419
|
+
// Only the buffer engine can join sample-accurately.
|
|
420
|
+
engine: "buffer"
|
|
421
|
+
});
|
|
422
|
+
const sync = new ScoreAudioSync(scorePlayer, clipPlayer, context, {
|
|
423
|
+
...options,
|
|
424
|
+
clipOffsetSeconds
|
|
425
|
+
});
|
|
426
|
+
if (!options.context) ownContext(sync, context, options.onOperationError);
|
|
427
|
+
return { sync, scorePlayer, clipPlayer };
|
|
428
|
+
} catch (error) {
|
|
429
|
+
for (const player of [clipPlayer, scorePlayer]) {
|
|
430
|
+
try {
|
|
431
|
+
player?.dispose();
|
|
432
|
+
} catch {
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
if (!options.context) closeContext(context, options.onOperationError);
|
|
436
|
+
throw error;
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
async function renderScoreToClip(score, options) {
|
|
440
|
+
const baseTempo = score.timeMap.tempi[0]?.bpm ?? 120;
|
|
441
|
+
const tempo = options?.tempo;
|
|
442
|
+
if (tempo !== void 0 && (!Number.isFinite(tempo) || tempo <= 0)) {
|
|
443
|
+
throw new RangeError("renderScoreToClip tempo must be finite and > 0.");
|
|
444
|
+
}
|
|
445
|
+
const tail = options?.tailSeconds;
|
|
446
|
+
if (tail !== void 0 && (!Number.isFinite(tail) || tail < 0)) {
|
|
447
|
+
throw new RangeError("renderScoreToClip tailSeconds must be finite and >= 0.");
|
|
448
|
+
}
|
|
449
|
+
const buffer = await (0, import_play.renderScoreToBuffer)(score, options);
|
|
450
|
+
const channelData = [];
|
|
451
|
+
for (let channel = 0; channel < buffer.numberOfChannels; channel++) {
|
|
452
|
+
channelData.push(buffer.getChannelData(channel));
|
|
453
|
+
}
|
|
454
|
+
const clip = (0, import_audio2.createAudioClip)({ channelData, sampleRate: buffer.sampleRate });
|
|
455
|
+
recordRenderProvenance(clip, score, tempo === void 0 ? 1 : tempo / baseTempo, tail === void 0 || tail > 0);
|
|
456
|
+
return clip;
|
|
457
|
+
}
|
|
458
|
+
function assertInitialScoreTempo(score, tempo) {
|
|
459
|
+
if (tempo === void 0) return;
|
|
460
|
+
const baseTempo = score.timeMap.tempi[0]?.bpm ?? 120;
|
|
461
|
+
const rate = tempo / baseTempo;
|
|
462
|
+
if (!Number.isFinite(rate) || rate < MIN_SHARED_PLAYBACK_RATE || rate > MAX_SHARED_PLAYBACK_RATE) {
|
|
463
|
+
throw new RangeError(
|
|
464
|
+
`scoreOptions.tempo must set an initial shared rate between ${MIN_SHARED_PLAYBACK_RATE} and ${MAX_SHARED_PLAYBACK_RATE} times the score tempo.`
|
|
465
|
+
);
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
function assertSharedRate(rate) {
|
|
469
|
+
if (!Number.isFinite(rate) || rate < MIN_SHARED_PLAYBACK_RATE || rate > MAX_SHARED_PLAYBACK_RATE) {
|
|
470
|
+
throw new RangeError(`rate must be finite and between ${MIN_SHARED_PLAYBACK_RATE} and ${MAX_SHARED_PLAYBACK_RATE}.`);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
// src/audio-master.ts
|
|
475
|
+
var import_audio_context2 = require("@webmusic/kernel/audio-context");
|
|
476
|
+
var import_headless3 = require("@webmusic/audio/play/headless");
|
|
477
|
+
var import_headless4 = require("@webmusic/score/play/headless");
|
|
478
|
+
function offsetClockView(clock, offset) {
|
|
479
|
+
if (offset === 0) return clock;
|
|
480
|
+
return {
|
|
481
|
+
get state() {
|
|
482
|
+
const state = clock.state;
|
|
483
|
+
return { ...state, originPosition: state.originPosition + offset };
|
|
484
|
+
},
|
|
485
|
+
get rate() {
|
|
486
|
+
return clock.rate;
|
|
487
|
+
},
|
|
488
|
+
get paused() {
|
|
489
|
+
return clock.paused;
|
|
490
|
+
},
|
|
491
|
+
get holding() {
|
|
492
|
+
return clock.holding;
|
|
493
|
+
},
|
|
494
|
+
positionAt: (t) => clock.positionAt(t) + offset,
|
|
495
|
+
timeAt: (position) => clock.timeAt(position - offset)
|
|
496
|
+
};
|
|
497
|
+
}
|
|
498
|
+
function clipAsMaster(clip) {
|
|
499
|
+
return {
|
|
500
|
+
play: (when) => clip.play(when),
|
|
501
|
+
pause: () => clip.pause(),
|
|
502
|
+
stop: () => clip.stop(),
|
|
503
|
+
seekNominal: (seconds, when) => {
|
|
504
|
+
if (when === void 0 || !clip.playing) {
|
|
505
|
+
clip.seek(seconds);
|
|
506
|
+
return;
|
|
507
|
+
}
|
|
508
|
+
clip.pause();
|
|
509
|
+
clip.seek(seconds);
|
|
510
|
+
return clip.play(when);
|
|
511
|
+
},
|
|
512
|
+
setRate: (rate) => clip.setRate(rate),
|
|
513
|
+
get nominalSeconds() {
|
|
514
|
+
return clip.seconds;
|
|
515
|
+
},
|
|
516
|
+
get clock() {
|
|
517
|
+
return clip.clock;
|
|
518
|
+
},
|
|
519
|
+
dispose: () => clip.dispose()
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
function scoreAsFollower(score, options = {}) {
|
|
523
|
+
const offset = validatedClipOffsetSeconds(options.clipOffsetSeconds);
|
|
524
|
+
let requested = 0;
|
|
525
|
+
return {
|
|
526
|
+
play: (when) => {
|
|
527
|
+
if (when !== void 0 && requested < 0) {
|
|
528
|
+
return score.play(when + -requested / score.rate);
|
|
529
|
+
}
|
|
530
|
+
return score.play(when);
|
|
531
|
+
},
|
|
532
|
+
pause: () => score.pause(),
|
|
533
|
+
stop: () => {
|
|
534
|
+
requested = 0;
|
|
535
|
+
score.stop();
|
|
536
|
+
},
|
|
537
|
+
// The sync only ever seeks a follower it has just paused, and a paused
|
|
538
|
+
// seekNominal applies its re-anchor synchronously before resolving.
|
|
539
|
+
seek: (seconds) => {
|
|
540
|
+
requested = seconds - offset;
|
|
541
|
+
void score.seekNominal(requested);
|
|
542
|
+
},
|
|
543
|
+
setRate: (rate) => score.setRate(rate),
|
|
544
|
+
get seconds() {
|
|
545
|
+
return score.nominalSeconds + offset;
|
|
546
|
+
},
|
|
547
|
+
get playing() {
|
|
548
|
+
return score.isPlaying();
|
|
549
|
+
},
|
|
550
|
+
get clock() {
|
|
551
|
+
return offsetClockView(score.clock, offset);
|
|
552
|
+
},
|
|
553
|
+
dispose: () => score.dispose()
|
|
554
|
+
};
|
|
555
|
+
}
|
|
556
|
+
function createAudioMasteredPlayback(score, clip, options = {}) {
|
|
557
|
+
const clipOptions = options.clipOptions;
|
|
558
|
+
assertFactoryClipOptions("createAudioMasteredPlayback", clip, clipOptions);
|
|
559
|
+
const clipOffsetSeconds = validatedClipOffsetSeconds(options.clipOffsetSeconds);
|
|
560
|
+
const scoreOptions = options.scoreOptions;
|
|
561
|
+
assertRenderedClipAlignment("createAudioMasteredPlayback", score, clip, scoreOptions?.expandRepeats);
|
|
562
|
+
if (scoreOptions?.tempo !== void 0) {
|
|
563
|
+
throw new RangeError(
|
|
564
|
+
"createAudioMasteredPlayback does not accept scoreOptions.tempo: the audio master owns the shared rate. Change both players with sync.setRate()."
|
|
565
|
+
);
|
|
566
|
+
}
|
|
567
|
+
const context = options.context ?? (0, import_audio_context2.createWebAudioContext)("Web Audio is not available. Pass an existing AudioContext in options.context.");
|
|
568
|
+
let scorePlayer;
|
|
569
|
+
let clipPlayer;
|
|
570
|
+
try {
|
|
571
|
+
scorePlayer = new import_headless4.ScorePlayer(score, { ...scoreOptions, audioContext: context });
|
|
572
|
+
clipPlayer = new import_headless3.AudioClipPlayer(clip, {
|
|
573
|
+
...clipOptions,
|
|
574
|
+
audioContext: context,
|
|
575
|
+
engine: "buffer"
|
|
576
|
+
});
|
|
577
|
+
const sync = new ScoreAudioSync(
|
|
578
|
+
clipAsMaster(clipPlayer),
|
|
579
|
+
scoreAsFollower(scorePlayer, { clipOffsetSeconds }),
|
|
580
|
+
context,
|
|
581
|
+
// The follower adapter already translates the offset onto the clip axis.
|
|
582
|
+
{ ...options, clipOffsetSeconds: 0 }
|
|
583
|
+
);
|
|
584
|
+
if (!options.context) ownContext(sync, context, options.onOperationError);
|
|
585
|
+
return { sync, scorePlayer, clipPlayer };
|
|
586
|
+
} catch (error) {
|
|
587
|
+
for (const player of [clipPlayer, scorePlayer]) {
|
|
588
|
+
try {
|
|
589
|
+
player?.dispose();
|
|
590
|
+
} catch {
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
if (!options.context) closeContext(context, options.onOperationError);
|
|
594
|
+
throw error;
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
// src/transcription.ts
|
|
599
|
+
var import_score2 = require("@webmusic/score");
|
|
600
|
+
var TICKS_PER_QUARTER = 480;
|
|
601
|
+
var DEFAULT_MAX_TRANSCRIPTION_NOTES = 1e5;
|
|
602
|
+
var DEFAULT_MAX_TRANSCRIPTION_MEASURES = 4096;
|
|
603
|
+
function scoreFromTranscription(notes, options = {}) {
|
|
604
|
+
const bpm = options.bpm ?? 120;
|
|
605
|
+
if (!(Number.isFinite(bpm) && bpm > 0)) {
|
|
606
|
+
throw new RangeError(`scoreFromTranscription: bpm must be finite and > 0, got ${bpm}.`);
|
|
607
|
+
}
|
|
608
|
+
const grid = options.quantizeGrid ?? 4;
|
|
609
|
+
if (!(Number.isSafeInteger(grid) && grid >= 0)) {
|
|
610
|
+
throw new RangeError(`scoreFromTranscription: quantizeGrid must be a non-negative safe integer, got ${grid}.`);
|
|
611
|
+
}
|
|
612
|
+
const timeSignature = options.timeSignature ?? { numerator: 4, denominator: 4 };
|
|
613
|
+
if (!Number.isSafeInteger(timeSignature.numerator) || timeSignature.numerator < 1 || !Number.isSafeInteger(timeSignature.denominator) || timeSignature.denominator < 1) {
|
|
614
|
+
throw new RangeError("scoreFromTranscription: timeSignature values must be positive safe integers.");
|
|
615
|
+
}
|
|
616
|
+
const maxNotes = resolvePositiveLimit(
|
|
617
|
+
"maxNotes",
|
|
618
|
+
options.maxNotes,
|
|
619
|
+
DEFAULT_MAX_TRANSCRIPTION_NOTES
|
|
620
|
+
);
|
|
621
|
+
const maxMeasures = resolvePositiveLimit(
|
|
622
|
+
"maxMeasures",
|
|
623
|
+
options.maxMeasures,
|
|
624
|
+
DEFAULT_MAX_TRANSCRIPTION_MEASURES
|
|
625
|
+
);
|
|
626
|
+
if (notes.length > maxNotes) {
|
|
627
|
+
throw new RangeError(
|
|
628
|
+
`Transcription resource limit exceeded: ${notes.length.toLocaleString()} note events (maxNotes is ${maxNotes.toLocaleString()}).`
|
|
629
|
+
);
|
|
630
|
+
}
|
|
631
|
+
const denominator = grid > 0 ? grid : TICKS_PER_QUARTER;
|
|
632
|
+
const secondsToQuarterUnits = (seconds, label) => {
|
|
633
|
+
const units = Math.round(seconds * bpm * denominator / 60);
|
|
634
|
+
if (!Number.isSafeInteger(units)) {
|
|
635
|
+
throw new RangeError(`scoreFromTranscription: ${label} is too large to represent safely.`);
|
|
636
|
+
}
|
|
637
|
+
return units;
|
|
638
|
+
};
|
|
639
|
+
const builder = new import_score2.ScoreBuilder();
|
|
640
|
+
builder.setMetadata({ title: options.title ?? "Transcription" }).addTempo({ atQuarters: import_score2.Rational.ZERO, bpm }).addMeter({ atQuarters: import_score2.Rational.ZERO, measureNumber: 1, timeSignature });
|
|
641
|
+
const partId = (0, import_score2.PartId)("transcription");
|
|
642
|
+
const voice = (0, import_score2.VoiceId)("v1");
|
|
643
|
+
builder.addPart({ id: partId, name: options.partName ?? "Transcribed", staves: 1 });
|
|
644
|
+
let maxEndUnits = 0;
|
|
645
|
+
for (const [index, note] of notes.entries()) {
|
|
646
|
+
if (!Number.isFinite(note.midi)) {
|
|
647
|
+
throw new RangeError(`scoreFromTranscription: note ${index} pitch must be finite.`);
|
|
648
|
+
}
|
|
649
|
+
const midi = Math.round(note.midi);
|
|
650
|
+
if (midi < 0 || midi > 127) continue;
|
|
651
|
+
if (!Number.isFinite(note.startSeconds) || note.startSeconds < 0 || !Number.isFinite(note.endSeconds) || note.endSeconds < note.startSeconds) {
|
|
652
|
+
throw new RangeError(
|
|
653
|
+
`scoreFromTranscription: note ${index} must have finite, non-negative, ordered start/end seconds.`
|
|
654
|
+
);
|
|
655
|
+
}
|
|
656
|
+
if (!Number.isFinite(note.velocity)) {
|
|
657
|
+
throw new RangeError(`scoreFromTranscription: note ${index} velocity must be finite.`);
|
|
658
|
+
}
|
|
659
|
+
const onsetUnits = secondsToQuarterUnits(note.startSeconds, `note ${index} startSeconds`);
|
|
660
|
+
const endUnits = Math.max(
|
|
661
|
+
onsetUnits + 1,
|
|
662
|
+
secondsToQuarterUnits(note.endSeconds, `note ${index} endSeconds`)
|
|
663
|
+
);
|
|
664
|
+
if (!Number.isSafeInteger(endUnits)) {
|
|
665
|
+
throw new RangeError(`scoreFromTranscription: note ${index} duration is too large to represent safely.`);
|
|
666
|
+
}
|
|
667
|
+
maxEndUnits = Math.max(maxEndUnits, endUnits);
|
|
668
|
+
builder.addNote(partId, {
|
|
669
|
+
id: builder.newNoteId(),
|
|
670
|
+
pitch: import_score2.Pitch.fromMidi(midi),
|
|
671
|
+
onsetQuarters: new import_score2.Rational(onsetUnits, denominator),
|
|
672
|
+
duration: new import_score2.Duration({ base: new import_score2.Rational(endUnits - onsetUnits, denominator) }),
|
|
673
|
+
voice,
|
|
674
|
+
performed: {
|
|
675
|
+
onsetSec: note.startSeconds,
|
|
676
|
+
durationSec: Math.max(0, note.endSeconds - note.startSeconds),
|
|
677
|
+
velocity: Math.min(127, Math.max(1, Math.round(note.velocity * 127)))
|
|
678
|
+
}
|
|
679
|
+
});
|
|
680
|
+
}
|
|
681
|
+
const materialUnits = BigInt(maxEndUnits) * BigInt(timeSignature.denominator);
|
|
682
|
+
const measureUnits = BigInt(denominator) * BigInt(timeSignature.numerator) * 4n;
|
|
683
|
+
const exactMeasureCount = materialUnits === 0n ? 1n : (materialUnits + measureUnits - 1n) / measureUnits;
|
|
684
|
+
if (exactMeasureCount > BigInt(maxMeasures)) {
|
|
685
|
+
throw new RangeError(
|
|
686
|
+
`Transcription resource limit exceeded: score would create ${exactMeasureCount.toLocaleString()} measures (maxMeasures is ${maxMeasures.toLocaleString()}).`
|
|
687
|
+
);
|
|
688
|
+
}
|
|
689
|
+
const measureCount = Number(exactMeasureCount);
|
|
690
|
+
const quartersPerMeasure = quartersPerMeasureFrom(timeSignature);
|
|
691
|
+
for (let index = 0; index < measureCount; index++) {
|
|
692
|
+
builder.addMeasure({
|
|
693
|
+
id: (0, import_score2.MeasureId)(`m${index + 1}`),
|
|
694
|
+
number: index + 1,
|
|
695
|
+
onsetQuarters: quartersPerMeasure.mul(new import_score2.Rational(index, 1)),
|
|
696
|
+
durationQuarters: quartersPerMeasure,
|
|
697
|
+
timeSignature
|
|
698
|
+
});
|
|
699
|
+
}
|
|
700
|
+
return builder.build();
|
|
701
|
+
}
|
|
702
|
+
function resolvePositiveLimit(name, value, fallback) {
|
|
703
|
+
if (value === void 0) return fallback;
|
|
704
|
+
if (!Number.isSafeInteger(value) || value < 1) {
|
|
705
|
+
throw new RangeError(`scoreFromTranscription: ${name} must be a positive safe integer.`);
|
|
706
|
+
}
|
|
707
|
+
return value;
|
|
708
|
+
}
|
|
709
|
+
function quartersPerMeasureFrom(timeSignature) {
|
|
710
|
+
let numerator = BigInt(timeSignature.numerator) * 4n;
|
|
711
|
+
let denominator = BigInt(timeSignature.denominator);
|
|
712
|
+
const divisor = greatestCommonDivisor(numerator, denominator);
|
|
713
|
+
numerator /= divisor;
|
|
714
|
+
denominator /= divisor;
|
|
715
|
+
const maxSafe = BigInt(Number.MAX_SAFE_INTEGER);
|
|
716
|
+
if (numerator > maxSafe || denominator > maxSafe) {
|
|
717
|
+
throw new RangeError(
|
|
718
|
+
"scoreFromTranscription: timeSignature measure duration is too large to represent safely."
|
|
719
|
+
);
|
|
720
|
+
}
|
|
721
|
+
return new import_score2.Rational(Number(numerator), Number(denominator));
|
|
722
|
+
}
|
|
723
|
+
function greatestCommonDivisor(left, right) {
|
|
724
|
+
while (right !== 0n) {
|
|
725
|
+
const remainder = left % right;
|
|
726
|
+
left = right;
|
|
727
|
+
right = remainder;
|
|
728
|
+
}
|
|
729
|
+
return left;
|
|
730
|
+
}
|
|
731
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
732
|
+
0 && (module.exports = {
|
|
733
|
+
DEFAULT_MAX_MAPPED_BEATS,
|
|
734
|
+
DEFAULT_MAX_TRANSCRIPTION_MEASURES,
|
|
735
|
+
DEFAULT_MAX_TRANSCRIPTION_NOTES,
|
|
736
|
+
ScoreAudioSync,
|
|
737
|
+
beatGridFromTimeMap,
|
|
738
|
+
clipAsMaster,
|
|
739
|
+
createAudioMasteredPlayback,
|
|
740
|
+
createSyncedPlayback,
|
|
741
|
+
renderScoreToClip,
|
|
742
|
+
scoreAsFollower,
|
|
743
|
+
scoreFromTranscription,
|
|
744
|
+
timeMapFromBeatGrid
|
|
745
|
+
});
|
|
746
|
+
//# sourceMappingURL=index.cjs.map
|