@webmusic/bridge 0.0.0-stage → 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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/mapping.ts","../src/render.ts","../src/session.ts","../src/audio-participant.ts","../src/transcription.ts","../src/project.ts"],"sourcesContent":["export {\n DEFAULT_MAX_MAPPED_BEATS,\n beatGridFromTimeMap,\n timeMapFromBeatGrid,\n type BeatGridFromTimeMapOptions,\n} from './mapping';\nexport {renderScoreToClip} from './render';\nexport {\n createScoreAudioSession,\n type CreateScoreAudioSessionOptions,\n type ScoreAudioSession,\n} from './session';\nexport {registerAudioParticipant, type AudioParticipantOptions, type AudioParticipantPlayer} from './audio-participant';\nexport {\n DEFAULT_MAX_TRANSCRIPTION_MEASURES,\n DEFAULT_MAX_TRANSCRIPTION_NOTES,\n scoreFromTranscription,\n type ScoreFromTranscriptionOptions,\n} from './transcription';\nexport {createWebMusicProjectPlugins, type WebMusicProjectPluginOptions} from './project';\n","// ============================================================================\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","import type {AudioClipPlayer} from '@webmusic/audio/play/headless';\nimport type {ModuleSession, SessionParticipantLease} from '@webmusic/kernel/session';\n\n/** The engine surface a participant adapter needs; `AudioPlayer` and `AudioClipPlayer` both provide it. */\nexport type AudioParticipantPlayer = Pick<AudioClipPlayer,\n 'play' | 'pause' | 'stop' | 'seek' | 'setRate' | 'seconds' | 'playing' | 'clock' | 'duration' |\n 'activateScheduling' | 'attachScheduling' | 'timingCapabilities'>;\n\nexport interface AudioParticipantOptions {\n offsetSeconds?: number;\n positionScale?: number;\n /** Prepare and route the player's output before the Session anchors a start. */\n prepare: () => void | Promise<void>;\n}\n\n/**\n * Register a Headless Audio engine with a Session on the `clip-seconds` axis —\n * the same axis `<audio-player>` uses, so Score and Audio mappings agree\n * (DEC-068). Native buffer playback attaches and activates the shared\n * scheduling anchor; other engines (document sequences, media streams,\n * borrowed queues) are commanded by the Session without activation.\n */\nexport function registerAudioParticipant(\n session: ModuleSession,\n player: AudioParticipantPlayer,\n options: AudioParticipantOptions,\n): SessionParticipantLease {\n return session.register({\n play: (when) => player.play(when), pause: () => player.pause(), stop: () => player.stop(),\n seek: (seconds) => player.seek(seconds), setRate: (rate) => player.setRate(rate),\n get position() { return player.seconds; }, get running() { return player.playing; },\n get clock() { return player.clock; },\n }, {\n axis: 'clip-seconds', identity: player, durationSeconds: () => player.duration, endPolicy: 'position',\n offsetSeconds: options.offsetSeconds, positionScale: options.positionScale,\n prepare: options.prepare,\n // Only native buffer playback can follow the Session's scheduling anchor;\n // document sequences, media and external transports follow by command,\n // as they do under `<audio-player>`.\n ...(player.timingCapabilities.sharedSessionClock && {\n activate: () => player.activateScheduling(),\n attachScheduling: (binding) => player.attachScheduling(binding),\n }),\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","import {registerAudioParticipant} from './audio-participant';\nimport {Score} from '@webmusic/score';\nimport {Effect, MidiAccessSource, ScorePlayerModule, ScoreRackModule, Sound, createMidiPlugins, soundModulePlugin} from '@webmusic/score/play/headless';\nimport {AudioClip} from '@webmusic/audio';\nimport {AudioClipPlayer, createBufferPlugins} from '@webmusic/audio/play/headless';\nimport {InsertChain} from '@webmusic/kernel/effect';\nimport {createMessagePlugins} from '@webmusic/kernel/message';\nimport {\n AudioOutputPort, ParamHandle, ParamSurface, createStructurePlugins, routeModuleOutput,\n type ConnectionLease, type ModuleEnvironment, type ModuleHandle, type ProjectFactoryRequest,\n type ProjectJsonObject, type ProjectModuleInstance, type ProjectPluginFactory,\n} from '@webmusic/kernel/module';\nimport {sequencerPlugin} from '@webmusic/kernel/sequence';\nimport {SessionLFO} from '@webmusic/kernel/session';\n\nconst version = '1.0.0';\nconst audioOutput = Object.freeze([{id: 'output', direction: 'output' as const, kind: 'audio' as const}]);\nconst audioInsert = Object.freeze([{id: 'input', direction: 'input' as const, kind: 'audio' as const}, ...audioOutput]);\n\nexport interface WebMusicProjectPluginOptions {\n /** Where printing, script output and module failures go, and the clock for timed messages; see Kernel's `ModuleEnvironment`. */\n readonly modules?: ModuleEnvironment;\n /** Web MIDI for the MIDI modules; one is made when omitted, and asks for access only when a module needs a device. */\n readonly midi?: MidiAccessSource;\n}\n\n/**\n * The standard set (DEC-097): the Bridge's own players, rack, bus, effect and\n * LFO, which need both domains, with the module types each package registers\n * — Kernel's message, structure and sequence modules, Score's MIDI and sound\n * modules, and Audio's buffer modules. Trusted, explicit factories; asset\n * resolution and storage remain application responsibilities.\n */\nexport function createWebMusicProjectPlugins(options: WebMusicProjectPluginOptions = {}): readonly ProjectPluginFactory[] {\n const environment = options.modules ?? {};\n return Object.freeze([\n {id: 'webmusic.score-player', version, create: createScore},\n {id: 'webmusic.audio-player', version, create: createAudio},\n {id: 'webmusic.score-rack', version, create: createRack},\n {id: 'webmusic.audio-bus', version, create: (request: ProjectFactoryRequest) => createInsert(request, Effect.gain(number(request.record.config, 'gain', 1)))},\n {id: 'webmusic.effect', version, create: (request: ProjectFactoryRequest) => createInsert(request, effectRecipe(request.record.config))},\n {id: 'webmusic.lfo', version, create: createLfo},\n ...createMessagePlugins(environment),\n ...createStructurePlugins(environment),\n sequencerPlugin(environment),\n ...createMidiPlugins(options.midi ?? new MidiAccessSource()),\n soundModulePlugin(),\n ...createBufferPlugins(environment),\n ]);\n}\n\nasync function createScore(request: ProjectFactoryRequest): Promise<ProjectModuleInstance> {\n const score = await request.resolveAsset('source');\n request.signal.throwIfAborted();\n if (!(score instanceof Score)) throw new TypeError('The score-player source asset must resolve to a Score.');\n const config = request.record.config;\n const sound = Sound.oscillator({type: waveform(config.waveform)});\n let module: ScorePlayerModule;\n try {\n module = new ScorePlayerModule(score, {\n context: request.context, id: request.record.id, synth: sound, synthOwnership: 'owned', reverb: false,\n offsetSeconds: number(config, 'offsetSeconds', 0), positionScale: number(config, 'positionScale', 1),\n });\n } catch (error) { sound.dispose(); throw error; }\n return {module, ports: audioOutput, childContext: child => child.derive({id: child.id, target: module}),\n exportConfig: () => config, dispose: () => module.dispose()};\n}\n\nasync function createAudio(request: ProjectFactoryRequest): Promise<ProjectModuleInstance> {\n const clip = await request.resolveAsset('source');\n request.signal.throwIfAborted();\n if (!(clip instanceof AudioClip)) throw new TypeError('The audio-player source asset must resolve to an AudioClip.');\n const {context, record} = request;\n const player = new AudioClipPlayer(clip, {moduleContext: context});\n const volume = new ParamHandle({id: 'volume', unit: 'ratio', range: {min: 0, max: 1}, defaultValue: 1, modulation: 'none'}, {apply: value => player.setVolume(value)});\n const pan = new ParamHandle({id: 'pan', unit: 'ratio', range: {min: -1, max: 1}, defaultValue: 0, modulation: 'none'}, {apply: value => player.setPan(value)});\n const params = new ParamSurface([volume, pan]);\n let route: ConnectionLease | undefined;\n let registration: ConnectionLease | undefined;\n let participant: {release(): void} | undefined;\n let disposed = false;\n const module: ModuleHandle = {\n id: record.id, params,\n get inserts() { return player.insertChain; },\n getPort: name => name === 'output' ? player.peekOutputPort() : undefined,\n prepare: async () => {\n if (disposed) throw new Error('Project audio player has been disposed.');\n await player.preload();\n if (disposed) throw new Error('Project audio player preparation was cancelled.');\n if (!route) {\n const candidate = routeModuleOutput(context, module, player.outputPort);\n if (disposed || !candidate.active) { candidate.release(); throw new Error('Project audio player admission was cancelled.'); }\n route = candidate;\n }\n },\n };\n const dispose = () => {\n if (disposed) return;\n disposed = true;\n clean([() => participant?.release(), () => route?.release(), () => registration?.release(),\n () => volume.dispose(), () => pan.dispose(), () => player.dispose()]);\n };\n try {\n registration = context.registry.register(module);\n participant = context.session ? registerAudioParticipant(context.session, player, {\n offsetSeconds: number(record.config, 'offsetSeconds', 0), positionScale: number(record.config, 'positionScale', 1),\n prepare: () => module.prepare!(),\n }) : undefined;\n } catch (error) { try { dispose(); } catch { /* Preserve creation failure. */ } throw error; }\n return {module, ports: audioOutput, childContext: child => child.derive({id: child.id, target: module}),\n exportConfig: () => record.config, dispose};\n}\n\ninterface ProjectRackChannelState { volume?: number; muted?: boolean; solo?: boolean }\n\nfunction rackChannels(config: ProjectJsonObject): Record<string, ProjectRackChannelState> {\n const channels = config.channels ?? {};\n if (channels === null || typeof channels !== 'object' || Array.isArray(channels)) throw new TypeError('Rack channels must be an object keyed by stable module ID.');\n const result: Record<string, ProjectRackChannelState> = Object.create(null);\n for (const [id, value] of Object.entries(channels)) {\n if (!id.trim() || value === null || typeof value !== 'object' || Array.isArray(value)) throw new TypeError('Rack channel state requires a module ID and an object.');\n const fields = value as ProjectJsonObject;\n const state: ProjectRackChannelState = {};\n if (fields.volume !== undefined) {\n const volume = number(fields, 'volume', 1);\n if (volume < 0 || volume > 1) throw new RangeError('Rack channel volume must be in [0, 1].');\n state.volume = volume;\n }\n for (const key of ['muted', 'solo'] as const) {\n if (fields[key] !== undefined) {\n if (typeof fields[key] !== 'boolean') throw new TypeError(`Rack channel ${key} must be boolean.`);\n state[key] = fields[key];\n }\n }\n result[id] = state;\n }\n return result;\n}\n\nfunction createRack({context, record}: ProjectFactoryRequest): ProjectModuleInstance {\n const channels = rackChannels(record.config);\n const masterVolume = number(record.config, 'masterVolume', 1);\n if (masterVolume < 0 || masterVolume > 1) throw new RangeError('Rack masterVolume must be in [0, 1].');\n const rack = new ScoreRackModule(context, {id: record.id});\n try { rack.setMasterVolume(masterVolume); }\n catch (error) { rack.dispose(); throw error; }\n return {\n module: rack, ports: audioInsert, getInput: name => name === 'input' ? rack.input : undefined,\n childContext: child => child.derive({id: child.id, target: rack, admit: (module, port) => {\n const lease = rack.admit(module, port);\n try {\n const state = channels[module.id];\n if (state?.volume !== undefined) rack.setVolume(module.id, state.volume);\n if (state?.muted !== undefined) rack.mute(module.id, state.muted);\n if (state?.solo !== undefined) rack.solo(module.id, state.solo);\n if (!lease.active) throw new Error('Rack channel admission was cancelled.');\n return lease;\n } catch (error) { try { lease.release(); } catch { /* Preserve admission failure. */ } throw error; }\n }}),\n exportConfig: () => ({...record.config, masterVolume: rack.masterVolume,\n channels: {...Object.fromEntries(Object.entries(channels).map(([id, state]) => [id, {...state}])), ...Object.fromEntries(rack.list().map(channel => [channel.id, {volume: channel.volume, muted: channel.muted, solo: channel.solo}]))}}),\n dispose: () => rack.dispose(),\n };\n}\n\nfunction createInsert({context, record}: ProjectFactoryRequest, recipe: Effect): ProjectModuleInstance {\n let chain: InsertChain | undefined;\n let port: AudioOutputPort | undefined;\n let route: ConnectionLease | undefined;\n let disposed = false;\n let preparing = false;\n const module: ModuleHandle = {\n id: record.id,\n get params() { return chain?.instances[0]?.params; },\n get inserts() { return chain; },\n getPort: name => name === 'output' ? port : undefined,\n prepare: () => {\n if (disposed) throw new Error('Project insert has been disposed.');\n if (chain) return;\n if (preparing) throw new Error('Project insert preparation cannot re-enter.');\n preparing = true;\n let candidate: InsertChain | undefined;\n let candidateRoute: ConnectionLease | undefined;\n let candidatePort: AudioOutputPort | undefined;\n try {\n candidate = new InsertChain(context.audio.prepare());\n candidate.setSlot({id: 'effect', recipe});\n candidatePort = new AudioOutputPort(candidate.output, {id: `${record.id}:output`});\n candidateRoute = routeModuleOutput(context, module, candidatePort);\n if (disposed || !candidateRoute.active) throw new Error('Project insert admission was cancelled.');\n chain = candidate; port = candidatePort; route = candidateRoute;\n } catch (error) {\n try { candidateRoute?.release(); } catch { /* Preserve preparation failure. */ }\n try { candidatePort?.dispose(); } catch { /* Preserve preparation failure. */ }\n try { candidate?.dispose(); } catch { /* Preserve preparation failure. */ }\n throw error;\n } finally { preparing = false; }\n },\n };\n const registration = context.registry.register(module);\n return {\n module, ports: audioInsert, getInput: name => name === 'input' ? chain?.input : undefined,\n childContext: child => child.derive({id: child.id, target: module, admit: null, destination: () => chain?.input}),\n exportConfig: () => record.config,\n dispose: () => {\n if (disposed) return;\n disposed = true;\n clean([() => route?.release(), () => registration?.release(), () => port?.dispose(), () => chain?.dispose()]);\n },\n };\n}\n\nfunction createLfo({context, record}: ProjectFactoryRequest): ProjectModuleInstance {\n let lfo: SessionLFO | undefined;\n let params: ParamSurface | undefined;\n let disposed = false;\n let preparing = false;\n const module: ModuleHandle = {\n id: record.id,\n get params() { return params; },\n prepare: () => {\n if (disposed) throw new Error('Project LFO has been disposed.');\n if (lfo) return;\n if (preparing) throw new Error('Project LFO preparation cannot re-enter.');\n if (!context.session) throw new Error('A project LFO requires a Session.');\n const loop = record.config.loop ?? 'repeat';\n if (loop !== 'repeat' && loop !== 'once') throw new TypeError('LFO loop must be repeat or once.');\n preparing = true;\n try {\n const candidate = new SessionLFO(context.audio.prepare(), context.session.scheduling, {\n frequency: number(record.config, 'frequency', 1), phase: number(record.config, 'phase', 0),\n waveform: waveform(record.config.waveform), loop,\n });\n if (disposed) { candidate.dispose(); throw new Error('Project LFO preparation was cancelled.'); }\n lfo = candidate;\n params = new ParamSurface([lfo.frequency, lfo.phase]);\n } finally { preparing = false; }\n },\n };\n const registration = context.registry.register(module);\n return {\n module, ports: [{id: 'output', direction: 'output', kind: 'control'}],\n getControl: name => name === 'output' ? lfo?.signal : undefined,\n exportConfig: () => ({...record.config, waveform: lfo?.waveform ?? waveform(record.config.waveform)}),\n dispose: () => { if (disposed) return; disposed = true; clean([() => registration.release(), () => lfo?.dispose()]); },\n };\n}\n\nfunction effectRecipe(config: ProjectJsonObject): Effect {\n const options = config.options ?? {};\n if (options === null || typeof options !== 'object' || Array.isArray(options)) throw new TypeError('Effect options must be an object.');\n const values = options as ProjectJsonObject;\n const numeric = (keys: readonly string[]) => Object.fromEntries(keys.filter(key => values[key] !== undefined).map(key => [key, number(values, key, 0)]));\n switch (config.type) {\n case 'gain': return Effect.gain(number(values, 'gain', 1));\n case 'delay': return Effect.delay(numeric(['delaySeconds', 'feedback', 'wet', 'dry']));\n case 'compressor': return Effect.compressor(numeric(['threshold', 'knee', 'ratio', 'attack', 'release']));\n case 'reverb': return Effect.reverb(numeric(['seconds', 'decay', 'wet', 'dry']));\n case 'filter': {\n const type = values.type ?? 'lowpass';\n if (!['lowpass', 'highpass', 'bandpass', 'lowshelf', 'highshelf', 'peaking', 'notch', 'allpass'].includes(String(type))) throw new TypeError('Unsupported filter type.');\n return Effect.filter({...numeric(['frequency', 'Q', 'gain']), type: type as BiquadFilterType});\n }\n default: throw new TypeError('Unsupported project effect type.');\n }\n}\n\nfunction number(config: ProjectJsonObject, key: string, fallback: number): number {\n const value = config[key] ?? fallback;\n if (typeof value !== 'number' || !Number.isFinite(value)) throw new TypeError(`${key} must be a finite number.`);\n return value;\n}\n\nfunction waveform(value: unknown): Exclude<OscillatorType, 'custom'> {\n const accepted = value ?? 'sine';\n if (!['sine', 'square', 'sawtooth', 'triangle'].includes(String(accepted))) throw new TypeError('Unsupported oscillator waveform.');\n return accepted as Exclude<OscillatorType, 'custom'>;\n}\n\nfunction clean(callbacks: readonly (() => void)[]): void {\n let failure: unknown;\n for (const callback of callbacks) { try { callback(); } catch (error) { failure ??= error; } }\n if (failure !== undefined) throw failure;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAA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I,CAAC,CAAC,WAAW,YAAY,YAAY,YAAY,aAAa,WAAW,SAAS,SAAS,EAAE,SAAS,OAAO,IAAI,CAAC,EAAG,OAAM,IAAI,UAAU,0BAA0B;AACvK,aAAO,wBAAO,OAAO,EAAC,GAAG,QAAQ,CAAC,aAAa,KAAK,MAAM,CAAC,GAAG,KAA8B,CAAC;AAAA,IAC/F;AAAA,IACA;AAAS,YAAM,IAAI,UAAU,kCAAkC;AAAA,EACjE;AACF;AAEA,SAAS,OAAO,QAA2B,KAAa,UAA0B;AAChF,QAAM,QAAQ,OAAO,GAAG,KAAK;AAC7B,MAAI,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,EAAG,OAAM,IAAI,UAAU,GAAG,GAAG,2BAA2B;AAC/G,SAAO;AACT;AAEA,SAAS,SAAS,OAAmD;AACnE,QAAM,WAAW,SAAS;AAC1B,MAAI,CAAC,CAAC,QAAQ,UAAU,YAAY,UAAU,EAAE,SAAS,OAAO,QAAQ,CAAC,EAAG,OAAM,IAAI,UAAU,kCAAkC;AAClI,SAAO;AACT;AAEA,SAAS,MAAM,WAA0C;AACvD,MAAI;AACJ,aAAW,YAAY,WAAW;AAAE,QAAI;AAAE,eAAS;AAAA,IAAG,SAAS,OAAO;AAAE,4BAAY;AAAA,IAAO;AAAA,EAAE;AAC7F,MAAI,YAAY,OAAW,OAAM;AACnC;","names":["import_audio","import_headless","import_score","import_score","import_headless","import_audio","import_module","import_session","module"]}
@@ -0,0 +1,143 @@
1
+ import { TimeMap, Score } from '@webmusic/score';
2
+ import { BeatGrid, AudioClip } from '@webmusic/audio';
3
+ import { RenderOptions } from '@webmusic/score/play';
4
+ import { AudioPlayer, AudioClipPlayer } from '@webmusic/audio/play/headless';
5
+ import { ModuleContext, ModuleEnvironment, ProjectPluginFactory } from '@webmusic/kernel/module';
6
+ import { SessionTransport, ModuleSession, SessionParticipantLease } from '@webmusic/kernel/session';
7
+ import { HeadlessSynth, ScorePlayerModule, MidiAccessSource } from '@webmusic/score/play/headless';
8
+ import { TranscribedNote } from '@webmusic/audio/analyze/transcribe';
9
+
10
+ interface BeatGridFromTimeMapOptions {
11
+ /** How many quarters of the score timeline to sample. */
12
+ durationQuarters: number;
13
+ /** Beat subdivisions per quarter note (default 1: beat = quarter). */
14
+ beatsPerQuarter?: number;
15
+ /** Maximum number of beat samples to allocate. Default 1,000,000. */
16
+ maxBeats?: number;
17
+ }
18
+ declare const DEFAULT_MAX_MAPPED_BEATS = 1000000;
19
+ /**
20
+ * Sample a {@link TimeMap} into a {@link BeatGrid}: one beat per
21
+ * `1/beatsPerQuarter` quarter from 0 through `durationQuarters`. Lossless up
22
+ * to the sampling density — tempo changes between sampled beats interpolate
23
+ * linearly on the grid.
24
+ */
25
+ declare function beatGridFromTimeMap(map: TimeMap, options: BeatGridFromTimeMapOptions): BeatGrid;
26
+ /**
27
+ * Approximate a {@link TimeMap} from a {@link BeatGrid}: beat index becomes
28
+ * the quarter axis and every inter-beat interval one tempo segment. The
29
+ * grid's absolute offset is NOT representable (a TimeMap always maps quarter
30
+ * 0 to second 0) — align `grid.beats[0]` on the consumer side. Zero-length
31
+ * intervals are rejected: they would demand an infinite tempo.
32
+ */
33
+ declare function timeMapFromBeatGrid(grid: BeatGrid): TimeMap;
34
+
35
+ /**
36
+ * Render a score offline into an {@link AudioClip} — a Score→Audio conversion
37
+ * that stays a data function (DEC-068). A positive tail (the default) keeps
38
+ * final samples after the score ends; `tailSeconds: 0` ends with the score. A
39
+ * tempo override changes the clip's content axis relative to the score.
40
+ */
41
+ declare function renderScoreToClip(score: Score, options?: RenderOptions): Promise<AudioClip>;
42
+
43
+ interface CreateScoreAudioSessionOptions {
44
+ /** Borrowed context; without one the composition creates and owns a lazy one. */
45
+ context?: AudioContext;
46
+ /** Score synth; defaults to the oscillator. */
47
+ synth?: HeadlessSynth;
48
+ /** Session seconds → nominal Score seconds: `score = session * scale + offset`. */
49
+ scoreOffsetSeconds?: number;
50
+ scorePositionScale?: number;
51
+ /** Session seconds → clip seconds: `clip = session * scale + offset`. */
52
+ clipOffsetSeconds?: number;
53
+ clipPositionScale?: number;
54
+ /** Lead-in before a shared start, in seconds. */
55
+ leadInSeconds?: number;
56
+ onOperationError?: (operation: string, error: unknown) => void;
57
+ }
58
+ /** One Session conducting a Score engine and an Audio player (DEC-068). */
59
+ interface ScoreAudioSession {
60
+ /** The only command authority: play, pause, stop, seek, rate and loop go here. */
61
+ readonly session: SessionTransport;
62
+ readonly context: ModuleContext;
63
+ readonly scoreModule: ScorePlayerModule;
64
+ readonly clipPlayer: AudioPlayer;
65
+ /** Release both participants, their routes, the Session and an owned context. */
66
+ dispose(): void;
67
+ }
68
+ /**
69
+ * Compose a Score and an Audio clip under one Session — Bridge's replacement
70
+ * for the former master/follower sync family. Each engine is a Session
71
+ * participant with an explicit mapping from Session seconds into its own axis
72
+ * (`score-nominal-seconds`, `clip-seconds`); use `beatGridFromTimeMap` and
73
+ * `timeMapFromBeatGrid` to derive mappings between musical and audio time.
74
+ * Nothing is allocated until the Session prepares or plays.
75
+ */
76
+ declare function createScoreAudioSession(score: Score, clip: AudioClip, options?: CreateScoreAudioSessionOptions): ScoreAudioSession;
77
+
78
+ /** The engine surface a participant adapter needs; `AudioPlayer` and `AudioClipPlayer` both provide it. */
79
+ type AudioParticipantPlayer = Pick<AudioClipPlayer, 'play' | 'pause' | 'stop' | 'seek' | 'setRate' | 'seconds' | 'playing' | 'clock' | 'duration' | 'activateScheduling' | 'attachScheduling' | 'timingCapabilities'>;
80
+ interface AudioParticipantOptions {
81
+ offsetSeconds?: number;
82
+ positionScale?: number;
83
+ /** Prepare and route the player's output before the Session anchors a start. */
84
+ prepare: () => void | Promise<void>;
85
+ }
86
+ /**
87
+ * Register a Headless Audio engine with a Session on the `clip-seconds` axis —
88
+ * the same axis `<audio-player>` uses, so Score and Audio mappings agree
89
+ * (DEC-068). Native buffer playback attaches and activates the shared
90
+ * scheduling anchor; other engines (document sequences, media streams,
91
+ * borrowed queues) are commanded by the Session without activation.
92
+ */
93
+ declare function registerAudioParticipant(session: ModuleSession, player: AudioParticipantPlayer, options: AudioParticipantOptions): SessionParticipantLease;
94
+
95
+ interface ScoreFromTranscriptionOptions {
96
+ /** Tempo of the produced score. Default 120 (pass the transcriber's bpm). */
97
+ bpm?: number;
98
+ /** Time signature. Default 4/4. */
99
+ timeSignature?: {
100
+ numerator: number;
101
+ denominator: number;
102
+ };
103
+ /**
104
+ * Notation grid in subdivisions per quarter note: onsets/durations snap to
105
+ * `1/grid` quarters and durations never collapse below one grid unit.
106
+ * Default 4 (sixteenth notes). Pass 0 to keep exact (unquantized) values
107
+ * on the 1/480 tick grid.
108
+ */
109
+ quantizeGrid?: number;
110
+ /** Score title. Default 'Transcription'. */
111
+ title?: string;
112
+ /** Part name. Default 'Transcribed'. */
113
+ partName?: string;
114
+ /** Maximum number of input note events to process. Default 100,000. */
115
+ maxNotes?: number;
116
+ /** Maximum number of measures to materialize. Default 4,096. */
117
+ maxMeasures?: number;
118
+ }
119
+ declare const DEFAULT_MAX_TRANSCRIPTION_NOTES = 100000;
120
+ declare const DEFAULT_MAX_TRANSCRIPTION_MEASURES = 4096;
121
+ /**
122
+ * Assemble a Score from transcribed note events. Notes with a MIDI pitch
123
+ * outside [0, 127] are skipped (transcription noise); velocities clamp into
124
+ * the 1..127 MIDI range; measures are laid out to cover the material.
125
+ */
126
+ declare function scoreFromTranscription(notes: readonly TranscribedNote[], options?: ScoreFromTranscriptionOptions): Score;
127
+
128
+ interface WebMusicProjectPluginOptions {
129
+ /** Where printing, script output and module failures go, and the clock for timed messages; see Kernel's `ModuleEnvironment`. */
130
+ readonly modules?: ModuleEnvironment;
131
+ /** Web MIDI for the MIDI modules; one is made when omitted, and asks for access only when a module needs a device. */
132
+ readonly midi?: MidiAccessSource;
133
+ }
134
+ /**
135
+ * The standard set (DEC-097): the Bridge's own players, rack, bus, effect and
136
+ * LFO, which need both domains, with the module types each package registers
137
+ * — Kernel's message, structure and sequence modules, Score's MIDI and sound
138
+ * modules, and Audio's buffer modules. Trusted, explicit factories; asset
139
+ * resolution and storage remain application responsibilities.
140
+ */
141
+ declare function createWebMusicProjectPlugins(options?: WebMusicProjectPluginOptions): readonly ProjectPluginFactory[];
142
+
143
+ export { type AudioParticipantOptions, type AudioParticipantPlayer, type BeatGridFromTimeMapOptions, type CreateScoreAudioSessionOptions, DEFAULT_MAX_MAPPED_BEATS, DEFAULT_MAX_TRANSCRIPTION_MEASURES, DEFAULT_MAX_TRANSCRIPTION_NOTES, type ScoreAudioSession, type ScoreFromTranscriptionOptions, type WebMusicProjectPluginOptions, beatGridFromTimeMap, createScoreAudioSession, createWebMusicProjectPlugins, registerAudioParticipant, renderScoreToClip, scoreFromTranscription, timeMapFromBeatGrid };
@@ -0,0 +1,143 @@
1
+ import { TimeMap, Score } from '@webmusic/score';
2
+ import { BeatGrid, AudioClip } from '@webmusic/audio';
3
+ import { RenderOptions } from '@webmusic/score/play';
4
+ import { AudioPlayer, AudioClipPlayer } from '@webmusic/audio/play/headless';
5
+ import { ModuleContext, ModuleEnvironment, ProjectPluginFactory } from '@webmusic/kernel/module';
6
+ import { SessionTransport, ModuleSession, SessionParticipantLease } from '@webmusic/kernel/session';
7
+ import { HeadlessSynth, ScorePlayerModule, MidiAccessSource } from '@webmusic/score/play/headless';
8
+ import { TranscribedNote } from '@webmusic/audio/analyze/transcribe';
9
+
10
+ interface BeatGridFromTimeMapOptions {
11
+ /** How many quarters of the score timeline to sample. */
12
+ durationQuarters: number;
13
+ /** Beat subdivisions per quarter note (default 1: beat = quarter). */
14
+ beatsPerQuarter?: number;
15
+ /** Maximum number of beat samples to allocate. Default 1,000,000. */
16
+ maxBeats?: number;
17
+ }
18
+ declare const DEFAULT_MAX_MAPPED_BEATS = 1000000;
19
+ /**
20
+ * Sample a {@link TimeMap} into a {@link BeatGrid}: one beat per
21
+ * `1/beatsPerQuarter` quarter from 0 through `durationQuarters`. Lossless up
22
+ * to the sampling density — tempo changes between sampled beats interpolate
23
+ * linearly on the grid.
24
+ */
25
+ declare function beatGridFromTimeMap(map: TimeMap, options: BeatGridFromTimeMapOptions): BeatGrid;
26
+ /**
27
+ * Approximate a {@link TimeMap} from a {@link BeatGrid}: beat index becomes
28
+ * the quarter axis and every inter-beat interval one tempo segment. The
29
+ * grid's absolute offset is NOT representable (a TimeMap always maps quarter
30
+ * 0 to second 0) — align `grid.beats[0]` on the consumer side. Zero-length
31
+ * intervals are rejected: they would demand an infinite tempo.
32
+ */
33
+ declare function timeMapFromBeatGrid(grid: BeatGrid): TimeMap;
34
+
35
+ /**
36
+ * Render a score offline into an {@link AudioClip} — a Score→Audio conversion
37
+ * that stays a data function (DEC-068). A positive tail (the default) keeps
38
+ * final samples after the score ends; `tailSeconds: 0` ends with the score. A
39
+ * tempo override changes the clip's content axis relative to the score.
40
+ */
41
+ declare function renderScoreToClip(score: Score, options?: RenderOptions): Promise<AudioClip>;
42
+
43
+ interface CreateScoreAudioSessionOptions {
44
+ /** Borrowed context; without one the composition creates and owns a lazy one. */
45
+ context?: AudioContext;
46
+ /** Score synth; defaults to the oscillator. */
47
+ synth?: HeadlessSynth;
48
+ /** Session seconds → nominal Score seconds: `score = session * scale + offset`. */
49
+ scoreOffsetSeconds?: number;
50
+ scorePositionScale?: number;
51
+ /** Session seconds → clip seconds: `clip = session * scale + offset`. */
52
+ clipOffsetSeconds?: number;
53
+ clipPositionScale?: number;
54
+ /** Lead-in before a shared start, in seconds. */
55
+ leadInSeconds?: number;
56
+ onOperationError?: (operation: string, error: unknown) => void;
57
+ }
58
+ /** One Session conducting a Score engine and an Audio player (DEC-068). */
59
+ interface ScoreAudioSession {
60
+ /** The only command authority: play, pause, stop, seek, rate and loop go here. */
61
+ readonly session: SessionTransport;
62
+ readonly context: ModuleContext;
63
+ readonly scoreModule: ScorePlayerModule;
64
+ readonly clipPlayer: AudioPlayer;
65
+ /** Release both participants, their routes, the Session and an owned context. */
66
+ dispose(): void;
67
+ }
68
+ /**
69
+ * Compose a Score and an Audio clip under one Session — Bridge's replacement
70
+ * for the former master/follower sync family. Each engine is a Session
71
+ * participant with an explicit mapping from Session seconds into its own axis
72
+ * (`score-nominal-seconds`, `clip-seconds`); use `beatGridFromTimeMap` and
73
+ * `timeMapFromBeatGrid` to derive mappings between musical and audio time.
74
+ * Nothing is allocated until the Session prepares or plays.
75
+ */
76
+ declare function createScoreAudioSession(score: Score, clip: AudioClip, options?: CreateScoreAudioSessionOptions): ScoreAudioSession;
77
+
78
+ /** The engine surface a participant adapter needs; `AudioPlayer` and `AudioClipPlayer` both provide it. */
79
+ type AudioParticipantPlayer = Pick<AudioClipPlayer, 'play' | 'pause' | 'stop' | 'seek' | 'setRate' | 'seconds' | 'playing' | 'clock' | 'duration' | 'activateScheduling' | 'attachScheduling' | 'timingCapabilities'>;
80
+ interface AudioParticipantOptions {
81
+ offsetSeconds?: number;
82
+ positionScale?: number;
83
+ /** Prepare and route the player's output before the Session anchors a start. */
84
+ prepare: () => void | Promise<void>;
85
+ }
86
+ /**
87
+ * Register a Headless Audio engine with a Session on the `clip-seconds` axis —
88
+ * the same axis `<audio-player>` uses, so Score and Audio mappings agree
89
+ * (DEC-068). Native buffer playback attaches and activates the shared
90
+ * scheduling anchor; other engines (document sequences, media streams,
91
+ * borrowed queues) are commanded by the Session without activation.
92
+ */
93
+ declare function registerAudioParticipant(session: ModuleSession, player: AudioParticipantPlayer, options: AudioParticipantOptions): SessionParticipantLease;
94
+
95
+ interface ScoreFromTranscriptionOptions {
96
+ /** Tempo of the produced score. Default 120 (pass the transcriber's bpm). */
97
+ bpm?: number;
98
+ /** Time signature. Default 4/4. */
99
+ timeSignature?: {
100
+ numerator: number;
101
+ denominator: number;
102
+ };
103
+ /**
104
+ * Notation grid in subdivisions per quarter note: onsets/durations snap to
105
+ * `1/grid` quarters and durations never collapse below one grid unit.
106
+ * Default 4 (sixteenth notes). Pass 0 to keep exact (unquantized) values
107
+ * on the 1/480 tick grid.
108
+ */
109
+ quantizeGrid?: number;
110
+ /** Score title. Default 'Transcription'. */
111
+ title?: string;
112
+ /** Part name. Default 'Transcribed'. */
113
+ partName?: string;
114
+ /** Maximum number of input note events to process. Default 100,000. */
115
+ maxNotes?: number;
116
+ /** Maximum number of measures to materialize. Default 4,096. */
117
+ maxMeasures?: number;
118
+ }
119
+ declare const DEFAULT_MAX_TRANSCRIPTION_NOTES = 100000;
120
+ declare const DEFAULT_MAX_TRANSCRIPTION_MEASURES = 4096;
121
+ /**
122
+ * Assemble a Score from transcribed note events. Notes with a MIDI pitch
123
+ * outside [0, 127] are skipped (transcription noise); velocities clamp into
124
+ * the 1..127 MIDI range; measures are laid out to cover the material.
125
+ */
126
+ declare function scoreFromTranscription(notes: readonly TranscribedNote[], options?: ScoreFromTranscriptionOptions): Score;
127
+
128
+ interface WebMusicProjectPluginOptions {
129
+ /** Where printing, script output and module failures go, and the clock for timed messages; see Kernel's `ModuleEnvironment`. */
130
+ readonly modules?: ModuleEnvironment;
131
+ /** Web MIDI for the MIDI modules; one is made when omitted, and asks for access only when a module needs a device. */
132
+ readonly midi?: MidiAccessSource;
133
+ }
134
+ /**
135
+ * The standard set (DEC-097): the Bridge's own players, rack, bus, effect and
136
+ * LFO, which need both domains, with the module types each package registers
137
+ * — Kernel's message, structure and sequence modules, Score's MIDI and sound
138
+ * modules, and Audio's buffer modules. Trusted, explicit factories; asset
139
+ * resolution and storage remain application responsibilities.
140
+ */
141
+ declare function createWebMusicProjectPlugins(options?: WebMusicProjectPluginOptions): readonly ProjectPluginFactory[];
142
+
143
+ export { type AudioParticipantOptions, type AudioParticipantPlayer, type BeatGridFromTimeMapOptions, type CreateScoreAudioSessionOptions, DEFAULT_MAX_MAPPED_BEATS, DEFAULT_MAX_TRANSCRIPTION_MEASURES, DEFAULT_MAX_TRANSCRIPTION_NOTES, type ScoreAudioSession, type ScoreFromTranscriptionOptions, type WebMusicProjectPluginOptions, beatGridFromTimeMap, createScoreAudioSession, createWebMusicProjectPlugins, registerAudioParticipant, renderScoreToClip, scoreFromTranscription, timeMapFromBeatGrid };