@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/LICENSE +202 -21
- package/NOTICE +2 -0
- package/README.md +66 -70
- package/dist/THIRD_PARTY_NOTICES.txt +1605 -0
- package/dist/build-receipt.json +3 -3
- package/dist/chunk-XQXQSBVS.js +408 -0
- package/dist/chunk-XQXQSBVS.js.map +1 -0
- package/dist/component/global.cjs +19 -0
- package/dist/component/global.cjs.map +1 -0
- package/dist/component/global.d.ts +9 -0
- package/dist/component/global.js +1 -0
- package/dist/component/global.js.map +1 -0
- package/dist/component.cjs +3091 -0
- package/dist/component.cjs.map +1 -0
- package/dist/component.d.cts +860 -0
- package/dist/component.d.ts +860 -0
- package/dist/component.global.js +3541 -0
- package/dist/component.global.js.map +1 -0
- package/dist/component.js +2672 -0
- package/dist/component.js.map +1 -0
- package/dist/index.cjs +447 -486
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +65 -297
- package/dist/index.d.ts +65 -297
- package/dist/index.js +66 -488
- package/dist/index.js.map +1 -1
- package/package.json +32 -9
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/mapping.ts","../src/sync.ts","../src/owned-context.ts","../src/factory-clip-options.ts","../src/render-provenance.ts","../src/audio-master.ts","../src/transcription.ts"],"sourcesContent":["// ============================================================================\n// Timeline conversions between the two families' musical time models.\n// TimeMap → BeatGrid is lossless sampling (evaluate the exact map at each\n// beat); BeatGrid → TimeMap is approximate (each inter-beat interval becomes\n// one tempo segment). Both project onto the same seconds ruler, which is what\n// makes score↔audio alignment composable.\n// ============================================================================\n\nimport {Rational, TimeMap, type TempoEntry} from '@webmusic/score';\nimport {BeatGrid} from '@webmusic/audio';\n\nexport interface BeatGridFromTimeMapOptions {\n /** How many quarters of the score timeline to sample. */\n durationQuarters: number;\n /** Beat subdivisions per quarter note (default 1: beat = quarter). */\n beatsPerQuarter?: number;\n /** Maximum number of beat samples to allocate. Default 1,000,000. */\n maxBeats?: number;\n}\n\nexport const DEFAULT_MAX_MAPPED_BEATS = 1_000_000;\n\n/**\n * Sample a {@link TimeMap} into a {@link BeatGrid}: one beat per\n * `1/beatsPerQuarter` quarter from 0 through `durationQuarters`. Lossless up\n * to the sampling density — tempo changes between sampled beats interpolate\n * linearly on the grid.\n */\nexport function beatGridFromTimeMap(map: TimeMap, options: BeatGridFromTimeMapOptions): BeatGrid {\n const {durationQuarters, beatsPerQuarter = 1, maxBeats = DEFAULT_MAX_MAPPED_BEATS} = options;\n if (!Number.isFinite(durationQuarters) || durationQuarters <= 0) {\n throw new RangeError('durationQuarters must be finite and > 0');\n }\n if (!Number.isSafeInteger(beatsPerQuarter) || beatsPerQuarter < 1) {\n throw new RangeError('beatsPerQuarter must be a positive safe integer');\n }\n if (!Number.isSafeInteger(maxBeats) || maxBeats < 2) {\n throw new RangeError('maxBeats must be a safe integer >= 2');\n }\n const scaledDuration = durationQuarters * beatsPerQuarter;\n const nearestInteger = Math.round(scaledDuration);\n const ulpTolerance = Number.EPSILON * Math.max(1, Math.abs(scaledDuration)) * 4;\n const normalizedDuration =\n Math.abs(scaledDuration - nearestInteger) <= ulpTolerance\n ? nearestInteger\n : scaledDuration;\n const total = Math.ceil(normalizedDuration);\n if (!Number.isSafeInteger(total) || total >= maxBeats) {\n throw new RangeError(\n `Beat-grid mapping would allocate more than maxBeats (${maxBeats.toLocaleString()}) samples.`,\n );\n }\n const beats: number[] = [];\n for (let index = 0; index <= total; index++) {\n beats.push(map.quartersToSeconds(new Rational(index, beatsPerQuarter)));\n }\n // The sampled positions come from quartersToSeconds, which integrates tempo\n // as 60 / (bpm * unit) seconds per quarter — so the effective quarters per\n // minute is `bpm * unit`, not the raw bpm. Folding `unit` in here keeps the\n // grid's nominal tempo consistent with its own beat spacing; without it a\n // metronome mark like \"half note = 60\" produced 0.5 s beats under a grid\n // claiming 60 bpm, and BeatGrid's extrapolation before beat 0 disagreed with\n // every sampled beat after it.\n const tempo = map.tempoAt(Rational.ZERO);\n const bpm = tempo.bpm * (tempo.unit ?? 1) * beatsPerQuarter;\n return new BeatGrid({bpm, beats});\n}\n\n/**\n * Approximate a {@link TimeMap} from a {@link BeatGrid}: beat index becomes\n * the quarter axis and every inter-beat interval one tempo segment. The\n * grid's absolute offset is NOT representable (a TimeMap always maps quarter\n * 0 to second 0) — align `grid.beats[0]` on the consumer side. Zero-length\n * intervals are rejected: they would demand an infinite tempo.\n */\nexport function timeMapFromBeatGrid(grid: BeatGrid): TimeMap {\n const beats = grid.beats;\n const tempi: TempoEntry[] = [];\n if (beats.length < 2) {\n tempi.push({atQuarters: Rational.ZERO, bpm: grid.bpm});\n } else {\n for (let index = 0; index < beats.length - 1; index++) {\n const interval = beats[index + 1] - beats[index];\n if (!(interval > 0)) {\n throw new RangeError(`BeatGrid interval at beat ${index} is not positive (${interval}).`);\n }\n tempi.push({atQuarters: new Rational(index, 1), bpm: 60 / interval});\n }\n }\n return new TimeMap(tempi, [\n {atQuarters: Rational.ZERO, measureNumber: 1, timeSignature: {numerator: 4, denominator: 4}},\n ]);\n}\n","// ============================================================================\n// Synchronized score + audio playback on one AudioContext clock.\n//\n// Strategy: the SCORE is the master transport. `play()` proposes a shared\n// audio-clock origin a lead-in ahead: a master supporting scheduled starts\n// (ScorePlayer) arms itself there, and the clip joins at the very same\n// instant via the buffer engine's sample-accurate `play(when)` — both\n// transports make their first sound together. A master that ignores the\n// proposal starts immediately and the clip joins a lead-in later, exactly\n// as before. When the transport exposes its kernel TransportClock, the sync\n// anchors by READING the clock — the exact affine map the scheduler plays\n// by, no sampling skew; clockless transports fall back to sampled anchoring\n// via a kernel MirrorClockMaster. A drift monitor re-joins the clip if the\n// transports ever diverge in position OR in rate (e.g. after rate clamping);\n// every join matches the follower to the master's current slope, so a\n// correction converges instead of being re-issued on every check.\n//\n// The choreography itself — command serialization, generation guards,\n// scheduled joins, drift monitoring, master-stop reconciliation — lives in\n// the kernel's family-neutral TransportGroup (@webmusic/kernel/sync); this\n// module is the score↔audio DOMAIN ASSEMBLY: it adapts ScorePlayer-shaped\n// masters and AudioClipPlayer-shaped followers onto the kernel roles and\n// keeps the established ScoreAudioSync surface.\n//\n// Both players MUST share one AudioContext — use createSyncedPlayback() to\n// construct everything correctly, or pass the same `audioContext` option to\n// both constructors yourself.\n// ============================================================================\n\nimport type {TransportClockReader} from '@webmusic/kernel/transport';\nimport type {TickSourceOptions} from '@webmusic/kernel/tick';\nimport {\n MirrorClockMaster,\n TransportGroup,\n type ClocklessMasterTransport,\n type TransportCommand,\n type TransportCommit,\n type TransportEvent,\n type TransportSnapshot,\n type SyncFollowerTransport as KernelFollowerRole,\n type SyncMasterTransport as KernelMasterRole,\n} from '@webmusic/kernel/sync';\nimport {createWebAudioContext} from '@webmusic/kernel/audio-context';\nimport {createAudioClip, type AudioClip} from '@webmusic/audio';\nimport {AudioClipPlayer} from '@webmusic/audio/play/headless';\nimport type {Score} from '@webmusic/score';\nimport {ScorePlayer} from '@webmusic/score/play/headless';\nimport {renderScoreToBuffer, type RenderOptions} from '@webmusic/score/play';\nimport {closeContext, ownContext, releaseOwnedContext} from './owned-context';\nimport {\n assertFactoryClipOptions,\n validatedClipOffsetSeconds,\n type FactoryClipOptions,\n} from './factory-clip-options';\nimport {assertRenderedClipAlignment, recordRenderProvenance} from './render-provenance';\n\n/** Read-only clock view a transport may expose (kernel TransportClockReader). */\nexport type SyncTransportClockView = TransportClockReader;\n\n/**\n * Minimal structural surface the sync needs from the score-side transport.\n * Everything is on the NOMINAL score-seconds axis (the rendered-clip\n * timeline) — v2 dropped the rate-scaled members entirely.\n *\n * When `clock` is present (ScorePlayer exposes its kernel transport clock),\n * the sync anchors by READING the clock — no sampling, no skew, and an armed\n * scheduled start is visible through `holding`. Transports without a clock\n * (TonePlayer, third parties) fall back to sampled anchoring; the sync then\n * runs them behind a kernel MirrorClockMaster exactly as v1's inline mirror\n * did.\n */\nexport interface SyncScoreTransport {\n /**\n * Start playback. The sync passes a proposed start time (absolute\n * AudioContext seconds, a lead-in ahead) — a master supporting scheduled\n * starts (ScorePlayer) arms its clock there so the clip can join at the\n * exact same instant. Masters without the capability simply take no\n * parameter and start immediately (a narrower signature satisfies this\n * member structurally); the sync detects the difference by observing\n * `clock.holding`, never through a declared flag.\n */\n play(when?: number): Promise<void> | void;\n pause(): void;\n stop(): void;\n /**\n * Seek to a NOMINAL score-seconds position. A returned promise settles\n * once the seek has been applied and any mid-playback restart attempted;\n * the sync awaits it before re-anchoring the clip, which is what makes\n * mid-playback seeks land sample-accurately. The promise MAY resolve with\n * the transport left paused when the restart failed (ScorePlayer swallows\n * restart errors) — the sync treats that as a failed resume: it pauses the\n * clip, settles into the paused state and reports 'resume after seek'\n * through {@link ScoreAudioSyncOptions.onOperationError}.\n *\n * While playing, the sync passes a proposed re-entry time the same way\n * {@link play} does, so a transport supporting scheduled re-anchoring\n * brings both sides back in together. Transports that ignore it resume\n * immediately and the clip re-joins a lead-in later, as before.\n */\n seekNominal(nominalSeconds: number, when?: number): void | Promise<void>;\n setRate?(rate: number): void;\n /** Nominal score-timeline position. */\n readonly nominalSeconds: number;\n /** Read-only transport clock (nominal axis), when the transport has one. */\n readonly clock?: SyncTransportClockView;\n dispose?(): void;\n}\n\n/**\n * Role-neutral names for the two participants. The sync is defined by ROLE,\n * not by family: the first constructor argument drives the transport and the\n * second follows it. The score-mastered pairing these interfaces were named\n * for is the default (see {@link createSyncedPlayback}), and the reverse —\n * a recording driving the score — is assembled by the adapters in\n * `audio-master.ts`. Prefer these names in role-generic code. They are the\n * BRIDGE's shapes; the kernel's own role contracts are adapted onto them in\n * the constructor.\n */\nexport type SyncMasterTransport = SyncScoreTransport;\n/** @see SyncMasterTransport */\nexport type SyncFollowerTransport = SyncClipTransport;\n\n/** Minimal structural surface the sync needs from the clip-side transport. */\nexport interface SyncClipTransport {\n play(when?: number): Promise<void> | void;\n pause(): void;\n stop(): void;\n seek(seconds: number): void;\n setRate?(rate: number): void;\n readonly seconds: number;\n readonly playing?: boolean;\n /**\n * Read-only transport clock on the clip's own seconds axis, when the\n * transport has one (AudioClipPlayer exposes the buffer engine's). When\n * present, the drift monitor reads the clip position and running state\n * from the clock instead of sampling `seconds`/`playing` — the same\n * skew-free read-through the score side gets. (AudioClipPlayer's clock is\n * unwrapped under clip-side loops, but the sync never sets one: looping\n * is driven through master seeks, so the two axes agree here.)\n */\n readonly clock?: SyncTransportClockView;\n dispose?(): void;\n}\n\nexport interface ScoreAudioSyncOptions {\n /** Scheduling headroom before the clip joins, in seconds. Default 0.06. */\n leadInSeconds?: number;\n /** Clip seconds corresponding to score-seconds zero. Default 0. */\n clipOffsetSeconds?: number;\n /** Reseek the clip when |clip − expected| exceeds this. Default 0.03 s. */\n driftToleranceSeconds?: number;\n /** Drift check cadence. Default 250 ms. 0 disables drift checks; natural-stop and loop watching remain active. */\n driftCheckIntervalMs?: number;\n /** Loop region in score seconds; also settable at runtime via {@link ScoreAudioSync.setLoop}. */\n loop?: SyncLoopRegion | null;\n /** Injectable tick source options (tests; custom hosting). */\n tick?: TickSourceOptions;\n /**\n * Observer for failures of the sync's own fire-and-forget operations\n * (drift and rate re-joins, loop wraps, pause/stop reconciliation). Those\n * run behind the command queue with no caller promise to reject, and on\n * failure they settle the sync into a paused state — without an observer\n * that settlement is silent. Observer exceptions are swallowed.\n */\n onOperationError?: (operation: string, error: unknown) => void;\n}\n\n/** A loop region on the nominal score-seconds axis. */\nexport interface SyncLoopRegion {\n startSeconds: number;\n endSeconds: number;\n}\n\nconst MIN_SHARED_PLAYBACK_RATE = 0.25;\nconst MAX_SHARED_PLAYBACK_RATE = 4;\n\n/**\n * Drives a score player and a clip player as one transport. Positions are in\n * NOMINAL score seconds (the rendered-clip timeline); the clip is expected to\n * run `clipOffsetSeconds` ahead of the score's zero (use 0 for a clip\n * rendered from the same score).\n */\nexport class ScoreAudioSync {\n readonly #group: TransportGroup;\n readonly #score: SyncScoreTransport;\n #disposed = false;\n\n constructor(\n score: SyncScoreTransport,\n clip: SyncClipTransport,\n context: BaseAudioContext,\n options: ScoreAudioSyncOptions = {},\n ) {\n this.#score = score;\n const clipOffset = validatedClipOffsetSeconds(options.clipOffsetSeconds);\n const now = () => context.currentTime;\n const commands: ClocklessMasterTransport = {\n play: (when?: number) => score.play(when),\n pause: () => score.pause(),\n stop: () => score.stop(),\n seekPosition: (position: number, when?: number) => score.seekNominal(position, when),\n setRate: (rate: number) => score.setRate?.(rate),\n get position() {\n return score.nominalSeconds;\n },\n dispose: () => score.dispose?.(),\n };\n // A master's clock can APPEAR after construction: AudioClipPlayer only\n // builds its buffer-engine clock on first play, and `clipAsMaster` reads\n // it through live. Snapshotting the clock here would pin such a master to\n // the sampled mirror for its whole life and silently give up the\n // sample-accurate clock it grows — so every read goes back to the\n // transport, and the mirror is kept warm underneath purely as the\n // fallback for a master that never grows one (TonePlayer, third parties).\n const mirror = new MirrorClockMaster(commands, now, {\n reconcileToleranceSeconds: options.driftToleranceSeconds ?? 0.03,\n });\n const master: KernelMasterRole = {\n play: (when?: number) => mirror.play(when),\n pause: () => mirror.pause(),\n stop: () => mirror.stop(),\n seekPosition: (position: number, when?: number) => mirror.seekPosition(position, when),\n setRate: (rate: number) => mirror.setRate(rate),\n get position() {\n return score.nominalSeconds;\n },\n get clock() {\n return score.clock ?? mirror.clock;\n },\n // Dead reckoning is only meaningful while the transport has no clock of\n // its own; once it exposes one the group reads the truth directly and\n // the group's own master-stop check covers the stall case.\n reconcile: (at: number) => (score.clock ? 'ok' : mirror.reconcile(at)),\n dispose: () => mirror.dispose(),\n };\n const follower: KernelFollowerRole = {\n play: (when?: number) => clip.play(when),\n pause: () => clip.pause(),\n stop: () => clip.stop(),\n seek: (position: number) => clip.seek(position),\n setRate: (rate: number) => clip.setRate?.(rate),\n get position() {\n return clip.seconds;\n },\n get running() {\n return clip.playing;\n },\n get clock() {\n return clip.clock;\n },\n dispose: () => clip.dispose?.(),\n };\n this.#group = new TransportGroup(master, now, {\n leadInSeconds: options.leadInSeconds,\n driftToleranceSeconds: options.driftToleranceSeconds,\n driftCheckIntervalMs: options.driftCheckIntervalMs,\n loop: options.loop,\n tick: options.tick,\n onOperationError: options.onOperationError,\n });\n this.#group.addFollower(follower, {offsetSeconds: clipOffset});\n }\n\n /**\n * The shared transport clock (nominal score seconds): a read-through to the\n * score transport's own clock when it has one, else the kernel mirror. The\n * sync never mutates a transport-owned clock.\n */\n get clock(): SyncTransportClockView {\n return this.#group.clock;\n }\n\n /** Coherent state on the nominal master-seconds axis. */\n get snapshot(): TransportSnapshot {\n return this.#group.snapshot;\n }\n\n /** Subscribe before receiving the current snapshot. Detaching the observer\n * does not stop either player. Subsequent events describe command invalidation,\n * committed/superseded settlement, errors and disposal. */\n subscribe(listener: (event: TransportEvent) => void): () => void {\n this.#assertActive();\n return this.#group.subscribe(listener);\n }\n\n /** Await a command's participant settlement. Seek positions and loop bounds\n * are nominal master seconds; rate never changes that coordinate system.\n * The shared 0.25–4 rate range also applies to this command surface. */\n dispatch(command: TransportCommand): Promise<TransportCommit> {\n this.#assertActive();\n if (command.type === 'rate') assertSharedRate(command.rate);\n return this.#group.dispatch(command);\n }\n\n /**\n * Set (or clear) a loop region on the score-seconds axis, live. The wrap\n * runs through {@link seek}, so it inherits the shared re-entry origin:\n * both transports leave the boundary together on one audio-clock instant,\n * with no score-only opening on each cycle. A worker-backed tick watcher\n * detects the boundary, so the wrap INSTANT still trails the true boundary\n * by watcher delivery, preparation and lead-in delays; browser throttling\n * prevents a fixed upper bound. Landing the wrap on\n * the boundary itself needs the scheduler to commit notes across it (or\n * the clip to loop natively), which is a separate design.\n */\n setLoop(loop: SyncLoopRegion | null): void {\n this.#assertActive();\n this.#group.setLoop(loop);\n }\n\n get loop(): SyncLoopRegion | null {\n return this.#group.loop;\n }\n\n /** Current transport position in nominal score seconds. */\n get seconds(): number {\n return this.#score.nominalSeconds;\n }\n\n /**\n * Start both transports on one shared audio-clock origin. The sync\n * proposes `now + leadInSeconds` to the score master; one that supports\n * scheduled starts arms there and the clip joins at that very instant, so\n * with buffer-engine playback both make their first sound together. A\n * master that ignores the proposal starts immediately and the clip joins\n * a lead-in later, offset-matched to its anchor, exactly as before.\n */\n async play(): Promise<void> {\n this.#assertActive();\n return this.#group.play();\n }\n\n pause(): void {\n if (this.#disposed) return;\n this.#group.pause();\n }\n\n stop(): void {\n if (this.#disposed) return;\n this.#group.stop();\n }\n\n /**\n * Seek both transports to a score-seconds position. While playing, the\n * sync proposes a shared re-entry origin exactly as {@link play} does and\n * then re-joins the clip there, so both sides come back in together\n * instead of the score resuming a lead-in ahead of the clip. Loop wraps\n * run through this path and inherit the same shared origin.\n */\n async seek(scoreSeconds: number): Promise<void> {\n this.#assertActive();\n if (!Number.isFinite(scoreSeconds) || scoreSeconds < 0) {\n throw new RangeError('scoreSeconds must be finite and >= 0.');\n }\n return this.#group.seek(scoreSeconds);\n }\n\n /**\n * Set the shared playback rate on both transports. The score scheduler's\n * retune is synchronous, so the clip re-joins immediately on the audio\n * clock. The group owns the session command; each engine retains its own\n * transport clock until shared-instance injection is implemented.\n */\n setRate(rate: number): void {\n this.#assertActive();\n assertSharedRate(rate);\n this.#group.setRate(rate);\n }\n\n dispose(): void {\n if (this.#disposed) return;\n this.#disposed = true;\n try {\n this.#group.dispose();\n } finally {\n releaseOwnedContext(this);\n }\n }\n\n /**\n * One drift check. Corrections re-join on the audio clock (the same\n * scheduled-start dance as {@link play}) rather than command-level seeking,\n * so a correction lands sample-accurately instead of chasing the score by\n * one JS-tick each time.\n */\n checkDrift(): number {\n this.#assertActive();\n return this.#group.checkDrift();\n }\n\n #assertActive(): void {\n if (this.#disposed) throw new Error('ScoreAudioSync has been disposed.');\n }\n}\n\nexport interface CreateSyncedPlaybackOptions extends ScoreAudioSyncOptions {\n /** Shared AudioContext. If omitted, the factory creates one and sync.dispose() closes it. */\n context?: AudioContext;\n /** ScorePlayer options. An initial tempo must imply a shared rate within 0.25–4×. */\n scoreOptions?: ConstructorParameters<typeof ScorePlayer>[1];\n /**\n * Options forwarded to the AudioClipPlayer constructor. The engine is not\n * selectable here: only the buffer engine can join sample-accurately, so\n * the sync always builds a buffer-engine player ('buffer' is accepted,\n * anything else throws). The media adapter and clip-side loop/rate\n * overrides are rejected; use the sync's setLoop()/setRate() instead.\n * Construct the players and a {@link ScoreAudioSync} directly to pair a\n * score with other clip transports.\n */\n clipOptions?: FactoryClipOptions;\n}\n\n/**\n * Construct a score player, a clip player and a {@link ScoreAudioSync} on one\n * shared AudioContext — the safe way to get synchronized playback. The clip\n * must carry decoded samples (streaming/URL-only clips cannot feed the\n * buffer engine). To pair a clip from {@link renderScoreToClip} here, render\n * with `tailSeconds: 0`; otherwise use {@link createAudioMasteredPlayback} so\n * the clip can finish after the score's natural end.\n */\nexport function createSyncedPlayback(\n score: Score,\n clip: AudioClip,\n options: CreateSyncedPlaybackOptions = {},\n): {sync: ScoreAudioSync; scorePlayer: ScorePlayer; clipPlayer: AudioClipPlayer} {\n const clipOptions = options.clipOptions;\n assertFactoryClipOptions('createSyncedPlayback', clip, clipOptions);\n const clipOffsetSeconds = validatedClipOffsetSeconds(options.clipOffsetSeconds);\n const scoreOptions = options.scoreOptions;\n assertRenderedClipAlignment('createSyncedPlayback', score, clip, scoreOptions?.expandRepeats);\n assertInitialScoreTempo(score, scoreOptions?.tempo);\n const context = options.context ??\n createWebAudioContext('Web Audio is not available. Pass an existing AudioContext in options.context.');\n let scorePlayer: ScorePlayer | undefined;\n let clipPlayer: AudioClipPlayer | undefined;\n try {\n scorePlayer = new ScorePlayer(score, {...scoreOptions, audioContext: context});\n clipPlayer = new AudioClipPlayer(clip, {\n ...clipOptions,\n audioContext: context,\n // Only the buffer engine can join sample-accurately.\n engine: 'buffer',\n });\n const sync = new ScoreAudioSync(scorePlayer, clipPlayer, context, {\n ...options,\n clipOffsetSeconds,\n });\n if (!options.context) ownContext(sync, context, options.onOperationError);\n return {sync, scorePlayer, clipPlayer};\n } catch (error) {\n for (const player of [clipPlayer, scorePlayer]) {\n try { player?.dispose(); } catch { /* Preserve the construction failure. */ }\n }\n if (!options.context) closeContext(context, options.onOperationError);\n throw error;\n }\n}\n\n/**\n * Render a score offline into an {@link AudioClip}. With the default positive\n * tail, use the clip as master so its final samples are not cut off when the\n * score stops; `tailSeconds: 0` permits a score-mastered pairing. A tempo\n * override that differs from the score's base tempo changes the clip's\n * content axis and cannot be paired by either fixed-offset factory.\n */\nexport async function renderScoreToClip(score: Score, options?: RenderOptions): Promise<AudioClip> {\n const baseTempo = score.timeMap.tempi[0]?.bpm ?? 120;\n const tempo = options?.tempo;\n if (tempo !== undefined && (!Number.isFinite(tempo) || tempo <= 0)) {\n throw new RangeError('renderScoreToClip tempo must be finite and > 0.');\n }\n const tail = options?.tailSeconds;\n if (tail !== undefined && (!Number.isFinite(tail) || tail < 0)) {\n throw new RangeError('renderScoreToClip tailSeconds must be finite and >= 0.');\n }\n const buffer = await renderScoreToBuffer(score, options);\n const channelData: Float32Array[] = [];\n for (let channel = 0; channel < buffer.numberOfChannels; channel++) {\n channelData.push(buffer.getChannelData(channel));\n }\n const clip = createAudioClip({channelData, sampleRate: buffer.sampleRate});\n recordRenderProvenance(clip, score, tempo === undefined ? 1 : tempo / baseTempo, tail === undefined || tail > 0);\n return clip;\n}\n\n/** Validate the Score master's initial rate before acquiring a context. */\nfunction assertInitialScoreTempo(score: Score, tempo: number | undefined): void {\n if (tempo === undefined) return;\n const baseTempo = score.timeMap.tempi[0]?.bpm ?? 120;\n const rate = tempo / baseTempo;\n if (!Number.isFinite(rate) || rate < MIN_SHARED_PLAYBACK_RATE || rate > MAX_SHARED_PLAYBACK_RATE) {\n throw new RangeError(\n `scoreOptions.tempo must set an initial shared rate between ` +\n `${MIN_SHARED_PLAYBACK_RATE} and ${MAX_SHARED_PLAYBACK_RATE} times the score tempo.`,\n );\n }\n}\n\nfunction assertSharedRate(rate: number): void {\n if (!Number.isFinite(rate) || rate < MIN_SHARED_PLAYBACK_RATE || rate > MAX_SHARED_PLAYBACK_RATE) {\n throw new RangeError(`rate must be finite and between ${MIN_SHARED_PLAYBACK_RATE} and ${MAX_SHARED_PLAYBACK_RATE}.`);\n }\n}\n","/** Contexts allocated by a playback factory belong to its returned sync. */\ntype OperationErrorObserver = (operation: string, error: unknown) => void;\nconst ownedContexts = new WeakMap<object, {\n context: AudioContext;\n onOperationError?: OperationErrorObserver;\n}>();\n\nexport function ownContext(owner: object, context: AudioContext, onOperationError?: OperationErrorObserver): void {\n ownedContexts.set(owner, {context, onOperationError});\n}\n\nexport function releaseOwnedContext(owner: object): void {\n const owned = ownedContexts.get(owner);\n if (!owned) return;\n // Delete before calling external code, so re-entrant disposal is harmless.\n ownedContexts.delete(owner);\n closeContext(owned.context, owned.onOperationError);\n}\n\nexport function closeContext(context: AudioContext, onOperationError?: OperationErrorObserver): void {\n const report = (error: unknown) => {\n try {\n onOperationError?.('context.close', error);\n } catch {\n // An observer cannot replace the original construction/disposal error.\n }\n };\n try {\n void context.close().catch(report);\n } catch (error) {\n report(error);\n }\n}\n","import type {AudioClip} from '@webmusic/audio';\nimport type {AudioClipPlayer} from '@webmusic/audio/play/headless';\n\n/** Both factory directions use one buffer engine and group-owned loop/rate. */\nexport type FactoryClipOptions = Omit<\n NonNullable<ConstructorParameters<typeof AudioClipPlayer>[1]>,\n 'engine' | 'mediaAdapterFactory' | 'loop' | 'rate'\n> & {engine?: 'buffer'};\n\ntype FactoryName = 'createSyncedPlayback' | 'createAudioMasteredPlayback';\n\n/** Both master directions place score zero at a finite clip position. */\nexport function validatedClipOffsetSeconds(value: number | undefined): number {\n const offset = value ?? 0;\n if (!Number.isFinite(offset) || offset < 0) {\n throw new RangeError('clipOffsetSeconds must be finite and >= 0.');\n }\n return offset;\n}\n\n/** Validate before either factory acquires a context or constructs a player. */\nexport function assertFactoryClipOptions(\n factory: FactoryName,\n clip: AudioClip,\n options: FactoryClipOptions | undefined,\n): void {\n // Runtime callers can bypass the restricted TypeScript options shape.\n const input = options as\n | {engine?: unknown; mediaAdapterFactory?: unknown; loop?: unknown; rate?: unknown}\n | undefined;\n if (input?.loop !== undefined) {\n throw new RangeError(\n `${factory} does not accept clipOptions.loop: native clip looping does not expose the ` +\n 'wrapped group axis. Use ScoreAudioSync.setLoop to loop both transports together.',\n );\n }\n if (input?.rate !== undefined) {\n throw new RangeError(\n `${factory} does not accept clipOptions.rate: the shared rate is owned by the ` +\n 'transport group. Use ScoreAudioSync.setRate to change it on both transports.',\n );\n }\n if (input?.engine !== undefined && input.engine !== 'buffer') {\n throw new RangeError(\n `${factory} always uses the buffer engine (only it supplies the required scheduled clock); ` +\n `got engine '${String(input.engine)}'. Construct the players and ScoreAudioSync directly ` +\n 'to use another clip transport.',\n );\n }\n if (input?.mediaAdapterFactory !== undefined) {\n throw new RangeError(\n `${factory} always uses the buffer engine; mediaAdapterFactory does not apply.`,\n );\n }\n if (!clip.hasSamples) {\n throw new RangeError(\n `${factory} requires a clip with decoded samples: the buffer engine cannot play ` +\n 'a streaming (URL-only) clip. Decode the audio when loading it, or render a matched ' +\n 'backing track with renderScoreToClip.',\n );\n }\n}\n","import type {AudioClip} from '@webmusic/audio';\nimport type {Score} from '@webmusic/score';\n\ninterface RenderProvenance {\n score: Score;\n tempoScale: number;\n hasTail: boolean;\n}\n\n// The registry is shared by ESM/CJS or duplicate Bridge module instances in\n// one JS realm. It holds neither samples nor a transport; its WeakMap key is\n// only the exact immutable clip returned by renderScoreToClip. Clips moved\n// across realms, copied, sliced or serialized may have different timelines\n// and carry no provenance.\nconst REGISTRY_KEY = Symbol.for('@webmusic/bridge/render-provenance-v1');\n\nfunction renderProvenance(create: boolean): WeakMap<AudioClip, RenderProvenance> | undefined {\n let registry = Reflect.get(globalThis, REGISTRY_KEY) as WeakMap<AudioClip, RenderProvenance> | undefined;\n if (registry === undefined && create) {\n registry = new WeakMap<AudioClip, RenderProvenance>();\n Object.defineProperty(globalThis, REGISTRY_KEY, {\n value: registry,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n }\n return registry;\n}\n\nexport function recordRenderProvenance(\n clip: AudioClip,\n score: Score,\n tempoScale: number,\n hasTail: boolean,\n): void {\n renderProvenance(true)!.set(clip, {score, tempoScale, hasTail});\n}\n\nexport function assertRenderedClipAlignment(\n factory: 'createSyncedPlayback' | 'createAudioMasteredPlayback',\n score: Score,\n clip: AudioClip,\n expandRepeats: boolean | undefined = false,\n): void {\n const provenance = renderProvenance(false)?.get(clip);\n if (!provenance) return;\n if (provenance.score !== score) {\n throw new RangeError(\n `${factory} cannot pair a Bridge-rendered clip with a different Score instance. ` +\n 'Render this score again with renderScoreToClip(), or use an ordinary clip ' +\n 'if your application owns the alignment.',\n );\n }\n if (expandRepeats) {\n throw new RangeError(\n `${factory} cannot expand repeats only in ScorePlayer for a Bridge-rendered clip: ` +\n 'the score and clip would follow different timelines. Call expandRepeats(score) first, ' +\n 'then renderScoreToClip(expandedScore) and pair that same expanded Score instance ' +\n 'without scoreOptions.expandRepeats.',\n );\n }\n if (provenance.tempoScale !== 1) {\n throw new RangeError(\n `${factory} cannot pair a clip rendered with a tempo override: its audio seconds ` +\n 'do not match the score-seconds axis. Render at the score tempo, then ' +\n 'change both players with sync.setRate().',\n );\n }\n if (factory === 'createSyncedPlayback' && provenance.hasTail) {\n throw new RangeError(\n 'createSyncedPlayback cannot play the tail of a clip rendered from the same score: ' +\n 'the score master stops at its natural end. Use createAudioMasteredPlayback(score, clip) ' +\n 'to play the complete render, or render with tailSeconds: 0.',\n );\n }\n}\n","// ============================================================================\n// Audio as master: drive playback from a real recording and have the score\n// follow it — the reverse of the score-mastered pairing in sync.ts.\n//\n// No new transport machinery. ScoreAudioSync is already role-based (its first\n// participant drives, its second follows) and both families now hold both\n// primitives: AudioClipPlayer exposes the buffer engine's clock and arms it on\n// `play(when)`, and ScorePlayer accepts scheduled starts and re-anchors. What\n// the reversal needs is an AXIS translation, which is what the two adapters\n// below are:\n//\n// - The sync's position axis is always the MASTER's axis. With a clip\n// master that axis is clip seconds.\n// - `ScorePlayer.seek()` is in RATE-SCALED seconds, so a score follower\n// cannot be handed to the sync directly: at any rate but 1 the positions\n// would silently diverge. `seekNominal`/`nominalSeconds` are the\n// rate-invariant members, and the follower adapter routes through them.\n// - `clipOffsetSeconds` (clip time at score-zero) flips direction: the\n// follower's position is `masterPosition - offset`, so the adapter\n// absorbs the offset rather than the sync applying it.\n// ============================================================================\n\nimport {createWebAudioContext} from '@webmusic/kernel/audio-context';\nimport type {AudioClip} from '@webmusic/audio';\nimport {AudioClipPlayer} from '@webmusic/audio/play/headless';\nimport type {Score} from '@webmusic/score';\nimport {ScorePlayer} from '@webmusic/score/play/headless';\nimport {closeContext, ownContext} from './owned-context';\nimport {\n assertFactoryClipOptions,\n validatedClipOffsetSeconds,\n type FactoryClipOptions,\n} from './factory-clip-options';\nimport {assertRenderedClipAlignment} from './render-provenance';\nimport {\n ScoreAudioSync,\n type ScoreAudioSyncOptions,\n type SyncFollowerTransport,\n type SyncMasterTransport,\n type SyncTransportClockView,\n} from './sync';\n\n/**\n * Shift a read-only clock onto another axis by a constant offset. The sync\n * reads the follower's clock to measure drift, so a follower whose own axis\n * is displaced from the master's must present a shifted view or every drift\n * check would report the offset itself as drift.\n */\nfunction offsetClockView(clock: SyncTransportClockView, offset: number): SyncTransportClockView {\n if (offset === 0) return clock;\n return {\n get state() {\n const state = clock.state;\n return {...state, originPosition: state.originPosition + offset};\n },\n get rate() {\n return clock.rate;\n },\n get paused() {\n return clock.paused;\n },\n get holding() {\n return clock.holding;\n },\n positionAt: (t: number) => clock.positionAt(t) + offset,\n timeAt: (position: number) => clock.timeAt(position - offset),\n };\n}\n\n/** Options shared by the reverse-role adapters. */\nexport interface AudioMasterAdapterOptions {\n /** Finite, non-negative clip seconds corresponding to score-seconds zero. Default 0. */\n clipOffsetSeconds?: number;\n}\n\n/**\n * Present an {@link AudioClipPlayer} as the sync's MASTER transport.\n *\n * A scheduled re-anchor (`seekNominal(position, when)`) is expressed as\n * pause → seek → `play(when)`: the engine's own `seek` restarts immediately\n * while playing, and its `play` is a no-op unless paused, so this is the\n * sequence that actually arms the clock at `when` rather than starting at\n * once. That is what lets a follower join the reversed pairing on a shared\n * origin, exactly as the clip does in the forward one.\n */\nexport function clipAsMaster(clip: AudioClipPlayer): SyncMasterTransport {\n return {\n play: (when?: number) => clip.play(when),\n pause: () => clip.pause(),\n stop: () => clip.stop(),\n seekNominal: (seconds: number, when?: number) => {\n if (when === undefined || !clip.playing) {\n clip.seek(seconds);\n return;\n }\n clip.pause();\n clip.seek(seconds);\n return clip.play(when);\n },\n setRate: (rate: number) => clip.setRate(rate),\n get nominalSeconds() {\n return clip.seconds;\n },\n get clock() {\n return clip.clock;\n },\n dispose: () => clip.dispose(),\n };\n}\n\n/**\n * Present a {@link ScorePlayer} as the sync's FOLLOWER transport, on the\n * master clip's seconds axis.\n *\n * Three translations happen here.\n *\n * 1. Rate-invariant positions: `seekNominal`/`nominalSeconds`, never\n * `seek`/`seconds`, which are rate-scaled and would desync the pairing at\n * any rate but 1.\n * 2. The clip-offset shift, so the sync itself needs no offset here.\n * 3. The LEAD-IN region. A recording may hold material before score-zero — a\n * count-in, an anacrusis, room tone — and there the score has no position\n * at all: the requested one is negative and `seekNominal` clamps it to the\n * start. Starting the score anyway would have it run the whole recording\n * that much early, so a scheduled start is deferred by exactly the\n * remaining lead-in, and the score enters when the recording actually\n * reaches score-zero.\n */\nexport function scoreAsFollower(\n score: ScorePlayer,\n options: AudioMasterAdapterOptions = {},\n): SyncFollowerTransport {\n const offset = validatedClipOffsetSeconds(options.clipOffsetSeconds);\n // Last position requested on the score's axis, BEFORE seekNominal's clamp.\n // Negative means the transport currently sits in the recording's lead-in.\n let requested = 0;\n return {\n play: (when?: number) => {\n if (when !== undefined && requested < 0) {\n // `requested` is (master position − offset), so the recording reaches\n // score-zero exactly `-requested` nominal seconds after `when`.\n return score.play(when + -requested / score.rate);\n }\n return score.play(when);\n },\n pause: () => score.pause(),\n stop: () => {\n requested = 0;\n score.stop();\n },\n // The sync only ever seeks a follower it has just paused, and a paused\n // seekNominal applies its re-anchor synchronously before resolving.\n seek: (seconds: number) => {\n requested = seconds - offset;\n void score.seekNominal(requested);\n },\n setRate: (rate: number) => score.setRate(rate),\n get seconds() {\n return score.nominalSeconds + offset;\n },\n get playing() {\n return score.isPlaying();\n },\n get clock() {\n return offsetClockView(score.clock, offset);\n },\n dispose: () => score.dispose(),\n };\n}\n\nexport interface CreateAudioMasteredPlaybackOptions extends ScoreAudioSyncOptions {\n /** Shared AudioContext. If omitted, the factory creates one and sync.dispose() closes it. */\n context?: AudioContext;\n /** ScorePlayer options; tempo is group-owned and must be set with `sync.setRate()`. */\n scoreOptions?: ConstructorParameters<typeof ScorePlayer>[1];\n /**\n * Options forwarded to the AudioClipPlayer constructor. As in the forward\n * pairing the engine is not selectable: only the buffer engine holds a\n * sample-accurate clock, and here it is the MASTER's clock, so nothing\n * downstream could be accurate without it. The media adapter and clip-side\n * loop/rate overrides are rejected; use the sync's setLoop()/setRate().\n */\n clipOptions?: FactoryClipOptions;\n}\n\n/**\n * Construct an audio-mastered pairing: the CLIP drives the transport and the\n * score follows it, on one shared AudioContext. This is the configuration for\n * following a real recording — a performance, a rehearsal take — with the\n * notation tracking it, rather than the score-mastered\n * `createSyncedPlayback`, where the clip is typically a backing track\n * rendered from the score itself.\n *\n * Positions are on the CLIP's seconds axis (the master's axis). Pass\n * `clipOffsetSeconds` when the recording does not begin at score-seconds\n * zero. The score player is returned so callers can silence it\n * (`setVolume(0)`) when the recording is meant to be the only sounding\n * source, which is the usual case here.\n */\nexport function createAudioMasteredPlayback(\n score: Score,\n clip: AudioClip,\n options: CreateAudioMasteredPlaybackOptions = {},\n): {sync: ScoreAudioSync; scorePlayer: ScorePlayer; clipPlayer: AudioClipPlayer} {\n const clipOptions = options.clipOptions;\n assertFactoryClipOptions('createAudioMasteredPlayback', clip, clipOptions);\n const clipOffsetSeconds = validatedClipOffsetSeconds(options.clipOffsetSeconds);\n const scoreOptions = options.scoreOptions;\n assertRenderedClipAlignment('createAudioMasteredPlayback', score, clip, scoreOptions?.expandRepeats);\n if (scoreOptions?.tempo !== undefined) {\n throw new RangeError(\n 'createAudioMasteredPlayback does not accept scoreOptions.tempo: the audio master owns ' +\n 'the shared rate. Change both players with sync.setRate().',\n );\n }\n const context = options.context ??\n createWebAudioContext('Web Audio is not available. Pass an existing AudioContext in options.context.');\n let scorePlayer: ScorePlayer | undefined;\n let clipPlayer: AudioClipPlayer | undefined;\n try {\n scorePlayer = new ScorePlayer(score, {...scoreOptions, audioContext: context});\n clipPlayer = new AudioClipPlayer(clip, {\n ...clipOptions,\n audioContext: context,\n engine: 'buffer',\n });\n const sync = new ScoreAudioSync(\n clipAsMaster(clipPlayer),\n scoreAsFollower(scorePlayer, {clipOffsetSeconds}),\n context,\n // The follower adapter already translates the offset onto the clip axis.\n {...options, clipOffsetSeconds: 0},\n );\n if (!options.context) ownContext(sync, context, options.onOperationError);\n return {sync, scorePlayer, clipPlayer};\n } catch (error) {\n for (const player of [clipPlayer, scorePlayer]) {\n try { player?.dispose(); } catch { /* Preserve the construction failure. */ }\n }\n if (!options.context) closeContext(context, options.onOperationError);\n throw error;\n }\n}\n","// ============================================================================\n// Audio → symbolic assembly: build a real @webmusic/score Score from the\n// family-neutral note events that @webmusic/audio/analyze/transcribe emits. This\n// deliberately lives in the bridge — the analyze package knows nothing about\n// scores, and this module is the only place the two vocabularies meet.\n//\n// Notation is quantized to a grid; the exact audio timing survives on each\n// note's `performed` attributes (onsetSec/durationSec/velocity), so nothing\n// the transcriber heard is lost to the grid.\n// ============================================================================\n\nimport type {TranscribedNote} from '@webmusic/audio/analyze/transcribe';\nimport {\n Duration,\n MeasureId,\n PartId,\n Pitch,\n Rational,\n ScoreBuilder,\n VoiceId,\n type Score,\n} from '@webmusic/score';\n\nexport interface ScoreFromTranscriptionOptions {\n /** Tempo of the produced score. Default 120 (pass the transcriber's bpm). */\n bpm?: number;\n /** Time signature. Default 4/4. */\n timeSignature?: {numerator: number; denominator: number};\n /**\n * Notation grid in subdivisions per quarter note: onsets/durations snap to\n * `1/grid` quarters and durations never collapse below one grid unit.\n * Default 4 (sixteenth notes). Pass 0 to keep exact (unquantized) values\n * on the 1/480 tick grid.\n */\n quantizeGrid?: number;\n /** Score title. Default 'Transcription'. */\n title?: string;\n /** Part name. Default 'Transcribed'. */\n partName?: string;\n /** Maximum number of input note events to process. Default 100,000. */\n maxNotes?: number;\n /** Maximum number of measures to materialize. Default 4,096. */\n maxMeasures?: number;\n}\n\nconst TICKS_PER_QUARTER = 480;\nexport const DEFAULT_MAX_TRANSCRIPTION_NOTES = 100_000;\nexport const DEFAULT_MAX_TRANSCRIPTION_MEASURES = 4_096;\n\n/**\n * Assemble a Score from transcribed note events. Notes with a MIDI pitch\n * outside [0, 127] are skipped (transcription noise); velocities clamp into\n * the 1..127 MIDI range; measures are laid out to cover the material.\n */\nexport function scoreFromTranscription(\n notes: readonly TranscribedNote[],\n options: ScoreFromTranscriptionOptions = {},\n): Score {\n const bpm = options.bpm ?? 120;\n if (!(Number.isFinite(bpm) && bpm > 0)) {\n throw new RangeError(`scoreFromTranscription: bpm must be finite and > 0, got ${bpm}.`);\n }\n const grid = options.quantizeGrid ?? 4;\n if (!(Number.isSafeInteger(grid) && grid >= 0)) {\n throw new RangeError(`scoreFromTranscription: quantizeGrid must be a non-negative safe integer, got ${grid}.`);\n }\n const timeSignature = options.timeSignature ?? {numerator: 4, denominator: 4};\n if (\n !Number.isSafeInteger(timeSignature.numerator) || timeSignature.numerator < 1 ||\n !Number.isSafeInteger(timeSignature.denominator) || timeSignature.denominator < 1\n ) {\n throw new RangeError('scoreFromTranscription: timeSignature values must be positive safe integers.');\n }\n const maxNotes = resolvePositiveLimit(\n 'maxNotes',\n options.maxNotes,\n DEFAULT_MAX_TRANSCRIPTION_NOTES,\n );\n const maxMeasures = resolvePositiveLimit(\n 'maxMeasures',\n options.maxMeasures,\n DEFAULT_MAX_TRANSCRIPTION_MEASURES,\n );\n if (notes.length > maxNotes) {\n throw new RangeError(\n `Transcription resource limit exceeded: ${notes.length.toLocaleString()} note events ` +\n `(maxNotes is ${maxNotes.toLocaleString()}).`,\n );\n }\n\n const denominator = grid > 0 ? grid : TICKS_PER_QUARTER;\n const secondsToQuarterUnits = (seconds: number, label: string): number => {\n const units = Math.round((seconds * bpm * denominator) / 60);\n if (!Number.isSafeInteger(units)) {\n throw new RangeError(`scoreFromTranscription: ${label} is too large to represent safely.`);\n }\n return units;\n };\n\n const builder = new ScoreBuilder();\n builder\n .setMetadata({title: options.title ?? 'Transcription'})\n .addTempo({atQuarters: Rational.ZERO, bpm})\n .addMeter({atQuarters: Rational.ZERO, measureNumber: 1, timeSignature});\n\n const partId = PartId('transcription');\n const voice = VoiceId('v1');\n builder.addPart({id: partId, name: options.partName ?? 'Transcribed', staves: 1});\n\n let maxEndUnits = 0;\n for (const [index, note] of notes.entries()) {\n if (!Number.isFinite(note.midi)) {\n throw new RangeError(`scoreFromTranscription: note ${index} pitch must be finite.`);\n }\n const midi = Math.round(note.midi);\n if (midi < 0 || midi > 127) continue; // transcription noise\n if (\n !Number.isFinite(note.startSeconds) || note.startSeconds < 0 ||\n !Number.isFinite(note.endSeconds) || note.endSeconds < note.startSeconds\n ) {\n throw new RangeError(\n `scoreFromTranscription: note ${index} must have finite, non-negative, ordered start/end seconds.`,\n );\n }\n if (!Number.isFinite(note.velocity)) {\n throw new RangeError(`scoreFromTranscription: note ${index} velocity must be finite.`);\n }\n const onsetUnits = secondsToQuarterUnits(note.startSeconds, `note ${index} startSeconds`);\n const endUnits = Math.max(\n onsetUnits + 1,\n secondsToQuarterUnits(note.endSeconds, `note ${index} endSeconds`),\n );\n if (!Number.isSafeInteger(endUnits)) {\n throw new RangeError(`scoreFromTranscription: note ${index} duration is too large to represent safely.`);\n }\n maxEndUnits = Math.max(maxEndUnits, endUnits);\n builder.addNote(partId, {\n id: builder.newNoteId(),\n pitch: Pitch.fromMidi(midi),\n onsetQuarters: new Rational(onsetUnits, denominator),\n duration: new Duration({base: new Rational(endUnits - onsetUnits, denominator)}),\n voice,\n performed: {\n onsetSec: note.startSeconds,\n durationSec: Math.max(0, note.endSeconds - note.startSeconds),\n velocity: Math.min(127, Math.max(1, Math.round(note.velocity * 127))),\n },\n });\n }\n\n // Measures cover the material (at least one, so an empty transcription is\n // still a valid score).\n const materialUnits = BigInt(maxEndUnits) * BigInt(timeSignature.denominator);\n const measureUnits = BigInt(denominator) * BigInt(timeSignature.numerator) * 4n;\n const exactMeasureCount = materialUnits === 0n\n ? 1n\n : (materialUnits + measureUnits - 1n) / measureUnits;\n if (exactMeasureCount > BigInt(maxMeasures)) {\n throw new RangeError(\n `Transcription resource limit exceeded: score would create ` +\n `${exactMeasureCount.toLocaleString()} measures ` +\n `(maxMeasures is ${maxMeasures.toLocaleString()}).`,\n );\n }\n const measureCount = Number(exactMeasureCount);\n const quartersPerMeasure = quartersPerMeasureFrom(timeSignature);\n for (let index = 0; index < measureCount; index++) {\n builder.addMeasure({\n id: MeasureId(`m${index + 1}`),\n number: index + 1,\n onsetQuarters: quartersPerMeasure.mul(new Rational(index, 1)),\n durationQuarters: quartersPerMeasure,\n timeSignature,\n });\n }\n\n return builder.build();\n}\n\nfunction resolvePositiveLimit(name: 'maxNotes' | 'maxMeasures', value: number | undefined, fallback: number): number {\n if (value === undefined) return fallback;\n if (!Number.isSafeInteger(value) || value < 1) {\n throw new RangeError(`scoreFromTranscription: ${name} must be a positive safe integer.`);\n }\n return value;\n}\n\nfunction quartersPerMeasureFrom(timeSignature: {numerator: number; denominator: number}): Rational {\n let numerator = BigInt(timeSignature.numerator) * 4n;\n let denominator = BigInt(timeSignature.denominator);\n const divisor = greatestCommonDivisor(numerator, denominator);\n numerator /= divisor;\n denominator /= divisor;\n const maxSafe = BigInt(Number.MAX_SAFE_INTEGER);\n if (numerator > maxSafe || denominator > maxSafe) {\n throw new RangeError(\n 'scoreFromTranscription: timeSignature measure duration is too large to represent safely.',\n );\n }\n return new Rational(Number(numerator), Number(denominator));\n}\n\nfunction greatestCommonDivisor(left: bigint, right: bigint): bigint {\n while (right !== 0n) {\n const remainder = left % right;\n left = right;\n right = remainder;\n }\n return left;\n}\n"],"mappings":";;;;;;;;;;AAQA,SAAQ,UAAU,eAA+B;AACjD,SAAQ,gBAAe;AAWhB,IAAM,2BAA2B;AAQjC,SAAS,oBAAoB,KAAc,SAA+C;AAC/F,QAAM,EAAC,kBAAkB,kBAAkB,GAAG,WAAW,yBAAwB,IAAI;AACrF,MAAI,CAAC,OAAO,SAAS,gBAAgB,KAAK,oBAAoB,GAAG;AAC/D,UAAM,IAAI,WAAW,yCAAyC;AAAA,EAChE;AACA,MAAI,CAAC,OAAO,cAAc,eAAe,KAAK,kBAAkB,GAAG;AACjE,UAAM,IAAI,WAAW,iDAAiD;AAAA,EACxE;AACA,MAAI,CAAC,OAAO,cAAc,QAAQ,KAAK,WAAW,GAAG;AACnD,UAAM,IAAI,WAAW,sCAAsC;AAAA,EAC7D;AACA,QAAM,iBAAiB,mBAAmB;AAC1C,QAAM,iBAAiB,KAAK,MAAM,cAAc;AAChD,QAAM,eAAe,OAAO,UAAU,KAAK,IAAI,GAAG,KAAK,IAAI,cAAc,CAAC,IAAI;AAC9E,QAAM,qBACJ,KAAK,IAAI,iBAAiB,cAAc,KAAK,eACzC,iBACA;AACN,QAAM,QAAQ,KAAK,KAAK,kBAAkB;AAC1C,MAAI,CAAC,OAAO,cAAc,KAAK,KAAK,SAAS,UAAU;AACrD,UAAM,IAAI;AAAA,MACR,wDAAwD,SAAS,eAAe,CAAC;AAAA,IACnF;AAAA,EACF;AACA,QAAM,QAAkB,CAAC;AACzB,WAAS,QAAQ,GAAG,SAAS,OAAO,SAAS;AAC3C,UAAM,KAAK,IAAI,kBAAkB,IAAI,SAAS,OAAO,eAAe,CAAC,CAAC;AAAA,EACxE;AAQA,QAAM,QAAQ,IAAI,QAAQ,SAAS,IAAI;AACvC,QAAM,MAAM,MAAM,OAAO,MAAM,QAAQ,KAAK;A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AM,UAAU,OAAO,OAAO,gBAAgB;AAC9C,MAAI,YAAY,WAAW,cAAc,SAAS;AAChD,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO,IAAIA,UAAS,OAAO,SAAS,GAAG,OAAO,WAAW,CAAC;AAC5D;AAEA,SAAS,sBAAsB,MAAc,OAAuB;AAClE,SAAO,UAAU,IAAI;AACnB,UAAM,YAAY,OAAO;AACzB,WAAO;AACP,YAAQ;AAAA,EACV;AACA,SAAO;AACT;","names":["createWebAudioContext","AudioClipPlayer","ScorePlayer","createWebAudioContext","ScorePlayer","AudioClipPlayer","Rational"]}
|
|
1
|
+
{"version":3,"sources":["../src/mapping.ts","../src/render.ts","../src/session.ts","../src/transcription.ts"],"sourcesContent":["// ============================================================================\n// Timeline conversions between the two families' musical time models.\n// TimeMap → BeatGrid is lossless sampling (evaluate the exact map at each\n// beat); BeatGrid → TimeMap is approximate (each inter-beat interval becomes\n// one tempo segment). Both project onto the same seconds ruler, which is what\n// makes score↔audio alignment composable.\n// ============================================================================\n\nimport {Rational, TimeMap, type TempoEntry} from '@webmusic/score';\nimport {BeatGrid} from '@webmusic/audio';\n\nexport interface BeatGridFromTimeMapOptions {\n /** How many quarters of the score timeline to sample. */\n durationQuarters: number;\n /** Beat subdivisions per quarter note (default 1: beat = quarter). */\n beatsPerQuarter?: number;\n /** Maximum number of beat samples to allocate. Default 1,000,000. */\n maxBeats?: number;\n}\n\nexport const DEFAULT_MAX_MAPPED_BEATS = 1_000_000;\n\n/**\n * Sample a {@link TimeMap} into a {@link BeatGrid}: one beat per\n * `1/beatsPerQuarter` quarter from 0 through `durationQuarters`. Lossless up\n * to the sampling density — tempo changes between sampled beats interpolate\n * linearly on the grid.\n */\nexport function beatGridFromTimeMap(map: TimeMap, options: BeatGridFromTimeMapOptions): BeatGrid {\n const {durationQuarters, beatsPerQuarter = 1, maxBeats = DEFAULT_MAX_MAPPED_BEATS} = options;\n if (!Number.isFinite(durationQuarters) || durationQuarters <= 0) {\n throw new RangeError('durationQuarters must be finite and > 0');\n }\n if (!Number.isSafeInteger(beatsPerQuarter) || beatsPerQuarter < 1) {\n throw new RangeError('beatsPerQuarter must be a positive safe integer');\n }\n if (!Number.isSafeInteger(maxBeats) || maxBeats < 2) {\n throw new RangeError('maxBeats must be a safe integer >= 2');\n }\n const scaledDuration = durationQuarters * beatsPerQuarter;\n const nearestInteger = Math.round(scaledDuration);\n const ulpTolerance = Number.EPSILON * Math.max(1, Math.abs(scaledDuration)) * 4;\n const normalizedDuration =\n Math.abs(scaledDuration - nearestInteger) <= ulpTolerance\n ? nearestInteger\n : scaledDuration;\n const total = Math.ceil(normalizedDuration);\n if (!Number.isSafeInteger(total) || total >= maxBeats) {\n throw new RangeError(\n `Beat-grid mapping would allocate more than maxBeats (${maxBeats.toLocaleString()}) samples.`,\n );\n }\n const beats: number[] = [];\n for (let index = 0; index <= total; index++) {\n beats.push(map.quartersToSeconds(new Rational(index, beatsPerQuarter)));\n }\n // The sampled positions come from quartersToSeconds, which integrates tempo\n // as 60 / (bpm * unit) seconds per quarter — so the effective quarters per\n // minute is `bpm * unit`, not the raw bpm. Folding `unit` in here keeps the\n // grid's nominal tempo consistent with its own beat spacing; without it a\n // metronome mark like \"half note = 60\" produced 0.5 s beats under a grid\n // claiming 60 bpm, and BeatGrid's extrapolation before beat 0 disagreed with\n // every sampled beat after it.\n const tempo = map.tempoAt(Rational.ZERO);\n const bpm = tempo.bpm * (tempo.unit ?? 1) * beatsPerQuarter;\n return new BeatGrid({bpm, beats});\n}\n\n/**\n * Approximate a {@link TimeMap} from a {@link BeatGrid}: beat index becomes\n * the quarter axis and every inter-beat interval one tempo segment. The\n * grid's absolute offset is NOT representable (a TimeMap always maps quarter\n * 0 to second 0) — align `grid.beats[0]` on the consumer side. Zero-length\n * intervals are rejected: they would demand an infinite tempo.\n */\nexport function timeMapFromBeatGrid(grid: BeatGrid): TimeMap {\n const beats = grid.beats;\n const tempi: TempoEntry[] = [];\n if (beats.length < 2) {\n tempi.push({atQuarters: Rational.ZERO, bpm: grid.bpm});\n } else {\n for (let index = 0; index < beats.length - 1; index++) {\n const interval = beats[index + 1] - beats[index];\n if (!(interval > 0)) {\n throw new RangeError(`BeatGrid interval at beat ${index} is not positive (${interval}).`);\n }\n tempi.push({atQuarters: new Rational(index, 1), bpm: 60 / interval});\n }\n }\n return new TimeMap(tempi, [\n {atQuarters: Rational.ZERO, measureNumber: 1, timeSignature: {numerator: 4, denominator: 4}},\n ]);\n}\n","import {createAudioClip, type AudioClip} from '@webmusic/audio';\nimport type {Score} from '@webmusic/score';\nimport {renderScoreToBuffer, type RenderOptions} from '@webmusic/score/play';\n\n/**\n * Render a score offline into an {@link AudioClip} — a Score→Audio conversion\n * that stays a data function (DEC-068). A positive tail (the default) keeps\n * final samples after the score ends; `tailSeconds: 0` ends with the score. A\n * tempo override changes the clip's content axis relative to the score.\n */\nexport async function renderScoreToClip(score: Score, options?: RenderOptions): Promise<AudioClip> {\n const tempo = options?.tempo;\n if (tempo !== undefined && (!Number.isFinite(tempo) || tempo <= 0)) {\n throw new RangeError('renderScoreToClip tempo must be finite and > 0.');\n }\n const tail = options?.tailSeconds;\n if (tail !== undefined && (!Number.isFinite(tail) || tail < 0)) {\n throw new RangeError('renderScoreToClip tailSeconds must be finite and >= 0.');\n }\n const buffer = await renderScoreToBuffer(score, options);\n const channelData: Float32Array[] = [];\n for (let channel = 0; channel < buffer.numberOfChannels; channel++) {\n channelData.push(buffer.getChannelData(channel));\n }\n return createAudioClip({channelData, sampleRate: buffer.sampleRate});\n}\n","import type {AudioClip} from '@webmusic/audio';\nimport {AudioPlayer} from '@webmusic/audio/play/headless';\nimport {ModuleAudioEnvironment, ModuleContext, routeModuleOutput, type ConnectionLease} from '@webmusic/kernel/module';\nimport {SessionTransport, type SessionParticipantLease} from '@webmusic/kernel/session';\nimport type {Score} from '@webmusic/score';\nimport {ScorePlayerModule, type HeadlessSynth} from '@webmusic/score/play/headless';\nimport {registerAudioParticipant} from './audio-participant';\n\nexport interface CreateScoreAudioSessionOptions {\n /** Borrowed context; without one the composition creates and owns a lazy one. */\n context?: AudioContext;\n /** Score synth; defaults to the oscillator. */\n synth?: HeadlessSynth;\n /** Session seconds → nominal Score seconds: `score = session * scale + offset`. */\n scoreOffsetSeconds?: number;\n scorePositionScale?: number;\n /** Session seconds → clip seconds: `clip = session * scale + offset`. */\n clipOffsetSeconds?: number;\n clipPositionScale?: number;\n /** Lead-in before a shared start, in seconds. */\n leadInSeconds?: number;\n onOperationError?: (operation: string, error: unknown) => void;\n}\n\n/** One Session conducting a Score engine and an Audio player (DEC-068). */\nexport interface ScoreAudioSession {\n /** The only command authority: play, pause, stop, seek, rate and loop go here. */\n readonly session: SessionTransport;\n readonly context: ModuleContext;\n readonly scoreModule: ScorePlayerModule;\n readonly clipPlayer: AudioPlayer;\n /** Release both participants, their routes, the Session and an owned context. */\n dispose(): void;\n}\n\n/**\n * Compose a Score and an Audio clip under one Session — Bridge's replacement\n * for the former master/follower sync family. Each engine is a Session\n * participant with an explicit mapping from Session seconds into its own axis\n * (`score-nominal-seconds`, `clip-seconds`); use `beatGridFromTimeMap` and\n * `timeMapFromBeatGrid` to derive mappings between musical and audio time.\n * Nothing is allocated until the Session prepares or plays.\n */\nexport function createScoreAudioSession(score: Score, clip: AudioClip, options: CreateScoreAudioSessionOptions = {}): ScoreAudioSession {\n const audio = new ModuleAudioEnvironment(options.context ? {context: options.context} : {});\n const session = new SessionTransport(() => audio.peek()?.currentTime ?? 0, {\n ...(options.leadInSeconds !== undefined ? {leadInSeconds: options.leadInSeconds} : {}),\n onOperationError: options.onOperationError,\n });\n const context = new ModuleContext({id: 'score-audio-session', audio, session});\n let scoreModule: ScorePlayerModule | undefined;\n let clipPlayer: AudioPlayer | undefined;\n let participant: SessionParticipantLease | undefined;\n let route: ConnectionLease | undefined;\n let disposed = false;\n const dispose = (): void => {\n if (disposed) return;\n disposed = true;\n let failure: unknown;\n for (const release of [() => participant?.release(), () => route?.release(), () => clipPlayer?.dispose(),\n () => scoreModule?.dispose(), () => session.dispose(), () => audio.dispose()]) {\n try { release(); } catch (error) { failure ??= error; }\n }\n if (failure !== undefined) throw failure;\n };\n try {\n scoreModule = new ScorePlayerModule(score, {\n id: 'score', context, synth: options.synth,\n offsetSeconds: options.scoreOffsetSeconds, positionScale: options.scorePositionScale,\n onError: (error) => options.onOperationError?.('score', error),\n });\n const player = new AudioPlayer(clip, {moduleContext: context});\n clipPlayer = player;\n participant = registerAudioParticipant(session, player, {\n offsetSeconds: options.clipOffsetSeconds, positionScale: options.clipPositionScale,\n prepare: async () => {\n await player.preload();\n if (disposed) throw new Error('Score/Audio Session was disposed during preparation.');\n if (!route) route = routeModuleOutput(context, {id: 'clip', getPort: () => player.outputPort}, player.outputPort!);\n },\n });\n } catch (error) {\n try { dispose(); } catch { /* Preserve the construction failure. */ }\n throw error;\n }\n return Object.freeze({session, context, scoreModule, clipPlayer, dispose});\n}\n","// ============================================================================\n// Audio → symbolic assembly: build a real @webmusic/score Score from the\n// family-neutral note events that @webmusic/audio/analyze/transcribe emits. This\n// deliberately lives in the bridge — the analyze package knows nothing about\n// scores, and this module is the only place the two vocabularies meet.\n//\n// Notation is quantized to a grid; the exact audio timing survives on each\n// note's `performed` attributes (onsetSec/durationSec/velocity), so nothing\n// the transcriber heard is lost to the grid.\n// ============================================================================\n\nimport type {TranscribedNote} from '@webmusic/audio/analyze/transcribe';\nimport {\n Duration,\n MeasureId,\n PartId,\n Pitch,\n Rational,\n ScoreBuilder,\n VoiceId,\n type Score,\n} from '@webmusic/score';\n\nexport interface ScoreFromTranscriptionOptions {\n /** Tempo of the produced score. Default 120 (pass the transcriber's bpm). */\n bpm?: number;\n /** Time signature. Default 4/4. */\n timeSignature?: {numerator: number; denominator: number};\n /**\n * Notation grid in subdivisions per quarter note: onsets/durations snap to\n * `1/grid` quarters and durations never collapse below one grid unit.\n * Default 4 (sixteenth notes). Pass 0 to keep exact (unquantized) values\n * on the 1/480 tick grid.\n */\n quantizeGrid?: number;\n /** Score title. Default 'Transcription'. */\n title?: string;\n /** Part name. Default 'Transcribed'. */\n partName?: string;\n /** Maximum number of input note events to process. Default 100,000. */\n maxNotes?: number;\n /** Maximum number of measures to materialize. Default 4,096. */\n maxMeasures?: number;\n}\n\nconst TICKS_PER_QUARTER = 480;\nexport const DEFAULT_MAX_TRANSCRIPTION_NOTES = 100_000;\nexport const DEFAULT_MAX_TRANSCRIPTION_MEASURES = 4_096;\n\n/**\n * Assemble a Score from transcribed note events. Notes with a MIDI pitch\n * outside [0, 127] are skipped (transcription noise); velocities clamp into\n * the 1..127 MIDI range; measures are laid out to cover the material.\n */\nexport function scoreFromTranscription(\n notes: readonly TranscribedNote[],\n options: ScoreFromTranscriptionOptions = {},\n): Score {\n const bpm = options.bpm ?? 120;\n if (!(Number.isFinite(bpm) && bpm > 0)) {\n throw new RangeError(`scoreFromTranscription: bpm must be finite and > 0, got ${bpm}.`);\n }\n const grid = options.quantizeGrid ?? 4;\n if (!(Number.isSafeInteger(grid) && grid >= 0)) {\n throw new RangeError(`scoreFromTranscription: quantizeGrid must be a non-negative safe integer, got ${grid}.`);\n }\n const timeSignature = options.timeSignature ?? {numerator: 4, denominator: 4};\n if (\n !Number.isSafeInteger(timeSignature.numerator) || timeSignature.numerator < 1 ||\n !Number.isSafeInteger(timeSignature.denominator) || timeSignature.denominator < 1\n ) {\n throw new RangeError('scoreFromTranscription: timeSignature values must be positive safe integers.');\n }\n const maxNotes = resolvePositiveLimit(\n 'maxNotes',\n options.maxNotes,\n DEFAULT_MAX_TRANSCRIPTION_NOTES,\n );\n const maxMeasures = resolvePositiveLimit(\n 'maxMeasures',\n options.maxMeasures,\n DEFAULT_MAX_TRANSCRIPTION_MEASURES,\n );\n if (notes.length > maxNotes) {\n throw new RangeError(\n `Transcription resource limit exceeded: ${notes.length.toLocaleString()} note events ` +\n `(maxNotes is ${maxNotes.toLocaleString()}).`,\n );\n }\n\n const denominator = grid > 0 ? grid : TICKS_PER_QUARTER;\n const secondsToQuarterUnits = (seconds: number, label: string): number => {\n const units = Math.round((seconds * bpm * denominator) / 60);\n if (!Number.isSafeInteger(units)) {\n throw new RangeError(`scoreFromTranscription: ${label} is too large to represent safely.`);\n }\n return units;\n };\n\n const builder = new ScoreBuilder();\n builder\n .setMetadata({title: options.title ?? 'Transcription'})\n .addTempo({atQuarters: Rational.ZERO, bpm})\n .addMeter({atQuarters: Rational.ZERO, measureNumber: 1, timeSignature});\n\n const partId = PartId('transcription');\n const voice = VoiceId('v1');\n builder.addPart({id: partId, name: options.partName ?? 'Transcribed', staves: 1});\n\n let maxEndUnits = 0;\n for (const [index, note] of notes.entries()) {\n if (!Number.isFinite(note.midi)) {\n throw new RangeError(`scoreFromTranscription: note ${index} pitch must be finite.`);\n }\n const midi = Math.round(note.midi);\n if (midi < 0 || midi > 127) continue; // transcription noise\n if (\n !Number.isFinite(note.startSeconds) || note.startSeconds < 0 ||\n !Number.isFinite(note.endSeconds) || note.endSeconds < note.startSeconds\n ) {\n throw new RangeError(\n `scoreFromTranscription: note ${index} must have finite, non-negative, ordered start/end seconds.`,\n );\n }\n if (!Number.isFinite(note.velocity)) {\n throw new RangeError(`scoreFromTranscription: note ${index} velocity must be finite.`);\n }\n const onsetUnits = secondsToQuarterUnits(note.startSeconds, `note ${index} startSeconds`);\n const endUnits = Math.max(\n onsetUnits + 1,\n secondsToQuarterUnits(note.endSeconds, `note ${index} endSeconds`),\n );\n if (!Number.isSafeInteger(endUnits)) {\n throw new RangeError(`scoreFromTranscription: note ${index} duration is too large to represent safely.`);\n }\n maxEndUnits = Math.max(maxEndUnits, endUnits);\n builder.addNote(partId, {\n id: builder.newNoteId(),\n pitch: Pitch.fromMidi(midi),\n onsetQuarters: new Rational(onsetUnits, denominator),\n duration: new Duration({base: new Rational(endUnits - onsetUnits, denominator)}),\n voice,\n performed: {\n onsetSec: note.startSeconds,\n durationSec: Math.max(0, note.endSeconds - note.startSeconds),\n velocity: Math.min(127, Math.max(1, Math.round(note.velocity * 127))),\n },\n });\n }\n\n // Measures cover the material (at least one, so an empty transcription is\n // still a valid score).\n const materialUnits = BigInt(maxEndUnits) * BigInt(timeSignature.denominator);\n const measureUnits = BigInt(denominator) * BigInt(timeSignature.numerator) * 4n;\n const exactMeasureCount = materialUnits === 0n\n ? 1n\n : (materialUnits + measureUnits - 1n) / measureUnits;\n if (exactMeasureCount > BigInt(maxMeasures)) {\n throw new RangeError(\n `Transcription resource limit exceeded: score would create ` +\n `${exactMeasureCount.toLocaleString()} measures ` +\n `(maxMeasures is ${maxMeasures.toLocaleString()}).`,\n );\n }\n const measureCount = Number(exactMeasureCount);\n const quartersPerMeasure = quartersPerMeasureFrom(timeSignature);\n for (let index = 0; index < measureCount; index++) {\n builder.addMeasure({\n id: MeasureId(`m${index + 1}`),\n number: index + 1,\n onsetQuarters: quartersPerMeasure.mul(new Rational(index, 1)),\n durationQuarters: quartersPerMeasure,\n timeSignature,\n });\n }\n\n return builder.build();\n}\n\nfunction resolvePositiveLimit(name: 'maxNotes' | 'maxMeasures', value: number | undefined, fallback: number): number {\n if (value === undefined) return fallback;\n if (!Number.isSafeInteger(value) || value < 1) {\n throw new RangeError(`scoreFromTranscription: ${name} must be a positive safe integer.`);\n }\n return value;\n}\n\nfunction quartersPerMeasureFrom(timeSignature: {numerator: number; denominator: number}): Rational {\n let numerator = BigInt(timeSignature.numerator) * 4n;\n let denominator = BigInt(timeSignature.denominator);\n const divisor = greatestCommonDivisor(numerator, denominator);\n numerator /= divisor;\n denominator /= divisor;\n const maxSafe = BigInt(Number.MAX_SAFE_INTEGER);\n if (numerator > maxSafe || denominator > maxSafe) {\n throw new RangeError(\n 'scoreFromTranscription: timeSignature measure duration is too large to represent safely.',\n );\n }\n return new Rational(Number(numerator), Number(denominator));\n}\n\nfunction greatestCommonDivisor(left: bigint, right: bigint): bigint {\n while (right !== 0n) {\n const remainder = left % right;\n left = right;\n right = remainder;\n }\n return left;\n}\n"],"mappings":";;;;;;AAQA,SAAQ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-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Bridge between the score and audio families of the WebMusic ecosystem: synchronized score+audio playback on one AudioContext clock, score-to-clip offline rendering, and TimeMap/BeatGrid conversions. The only package allowed to import both families.",
|
|
5
5
|
"type": "module",
|
|
6
|
-
"sideEffects":
|
|
6
|
+
"sideEffects": [
|
|
7
|
+
"./dist/component.global.js"
|
|
8
|
+
],
|
|
7
9
|
"main": "./dist/index.cjs",
|
|
8
10
|
"module": "./dist/index.js",
|
|
9
11
|
"types": "./dist/index.d.ts",
|
|
@@ -18,10 +20,24 @@
|
|
|
18
20
|
"default": "./dist/index.cjs"
|
|
19
21
|
}
|
|
20
22
|
},
|
|
23
|
+
"./component": {
|
|
24
|
+
"import": {
|
|
25
|
+
"types": "./dist/component.d.ts",
|
|
26
|
+
"default": "./dist/component.js"
|
|
27
|
+
},
|
|
28
|
+
"require": {
|
|
29
|
+
"types": "./dist/component.d.cts",
|
|
30
|
+
"default": "./dist/component.cjs"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"./component/global": {
|
|
34
|
+
"types": "./dist/component/global.d.ts",
|
|
35
|
+
"default": "./dist/component.global.js"
|
|
36
|
+
},
|
|
21
37
|
"./package.json": "./package.json"
|
|
22
38
|
},
|
|
23
39
|
"scripts": {
|
|
24
|
-
"build": "
|
|
40
|
+
"build": "node ../../scripts/clean-dist.mjs --begin dist && tsup && node ../../scripts/bundle-notices.mjs --package-dir . && node ../../scripts/clean-dist.mjs --prune dist && node ../../scripts/package-artifacts.mjs --write",
|
|
25
41
|
"test": "vitest run",
|
|
26
42
|
"typecheck": "tsc --noEmit",
|
|
27
43
|
"prepack": "node ../../scripts/package-artifacts.mjs"
|
|
@@ -29,9 +45,9 @@
|
|
|
29
45
|
"devDependencies": {
|
|
30
46
|
"tsup": "^8.5.0",
|
|
31
47
|
"typescript": "^5.4.0",
|
|
32
|
-
"vitest": "^5.
|
|
48
|
+
"vitest": "^5.1.0"
|
|
33
49
|
},
|
|
34
|
-
"license": "
|
|
50
|
+
"license": "Apache-2.0",
|
|
35
51
|
"publishConfig": {
|
|
36
52
|
"access": "public"
|
|
37
53
|
},
|
|
@@ -42,7 +58,8 @@
|
|
|
42
58
|
"files": [
|
|
43
59
|
"dist",
|
|
44
60
|
"README.md",
|
|
45
|
-
"LICENSE"
|
|
61
|
+
"LICENSE",
|
|
62
|
+
"NOTICE"
|
|
46
63
|
],
|
|
47
64
|
"repository": {
|
|
48
65
|
"type": "git",
|
|
@@ -63,8 +80,14 @@
|
|
|
63
80
|
"typescript"
|
|
64
81
|
],
|
|
65
82
|
"peerDependencies": {
|
|
66
|
-
"@webmusic/audio": "^0.
|
|
67
|
-
"@webmusic/kernel": "^0.
|
|
68
|
-
"@webmusic/score": "^0.
|
|
83
|
+
"@webmusic/audio": "^0.4.0",
|
|
84
|
+
"@webmusic/kernel": "^0.4.0",
|
|
85
|
+
"@webmusic/score": "^0.4.0",
|
|
86
|
+
"@webmusic/ui": "^0.4.0"
|
|
87
|
+
},
|
|
88
|
+
"peerDependenciesMeta": {
|
|
89
|
+
"@webmusic/ui": {
|
|
90
|
+
"optional": true
|
|
91
|
+
}
|
|
69
92
|
}
|
|
70
93
|
}
|