@motionscript/browser 0.1.0 → 0.1.1-alpha.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.
Files changed (102) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/asset-bytes.d.ts +12 -50
  3. package/dist/asset-bytes.d.ts.map +1 -1
  4. package/dist/asset-bytes.js +20 -52
  5. package/dist/asset-bytes.js.map +1 -1
  6. package/dist/audio/bus-graph.d.ts +4 -39
  7. package/dist/audio/bus-graph.d.ts.map +1 -1
  8. package/dist/audio/bus-graph.js +4 -38
  9. package/dist/audio/bus-graph.js.map +1 -1
  10. package/dist/audio/effect-graph.d.ts +4 -29
  11. package/dist/audio/effect-graph.d.ts.map +1 -1
  12. package/dist/audio/effect-graph.js +4 -31
  13. package/dist/audio/effect-graph.js.map +1 -1
  14. package/dist/audio/loop-region.d.ts +3 -21
  15. package/dist/audio/loop-region.d.ts.map +1 -1
  16. package/dist/audio/loop-region.js +3 -21
  17. package/dist/audio/loop-region.js.map +1 -1
  18. package/dist/audio/mixer.d.ts +9 -41
  19. package/dist/audio/mixer.d.ts.map +1 -1
  20. package/dist/audio/mixer.js +11 -44
  21. package/dist/audio/mixer.js.map +1 -1
  22. package/dist/audio/player.d.ts +3 -17
  23. package/dist/audio/player.d.ts.map +1 -1
  24. package/dist/audio/player.js +4 -23
  25. package/dist/audio/player.js.map +1 -1
  26. package/dist/browser/audio.js +1 -1
  27. package/dist/browser/chunks/chunk-NDJYMKIV.js +2 -0
  28. package/dist/browser/chunks/chunk-NDJYMKIV.js.map +7 -0
  29. package/dist/browser/index.js +19 -19
  30. package/dist/browser/index.js.map +4 -4
  31. package/dist/browser/manifest.json +1 -1
  32. package/dist/browser/ms_renderer_bg.wasm +0 -0
  33. package/dist/concat.d.ts +25 -84
  34. package/dist/concat.d.ts.map +1 -1
  35. package/dist/concat.js +19 -69
  36. package/dist/concat.js.map +1 -1
  37. package/dist/dynamic-nodes.d.ts +1 -6
  38. package/dist/dynamic-nodes.d.ts.map +1 -1
  39. package/dist/dynamic-nodes.js +3 -24
  40. package/dist/dynamic-nodes.js.map +1 -1
  41. package/dist/engine.d.ts +9 -42
  42. package/dist/engine.d.ts.map +1 -1
  43. package/dist/engine.js +10 -44
  44. package/dist/engine.js.map +1 -1
  45. package/dist/export-audio.d.ts +1 -6
  46. package/dist/export-audio.d.ts.map +1 -1
  47. package/dist/export-audio.js +1 -6
  48. package/dist/export-audio.js.map +1 -1
  49. package/dist/exporter.d.ts +28 -141
  50. package/dist/exporter.d.ts.map +1 -1
  51. package/dist/exporter.js +15 -90
  52. package/dist/exporter.js.map +1 -1
  53. package/dist/frame-loop.d.ts +19 -105
  54. package/dist/frame-loop.d.ts.map +1 -1
  55. package/dist/frame-loop.js +20 -82
  56. package/dist/frame-loop.js.map +1 -1
  57. package/dist/index.d.ts +1 -0
  58. package/dist/index.d.ts.map +1 -1
  59. package/dist/index.js +7 -15
  60. package/dist/index.js.map +1 -1
  61. package/dist/mix-timeline-audio.d.ts +7 -24
  62. package/dist/mix-timeline-audio.d.ts.map +1 -1
  63. package/dist/mix-timeline-audio.js +7 -23
  64. package/dist/mix-timeline-audio.js.map +1 -1
  65. package/dist/native-export.d.ts +29 -0
  66. package/dist/native-export.d.ts.map +1 -0
  67. package/dist/native-export.js +99 -0
  68. package/dist/native-export.js.map +1 -0
  69. package/dist/parallel/export-parallel.d.ts +2 -16
  70. package/dist/parallel/export-parallel.d.ts.map +1 -1
  71. package/dist/parallel/export-parallel.js +1 -11
  72. package/dist/parallel/export-parallel.js.map +1 -1
  73. package/dist/parallel/governor.d.ts +2 -15
  74. package/dist/parallel/governor.d.ts.map +1 -1
  75. package/dist/parallel/governor.js +1 -5
  76. package/dist/parallel/governor.js.map +1 -1
  77. package/dist/parallel/lane.d.ts +1 -5
  78. package/dist/parallel/lane.d.ts.map +1 -1
  79. package/dist/parallel/lane.js.map +1 -1
  80. package/dist/parallel/plan.d.ts +3 -7
  81. package/dist/parallel/plan.d.ts.map +1 -1
  82. package/dist/parallel/plan.js +1 -6
  83. package/dist/parallel/plan.js.map +1 -1
  84. package/dist/parallel/run-lanes.d.ts +4 -18
  85. package/dist/parallel/run-lanes.d.ts.map +1 -1
  86. package/dist/parallel/run-lanes.js +1 -12
  87. package/dist/parallel/run-lanes.js.map +1 -1
  88. package/dist/screenshot.d.ts +1 -12
  89. package/dist/screenshot.d.ts.map +1 -1
  90. package/dist/screenshot.js +1 -12
  91. package/dist/screenshot.js.map +1 -1
  92. package/dist/still.d.ts +17 -74
  93. package/dist/still.d.ts.map +1 -1
  94. package/dist/still.js +13 -50
  95. package/dist/still.js.map +1 -1
  96. package/dist/ticker.d.ts +10 -39
  97. package/dist/ticker.d.ts.map +1 -1
  98. package/dist/ticker.js +13 -45
  99. package/dist/ticker.js.map +1 -1
  100. package/package.json +4 -4
  101. package/dist/browser/chunks/chunk-F3AZKPHU.js +0 -2
  102. package/dist/browser/chunks/chunk-F3AZKPHU.js.map +0 -7
@@ -1 +1 @@
1
- {"version":3,"file":"player.js","sourceRoot":"","sources":["../../src/audio/player.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAgB,MAAM,oBAAoB,CAAC;AAC7D,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC1D,OAAO,EAAE,wBAAwB,EAAE,qBAAqB,EAAE,UAAU,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAWzH;;;;;;GAMG;AACH,MAAM,OAAO,YAAa,SAAQ,SAAS;IACtB,QAAQ,CAA2B;IAC5C,QAAQ,GAAwB,IAAI,CAAC;IACrC,WAAW,GAAG,IAAI,GAAG,EAAuB,CAAC;IAC7C,QAAQ,GAAG,IAAI,GAAG,EAAyB,CAAC;IAC5C,MAAM,GAAG,IAAI,GAAG,EAAwB,CAAC;IACzC,SAAS,GAAmB,EAAE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AAG,IAAI,CAAC;QACrB,KAAK,CAAC,OAAO,EAAE,CAAC;QAChB,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC;QACzB,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;QACtB,IAAI,CAAC,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC;QAC1B,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC;QAC7B,IAAI,CAAC;YACD,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,UAAU,EAAE,CAAC;QACrC,CAAC;QAAC,MAAM,CAAC;YACL,uBAAuB;QAC3B,CAAC;QACD,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC;QACnD,IAAI,KAAK,IAAI,KAAK,CAAC,KAAK,KAAK,QAAQ,EAAE,CAAC;YACpC,KAAK,CAAC,KAAK,EAAE,CAAC;QAClB,CAAC;IACL,CAAC;CACJ","sourcesContent":["import { AudioSink, AudioRequest } from \"@motionscript/core\";\nimport { AudioBusGraph } from \"./bus-graph\";\nimport { applyLoop, wrapIntoRegion } from \"./loop-region\";\nimport { applySpeedToPlaybackRate, buildAudioEffectGraph, buildLevel, playbackOf, sourceOffsetOf } from \"./effect-graph\";\n\ntype ActiveSource = {\n source: AudioBufferSourceNode;\n request: AudioRequest;\n /** Effect and level nodes to disconnect on teardown. */\n nodes: AudioNode[];\n /** Tremolo LFOs to stop on teardown. */\n oscillators: OscillatorNode[];\n};\n\n/**\n * Web Audio implementation of {@link AudioSink} — decodes and caches source\n * buffers, then schedules/plays {@link AudioRequest}s as `AudioBufferSourceNode`s\n * through a shared master gain (global mute and volume). `schedule` registers the\n * active set of requests for the current frame; `syncTo` then starts/stops\n * sources to match `clipTime`, so playback follows scrubbing and seeks.\n */\nexport class WebAudioSink extends AudioSink {\n private readonly borrowed: AudioContext | undefined;\n private _context: AudioContext | null = null;\n private bufferCache = new Map<string, AudioBuffer>();\n private decoding = new Map<string, Promise<void>>();\n private active = new Map<string, ActiveSource>();\n private scheduled: AudioRequest[] = [];\n private disposed: boolean = false;\n /** The master gain and the live bus chains (shared across every clip that names one), built with the context. */\n private _graph: { master: GainNode; buses: AudioBusGraph } | null = null;\n private muted = false;\n private volume = 1;\n\n constructor(context?: AudioContext) {\n super();\n this.borrowed = context;\n }\n\n /**\n * The context, created on first use rather than with the sink: a new\n * AudioContext opens the audio device (50–65 ms on a desktop), and a\n * session that never plays or decodes sound never needs one.\n */\n getContext(): AudioContext {\n this._context ??= this.borrowed ?? new AudioContext();\n return this._context;\n }\n\n private get context(): AudioContext {\n return this.getContext();\n }\n\n private get graph(): { master: GainNode; buses: AudioBusGraph } {\n if (!this._graph) {\n const master = this.context.createGain();\n master.connect(this.context.destination);\n this._graph = { master, buses: new AudioBusGraph(this.context, master) };\n this.applyMasterGain();\n }\n return this._graph;\n }\n\n /**\n * Resume the AudioContext. Must be called from within a user gesture\n * (e.g. a click handler) the first time, or browsers keep the context\n * suspended and no audio is heard.\n */\n unlock(): void {\n if (this.context.state === \"suspended\") {\n this.context.resume();\n }\n }\n\n has(src: string): boolean {\n return this.bufferCache.has(src);\n }\n\n async append(src: string, data: ArrayBuffer): Promise<void> {\n if (this.bufferCache.has(src)) return;\n const existing = this.decoding.get(src);\n if (existing) return existing;\n\n // decodeAudioData detaches `data` — that's fine, the caller in\n // AssetManager.fetchAudio discards its reference immediately after\n // awaiting append. Skipping the defensive .slice(0) saves a multi-MB\n // allocation per audio source.\n const job = this.context.decodeAudioData(data).then((buffer) => {\n this.bufferCache.set(src, buffer);\n }).finally(() => {\n this.decoding.delete(src);\n });\n this.decoding.set(src, job);\n await job;\n }\n\n /** Drops cached buffers and stops active sources for srcs/requests no longer referenced — called when the asset set changes (e.g. seeking across scene boundaries). */\n retain(keep: ReadonlySet<string>): void {\n for (const src of [...this.bufferCache.keys()]) {\n if (!keep.has(src)) this.bufferCache.delete(src);\n }\n for (const [id, active] of this.active) {\n if (!keep.has(active.request.src)) this.stopSource(id, active);\n }\n }\n\n /** Replaces the active request set; stops any currently-playing source whose request is no longer scheduled. Actual start/stop-to-match-time happens in `syncTo`. */\n schedule(requests: readonly AudioRequest[]): void {\n const next = new Set(requests.map(r => r.id));\n for (const [id, active] of this.active) {\n if (!next.has(id)) this.stopSource(id, active);\n }\n this.scheduled = requests.slice();\n }\n\n /** Starts sources whose `[startAt, endAt)` window now contains `clipTime` (computing the correct buffer offset for the seek point) and stops any that have fallen outside it. */\n syncTo(clipTime: number): void {\n const liveIds = new Set<string>();\n\n for (const req of this.scheduled) {\n // `endAt` is `Infinity` for an open clip, so the comparison needs no\n // nullish fallback — see AudioRequest.endAt.\n const isInWindow = clipTime >= req.startAt && clipTime < req.endAt;\n if (!isInWindow) continue;\n\n liveIds.add(req.id);\n if (!this.active.has(req.id)) {\n const buffer = this.bufferCache.get(req.src);\n if (buffer) this.playBuffer(buffer, req, clipTime);\n }\n }\n\n for (const [id, active] of this.active) {\n if (!liveIds.has(id)) this.stopSource(id, active);\n }\n }\n\n async play(time: number, _speed: number, _reverse: boolean): Promise<void> {\n if (this.context.state === \"suspended\") {\n await this.context.resume();\n }\n this.syncTo(time);\n }\n\n stop(): void {\n for (const [id, active] of this.active) {\n this.stopSource(id, active);\n }\n // A bus's curves are scheduled against the clock of the run that built\n // it, so the next play, from wherever it lands, builds them again.\n this._graph?.buses.dispose();\n }\n\n setMuted(muted: boolean): void {\n this.muted = muted;\n this.applyMasterGain();\n }\n\n setVolume(volume: number): void {\n this.volume = Math.max(0, volume);\n this.applyMasterGain();\n }\n\n /** Mute and volume are held separately so unmuting restores the set level. */\n private applyMasterGain(): void {\n if (this._graph) this._graph.master.gain.value = this.muted ? 0 : this.volume;\n }\n\n /** Starts a buffer source mid-clip if `clipTime` lands after the request's start — the offset accounts for the request's trim, the elapsed time since `startAt`, and its speed. */\n private playBuffer(buffer: AudioBuffer, req: AudioRequest, clipTime: number): void {\n const startTime = this.context.currentTime;\n const playback = playbackOf(req, buffer.duration);\n const elapsed = Math.max(0, clipTime - req.startAt);\n\n const source = this.context.createBufferSource();\n source.buffer = buffer;\n const loopRegion = applyLoop(source, req);\n if (playback.rate !== 1) source.playbackRate.value = playback.rate;\n applySpeedToPlaybackRate(\n source.playbackRate, playback.speedRamp, playback.sourceLength, playback.clipDuration, startTime, elapsed,\n );\n\n const graph = buildAudioEffectGraph(\n this.context, source, req.effects ?? [], startTime, playback.clipDuration, elapsed,\n );\n const level = buildLevel(this.context, graph.output, req, playback, startTime, elapsed);\n // Into this clip's bus chain, or straight to the master when it has none.\n // The chain is shared: two clips on one bus reach the same nodes, which is\n // what makes a bus effect one tail rather than one per clip.\n level.output.connect(this.graph.buses.inputFor(req.bus, startTime, clipTime));\n\n const audioOffset = req.trimStart + sourceOffsetOf(playback, elapsed);\n source.start(startTime, wrapIntoRegion(loopRegion, audioOffset));\n for (const osc of graph.oscillators) osc.start(startTime);\n\n source.onended = () => {\n if (this.active.get(req.id)?.source === source) {\n this.active.delete(req.id);\n }\n };\n\n this.active.set(req.id, {\n source,\n request: req,\n nodes: [...graph.nodes, ...level.nodes],\n oscillators: graph.oscillators,\n });\n }\n\n private stopSource(id: string, active: ActiveSource): void {\n try {\n active.source.onended = null;\n active.source.stop();\n for (const osc of active.oscillators) osc.stop();\n active.source.disconnect();\n for (const node of active.nodes) node.disconnect();\n } catch {\n // already stopped\n }\n this.active.delete(id);\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n super.dispose();\n this.bufferCache.clear();\n this.decoding.clear();\n this.scheduled.length = 0;\n this._graph?.buses.dispose();\n try {\n this._graph?.master.disconnect();\n } catch {\n // already disconnected\n }\n const owned = this.borrowed ? null : this._context;\n if (owned && owned.state !== \"closed\") {\n owned.close();\n }\n }\n}\n"]}
1
+ {"version":3,"file":"player.js","sourceRoot":"","sources":["../../src/audio/player.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAA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AAM,CAAC,IAAI,EAAE,CAAC;YACrB,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,WAAW;gBAAE,GAAG,CAAC,IAAI,EAAE,CAAC;YACjD,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC;YAC3B,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,KAAK;gBAAE,IAAI,CAAC,UAAU,EAAE,CAAC;QACvD,CAAC;QAAC,MAAM,CAAC;QACT,CAAC;QACD,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;IAC3B,CAAC;IAED,OAAO;QACH,IAAI,IAAI,CAAC,QAAQ;YAAE,OAAO;QAC1B,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;QACrB,KAAK,CAAC,OAAO,EAAE,CAAC;QAChB,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC;QACzB,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;QACtB,IAAI,CAAC,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC;QAC1B,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC;QAC7B,IAAI,CAAC;YACD,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,UAAU,EAAE,CAAC;QACrC,CAAC;QAAC,MAAM,CAAC;QACT,CAAC;QACD,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC;QACnD,IAAI,KAAK,IAAI,KAAK,CAAC,KAAK,KAAK,QAAQ,EAAE,CAAC;YACpC,KAAK,CAAC,KAAK,EAAE,CAAC;QAClB,CAAC;IACL,CAAC;CACJ","sourcesContent":["import { AudioSink, AudioRequest } from \"@motionscript/core\";\nimport { AudioBusGraph } from \"./bus-graph\";\nimport { applyLoop, wrapIntoRegion } from \"./loop-region\";\nimport { applySpeedToPlaybackRate, buildAudioEffectGraph, buildLevel, playbackOf, sourceOffsetOf } from \"./effect-graph\";\n\ntype ActiveSource = {\n source: AudioBufferSourceNode;\n request: AudioRequest;\n nodes: AudioNode[];\n oscillators: OscillatorNode[];\n};\n\n/** Web Audio implementation of {@link AudioSink}: decodes and caches source buffers, then plays {@link AudioRequest}s as `AudioBufferSourceNode`s through a shared master gain (global mute and volume). `syncTo` starts/stops sources to match `clipTime`, so playback follows scrubbing and seeks. */\nexport class WebAudioSink extends AudioSink {\n private readonly borrowed: AudioContext | undefined;\n private _context: AudioContext | null = null;\n private bufferCache = new Map<string, AudioBuffer>();\n private decoding = new Map<string, Promise<void>>();\n private active = new Map<string, ActiveSource>();\n private scheduled: AudioRequest[] = [];\n private disposed: boolean = false;\n /** The master gain and the live bus chains (shared across every clip that names one), built with the context. */\n private _graph: { master: GainNode; buses: AudioBusGraph } | null = null;\n private muted = false;\n private volume = 1;\n\n constructor(context?: AudioContext) {\n super();\n this.borrowed = context;\n }\n\n /** Created on first use rather than with the sink: a new AudioContext opens the audio device (50–65 ms on desktop), which a session that never plays never needs. */\n getContext(): AudioContext {\n this._context ??= this.borrowed ?? new AudioContext();\n return this._context;\n }\n\n private get context(): AudioContext {\n return this.getContext();\n }\n\n private get graph(): { master: GainNode; buses: AudioBusGraph } {\n if (!this._graph) {\n const master = this.context.createGain();\n master.connect(this.context.destination);\n this._graph = { master, buses: new AudioBusGraph(this.context, master) };\n this.applyMasterGain();\n }\n return this._graph;\n }\n\n /** Resumes the AudioContext; the first call must come from a user gesture or browsers keep it suspended and nothing is heard. */\n unlock(): void {\n if (this.context.state === \"suspended\") {\n this.context.resume();\n }\n }\n\n has(src: string): boolean {\n return this.bufferCache.has(src);\n }\n\n async append(src: string, data: ArrayBuffer): Promise<void> {\n if (this.bufferCache.has(src)) return;\n const existing = this.decoding.get(src);\n if (existing) return existing;\n\n // decodeAudioData detaches `data`; the AssetManager caller discards its reference after awaiting append, so skipping a defensive .slice(0) saves a multi-MB allocation per source.\n const job = this.context.decodeAudioData(data).then((buffer) => {\n this.bufferCache.set(src, buffer);\n }).finally(() => {\n this.decoding.delete(src);\n });\n this.decoding.set(src, job);\n await job;\n }\n\n /** Drops cached buffers and stops active sources for srcs/requests no longer referenced — called when the asset set changes (e.g. seeking across scene boundaries). */\n retain(keep: ReadonlySet<string>): void {\n for (const src of [...this.bufferCache.keys()]) {\n if (!keep.has(src)) this.bufferCache.delete(src);\n }\n for (const [id, active] of this.active) {\n if (!keep.has(active.request.src)) this.stopSource(id, active);\n }\n }\n\n /** Replaces the active request set; stops any currently-playing source whose request is no longer scheduled. Actual start/stop-to-match-time happens in `syncTo`. */\n schedule(requests: readonly AudioRequest[]): void {\n const next = new Set(requests.map(r => r.id));\n for (const [id, active] of this.active) {\n if (!next.has(id)) this.stopSource(id, active);\n }\n this.scheduled = requests.slice();\n }\n\n /** Starts sources whose `[startAt, endAt)` window now contains `clipTime` (computing the correct buffer offset for the seek point) and stops any that have fallen outside it. */\n syncTo(clipTime: number): void {\n const liveIds = new Set<string>();\n\n for (const req of this.scheduled) {\n // `endAt` is `Infinity` for an open clip, so the comparison needs no\n // nullish fallback — see AudioRequest.endAt.\n const isInWindow = clipTime >= req.startAt && clipTime < req.endAt;\n if (!isInWindow) continue;\n\n liveIds.add(req.id);\n if (!this.active.has(req.id)) {\n const buffer = this.bufferCache.get(req.src);\n if (buffer) this.playBuffer(buffer, req, clipTime);\n }\n }\n\n for (const [id, active] of this.active) {\n if (!liveIds.has(id)) this.stopSource(id, active);\n }\n }\n\n async play(time: number, _speed: number, _reverse: boolean): Promise<void> {\n if (this.context.state === \"suspended\") {\n await this.context.resume();\n }\n this.syncTo(time);\n }\n\n stop(): void {\n for (const [id, active] of this.active) {\n this.stopSource(id, active);\n }\n // A bus's curves are scheduled against the clock of the run that built\n // it, so the next play, from wherever it lands, builds them again.\n this._graph?.buses.dispose();\n }\n\n setMuted(muted: boolean): void {\n this.muted = muted;\n this.applyMasterGain();\n }\n\n setVolume(volume: number): void {\n this.volume = Math.max(0, volume);\n this.applyMasterGain();\n }\n\n /** Mute and volume are held separately so unmuting restores the set level. */\n private applyMasterGain(): void {\n if (this._graph) this._graph.master.gain.value = this.muted ? 0 : this.volume;\n }\n\n /** Starts a buffer source mid-clip if `clipTime` lands after the request's start — the offset accounts for the request's trim, the elapsed time since `startAt`, and its speed. */\n private playBuffer(buffer: AudioBuffer, req: AudioRequest, clipTime: number): void {\n const startTime = this.context.currentTime;\n const playback = playbackOf(req, buffer.duration);\n const elapsed = Math.max(0, clipTime - req.startAt);\n\n const source = this.context.createBufferSource();\n source.buffer = buffer;\n const loopRegion = applyLoop(source, req);\n if (playback.rate !== 1) source.playbackRate.value = playback.rate;\n applySpeedToPlaybackRate(\n source.playbackRate, playback.speedRamp, playback.sourceLength, playback.clipDuration, startTime, elapsed,\n );\n\n const graph = buildAudioEffectGraph(\n this.context, source, req.effects ?? [], startTime, playback.clipDuration, elapsed,\n );\n const level = buildLevel(this.context, graph.output, req, playback, startTime, elapsed);\n // Into this clip's bus chain, or straight to the master when it has none.\n // The chain is shared: two clips on one bus reach the same nodes, which is\n // what makes a bus effect one tail rather than one per clip.\n level.output.connect(this.graph.buses.inputFor(req.bus, startTime, clipTime));\n\n const audioOffset = req.trimStart + sourceOffsetOf(playback, elapsed);\n source.start(startTime, wrapIntoRegion(loopRegion, audioOffset));\n for (const osc of graph.oscillators) osc.start(startTime);\n\n source.onended = () => {\n if (this.active.get(req.id)?.source === source) {\n this.active.delete(req.id);\n }\n };\n\n this.active.set(req.id, {\n source,\n request: req,\n nodes: [...graph.nodes, ...level.nodes],\n oscillators: graph.oscillators,\n });\n }\n\n private stopSource(id: string, active: ActiveSource): void {\n try {\n active.source.onended = null;\n active.source.stop();\n for (const osc of active.oscillators) osc.stop();\n active.source.disconnect();\n for (const node of active.nodes) node.disconnect();\n } catch {\n }\n this.active.delete(id);\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n super.dispose();\n this.bufferCache.clear();\n this.decoding.clear();\n this.scheduled.length = 0;\n this._graph?.buses.dispose();\n try {\n this._graph?.master.disconnect();\n } catch {\n }\n const owned = this.borrowed ? null : this._context;\n if (owned && owned.state !== \"closed\") {\n owned.close();\n }\n }\n}\n"]}
@@ -1,2 +1,2 @@
1
- import{c as e,d as i,e as r,f as A,g as d,h as o}from"./chunks/chunk-F3AZKPHU.js";import"./chunks/chunk-KLXMRKTL.js";export{e as AudioBusGraph,i as DEFAULT_SAMPLE_RATE,A as WebAudioMixer,o as WebAudioPlayer,o as WebAudioSink,d as encodeWav,r as mixAudio};
1
+ import{c as e,d as i,e as r,f as A,g as d,h as o}from"./chunks/chunk-NDJYMKIV.js";import"./chunks/chunk-KLXMRKTL.js";export{e as AudioBusGraph,i as DEFAULT_SAMPLE_RATE,A as WebAudioMixer,o as WebAudioPlayer,o as WebAudioSink,d as encodeWav,r as mixAudio};
2
2
  //# sourceMappingURL=audio.js.map
@@ -0,0 +1,2 @@
1
+ var F=null;function ot(e){F=e}async function H(e){if(!F)return null;try{return await F(e)}catch{return null}}async function K(e){let t=await fetch(e);if(!t.ok){let n=t.statusText?`${t.status} ${t.statusText}`:`${t.status}`;throw new Error(`Fetching "${e}" failed: HTTP ${n}`)}return t.blob()}var _=new Map;function V(e){let t=_.get(e);if(t)return t;let n=(async()=>await H(e)??K(e))().finally(()=>_.delete(e));return _.set(e,n),n}import{busStopKey as Z}from"@motionscript/core";import{clipTimeAtSource as P,isRamp as E,resolveRamp as Q,sampleRamp as T,sourceTimeAtClip as U,staticValue as z,transitionGainAt as J,transitionSpans as X}from"@motionscript/core";var B=200;function I(e,t,n,s,r,i=c=>c){let c=u=>{let h=i(u);return Number.isFinite(h)?h:e.value};if(!E(t)){e.value=c(t);return}if(!Number.isFinite(s)||s<=0){e.value=c(z(t,e.value));return}let a=Q(t,s);if(a.length===0)return;let d=n-r;e.setValueAtTime(c(T(t,Math.max(0,r),s,e.value)),n);for(let u=1;u<a.length;u++){let h=a[u-1],o=a[u],l=d+h.time,f=d+o.time;if(f<=n)continue;let p=o.time-h.time;if(p<=0){e.setValueAtTime(c(o.value),Math.max(f,n));continue}let m=Math.max(0,(n-l)/p),x=Math.max(l,n);if(o.linear)m===0&&e.setValueAtTime(c(h.value),x),e.linearRampToValueAtTime(c(o.value),f);else{let y=f-x,g=Math.max(2,Math.ceil(y*B)),v=new Float32Array(g);for(let w=0;w<g;w++){let O=m+(1-m)*(w/(g-1));v[w]=c(h.value+(o.value-h.value)*o.ease(O))}e.setValueCurveAtTime(v,x,y)}}}function b(e,t,n,s=e.currentTime,r=0,i=0){let c=[],a=[],d=t,u=o=>{d.connect(o),c.push(o),d=o},h=(o,l,f)=>I(o,l,s,r,i,f);for(let o of n)switch(o.type){case"gain":{let l=e.createGain();h(l.gain,o.value),u(l);break}case"highpass":case"lowpass":{let l=e.createBiquadFilter();l.type=o.type,h(l.frequency,o.frequency),o.q!==void 0&&h(l.Q,o.q),u(l);break}case"tremolo":{let l=e.createGain(),f=e.createOscillator(),p=e.createGain();h(l.gain,o.depth,m=>1-M(m)/2),h(p.gain,o.depth,m=>M(m)/2),h(f.frequency,o.rate),f.connect(p),p.connect(l.gain),c.push(p),a.push(f),u(l);break}case"echo":{let l=d,f=e.createGain(),p=e.createGain();h(p.gain,o.mix??.5,g=>1-M(g)),l.connect(p),p.connect(f);let m=e.createDelay(Math.max(1,Y(o.delay)+1));h(m.delayTime,o.delay);let x=e.createGain();h(x.gain,o.feedback,g=>Math.max(0,Math.min(.99,g)));let y=e.createGain();h(y.gain,o.mix??.5,g=>M(g)),l.connect(m),m.connect(x),x.connect(m),m.connect(y),y.connect(f),c.push(p,m,x,y,f),d=f;break}}return{output:d,nodes:c,oscillators:a}}function M(e){return Math.max(0,Math.min(1,e))}function Y(e){return E(e)?Math.max(0,...e.keys.map(t=>t.value)):e}function L(e,t,n,s,r,i){if(!n&&!s)return;let c=Math.max(0,i),a=o=>J(o,t,n,s);e.setValueAtTime(a(c),r);let d=X(t,n,s),u=[];d.in>0&&u.push([0,d.in]),d.out>0&&Number.isFinite(t)&&u.push([t-d.out,t]);let h=r-i;for(let[o,l]of u){let f=Math.max(o,c),p=l-f;if(p<=0)continue;let m=Math.max(2,Math.ceil(p*B)),x=new Float32Array(m);for(let y=0;y<m;y++)x[y]=a(f+p*(y/(m-1)));e.setValueCurveAtTime(x,h+f,p)}}function R(e,t){let n=e.speed??1,s=E(n)?n:void 0,r=s||!(Number.isFinite(n)&&n>0)?1:n,i=e.sourceLength??Math.max(0,t-e.trimStart),c=Number.isFinite(e.endAt),a=c?Math.max(0,e.endAt-e.startAt):P(n,i);return{rate:r,speedRamp:s,sourceLength:i,clipDuration:a,transitionLength:c?a:1/0}}function S(e,t){return e.speedRamp?U(e.speedRamp,e.sourceLength,t):t*e.rate}function k(e,t,n,s,r,i){let c=e.createGain();if(I(c.gain,n.volume??1,r,s.clipDuration,i),t.connect(c),!n.transitionIn&&!n.transitionOut)return{output:c,nodes:[c]};let a=e.createGain();return L(a.gain,s.transitionLength,n.transitionIn,n.transitionOut,r,i),c.connect(a),{output:a,nodes:[c,a]}}function C(e,t,n,s,r,i){if(!t)return;let c=1/B,a=Math.max(0,i),d=u=>Math.max(1e-4,T(t,U(t,n,u),n,1));e.setValueAtTime(d(a),r);for(let u=a+c;u<=s+c;u+=c){let h=Math.min(u,s);if(e.linearRampToValueAtTime(d(h),r+(h-a)),h>=s)break}}var A=class{ctx;destination;constructor(t,n){this.ctx=t,this.destination=n}inputFor(t,n,s){return!t||t.length===0?this.destination:this.chainFrom(t,0,n,s)}dispose(){for(let t of this.nodes)try{t.disconnect()}catch{}for(let t of this.oscillators)try{t.stop()}catch{}this.nodes.length=0,this.oscillators.length=0,this.inputs.clear()}inputs=new Map;nodes=[];oscillators=[];chainFrom(t,n,s,r){if(n>=t.length)return this.destination;let i=t[n],c=t.slice(n).map(Z).join(">"),a=this.inputs.get(c);if(a)return a;let d=this.chainFrom(t,n+1,s,r),u=this.ctx.createGain();u.gain.value=1;let h={type:"gain",value:i.mute?0:i.volume},o=i.endAt-i.startAt,l=b(this.ctx,u,[...i.effects??[],h],s,o,r-i.startAt),f=l.output;if(i.transitionIn||i.transitionOut){let p=this.ctx.createGain();L(p.gain,o,i.transitionIn,i.transitionOut,s,r-i.startAt),f.connect(p),this.nodes.push(p),f=p}f.connect(d),this.nodes.push(u,...l.nodes),this.oscillators.push(...l.oscillators);for(let p of l.oscillators)p.start(s);return this.inputs.set(c,u),u}};function q(e,t){if(!e.loop)return null;let n=Math.min(Math.max(0,e.trimStart),t),s=Math.min(e.trimEnd??t,t);return s>n?{start:n,end:s}:null}function G(e,t){e.loop=t.loop;let n=e.buffer?q(t,e.buffer.duration):null;return n&&(e.loopStart=n.start,e.loopEnd=n.end),n}function D(e,t){return!e||t<e.end?t:e.start+(t-e.start)%(e.end-e.start)}var $=44100;function tt(e,t){if(!t)return e;try{return t.getAudioMeta(e).src||e}catch{try{return t.getVideoMeta(e).src||e}catch{return e}}}async function et(e,t){let n=await V(e);return t.decodeAudioData(await n.arrayBuffer())}async function nt(e,t,n={}){if(e.length===0)return null;let s=n.sampleRate??$,r=Math.ceil(t*s);if(r<=0)return null;let i=[...new Set(e.map(o=>o.request.src))],c=new OfflineAudioContext(2,r,s),a=new Set(e.filter(o=>!o.request.optional).map(o=>o.request.src)),d=new Map;await Promise.all(i.map(async o=>{try{d.set(o,await et(tt(o,n.catalog),c))}catch(l){if(a.has(o))throw l}}));let u=new OfflineAudioContext(2,r,s),h=new A(u,u.destination);for(let{request:o,globalOffset:l}of e){let f=d.get(o.src);if(!f)continue;let p=l+o.startAt,x=Math.min(l+o.endAt,t)-p;if(x<=0)continue;let y=u.createBufferSource();y.buffer=f,G(y,o);let g=R(o,f.duration);g.rate!==1&&(y.playbackRate.value=g.rate),C(y.playbackRate,g.speedRamp,g.sourceLength,g.clipDuration,p,0);let v=b(u,y,o.effects??[],p,g.clipDuration,0);k(u,v.output,o,g,p,0).output.connect(h.inputFor(o.bus,0,-l));let O=S(g,x);y.start(p,o.trimStart,O);for(let W of v.oscillators)W.start(p)}return u.startRendering()}var N=class{sampleRate;catalog;constructor(t=$,n){this.sampleRate=t,this.catalog=n}mix(t,n){return nt(t,n,{sampleRate:this.sampleRate,catalog:this.catalog})}};function yt(e){let t=e.numberOfChannels,n=e.length,s=2,r=t*s,i=n*r,c=new ArrayBuffer(44+i),a=new DataView(c),d=(o,l)=>{for(let f=0;f<l.length;f++)a.setUint8(o+f,l.charCodeAt(f))};d(0,"RIFF"),a.setUint32(4,36+i,!0),d(8,"WAVE"),d(12,"fmt "),a.setUint32(16,16,!0),a.setUint16(20,1,!0),a.setUint16(22,t,!0),a.setUint32(24,e.sampleRate,!0),a.setUint32(28,e.sampleRate*r,!0),a.setUint16(32,r,!0),a.setUint16(34,8*s,!0),d(36,"data"),a.setUint32(40,i,!0);let u=[];for(let o=0;o<t;o++)u.push(e.getChannelData(o));let h=44;for(let o=0;o<n;o++)for(let l=0;l<t;l++){let f=Math.max(-1,Math.min(1,u[l][o]));a.setInt16(h,f<0?f*32768:f*32767,!0),h+=s}return new Uint8Array(c)}import{AudioSink as st}from"@motionscript/core";var j=class extends st{borrowed;_context=null;bufferCache=new Map;decoding=new Map;active=new Map;scheduled=[];disposed=!1;_graph=null;muted=!1;volume=1;constructor(t){super(),this.borrowed=t}getContext(){return this._context??=this.borrowed??new AudioContext,this._context}get context(){return this.getContext()}get graph(){if(!this._graph){let t=this.context.createGain();t.connect(this.context.destination),this._graph={master:t,buses:new A(this.context,t)},this.applyMasterGain()}return this._graph}unlock(){this.context.state==="suspended"&&this.context.resume()}has(t){return this.bufferCache.has(t)}async append(t,n){if(this.bufferCache.has(t))return;let s=this.decoding.get(t);if(s)return s;let r=this.context.decodeAudioData(n).then(i=>{this.bufferCache.set(t,i)}).finally(()=>{this.decoding.delete(t)});this.decoding.set(t,r),await r}retain(t){for(let n of[...this.bufferCache.keys()])t.has(n)||this.bufferCache.delete(n);for(let[n,s]of this.active)t.has(s.request.src)||this.stopSource(n,s)}schedule(t){let n=new Set(t.map(s=>s.id));for(let[s,r]of this.active)n.has(s)||this.stopSource(s,r);this.scheduled=t.slice()}syncTo(t){let n=new Set;for(let s of this.scheduled)if(t>=s.startAt&&t<s.endAt&&(n.add(s.id),!this.active.has(s.id))){let i=this.bufferCache.get(s.src);i&&this.playBuffer(i,s,t)}for(let[s,r]of this.active)n.has(s)||this.stopSource(s,r)}async play(t,n,s){this.context.state==="suspended"&&await this.context.resume(),this.syncTo(t)}stop(){for(let[t,n]of this.active)this.stopSource(t,n);this._graph?.buses.dispose()}setMuted(t){this.muted=t,this.applyMasterGain()}setVolume(t){this.volume=Math.max(0,t),this.applyMasterGain()}applyMasterGain(){this._graph&&(this._graph.master.gain.value=this.muted?0:this.volume)}playBuffer(t,n,s){let r=this.context.currentTime,i=R(n,t.duration),c=Math.max(0,s-n.startAt),a=this.context.createBufferSource();a.buffer=t;let d=G(a,n);i.rate!==1&&(a.playbackRate.value=i.rate),C(a.playbackRate,i.speedRamp,i.sourceLength,i.clipDuration,r,c);let u=b(this.context,a,n.effects??[],r,i.clipDuration,c),h=k(this.context,u.output,n,i,r,c);h.output.connect(this.graph.buses.inputFor(n.bus,r,s));let o=n.trimStart+S(i,c);a.start(r,D(d,o));for(let l of u.oscillators)l.start(r);a.onended=()=>{this.active.get(n.id)?.source===a&&this.active.delete(n.id)},this.active.set(n.id,{source:a,request:n,nodes:[...u.nodes,...h.nodes],oscillators:u.oscillators})}stopSource(t,n){try{n.source.onended=null,n.source.stop();for(let s of n.oscillators)s.stop();n.source.disconnect();for(let s of n.nodes)s.disconnect()}catch{}this.active.delete(t)}dispose(){if(this.disposed)return;this.disposed=!0,super.dispose(),this.bufferCache.clear(),this.decoding.clear(),this.scheduled.length=0,this._graph?.buses.dispose();try{this._graph?.master.disconnect()}catch{}let t=this.borrowed?null:this._context;t&&t.state!=="closed"&&t.close()}};export{ot as a,V as b,A as c,$ as d,nt as e,N as f,yt as g,j as h};
2
+ //# sourceMappingURL=chunk-NDJYMKIV.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/asset-bytes.ts", "../../../src/audio/bus-graph.ts", "../../../src/audio/effect-graph.ts", "../../../src/audio/loop-region.ts", "../../../src/audio/mixer.ts", "../../../src/audio/player.ts"],
4
+ "sourcesContent": ["/**\n * Where a source URL's bytes come from: a host's local store, then the network. The renderer's storage adapter reads\n * every asset through it (`loadBytes`). The adapter otherwise fetches every asset by URL, which is wrong for bytes the\n * host already holds (a file just chosen, a local model's render, an upload still in flight or offline).\n *\n * It is module-level because the adapter is constructed at several sites inside this package (sessions, the exporter,\n * the audio mixer, the still renderer) a host cannot reach; a constructor argument would cover the preview and leave\n * export and stills on the network. This is an *injection point*, not a cache: the adapter still owns every decode,\n * cache and eviction rule, and a source answering `null` leaves it exactly as it was.\n */\n\n/** Local bytes for a source URL, or `null` to go to the network. */\nexport type AssetByteSource = (src: string) => Promise<Blob | null>;\n\nlet source: AssetByteSource | null = null;\n\n/** Installs the byte source for this browsing context, or clears it with `null`. Later calls replace the previous source rather than stacking: two sources disagreeing about one URL has no sensible answer. */\nexport function setAssetByteSource(next: AssetByteSource | null): void {\n source = next;\n}\n\n/** The bytes for `src`, or `null`. Swallows a throwing source on purpose: a failing local store is a cache miss, not a render failure, and the caller falls through to `fetch`. */\nexport async function localAssetBytes(src: string): Promise<Blob | null> {\n if (!source) return null;\n try {\n return await source(src);\n } catch {\n return null;\n }\n}\n\n/** The network's bytes for `url`. A non-OK response is a failed load, never bytes (a 404 page handed to the font manager marked a family loaded with no face). */\nexport async function fetchAssetBytes(url: string): Promise<Blob> {\n const response = await fetch(url);\n if (!response.ok) {\n const status = response.statusText ? `${response.status} ${response.statusText}` : `${response.status}`;\n throw new Error(`Fetching \"${url}\" failed: HTTP ${status}`);\n }\n return response.blob();\n}\n\nconst loading = new Map<string, Promise<Blob>>();\n\n/** The bytes for `src`: the host's local store first, then the network. A second ask while the first is out joins it, page-wide. */\nexport function loadAssetBytes(src: string): Promise<Blob> {\n const running = loading.get(src);\n if (running) return running;\n const job = (async () => (await localAssetBytes(src)) ?? fetchAssetBytes(src))().finally(() => loading.delete(src));\n loading.set(src, job);\n return job;\n}\n", "import { busStopKey, type AudioBusStop, type AudioEffect } from \"@motionscript/core\";\nimport { applyTransitions, buildAudioEffectGraph } from \"./effect-graph\";\n\n/** The live chains for one audio context's buses. Held per context, not per clip: every clip naming a bus connects into the *same* nodes, so a bus reverb is one shared tail (flattening levels into per-clip gain sounds right; flattening effects would not). */\nexport class AudioBusGraph {\n constructor(\n private readonly ctx: BaseAudioContext,\n private readonly destination: AudioNode,\n ) { }\n\n /** The input node a clip on `bus` should connect to, building the chain on first ask. `bus` is source-adjacent first (`bus[0]` is the one the clip feeds; each later stop is its parent); an empty or absent chain returns the destination. `startTime` is the context time a new chain's schedule starts from and `clipTime` the same instant in the stops' own seconds, which place a curve over its `startAt`–`endAt`. */\n inputFor(bus: readonly AudioBusStop[] | undefined, startTime: number, clipTime: number): AudioNode {\n if (!bus || bus.length === 0) return this.destination;\n return this.chainFrom(bus, 0, startTime, clipTime);\n }\n\n /** Disconnect every live bus node, so the next {@link inputFor} builds afresh. Safe to call more than once. */\n dispose(): void {\n for (const node of this.nodes) {\n try { node.disconnect(); } catch { /* already torn down */ }\n }\n for (const osc of this.oscillators) {\n try { osc.stop(); } catch { /* never started, or already stopped */ }\n }\n this.nodes.length = 0;\n this.oscillators.length = 0;\n this.inputs.clear();\n }\n\n private readonly inputs = new Map<string, AudioNode>();\n private readonly nodes: AudioNode[] = [];\n private readonly oscillators: OscillatorNode[] = [];\n\n /** Builds (or reuses) the chain for `bus[index]`, connected to whatever `bus[index + 1]` resolves to. Recursive because a bus's *output* must exist before its own nodes connect to it. Reuse is keyed by everything that changes what it sounds like, not by id alone: a bus edited under a playing device, or one id on two tracks, is a different chain, and a stale one would play stale levels and a curve anchored to the wrong span. */\n private chainFrom(bus: readonly AudioBusStop[], index: number, startTime: number, clipTime: number): AudioNode {\n if (index >= bus.length) return this.destination;\n\n const stop = bus[index];\n const key = bus.slice(index).map(busStopKey).join(\">\");\n const existing = this.inputs.get(key);\n if (existing) return existing;\n\n const output = this.chainFrom(bus, index + 1, startTime, clipTime);\n\n // A pass-through head every clip connects to, so the bus has one input\n // whatever its effects turn out to be.\n const input = this.ctx.createGain();\n input.gain.value = 1;\n\n // The level is a gain after the effects, as a sound's own level is, so a\n // ramp on it is scheduled exactly as one in `effects` is.\n const level: AudioEffect = { type: \"gain\", value: stop.mute ? 0 : stop.volume };\n const span = stop.endAt - stop.startAt;\n const graph = buildAudioEffectGraph(\n this.ctx, input, [...(stop.effects ?? []), level], startTime, span, clipTime - stop.startAt,\n );\n let tail = graph.output;\n if (stop.transitionIn || stop.transitionOut) {\n const transition = this.ctx.createGain();\n applyTransitions(transition.gain, span, stop.transitionIn, stop.transitionOut, startTime, clipTime - stop.startAt);\n tail.connect(transition);\n this.nodes.push(transition);\n tail = transition;\n }\n tail.connect(output);\n\n this.nodes.push(input, ...graph.nodes);\n this.oscillators.push(...graph.oscillators);\n for (const osc of graph.oscillators) osc.start(startTime);\n\n this.inputs.set(key, input);\n return input;\n }\n}\n", "import {\n clipTimeAtSource,\n isRamp,\n resolveRamp,\n sampleRamp,\n sourceTimeAtClip,\n staticValue,\n transitionGainAt,\n transitionSpans,\n type AudioEffect,\n type AudioRequest,\n type AudioTransition,\n type Param,\n type Ramp,\n} from \"@motionscript/core\";\n\n/** The Web Audio graph for one source's effect chain: `output` is the last node to connect downstream, `nodes` every node to `disconnect()` on teardown, `oscillators` tremolo LFOs the caller starts and stops with the source. */\nexport interface AudioEffectGraph {\n output: AudioNode;\n nodes: AudioNode[];\n oscillators: OscillatorNode[];\n}\n\n/** Sample points per second an eased segment or a transition is baked into: about every 5 ms. */\nconst CURVE_SAMPLES_PER_SECOND = 200;\n\n/** Applies a {@link Param} to a Web Audio {@link AudioParam}: a number once, a ramp as a schedule (linear segments via `linearRampToValueAtTime`, eased ones baked into `setValueCurveAtTime`). `elapsed` is the clip seconds already played at a mid-clip seek; `clamp` keeps scheduled values in the param's valid range. */\nfunction applyParam(\n audioParam: AudioParam,\n param: Param,\n startTime: number,\n clipDuration: number,\n elapsed: number,\n clamp: (v: number) => number = (v) => v,\n): void {\n // The platform throws on a non-finite value.\n const finite = (v: number): number => {\n const c = clamp(v);\n return Number.isFinite(c) ? c : audioParam.value;\n };\n\n if (!isRamp(param)) {\n audioParam.value = finite(param);\n return;\n }\n if (!Number.isFinite(clipDuration) || clipDuration <= 0) {\n audioParam.value = finite(staticValue(param, audioParam.value));\n return;\n }\n\n const keys = resolveRamp(param, clipDuration);\n if (keys.length === 0) return;\n const base = startTime - elapsed;\n audioParam.setValueAtTime(finite(sampleRamp(param, Math.max(0, elapsed), clipDuration, audioParam.value)), startTime);\n\n for (let i = 1; i < keys.length; i++) {\n const previous = keys[i - 1];\n const key = keys[i];\n const segStart = base + previous.time;\n const segEnd = base + key.time;\n if (segEnd <= startTime) continue;\n\n const span = key.time - previous.time;\n if (span <= 0) {\n audioParam.setValueAtTime(finite(key.value), Math.max(segEnd, startTime));\n continue;\n }\n\n // A segment already under way when the source starts carries on from\n // the value set at `startTime` rather than restarting from its own.\n const done = Math.max(0, (startTime - segStart) / span);\n const curveStart = Math.max(segStart, startTime);\n if (key.linear) {\n if (done === 0) audioParam.setValueAtTime(finite(previous.value), curveStart);\n audioParam.linearRampToValueAtTime(finite(key.value), segEnd);\n } else {\n const curveDur = segEnd - curveStart;\n const count = Math.max(2, Math.ceil(curveDur * CURVE_SAMPLES_PER_SECOND));\n const samples = new Float32Array(count);\n for (let n = 0; n < count; n++) {\n const local = done + (1 - done) * (n / (count - 1));\n samples[n] = finite(previous.value + (key.value - previous.value) * key.ease(local));\n }\n audioParam.setValueCurveAtTime(samples, curveStart, curveDur);\n }\n }\n}\n\n/** Builds the Web Audio graph for a clip's effect chain after an already-created `source`, shared by live playback ({@link WebAudioSink}) and offline export (`mixAudio`) so both sound identical. `startTime` is the context time the source starts; `clipDuration` the clip seconds ramps run over (a clip's, or a bus's span); `elapsed` the clip seconds already played at a mid-clip seek (0 for a clean start, negative before the span begins). */\nexport function buildAudioEffectGraph(\n ctx: BaseAudioContext,\n source: AudioNode,\n effects: readonly AudioEffect[],\n startTime: number = ctx.currentTime,\n clipDuration: number = 0,\n elapsed: number = 0,\n): AudioEffectGraph {\n const nodes: AudioNode[] = [];\n const oscillators: OscillatorNode[] = [];\n let cursor: AudioNode = source;\n\n const series = (node: AudioNode): void => {\n cursor.connect(node);\n nodes.push(node);\n cursor = node;\n };\n\n const apply = (p: AudioParam, v: Param, clamp?: (n: number) => number): void =>\n applyParam(p, v, startTime, clipDuration, elapsed, clamp);\n\n for (const effect of effects) {\n switch (effect.type) {\n case \"gain\": {\n const gain = ctx.createGain();\n apply(gain.gain, effect.value);\n series(gain);\n break;\n }\n case \"highpass\":\n case \"lowpass\": {\n const biquad = ctx.createBiquadFilter();\n biquad.type = effect.type;\n apply(biquad.frequency, effect.frequency);\n if (effect.q !== undefined) apply(biquad.Q, effect.q);\n series(biquad);\n break;\n }\n case \"tremolo\": {\n // A carrier gain an LFO swings: with depth d the carrier sits at\n // 1 - d/2 and the swing is d/2.\n const carrier = ctx.createGain();\n const lfo = ctx.createOscillator();\n const lfoDepth = ctx.createGain();\n\n apply(carrier.gain, effect.depth, (d) => 1 - clamp01(d) / 2);\n apply(lfoDepth.gain, effect.depth, (d) => clamp01(d) / 2);\n apply(lfo.frequency, effect.rate);\n\n lfo.connect(lfoDepth);\n lfoDepth.connect(carrier.gain);\n\n nodes.push(lfoDepth);\n oscillators.push(lfo);\n series(carrier);\n break;\n }\n case \"echo\": {\n const split = cursor;\n const merge = ctx.createGain();\n\n const dry = ctx.createGain();\n apply(dry.gain, effect.mix ?? 0.5, (m) => 1 - clamp01(m));\n split.connect(dry);\n dry.connect(merge);\n\n // The delay line is sized once, so it has to hold the ramp's longest delay.\n const delay = ctx.createDelay(Math.max(1, maxOf(effect.delay) + 1));\n apply(delay.delayTime, effect.delay);\n const feedbackGain = ctx.createGain();\n apply(feedbackGain.gain, effect.feedback, (f) => Math.max(0, Math.min(0.99, f)));\n const wet = ctx.createGain();\n apply(wet.gain, effect.mix ?? 0.5, (m) => clamp01(m));\n\n split.connect(delay);\n delay.connect(feedbackGain);\n feedbackGain.connect(delay);\n delay.connect(wet);\n wet.connect(merge);\n\n nodes.push(dry, delay, feedbackGain, wet, merge);\n cursor = merge;\n break;\n }\n }\n }\n\n return { output: cursor, nodes, oscillators };\n}\n\nfunction clamp01(v: number): number {\n return Math.max(0, Math.min(1, v));\n}\n\nfunction maxOf(p: Param): number {\n return isRamp(p) ? Math.max(0, ...p.keys.map((k) => k.value)) : p;\n}\n\n/** Schedules `transitionIn`/`transitionOut` onto a gain over a span `length` seconds long, baked like an eased ramp; holds at 1 between them. */\nexport function applyTransitions(\n gain: AudioParam,\n length: number,\n transitionIn: AudioTransition | undefined,\n transitionOut: AudioTransition | undefined,\n startTime: number,\n elapsed: number,\n): void {\n if (!transitionIn && !transitionOut) return;\n const seek = Math.max(0, elapsed);\n const at = (t: number): number => transitionGainAt(t, length, transitionIn, transitionOut);\n gain.setValueAtTime(at(seek), startTime);\n\n const spans = transitionSpans(length, transitionIn, transitionOut);\n const windows: [number, number][] = [];\n if (spans.in > 0) windows.push([0, spans.in]);\n if (spans.out > 0 && Number.isFinite(length)) windows.push([length - spans.out, length]);\n const base = startTime - elapsed;\n for (const [from, to] of windows) {\n const begin = Math.max(from, seek);\n const duration = to - begin;\n if (duration <= 0) continue;\n const count = Math.max(2, Math.ceil(duration * CURVE_SAMPLES_PER_SECOND));\n const samples = new Float32Array(count);\n for (let n = 0; n < count; n++) samples[n] = at(begin + duration * (n / (count - 1)));\n gain.setValueCurveAtTime(samples, base + begin, duration);\n }\n}\n\n/** How one request plays its source: the rate, and the lengths its ramps and transitions run over. */\nexport interface Playback {\n /** The constant `playbackRate`; 1 under a ramp, which is scheduled instead. */\n rate: number;\n speedRamp?: Ramp;\n /** Source seconds a speed ramp is placed on. */\n sourceLength: number;\n /** Clip seconds the volume and effect ramps run over. */\n clipDuration: number;\n /** What the transitions run over: the clip's length, unknown for an open one. */\n transitionLength: number;\n}\n\nexport function playbackOf(req: AudioRequest, bufferDuration: number): Playback {\n const speed = req.speed ?? 1;\n const speedRamp = isRamp(speed) ? speed : undefined;\n const rate = speedRamp || !(Number.isFinite(speed) && (speed as number) > 0) ? 1 : (speed as number);\n // Placed on the same length core sized the request with, not the decoded buffer.\n const sourceLength = req.sourceLength ?? Math.max(0, bufferDuration - req.trimStart);\n const bounded = Number.isFinite(req.endAt);\n const clipDuration = bounded ? Math.max(0, req.endAt - req.startAt) : clipTimeAtSource(speed, sourceLength);\n return { rate, speedRamp, sourceLength, clipDuration, transitionLength: bounded ? clipDuration : Infinity };\n}\n\n/** Source seconds after `trimStart` that `clipElapsed` clip seconds have played. */\nexport function sourceOffsetOf(playback: Playback, clipElapsed: number): number {\n return playback.speedRamp\n ? sourceTimeAtClip(playback.speedRamp, playback.sourceLength, clipElapsed)\n : clipElapsed * playback.rate;\n}\n\n/**\n * A request's level, then its transitions, after `from`: the gains every\n * request plays through on its way to its bus.\n */\nexport function buildLevel(\n ctx: BaseAudioContext,\n from: AudioNode,\n req: AudioRequest,\n playback: Playback,\n startTime: number,\n elapsed: number,\n): { output: AudioNode; nodes: AudioNode[] } {\n const level = ctx.createGain();\n applyParam(level.gain, req.volume ?? 1, startTime, playback.clipDuration, elapsed);\n from.connect(level);\n if (!req.transitionIn && !req.transitionOut) return { output: level, nodes: [level] };\n const transition = ctx.createGain();\n applyTransitions(transition.gain, playback.transitionLength, req.transitionIn, req.transitionOut, startTime, elapsed);\n level.connect(transition);\n return { output: transition, nodes: [level, transition] };\n}\n\n/** Schedules a speed ramp onto `playbackRate`. The ramp runs over **source** seconds and Web Audio schedules in context seconds, so this walks clip time in small steps and converts each through the integral inverse. `elapsed` is clip seconds already played at a mid-clip seek. */\nexport function applySpeedToPlaybackRate(\n rate: AudioParam,\n speed: Ramp | undefined,\n sourceLength: number,\n clipDuration: number,\n startTime: number,\n elapsed: number,\n): void {\n if (!speed) return;\n const step = 1 / CURVE_SAMPLES_PER_SECOND;\n const seekAt = Math.max(0, elapsed);\n const valueAt = (clipElapsed: number): number =>\n Math.max(1e-4, sampleRamp(speed, sourceTimeAtClip(speed, sourceLength, clipElapsed), sourceLength, 1));\n rate.setValueAtTime(valueAt(seekAt), startTime);\n\n for (let s = seekAt + step; s <= clipDuration + step; s += step) {\n const clamped = Math.min(s, clipDuration);\n rate.linearRampToValueAtTime(valueAt(clamped), startTime + (clamped - seekAt));\n if (clamped >= clipDuration) break;\n }\n}\n", "import type { AudioRequest } from \"@motionscript/core\";\n\n/** The span of a decoded buffer a looping request repeats, in source seconds. */\nexport interface LoopRegion {\n start: number;\n end: number;\n}\n\n/** The region a looping request repeats (in-point to out-point, else the end of the buffer); `null` when it does not loop or is degenerate (out-point at or before in-point), where the device wraps the whole buffer. Shared with the offline mixer so preview and export loop the same samples. */\nexport function loopRegionOf(request: AudioRequest, bufferDuration: number): LoopRegion | null {\n if (!request.loop) return null;\n const start = Math.min(Math.max(0, request.trimStart), bufferDuration);\n const end = Math.min(request.trimEnd ?? bufferDuration, bufferDuration);\n return end > start ? { start, end } : null;\n}\n\n/** Configures `source` to loop `request`'s trimmed region rather than the whole buffer (`loopStart`/`loopEnd` default to the whole buffer, which loses a trim). */\nexport function applyLoop(source: AudioBufferSourceNode, request: AudioRequest): LoopRegion | null {\n source.loop = request.loop;\n const region = source.buffer ? loopRegionOf(request, source.buffer.duration) : null;\n if (region) {\n source.loopStart = region.start;\n source.loopEnd = region.end;\n }\n return region;\n}\n\n/** Folds a source offset into a loop region: a seek into a looping clip lands at `trimStart + elapsed`, possibly many passes past the end, and the device does not wrap an offset that starts outside the region. */\nexport function wrapIntoRegion(region: LoopRegion | null, offset: number): number {\n if (!region || offset < region.end) return offset;\n return region.start + ((offset - region.start) % (region.end - region.start));\n}\n", "import type { AssetCatalog } from \"@motionscript/core\";\nimport type { AudioMixer, ScheduledAudioRequest } from \"../frame-loop\";\nimport { loadAssetBytes } from \"../asset-bytes\";\nimport { AudioBusGraph } from \"./bus-graph\";\nimport { applyLoop } from \"./loop-region\";\nimport { applySpeedToPlaybackRate, buildAudioEffectGraph, buildLevel, playbackOf, sourceOffsetOf } from \"./effect-graph\";\n\nexport const DEFAULT_SAMPLE_RATE = 44100;\n\nexport interface MixAudioOptions {\n sampleRate?: number;\n /** Resolves a request's `src` to the address its bytes live at, as the storage adapter does for live paths. Omitted, a `src` is fetched as written, right only while the host keys its manifest by URL. */\n catalog?: AssetCatalog;\n}\n\n/** Audio first, then video: a clip's own soundtrack is requested under the video's key. */\nfunction audioUrl(src: string, catalog: AssetCatalog | undefined): string {\n if (!catalog) return src;\n try {\n return catalog.getAudioMeta(src).src || src;\n } catch {\n try {\n return catalog.getVideoMeta(src).src || src;\n } catch {\n return src;\n }\n }\n}\n\n/** Reads and decodes an audio source against a scratch `OfflineAudioContext`. The host's byte source is asked first, as for every asset read: a mix that went to the network would fail where the preview played (offline, or bytes not yet uploaded). */\nasync function fetchAudioBuffer(src: string, ctx: OfflineAudioContext): Promise<AudioBuffer> {\n const blob = await loadAssetBytes(src);\n return ctx.decodeAudioData(await blob.arrayBuffer());\n}\n\n/**\n * Renders every scheduled request into one timeline-length buffer through an `OfflineAudioContext` graph (gain per\n * request, looping/trimming, the same filter chain as the live {@link WebAudioSink}) in one pass. Shared by the video\n * exporter and `mixTimelineAudio` so a split export and a whole one are the same mix. Curve-valued filter params and\n * `speed` curves schedule exactly as in {@link WebAudioSink.playBuffer}, the reference: read the two side by side when\n * either changes. One difference: this schedules at absolute context times, so clip starts are sample-accurate here\n * and quantized to `1/fps` live.\n */\nexport async function mixAudio(\n requests: readonly ScheduledAudioRequest[],\n totalDuration: number,\n options: MixAudioOptions = {},\n): Promise<AudioBuffer | null> {\n if (requests.length === 0) return null;\n const sampleRate = options.sampleRate ?? DEFAULT_SAMPLE_RATE;\n const frames = Math.ceil(totalDuration * sampleRate);\n if (frames <= 0) return null;\n\n const uniqueSrcs = [...new Set(requests.map(r => r.request.src))];\n const scratchCtx = new OfflineAudioContext(2, frames, sampleRate);\n\n // A source only a picture's own sound wants may hold no audio at all, which\n // is silence rather than a failed mix — see `AudioRequest.optional`.\n const asked = new Set(requests.filter(r => !r.request.optional).map(r => r.request.src));\n const decoded = new Map<string, AudioBuffer>();\n await Promise.all(uniqueSrcs.map(async (src) => {\n try {\n decoded.set(src, await fetchAudioBuffer(audioUrl(src, options.catalog), scratchCtx));\n } catch (cause) {\n if (asked.has(src)) throw cause;\n }\n }));\n\n const mixCtx = new OfflineAudioContext(2, frames, sampleRate);\n // The same shared-chain rule the live device uses, for the same reason: an\n // export that flattened buses into per-clip processing would not match what\n // the preview sounded like.\n const buses = new AudioBusGraph(mixCtx, mixCtx.destination);\n\n for (const { request: req, globalOffset } of requests) {\n const srcBuffer = decoded.get(req.src);\n if (!srcBuffer) continue;\n\n const globalStart = globalOffset + req.startAt;\n // `endAt` is `Infinity` for an open clip; either way the timeline bounds it.\n const globalEnd = Math.min(globalOffset + req.endAt, totalDuration);\n const playDuration = globalEnd - globalStart;\n if (playDuration <= 0) continue;\n\n const source = mixCtx.createBufferSource();\n source.buffer = srcBuffer;\n applyLoop(source, req);\n\n // Ramps resolve against the clip's own length, deliberately *not*\n // `playDuration`, which is that length truncated by the timeline end:\n // resolving against the truncated value would squeeze the whole ramp\n // into the surviving part instead of cutting it off. `elapsed` is 0:\n // unlike a live seek, the mix always starts a clip at its beginning.\n const playback = playbackOf(req, srcBuffer.duration);\n if (playback.rate !== 1) source.playbackRate.value = playback.rate;\n applySpeedToPlaybackRate(\n source.playbackRate, playback.speedRamp, playback.sourceLength, playback.clipDuration, globalStart, 0,\n );\n\n // The same chain as the live WebAudioSink graph, so exports sound like the preview.\n const graph = buildAudioEffectGraph(mixCtx, source, req.effects ?? [], globalStart, playback.clipDuration, 0);\n const level = buildLevel(mixCtx, graph.output, req, playback, globalStart, 0);\n // From the mix's start, whichever clip asks first: a bus's chain is shared,\n // so its schedule cannot begin at one clip's start. Context time 0 is\n // `-globalOffset` in this request's seconds, which are its stops' too.\n level.output.connect(buses.inputFor(req.bus, 0, -globalOffset));\n\n // start()'s 3rd arg is a source-buffer duration: under a speed ramp the\n // buffer consumed over a span of clip time is the integral of the rate,\n // not a multiple of it.\n const consumed = sourceOffsetOf(playback, playDuration);\n\n source.start(globalStart, req.trimStart, consumed);\n for (const osc of graph.oscillators) osc.start(globalStart);\n }\n\n return mixCtx.startRendering();\n}\n\n/** Adapter presenting {@link mixAudio} as the exporter's mixer seam. The sample rate is a constructor argument because {@link AudioMixer}, the seam `renderTimeline` calls through, takes exactly two parameters and a third would be silently dropped. */\nexport class WebAudioMixer implements AudioMixer<AudioBuffer> {\n constructor(\n private readonly sampleRate: number = DEFAULT_SAMPLE_RATE,\n private readonly catalog?: AssetCatalog,\n ) { }\n\n mix(\n requests: readonly ScheduledAudioRequest[],\n totalDuration: number,\n ): Promise<AudioBuffer | null> {\n return mixAudio(requests, totalDuration, {\n sampleRate: this.sampleRate,\n catalog: this.catalog,\n });\n }\n}\n\n/** Encodes an `AudioBuffer` as a 16-bit PCM WAV: no codec support needed and lossless, and the only other encoder here (AAC in the mp4 muxer) is reachable solely by exporting a video. */\nexport function encodeWav(buffer: AudioBuffer): Uint8Array<ArrayBuffer> {\n const channelCount = buffer.numberOfChannels;\n const frameCount = buffer.length;\n const bytesPerSample = 2;\n const blockAlign = channelCount * bytesPerSample;\n const dataBytes = frameCount * blockAlign;\n\n const out = new ArrayBuffer(44 + dataBytes);\n const view = new DataView(out);\n\n const ascii = (offset: number, text: string) => {\n for (let i = 0; i < text.length; i++) view.setUint8(offset + i, text.charCodeAt(i));\n };\n\n ascii(0, \"RIFF\");\n view.setUint32(4, 36 + dataBytes, true);\n ascii(8, \"WAVE\");\n ascii(12, \"fmt \");\n view.setUint32(16, 16, true); // PCM header length\n view.setUint16(20, 1, true); // format: PCM\n view.setUint16(22, channelCount, true);\n view.setUint32(24, buffer.sampleRate, true);\n view.setUint32(28, buffer.sampleRate * blockAlign, true);\n view.setUint16(32, blockAlign, true);\n view.setUint16(34, 8 * bytesPerSample, true);\n ascii(36, \"data\");\n view.setUint32(40, dataBytes, true);\n\n // Pull each channel out once — getChannelData is a live view, but calling it\n // per sample inside the interleave loop is measurably slower.\n const channels: Float32Array[] = [];\n for (let c = 0; c < channelCount; c++) channels.push(buffer.getChannelData(c));\n\n let offset = 44;\n for (let frame = 0; frame < frameCount; frame++) {\n for (let c = 0; c < channelCount; c++) {\n // Clamp before scaling: the mix bus can exceed [-1,1] where clips\n // overlap, and letting that wrap turns a loud passage into noise.\n const sample = Math.max(-1, Math.min(1, channels[c][frame]));\n view.setInt16(offset, sample < 0 ? sample * 0x8000 : sample * 0x7fff, true);\n offset += bytesPerSample;\n }\n }\n\n return new Uint8Array(out);\n}\n", "import { AudioSink, AudioRequest } from \"@motionscript/core\";\nimport { AudioBusGraph } from \"./bus-graph\";\nimport { applyLoop, wrapIntoRegion } from \"./loop-region\";\nimport { applySpeedToPlaybackRate, buildAudioEffectGraph, buildLevel, playbackOf, sourceOffsetOf } from \"./effect-graph\";\n\ntype ActiveSource = {\n source: AudioBufferSourceNode;\n request: AudioRequest;\n nodes: AudioNode[];\n oscillators: OscillatorNode[];\n};\n\n/** Web Audio implementation of {@link AudioSink}: decodes and caches source buffers, then plays {@link AudioRequest}s as `AudioBufferSourceNode`s through a shared master gain (global mute and volume). `syncTo` starts/stops sources to match `clipTime`, so playback follows scrubbing and seeks. */\nexport class WebAudioSink extends AudioSink {\n private readonly borrowed: AudioContext | undefined;\n private _context: AudioContext | null = null;\n private bufferCache = new Map<string, AudioBuffer>();\n private decoding = new Map<string, Promise<void>>();\n private active = new Map<string, ActiveSource>();\n private scheduled: AudioRequest[] = [];\n private disposed: boolean = false;\n /** The master gain and the live bus chains (shared across every clip that names one), built with the context. */\n private _graph: { master: GainNode; buses: AudioBusGraph } | null = null;\n private muted = false;\n private volume = 1;\n\n constructor(context?: AudioContext) {\n super();\n this.borrowed = context;\n }\n\n /** Created on first use rather than with the sink: a new AudioContext opens the audio device (50–65 ms on desktop), which a session that never plays never needs. */\n getContext(): AudioContext {\n this._context ??= this.borrowed ?? new AudioContext();\n return this._context;\n }\n\n private get context(): AudioContext {\n return this.getContext();\n }\n\n private get graph(): { master: GainNode; buses: AudioBusGraph } {\n if (!this._graph) {\n const master = this.context.createGain();\n master.connect(this.context.destination);\n this._graph = { master, buses: new AudioBusGraph(this.context, master) };\n this.applyMasterGain();\n }\n return this._graph;\n }\n\n /** Resumes the AudioContext; the first call must come from a user gesture or browsers keep it suspended and nothing is heard. */\n unlock(): void {\n if (this.context.state === \"suspended\") {\n this.context.resume();\n }\n }\n\n has(src: string): boolean {\n return this.bufferCache.has(src);\n }\n\n async append(src: string, data: ArrayBuffer): Promise<void> {\n if (this.bufferCache.has(src)) return;\n const existing = this.decoding.get(src);\n if (existing) return existing;\n\n // decodeAudioData detaches `data`; the AssetManager caller discards its reference after awaiting append, so skipping a defensive .slice(0) saves a multi-MB allocation per source.\n const job = this.context.decodeAudioData(data).then((buffer) => {\n this.bufferCache.set(src, buffer);\n }).finally(() => {\n this.decoding.delete(src);\n });\n this.decoding.set(src, job);\n await job;\n }\n\n /** Drops cached buffers and stops active sources for srcs/requests no longer referenced — called when the asset set changes (e.g. seeking across scene boundaries). */\n retain(keep: ReadonlySet<string>): void {\n for (const src of [...this.bufferCache.keys()]) {\n if (!keep.has(src)) this.bufferCache.delete(src);\n }\n for (const [id, active] of this.active) {\n if (!keep.has(active.request.src)) this.stopSource(id, active);\n }\n }\n\n /** Replaces the active request set; stops any currently-playing source whose request is no longer scheduled. Actual start/stop-to-match-time happens in `syncTo`. */\n schedule(requests: readonly AudioRequest[]): void {\n const next = new Set(requests.map(r => r.id));\n for (const [id, active] of this.active) {\n if (!next.has(id)) this.stopSource(id, active);\n }\n this.scheduled = requests.slice();\n }\n\n /** Starts sources whose `[startAt, endAt)` window now contains `clipTime` (computing the correct buffer offset for the seek point) and stops any that have fallen outside it. */\n syncTo(clipTime: number): void {\n const liveIds = new Set<string>();\n\n for (const req of this.scheduled) {\n // `endAt` is `Infinity` for an open clip, so the comparison needs no\n // nullish fallback — see AudioRequest.endAt.\n const isInWindow = clipTime >= req.startAt && clipTime < req.endAt;\n if (!isInWindow) continue;\n\n liveIds.add(req.id);\n if (!this.active.has(req.id)) {\n const buffer = this.bufferCache.get(req.src);\n if (buffer) this.playBuffer(buffer, req, clipTime);\n }\n }\n\n for (const [id, active] of this.active) {\n if (!liveIds.has(id)) this.stopSource(id, active);\n }\n }\n\n async play(time: number, _speed: number, _reverse: boolean): Promise<void> {\n if (this.context.state === \"suspended\") {\n await this.context.resume();\n }\n this.syncTo(time);\n }\n\n stop(): void {\n for (const [id, active] of this.active) {\n this.stopSource(id, active);\n }\n // A bus's curves are scheduled against the clock of the run that built\n // it, so the next play, from wherever it lands, builds them again.\n this._graph?.buses.dispose();\n }\n\n setMuted(muted: boolean): void {\n this.muted = muted;\n this.applyMasterGain();\n }\n\n setVolume(volume: number): void {\n this.volume = Math.max(0, volume);\n this.applyMasterGain();\n }\n\n /** Mute and volume are held separately so unmuting restores the set level. */\n private applyMasterGain(): void {\n if (this._graph) this._graph.master.gain.value = this.muted ? 0 : this.volume;\n }\n\n /** Starts a buffer source mid-clip if `clipTime` lands after the request's start — the offset accounts for the request's trim, the elapsed time since `startAt`, and its speed. */\n private playBuffer(buffer: AudioBuffer, req: AudioRequest, clipTime: number): void {\n const startTime = this.context.currentTime;\n const playback = playbackOf(req, buffer.duration);\n const elapsed = Math.max(0, clipTime - req.startAt);\n\n const source = this.context.createBufferSource();\n source.buffer = buffer;\n const loopRegion = applyLoop(source, req);\n if (playback.rate !== 1) source.playbackRate.value = playback.rate;\n applySpeedToPlaybackRate(\n source.playbackRate, playback.speedRamp, playback.sourceLength, playback.clipDuration, startTime, elapsed,\n );\n\n const graph = buildAudioEffectGraph(\n this.context, source, req.effects ?? [], startTime, playback.clipDuration, elapsed,\n );\n const level = buildLevel(this.context, graph.output, req, playback, startTime, elapsed);\n // Into this clip's bus chain, or straight to the master when it has none.\n // The chain is shared: two clips on one bus reach the same nodes, which is\n // what makes a bus effect one tail rather than one per clip.\n level.output.connect(this.graph.buses.inputFor(req.bus, startTime, clipTime));\n\n const audioOffset = req.trimStart + sourceOffsetOf(playback, elapsed);\n source.start(startTime, wrapIntoRegion(loopRegion, audioOffset));\n for (const osc of graph.oscillators) osc.start(startTime);\n\n source.onended = () => {\n if (this.active.get(req.id)?.source === source) {\n this.active.delete(req.id);\n }\n };\n\n this.active.set(req.id, {\n source,\n request: req,\n nodes: [...graph.nodes, ...level.nodes],\n oscillators: graph.oscillators,\n });\n }\n\n private stopSource(id: string, active: ActiveSource): void {\n try {\n active.source.onended = null;\n active.source.stop();\n for (const osc of active.oscillators) osc.stop();\n active.source.disconnect();\n for (const node of active.nodes) node.disconnect();\n } catch {\n }\n this.active.delete(id);\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n super.dispose();\n this.bufferCache.clear();\n this.decoding.clear();\n this.scheduled.length = 0;\n this._graph?.buses.dispose();\n try {\n this._graph?.master.disconnect();\n } catch {\n }\n const owned = this.borrowed ? null : this._context;\n if (owned && owned.state !== \"closed\") {\n owned.close();\n }\n }\n}\n"],
5
+ "mappings": "AAcA,IAAIA,EAAiC,KAG/B,SAAUC,GAAmBC,EAA4B,CAC3DF,EAASE,CACb,CAGA,eAAsBC,EAAgBC,EAAW,CAC7C,GAAI,CAACJ,EAAQ,OAAO,KACpB,GAAI,CACA,OAAO,MAAMA,EAAOI,CAAG,CAC3B,MAAQ,CACJ,OAAO,IACX,CACJ,CAGA,eAAsBC,EAAgBC,EAAW,CAC7C,IAAMC,EAAW,MAAM,MAAMD,CAAG,EAChC,GAAI,CAACC,EAAS,GAAI,CACd,IAAMC,EAASD,EAAS,WAAa,GAAGA,EAAS,MAAM,IAAIA,EAAS,UAAU,GAAK,GAAGA,EAAS,MAAM,GAC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KAAK,QAAQ,MAAM,QAAO,EAC1B,GAAI,CACA,KAAK,QAAQ,OAAO,WAAU,CAClC,MAAQ,CACR,CACA,IAAM8B,EAAQ,KAAK,SAAW,KAAO,KAAK,SACtCA,GAASA,EAAM,QAAU,UACzBA,EAAM,MAAK,CAEnB",
6
+ "names": ["source", "setAssetByteSource", "next", "localAssetBytes", "src", "fetchAssetBytes", "url", "response", "status", "loading", "loadAssetBytes", "running", "job", "busStopKey", "clipTimeAtSource", "isRamp", "resolveRamp", "sampleRamp", "sourceTimeAtClip", "staticValue", "transitionGainAt", "transitionSpans", "CURVE_SAMPLES_PER_SECOND", "applyParam", "audioParam", "param", "startTime", "clipDuration", "elapsed", "clamp", "v", "finite", "c", "keys", "base", "i", "previous", "key", "segStart", "segEnd", "span", "done", "curveStart", "curveDur", "count", "samples", "n", "local", "buildAudioEffectGraph", "ctx", "source", "effects", "nodes", "oscillators", "cursor", "series", "node", "apply", "p", "effect", "gain", "biquad", "carrier", "lfo", "lfoDepth", "d", "clamp01", "split", "merge", "dry", "m", "delay", "maxOf", "feedbackGain", "f", "wet", "k", "applyTransitions", "length", "transitionIn", "transitionOut", "seek", "at", "t", "spans", "windows", "from", "to", "begin", "duration", "playbackOf", "req", "bufferDuration", "speed", "speedRamp", "rate", "sourceLength", "bounded", "sourceOffsetOf", "playback", "clipElapsed", "buildLevel", "level", "transition", "applySpeedToPlaybackRate", "step", "seekAt", "valueAt", "s", "clamped", "AudioBusGraph", "ctx", "destination", "bus", "startTime", "clipTime", "node", "osc", "index", "stop", "key", "busStopKey", "existing", "output", "input", "level", "span", "graph", "buildAudioEffectGraph", "tail", "transition", "applyTransitions", "loopRegionOf", "request", "bufferDuration", "start", "end", "applyLoop", "source", "region", "wrapIntoRegion", "offset", "DEFAULT_SAMPLE_RATE", "audioUrl", "src", "catalog", "fetchAudioBuffer", "ctx", "blob", "loadAssetBytes", "mixAudio", "requests", "totalDuration", "options", "sampleRate", "frames", "uniqueSrcs", "r", "scratchCtx", "asked", "decoded", "cause", "mixCtx", "buses", "AudioBusGraph", "req", "globalOffset", "srcBuffer", "globalStart", "playDuration", "source", "applyLoop", "playback", "playbackOf", "applySpeedToPlaybackRate", "graph", "buildAudioEffectGraph", "buildLevel", "consumed", "sourceOffsetOf", "osc", "WebAudioMixer", "encodeWav", "buffer", "channelCount", "frameCount", "bytesPerSample", "blockAlign", "dataBytes", "out", "view", "ascii", "offset", "text", "i", "channels", "c", "frame", "sample", "AudioSink", "WebAudioSink", "AudioSink", "context", "master", "AudioBusGraph", "src", "data", "existing", "job", "buffer", "keep", "id", "active", "requests", "next", "r", "clipTime", "liveIds", "req", "time", "_speed", "_reverse", "muted", "volume", "startTime", "playback", "playbackOf", "elapsed", "source", "loopRegion", "applyLoop", "applySpeedToPlaybackRate", "graph", "buildAudioEffectGraph", "level", "buildLevel", "audioOffset", "sourceOffsetOf", "wrapIntoRegion", "osc", "node", "owned"]
7
+ }