@webmusic/kernel 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +46 -48
- package/dist/build-receipt.json +3 -3
- package/dist/{chunk-JNXB74G3.cjs → chunk-54JYWB5X.cjs} +104 -40
- package/dist/chunk-54JYWB5X.cjs.map +1 -0
- package/dist/{chunk-XBJBY4J5.js → chunk-ON64FRCF.js} +98 -34
- package/dist/chunk-ON64FRCF.js.map +1 -0
- package/dist/{chunk-HOKRTYPV.js → chunk-OPBHDUZK.js} +39 -1
- package/dist/chunk-OPBHDUZK.js.map +1 -0
- package/dist/{chunk-HZQX4J2J.cjs → chunk-WOPW6WLR.cjs} +40 -2
- package/dist/chunk-WOPW6WLR.cjs.map +1 -0
- package/dist/index.cjs +3 -3
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +2 -2
- package/dist/meter.cjs +2 -2
- package/dist/meter.d.cts +9 -1
- package/dist/meter.d.ts +9 -1
- package/dist/meter.js +1 -1
- package/dist/sync.cjs +2 -2
- package/dist/sync.d.cts +9 -6
- package/dist/sync.d.ts +9 -6
- package/dist/sync.js +1 -1
- package/package.json +3 -3
- package/dist/chunk-HOKRTYPV.js.map +0 -1
- package/dist/chunk-HZQX4J2J.cjs.map +0 -1
- package/dist/chunk-JNXB74G3.cjs.map +0 -1
- package/dist/chunk-XBJBY4J5.js.map +0 -1
package/dist/sync.d.ts
CHANGED
|
@@ -90,7 +90,8 @@ interface TransportGroupOptions {
|
|
|
90
90
|
leadInSeconds?: number;
|
|
91
91
|
/** Re-join a follower when |follower − expected| exceeds this. Default 0.03 s. */
|
|
92
92
|
driftToleranceSeconds?: number;
|
|
93
|
-
/** Drift check cadence. Default 250 ms. 0 disables
|
|
93
|
+
/** Drift check cadence. Default 250 ms. 0 disables follower drift checks;
|
|
94
|
+
* the playback watcher still detects natural master stops and loop ends. */
|
|
94
95
|
driftCheckIntervalMs?: number;
|
|
95
96
|
/** Loop region on the master axis; also settable live via {@link TransportGroup.setLoop}. */
|
|
96
97
|
loop?: SyncLoopRegion | null;
|
|
@@ -272,12 +273,14 @@ interface ClocklessMasterTransport {
|
|
|
272
273
|
* Adapts a transport WITHOUT a readable clock into the required-clock
|
|
273
274
|
* master role by dead-reckoning a mirror TransportClock across the command
|
|
274
275
|
* surface, and reconciling the reckoning against the transport's actual
|
|
275
|
-
* position
|
|
276
|
+
* position at drift checks or periodic lifecycle samples when follower drift
|
|
277
|
+
* checks are disabled:
|
|
276
278
|
*
|
|
277
|
-
* -
|
|
278
|
-
*
|
|
279
|
-
*
|
|
280
|
-
*
|
|
279
|
+
* - after observed forward motion establishes the position's reported step,
|
|
280
|
+
* a longer stationary interval can indicate that the transport stopped
|
|
281
|
+
* on its own. The adapter then pauses the mirror and reports 'stalled'.
|
|
282
|
+
* Without prior motion, repeated positions alone are inconclusive and
|
|
283
|
+
* the adapter leaves the transport running;
|
|
281
284
|
* - a moving transport that diverged from the extrapolation (refused or
|
|
282
285
|
* clamped rate, tempo automation) re-anchors the mirror so drift is
|
|
283
286
|
* measured against the transport, not the reckoning.
|
package/dist/sync.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webmusic/kernel",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Domain-neutral WebMusic contracts and utilities for events, elements, workers, metering and synchronized playback.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -129,13 +129,13 @@
|
|
|
129
129
|
"devDependencies": {
|
|
130
130
|
"tsup": "^8.5.0",
|
|
131
131
|
"typescript": "^5.4.0",
|
|
132
|
-
"vitest": "^
|
|
132
|
+
"vitest": "^5.0.0"
|
|
133
133
|
},
|
|
134
134
|
"license": "MIT",
|
|
135
135
|
"publishConfig": {
|
|
136
136
|
"access": "public"
|
|
137
137
|
},
|
|
138
|
-
"author": "
|
|
138
|
+
"author": "Koperative",
|
|
139
139
|
"engines": {
|
|
140
140
|
"node": ">=22"
|
|
141
141
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/meter.ts"],"sourcesContent":["// ============================================================================\n// Analyser metering shared by both families' level meters: a transparent\n// `input -> analyser -> output` tap plus the byte-domain level and spectrum\n// maths that read it. Numbers and Web Audio nodes only — no score, no clip,\n// no presenter, and nothing here decides WHEN to read a frame (a framework,\n// canvas renderer or presenter drives that).\n//\n// Extracted because both families had grown their own copy of the same tap\n// and the same RMS / peak-hold / bar-aggregation arithmetic, and the copies\n// had begun to drift. Per-family differences that are genuinely editorial —\n// the minimum bar count, the frame shape each family publishes, whether a\n// failing disconnect is swallowed — stay with the families; only the\n// mechanism lives here.\n// ============================================================================\n\n/** One time-domain reading, before a family decides what to publish. */\nexport interface AnalyserMeterFrame {\n /** Raw root-mean-square of the frame, unscaled and unclamped. */\n rms: number;\n /** `rms` scaled by `levelScale` and clamped to [0, 1] — the display value. */\n level: number;\n /** Instantaneous sample peak, scaled and clamped the same way. */\n peak: number;\n /** Decaying peak hold: `max(level, previousHold - peakDecay)`. */\n peakHold: number;\n}\n\nexport interface SpectrumBarOptions {\n /** Requested bar count, floored to a positive integer. Non-finite values use the default 28. */\n bars?: number;\n /** Floor applied to the requested count. Floored to an integer >= 1; non-finite values use 1. */\n minimumBars?: number;\n /** Treat the input as byte FFT data (0..255) and scale to [0, 1]. Default true. */\n normalizeBytes?: boolean;\n}\n\nexport interface AnalyserMeterOptions {\n /** Build and own a transparent `input -> analyser -> output` tap. */\n context?: BaseAudioContext;\n /** Borrow an existing analyser. It is never connected or disconnected. */\n analyser?: AnalyserNode;\n /** FFT size assigned to an owned analyser. Default 1024. */\n fftSize?: number;\n /** Smoothing assigned to an owned analyser. Default 0.8. */\n smoothingTimeConstant?: number;\n /** Gain applied to RMS and peak for the display values. Default 1.8. */\n levelScale?: number;\n /** Absolute peak-hold decay applied on every read. Default 0.012. */\n peakDecay?: number;\n /** Floor applied to {@link AnalyserMeter.readSpectrum}'s bar count; non-finite values use 1. */\n minimumBars?: number;\n}\n\n/**\n * Aggregate an FFT vector into a fixed number of normalized bars. Each bar is\n * the mean of its contiguous slice. When there are at least as many bins as\n * bars, the slices tile the input exactly. When there are fewer bins than\n * bars, bins are repeated to fill the requested display width.\n */\nexport function aggregateSpectrumBars(\n spectrum: ArrayLike<number>,\n options: SpectrumBarOptions = {},\n): Float32Array {\n const minimum = positiveBarCount(options.minimumBars, 1);\n const barCount = Math.max(minimum, positiveBarCount(options.bars, 28));\n const result = new Float32Array(barCount);\n if (spectrum.length === 0) return result;\n const byteScale = options.normalizeBytes ?? true;\n for (let bar = 0; bar < barCount; bar += 1) {\n const start = Math.floor((bar * spectrum.length) / barCount);\n const end = Math.max(start + 1, Math.floor(((bar + 1) * spectrum.length) / barCount));\n let sum = 0;\n let count = 0;\n for (let index = start; index < end && index < spectrum.length; index += 1) {\n const raw = spectrum[index];\n sum += (Number.isFinite(raw) ? raw : 0) / (byteScale ? 255 : 1);\n count += 1;\n }\n result[bar] = clamp(count > 0 ? sum / count : 0, 0, 1);\n }\n return result;\n}\n\n/**\n * Live analyser meter.\n *\n * Supplying `context` creates an owned pass-through tap; supplying `analyser`\n * borrows that node. The two modes are mutually exclusive so resource\n * ownership is never ambiguous.\n */\nexport class AnalyserMeter {\n readonly #levelScale: number;\n readonly #peakDecay: number;\n readonly #minimumBars: number;\n #analyser?: AnalyserNode;\n #input?: GainNode;\n #output?: GainNode;\n #ownsGraph = false;\n #disposed = false;\n #timeBuffer?: Uint8Array<ArrayBuffer>;\n #frequencyBuffer?: Uint8Array<ArrayBuffer>;\n #peakHold = 0;\n\n constructor(options: AnalyserMeterOptions = {}) {\n if (options.context && options.analyser) {\n throw new TypeError('AnalyserMeter accepts either context or analyser, not both');\n }\n this.#levelScale = finiteNonNegative(options.levelScale, 1.8);\n this.#peakDecay = finiteNonNegative(options.peakDecay, 0.012);\n this.#minimumBars = positiveBarCount(options.minimumBars, 1);\n\n if (options.analyser) this.#analyser = options.analyser;\n else if (options.context) this.#buildOwnedGraph(options.context, options);\n }\n\n /** The owned or borrowed analyser currently read. */\n get analyser(): AnalyserNode | undefined {\n return this.#analyser;\n }\n\n /** Input of an owned tap; absent when borrowing an analyser. */\n get input(): AudioNode | undefined {\n return this.#input;\n }\n\n /** Output of an owned tap; absent when borrowing an analyser. */\n get output(): AudioNode | undefined {\n return this.#output;\n }\n\n /** Whether this meter created and owns its tap graph. */\n get ownsGraph(): boolean {\n return this.#ownsGraph;\n }\n\n /** Read one time-domain frame and derive its level, peak and peak hold. */\n readLevel(): AnalyserMeterFrame {\n const analyser = this.#assertReadable();\n const length = Math.max(1, analyser.fftSize);\n if (!this.#timeBuffer || this.#timeBuffer.length !== length) {\n this.#timeBuffer = new Uint8Array(new ArrayBuffer(length));\n }\n analyser.getByteTimeDomainData(this.#timeBuffer);\n\n let sumSquares = 0;\n let samplePeak = 0;\n for (let index = 0; index < length; index += 1) {\n const sample = ((this.#timeBuffer[index] ?? 128) - 128) / 128;\n sumSquares += sample * sample;\n samplePeak = Math.max(samplePeak, Math.abs(sample));\n }\n const rms = Math.sqrt(sumSquares / length);\n const level = clamp(rms * this.#levelScale, 0, 1);\n const peak = clamp(samplePeak * this.#levelScale, 0, 1);\n this.#peakHold = Math.max(level, this.#peakHold - this.#peakDecay);\n return {rms, level, peak, peakHold: this.#peakHold};\n }\n\n /** Read one frequency-domain frame, aggregated into normalized bars. */\n readSpectrum(bars = 28): Float32Array {\n const analyser = this.#assertReadable();\n const length = Math.max(1, analyser.frequencyBinCount);\n if (!this.#frequencyBuffer || this.#frequencyBuffer.length !== length) {\n this.#frequencyBuffer = new Uint8Array(new ArrayBuffer(length));\n }\n analyser.getByteFrequencyData(this.#frequencyBuffer);\n return aggregateSpectrumBars(this.#frequencyBuffer, {\n bars,\n minimumBars: this.#minimumBars,\n normalizeBytes: true,\n });\n }\n\n /**\n * Release an owned graph; a borrowed analyser is never disconnected. Every\n * owned node is attempted even when an earlier disconnect throws, and the\n * meter has reached its disposed state before the first error is rethrown.\n * Repeated calls are safe.\n */\n dispose(): void {\n if (this.#disposed) return;\n this.#disposed = true;\n const analyser = this.#analyser;\n const input = this.#input;\n const output = this.#output;\n const ownsGraph = this.#ownsGraph;\n\n this.#analyser = undefined;\n this.#input = undefined;\n this.#output = undefined;\n this.#ownsGraph = false;\n this.#timeBuffer = undefined;\n this.#frequencyBuffer = undefined;\n this.#peakHold = 0;\n\n if (!ownsGraph) return;\n let failed = false;\n let firstError: unknown;\n for (const node of [input, analyser, output]) {\n try {\n node?.disconnect();\n } catch (error) {\n if (!failed) firstError = error;\n failed = true;\n }\n }\n if (failed) throw firstError;\n }\n\n #buildOwnedGraph(context: BaseAudioContext, options: AnalyserMeterOptions): void {\n let input: GainNode | undefined;\n let output: GainNode | undefined;\n let analyser: AnalyserNode | undefined;\n try {\n input = context.createGain();\n output = context.createGain();\n analyser = context.createAnalyser();\n analyser.fftSize = options.fftSize ?? 1024;\n analyser.smoothingTimeConstant = options.smoothingTimeConstant ?? 0.8;\n input.connect(analyser);\n analyser.connect(output);\n } catch (error) {\n for (const node of [input, analyser, output]) {\n try {\n node?.disconnect();\n } catch {\n // Preserve the construction failure after a best-effort rollback.\n }\n }\n throw error;\n }\n this.#input = input;\n this.#output = output;\n this.#analyser = analyser;\n this.#ownsGraph = true;\n }\n\n #assertReadable(): AnalyserNode {\n if (this.#disposed) throw new Error('AnalyserMeter has been disposed');\n if (!this.#analyser) throw new Error('AnalyserMeter has no analyser');\n return this.#analyser;\n }\n}\n\n/** Build an {@link AnalyserMeter} (the `createX` convention). */\nexport function createAnalyserMeter(options?: AnalyserMeterOptions): AnalyserMeter {\n return new AnalyserMeter(options);\n}\n\nfunction finiteNonNegative(value: number | undefined, fallback: number): number {\n return value === undefined || !Number.isFinite(value) ? fallback : Math.max(0, value);\n}\n\nfunction positiveBarCount(value: number | undefined, fallback: number): number {\n return Math.max(1, Math.floor(finiteNonNegative(value, fallback)));\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n"],"mappings":";;;;;;;;AA2DO,SAAS,sBACd,UACA,UAA8B,CAAC,GACjB;AACd,QAAM,UAAU,iBAAiB,QAAQ,aAAa,CAAC;AACvD,QAAM,WAAW,KAAK,IAAI,SAAS,iBAAiB,QAAQ,MAAM,EAAE,CAAC;AACrE,QAAM,SAAS,IAAI,aAAa,QAAQ;AACxC,MAAI,SAAS,WAAW,EAAG,QAAO;AAClC,QAAM,YAAY,QAAQ,kBAAkB;AAC5C,WAAS,MAAM,GAAG,MAAM,UAAU,OAAO,GAAG;AAC1C,UAAM,QAAQ,KAAK,MAAO,MAAM,SAAS,SAAU,QAAQ;AAC3D,UAAM,MAAM,KAAK,IAAI,QAAQ,GAAG,KAAK,OAAQ,MAAM,KAAK,SAAS,SAAU,QAAQ,CAAC;AACpF,QAAI,MAAM;AACV,QAAI,QAAQ;AACZ,aAAS,QAAQ,OAAO,QAAQ,OAAO,QAAQ,SAAS,QAAQ,SAAS,GAAG;AAC1E,YAAM,MAAM,SAAS,KAAK;AAC1B,cAAQ,OAAO,SAAS,GAAG,IAAI,MAAM,MAAM,YAAY,MAAM;AAC7D,eAAS;AAAA,IACX;AACA,WAAO,GAAG,IAAI,MAAM,QAAQ,IAAI,MAAM,QAAQ,GAAG,GAAG,CAAC;AAAA,EACvD;AACA,SAAO;AACT;AAjFA;AA0FO,IAAM,gBAAN,MAAoB;AAAA,EAazB,YAAY,UAAgC,CAAC,GAAG;AAb3C;AACL,uBAAS;AACT,uBAAS;AACT,uBAAS;AACT;AACA;AACA;AACA,mCAAa;AACb,kCAAY;AACZ;AACA;AACA,kCAAY;AAGV,QAAI,QAAQ,WAAW,QAAQ,UAAU;AACvC,YAAM,IAAI,UAAU,4DAA4D;AAAA,IAClF;AACA,uBAAK,aAAc,kBAAkB,QAAQ,YAAY,G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,EAAY,QAAA,CAAA;AACjB,EAAA,4CAAA,IAAA,EAAK,UAAA,EAAa,IAAA,CAAA;AACpB,CAAA;AAEA,kBAAA,EAAe,QAAA,CAAA,EAAiB;AAC9B,EAAA,GAAA,CAAI,4CAAA,IAAA,EAAK,SAAA,CAAA,EAAW,MAAM,IAAI,KAAA,CAAM,iCAAiC,CAAA;AACrE,EAAA,GAAA,CAAI,CAAC,4CAAA,IAAA,EAAK,SAAA,CAAA,EAAW,MAAM,IAAI,KAAA,CAAM,+BAA+B,CAAA;AACpE,EAAA,OAAO,4CAAA,IAAA,EAAK,SAAA,CAAA;AACd,CAAA;AAIK,SAAS,mBAAA,CAAoB,OAAA,EAA+C;AACjF,EAAA,OAAO,IAAI,aAAA,CAAc,OAAO,CAAA;AAClC;AAEA,SAAS,iBAAA,CAAkB,KAAA,EAA2B,QAAA,EAA0B;AAC9E,EAAA,OAAO,MAAA,IAAU,KAAA,EAAA,GAAa,CAAC,MAAA,CAAO,QAAA,CAAS,KAAK,EAAA,EAAI,SAAA,EAAW,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,KAAK,CAAA;AACtF;AAEA,SAAS,gBAAA,CAAiB,KAAA,EAA2B,QAAA,EAA0B;AAC7E,EAAA,OAAO,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,IAAA,CAAK,KAAA,CAAM,iBAAA,CAAkB,KAAA,EAAO,QAAQ,CAAC,CAAC,CAAA;AACnE;AAEA,SAAS,KAAA,CAAM,KAAA,EAAe,GAAA,EAAa,GAAA,EAAqB;AAC9D,EAAA,OAAO,IAAA,CAAK,GAAA,CAAI,GAAA,EAAK,IAAA,CAAK,GAAA,CAAI,GAAA,EAAK,KAAK,CAAC,CAAA;AAC3C;ADnEA;AACA;AACE;AACA;AACA;AACF,gJAAC","file":"/Users/mamingchen/GitHub/public/WebMusic/platform/kernel/dist/chunk-HZQX4J2J.cjs","sourcesContent":[null,"// ============================================================================\n// Analyser metering shared by both families' level meters: a transparent\n// `input -> analyser -> output` tap plus the byte-domain level and spectrum\n// maths that read it. Numbers and Web Audio nodes only — no score, no clip,\n// no presenter, and nothing here decides WHEN to read a frame (a framework,\n// canvas renderer or presenter drives that).\n//\n// Extracted because both families had grown their own copy of the same tap\n// and the same RMS / peak-hold / bar-aggregation arithmetic, and the copies\n// had begun to drift. Per-family differences that are genuinely editorial —\n// the minimum bar count, the frame shape each family publishes, whether a\n// failing disconnect is swallowed — stay with the families; only the\n// mechanism lives here.\n// ============================================================================\n\n/** One time-domain reading, before a family decides what to publish. */\nexport interface AnalyserMeterFrame {\n /** Raw root-mean-square of the frame, unscaled and unclamped. */\n rms: number;\n /** `rms` scaled by `levelScale` and clamped to [0, 1] — the display value. */\n level: number;\n /** Instantaneous sample peak, scaled and clamped the same way. */\n peak: number;\n /** Decaying peak hold: `max(level, previousHold - peakDecay)`. */\n peakHold: number;\n}\n\nexport interface SpectrumBarOptions {\n /** Requested bar count, floored to a positive integer. Non-finite values use the default 28. */\n bars?: number;\n /** Floor applied to the requested count. Floored to an integer >= 1; non-finite values use 1. */\n minimumBars?: number;\n /** Treat the input as byte FFT data (0..255) and scale to [0, 1]. Default true. */\n normalizeBytes?: boolean;\n}\n\nexport interface AnalyserMeterOptions {\n /** Build and own a transparent `input -> analyser -> output` tap. */\n context?: BaseAudioContext;\n /** Borrow an existing analyser. It is never connected or disconnected. */\n analyser?: AnalyserNode;\n /** FFT size assigned to an owned analyser. Default 1024. */\n fftSize?: number;\n /** Smoothing assigned to an owned analyser. Default 0.8. */\n smoothingTimeConstant?: number;\n /** Gain applied to RMS and peak for the display values. Default 1.8. */\n levelScale?: number;\n /** Absolute peak-hold decay applied on every read. Default 0.012. */\n peakDecay?: number;\n /** Floor applied to {@link AnalyserMeter.readSpectrum}'s bar count; non-finite values use 1. */\n minimumBars?: number;\n}\n\n/**\n * Aggregate an FFT vector into a fixed number of normalized bars. Each bar is\n * the mean of its contiguous slice. When there are at least as many bins as\n * bars, the slices tile the input exactly. When there are fewer bins than\n * bars, bins are repeated to fill the requested display width.\n */\nexport function aggregateSpectrumBars(\n spectrum: ArrayLike<number>,\n options: SpectrumBarOptions = {},\n): Float32Array {\n const minimum = positiveBarCount(options.minimumBars, 1);\n const barCount = Math.max(minimum, positiveBarCount(options.bars, 28));\n const result = new Float32Array(barCount);\n if (spectrum.length === 0) return result;\n const byteScale = options.normalizeBytes ?? true;\n for (let bar = 0; bar < barCount; bar += 1) {\n const start = Math.floor((bar * spectrum.length) / barCount);\n const end = Math.max(start + 1, Math.floor(((bar + 1) * spectrum.length) / barCount));\n let sum = 0;\n let count = 0;\n for (let index = start; index < end && index < spectrum.length; index += 1) {\n const raw = spectrum[index];\n sum += (Number.isFinite(raw) ? raw : 0) / (byteScale ? 255 : 1);\n count += 1;\n }\n result[bar] = clamp(count > 0 ? sum / count : 0, 0, 1);\n }\n return result;\n}\n\n/**\n * Live analyser meter.\n *\n * Supplying `context` creates an owned pass-through tap; supplying `analyser`\n * borrows that node. The two modes are mutually exclusive so resource\n * ownership is never ambiguous.\n */\nexport class AnalyserMeter {\n readonly #levelScale: number;\n readonly #peakDecay: number;\n readonly #minimumBars: number;\n #analyser?: AnalyserNode;\n #input?: GainNode;\n #output?: GainNode;\n #ownsGraph = false;\n #disposed = false;\n #timeBuffer?: Uint8Array<ArrayBuffer>;\n #frequencyBuffer?: Uint8Array<ArrayBuffer>;\n #peakHold = 0;\n\n constructor(options: AnalyserMeterOptions = {}) {\n if (options.context && options.analyser) {\n throw new TypeError('AnalyserMeter accepts either context or analyser, not both');\n }\n this.#levelScale = finiteNonNegative(options.levelScale, 1.8);\n this.#peakDecay = finiteNonNegative(options.peakDecay, 0.012);\n this.#minimumBars = positiveBarCount(options.minimumBars, 1);\n\n if (options.analyser) this.#analyser = options.analyser;\n else if (options.context) this.#buildOwnedGraph(options.context, options);\n }\n\n /** The owned or borrowed analyser currently read. */\n get analyser(): AnalyserNode | undefined {\n return this.#analyser;\n }\n\n /** Input of an owned tap; absent when borrowing an analyser. */\n get input(): AudioNode | undefined {\n return this.#input;\n }\n\n /** Output of an owned tap; absent when borrowing an analyser. */\n get output(): AudioNode | undefined {\n return this.#output;\n }\n\n /** Whether this meter created and owns its tap graph. */\n get ownsGraph(): boolean {\n return this.#ownsGraph;\n }\n\n /** Read one time-domain frame and derive its level, peak and peak hold. */\n readLevel(): AnalyserMeterFrame {\n const analyser = this.#assertReadable();\n const length = Math.max(1, analyser.fftSize);\n if (!this.#timeBuffer || this.#timeBuffer.length !== length) {\n this.#timeBuffer = new Uint8Array(new ArrayBuffer(length));\n }\n analyser.getByteTimeDomainData(this.#timeBuffer);\n\n let sumSquares = 0;\n let samplePeak = 0;\n for (let index = 0; index < length; index += 1) {\n const sample = ((this.#timeBuffer[index] ?? 128) - 128) / 128;\n sumSquares += sample * sample;\n samplePeak = Math.max(samplePeak, Math.abs(sample));\n }\n const rms = Math.sqrt(sumSquares / length);\n const level = clamp(rms * this.#levelScale, 0, 1);\n const peak = clamp(samplePeak * this.#levelScale, 0, 1);\n this.#peakHold = Math.max(level, this.#peakHold - this.#peakDecay);\n return {rms, level, peak, peakHold: this.#peakHold};\n }\n\n /** Read one frequency-domain frame, aggregated into normalized bars. */\n readSpectrum(bars = 28): Float32Array {\n const analyser = this.#assertReadable();\n const length = Math.max(1, analyser.frequencyBinCount);\n if (!this.#frequencyBuffer || this.#frequencyBuffer.length !== length) {\n this.#frequencyBuffer = new Uint8Array(new ArrayBuffer(length));\n }\n analyser.getByteFrequencyData(this.#frequencyBuffer);\n return aggregateSpectrumBars(this.#frequencyBuffer, {\n bars,\n minimumBars: this.#minimumBars,\n normalizeBytes: true,\n });\n }\n\n /**\n * Release an owned graph; a borrowed analyser is never disconnected. Every\n * owned node is attempted even when an earlier disconnect throws, and the\n * meter has reached its disposed state before the first error is rethrown.\n * Repeated calls are safe.\n */\n dispose(): void {\n if (this.#disposed) return;\n this.#disposed = true;\n const analyser = this.#analyser;\n const input = this.#input;\n const output = this.#output;\n const ownsGraph = this.#ownsGraph;\n\n this.#analyser = undefined;\n this.#input = undefined;\n this.#output = undefined;\n this.#ownsGraph = false;\n this.#timeBuffer = undefined;\n this.#frequencyBuffer = undefined;\n this.#peakHold = 0;\n\n if (!ownsGraph) return;\n let failed = false;\n let firstError: unknown;\n for (const node of [input, analyser, output]) {\n try {\n node?.disconnect();\n } catch (error) {\n if (!failed) firstError = error;\n failed = true;\n }\n }\n if (failed) throw firstError;\n }\n\n #buildOwnedGraph(context: BaseAudioContext, options: AnalyserMeterOptions): void {\n let input: GainNode | undefined;\n let output: GainNode | undefined;\n let analyser: AnalyserNode | undefined;\n try {\n input = context.createGain();\n output = context.createGain();\n analyser = context.createAnalyser();\n analyser.fftSize = options.fftSize ?? 1024;\n analyser.smoothingTimeConstant = options.smoothingTimeConstant ?? 0.8;\n input.connect(analyser);\n analyser.connect(output);\n } catch (error) {\n for (const node of [input, analyser, output]) {\n try {\n node?.disconnect();\n } catch {\n // Preserve the construction failure after a best-effort rollback.\n }\n }\n throw error;\n }\n this.#input = input;\n this.#output = output;\n this.#analyser = analyser;\n this.#ownsGraph = true;\n }\n\n #assertReadable(): AnalyserNode {\n if (this.#disposed) throw new Error('AnalyserMeter has been disposed');\n if (!this.#analyser) throw new Error('AnalyserMeter has no analyser');\n return this.#analyser;\n }\n}\n\n/** Build an {@link AnalyserMeter} (the `createX` convention). */\nexport function createAnalyserMeter(options?: AnalyserMeterOptions): AnalyserMeter {\n return new AnalyserMeter(options);\n}\n\nfunction finiteNonNegative(value: number | undefined, fallback: number): number {\n return value === undefined || !Number.isFinite(value) ? fallback : Math.max(0, value);\n}\n\nfunction positiveBarCount(value: number | undefined, fallback: number): number {\n return Math.max(1, Math.floor(finiteNonNegative(value, fallback)));\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/mamingchen/GitHub/public/WebMusic/platform/kernel/dist/chunk-JNXB74G3.cjs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AA;AAC9D,IAAA;AAA6B,MAAA;AAC/B,EAAA;AACF;AD3U0B;AACA;AACA;AACA;AACA","file":"/Users/mamingchen/GitHub/public/WebMusic/platform/kernel/dist/chunk-JNXB74G3.cjs","sourcesContent":[null,"// ============================================================================\n// Family-neutral synchronized-transport choreography: one master transport,\n// N schedulable followers, all positions on the MASTER's position axis\n// against one shared reference clock (typically AudioContext.currentTime).\n//\n// This is the sync machinery the score↔audio bridge proved out — command\n// serialization, generation guards, drift monitoring, scheduled joins,\n// master-self-stop reconciliation — hoisted here so every transport pairing\n// (score+clip, future families, external masters) reuses one hardened\n// implementation instead of re-writing it per pair. @webmusic/bridge remains\n// the domain assembly: it adapts ScorePlayer/AudioClipPlayer onto these role\n// contracts and keeps its public ScoreAudioSync surface.\n//\n// The master MUST expose a kernel TransportClockReader — the group anchors\n// by READING the clock, the exact affine map the master plays by, with no\n// sampling skew. A transport without a clock is wrapped in\n// {@link MirrorClockMaster}, which owns the sampled mirror-clock fallback\n// (dead-reckoning plus reconciliation) as ONE adapter instead of a second\n// code path inside the group.\n//\n// The group is the session command authority: revisioned invalidation and\n// settlement wrap its existing cancellation/re-entry choreography. Engines\n// still own their clocks. This is not same-instance writable-clock injection;\n// see platform/shared-clock-injection.md for that separate migration boundary.\n// ============================================================================\n\nimport {TransportClock, type TransportClockReader} from './transport';\nimport {\n MAX_TIMER_DELAY_MS,\n createTickSource,\n type TickSource,\n type TickSourceOptions,\n} from './tick';\n\n/**\n * Master role: the transport whose clock is the group's timeline. Everything\n * is on the master's own position axis (for a score player: nominal score\n * seconds; for a clip player: clip seconds).\n */\nexport interface SyncMasterTransport {\n /**\n * Start the transport. `when` (optional, absolute reference-clock seconds)\n * proposes an ARMED start: a master supporting scheduled starts arms its\n * clock there so followers can join at the very same instant. Masters\n * without the capability ignore the argument and start immediately — the\n * group detects which happened by observing `clock.holding`, never\n * through a declared flag.\n */\n play(when?: number): Promise<void> | void;\n pause(): void;\n stop(): void;\n /**\n * Seek to a position on the master's axis. A returned promise settles\n * once the seek has been applied and any mid-playback restart attempted;\n * the group awaits it before re-anchoring followers. The promise MAY\n * resolve with the transport left paused when the restart failed — the\n * group treats that as a failed resume: it pauses the followers, settles\n * into the paused state and reports 'resume after seek' through\n * {@link TransportGroupOptions.onOperationError}. While playing, the\n * group passes a proposed re-entry time the same way {@link play} does.\n */\n seekPosition(position: number, when?: number): void | Promise<void>;\n setRate?(rate: number): void;\n /** Current position on the master's axis. */\n readonly position: number;\n /** Read-only transport clock (master position axis). REQUIRED — wrap a\n * clockless transport in {@link MirrorClockMaster}. */\n readonly clock: TransportClockReader;\n /**\n * Optional pre-drift-check reconciliation hook (adapters). Called once\n * per drift check with the current reference time; returning 'stalled'\n * tells the group the master stopped on its own (the adapter has already\n * paused its clock) — the group then wraps or settles exactly as for an\n * observed master stop.\n */\n reconcile?(now: number): 'ok' | 'stalled';\n dispose?(): void;\n}\n\n/** Follower role: a transport that can join the master's timeline. */\nexport interface SyncFollowerTransport {\n /**\n * Start playback. `when` (optional, absolute reference-clock seconds) is\n * the scheduled start the join dance relies on: the follower MUST honor\n * it sample-accurately for gapless joins (a follower that starts\n * immediately instead will sit one lead-in ahead and be re-corrected\n * forever by the drift monitor).\n */\n play(when?: number): Promise<void> | void;\n pause(): void;\n stop(): void;\n seek(position: number): void;\n setRate?(rate: number): void;\n /** Current position on the follower's own axis. */\n readonly position: number;\n /** Whether the follower is running, when it can say (optional). */\n readonly running?: boolean;\n /**\n * Read-only clock on the follower's own axis, when the transport has one.\n * When present, the drift monitor reads position and running state from\n * it instead of sampling `position`/`running`.\n */\n readonly clock?: TransportClockReader;\n dispose?(): void;\n}\n\n/** Per-follower registration options. */\nexport interface FollowerOptions {\n /** Follower position corresponding to master position zero. Default 0. */\n offsetSeconds?: number;\n /** Positive affine scale: local position = offsetSeconds + master position × positionScale.\n * The follower's playback rate is scaled by the same factor. Default 1.\n * This is a constant map, not nonlinear warping. */\n positionScale?: number;\n /** Local loop bounds for a transport ALREADY configured to loop natively.\n * The group maps join/seek positions and drift into this phase; it does not\n * configure or schedule that native loop. Positions before the loop end\n * retain their intro; at/past the end they wrap into [start, end). */\n loop?: SyncLoopRegion;\n}\n\nexport interface TransportGroupOptions {\n /** Scheduling headroom before followers join, in seconds. Default 0.06. */\n leadInSeconds?: number;\n /** Re-join a follower when |follower − expected| exceeds this. Default 0.03 s. */\n driftToleranceSeconds?: number;\n /** Drift check cadence. Default 250 ms. 0 disables the monitor. */\n driftCheckIntervalMs?: number;\n /** Loop region on the master axis; also settable live via {@link TransportGroup.setLoop}. */\n loop?: SyncLoopRegion | null;\n /** Injectable tick source options (tests; custom hosting). */\n tick?: TickSourceOptions;\n /**\n * Observer for failures of the group'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 group 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 master position axis. */\nexport interface SyncLoopRegion {\n startSeconds: number;\n endSeconds: number;\n}\n\n/** Commands accepted by the group's single authority. Positions use the master's\n * stable content axis, never a duration divided by the current playback rate. */\nexport type TransportCommand =\n | {readonly type: 'play' | 'pause' | 'stop'}\n | {readonly type: 'seek'; readonly position: number}\n | {readonly type: 'rate'; readonly rate: number}\n | {readonly type: 'loop'; readonly loop: SyncLoopRegion | null};\n\n/** Coherent observation at one reference-clock instant. This is a snapshot,\n * not a display timer; read again or use clock.positionAt for moving positions. */\nexport interface TransportSnapshot {\n readonly revision: number;\n readonly referenceTime: number;\n readonly position: number;\n readonly rate: number;\n readonly paused: boolean;\n readonly holding: boolean;\n readonly loop: Readonly<SyncLoopRegion> | null;\n readonly pending: boolean;\n readonly disposed: boolean;\n}\n\nexport interface TransportCommit {\n readonly revision: number;\n readonly command: TransportCommand;\n /** A newer command or disposal supersedes this operation's authority. */\n readonly status: 'committed' | 'superseded';\n readonly snapshot: TransportSnapshot;\n}\n\n/** Invalidation precedes participant commands, settlement follows their\n * asynchronous work. Engines retract/re-arm through their existing commands;\n * this observer protocol does not inject a shared writable clock. */\nexport type TransportEvent =\n | {readonly type: 'snapshot'; readonly snapshot: TransportSnapshot}\n | {readonly type: 'reconcile'; readonly operation: string; readonly phase: 'invalidate' | 'settled'; readonly snapshot: TransportSnapshot}\n | {readonly type: 'operation-error'; readonly operation: string; readonly error: unknown; readonly snapshot: TransportSnapshot}\n | {readonly type: 'invalidate'; readonly revision: number; readonly command: TransportCommand; readonly snapshot: TransportSnapshot}\n | {readonly type: 'commit'; readonly commit: TransportCommit; readonly snapshot: TransportSnapshot}\n | {readonly type: 'error'; readonly revision: number; readonly command: TransportCommand; readonly error: unknown; readonly snapshot: TransportSnapshot};\n\n/**\n * How many consecutive drift corrections may fail before the group stops\n * re-joining a follower and reports instead. Each correction restarts the\n * follower audibly, so a mismatch the corrections cannot fix must not\n * stutter forever.\n */\nconst MAX_CONSECUTIVE_DRIFT_JOINS = 3;\n\n/**\n * Relative slope error before {@link MirrorClockMaster} re-learns a\n * clockless transport's rate. Loose enough to ignore the quantization noise\n * of a transport whose position updates on a frame boundary, tight enough\n * that a refused or clamped rate is caught on the first reconcile that has\n * two samples.\n */\nconst MIRROR_RATE_TOLERANCE = 0.02;\n\ninterface FollowerRecord {\n transport: SyncFollowerTransport;\n offset: number;\n scale: number;\n loop: SyncLoopRegion | null;\n /** Reference time a scheduled join is armed for; drift holds off until then. */\n joinAt: number;\n /**\n * Last rate handed to this follower. Only consulted for followers without\n * a clock to read back; `undefined` until the first application, so a\n * follower constructed at its own rate is corrected rather than assumed.\n */\n lastRate?: number;\n /** Consecutive corrections that did not bring this follower into tolerance. */\n consecutiveDriftJoins: number;\n /** Set once corrections are proven not to converge; cleared by any command. */\n driftJoinsSuppressed: boolean;\n}\n\n/**\n * Drives one master transport and N schedulable followers as a single\n * transport. Positions are on the MASTER's axis; each follower runs\n * `offsetSeconds` ahead of the master's zero. The reference clock is\n * injected (`now`), so the group itself is Web-Audio-free and testable\n * against any monotonic time source.\n */\nexport class TransportGroup {\n #master: SyncMasterTransport;\n readonly #followers: FollowerRecord[] = [];\n readonly #now: () => number;\n #leadIn: number;\n #driftTolerance: number;\n #driftIntervalMs: number;\n #ticker: TickSource | null = null;\n #tickOptions: TickSourceOptions;\n #ticksPerDriftCheck: number;\n #tickCount = 0;\n #loop: SyncLoopRegion | null = null;\n #wrapping = false;\n #generation = 0;\n #revision = 0;\n readonly #pendingCommands = new Set<number>();\n readonly #observers = new Set<(event: TransportEvent) => void>();\n #lastSnapshot?: TransportSnapshot;\n #pendingTransitions = 0;\n /** Serializes transport commands so late async settlements cannot reorder state. */\n #commandActive = false;\n #queuedCommands: Array<() => void> = [];\n #intent: 'playing' | 'paused' | 'stopped' | 'disposed' = 'paused';\n #disposed = false;\n readonly #onOperationError: ((operation: string, error: unknown) => void) | undefined;\n\n constructor(\n master: SyncMasterTransport,\n now: () => number,\n options: TransportGroupOptions = {},\n ) {\n this.#master = master;\n this.#now = now;\n this.#leadIn = options.leadInSeconds ?? 0.06;\n this.#driftTolerance = options.driftToleranceSeconds ?? 0.03;\n this.#driftIntervalMs = options.driftCheckIntervalMs ?? 250;\n this.#onOperationError = options.onOperationError;\n this.#tickOptions = {intervalMs: 25, ...options.tick};\n assertFiniteNonNegative('leadInSeconds', this.#leadIn);\n assertFiniteNonNegative('driftToleranceSeconds', this.#driftTolerance);\n assertFiniteNonNegative('driftCheckIntervalMs', this.#driftIntervalMs);\n const tickInterval = this.#tickOptions.intervalMs ?? 25;\n if (!Number.isSafeInteger(tickInterval) || tickInterval < 1 || tickInterval > MAX_TIMER_DELAY_MS) {\n throw new RangeError(\n `tick.intervalMs must be a positive safe integer no greater than ${MAX_TIMER_DELAY_MS}.`,\n );\n }\n this.#ticksPerDriftCheck = Math.max(1, Math.round(this.#driftIntervalMs / (this.#tickOptions.intervalMs ?? 25)));\n if (options.loop) {\n assertValidLoop(options.loop);\n this.#loop = {...options.loop};\n }\n }\n\n /** The group timeline: a read-through to the master's own clock. */\n get clock(): TransportClockReader {\n return this.#master.clock;\n }\n\n /** Current position on the master axis. */\n get position(): number {\n return this.#master.position;\n }\n\n /** Read one coherent state on the master's stable position axis. */\n get snapshot(): TransportSnapshot {\n if (this.#disposed && this.#lastSnapshot) {\n return Object.freeze({...this.#lastSnapshot, revision: this.#revision, pending: false, disposed: true});\n }\n const referenceTime = this.#now();\n const clock = this.clock;\n const loop = this.loop;\n const snapshot: TransportSnapshot = Object.freeze({\n revision: this.#revision,\n referenceTime,\n position: clock.positionAt(referenceTime),\n rate: clock.rate,\n paused: clock.paused,\n holding: clock.holding && clock.state.originTime > referenceTime,\n loop: loop ? Object.freeze(loop) : null,\n pending: this.#pendingCommands.size > 0 || this.#pendingTransitions > 0,\n disposed: this.#disposed,\n });\n this.#lastSnapshot = snapshot;\n return snapshot;\n }\n\n /** Register before synchronously delivering the initial snapshot. Observer\n * failures are contained. Unsubscribe never stops borrowed playback. */\n subscribe(listener: (event: TransportEvent) => void): () => void {\n this.#assertActive();\n this.#observers.add(listener);\n try { listener({type: 'snapshot', snapshot: this.snapshot}); } catch {\n // A failed initial delivery must not leave an orphan subscription.\n this.#observers.delete(listener);\n }\n return () => { this.#observers.delete(listener); };\n }\n\n /** Submit a command and await its actual participant settlement. Failures\n * reject and emit an error; superseded work cannot claim a committed result.\n * Pause/stop take effect synchronously and await any late-start reconciliation.\n * Call this authority exclusively while coordinating a session. */\n dispatch(command: TransportCommand): Promise<TransportCommit> {\n return this.#dispatch(command, true);\n }\n\n #dispatch(input: TransportCommand, strict: boolean): Promise<TransportCommit> {\n this.#assertActive();\n validateCommand(input);\n const command = Object.freeze(input.type === 'loop'\n ? {...input, loop: input.loop ? Object.freeze({...input.loop}) : null}\n : {...input});\n const revision = ++this.#revision;\n this.#pendingCommands.add(revision);\n this.#publish({type: 'invalidate', revision, command, snapshot: this.snapshot});\n let operation: Promise<void> | void = undefined;\n try {\n // An observer may synchronously replace this command or dispose us.\n if (revision === this.#revision && !this.#disposed) {\n switch (command.type) {\n case 'play': operation = this.#play(strict); break;\n case 'pause': operation = this.#pause(); break;\n case 'stop': operation = this.#stop(); break;\n case 'seek': operation = this.#seek(command.position, strict); break;\n case 'rate': operation = this.#setRate(command.rate, strict, revision); break;\n case 'loop': operation = this.#setLoop(command.loop); break;\n }\n }\n } catch (error) {\n operation = Promise.reject(error);\n }\n return Promise.resolve(operation).then(() => {\n this.#pendingCommands.delete(revision);\n const snapshot = this.snapshot;\n const commit: TransportCommit = Object.freeze({\n revision, command,\n status: revision === this.#revision && !this.#disposed ? 'committed' : 'superseded',\n snapshot,\n });\n this.#publish({type: 'commit', commit, snapshot});\n return commit;\n }, (error: unknown) => {\n if (strict && revision === this.#revision && !this.#disposed) this.#rollbackFailedPlay();\n this.#pendingCommands.delete(revision);\n this.#publish({type: 'error', revision, command, error, snapshot: this.snapshot});\n throw error;\n });\n }\n\n #publish(event: TransportEvent): void {\n for (const listener of [...this.#observers]) {\n if (!this.#observers.has(listener)) continue;\n try { listener(event); } catch { /* Observers cannot interrupt transport cleanup. */ }\n // A reentrant command publishes its newer state first; do not then\n // deliver this stale snapshot to the remaining observers.\n if (event.snapshot.revision !== this.#revision) break;\n }\n }\n\n /**\n * Register a follower. While the group is playing, the follower joins the\n * running timeline on the next scheduled join.\n */\n addFollower(transport: SyncFollowerTransport, options: FollowerOptions = {}): void {\n this.#assertActive();\n const offset = options.offsetSeconds ?? 0;\n assertFiniteNonNegative('offsetSeconds', offset);\n const scale = options.positionScale ?? 1;\n if (!Number.isFinite(scale) || scale <= 0) throw new RangeError('positionScale must be finite and > 0.');\n if (scale !== 1 && !transport.setRate) throw new Error('A scaled follower must support setRate.');\n if (options.loop) assertValidLoop(options.loop);\n const record: FollowerRecord = {\n transport,\n offset,\n scale,\n loop: options.loop ? {...options.loop} : null,\n joinAt: 0,\n consecutiveDriftJoins: 0,\n driftJoinsSuppressed: false,\n };\n this.#followers.push(record);\n if (!this.clock.paused) {\n this.#observeReconciliation('follower join', () => this.#queueJoin(this.#generation, 'follower join', [record]));\n }\n }\n\n /**\n * Remove a follower from the group (the transport itself is left as-is,\n * still playing if it was; the caller owns its lifecycle from here).\n * Returns false when the transport was not a member.\n */\n removeFollower(transport: SyncFollowerTransport): boolean {\n const index = this.#followers.findIndex((record) => record.transport === transport);\n if (index < 0) return false;\n this.#followers.splice(index, 1);\n return true;\n }\n\n /** Number of registered followers. */\n get followerCount(): number {\n return this.#followers.length;\n }\n\n /**\n * Set (or clear) a loop region on the master axis, live. The wrap runs\n * through {@link seek}, so it inherits the shared re-entry origin; the\n * boundary is detected by a worker-backed tick watcher, so the wrap\n * instant may trail the boundary by the watcher/preparation delay and lead-in.\n * Browser throttling means this is not a bounded timing guarantee.\n */\n setLoop(loop: SyncLoopRegion | null): void {\n this.#assertActive();\n if (loop) assertValidLoop(loop);\n void this.#dispatch({type: 'loop', loop}, false).catch((error: unknown) => this.#reportOperationError('loop', error));\n }\n\n #setLoop(loop: SyncLoopRegion | null): void {\n this.#assertActive();\n if (loop) assertValidLoop(loop);\n this.#loop = loop ? {...loop} : null;\n if (this.clock.paused) {\n if (!this.#needsMonitor()) this.#stopDriftMonitor();\n } else if (this.#needsMonitor()) {\n this.#startDriftMonitor();\n } else {\n this.#stopDriftMonitor();\n }\n }\n\n get loop(): SyncLoopRegion | null {\n return this.#loop ? {...this.#loop} : null;\n }\n\n /**\n * Start master and followers on one shared origin. The group proposes\n * `now + leadInSeconds` to the master; one that supports scheduled starts\n * arms there and every follower joins at that very instant. A master that\n * ignores the proposal starts immediately and followers join a lead-in\n * later, offset-matched to its anchor.\n */\n async play(): Promise<void> {\n await this.#dispatch({type: 'play'}, false);\n }\n\n async #play(strict: boolean): Promise<void> {\n this.#assertActive();\n const generation = ++this.#generation;\n this.#pendingTransitions += 1;\n this.#intent = 'playing';\n this.#resetDriftConvergence();\n return this.#enqueueCommand(async () => {\n try {\n if (!this.#isCurrent(generation)) return;\n await this.#master.play(this.#now() + this.#leadIn);\n if (!this.#isCurrent(generation)) {\n this.#reapplySynchronousIntent();\n return;\n }\n if (strict && this.clock.paused) throw new Error('Master transport did not start.');\n await this.#joinFollowers(generation, this.#followers, strict);\n if (this.#isCurrent(generation)) this.#startDriftMonitor();\n } catch (error) {\n if (this.#isCurrent(generation)) this.#rollbackFailedPlay();\n throw error;\n } finally {\n this.#pendingTransitions -= 1;\n }\n });\n }\n\n pause(): void {\n if (this.#disposed) return;\n void this.#dispatch({type: 'pause'}, false).catch((error: unknown) => this.#reportOperationError('pause', error));\n }\n\n #pause(): Promise<void> | void {\n if (this.#disposed) return;\n const hadPendingTransition = this.#pendingTransitions > 0;\n ++this.#generation;\n this.#intent = 'paused';\n this.#resetDriftConvergence();\n this.#stopDriftMonitor();\n this.#applyPause();\n if (hadPendingTransition) {\n return this.#enqueueCommand(() => {\n if (!this.#disposed) this.#applyPause();\n });\n }\n }\n\n stop(): void {\n if (this.#disposed) return;\n void this.#dispatch({type: 'stop'}, false).catch((error: unknown) => this.#reportOperationError('stop', error));\n }\n\n #stop(): Promise<void> | void {\n if (this.#disposed) return;\n const hadPendingTransition = this.#pendingTransitions > 0;\n ++this.#generation;\n this.#intent = 'stopped';\n this.#resetDriftConvergence();\n this.#stopDriftMonitor();\n this.#applyStop();\n if (hadPendingTransition) {\n return this.#enqueueCommand(() => {\n if (!this.#disposed) this.#applyStop();\n });\n }\n }\n\n /**\n * Seek master and followers to a master-axis position. While playing, the\n * group proposes a shared re-entry origin exactly as {@link play} does\n * and re-joins the followers there, so all sides come back in together.\n * Loop wraps run through this path and inherit the same shared origin.\n */\n async seek(position: number): Promise<void> {\n await this.#dispatch({type: 'seek', position}, false);\n }\n\n async #seek(position: number, strict: boolean): Promise<void> {\n this.#assertActive();\n assertFiniteNonNegative('position', position);\n this.#pendingTransitions += 1;\n this.#resetDriftConvergence();\n return this.#enqueueCommand(async () => {\n try {\n if (this.#disposed) return;\n const generation = this.#generation;\n const wasRunning = !this.clock.paused;\n // Propose a shared re-entry origin only for a mid-playback seek: a\n // seek while paused must not start playback.\n await this.#master.seekPosition(\n position,\n wasRunning ? this.#now() + this.#leadIn : undefined,\n );\n const settled = this.#readSettledMasterPosition();\n if (!this.#isCurrent(generation)) {\n this.#reconcileStaleSeek(settled);\n this.#reapplySynchronousIntent();\n return;\n }\n if (this.clock.paused) {\n // A master that was running but comes back paused failed to\n // resume (seekPosition resolves even then) — mirror the stop\n // instead of seeking still-running followers out from under it.\n if (wasRunning && this.#intent === 'playing') {\n this.#settleFailedResume();\n if (strict) throw new Error('Master transport stayed paused after seek.');\n this.#reconcileStaleSeek(settled);\n return;\n }\n for (const record of [...this.#followers]) {\n if (!this.#isCurrent(generation)) break;\n if (!this.#followers.includes(record)) continue;\n record.transport.seek(this.#localPosition(record, settled));\n }\n } else {\n await this.#joinFollowers(generation, this.#followers, strict);\n }\n } finally {\n this.#pendingTransitions -= 1;\n }\n });\n }\n\n /**\n * Set the playback rate on the master and every follower. Followers\n * re-join immediately on the shared clock. NOTE: the group does not clamp\n * the rate beyond finite-and-positive — a domain wrapper owns any shared\n * range its transports require.\n */\n setRate(rate: number): void {\n this.#assertActive();\n validateCommand({type: 'rate', rate});\n void this.#dispatch({type: 'rate', rate}, false).catch((error: unknown) => this.#reportOperationError('rate', error));\n }\n\n #setRate(rate: number, strict: boolean, revision: number, queued = false): Promise<void> | void {\n if (strict && !queued) {\n this.#pendingTransitions += 1;\n return this.#enqueueCommand(async () => {\n try {\n if (revision !== this.#revision || this.#disposed) return;\n await this.#setRate(rate, strict, revision, true);\n } finally {\n this.#pendingTransitions -= 1;\n }\n });\n }\n this.#assertActive();\n if (!Number.isFinite(rate) || rate <= 0) {\n throw new RangeError(`rate must be finite and > 0, got ${rate}.`);\n }\n const generation = this.#generation;\n this.#resetDriftConvergence();\n try {\n this.#master.setRate?.(rate);\n } catch (error) {\n if (strict) throw error;\n this.#reportOperationError('master rate match', error);\n }\n if (revision !== this.#revision || this.#disposed) return;\n if (strict && this.clock.rate !== rate) throw new Error('Master transport did not accept the requested rate.');\n for (const record of [...this.#followers]) {\n if (revision !== this.#revision || this.#disposed) return;\n if (!this.#followers.includes(record)) continue;\n this.#applyFollowerRate(record, rate, strict);\n }\n if (revision !== this.#revision || this.#disposed) return;\n if (!this.clock.paused) {\n return queued\n ? this.#joinFollowers(generation, this.#followers, strict)\n : this.#queueJoin(generation, 'rate re-join', this.#followers, strict);\n }\n }\n\n dispose(): void {\n if (this.#disposed) return;\n this.#lastSnapshot = this.snapshot;\n this.#disposed = true;\n ++this.#revision;\n ++this.#generation;\n this.#intent = 'disposed';\n const ticker = this.#ticker;\n this.#ticker = null;\n const errors: unknown[] = [];\n const releases: Array<() => void> = [() => ticker?.dispose()];\n for (const record of this.#followers) {\n releases.push(() => record.transport.dispose?.());\n }\n releases.push(() => this.#master.dispose?.());\n for (const release of releases) {\n try {\n release();\n } catch (error) {\n errors.push(error);\n }\n }\n this.#publish({type: 'snapshot', snapshot: this.snapshot});\n this.#observers.clear();\n if (errors.length > 0) throw errors[0];\n }\n\n /**\n * One drift check: every follower is measured against the master clock,\n * and each one out of tolerance is re-joined on the shared clock (the\n * same scheduled-start dance as {@link play}). Returns the largest\n * absolute drift observed (0 with no followers or while holding off).\n */\n checkDrift(): number {\n this.#assertActive();\n if (this.#pendingTransitions > 0) return 0;\n const now = this.#now();\n if (this.#master.reconcile) {\n const verdict = this.#master.reconcile(now);\n if (verdict === 'stalled' && this.#intent === 'playing') {\n this.#handleMasterStopped();\n return 0;\n }\n }\n let worst = 0;\n const stragglers: FollowerRecord[] = [];\n for (const record of this.#followers) {\n // Hold off while a scheduled join is still pending — the follower's\n // position deliberately parks at its offset through the pre-roll.\n if (now < record.joinAt) continue;\n const expected = this.#localPosition(record, this.clock.positionAt(now));\n // Prefer the follower's own clock over sampling: exact read at `now`,\n // and `paused` is authoritative where the optional `running` getter\n // may be absent entirely.\n const followerClock = record.transport.clock;\n // A follower's own pre-roll may extend past the common join instant.\n // Its parked position is not drift until that actual start arrives.\n if (followerClock?.holding && now < followerClock.state.originTime) continue;\n const followerPosition = followerClock\n ? followerClock.positionAt(now)\n : record.transport.position;\n const followerRunning = followerClock\n ? !followerClock.paused\n : record.transport.running !== false;\n let localDrift = this.#wrapLocal(record, followerPosition) - expected;\n if (record.loop && followerPosition >= record.loop.startSeconds && expected >= record.loop.startSeconds) {\n const period = record.loop.endSeconds - record.loop.startSeconds;\n localDrift = ((localDrift + period / 2) % period + period) % period - period / 2;\n }\n const drift = localDrift / record.scale;\n // Drift is REPORTED for every member, running or not — a follower whose\n // clock reports paused (ended, torn down) is a real divergence a caller\n // may want to see. It is simply never corrected into a re-join thrash.\n if (Math.abs(drift) > Math.abs(worst)) worst = drift;\n if (!followerRunning) continue;\n // A slope mismatch counts as divergence in its own right: re-joining on\n // position alone re-diverges immediately, which is a re-join every\n // check forever rather than convergence. Both axes carry the same rate\n // scalar after applying the explicit local-axis scale, so an\n // inequality here is real divergence, not a unit difference.\n const rateMismatch = followerClock !== undefined && followerClock.rate !== this.clock.rate * record.scale;\n if (Math.abs(drift) <= this.#driftTolerance && !rateMismatch) {\n // In tolerance on both axes: whatever the last correction did, it stuck.\n record.consecutiveDriftJoins = 0;\n record.driftJoinsSuppressed = false;\n continue;\n }\n if (record.driftJoinsSuppressed) continue;\n record.consecutiveDriftJoins += 1;\n if (record.consecutiveDriftJoins > MAX_CONSECUTIVE_DRIFT_JOINS) {\n // Every correction so far re-anchored this follower and the drift\n // came straight back, so it cannot hold the master's slope (an\n // unclampable master rate, a follower without setRate). Re-joining\n // forever would just restart it once per check with no prospect of\n // converging; stop and say so instead. A check that lands back in\n // tolerance, or any explicit command, re-arms corrections.\n record.driftJoinsSuppressed = true;\n this.#reportOperationError(\n 'drift re-join',\n new Error(\n `TransportGroup: ${record.consecutiveDriftJoins} consecutive drift corrections failed to ` +\n `converge (drift ${drift.toFixed(4)}s, master rate ${this.clock.rate}). The follower ` +\n 'cannot follow the master rate; automatic re-joins are paused until they agree again.',\n ),\n );\n continue;\n }\n stragglers.push(record);\n }\n if (stragglers.length > 0) {\n this.#observeReconciliation('drift re-join', () => this.#queueJoin(this.#generation, 'drift re-join', stragglers));\n }\n return worst;\n }\n\n #wrapLocal(record: FollowerRecord, position: number): number {\n const loop = record.loop;\n if (!loop || position < loop.endSeconds) return position;\n return loop.startSeconds + (position - loop.startSeconds) % (loop.endSeconds - loop.startSeconds);\n }\n\n #localPosition(record: FollowerRecord, masterPosition: number): number {\n return this.#wrapLocal(record, record.offset + masterPosition * record.scale);\n }\n\n /**\n * Schedule followers to (re)join the running master: one reference-clock\n * read, the seek target exact-by-construction for `when` — the same\n * affine map the master plays by. A holding (scheduled-start) master\n * clock whose origin is still in the future is taken as-is, even inside\n * the lead-in horizon: the master has not made a sound yet, so joining\n * exactly at the armed origin is what makes the shared start gapless.\n */\n async #joinFollowers(generation: number, targets: readonly FollowerRecord[], strict = false): Promise<void> {\n if (!this.#isCurrent(generation)) return;\n // External callbacks may remove members while this operation is visiting\n // them. Preserve the visit order without skipping the next live member.\n const members = [...targets];\n for (const record of members) {\n if (!this.#isCurrent(generation)) return;\n if (this.#followers.includes(record)) record.transport.pause();\n }\n const clock = this.clock;\n if (clock.paused) return;\n const now = this.#now();\n const armedOrigin = clock.holding ? clock.state.originTime : -Infinity;\n const when = armedOrigin > now ? armedOrigin : now + this.#leadIn;\n const position = clock.positionAt(when);\n const starts: Array<Promise<void> | void> = [];\n for (const record of members) {\n if (!this.#isCurrent(generation)) break;\n if (!this.#followers.includes(record)) continue;\n try {\n record.joinAt = when;\n // Align the local slope before seeking the mapped future phase.\n this.#applyFollowerRate(record, clock.rate, strict);\n // Rate callbacks can detach a follower or synchronously replace\n // the command. Its old join must not mutate either lifetime.\n if (!this.#isCurrent(generation) || !this.#followers.includes(record)) continue;\n record.transport.seek(this.#localPosition(record, position));\n if (!this.#isCurrent(generation) || !this.#followers.includes(record)) continue;\n starts.push(record.transport.play(when));\n } catch (error) {\n starts.push(Promise.reject(error));\n break;\n }\n }\n // A rejected participant must not leave a still-pending sibling able to\n // restart after failure cleanup has already been reported as complete.\n const settled = await Promise.allSettled(starts);\n if (!this.#isCurrent(generation)) this.#reapplySynchronousIntent();\n const failure = settled.find((result) => result.status === 'rejected');\n if (failure?.status === 'rejected') throw failure.reason;\n if (strict && this.#isCurrent(generation)) {\n for (const record of members) {\n if (!this.#followers.includes(record)) continue;\n const followerClock = record.transport.clock;\n const running = followerClock ? !followerClock.paused : record.transport.running;\n if (running === false) throw new Error('Follower transport did not start.');\n }\n }\n }\n\n /**\n * Hand a follower a rate, skipping the call when it already runs at it.\n * A follower with a clock is asked directly; for one without, the last\n * applied value is remembered. Best-effort by contract: `setRate` is\n * optional on {@link SyncFollowerTransport}, and a transport that has one\n * may still clamp or refuse it — the convergence check below is what\n * surfaces a mismatch neither side can resolve.\n */\n #applyFollowerRate(record: FollowerRecord, rate: number, strict = false): void {\n rate *= record.scale;\n if (!record.transport.setRate) {\n if (strict && (record.transport.clock?.rate ?? 1) !== rate) {\n throw new Error('Follower transport cannot accept the requested rate.');\n }\n return;\n }\n if (!Number.isFinite(rate) || rate <= 0) return;\n const current = record.transport.clock?.rate ?? record.lastRate;\n if (current === rate) return;\n try {\n record.transport.setRate(rate);\n if (strict && record.transport.clock && record.transport.clock.rate !== rate) {\n throw new Error('Follower transport did not accept the requested rate.');\n }\n record.lastRate = rate;\n } catch (error) {\n if (strict) throw error;\n this.#reportOperationError('follower rate match', error);\n }\n }\n\n /** Re-arm drift corrections; any explicit command counts as a fresh start. */\n #resetDriftConvergence(): void {\n for (const record of this.#followers) {\n record.consecutiveDriftJoins = 0;\n record.driftJoinsSuppressed = false;\n }\n }\n\n /**\n * One watcher drives every concern off a kernel tick source (worker-backed\n * where the platform allows, so background-tab throttling does not starve\n * it): master-stop reconciliation and the loop boundary every tick, drift\n * every `driftCheckIntervalMs` worth of ticks.\n */\n #onTick(): void {\n if (this.#disposed) return;\n const revision = this.#revision;\n try {\n this.#reconcileMasterStop();\n this.#checkLoop();\n this.#tickCount += 1;\n if (this.#driftIntervalMs > 0 && this.#tickCount % this.#ticksPerDriftCheck === 0) {\n this.checkDrift();\n }\n } catch (error) {\n // There is no awaiting caller for a timer callback. Report its failure\n // after settling the current session, without pausing a newer command\n // that an adapter may have synchronously dispatched before throwing.\n if (this.#disposed) return;\n if (revision === this.#revision) this.#rollbackFailedPlay();\n this.#reportOperationError('transport monitor', error);\n }\n }\n\n /**\n * The master can stop on its own (a score player finishing at its natural\n * end pauses and rewinds its clock, racing the group's boundary watcher\n * tick-for-tick). A self-stopped clock while the group means to play\n * either wraps (loop active — the loop's continuation intent outranks the\n * master's own finish) or settles into the paused state.\n */\n #reconcileMasterStop(): void {\n if (this.#intent !== 'playing' || this.#wrapping || this.#pendingTransitions > 0) return;\n if (!this.clock.paused) return;\n this.#handleMasterStopped();\n }\n\n #handleMasterStopped(): void {\n if (this.#loop && !this.#wrapping) {\n this.#wrap(this.#loop.startSeconds);\n } else {\n this.#settleMasterStopped();\n }\n }\n\n #checkLoop(): void {\n const loop = this.#loop;\n if (!loop || this.clock.paused || this.#wrapping || this.#pendingTransitions > 0) return;\n if (this.clock.positionAt(this.#now()) >= loop.endSeconds) {\n this.#wrap(loop.startSeconds);\n }\n }\n\n /**\n * Wrap to the loop start. A running master re-joins inside seek(); a\n * master that stopped on its own (natural finish at or past the loop end)\n * is restarted afterwards. A failed wrap settles into the paused state\n * instead of retrying every tick, and is reported as 'loop wrap'.\n */\n #wrap(startSeconds: number): void {\n this.#wrapping = true;\n void this.seek(startSeconds)\n .then(() => {\n if (!this.#disposed && this.#intent === 'playing' && this.clock.paused) {\n return this.play();\n }\n })\n .catch((error: unknown) => {\n this.#reportOperationError('loop wrap', error);\n if (!this.#disposed && this.#intent === 'playing') this.#settleMasterStopped();\n })\n .finally(() => {\n this.#wrapping = false;\n });\n }\n\n #startDriftMonitor(): void {\n if (!this.#needsMonitor()) {\n this.#stopDriftMonitor();\n return;\n }\n this.#ticker ??= createTickSource(this.#tickOptions);\n this.#ticker.start(() => this.#onTick());\n }\n\n #stopDriftMonitor(): void {\n this.#ticker?.stop();\n this.#tickCount = 0;\n }\n\n #needsMonitor(): boolean {\n return this.#loop !== null || this.#driftIntervalMs > 0;\n }\n\n #isCurrent(generation: number): boolean {\n return !this.#disposed && generation === this.#generation;\n }\n\n #reportOperationError(operation: string, error: unknown): void {\n this.#publish({type: 'operation-error', operation, error, snapshot: this.snapshot});\n try {\n this.#onOperationError?.(operation, error);\n } catch {\n // The observer must never disturb transport-state handling.\n }\n }\n\n /**\n * The master stopped although the group meant to be playing (a swallowed\n * restart failure, or the master ending on its own): pause the followers\n * and settle, exactly as an explicit pause() would.\n */\n #settleMasterStopped(): void {\n this.pause();\n }\n\n #settleFailedResume(): void {\n this.#settleMasterStopped();\n this.#reportOperationError(\n 'resume after seek',\n new Error('TransportGroup: the master transport stayed paused after a mid-playback seek.'),\n );\n }\n\n #assertActive(): void {\n if (this.#disposed) throw new Error('TransportGroup has been disposed.');\n }\n\n #observeReconciliation(operation: string, apply: () => Promise<void>): void {\n const revision = ++this.#revision;\n this.#pendingCommands.add(revision);\n this.#publish({type: 'reconcile', operation, phase: 'invalidate', snapshot: this.snapshot});\n const pending = revision === this.#revision && !this.#disposed ? apply() : Promise.resolve();\n void pending.catch((error: unknown) => this.#reportOperationError(operation, error)).finally(() => {\n this.#pendingCommands.delete(revision);\n this.#publish({type: 'reconcile', operation, phase: 'settled', snapshot: this.snapshot});\n });\n }\n\n /**\n * Queue an independent re-join as a visible transition. Public pause/stop\n * calls can then schedule one final reconciliation behind it, preventing\n * a late follower play() settlement from reviving playback.\n */\n #queueJoin(generation: number, operation: string, targets: readonly FollowerRecord[], strict = false): Promise<void> {\n const revision = this.#revision;\n this.#pendingTransitions += 1;\n return this.#enqueueCommand(async () => {\n try {\n await this.#joinFollowers(generation, targets, strict);\n } finally {\n this.#pendingTransitions -= 1;\n }\n }).catch((error: unknown) => {\n // The FIFO may already have begun a newer seek/rate command before\n // this rejection handler runs. Old failure must not pause that owner.\n if (this.#isCurrent(generation) && revision === this.#revision) this.#rollbackFailedPlay();\n if (!this.#disposed) this.#reportOperationError(operation, error);\n if (strict) throw error;\n });\n }\n\n /**\n * Run the first idle command immediately so master.play() remains inside\n * the browser's transient user-activation stack. Only commands that\n * actually have an async predecessor wait in the FIFO.\n */\n #enqueueCommand<Result>(operation: () => Result | PromiseLike<Result>): Promise<Result> {\n return new Promise<Result>((resolve, reject) => {\n const run = () => {\n let result: Result | PromiseLike<Result>;\n try {\n result = operation();\n } catch (error) {\n reject(error);\n this.#finishCommand();\n return;\n }\n Promise.resolve(result).then(\n (value) => {\n resolve(value);\n this.#finishCommand();\n },\n (error: unknown) => {\n reject(error);\n this.#finishCommand();\n },\n );\n };\n\n if (this.#commandActive) {\n this.#queuedCommands.push(run);\n } else {\n this.#commandActive = true;\n run();\n }\n });\n }\n\n #finishCommand(): void {\n const next = this.#queuedCommands.shift();\n if (next) {\n next();\n } else {\n this.#commandActive = false;\n }\n }\n\n /** Read the master's actual post-seek position (it may clamp). */\n #readSettledMasterPosition(): number {\n const position = this.#master.position;\n if (!Number.isFinite(position) || position < 0) {\n throw new RangeError('Master transport returned an invalid position after seek.');\n }\n return position;\n }\n\n /** Preserve the completed seek position when pause superseded it. */\n #reconcileStaleSeek(position: number): void {\n if (this.#disposed || this.#intent !== 'paused') return;\n const generation = this.#generation;\n for (const record of [...this.#followers]) {\n if (!this.#isCurrent(generation)) break;\n if (!this.#followers.includes(record)) continue;\n record.transport.seek(this.#localPosition(record, position));\n }\n }\n\n /** Re-apply pause/stop after an older async master command settles late. */\n #reapplySynchronousIntent(): void {\n if (this.#disposed) return;\n if (this.#intent === 'paused') {\n this.#applyPause();\n } else if (this.#intent === 'stopped') {\n this.#applyStop();\n }\n }\n\n #applyPause(): void {\n const generation = this.#generation;\n const errors: unknown[] = [];\n for (const record of [...this.#followers]) {\n if (!this.#isCurrent(generation)) break;\n if (!this.#followers.includes(record)) continue;\n try { record.transport.pause(); } catch (error) { errors.push(error); }\n }\n if (this.#isCurrent(generation)) {\n try { this.#master.pause(); } catch (error) { errors.push(error); }\n }\n if (errors.length > 0) throw errors[0];\n }\n\n #applyStop(): void {\n const generation = this.#generation;\n const errors: unknown[] = [];\n for (const record of [...this.#followers]) {\n if (!this.#isCurrent(generation)) break;\n if (!this.#followers.includes(record)) continue;\n try { record.transport.stop(); } catch (error) { errors.push(error); }\n }\n if (this.#isCurrent(generation)) {\n try { this.#master.stop(); } catch (error) { errors.push(error); }\n }\n if (errors.length > 0) throw errors[0];\n }\n\n #rollbackFailedPlay(): void {\n ++this.#generation;\n this.#intent = 'paused';\n this.#stopDriftMonitor();\n try {\n this.#applyPause();\n } catch {\n // Preserve the original failure while respecting callback re-entry.\n }\n }\n}\n\n/**\n * Minimal command surface a clockless transport must offer so\n * {@link MirrorClockMaster} can adapt it into the master role.\n */\nexport interface ClocklessMasterTransport {\n play(when?: number): Promise<void> | void;\n pause(): void;\n stop(): void;\n seekPosition(position: number, when?: number): void | Promise<void>;\n setRate?(rate: number): void;\n readonly position: number;\n dispose?(): void;\n}\n\n/**\n * Adapts a transport WITHOUT a readable clock into the required-clock\n * master role by dead-reckoning a mirror TransportClock across the command\n * surface, and reconciling the reckoning against the transport's actual\n * position on every drift check:\n *\n * - two identical position samples while the mirror advanced past the\n * tolerance mean the transport stopped on its own (ended, clamped at its\n * duration, paused out of band) — the adapter pauses the mirror and\n * reports 'stalled', which the group treats as a master stop;\n * - a moving transport that diverged from the extrapolation (refused or\n * clamped rate, tempo automation) re-anchors the mirror so drift is\n * measured against the transport, not the reckoning.\n *\n * This is the ONE home of the sampled fallback the score↔audio bridge used\n * to interleave through its clocked path.\n */\nexport class MirrorClockMaster implements SyncMasterTransport {\n readonly #inner: ClocklessMasterTransport;\n readonly #mirror: TransportClock;\n readonly #now: () => number;\n #tolerance: number;\n #lastSample: {position: number; mirrorPosition: number; time: number} | null = null;\n\n constructor(inner: ClocklessMasterTransport, now: () => number, options: {reconcileToleranceSeconds?: number} = {}) {\n this.#inner = inner;\n this.#now = now;\n this.#tolerance = options.reconcileToleranceSeconds ?? 0.03;\n assertFiniteNonNegative('reconcileToleranceSeconds', this.#tolerance);\n this.#mirror = new TransportClock(now);\n }\n\n get clock(): TransportClockReader {\n return this.#mirror;\n }\n\n get position(): number {\n return this.#inner.position;\n }\n\n async play(when?: number): Promise<void> {\n await this.#inner.play(when);\n this.#lastSample = null;\n this.#mirror.start(this.#now(), this.#inner.position);\n }\n\n pause(): void {\n this.#inner.pause();\n this.#lastSample = null;\n this.#mirror.pause(this.#now());\n }\n\n stop(): void {\n this.#inner.stop();\n this.#lastSample = null;\n const now = this.#now();\n this.#mirror.pause(now);\n this.#mirror.seekTo(0, now);\n }\n\n async seekPosition(position: number, when?: number): Promise<void> {\n await this.#inner.seekPosition(position, when);\n this.#lastSample = null;\n this.#mirror.seekTo(this.#inner.position, this.#now());\n }\n\n setRate(rate: number): void {\n this.#inner.setRate?.(rate);\n this.#lastSample = null;\n this.#mirror.setRate(rate, this.#now());\n }\n\n reconcile(now: number): 'ok' | 'stalled' {\n const actual = this.#inner.position;\n if (!Number.isFinite(actual) || actual < 0) return 'ok';\n const mirrorPosition = this.#mirror.positionAt(now);\n const sample = this.#lastSample;\n this.#lastSample = {position: actual, mirrorPosition, time: now};\n if (\n sample !== null &&\n actual === sample.position &&\n mirrorPosition - sample.mirrorPosition > this.#tolerance &&\n !this.#mirror.paused\n ) {\n this.#lastSample = null;\n this.#mirror.pause(now);\n return 'stalled';\n }\n // Correct the reckoning's SLOPE, not only its intercept. A transport\n // that clamped or refused the shared rate advances at a rate the mirror\n // does not know; re-anchoring the position alone leaves the mirror\n // drifting away again before the next check, which is what turns a rate\n // mismatch into an endless correction loop. The next join then hands the\n // followers the rate the transport actually runs at.\n if (sample !== null && !this.#mirror.paused) {\n const elapsed = now - sample.time;\n const advanced = actual - sample.position;\n if (elapsed > 0 && advanced > 0) {\n const measured = advanced / elapsed;\n const current = this.#mirror.rate;\n if (\n Number.isFinite(measured) &&\n measured > 0 &&\n Math.abs(measured - current) > MIRROR_RATE_TOLERANCE * current\n ) {\n this.#mirror.setRate(measured, now);\n }\n }\n }\n if (Math.abs(mirrorPosition - actual) > this.#tolerance) {\n this.#mirror.seekTo(actual, now);\n }\n return 'ok';\n }\n\n dispose(): void {\n this.#inner.dispose?.();\n }\n}\n\nfunction assertFiniteNonNegative(name: string, value: number): void {\n if (!Number.isFinite(value) || value < 0) {\n throw new RangeError(`${name} must be finite and >= 0.`);\n }\n}\n\nfunction assertValidLoop(loop: SyncLoopRegion): void {\n if (\n !Number.isFinite(loop.startSeconds) || loop.startSeconds < 0 ||\n !Number.isFinite(loop.endSeconds) || !(loop.endSeconds > loop.startSeconds)\n ) {\n throw new RangeError('Loop bounds must be finite, non-negative, and endSeconds must be greater than startSeconds.');\n }\n}\n\n/** Validate before changing revision or touching participants. */\nfunction validateCommand(command: TransportCommand): void {\n switch (command.type) {\n case 'play': case 'pause': case 'stop': return;\n case 'seek': assertFiniteNonNegative('position', command.position); return;\n case 'rate':\n if (!Number.isFinite(command.rate) || command.rate <= 0) throw new RangeError('rate must be finite and > 0.');\n return;\n case 'loop': if (command.loop) assertValidLoop(command.loop); return;\n default: throw new TypeError('Unknown transport command.');\n }\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/sync.ts"],"sourcesContent":["// ============================================================================\n// Family-neutral synchronized-transport choreography: one master transport,\n// N schedulable followers, all positions on the MASTER's position axis\n// against one shared reference clock (typically AudioContext.currentTime).\n//\n// This is the sync machinery the score↔audio bridge proved out — command\n// serialization, generation guards, drift monitoring, scheduled joins,\n// master-self-stop reconciliation — hoisted here so every transport pairing\n// (score+clip, future families, external masters) reuses one hardened\n// implementation instead of re-writing it per pair. @webmusic/bridge remains\n// the domain assembly: it adapts ScorePlayer/AudioClipPlayer onto these role\n// contracts and keeps its public ScoreAudioSync surface.\n//\n// The master MUST expose a kernel TransportClockReader — the group anchors\n// by READING the clock, the exact affine map the master plays by, with no\n// sampling skew. A transport without a clock is wrapped in\n// {@link MirrorClockMaster}, which owns the sampled mirror-clock fallback\n// (dead-reckoning plus reconciliation) as ONE adapter instead of a second\n// code path inside the group.\n//\n// The group is the session command authority: revisioned invalidation and\n// settlement wrap its existing cancellation/re-entry choreography. Engines\n// still own their clocks. This is not same-instance writable-clock injection;\n// see platform/shared-clock-injection.md for that separate migration boundary.\n// ============================================================================\n\nimport {TransportClock, type TransportClockReader} from './transport';\nimport {\n MAX_TIMER_DELAY_MS,\n createTickSource,\n type TickSource,\n type TickSourceOptions,\n} from './tick';\n\n/**\n * Master role: the transport whose clock is the group's timeline. Everything\n * is on the master's own position axis (for a score player: nominal score\n * seconds; for a clip player: clip seconds).\n */\nexport interface SyncMasterTransport {\n /**\n * Start the transport. `when` (optional, absolute reference-clock seconds)\n * proposes an ARMED start: a master supporting scheduled starts arms its\n * clock there so followers can join at the very same instant. Masters\n * without the capability ignore the argument and start immediately — the\n * group detects which happened by observing `clock.holding`, never\n * through a declared flag.\n */\n play(when?: number): Promise<void> | void;\n pause(): void;\n stop(): void;\n /**\n * Seek to a position on the master's axis. A returned promise settles\n * once the seek has been applied and any mid-playback restart attempted;\n * the group awaits it before re-anchoring followers. The promise MAY\n * resolve with the transport left paused when the restart failed — the\n * group treats that as a failed resume: it pauses the followers, settles\n * into the paused state and reports 'resume after seek' through\n * {@link TransportGroupOptions.onOperationError}. While playing, the\n * group passes a proposed re-entry time the same way {@link play} does.\n */\n seekPosition(position: number, when?: number): void | Promise<void>;\n setRate?(rate: number): void;\n /** Current position on the master's axis. */\n readonly position: number;\n /** Read-only transport clock (master position axis). REQUIRED — wrap a\n * clockless transport in {@link MirrorClockMaster}. */\n readonly clock: TransportClockReader;\n /**\n * Optional pre-drift-check reconciliation hook (adapters). Called once\n * per drift check with the current reference time; returning 'stalled'\n * tells the group the master stopped on its own (the adapter has already\n * paused its clock) — the group then wraps or settles exactly as for an\n * observed master stop.\n */\n reconcile?(now: number): 'ok' | 'stalled';\n dispose?(): void;\n}\n\n/** Follower role: a transport that can join the master's timeline. */\nexport interface SyncFollowerTransport {\n /**\n * Start playback. `when` (optional, absolute reference-clock seconds) is\n * the scheduled start the join dance relies on: the follower MUST honor\n * it sample-accurately for gapless joins (a follower that starts\n * immediately instead will sit one lead-in ahead and be re-corrected\n * forever by the drift monitor).\n */\n play(when?: number): Promise<void> | void;\n pause(): void;\n stop(): void;\n seek(position: number): void;\n setRate?(rate: number): void;\n /** Current position on the follower's own axis. */\n readonly position: number;\n /** Whether the follower is running, when it can say (optional). */\n readonly running?: boolean;\n /**\n * Read-only clock on the follower's own axis, when the transport has one.\n * When present, the drift monitor reads position and running state from\n * it instead of sampling `position`/`running`.\n */\n readonly clock?: TransportClockReader;\n dispose?(): void;\n}\n\n/** Per-follower registration options. */\nexport interface FollowerOptions {\n /** Follower position corresponding to master position zero. Default 0. */\n offsetSeconds?: number;\n /** Positive affine scale: local position = offsetSeconds + master position × positionScale.\n * The follower's playback rate is scaled by the same factor. Default 1.\n * This is a constant map, not nonlinear warping. */\n positionScale?: number;\n /** Local loop bounds for a transport ALREADY configured to loop natively.\n * The group maps join/seek positions and drift into this phase; it does not\n * configure or schedule that native loop. Positions before the loop end\n * retain their intro; at/past the end they wrap into [start, end). */\n loop?: SyncLoopRegion;\n}\n\nexport interface TransportGroupOptions {\n /** Scheduling headroom before followers join, in seconds. Default 0.06. */\n leadInSeconds?: number;\n /** Re-join a follower when |follower − expected| exceeds this. Default 0.03 s. */\n driftToleranceSeconds?: number;\n /** Drift check cadence. Default 250 ms. 0 disables the monitor. */\n driftCheckIntervalMs?: number;\n /** Loop region on the master axis; also settable live via {@link TransportGroup.setLoop}. */\n loop?: SyncLoopRegion | null;\n /** Injectable tick source options (tests; custom hosting). */\n tick?: TickSourceOptions;\n /**\n * Observer for failures of the group'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 group 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 master position axis. */\nexport interface SyncLoopRegion {\n startSeconds: number;\n endSeconds: number;\n}\n\n/** Commands accepted by the group's single authority. Positions use the master's\n * stable content axis, never a duration divided by the current playback rate. */\nexport type TransportCommand =\n | {readonly type: 'play' | 'pause' | 'stop'}\n | {readonly type: 'seek'; readonly position: number}\n | {readonly type: 'rate'; readonly rate: number}\n | {readonly type: 'loop'; readonly loop: SyncLoopRegion | null};\n\n/** Coherent observation at one reference-clock instant. This is a snapshot,\n * not a display timer; read again or use clock.positionAt for moving positions. */\nexport interface TransportSnapshot {\n readonly revision: number;\n readonly referenceTime: number;\n readonly position: number;\n readonly rate: number;\n readonly paused: boolean;\n readonly holding: boolean;\n readonly loop: Readonly<SyncLoopRegion> | null;\n readonly pending: boolean;\n readonly disposed: boolean;\n}\n\nexport interface TransportCommit {\n readonly revision: number;\n readonly command: TransportCommand;\n /** A newer command or disposal supersedes this operation's authority. */\n readonly status: 'committed' | 'superseded';\n readonly snapshot: TransportSnapshot;\n}\n\n/** Invalidation precedes participant commands, settlement follows their\n * asynchronous work. Engines retract/re-arm through their existing commands;\n * this observer protocol does not inject a shared writable clock. */\nexport type TransportEvent =\n | {readonly type: 'snapshot'; readonly snapshot: TransportSnapshot}\n | {readonly type: 'reconcile'; readonly operation: string; readonly phase: 'invalidate' | 'settled'; readonly snapshot: TransportSnapshot}\n | {readonly type: 'operation-error'; readonly operation: string; readonly error: unknown; readonly snapshot: TransportSnapshot}\n | {readonly type: 'invalidate'; readonly revision: number; readonly command: TransportCommand; readonly snapshot: TransportSnapshot}\n | {readonly type: 'commit'; readonly commit: TransportCommit; readonly snapshot: TransportSnapshot}\n | {readonly type: 'error'; readonly revision: number; readonly command: TransportCommand; readonly error: unknown; readonly snapshot: TransportSnapshot};\n\n/**\n * How many consecutive drift corrections may fail before the group stops\n * re-joining a follower and reports instead. Each correction restarts the\n * follower audibly, so a mismatch the corrections cannot fix must not\n * stutter forever.\n */\nconst MAX_CONSECUTIVE_DRIFT_JOINS = 3;\n\n/**\n * Relative slope error before {@link MirrorClockMaster} re-learns a\n * clockless transport's rate. Loose enough to ignore the quantization noise\n * of a transport whose position updates on a frame boundary, tight enough\n * that a refused or clamped rate is caught on the first reconcile that has\n * two samples.\n */\nconst MIRROR_RATE_TOLERANCE = 0.02;\n\ninterface FollowerRecord {\n transport: SyncFollowerTransport;\n offset: number;\n scale: number;\n loop: SyncLoopRegion | null;\n /** Reference time a scheduled join is armed for; drift holds off until then. */\n joinAt: number;\n /**\n * Last rate handed to this follower. Only consulted for followers without\n * a clock to read back; `undefined` until the first application, so a\n * follower constructed at its own rate is corrected rather than assumed.\n */\n lastRate?: number;\n /** Consecutive corrections that did not bring this follower into tolerance. */\n consecutiveDriftJoins: number;\n /** Set once corrections are proven not to converge; cleared by any command. */\n driftJoinsSuppressed: boolean;\n}\n\n/**\n * Drives one master transport and N schedulable followers as a single\n * transport. Positions are on the MASTER's axis; each follower runs\n * `offsetSeconds` ahead of the master's zero. The reference clock is\n * injected (`now`), so the group itself is Web-Audio-free and testable\n * against any monotonic time source.\n */\nexport class TransportGroup {\n #master: SyncMasterTransport;\n readonly #followers: FollowerRecord[] = [];\n readonly #now: () => number;\n #leadIn: number;\n #driftTolerance: number;\n #driftIntervalMs: number;\n #ticker: TickSource | null = null;\n #tickOptions: TickSourceOptions;\n #ticksPerDriftCheck: number;\n #tickCount = 0;\n #loop: SyncLoopRegion | null = null;\n #wrapping = false;\n #generation = 0;\n #revision = 0;\n readonly #pendingCommands = new Set<number>();\n readonly #observers = new Set<(event: TransportEvent) => void>();\n #lastSnapshot?: TransportSnapshot;\n #pendingTransitions = 0;\n /** Serializes transport commands so late async settlements cannot reorder state. */\n #commandActive = false;\n #queuedCommands: Array<() => void> = [];\n #intent: 'playing' | 'paused' | 'stopped' | 'disposed' = 'paused';\n #disposed = false;\n readonly #onOperationError: ((operation: string, error: unknown) => void) | undefined;\n\n constructor(\n master: SyncMasterTransport,\n now: () => number,\n options: TransportGroupOptions = {},\n ) {\n this.#master = master;\n this.#now = now;\n this.#leadIn = options.leadInSeconds ?? 0.06;\n this.#driftTolerance = options.driftToleranceSeconds ?? 0.03;\n this.#driftIntervalMs = options.driftCheckIntervalMs ?? 250;\n this.#onOperationError = options.onOperationError;\n this.#tickOptions = {intervalMs: 25, ...options.tick};\n assertFiniteNonNegative('leadInSeconds', this.#leadIn);\n assertFiniteNonNegative('driftToleranceSeconds', this.#driftTolerance);\n assertFiniteNonNegative('driftCheckIntervalMs', this.#driftIntervalMs);\n const tickInterval = this.#tickOptions.intervalMs ?? 25;\n if (!Number.isSafeInteger(tickInterval) || tickInterval < 1 || tickInterval > MAX_TIMER_DELAY_MS) {\n throw new RangeError(\n `tick.intervalMs must be a positive safe integer no greater than ${MAX_TIMER_DELAY_MS}.`,\n );\n }\n this.#ticksPerDriftCheck = Math.max(1, Math.round(this.#driftIntervalMs / (this.#tickOptions.intervalMs ?? 25)));\n if (options.loop) {\n assertValidLoop(options.loop);\n this.#loop = {...options.loop};\n }\n }\n\n /** The group timeline: a read-through to the master's own clock. */\n get clock(): TransportClockReader {\n return this.#master.clock;\n }\n\n /** Current position on the master axis. */\n get position(): number {\n return this.#master.position;\n }\n\n /** Read one coherent state on the master's stable position axis. */\n get snapshot(): TransportSnapshot {\n if (this.#disposed && this.#lastSnapshot) {\n return Object.freeze({...this.#lastSnapshot, revision: this.#revision, pending: false, disposed: true});\n }\n const referenceTime = this.#now();\n const clock = this.clock;\n const loop = this.loop;\n const snapshot: TransportSnapshot = Object.freeze({\n revision: this.#revision,\n referenceTime,\n position: clock.positionAt(referenceTime),\n rate: clock.rate,\n paused: clock.paused,\n holding: clock.holding && clock.state.originTime > referenceTime,\n loop: loop ? Object.freeze(loop) : null,\n pending: this.#pendingCommands.size > 0 || this.#pendingTransitions > 0,\n disposed: this.#disposed,\n });\n this.#lastSnapshot = snapshot;\n return snapshot;\n }\n\n /** Register before synchronously delivering the initial snapshot. Observer\n * failures are contained. Unsubscribe never stops borrowed playback. */\n subscribe(listener: (event: TransportEvent) => void): () => void {\n this.#assertActive();\n this.#observers.add(listener);\n try { listener({type: 'snapshot', snapshot: this.snapshot}); } catch {\n // A failed initial delivery must not leave an orphan subscription.\n this.#observers.delete(listener);\n }\n return () => { this.#observers.delete(listener); };\n }\n\n /** Submit a command and await its actual participant settlement. Failures\n * reject and emit an error; superseded work cannot claim a committed result.\n * Pause/stop take effect synchronously and await any late-start reconciliation.\n * Call this authority exclusively while coordinating a session. */\n dispatch(command: TransportCommand): Promise<TransportCommit> {\n return this.#dispatch(command, true);\n }\n\n #dispatch(input: TransportCommand, strict: boolean): Promise<TransportCommit> {\n this.#assertActive();\n validateCommand(input);\n const command = Object.freeze(input.type === 'loop'\n ? {...input, loop: input.loop ? Object.freeze({...input.loop}) : null}\n : {...input});\n const revision = ++this.#revision;\n this.#pendingCommands.add(revision);\n this.#publish({type: 'invalidate', revision, command, snapshot: this.snapshot});\n let operation: Promise<void> | void = undefined;\n try {\n // An observer may synchronously replace this command or dispose us.\n if (revision === this.#revision && !this.#disposed) {\n switch (command.type) {\n case 'play': operation = this.#play(strict); break;\n case 'pause': operation = this.#pause(); break;\n case 'stop': operation = this.#stop(); break;\n case 'seek': operation = this.#seek(command.position, strict); break;\n case 'rate': operation = this.#setRate(command.rate, strict, revision); break;\n case 'loop': operation = this.#setLoop(command.loop); break;\n }\n }\n } catch (error) {\n operation = Promise.reject(error);\n }\n return Promise.resolve(operation).then(() => {\n this.#pendingCommands.delete(revision);\n const snapshot = this.snapshot;\n const commit: TransportCommit = Object.freeze({\n revision, command,\n status: revision === this.#revision && !this.#disposed ? 'committed' : 'superseded',\n snapshot,\n });\n this.#publish({type: 'commit', commit, snapshot});\n return commit;\n }, (error: unknown) => {\n if (strict && revision === this.#revision && !this.#disposed) this.#rollbackFailedPlay();\n this.#pendingCommands.delete(revision);\n this.#publish({type: 'error', revision, command, error, snapshot: this.snapshot});\n throw error;\n });\n }\n\n #publish(event: TransportEvent): void {\n for (const listener of [...this.#observers]) {\n if (!this.#observers.has(listener)) continue;\n try { listener(event); } catch { /* Observers cannot interrupt transport cleanup. */ }\n // A reentrant command publishes its newer state first; do not then\n // deliver this stale snapshot to the remaining observers.\n if (event.snapshot.revision !== this.#revision) break;\n }\n }\n\n /**\n * Register a follower. While the group is playing, the follower joins the\n * running timeline on the next scheduled join.\n */\n addFollower(transport: SyncFollowerTransport, options: FollowerOptions = {}): void {\n this.#assertActive();\n const offset = options.offsetSeconds ?? 0;\n assertFiniteNonNegative('offsetSeconds', offset);\n const scale = options.positionScale ?? 1;\n if (!Number.isFinite(scale) || scale <= 0) throw new RangeError('positionScale must be finite and > 0.');\n if (scale !== 1 && !transport.setRate) throw new Error('A scaled follower must support setRate.');\n if (options.loop) assertValidLoop(options.loop);\n const record: FollowerRecord = {\n transport,\n offset,\n scale,\n loop: options.loop ? {...options.loop} : null,\n joinAt: 0,\n consecutiveDriftJoins: 0,\n driftJoinsSuppressed: false,\n };\n this.#followers.push(record);\n if (!this.clock.paused) {\n this.#observeReconciliation('follower join', () => this.#queueJoin(this.#generation, 'follower join', [record]));\n }\n }\n\n /**\n * Remove a follower from the group (the transport itself is left as-is,\n * still playing if it was; the caller owns its lifecycle from here).\n * Returns false when the transport was not a member.\n */\n removeFollower(transport: SyncFollowerTransport): boolean {\n const index = this.#followers.findIndex((record) => record.transport === transport);\n if (index < 0) return false;\n this.#followers.splice(index, 1);\n return true;\n }\n\n /** Number of registered followers. */\n get followerCount(): number {\n return this.#followers.length;\n }\n\n /**\n * Set (or clear) a loop region on the master axis, live. The wrap runs\n * through {@link seek}, so it inherits the shared re-entry origin; the\n * boundary is detected by a worker-backed tick watcher, so the wrap\n * instant may trail the boundary by the watcher/preparation delay and lead-in.\n * Browser throttling means this is not a bounded timing guarantee.\n */\n setLoop(loop: SyncLoopRegion | null): void {\n this.#assertActive();\n if (loop) assertValidLoop(loop);\n void this.#dispatch({type: 'loop', loop}, false).catch((error: unknown) => this.#reportOperationError('loop', error));\n }\n\n #setLoop(loop: SyncLoopRegion | null): void {\n this.#assertActive();\n if (loop) assertValidLoop(loop);\n this.#loop = loop ? {...loop} : null;\n if (this.clock.paused) {\n if (!this.#needsMonitor()) this.#stopDriftMonitor();\n } else if (this.#needsMonitor()) {\n this.#startDriftMonitor();\n } else {\n this.#stopDriftMonitor();\n }\n }\n\n get loop(): SyncLoopRegion | null {\n return this.#loop ? {...this.#loop} : null;\n }\n\n /**\n * Start master and followers on one shared origin. The group proposes\n * `now + leadInSeconds` to the master; one that supports scheduled starts\n * arms there and every follower joins at that very instant. A master that\n * ignores the proposal starts immediately and followers join a lead-in\n * later, offset-matched to its anchor.\n */\n async play(): Promise<void> {\n await this.#dispatch({type: 'play'}, false);\n }\n\n async #play(strict: boolean): Promise<void> {\n this.#assertActive();\n const generation = ++this.#generation;\n this.#pendingTransitions += 1;\n this.#intent = 'playing';\n this.#resetDriftConvergence();\n return this.#enqueueCommand(async () => {\n try {\n if (!this.#isCurrent(generation)) return;\n await this.#master.play(this.#now() + this.#leadIn);\n if (!this.#isCurrent(generation)) {\n this.#reapplySynchronousIntent();\n return;\n }\n if (strict && this.clock.paused) throw new Error('Master transport did not start.');\n await this.#joinFollowers(generation, this.#followers, strict);\n if (this.#isCurrent(generation)) this.#startDriftMonitor();\n } catch (error) {\n if (this.#isCurrent(generation)) this.#rollbackFailedPlay();\n throw error;\n } finally {\n this.#pendingTransitions -= 1;\n }\n });\n }\n\n pause(): void {\n if (this.#disposed) return;\n void this.#dispatch({type: 'pause'}, false).catch((error: unknown) => this.#reportOperationError('pause', error));\n }\n\n #pause(): Promise<void> | void {\n if (this.#disposed) return;\n const hadPendingTransition = this.#pendingTransitions > 0;\n ++this.#generation;\n this.#intent = 'paused';\n this.#resetDriftConvergence();\n this.#stopDriftMonitor();\n this.#applyPause();\n if (hadPendingTransition) {\n return this.#enqueueCommand(() => {\n if (!this.#disposed) this.#applyPause();\n });\n }\n }\n\n stop(): void {\n if (this.#disposed) return;\n void this.#dispatch({type: 'stop'}, false).catch((error: unknown) => this.#reportOperationError('stop', error));\n }\n\n #stop(): Promise<void> | void {\n if (this.#disposed) return;\n const hadPendingTransition = this.#pendingTransitions > 0;\n ++this.#generation;\n this.#intent = 'stopped';\n this.#resetDriftConvergence();\n this.#stopDriftMonitor();\n this.#applyStop();\n if (hadPendingTransition) {\n return this.#enqueueCommand(() => {\n if (!this.#disposed) this.#applyStop();\n });\n }\n }\n\n /**\n * Seek master and followers to a master-axis position. While playing, the\n * group proposes a shared re-entry origin exactly as {@link play} does\n * and re-joins the followers there, so all sides come back in together.\n * Loop wraps run through this path and inherit the same shared origin.\n */\n async seek(position: number): Promise<void> {\n await this.#dispatch({type: 'seek', position}, false);\n }\n\n async #seek(position: number, strict: boolean): Promise<void> {\n this.#assertActive();\n assertFiniteNonNegative('position', position);\n this.#pendingTransitions += 1;\n this.#resetDriftConvergence();\n return this.#enqueueCommand(async () => {\n try {\n if (this.#disposed) return;\n const generation = this.#generation;\n const wasRunning = !this.clock.paused;\n // Propose a shared re-entry origin only for a mid-playback seek: a\n // seek while paused must not start playback.\n await this.#master.seekPosition(\n position,\n wasRunning ? this.#now() + this.#leadIn : undefined,\n );\n const settled = this.#readSettledMasterPosition();\n if (!this.#isCurrent(generation)) {\n this.#reconcileStaleSeek(settled);\n this.#reapplySynchronousIntent();\n return;\n }\n if (this.clock.paused) {\n // A master that was running but comes back paused failed to\n // resume (seekPosition resolves even then) — mirror the stop\n // instead of seeking still-running followers out from under it.\n if (wasRunning && this.#intent === 'playing') {\n this.#settleFailedResume();\n if (strict) throw new Error('Master transport stayed paused after seek.');\n this.#reconcileStaleSeek(settled);\n return;\n }\n for (const record of [...this.#followers]) {\n if (!this.#isCurrent(generation)) break;\n if (!this.#followers.includes(record)) continue;\n record.transport.seek(this.#localPosition(record, settled));\n }\n } else {\n await this.#joinFollowers(generation, this.#followers, strict);\n }\n } finally {\n this.#pendingTransitions -= 1;\n }\n });\n }\n\n /**\n * Set the playback rate on the master and every follower. Followers\n * re-join immediately on the shared clock. NOTE: the group does not clamp\n * the rate beyond finite-and-positive — a domain wrapper owns any shared\n * range its transports require.\n */\n setRate(rate: number): void {\n this.#assertActive();\n validateCommand({type: 'rate', rate});\n void this.#dispatch({type: 'rate', rate}, false).catch((error: unknown) => this.#reportOperationError('rate', error));\n }\n\n #setRate(rate: number, strict: boolean, revision: number, queued = false): Promise<void> | void {\n if (strict && !queued) {\n this.#pendingTransitions += 1;\n return this.#enqueueCommand(async () => {\n try {\n if (revision !== this.#revision || this.#disposed) return;\n await this.#setRate(rate, strict, revision, true);\n } finally {\n this.#pendingTransitions -= 1;\n }\n });\n }\n this.#assertActive();\n if (!Number.isFinite(rate) || rate <= 0) {\n throw new RangeError(`rate must be finite and > 0, got ${rate}.`);\n }\n const generation = this.#generation;\n this.#resetDriftConvergence();\n try {\n this.#master.setRate?.(rate);\n } catch (error) {\n if (strict) throw error;\n this.#reportOperationError('master rate match', error);\n }\n if (revision !== this.#revision || this.#disposed) return;\n if (strict && this.clock.rate !== rate) throw new Error('Master transport did not accept the requested rate.');\n for (const record of [...this.#followers]) {\n if (revision !== this.#revision || this.#disposed) return;\n if (!this.#followers.includes(record)) continue;\n this.#applyFollowerRate(record, rate, strict);\n }\n if (revision !== this.#revision || this.#disposed) return;\n if (!this.clock.paused) {\n return queued\n ? this.#joinFollowers(generation, this.#followers, strict)\n : this.#queueJoin(generation, 'rate re-join', this.#followers, strict);\n }\n }\n\n dispose(): void {\n if (this.#disposed) return;\n this.#lastSnapshot = this.snapshot;\n this.#disposed = true;\n ++this.#revision;\n ++this.#generation;\n this.#intent = 'disposed';\n const ticker = this.#ticker;\n this.#ticker = null;\n const errors: unknown[] = [];\n const releases: Array<() => void> = [() => ticker?.dispose()];\n for (const record of this.#followers) {\n releases.push(() => record.transport.dispose?.());\n }\n releases.push(() => this.#master.dispose?.());\n for (const release of releases) {\n try {\n release();\n } catch (error) {\n errors.push(error);\n }\n }\n this.#publish({type: 'snapshot', snapshot: this.snapshot});\n this.#observers.clear();\n if (errors.length > 0) throw errors[0];\n }\n\n /**\n * One drift check: every follower is measured against the master clock,\n * and each one out of tolerance is re-joined on the shared clock (the\n * same scheduled-start dance as {@link play}). Returns the largest\n * absolute drift observed (0 with no followers or while holding off).\n */\n checkDrift(): number {\n this.#assertActive();\n if (this.#pendingTransitions > 0) return 0;\n const now = this.#now();\n if (this.#master.reconcile) {\n const verdict = this.#master.reconcile(now);\n if (verdict === 'stalled' && this.#intent === 'playing') {\n this.#handleMasterStopped();\n return 0;\n }\n }\n let worst = 0;\n const stragglers: FollowerRecord[] = [];\n for (const record of this.#followers) {\n // Hold off while a scheduled join is still pending — the follower's\n // position deliberately parks at its offset through the pre-roll.\n if (now < record.joinAt) continue;\n const expected = this.#localPosition(record, this.clock.positionAt(now));\n // Prefer the follower's own clock over sampling: exact read at `now`,\n // and `paused` is authoritative where the optional `running` getter\n // may be absent entirely.\n const followerClock = record.transport.clock;\n // A follower's own pre-roll may extend past the common join instant.\n // Its parked position is not drift until that actual start arrives.\n if (followerClock?.holding && now < followerClock.state.originTime) continue;\n const followerPosition = followerClock\n ? followerClock.positionAt(now)\n : record.transport.position;\n const followerRunning = followerClock\n ? !followerClock.paused\n : record.transport.running !== false;\n let localDrift = this.#wrapLocal(record, followerPosition) - expected;\n if (record.loop && followerPosition >= record.loop.startSeconds && expected >= record.loop.startSeconds) {\n const period = record.loop.endSeconds - record.loop.startSeconds;\n localDrift = ((localDrift + period / 2) % period + period) % period - period / 2;\n }\n const drift = localDrift / record.scale;\n // Drift is REPORTED for every member, running or not — a follower whose\n // clock reports paused (ended, torn down) is a real divergence a caller\n // may want to see. It is simply never corrected into a re-join thrash.\n if (Math.abs(drift) > Math.abs(worst)) worst = drift;\n if (!followerRunning) continue;\n // A slope mismatch counts as divergence in its own right: re-joining on\n // position alone re-diverges immediately, which is a re-join every\n // check forever rather than convergence. Both axes carry the same rate\n // scalar after applying the explicit local-axis scale, so an\n // inequality here is real divergence, not a unit difference.\n const rateMismatch = followerClock !== undefined && followerClock.rate !== this.clock.rate * record.scale;\n if (Math.abs(drift) <= this.#driftTolerance && !rateMismatch) {\n // In tolerance on both axes: whatever the last correction did, it stuck.\n record.consecutiveDriftJoins = 0;\n record.driftJoinsSuppressed = false;\n continue;\n }\n if (record.driftJoinsSuppressed) continue;\n record.consecutiveDriftJoins += 1;\n if (record.consecutiveDriftJoins > MAX_CONSECUTIVE_DRIFT_JOINS) {\n // Every correction so far re-anchored this follower and the drift\n // came straight back, so it cannot hold the master's slope (an\n // unclampable master rate, a follower without setRate). Re-joining\n // forever would just restart it once per check with no prospect of\n // converging; stop and say so instead. A check that lands back in\n // tolerance, or any explicit command, re-arms corrections.\n record.driftJoinsSuppressed = true;\n this.#reportOperationError(\n 'drift re-join',\n new Error(\n `TransportGroup: ${record.consecutiveDriftJoins} consecutive drift corrections failed to ` +\n `converge (drift ${drift.toFixed(4)}s, master rate ${this.clock.rate}). The follower ` +\n 'cannot follow the master rate; automatic re-joins are paused until they agree again.',\n ),\n );\n continue;\n }\n stragglers.push(record);\n }\n if (stragglers.length > 0) {\n this.#observeReconciliation('drift re-join', () => this.#queueJoin(this.#generation, 'drift re-join', stragglers));\n }\n return worst;\n }\n\n #wrapLocal(record: FollowerRecord, position: number): number {\n const loop = record.loop;\n if (!loop || position < loop.endSeconds) return position;\n return loop.startSeconds + (position - loop.startSeconds) % (loop.endSeconds - loop.startSeconds);\n }\n\n #localPosition(record: FollowerRecord, masterPosition: number): number {\n return this.#wrapLocal(record, record.offset + masterPosition * record.scale);\n }\n\n /**\n * Schedule followers to (re)join the running master: one reference-clock\n * read, the seek target exact-by-construction for `when` — the same\n * affine map the master plays by. A holding (scheduled-start) master\n * clock whose origin is still in the future is taken as-is, even inside\n * the lead-in horizon: the master has not made a sound yet, so joining\n * exactly at the armed origin is what makes the shared start gapless.\n */\n async #joinFollowers(generation: number, targets: readonly FollowerRecord[], strict = false): Promise<void> {\n if (!this.#isCurrent(generation)) return;\n // External callbacks may remove members while this operation is visiting\n // them. Preserve the visit order without skipping the next live member.\n const members = [...targets];\n for (const record of members) {\n if (!this.#isCurrent(generation)) return;\n if (this.#followers.includes(record)) record.transport.pause();\n }\n const clock = this.clock;\n if (clock.paused) return;\n const now = this.#now();\n const armedOrigin = clock.holding ? clock.state.originTime : -Infinity;\n const when = armedOrigin > now ? armedOrigin : now + this.#leadIn;\n const position = clock.positionAt(when);\n const starts: Array<Promise<void> | void> = [];\n for (const record of members) {\n if (!this.#isCurrent(generation)) break;\n if (!this.#followers.includes(record)) continue;\n try {\n record.joinAt = when;\n // Align the local slope before seeking the mapped future phase.\n this.#applyFollowerRate(record, clock.rate, strict);\n // Rate callbacks can detach a follower or synchronously replace\n // the command. Its old join must not mutate either lifetime.\n if (!this.#isCurrent(generation) || !this.#followers.includes(record)) continue;\n record.transport.seek(this.#localPosition(record, position));\n if (!this.#isCurrent(generation) || !this.#followers.includes(record)) continue;\n starts.push(record.transport.play(when));\n } catch (error) {\n starts.push(Promise.reject(error));\n break;\n }\n }\n // A rejected participant must not leave a still-pending sibling able to\n // restart after failure cleanup has already been reported as complete.\n const settled = await Promise.allSettled(starts);\n if (!this.#isCurrent(generation)) this.#reapplySynchronousIntent();\n const failure = settled.find((result) => result.status === 'rejected');\n if (failure?.status === 'rejected') throw failure.reason;\n if (strict && this.#isCurrent(generation)) {\n for (const record of members) {\n if (!this.#followers.includes(record)) continue;\n const followerClock = record.transport.clock;\n const running = followerClock ? !followerClock.paused : record.transport.running;\n if (running === false) throw new Error('Follower transport did not start.');\n }\n }\n }\n\n /**\n * Hand a follower a rate, skipping the call when it already runs at it.\n * A follower with a clock is asked directly; for one without, the last\n * applied value is remembered. Best-effort by contract: `setRate` is\n * optional on {@link SyncFollowerTransport}, and a transport that has one\n * may still clamp or refuse it — the convergence check below is what\n * surfaces a mismatch neither side can resolve.\n */\n #applyFollowerRate(record: FollowerRecord, rate: number, strict = false): void {\n rate *= record.scale;\n if (!record.transport.setRate) {\n if (strict && (record.transport.clock?.rate ?? 1) !== rate) {\n throw new Error('Follower transport cannot accept the requested rate.');\n }\n return;\n }\n if (!Number.isFinite(rate) || rate <= 0) return;\n const current = record.transport.clock?.rate ?? record.lastRate;\n if (current === rate) return;\n try {\n record.transport.setRate(rate);\n if (strict && record.transport.clock && record.transport.clock.rate !== rate) {\n throw new Error('Follower transport did not accept the requested rate.');\n }\n record.lastRate = rate;\n } catch (error) {\n if (strict) throw error;\n this.#reportOperationError('follower rate match', error);\n }\n }\n\n /** Re-arm drift corrections; any explicit command counts as a fresh start. */\n #resetDriftConvergence(): void {\n for (const record of this.#followers) {\n record.consecutiveDriftJoins = 0;\n record.driftJoinsSuppressed = false;\n }\n }\n\n /**\n * One watcher drives every concern off a kernel tick source (worker-backed\n * where the platform allows, so background-tab throttling does not starve\n * it): master-stop reconciliation and the loop boundary every tick, drift\n * every `driftCheckIntervalMs` worth of ticks.\n */\n #onTick(): void {\n if (this.#disposed) return;\n const revision = this.#revision;\n try {\n this.#reconcileMasterStop();\n this.#checkLoop();\n this.#tickCount += 1;\n if (this.#driftIntervalMs > 0 && this.#tickCount % this.#ticksPerDriftCheck === 0) {\n this.checkDrift();\n }\n } catch (error) {\n // There is no awaiting caller for a timer callback. Report its failure\n // after settling the current session, without pausing a newer command\n // that an adapter may have synchronously dispatched before throwing.\n if (this.#disposed) return;\n if (revision === this.#revision) this.#rollbackFailedPlay();\n this.#reportOperationError('transport monitor', error);\n }\n }\n\n /**\n * The master can stop on its own (a score player finishing at its natural\n * end pauses and rewinds its clock, racing the group's boundary watcher\n * tick-for-tick). A self-stopped clock while the group means to play\n * either wraps (loop active — the loop's continuation intent outranks the\n * master's own finish) or settles into the paused state.\n */\n #reconcileMasterStop(): void {\n if (this.#intent !== 'playing' || this.#wrapping || this.#pendingTransitions > 0) return;\n if (!this.clock.paused) return;\n this.#handleMasterStopped();\n }\n\n #handleMasterStopped(): void {\n if (this.#loop && !this.#wrapping) {\n this.#wrap(this.#loop.startSeconds);\n } else {\n this.#settleMasterStopped();\n }\n }\n\n #checkLoop(): void {\n const loop = this.#loop;\n if (!loop || this.clock.paused || this.#wrapping || this.#pendingTransitions > 0) return;\n if (this.clock.positionAt(this.#now()) >= loop.endSeconds) {\n this.#wrap(loop.startSeconds);\n }\n }\n\n /**\n * Wrap to the loop start. A running master re-joins inside seek(); a\n * master that stopped on its own (natural finish at or past the loop end)\n * is restarted afterwards. A failed wrap settles into the paused state\n * instead of retrying every tick, and is reported as 'loop wrap'.\n */\n #wrap(startSeconds: number): void {\n this.#wrapping = true;\n void this.seek(startSeconds)\n .then(() => {\n if (!this.#disposed && this.#intent === 'playing' && this.clock.paused) {\n return this.play();\n }\n })\n .catch((error: unknown) => {\n this.#reportOperationError('loop wrap', error);\n if (!this.#disposed && this.#intent === 'playing') this.#settleMasterStopped();\n })\n .finally(() => {\n this.#wrapping = false;\n });\n }\n\n #startDriftMonitor(): void {\n if (!this.#needsMonitor()) {\n this.#stopDriftMonitor();\n return;\n }\n this.#ticker ??= createTickSource(this.#tickOptions);\n this.#ticker.start(() => this.#onTick());\n }\n\n #stopDriftMonitor(): void {\n this.#ticker?.stop();\n this.#tickCount = 0;\n }\n\n #needsMonitor(): boolean {\n return this.#loop !== null || this.#driftIntervalMs > 0;\n }\n\n #isCurrent(generation: number): boolean {\n return !this.#disposed && generation === this.#generation;\n }\n\n #reportOperationError(operation: string, error: unknown): void {\n this.#publish({type: 'operation-error', operation, error, snapshot: this.snapshot});\n try {\n this.#onOperationError?.(operation, error);\n } catch {\n // The observer must never disturb transport-state handling.\n }\n }\n\n /**\n * The master stopped although the group meant to be playing (a swallowed\n * restart failure, or the master ending on its own): pause the followers\n * and settle, exactly as an explicit pause() would.\n */\n #settleMasterStopped(): void {\n this.pause();\n }\n\n #settleFailedResume(): void {\n this.#settleMasterStopped();\n this.#reportOperationError(\n 'resume after seek',\n new Error('TransportGroup: the master transport stayed paused after a mid-playback seek.'),\n );\n }\n\n #assertActive(): void {\n if (this.#disposed) throw new Error('TransportGroup has been disposed.');\n }\n\n #observeReconciliation(operation: string, apply: () => Promise<void>): void {\n const revision = ++this.#revision;\n this.#pendingCommands.add(revision);\n this.#publish({type: 'reconcile', operation, phase: 'invalidate', snapshot: this.snapshot});\n const pending = revision === this.#revision && !this.#disposed ? apply() : Promise.resolve();\n void pending.catch((error: unknown) => this.#reportOperationError(operation, error)).finally(() => {\n this.#pendingCommands.delete(revision);\n this.#publish({type: 'reconcile', operation, phase: 'settled', snapshot: this.snapshot});\n });\n }\n\n /**\n * Queue an independent re-join as a visible transition. Public pause/stop\n * calls can then schedule one final reconciliation behind it, preventing\n * a late follower play() settlement from reviving playback.\n */\n #queueJoin(generation: number, operation: string, targets: readonly FollowerRecord[], strict = false): Promise<void> {\n const revision = this.#revision;\n this.#pendingTransitions += 1;\n return this.#enqueueCommand(async () => {\n try {\n await this.#joinFollowers(generation, targets, strict);\n } finally {\n this.#pendingTransitions -= 1;\n }\n }).catch((error: unknown) => {\n // The FIFO may already have begun a newer seek/rate command before\n // this rejection handler runs. Old failure must not pause that owner.\n if (this.#isCurrent(generation) && revision === this.#revision) this.#rollbackFailedPlay();\n if (!this.#disposed) this.#reportOperationError(operation, error);\n if (strict) throw error;\n });\n }\n\n /**\n * Run the first idle command immediately so master.play() remains inside\n * the browser's transient user-activation stack. Only commands that\n * actually have an async predecessor wait in the FIFO.\n */\n #enqueueCommand<Result>(operation: () => Result | PromiseLike<Result>): Promise<Result> {\n return new Promise<Result>((resolve, reject) => {\n const run = () => {\n let result: Result | PromiseLike<Result>;\n try {\n result = operation();\n } catch (error) {\n reject(error);\n this.#finishCommand();\n return;\n }\n Promise.resolve(result).then(\n (value) => {\n resolve(value);\n this.#finishCommand();\n },\n (error: unknown) => {\n reject(error);\n this.#finishCommand();\n },\n );\n };\n\n if (this.#commandActive) {\n this.#queuedCommands.push(run);\n } else {\n this.#commandActive = true;\n run();\n }\n });\n }\n\n #finishCommand(): void {\n const next = this.#queuedCommands.shift();\n if (next) {\n next();\n } else {\n this.#commandActive = false;\n }\n }\n\n /** Read the master's actual post-seek position (it may clamp). */\n #readSettledMasterPosition(): number {\n const position = this.#master.position;\n if (!Number.isFinite(position) || position < 0) {\n throw new RangeError('Master transport returned an invalid position after seek.');\n }\n return position;\n }\n\n /** Preserve the completed seek position when pause superseded it. */\n #reconcileStaleSeek(position: number): void {\n if (this.#disposed || this.#intent !== 'paused') return;\n const generation = this.#generation;\n for (const record of [...this.#followers]) {\n if (!this.#isCurrent(generation)) break;\n if (!this.#followers.includes(record)) continue;\n record.transport.seek(this.#localPosition(record, position));\n }\n }\n\n /** Re-apply pause/stop after an older async master command settles late. */\n #reapplySynchronousIntent(): void {\n if (this.#disposed) return;\n if (this.#intent === 'paused') {\n this.#applyPause();\n } else if (this.#intent === 'stopped') {\n this.#applyStop();\n }\n }\n\n #applyPause(): void {\n const generation = this.#generation;\n const errors: unknown[] = [];\n for (const record of [...this.#followers]) {\n if (!this.#isCurrent(generation)) break;\n if (!this.#followers.includes(record)) continue;\n try { record.transport.pause(); } catch (error) { errors.push(error); }\n }\n if (this.#isCurrent(generation)) {\n try { this.#master.pause(); } catch (error) { errors.push(error); }\n }\n if (errors.length > 0) throw errors[0];\n }\n\n #applyStop(): void {\n const generation = this.#generation;\n const errors: unknown[] = [];\n for (const record of [...this.#followers]) {\n if (!this.#isCurrent(generation)) break;\n if (!this.#followers.includes(record)) continue;\n try { record.transport.stop(); } catch (error) { errors.push(error); }\n }\n if (this.#isCurrent(generation)) {\n try { this.#master.stop(); } catch (error) { errors.push(error); }\n }\n if (errors.length > 0) throw errors[0];\n }\n\n #rollbackFailedPlay(): void {\n ++this.#generation;\n this.#intent = 'paused';\n this.#stopDriftMonitor();\n try {\n this.#applyPause();\n } catch {\n // Preserve the original failure while respecting callback re-entry.\n }\n }\n}\n\n/**\n * Minimal command surface a clockless transport must offer so\n * {@link MirrorClockMaster} can adapt it into the master role.\n */\nexport interface ClocklessMasterTransport {\n play(when?: number): Promise<void> | void;\n pause(): void;\n stop(): void;\n seekPosition(position: number, when?: number): void | Promise<void>;\n setRate?(rate: number): void;\n readonly position: number;\n dispose?(): void;\n}\n\n/**\n * Adapts a transport WITHOUT a readable clock into the required-clock\n * master role by dead-reckoning a mirror TransportClock across the command\n * surface, and reconciling the reckoning against the transport's actual\n * position on every drift check:\n *\n * - two identical position samples while the mirror advanced past the\n * tolerance mean the transport stopped on its own (ended, clamped at its\n * duration, paused out of band) — the adapter pauses the mirror and\n * reports 'stalled', which the group treats as a master stop;\n * - a moving transport that diverged from the extrapolation (refused or\n * clamped rate, tempo automation) re-anchors the mirror so drift is\n * measured against the transport, not the reckoning.\n *\n * This is the ONE home of the sampled fallback the score↔audio bridge used\n * to interleave through its clocked path.\n */\nexport class MirrorClockMaster implements SyncMasterTransport {\n readonly #inner: ClocklessMasterTransport;\n readonly #mirror: TransportClock;\n readonly #now: () => number;\n #tolerance: number;\n #lastSample: {position: number; mirrorPosition: number; time: number} | null = null;\n\n constructor(inner: ClocklessMasterTransport, now: () => number, options: {reconcileToleranceSeconds?: number} = {}) {\n this.#inner = inner;\n this.#now = now;\n this.#tolerance = options.reconcileToleranceSeconds ?? 0.03;\n assertFiniteNonNegative('reconcileToleranceSeconds', this.#tolerance);\n this.#mirror = new TransportClock(now);\n }\n\n get clock(): TransportClockReader {\n return this.#mirror;\n }\n\n get position(): number {\n return this.#inner.position;\n }\n\n async play(when?: number): Promise<void> {\n await this.#inner.play(when);\n this.#lastSample = null;\n this.#mirror.start(this.#now(), this.#inner.position);\n }\n\n pause(): void {\n this.#inner.pause();\n this.#lastSample = null;\n this.#mirror.pause(this.#now());\n }\n\n stop(): void {\n this.#inner.stop();\n this.#lastSample = null;\n const now = this.#now();\n this.#mirror.pause(now);\n this.#mirror.seekTo(0, now);\n }\n\n async seekPosition(position: number, when?: number): Promise<void> {\n await this.#inner.seekPosition(position, when);\n this.#lastSample = null;\n this.#mirror.seekTo(this.#inner.position, this.#now());\n }\n\n setRate(rate: number): void {\n this.#inner.setRate?.(rate);\n this.#lastSample = null;\n this.#mirror.setRate(rate, this.#now());\n }\n\n reconcile(now: number): 'ok' | 'stalled' {\n const actual = this.#inner.position;\n if (!Number.isFinite(actual) || actual < 0) return 'ok';\n const mirrorPosition = this.#mirror.positionAt(now);\n const sample = this.#lastSample;\n this.#lastSample = {position: actual, mirrorPosition, time: now};\n if (\n sample !== null &&\n actual === sample.position &&\n mirrorPosition - sample.mirrorPosition > this.#tolerance &&\n !this.#mirror.paused\n ) {\n this.#lastSample = null;\n this.#mirror.pause(now);\n return 'stalled';\n }\n // Correct the reckoning's SLOPE, not only its intercept. A transport\n // that clamped or refused the shared rate advances at a rate the mirror\n // does not know; re-anchoring the position alone leaves the mirror\n // drifting away again before the next check, which is what turns a rate\n // mismatch into an endless correction loop. The next join then hands the\n // followers the rate the transport actually runs at.\n if (sample !== null && !this.#mirror.paused) {\n const elapsed = now - sample.time;\n const advanced = actual - sample.position;\n if (elapsed > 0 && advanced > 0) {\n const measured = advanced / elapsed;\n const current = this.#mirror.rate;\n if (\n Number.isFinite(measured) &&\n measured > 0 &&\n Math.abs(measured - current) > MIRROR_RATE_TOLERANCE * current\n ) {\n this.#mirror.setRate(measured, now);\n }\n }\n }\n if (Math.abs(mirrorPosition - actual) > this.#tolerance) {\n this.#mirror.seekTo(actual, now);\n }\n return 'ok';\n }\n\n dispose(): void {\n this.#inner.dispose?.();\n }\n}\n\nfunction assertFiniteNonNegative(name: string, value: number): void {\n if (!Number.isFinite(value) || value < 0) {\n throw new RangeError(`${name} must be finite and >= 0.`);\n }\n}\n\nfunction assertValidLoop(loop: SyncLoopRegion): void {\n if (\n !Number.isFinite(loop.startSeconds) || loop.startSeconds < 0 ||\n !Number.isFinite(loop.endSeconds) || !(loop.endSeconds > loop.startSeconds)\n ) {\n throw new RangeError('Loop bounds must be finite, non-negative, and endSeconds must be greater than startSeconds.');\n }\n}\n\n/** Validate before changing revision or touching participants. */\nfunction validateCommand(command: TransportCommand): void {\n switch (command.type) {\n case 'play': case 'pause': case 'stop': return;\n case 'seek': assertFiniteNonNegative('position', command.position); return;\n case 'rate':\n if (!Number.isFinite(command.rate) || command.rate <= 0) throw new RangeError('rate must be finite and > 0.');\n return;\n case 'loop': if (command.loop) assertValidLoop(command.loop); return;\n default: throw new TypeError('Unknown transport command.');\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAmMA,IAAM,8BAA8B;AASpC,IAAM,wBAAwB;AA5M9B;AAwOO,IAAM,iBAAN,MAAqB;AAAA,EA0B1B,YACE,QACA,KACA,UAAiC,CAAC,GAClC;AA9BG;AACL;AACA,uBAAS,YAA+B,CAAC;AACzC,uBAAS;AACT;AACA;AACA;AACA,gCAA6B;AAC7B;AACA;AACA,mCAAa;AACb,8BAA+B;AAC/B,kCAAY;AACZ,oCAAc;AACd,kCAAY;AACZ,uBAAS,kBAAmB,oBAAI,IAAY;AAC5C,uBAAS,YAAa,oBAAI,IAAqC;AAC/D;AACA,4CAAsB;AAEtB;AAAA,uCAAiB;AACjB,wCAAqC,CAAC;AACtC,gCAAyD;AACzD,kCAAY;AACZ,uBAAS;AAOP,uBAAK,SAAU;AACf,uBAAK,MAAO;AACZ,uBAAK,SAAU,QAAQ,iBAAiB;AACxC,uBAAK,iBAAkB,QAAQ,yBAAyB;AACxD,uBAAK,kBAAmB,QAAQ,wBAAwB;AACxD,uBAAK,mBAAoB,QAAQ;AACjC,uBAAK,cAAe,EAAC,YAAY,IAAI,GAAG,QAAQ,KAAI;AACpD,4BAAwB,iBAAiB,mBAAK,QAAO;AACrD,4BAAwB,yBAAyB,mBAAK,gBAAe;AACrE,4BAAwB,wBAAwB,mBAAK,iBAAgB;AACrE,UAAM,eAAe,mBAAK,cAAa,cAAc;AACrD,QAAI,CAAC,OAAO,cAAc,YAAY,KAAK,eAAe,KAAK,eAAe,oBAAoB;AAChG,YAAM,IAAI;AAAA,QACR,mEAAmE,kBAAkB;A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